fix(web): accept a date alone as a task due date and show save errors (#198) #210
12 changed files with 629 additions and 30 deletions
|
|
@ -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`
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> = {
|
||||
...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;
|
||||
|
|
|
|||
204
web/src/app/api/tasks/route.test.ts
Normal file
204
web/src/app/api/tasks/route.test.ts
Normal file
|
|
@ -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<typeof import('@/lib/api')>()),
|
||||
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<T = Record<string, unknown>>(sql: string, params: unknown[]): Promise<T | undefined> {
|
||||
return (await h.pg.query<T>(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<Account> {
|
||||
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<string> {
|
||||
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<string, unknown>): Promise<Response> {
|
||||
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<string, unknown>): Promise<Response> {
|
||||
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<TaskRow | undefined> {
|
||||
return row<TaskRow>('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<string | null> {
|
||||
return (await taskRow(id))?.due_date?.toISOString() ?? null;
|
||||
}
|
||||
|
||||
async function taskCount(userId: string): Promise<number> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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) {
|
|||
</select>
|
||||
</div>
|
||||
|
||||
{saveError && (
|
||||
<p role="alert" className="text-xs text-rouge">
|
||||
{t("task.saveError")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setExpanded(false);
|
||||
setTitle("");
|
||||
setSaveError(false);
|
||||
onClose?.();
|
||||
}}
|
||||
className="px-3 py-1.5 text-sm text-foreground/60 hover:text-foreground"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { Task, TagPill } from "@/lib/types";
|
||||
import { localDay, dueDateField } from "@/lib/dueDate";
|
||||
import { TaskForm } from "./TaskForm";
|
||||
|
||||
const PRIORITY_COLORS: Record<number, string> = {
|
||||
|
|
@ -74,12 +75,12 @@ export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, account
|
|||
const [title, setTitle] = useState(task.title);
|
||||
const [notes, setNotes] = useState(task.notes || "");
|
||||
const [priority, setPriority] = useState(task.priority);
|
||||
const [dueDate, setDueDate] = useState(
|
||||
task.dueDate ? new Date(String(task.dueDate)).toISOString().split("T")[0] : ""
|
||||
);
|
||||
// The date field shows the local day, the one the list shows (#198).
|
||||
const [dueDate, setDueDate] = useState(localDay(task.dueDate));
|
||||
const [recurrence, setRecurrence] = useState(task.recurrence || "");
|
||||
const [showSubtaskForm, setShowSubtaskForm] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState(false);
|
||||
const [tagBusy, setTagBusy] = useState(false);
|
||||
|
||||
const taskTags = tagsMap[task.id] ?? [];
|
||||
|
|
@ -109,9 +110,7 @@ export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, account
|
|||
setTitle(task.title);
|
||||
setNotes(task.notes || "");
|
||||
setPriority(task.priority);
|
||||
setDueDate(
|
||||
task.dueDate ? new Date(String(task.dueDate)).toISOString().split("T")[0] : ""
|
||||
);
|
||||
setDueDate(localDay(task.dueDate));
|
||||
setRecurrence(task.recurrence || "");
|
||||
}, [task]);
|
||||
|
||||
|
|
@ -127,23 +126,38 @@ export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, account
|
|||
const saveEdit = async () => {
|
||||
if (!title.trim() || saving) return;
|
||||
setSaving(true);
|
||||
setSaveError(false);
|
||||
// The due date is sent only when the date field changed (#198): otherwise
|
||||
// the server keeps the stored instant, with the time set on the phone.
|
||||
const due = dueDateField(localDay(task.dueDate), dueDate);
|
||||
let saved = false;
|
||||
try {
|
||||
await fetch(`/api/tasks/${task.id}`, {
|
||||
const res = await fetch(`/api/tasks/${task.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
notes: notes || null,
|
||||
priority,
|
||||
dueDate: dueDate || null,
|
||||
...(due === undefined ? {} : { dueDate: due }),
|
||||
recurrence: recurrence || null,
|
||||
}),
|
||||
});
|
||||
setEditing(false);
|
||||
router.refresh();
|
||||
saved = res.ok;
|
||||
} catch {
|
||||
// Network error: handled like a refusal.
|
||||
saved = false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
// A refusal keeps the edit form open with its values (#198).
|
||||
if (!saved) {
|
||||
setSaveError(true);
|
||||
return;
|
||||
}
|
||||
setEditing(false);
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
// Add or remove an existing tag through the task-tag API, then reload.
|
||||
|
|
@ -309,9 +323,17 @@ export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, account
|
|||
<option value="yearly">{t("recurrence.yearly")}</option>
|
||||
</select>
|
||||
</div>
|
||||
{saveError && (
|
||||
<p role="alert" className="text-xs text-rouge">
|
||||
{t("task.saveError")}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button
|
||||
onClick={() => setEditing(false)}
|
||||
onClick={() => {
|
||||
setEditing(false);
|
||||
setSaveError(false);
|
||||
}}
|
||||
className="px-3 py-1 text-sm text-foreground/60 hover:text-foreground"
|
||||
>
|
||||
{t("task.cancel")}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@
|
|||
"priority": "Priority",
|
||||
"priorityLabel": "Priority: {{value}}",
|
||||
"dueDate": "Due: {{value}}",
|
||||
"recurrenceLabel": "Recurrence: {{value}}"
|
||||
"recurrenceLabel": "Recurrence: {{value}}",
|
||||
"saveError": "The task could not be saved."
|
||||
},
|
||||
"tag": {
|
||||
"label": "Tags:",
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@
|
|||
"priority": "Priorité",
|
||||
"priorityLabel": "Priorité : {{value}}",
|
||||
"dueDate": "Échéance : {{value}}",
|
||||
"recurrenceLabel": "Récurrence : {{value}}"
|
||||
"recurrenceLabel": "Récurrence : {{value}}",
|
||||
"saveError": "La tâche n'a pas pu être enregistrée."
|
||||
},
|
||||
"tag": {
|
||||
"label": "Étiquettes :",
|
||||
|
|
|
|||
224
web/src/lib/dueDate.test.ts
Normal file
224
web/src/lib/dueDate.test.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, it, expect } from 'vitest';
|
||||
import { parseDueDate, DUE_DATE_MAX_LENGTH, localDay, dueDateField } from './dueDate';
|
||||
import { dueDateSchema } from './validators';
|
||||
|
||||
// Due date convention (#198): a date alone at noon UTC, a date-time with its
|
||||
// offset kept as it is, the rest refused.
|
||||
|
||||
const iso = (value: string) => parseDueDate(value)?.toISOString() ?? null;
|
||||
|
||||
describe('dueDate.ts', () => {
|
||||
it('stays import-free: the browser loads it, and zod must not follow it there', () => {
|
||||
const source = fs.readFileSync(path.join(__dirname, 'dueDate.ts'), 'utf8');
|
||||
expect(source).not.toMatch(/^\s*import\s|\bimport\(|\brequire\(/m);
|
||||
expect(source).toMatch(/^export function parseDueDate\(/m);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseDueDate', () => {
|
||||
it('stores a date alone at noon UTC', () => {
|
||||
expect(iso('2026-11-15')).toBe('2026-11-15T12:00:00.000Z');
|
||||
expect(iso('2026-07-01')).toBe('2026-07-01T12:00:00.000Z');
|
||||
expect(iso('2026-12-31')).toBe('2026-12-31T12:00:00.000Z');
|
||||
});
|
||||
|
||||
it('accepts February 29 of a leap year only', () => {
|
||||
expect(iso('2024-02-29')).toBe('2024-02-29T12:00:00.000Z');
|
||||
expect(iso('2000-02-29')).toBe('2000-02-29T12:00:00.000Z');
|
||||
expect(parseDueDate('2026-02-29')).toBeNull();
|
||||
expect(parseDueDate('2100-02-29')).toBeNull();
|
||||
});
|
||||
|
||||
it('knows the last day of every month', () => {
|
||||
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].forEach((days, index) => {
|
||||
const month = String(index + 1).padStart(2, '0');
|
||||
expect(iso(`2026-${month}-${days}`), month).toBe(`2026-${month}-${days}T12:00:00.000Z`);
|
||||
expect(parseDueDate(`2026-${month}-${days + 1}`), month).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the instant of a date-time with Z', () => {
|
||||
expect(iso('2026-11-20T14:00:00Z')).toBe('2026-11-20T14:00:00.000Z');
|
||||
expect(iso('2026-11-20T14:30:00.250Z')).toBe('2026-11-20T14:30:00.250Z');
|
||||
});
|
||||
|
||||
it('keeps the instant of a date-time with an offset', () => {
|
||||
expect(iso('2026-11-20T09:00:00-05:00')).toBe('2026-11-20T14:00:00.000Z');
|
||||
expect(iso('2026-07-01T08:00:00-04:00')).toBe('2026-07-01T12:00:00.000Z');
|
||||
expect(iso('2026-11-20T23:30:00+09:00')).toBe('2026-11-20T14:30:00.000Z');
|
||||
expect(iso('2026-11-20T14:00:00+00:00')).toBe('2026-11-20T14:00:00.000Z');
|
||||
// The offset moves the instant to another day.
|
||||
expect(iso('2026-11-20T22:00:00-05:00')).toBe('2026-11-21T03:00:00.000Z');
|
||||
});
|
||||
|
||||
it('accepts a date-time without seconds', () => {
|
||||
expect(iso('2026-11-20T09:00-05:00')).toBe('2026-11-20T14:00:00.000Z');
|
||||
expect(iso('2026-11-20T14:00Z')).toBe('2026-11-20T14:00:00.000Z');
|
||||
});
|
||||
|
||||
it('cuts a fraction of a second to the millisecond', () => {
|
||||
expect(iso('2026-11-20T14:00:00.5Z')).toBe('2026-11-20T14:00:00.500Z');
|
||||
expect(iso('2026-11-20T14:00:00.12Z')).toBe('2026-11-20T14:00:00.120Z');
|
||||
expect(iso('2026-11-20T14:00:00.123999Z')).toBe('2026-11-20T14:00:00.123Z');
|
||||
});
|
||||
|
||||
it('refuses a day that does not exist', () => {
|
||||
for (const value of [
|
||||
'2026-02-30', '2026-04-31', '2026-13-01', '2026-00-10', '2026-11-00', '2026-11-32',
|
||||
'2026-02-30T09:00:00Z', '2026-04-31T09:00:00-05:00',
|
||||
]) {
|
||||
expect(parseDueDate(value), value).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a date-time without a time zone', () => {
|
||||
for (const value of ['2026-11-15T09:00:00', '2026-11-15T09:00', '2026-11-15T09:00:00.000']) {
|
||||
expect(parseDueDate(value), value).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a time or an offset out of range', () => {
|
||||
for (const value of [
|
||||
'2026-11-15T24:00:00Z', '2026-11-15T09:60:00Z', '2026-11-15T09:00:60Z',
|
||||
'2026-11-15T09:00:00+24:00', '2026-11-15T09:00:00-05:60',
|
||||
]) {
|
||||
expect(parseDueDate(value), value).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts the last time and the last offset in range', () => {
|
||||
expect(iso('2026-11-15T23:59:59.999Z')).toBe('2026-11-15T23:59:59.999Z');
|
||||
expect(iso('2026-11-15T23:59:59+23:59')).toBe('2026-11-15T00:00:59.000Z');
|
||||
expect(iso('2026-11-15T00:00:00-23:59')).toBe('2026-11-15T23:59:00.000Z');
|
||||
});
|
||||
|
||||
it('refuses free text, an empty string and other formats', () => {
|
||||
// Digits that are not ASCII: 2026 in Arabic-Indic numerals.
|
||||
const arabicIndicYear = String.fromCodePoint(0x662, 0x660, 0x662, 0x666);
|
||||
for (const value of [
|
||||
'', 'demain', 'tomorrow', '15/11/2026', '2026-1-5', '20261115', '2026-11-15T',
|
||||
' 2026-11-15', '2026-11-15 ', '2026-11-15\n', '2026-11-15T09:00:00Z\n',
|
||||
'2026-11-15 09:00:00Z', '2026-11-15t09:00:00z', '2026-11-15T09:00:00+0500', '2026-11-15T09:00:00+05',
|
||||
'2026-11-15T09:00:00.Z', '2026-11-15T09:00.5Z', '+002026-11-15', `${arabicIndicYear}-11-15`,
|
||||
// Nothing before a date-time either: a fifth digit of the year, a space.
|
||||
'12026-11-15T09:00:00Z', ' 2026-11-15T09:00:00Z',
|
||||
]) {
|
||||
expect(parseDueDate(value), JSON.stringify(value)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses an instant whose UTC year PostgreSQL cannot read (0000, or beyond 9999)', () => {
|
||||
expect(iso('0001-01-01')).toBe('0001-01-01T12:00:00.000Z');
|
||||
expect(iso('9999-12-31T23:59:59.999Z')).toBe('9999-12-31T23:59:59.999Z');
|
||||
for (const value of [
|
||||
'0000-06-01', '0000-06-01T12:00:00Z',
|
||||
'0001-01-01T00:00:00+14:00', // 0000-12-31 in UTC
|
||||
'9999-12-31T23:59:59-00:01', // 10000-01-01 in UTC
|
||||
]) {
|
||||
expect(parseDueDate(value), value).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('dueDateSchema', () => {
|
||||
it('turns an accepted value into a Date', () => {
|
||||
const r = dueDateSchema.safeParse('2026-11-15');
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.data).toBeInstanceOf(Date);
|
||||
expect(r.data!.toISOString()).toBe('2026-11-15T12:00:00.000Z');
|
||||
expect(dueDateSchema.parse('2026-11-20T09:00:00-05:00').toISOString()).toBe('2026-11-20T14:00:00.000Z');
|
||||
});
|
||||
|
||||
it('refuses what parseDueDate refuses, with a single issue', () => {
|
||||
for (const value of ['demain', '2026-02-30', '2026-11-15T09:00:00', '']) {
|
||||
const r = dueDateSchema.safeParse(value);
|
||||
expect(r.success, JSON.stringify(value)).toBe(false);
|
||||
expect(r.error!.issues).toHaveLength(1);
|
||||
expect(r.error!.issues[0].code).toBe('custom');
|
||||
expect(r.error!.issues[0].message).toMatch(/^Invalid due date/);
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a value that is not a string', () => {
|
||||
for (const value of [20261115, null, undefined, true, {}, new Date('2026-11-15T12:00:00.000Z')]) {
|
||||
expect(dueDateSchema.safeParse(value).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('bounds the text at 40 characters before reading it', () => {
|
||||
const fits = `2026-11-20T09:00:00.${'1'.repeat(14)}-05:00`;
|
||||
const tooLong = `2026-11-20T09:00:00.${'1'.repeat(15)}-05:00`;
|
||||
expect(DUE_DATE_MAX_LENGTH).toBe(40);
|
||||
expect(fits).toHaveLength(40);
|
||||
expect(dueDateSchema.parse(fits).toISOString()).toBe('2026-11-20T14:00:00.111Z');
|
||||
// The format is fine: only the bound refuses it.
|
||||
expect(parseDueDate(tooLong)).not.toBeNull();
|
||||
const r = dueDateSchema.safeParse(tooLong);
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error!.issues).toHaveLength(1);
|
||||
expect(r.error!.issues[0].code).toBe('too_big');
|
||||
});
|
||||
});
|
||||
|
||||
describe('localDay', () => {
|
||||
// The local day depends on the time zone: each test sets its own.
|
||||
const zone = process.env.TZ;
|
||||
|
||||
afterEach(() => {
|
||||
if (zone === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = zone;
|
||||
});
|
||||
|
||||
it('gives the local day, not the UTC day, west of UTC', () => {
|
||||
process.env.TZ = 'America/Toronto';
|
||||
// 23:00 on November 15 in Quebec is already November 16 in UTC.
|
||||
expect(localDay('2026-11-16T04:00:00.000Z')).toBe('2026-11-15');
|
||||
expect(localDay(new Date('2026-11-16T04:00:00.000Z'))).toBe('2026-11-15');
|
||||
});
|
||||
|
||||
it('gives the local day, not the UTC day, east of UTC', () => {
|
||||
process.env.TZ = 'Asia/Tokyo';
|
||||
// 01:00 on November 16 in Tokyo is still November 15 in UTC.
|
||||
expect(localDay('2026-11-15T16:00:00.000Z')).toBe('2026-11-16');
|
||||
expect(localDay(new Date('2026-11-15T16:00:00.000Z'))).toBe('2026-11-16');
|
||||
});
|
||||
|
||||
it('shows a date stored at noon UTC on its own day from UTC-11 to UTC+11', () => {
|
||||
for (const tz of ['Pacific/Pago_Pago', 'America/Toronto', 'UTC', 'Europe/Paris', 'Pacific/Noumea']) {
|
||||
process.env.TZ = tz;
|
||||
// Winter and summer (daylight saving time in Toronto and Paris).
|
||||
expect(localDay(parseDueDate('2026-11-15')), tz).toBe('2026-11-15');
|
||||
expect(localDay(parseDueDate('2026-07-01')), tz).toBe('2026-07-01');
|
||||
}
|
||||
});
|
||||
|
||||
it('pads the month and the day', () => {
|
||||
process.env.TZ = 'America/Toronto';
|
||||
expect(localDay('2026-01-05T17:00:00.000Z')).toBe('2026-01-05');
|
||||
});
|
||||
|
||||
it('is empty without a due date, and for a text that is not an instant', () => {
|
||||
expect(localDay(null)).toBe('');
|
||||
expect(localDay('')).toBe('');
|
||||
expect(localDay('demain')).toBe('');
|
||||
expect(localDay(new Date(Number.NaN))).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dueDateField', () => {
|
||||
it('sends nothing when the field has not changed', () => {
|
||||
expect(dueDateField('2026-11-15', '2026-11-15')).toBeUndefined();
|
||||
expect(dueDateField('', '')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clears the due date when the field was emptied', () => {
|
||||
expect(dueDateField('2026-11-15', '')).toBeNull();
|
||||
});
|
||||
|
||||
it('sends the day typed when the field changed', () => {
|
||||
expect(dueDateField('2026-11-15', '2026-11-20')).toBe('2026-11-20');
|
||||
expect(dueDateField('', '2026-11-20')).toBe('2026-11-20');
|
||||
});
|
||||
});
|
||||
103
web/src/lib/dueDate.ts
Normal file
103
web/src/lib/dueDate.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// Due date convention of the companion (#198), kept out of the JSX so vitest
|
||||
// covers it without a DOM.
|
||||
//
|
||||
// A due date is an instant, and the server does not know the user's time zone.
|
||||
// A date alone (what <input type="date"> gives) is stored at noon UTC: it shows
|
||||
// on the same day from UTC-11 to UTC+11, and its reminder rings at 7:00 in
|
||||
// winter and 8:00 in summer in Quebec (America/Toronto). A date-time names its
|
||||
// own offset and is kept as it is.
|
||||
//
|
||||
// This module stays import-free: TaskItem.tsx loads it in the browser, and an
|
||||
// import of zod here would put zod in the client bundle. The zod schema built
|
||||
// on parseDueDate, dueDateSchema, lives in validators.ts.
|
||||
|
||||
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
|
||||
// Seconds are optional, a fraction of a second too; the zone is not.
|
||||
// Groups: 1 year, 2 month, 3 day, 4 hour, 5 minute, 6 second, 7 fraction,
|
||||
// 8 sign of the offset, 9 and 10 its hours and minutes (8 to 10 absent with Z).
|
||||
const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):(\d{2}))$/;
|
||||
|
||||
function daysInMonth(year: number, month: number): number {
|
||||
if (month === 2) return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
|
||||
return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
|
||||
}
|
||||
|
||||
function isCalendarDay(year: number, month: number, day: number): boolean {
|
||||
return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month);
|
||||
}
|
||||
|
||||
// Milliseconds since the epoch of a calendar day and a time of day, in UTC.
|
||||
// The caller has checked every field: the setters of Date do not refuse a
|
||||
// value out of range, they roll it over (February 30 becomes March 2).
|
||||
// setUTCFullYear and not Date.UTC, which reads the years 0 to 99 as 1900 to 1999.
|
||||
function utcTime(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): number {
|
||||
const date = new Date(0);
|
||||
date.setUTCFullYear(year, month - 1, day);
|
||||
date.setUTCHours(hour, minute, second, ms);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
// PostgreSQL reads the ISO text drizzle sends for a timestamp, and that text
|
||||
// only holds the years 0001 to 9999 (read in UTC): outside, the write fails.
|
||||
function storable(time: number): Date | null {
|
||||
const date = new Date(time);
|
||||
const year = date.getUTCFullYear();
|
||||
return year >= 1 && year <= 9999 ? date : null;
|
||||
}
|
||||
|
||||
// The instant of a due date received as text, null when the text is refused.
|
||||
// - `YYYY-MM-DD`, a real day of the calendar: that day at 12:00:00.000 UTC.
|
||||
// - An ISO 8601 date-time with `Z` or an offset (`+hh:mm`, `-hh:mm`): that
|
||||
// instant, cut to the millisecond.
|
||||
// - Anything else is refused: a date-time without a time zone (the server
|
||||
// cannot tell which one), another format, an empty string.
|
||||
export function parseDueDate(value: string): Date | null {
|
||||
const dateOnly = DATE.exec(value);
|
||||
if (dateOnly) {
|
||||
const [year, month, day] = dateOnly.slice(1).map(Number);
|
||||
if (!isCalendarDay(year, month, day)) return null;
|
||||
return storable(utcTime(year, month, day, 12, 0, 0, 0));
|
||||
}
|
||||
|
||||
const dateTime = DATE_TIME.exec(value);
|
||||
if (!dateTime) return null;
|
||||
const [year, month, day, hour, minute] = dateTime.slice(1, 6).map(Number);
|
||||
const second = Number(dateTime[6] ?? 0);
|
||||
const ms = Number((dateTime[7] ?? '').slice(0, 3).padEnd(3, '0'));
|
||||
const offsetHour = Number(dateTime[9] ?? 0);
|
||||
const offsetMinute = Number(dateTime[10] ?? 0);
|
||||
if (!isCalendarDay(year, month, day)) return null;
|
||||
if (hour > 23 || minute > 59 || second > 59) return null;
|
||||
if (offsetHour > 23 || offsetMinute > 59) return null;
|
||||
// Minutes east of UTC: 09:00-05:00 is 14:00 UTC.
|
||||
const offset = (dateTime[8] === '-' ? -1 : 1) * (offsetHour * 60 + offsetMinute);
|
||||
return storable(utcTime(year, month, day, hour, minute, second, ms) - offset * 60_000);
|
||||
}
|
||||
|
||||
// Longest text dueDateSchema (validators.ts) hands to parseDueDate; a
|
||||
// date-time with milliseconds and an offset holds in 29 characters.
|
||||
export const DUE_DATE_MAX_LENGTH = 40;
|
||||
|
||||
// The local day (`YYYY-MM-DD`) of a due date, in the time zone of the runtime:
|
||||
// the user's own in the browser. It prefills <input type="date"> with the day
|
||||
// the list shows. Empty without a due date.
|
||||
export function localDay(value: Date | string | null): string {
|
||||
if (value === null) return '';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const pad = (n: number, length: number) => String(n).padStart(length, '0');
|
||||
return `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1, 2)}-${pad(date.getDate(), 2)}`;
|
||||
}
|
||||
|
||||
// What the edit form sends for its date field. `prefill` is the day the field
|
||||
// was filled with (localDay of the stored due date), `current` its value when
|
||||
// the form is saved.
|
||||
// - undefined: unchanged, the body carries no `dueDate` and the server keeps
|
||||
// the stored instant, with the time set on the phone;
|
||||
// - null: emptied, the due date is cleared;
|
||||
// - otherwise the day typed, which the server stores at noon UTC.
|
||||
export function dueDateField(prefill: string, current: string): string | null | undefined {
|
||||
if (current === prefill) return undefined;
|
||||
return current === '' ? null : current;
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { DUE_DATE_MAX_LENGTH, parseDueDate } from './dueDate';
|
||||
|
||||
// Lists
|
||||
export const createListSchema = z.object({
|
||||
|
|
@ -23,12 +24,31 @@ export const reorderSchema = z.object({
|
|||
}).strict();
|
||||
|
||||
// Tasks
|
||||
|
||||
// The due date of a request body (#198): a bounded string, turned into the
|
||||
// Date the route writes. The convention is parseDueDate (dueDate.ts): a date
|
||||
// alone is stored at noon UTC, a date-time with Z or an offset is kept, the
|
||||
// rest is refused. The schema lives here and not in dueDate.ts, which the
|
||||
// browser loads and which stays free of zod.
|
||||
export const dueDateSchema = z.string().max(DUE_DATE_MAX_LENGTH).transform((value, ctx) => {
|
||||
const date = parseDueDate(value);
|
||||
if (date === null) {
|
||||
ctx.issues.push({
|
||||
code: 'custom',
|
||||
message: 'Invalid due date: expected YYYY-MM-DD, or an ISO 8601 date-time with Z or a UTC offset such as -05:00',
|
||||
input: value,
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return date;
|
||||
});
|
||||
|
||||
export const createTaskSchema = z.object({
|
||||
title: z.string().min(1).max(500),
|
||||
listId: z.string().uuid(),
|
||||
notes: z.string().max(5000).optional(),
|
||||
priority: z.number().int().min(0).max(3).optional(),
|
||||
dueDate: z.string().datetime().optional(),
|
||||
dueDate: dueDateSchema.optional(),
|
||||
parentId: z.string().uuid().optional(),
|
||||
recurrence: z.string().max(100).optional(),
|
||||
}).strict();
|
||||
|
|
@ -38,7 +58,8 @@ export const updateTaskSchema = z.object({
|
|||
notes: z.string().max(5000).nullable().optional(),
|
||||
completed: z.boolean().optional(),
|
||||
priority: z.number().int().min(0).max(3).optional(),
|
||||
dueDate: z.string().datetime().nullable().optional(),
|
||||
// null clears the due date; absent, it is left as it is.
|
||||
dueDate: dueDateSchema.nullable().optional(),
|
||||
listId: z.string().uuid().optional(),
|
||||
parentId: z.string().uuid().nullable().optional(),
|
||||
position: z.number().int().min(0).optional(),
|
||||
|
|
|
|||
|
|
@ -21,5 +21,8 @@ export default defineConfig({
|
|||
// Always shuffle: the sync route tests once depended on their order (#148).
|
||||
// Vitest prints the seed; replay a run with `npx vitest run --sequence.seed=<n>`.
|
||||
sequence: { shuffle: true },
|
||||
// Every route test file boots its own PGlite in a beforeAll, slower while
|
||||
// other files boot theirs: the default of 10 s has already been exceeded (#198).
|
||||
hookTimeout: 30_000,
|
||||
},
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue