aboutsummaryrefslogtreecommitdiff
path: root/src/routes/groceries/catalog/+page.server.ts
blob: 22464dc122ec9801c0614be93307fefee3452f80 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

import { fail } from '@sveltejs/kit';
import {
	loadAll,
	toggle,
	bulkUpdateGroceryCategory,
} from '$lib/server/services/groceries';
import {
	numericId,
	parseOptionalNumber,
} from '$lib/server/services/validation';
import type { EnrichedGrocery } from '$lib/server/services/groceries';
import type { Category } from '$lib/server/services/types';
import type { Actions, PageServerLoad } from './$types';

export interface CatalogOutput {
	items: EnrichedGrocery[];
	categories: Category[];
}

export const load: PageServerLoad = async () => {
	return loadAll();
};

export const actions: Actions = {
	toggle: async ({ request }) => {
		const data = await request.formData();
		try {
			const id = numericId(data.get('id'));
			await toggle(id);
		} catch {
			return fail(400, { error: 'ID invalide' });
		}
		return { success: true };
	},

	bulkUpdateCategory: async ({ request }) => {
		const data = await request.formData();
		const ids = data.getAll('ids').map(numericId);
		const rawCategoryId = parseOptionalNumber(data.get('category_id'));
		const categoryId = rawCategoryId === -1 ? null : rawCategoryId;

		if (ids.length === 0) {
			return fail(400, { error: 'Aucun article sélectionné' });
		}

		await bulkUpdateGroceryCategory(ids, categoryId);
		return { success: true, type: 'bulkUpdate' as const };
	},
};