import type { TacheRecord } from '@/types/collections'; /** Parse PocketBase `date` (YYYY-MM-DD) en date locale minuit. */ export function parsePbDateOnly(raw?: string | null): Date | null { if (!raw) return null; const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(raw.trim()); if (!m) return null; return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])); } export function startOfLocalDay(d: Date): Date { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); } export function addDays(d: Date, n: number): Date { const x = new Date(d); x.setDate(x.getDate() + n); return x; } export function formatPbDateOnly(d: Date): string { const y = d.getFullYear(); const m = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); return `${y}-${m}-${day}`; } export function isTaskActive(statut?: string): boolean { return statut !== 'fait' && statut !== 'annule'; } export type AgendaPartition = { overdue: TacheRecord[]; today: TacheRecord[]; week: TacheRecord[]; nodate: TacheRecord[]; }; /** Tâches actives : en retard, aujourd’hui, dans les 7 jours (excl. aujourd’hui), sans date. */ export function partitionTachesForAgenda(taches: TacheRecord[]): AgendaPartition { const now = new Date(); const startToday = startOfLocalDay(now); const startTomorrow = addDays(startToday, 1); const endWeek = addDays(startToday, 7); const overdue: TacheRecord[] = []; const today: TacheRecord[] = []; const week: TacheRecord[] = []; const nodate: TacheRecord[] = []; for (const t of taches) { if (!isTaskActive(t.statut)) continue; const d = parsePbDateOnly(t.date_echeance); if (!d) { nodate.push(t); continue; } if (d < startToday) overdue.push(t); else if (d < startTomorrow) today.push(t); else if (d < endWeek) week.push(t); } const byDue = (a: TacheRecord, b: TacheRecord) => { const da = parsePbDateOnly(a.date_echeance)?.getTime() ?? 0; const db = parsePbDateOnly(b.date_echeance)?.getTime() ?? 0; return da - db; }; overdue.sort(byDue); today.sort(byDue); week.sort(byDue); return { overdue, today, week, nodate }; }