aboutsummaryrefslogtreecommitdiff
path: root/src/routes/groceries/catalog/+page.server.ts
blob: fd71e306a679b2b10687073d38caefebd9dc3258 (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

import { fail } from '@sveltejs/kit';
import {
	loadAll,
	bulkUpdateGroceryCategory,
} from '$lib/server/services/groceries';
import { toggleGroceryAction } from '$lib/server/services/grocery-actions';
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: ({ request }) => toggleGroceryAction(request),

	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 };
	},
};