import { fail, type ActionFailure } from '@sveltejs/kit'; import { archive, complete, edit, loadCurrent } from './routines'; import { parseFormString } from './validation'; import { instantFromDay } from '$lib/shared/temporal'; import { Frequency } from '$lib/shared/frequency'; /** Shared routine edit/complete actions; rejects missing/archived routines. */ export type EditRoutineResult = ActionFailure<{ error: string }> | { success: boolean; type?: 'edit' }; export async function editRoutineAction( data: FormData, routineId: number, extra?: { type: 'edit' }, ): Promise { const current = await loadCurrent(routineId); if (!current) { return fail(400, { error: 'Routine introuvable' }); } if (current.archived) { return fail(400, { error: 'Routine archivée' }); } const name = parseFormString(data.get('name')); if (!name) { return fail(400, { error: 'Le nom est requis' }); } let frequency: string; try { frequency = Frequency.parse( data.get('frequency')?.toString() ?? '', ).toSpec(); } catch { return fail(400, { error: 'Fréquence invalide' }); } // Only touch description when the form sends one; list edits never wipe it. const fields: { name: string; frequency: string; description?: string } = { name, frequency, }; const description = data.get('description'); if (description !== null) { fields.description = description.toString(); } try { await edit(routineId, fields); } catch { return fail(400, { error: 'Routine introuvable' }); } return { success: true, type: extra?.type }; } export async function completeRoutineAction(data: FormData, routineId: number) { const current = await loadCurrent(routineId); if (!current) { return fail(400, { error: 'Routine introuvable' }); } if (current.archived) { return fail(400, { error: 'Routine archivée' }); } const now = Temporal.Now.instant(); const day = parseFormString(data.get('doneAt')); const doneAt = day ? instantFromDay(day, now) : now.toString({ smallestUnit: 'millisecond' }); if (doneAt === null) { return fail(400, { error: 'Date invalide' }); } try { await complete(routineId, parseFormString(data.get('note')), doneAt); } catch { return fail(400, { error: 'Routine introuvable' }); } return { success: true }; } export async function archiveRoutineAction(routineId: number) { try { await archive(routineId); } catch { return fail(400, { error: 'Routine introuvable' }); } return { success: true }; }