diff --git a/REVIEW.md b/REVIEW.md index c0a8568..bd562c6 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -97,6 +97,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Un lot de sync compte au plus 200 opérations (`SYNC_MAX_OPERATIONS`) et l'app en envoie 50 (`BATCH_SIZE`) : une montée de `BATCH_SIZE` se juge contre cette borne et contre la limite `sync` (10 requêtes par minute, GET et POST confondus), et le companion se déploie avant l'app. — `web/src/lib/validators.ts`, `src/services/syncRules.ts`, #147 - Tout tableau d'un schéma de requête a sa longueur contrôlée avant ses éléments (`z.array(z.unknown()).max(n).pipe(…)`) : zod valide chaque élément avant la longueur, et un tableau hostile produit un issue par élément. — `web/src/lib/validators.ts`, #147 - `parseBody` ne renvoie que le premier issue d'une erreur zod, et au plus 200 caractères. — `web/src/lib/api.ts`, #147 +- Une échéance reçue par `POST /api/tasks` ou `PUT /api/tasks/[id]` passe par `dueDateSchema` : une date seule `AAAA-MM-JJ`, date réelle du calendrier, est enregistrée à 12:00 UTC (7 h l'hiver et 8 h l'été, heure du Québec ; décision de Max du 2026-11-14), une date-heure ISO 8601 avec `Z` ou un décalage `±hh:mm` est gardée telle quelle, et tout le reste répond 400, dont une date-heure sans fuseau et un instant hors des années 0001 à 9999 en UTC, que PostgreSQL refuserait à l'écriture. Un `PUT` sans `dueDate` ne touche pas à l'échéance, `null` l'efface ; le formulaire d'édition du site n'envoie `dueDate` que si le champ de date a changé (`dueDateField`), sinon l'heure d'une échéance posée sur le téléphone serait réécrite à midi UTC. La sync garde son propre schéma (`isoDate` de `syncData.ts`) : l'app envoie des instants. `dueDate.ts` reste sans import, parce que `TaskItem.tsx` le charge dans le navigateur et que zod l'y suivrait (environ 100 Ko de JavaScript client en plus, mesurés au build) : le schéma zod vit dans `validators.ts`, et `dueDate.test.ts` le vérifie. — `web/src/lib/dueDate.ts`, `web/src/lib/validators.ts`, `web/src/app/api/tasks/route.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/components/TaskItem.tsx`, `web/src/app/api/tasks/route.test.ts`, #198 - Les clés d'idempotence sont des UUID, 5 000 au plus par compte, la plus ancienne évincée au-delà (`idempotency.ts`) : une clé évincée rejouée réapplique son opération. — `web/src/lib/idempotency.ts`, `web/src/app/api/sync/route.ts`, #147 - Aucune borne de taille du corps n'est posée par le companion : Next ne coupe le corps à 10 Mo (`experimental.proxyClientMaxBodySize`) que si `middleware.ts` couvre la route, ce que vérifie `middleware.test.ts`. Un `config.matcher` qui exclut une route d'API lui retire cette coupure. — `web/src/middleware.ts`, `web/src/middleware.test.ts`, #147 - Limites de débit par utilisateur et par catégorie (`sync`, `create`, `read`, `ws-ticket`) ; une route ajoutée en prend une. Le store est en mémoire : il repart à zéro à chaque redémarrage. — `web/src/lib/rateLimit.ts` diff --git a/web/src/app/api/tasks/[id]/route.ts b/web/src/app/api/tasks/[id]/route.ts index 82cd8cc..12f0597 100644 --- a/web/src/app/api/tasks/[id]/route.ts +++ b/web/src/app/api/tasks/[id]/route.ts @@ -21,16 +21,13 @@ export async function PUT( const body = await parseBody(request, (d) => updateTaskSchema.parse(d)); if (body.error) return body.error; + // body.data.dueDate is already a Date, or null to clear the due date: + // updateTaskSchema converts it (#198). Absent, the due date is left as it is. const updateData: Record = { ...body.data, updatedAt: new Date(), }; - // Convert dueDate string to Date - if (body.data.dueDate !== undefined) { - updateData.dueDate = body.data.dueDate ? new Date(body.data.dueDate) : null; - } - // Set completedAt when toggling completed if (body.data.completed !== undefined) { updateData.completedAt = body.data.completed ? new Date() : null; diff --git a/web/src/app/api/tasks/route.test.ts b/web/src/app/api/tasks/route.test.ts new file mode 100644 index 0000000..85e204f --- /dev/null +++ b/web/src/app/api/tasks/route.test.ts @@ -0,0 +1,204 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import type { PGlite } from 'electric-sql-pglite'; + +// REST task routes: the real POST /api/tasks and PUT /api/tasks/[id] handlers +// run against an in-memory Postgres (PGlite) with the companion migrations. +// Auth, rate limiting and the WebSocket notice are stubbed; the real parseBody +// and the real schemas run. Same setup as ../sync/route.test.ts. + +const h = await vi.hoisted(async () => { + const { PGlite } = await import('electric-sql-pglite'); + return { pg: new PGlite() as PGlite, userId: '' }; +}); + +vi.mock('@/db/client', async () => { + const { drizzle } = await import('drizzle-orm/pglite'); + const schema = await import('@/db/schema'); + return { db: drizzle(h.pg, { schema }) }; +}); + +vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null })); +vi.mock('@/lib/api', async (importOriginal) => ({ + ...(await importOriginal()), + requireAuth: async () => ({ userId: h.userId }), +})); + +vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null })); +vi.mock('@/lib/ws', () => ({ notifyUserChanged: () => {} })); + +const { POST } = await import('./route'); +const { PUT } = await import('./[id]/route'); + +type Account = { userId: string; list: string }; + +type TaskRow = { title: string; due_date: Date | null; updated_at: Date }; + +async function row>(sql: string, params: unknown[]): Promise { + return (await h.pg.query(sql, params)).rows[0]; +} + +// Each test creates its own account (#148): no test reads or writes the rows +// of another, so the file passes in any order (vitest runs it shuffled). +async function newAccount(): Promise { + const account = { userId: `user-${u()}`, list: u() }; + await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [account.list, account.userId, 'List']); + return account; +} + +// A task written straight to the table; `dueDate` is an ISO instant. +async function newTask(account: Account, fields: { dueDate?: string } = {}): Promise { + const id = u(); + await h.pg.query( + 'insert into sl_tasks (id, user_id, title, list_id, due_date) values ($1, $2, $3, $4, $5)', + [id, account.userId, 'Task', account.list, fields.dueDate ?? null], + ); + return id; +} + +async function postTask(userId: string, body: Record): Promise { + h.userId = userId; + return POST(new Request('http://localhost/api/tasks', { method: 'POST', body: JSON.stringify(body) })); +} + +async function putTask(userId: string, id: string, body: Record): Promise { + h.userId = userId; + return PUT( + new Request(`http://localhost/api/tasks/${id}`, { method: 'PUT', body: JSON.stringify(body) }), + { params: Promise.resolve({ id }) }, + ); +} + +async function taskRow(id: string): Promise { + return row('select title, due_date, updated_at from sl_tasks where id=$1', [id]); +} + +// The stored due date as an ISO instant, null without one. +async function dueOf(id: string): Promise { + return (await taskRow(id))?.due_date?.toISOString() ?? null; +} + +async function taskCount(userId: string): Promise { + return (await row<{ c: number }>('select count(*)::int c from sl_tasks where user_id=$1', [userId]))!.c; +} + +// Values the due date convention refuses (web/src/lib/dueDate.ts): free text, +// a day that does not exist, a date-time without a time zone. +const REFUSED = ['demain', '2026-02-30', '2026-11-15T09:00:00']; + +// An evening on the phone in Quebec: 23:00:00.123 on November 15, EST. +const PHONE_EVENING = '2026-11-16T04:00:00.123Z'; + +beforeAll(async () => { + const dir = path.join(__dirname, '../../../db/migrations'); + for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await h.pg.exec(stmt); + } + } +}); + +describe('POST /api/tasks: due date (#198)', () => { + it('stores a date alone at noon UTC', async () => { + const A = await newAccount(); + const res = await postTask(A.userId, { title: 'Dated', listId: A.list, dueDate: '2026-11-15' }); + expect(res.status).toBe(201); + const task = await res.json() as { id: string; dueDate: string | null }; + expect(task.dueDate).toBe('2026-11-15T12:00:00.000Z'); + expect(await dueOf(task.id)).toBe('2026-11-15T12:00:00.000Z'); + }); + + it('keeps the instant of a date-time with an offset', async () => { + const A = await newAccount(); + const res = await postTask(A.userId, { title: 'Timed', listId: A.list, dueDate: '2026-11-20T09:00:00-05:00' }); + expect(res.status).toBe(201); + const task = await res.json() as { id: string }; + expect(await dueOf(task.id)).toBe('2026-11-20T14:00:00.000Z'); + }); + + it('keeps the instant of a date-time with Z, as before #198', async () => { + const A = await newAccount(); + const res = await postTask(A.userId, { title: 'Timed', listId: A.list, dueDate: '2026-11-20T14:30:00.250Z' }); + expect(res.status).toBe(201); + const task = await res.json() as { id: string }; + expect(await dueOf(task.id)).toBe('2026-11-20T14:30:00.250Z'); + }); + + it('creates a task without a due date', async () => { + const A = await newAccount(); + const res = await postTask(A.userId, { title: 'Undated', listId: A.list }); + expect(res.status).toBe(201); + const task = await res.json() as { id: string; dueDate: string | null }; + expect(task.dueDate).toBeNull(); + expect(await dueOf(task.id)).toBeNull(); + }); + + it.each(REFUSED)('refuses %j with a 400 and writes nothing', async (dueDate) => { + const A = await newAccount(); + const res = await postTask(A.userId, { title: 'Dated', listId: A.list, dueDate }); + expect(res.status).toBe(400); + expect((await res.json() as { error: string }).error).toMatch(/^dueDate: /); + expect(await taskCount(A.userId)).toBe(0); + }); +}); + +describe('PUT /api/tasks/[id]: due date (#198)', () => { + it('stores a date alone at noon UTC', async () => { + const A = await newAccount(); + const id = await newTask(A); + const res = await putTask(A.userId, id, { dueDate: '2026-11-15' }); + expect(res.status).toBe(200); + expect((await res.json() as { dueDate: string | null }).dueDate).toBe('2026-11-15T12:00:00.000Z'); + expect(await dueOf(id)).toBe('2026-11-15T12:00:00.000Z'); + }); + + it('keeps the instant of a date-time with an offset', async () => { + const A = await newAccount(); + const id = await newTask(A, { dueDate: PHONE_EVENING }); + const res = await putTask(A.userId, id, { dueDate: '2026-11-20T09:00:00-05:00' }); + expect(res.status).toBe(200); + expect(await dueOf(id)).toBe('2026-11-20T14:00:00.000Z'); + }); + + it('leaves the due date untouched, to the millisecond, when only the title is sent', async () => { + const A = await newAccount(); + const id = await newTask(A, { dueDate: PHONE_EVENING }); + const res = await putTask(A.userId, id, { title: 'Renamed' }); + expect(res.status).toBe(200); + expect((await taskRow(id))?.title).toBe('Renamed'); + expect(await dueOf(id)).toBe(PHONE_EVENING); + }); + + it('accepts the body the edit form sends when the date field changed', async () => { + const A = await newAccount(); + const id = await newTask(A, { dueDate: PHONE_EVENING }); + const res = await putTask(A.userId, id, { + title: 'Renamed', notes: null, priority: 2, dueDate: '2026-11-17', recurrence: null, + }); + expect(res.status).toBe(200); + expect((await taskRow(id))?.title).toBe('Renamed'); + expect(await dueOf(id)).toBe('2026-11-17T12:00:00.000Z'); + }); + + it('clears the due date on null', async () => { + const A = await newAccount(); + const id = await newTask(A, { dueDate: PHONE_EVENING }); + const res = await putTask(A.userId, id, { dueDate: null }); + expect(res.status).toBe(200); + expect(await dueOf(id)).toBeNull(); + }); + + it.each(REFUSED)('refuses %j with a 400 and writes nothing', async (dueDate) => { + const A = await newAccount(); + const id = await newTask(A, { dueDate: PHONE_EVENING }); + const before = await taskRow(id); + const res = await putTask(A.userId, id, { title: 'Renamed', dueDate }); + expect(res.status).toBe(400); + expect((await res.json() as { error: string }).error).toMatch(/^dueDate: /); + // Title, due date and updated_at as they were. + expect(before?.due_date?.toISOString()).toBe(PHONE_EVENING); + expect(await taskRow(id)).toEqual(before); + }); +}); diff --git a/web/src/app/api/tasks/route.ts b/web/src/app/api/tasks/route.ts index da82273..697731a 100644 --- a/web/src/app/api/tasks/route.ts +++ b/web/src/app/api/tasks/route.ts @@ -42,11 +42,11 @@ export async function POST(request: Request) { } } + // body.data.dueDate is already a Date: createTaskSchema converts it (#198) const [task] = await db .insert(slTasks) .values({ ...body.data, - dueDate: body.data.dueDate ? new Date(body.data.dueDate) : undefined, userId: auth.userId, }) .returning(); diff --git a/web/src/components/TaskForm.tsx b/web/src/components/TaskForm.tsx index 7f9f493..5ccde72 100644 --- a/web/src/components/TaskForm.tsx +++ b/web/src/components/TaskForm.tsx @@ -21,6 +21,7 @@ export function TaskForm({ listId, parentId, onClose }: TaskFormProps) { const [recurrence, setRecurrence] = useState(""); const [expanded, setExpanded] = useState(false); const [submitting, setSubmitting] = useState(false); + const [saveError, setSaveError] = useState(false); const PRIORITY_LABELS = [ { value: 0, label: t("priority.none"), color: "" }, @@ -34,8 +35,10 @@ export function TaskForm({ listId, parentId, onClose }: TaskFormProps) { if (!title.trim() || submitting) return; setSubmitting(true); + setSaveError(false); + let saved = false; try { - await fetch("/api/tasks", { + const res = await fetch("/api/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ @@ -48,17 +51,28 @@ export function TaskForm({ listId, parentId, onClose }: TaskFormProps) { parentId: parentId || undefined, }), }); - setTitle(""); - setNotes(""); - setPriority(0); - setDueDate(""); - setRecurrence(""); - setExpanded(false); - router.refresh(); - onClose?.(); + saved = res.ok; + } catch { + // Network error: handled like a refusal. + saved = false; } finally { setSubmitting(false); } + + // A refusal keeps the form open with its values (#198): it empties and + // closes only once the task is saved. + if (!saved) { + setSaveError(true); + return; + } + setTitle(""); + setNotes(""); + setPriority(0); + setDueDate(""); + setRecurrence(""); + setExpanded(false); + router.refresh(); + onClose?.(); }; if (!expanded && !parentId) { @@ -91,6 +105,7 @@ export function TaskForm({ listId, parentId, onClose }: TaskFormProps) { type="button" onClick={() => { setExpanded(false); + setSaveError(false); onClose?.(); }} className="p-1 text-foreground/40 hover:text-foreground" @@ -141,12 +156,19 @@ export function TaskForm({ listId, parentId, onClose }: TaskFormProps) { + {saveError && ( +

+ {t("task.saveError")} +

+ )} +
+ {saveError && ( +

+ {t("task.saveError")} +

+ )}