feat(web): the server creates the next occurrence when a recurring task is completed (#201) #213

Open
maximus wants to merge 4 commits from issue-201-recurring-completion into issue-200-agent-tokens
9 changed files with 966 additions and 25 deletions

View file

@ -115,6 +115,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Les formes de données sont croisées : le client pousse en camelCase (`listId`, `dueDate`), le serveur renvoie en snake_case (`list_id`, `due_date`). Un champ ajouté l'est des deux côtés, avec la conversion des dates. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts`
- L'Inbox locale a l'identifiant fixe `00000000-0000-0000-0000-000000000001`, remappé vers un UUID serveur à la première sync (`initialMerge`). Une Inbox créée par la sync absorbe toutes les autres Inbox actives du compte (tâches déplacées, Inbox archivées), et elle est insérée avant le déplacement, car la clé étrangère `sl_tasks.list_id` n'est pas différable. Un id déjà présent dans le compte ne fusionne rien. Une seule Inbox est créée par POST, la suivante revient `skipped`. Une tâche envoyée vers une Inbox archivée, à la création comme à la mise à jour, va dans l'Inbox active. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts`, PR #58, #64, #145, `web/src/db/migrations/0002_cleanup_duplicate_inboxes.sql`
- `task create` écrit `completed` et `completedAt` ; une tâche terminée sans date reçoit la date du serveur, une tâche non terminée n'a pas de date (#146). — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts`
- L'occurrence suivante d'une tâche récurrente est créée par celui qui la coche, une seule fois : l'app pour ses propres complétions (`toggleComplete`, qui la pousse ensuite par la sync), et `completeTask` pour le site (`PUT /api/tasks/[id]`) et pour les outils MCP, qui l'appelleront (#203). Jamais `POST /api/sync` : un `task update` ou un `task create` terminé n'y crée aucune occurrence, sinon chaque complétion faite sur le téléphone en créerait deux. `completeTask` ne la crée que si son `UPDATE … WHERE completed = false … RETURNING` rend la ligne : un rejeu n'en crée pas une seconde, et deux requêtes simultanées n'en créent qu'une (la seconde attend la première, ce qu'aucun test PGlite ne voit, faute d'une seconde connexion). Elle est créée pour une tâche qui a une échéance et une récurrence de `RECURRENCES` : mêmes titre, notes, priorité, liste et récurrence, sans étiquettes ni parent, à l'échéance de la tâche plus une période, en fin de liste ; `reopenTask` la laisse en place. Le serveur calcule en UTC (`nextOccurrence`) et l'app en heure locale : à un changement d'heure, l'heure locale d'une occurrence créée par le serveur glisse d'une heure, et en fin de mois une échéance posée le soir au Québec, déjà le lendemain en UTC, peut donner un jour d'écart avec l'app ; les deux codes rendent les mêmes instants sous `TZ=UTC`, ce que vérifie `web/src/test/sync/recurrence.test.ts`. Contrat de `taskWrites.ts`, pour toutes ses fonctions : la transaction de l'appelant en premier argument, puis `userId` ; aucune transaction ouverte, aucune notification, aucun import de `@/db/client` ; `{ changed, … }`, ou `null` pour une ligne absente, supprimée ou d'un autre compte. L'appelant notifie une fois, après le commit. — `web/src/lib/taskWrites.ts`, `web/src/lib/recurrence.ts`, `web/src/app/api/tasks/[id]/route.ts`, `src/db/repository/tasks.ts`, `web/src/app/api/tasks/route.test.ts`, `web/src/app/api/sync/route.test.ts`, #201
- `initialReset` efface toutes les données locales avant de tirer celles du serveur : un appel ajouté se justifie, et il reste derrière une confirmation de l'utilisateur. — `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`
- Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165
- Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts`

View file

@ -520,6 +520,35 @@ describe('POST /api/sync: completion on task create (#146)', () => {
});
});
describe('POST /api/sync: a completed task creates no next occurrence (#201)', () => {
it('leaves the next occurrence of a recurring task to the app that completed it', async () => {
const { B } = await seed();
const id = u();
const taskCount = async () =>
(await row<{ c: number }>('select count(*)::int c from sl_tasks where user_id=$1', [B.userId]))!.c;
// The payloads of createTask, then of updateTask when toggleComplete
// completes the task (src/db/repository/tasks.ts): recurring, with a due date.
const task = { id, title: 'Recurring', notes: null, priority: 0, dueDate: D, listId: B.list, parentId: null, recurrence: 'weekly' };
expect(await push(B.userId, [['task', 'create', id, { ...task, completed: false, completedAt: null }]])).toEqual(['applied']);
const before = await taskCount();
expect(await push(B.userId, [
['task', 'update', id, { ...task, completed: true, completedAt: '2026-10-20T08:30:00.000Z' }],
])).toEqual(['applied']);
expect(await row('select completed, recurrence, due_date from sl_tasks where id=$1', [id]))
.toEqual({ completed: true, recurrence: 'weekly', due_date: new Date(D) });
// No row added: the app creates the next occurrence itself and pushes it.
expect(await taskCount()).toBe(before);
// Nor for a recurring task created done (initialMerge).
expect(await push(B.userId, [
['task', 'create', u(), { title: 'Done', listId: B.list, dueDate: D, recurrence: 'daily', completed: true }],
])).toEqual(['applied']);
expect(await taskCount()).toBe(before + 1);
});
});
describe('POST /api/sync: bounded batches (#147)', () => {
async function post(userId: string, body: unknown): Promise<Response> {
h.userId = userId;

View file

@ -1,11 +1,12 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { eq, and, isNull } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { deleteTask } from '@/lib/taskDelete';
import { completeTask, reopenTask, type TaskRow } from '@/lib/taskWrites';
import { updateTaskSchema } from '@/lib/validators';
export async function PUT(
@ -21,29 +22,63 @@ 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(),
};
// `completed` goes through completeTask or reopenTask (#201); the other
// fields are written as they are. fields.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 { completed, ...fields } = body.data;
const hasFields = Object.values(fields).some((value) => value !== undefined);
const now = new Date();
// Set completedAt when toggling completed
if (body.data.completed !== undefined) {
updateData.completedAt = body.data.completed ? new Date() : null;
}
// One transaction for the whole body (#201): the fields, the completion and
// the next occurrence of a recurring task are written together or not at
// all. It gives the task back, or null for a 404. A refusal returns before
// the first write: a return commits what was written before it.
const updated = await db.transaction(async (tx) => {
let task: TaskRow | undefined;
const [updated] = await db
.update(slTasks)
.set(updateData)
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
.returning();
// The other fields first: the task is completed as the body leaves it, and
// its next occurrence is copied from that state. Nothing is written here
// for a body that only carries `completed`, so that replaying it writes
// nothing at all.
if (hasFields || completed === undefined) {
[task] = await tx
.update(slTasks)
.set({ ...fields, updatedAt: now })
.where(and(
eq(slTasks.id, id),
eq(slTasks.userId, auth.userId),
// A body that carries `completed` does not reach a deleted task
// (404, as completeTask and reopenTask answer). Without `completed`,
// a deleted task is still written, as before #201.
completed === undefined ? undefined : isNull(slTasks.deletedAt),
))
.returning();
if (!task) return null;
}
if (completed !== undefined) {
const result = completed
? await completeTask(tx, auth.userId, id, now)
: await reopenTask(tx, auth.userId, id, now);
// Not a live task of the account. Nothing was written above in that
// case: the write of the fields, when there is one, has the same filter
// and has already returned.
if (!result) return null;
task = result.task;
}
return task ?? null;
});
if (!updated) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
// Once, and only after the commit: an open page or the app that reloads on
// this notice must find the task and its next occurrence.
notifyUserChanged(auth.userId);
// The task alone, as before: the next occurrence is not part of the answer.
return NextResponse.json(updated);
}

View file

@ -6,18 +6,38 @@ 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.
// Auth and rate limiting are stubbed, the WebSocket notice is recorded; 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: '' };
return {
pg: new PGlite() as PGlite,
userId: '',
// Transactions opened through db.transaction and not yet settled (#201).
openTransactions: 0,
// WebSocket notices, in order: the account, and whether every transaction
// had settled when the notice left.
notified: [] as { userId: string; afterCommit: boolean }[],
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
const db = drizzle(h.pg, { schema });
// Count the open transactions, so that the notice stub can tell a notice
// sent from inside a transaction from one sent after the commit (#201).
const transaction = db.transaction.bind(db);
db.transaction = (async (...args: Parameters<typeof transaction>) => {
h.openTransactions++;
try {
return await transaction(...args);
} finally {
h.openTransactions--;
}
}) as typeof db.transaction;
return { db };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
@ -27,15 +47,55 @@ vi.mock('@/lib/api', async (importOriginal) => ({
}));
vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null }));
vi.mock('@/lib/ws', () => ({ notifyUserChanged: () => {} }));
vi.mock('@/lib/ws', () => ({
notifyUserChanged: (userId: string) => {
h.notified.push({ userId, afterCommit: h.openTransactions === 0 });
},
}));
const { POST } = await import('./route');
const { PUT } = await import('./[id]/route');
const { db } = await import('@/db/client');
const { completeTask, reopenTask } = await import('@/lib/taskWrites');
type Account = { userId: string; list: string };
type TaskRow = { title: string; due_date: Date | null; updated_at: Date };
// Every column of sl_tasks, as PGlite returns a row.
type StoredTask = {
id: string;
user_id: string;
title: string;
notes: string | null;
completed: boolean;
completed_at: Date | null;
priority: number;
due_date: Date | null;
list_id: string;
parent_id: string | null;
position: number;
recurrence: string | null;
created_at: Date;
updated_at: Date;
deleted_at: Date | null;
};
// What newTask writes. Instants are ISO strings; `completedAt` makes the task
// a done one, `deletedAt` a deleted one, `list` puts it in another list.
type TaskFields = {
dueDate?: string;
title?: string;
notes?: string;
priority?: number;
recurrence?: string;
position?: number;
parentId?: string;
list?: string;
completedAt?: string;
deletedAt?: string;
};
async function row<T = Record<string, unknown>>(sql: string, params: unknown[]): Promise<T | undefined> {
return (await h.pg.query<T>(sql, params)).rows[0];
}
@ -49,11 +109,17 @@ async function newAccount(): Promise<Account> {
}
// A task written straight to the table; `dueDate` is an ISO instant.
async function newTask(account: Account, fields: { dueDate?: string } = {}): Promise<string> {
async function newTask(account: Account, fields: TaskFields = {}): 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],
`insert into sl_tasks
(id, user_id, title, list_id, due_date, notes, priority, recurrence, position, parent_id, completed, completed_at, deleted_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,
[
id, account.userId, fields.title ?? 'Task', fields.list ?? account.list, fields.dueDate ?? null,
fields.notes ?? null, fields.priority ?? 0, fields.recurrence ?? null, fields.position ?? 0,
fields.parentId ?? null, fields.completedAt !== undefined, fields.completedAt ?? null, fields.deletedAt ?? null,
],
);
return id;
}
@ -84,6 +150,37 @@ 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;
}
// Every column of a task.
async function stored(id: string): Promise<StoredTask> {
return (await row<StoredTask>('select * from sl_tasks where id=$1', [id]))!;
}
// The tasks of an account that the test did not write itself (`seeded`): the
// next occurrences its requests created.
async function occurrences(account: Account, seeded: string[]): Promise<StoredTask[]> {
const { rows } = await h.pg.query<StoredTask>(
'select * from sl_tasks where user_id=$1 order by created_at, id', [account.userId],
);
return rows.filter((task) => !seeded.includes(task.id));
}
// The WebSocket notices sent to an account, in order: true for a notice that
// left after the commit, false for one sent while a transaction was open.
function notices(userId: string): boolean[] {
return h.notified.filter((notice) => notice.userId === userId).map((notice) => notice.afterCommit);
}
// Run `fn` with `new Date()` frozen at `iso`: the handler stamps completedAt
// and updatedAt with it. Only Date is faked, the timers keep running.
async function at<T>(iso: string, fn: () => Promise<T>): Promise<T> {
vi.useFakeTimers({ toFake: ['Date'], now: new Date(iso) });
try {
return await fn();
} finally {
vi.useRealTimers();
}
}
// 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'];
@ -202,3 +299,379 @@ describe('PUT /api/tasks/[id]: due date (#198)', () => {
expect(await taskRow(id)).toEqual(before);
});
});
// Completion (#201). DUE is a Friday at 9:00 in Quebec; NOW, LATER and LAST
// are the clock of the requests, set by at().
const DUE = '2026-11-20T14:00:00.000Z';
const NOW = '2026-11-15T15:00:00.000Z';
const LATER = '2026-11-15T16:30:00.000Z';
const LAST = '2026-11-15T18:00:00.000Z';
const complete = (userId: string, id: string) => putTask(userId, id, { completed: true });
describe('PUT /api/tasks/[id]: completing a recurring task (#201)', () => {
it('creates one next occurrence, due one period after the due date, and answers with the task alone', async () => {
const A = await newAccount();
const id = await newTask(A, {
title: 'Water the plants', notes: 'Not the cactus', priority: 2, dueDate: DUE, recurrence: 'weekly',
});
const tag = u();
await h.pg.query('insert into sl_tags (id, user_id, name) values ($1, $2, $3)', [tag, A.userId, 'home']);
await h.pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [id, tag]);
const res = await at(NOW, () => complete(A.userId, id));
expect(res.status).toBe(200);
// The answer keeps its shape: the columns of the task, no next occurrence.
const body = await res.json() as Record<string, unknown>;
expect(Object.keys(body).sort()).toEqual([
'completed', 'completedAt', 'createdAt', 'deletedAt', 'dueDate', 'id', 'listId', 'notes',
'parentId', 'position', 'priority', 'recurrence', 'title', 'updatedAt', 'userId',
]);
expect(body).toMatchObject({ id, completed: true, completedAt: NOW, updatedAt: NOW, dueDate: DUE });
const task = await stored(id);
expect(task).toMatchObject({ completed: true, title: 'Water the plants', recurrence: 'weekly' });
expect(task.completed_at?.toISOString()).toBe(NOW);
expect(task.updated_at.toISOString()).toBe(NOW);
expect(task.due_date?.toISOString()).toBe(DUE);
const created = await occurrences(A, [id]);
expect(created).toHaveLength(1);
const [next] = created;
expect(next).toMatchObject({
user_id: A.userId, title: 'Water the plants', notes: 'Not the cactus', priority: 2, list_id: A.list,
recurrence: 'weekly', completed: false, completed_at: null, parent_id: null, deleted_at: null,
});
// Seven days later at the same UTC time.
expect(next.due_date?.toISOString()).toBe('2026-11-27T14:00:00.000Z');
// The pull of the app (updatedAt >= since) brings it to the phone.
expect(next.updated_at.toISOString()).toBe(NOW);
// The tags stay on the task and are not copied.
expect(await row('select 1 from sl_task_tags where task_id=$1', [next.id])).toBeUndefined();
expect(await row('select count(*)::int c from sl_task_tags where task_id=$1', [id])).toEqual({ c: 1 });
});
it('replayed, creates no second occurrence and writes nothing: completedAt stays', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'daily' });
expect((await at(NOW, () => complete(A.userId, id))).status).toBe(200);
const first = await stored(id);
expect(first.completed_at?.toISOString()).toBe(NOW);
const replay = await at(LATER, () => complete(A.userId, id));
expect(replay.status).toBe(200);
expect(await replay.json()).toMatchObject({ id, completed: true, completedAt: NOW, updatedAt: NOW });
// completedAt and updatedAt as the first request left them.
expect(await stored(id)).toEqual(first);
expect(await occurrences(A, [id])).toHaveLength(1);
});
it('keeps completedAt of a task already done when the body also carries other fields', async () => {
const A = await newAccount();
const done = '2026-11-01T10:00:00.000Z';
const id = await newTask(A, { dueDate: DUE, recurrence: 'daily', completedAt: done });
const res = await at(NOW, () => putTask(A.userId, id, { title: 'Renamed', completed: true }));
expect(res.status).toBe(200);
const task = await stored(id);
expect(task.title).toBe('Renamed');
expect(task.updated_at.toISOString()).toBe(NOW);
expect(task.completed_at?.toISOString()).toBe(done);
expect(await occurrences(A, [id])).toEqual([]);
});
it.each([
['a recurring task without a due date', { recurrence: 'daily' }],
['a dated task that does not recur', { dueDate: DUE }],
['the unknown recurrence "hourly"', { dueDate: DUE, recurrence: 'hourly' }],
['the unknown recurrence "Daily"', { dueDate: DUE, recurrence: 'Daily' }],
] as [string, TaskFields][])('creates nothing for %s', async (_case, fields) => {
const A = await newAccount();
const id = await newTask(A, fields);
const res = await complete(A.userId, id);
expect(res.status).toBe(200);
expect((await stored(id)).completed).toBe(true);
expect(await occurrences(A, [id])).toEqual([]);
});
it('keeps the next occurrence when the task is reopened, and creates another one when it is completed again', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'weekly' });
await at(NOW, () => complete(A.userId, id));
const created = await occurrences(A, [id]);
expect(created).toHaveLength(1);
const res = await at(LATER, () => putTask(A.userId, id, { completed: false }));
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({ id, completed: false, completedAt: null, updatedAt: LATER });
const reopened = await stored(id);
expect(reopened.completed).toBe(false);
expect(reopened.completed_at).toBeNull();
expect(reopened.updated_at.toISOString()).toBe(LATER);
// The occurrence is kept as it was: nothing links the two tasks.
expect(await occurrences(A, [id])).toEqual(created);
// Reopening an open task writes nothing.
expect((await at(LAST, () => putTask(A.userId, id, { completed: false }))).status).toBe(200);
expect(await stored(id)).toEqual(reopened);
// Completed again: each completion creates its occurrence, as in the app.
expect((await at(LAST, () => complete(A.userId, id))).status).toBe(200);
const all = await occurrences(A, [id]);
expect(all).toHaveLength(2);
expect(all.map((task) => task.due_date?.toISOString())).toEqual(Array(2).fill('2026-11-27T14:00:00.000Z'));
});
it('counts from the due date of an overdue task, not from the day it is completed', async () => {
const A = await newAccount();
// Thirteen days late when it is completed.
const id = await newTask(A, { dueDate: '2026-11-02T12:00:00.000Z', recurrence: 'daily' });
expect((await at(NOW, () => complete(A.userId, id))).status).toBe(200);
const [next] = await occurrences(A, [id]);
expect(next.due_date?.toISOString()).toBe('2026-11-03T12:00:00.000Z');
});
it('puts the next occurrence at the end of the list', async () => {
const A = await newAccount();
const B = await newAccount();
const otherList = u();
await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [otherList, A.userId, 'Other']);
const id = await newTask(A, { dueDate: DUE, recurrence: 'daily', position: 3 });
const seeded = [
id,
await newTask(A, { position: 5 }),
// A done task counts: the list is read whole, as the app does.
await newTask(A, { position: 7, completedAt: '2026-11-01T10:00:00.000Z' }),
// A subtask, a deleted task and a task of another list do not.
await newTask(A, { position: 40, parentId: id }),
await newTask(A, { position: 50, deletedAt: '2026-11-01T10:00:00.000Z' }),
await newTask(A, { position: 60, list: otherList }),
];
// Nor would a task of another account, were one in the list.
await newTask(B, { position: 70, list: A.list });
expect((await complete(A.userId, id)).status).toBe(200);
const [next] = await occurrences(A, seeded);
expect(next.position).toBe(8);
expect(next.list_id).toBe(A.list);
});
it('gives position 1 to the next occurrence of the only task of a list', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'daily' });
expect((await complete(A.userId, id)).status).toBe(200);
const [next] = await occurrences(A, [id]);
expect(next.position).toBe(1);
});
it('gives the next occurrence of a recurring subtask no parent', async () => {
const A = await newAccount();
const parent = await newTask(A, { position: 4 });
const sub = await newTask(A, { parentId: parent, dueDate: DUE, recurrence: 'monthly', position: 9 });
expect((await complete(A.userId, sub)).status).toBe(200);
const created = await occurrences(A, [parent, sub]);
expect(created).toHaveLength(1);
const [next] = created;
expect(next.parent_id).toBeNull();
expect(next.list_id).toBe(A.list);
// After the top-level tasks: the position of the subtask does not count.
expect(next.position).toBe(5);
expect(next.due_date?.toISOString()).toBe('2026-12-20T14:00:00.000Z');
});
it('completes the task as the body leaves it: the other fields are written first', async () => {
const A = await newAccount();
const id = await newTask(A, { title: 'Rent', dueDate: DUE });
const res = await at(NOW, () => putTask(A.userId, id, {
title: 'Pay the rent', dueDate: '2027-01-31', recurrence: 'monthly', completed: true,
}));
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
id, title: 'Pay the rent', dueDate: '2027-01-31T12:00:00.000Z', recurrence: 'monthly',
completed: true, completedAt: NOW,
});
const created = await occurrences(A, [id]);
expect(created).toHaveLength(1);
expect(created[0]).toMatchObject({ title: 'Pay the rent', recurrence: 'monthly', completed: false });
// January 31 plus a month: the last day of February.
expect(created[0].due_date?.toISOString()).toBe('2027-02-28T12:00:00.000Z');
});
it('completes a task whose next occurrence would fall after the year 9999, without creating it', async () => {
const A = await newAccount();
// The last occurrence that can be written, then the first that cannot.
const inside = await newTask(A, { dueDate: '9999-12-30T12:00:00.000Z', recurrence: 'daily' });
const outside = await newTask(A, { dueDate: '9999-12-31T12:00:00.000Z', recurrence: 'daily' });
expect((await complete(A.userId, inside)).status).toBe(200);
const created = await occurrences(A, [inside, outside]);
expect(created.map((task) => task.due_date?.toISOString())).toEqual(['9999-12-31T12:00:00.000Z']);
expect((await complete(A.userId, outside)).status).toBe(200);
expect((await stored(outside)).completed).toBe(true);
expect(await occurrences(A, [inside, outside])).toEqual(created);
});
it('notifies the account once, after the commit', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'daily' });
expect((await complete(A.userId, id)).status).toBe(200);
expect(notices(A.userId)).toEqual([true]);
// And once more for a body without `completed`.
expect((await putTask(A.userId, id, { title: 'Renamed' })).status).toBe(200);
expect(notices(A.userId)).toEqual([true, true]);
});
});
describe('PUT /api/tasks/[id]: refusals of a body that carries completed (#201)', () => {
const NOT_FOUND = { error: 'Not found' };
it('answers 404 for a deleted task and writes nothing, not even the other fields', async () => {
const A = await newAccount();
const open = await newTask(A, { dueDate: DUE, recurrence: 'daily', deletedAt: '2026-11-10T09:00:00.000Z' });
const done = await newTask(A, {
dueDate: DUE, recurrence: 'daily', completedAt: '2026-11-01T10:00:00.000Z', deletedAt: '2026-11-10T09:00:00.000Z',
});
const before = [await stored(open), await stored(done)];
for (const id of [open, done]) {
for (const body of [
{ completed: true }, { completed: false },
{ title: 'Renamed', completed: true }, { title: 'Renamed', completed: false },
]) {
const res = await putTask(A.userId, id, body);
expect(res.status, JSON.stringify(body)).toBe(404);
expect(await res.json()).toEqual(NOT_FOUND);
}
}
expect([await stored(open), await stored(done)]).toEqual(before);
expect(await occurrences(A, [open, done])).toEqual([]);
expect(notices(A.userId)).toEqual([]);
});
it('still writes the other fields of a deleted task when the body has no completed, as before #201', async () => {
const A = await newAccount();
const id = await newTask(A, { deletedAt: '2026-11-10T09:00:00.000Z' });
const res = await putTask(A.userId, id, { title: 'Renamed' });
expect(res.status).toBe(200);
expect((await stored(id)).title).toBe('Renamed');
});
it('answers 404 for a task of another account, open or done, and leaves it untouched', async () => {
const A = await newAccount();
const B = await newAccount();
const open = await newTask(B, { dueDate: DUE, recurrence: 'daily' });
const done = await newTask(B, { dueDate: DUE, recurrence: 'daily', completedAt: '2026-11-01T10:00:00.000Z' });
const before = [await stored(open), await stored(done)];
for (const id of [open, done]) {
for (const body of [{ completed: true }, { completed: false }, { title: 'Stolen', completed: true }]) {
const res = await putTask(A.userId, id, body);
expect(res.status, JSON.stringify(body)).toBe(404);
// Never the task of the other account in the answer.
expect(await res.json()).toEqual(NOT_FOUND);
}
}
expect([await stored(open), await stored(done)]).toEqual(before);
expect(await taskCount(A.userId)).toBe(0);
expect(await occurrences(B, [open, done])).toEqual([]);
expect(notices(A.userId)).toEqual([]);
expect(notices(B.userId)).toEqual([]);
});
it('answers 404 for an id that does not exist', async () => {
const A = await newAccount();
for (const completed of [true, false]) {
const res = await putTask(A.userId, u(), { completed });
expect(res.status).toBe(404);
expect(await res.json()).toEqual(NOT_FOUND);
}
expect(await taskCount(A.userId)).toBe(0);
expect(notices(A.userId)).toEqual([]);
});
});
// The contract #203 and #204 build on: the functions run in the transaction
// of their caller and say what they did.
describe('taskWrites: completeTask and reopenTask (#201)', () => {
const now = new Date(NOW);
it('completeTask returns the task and the next occurrence it created', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'weekly' });
const result = await db.transaction((tx) => completeTask(tx, A.userId, id, now));
const [next] = await occurrences(A, [id]);
expect(result).toMatchObject({
changed: true,
task: { id, userId: A.userId, completed: true, completedAt: now, updatedAt: now },
next: {
id: next.id, userId: A.userId, completed: false, completedAt: null, parentId: null,
dueDate: new Date('2026-11-27T14:00:00.000Z'), createdAt: now, updatedAt: now,
},
});
});
it('completeTask returns next: null for a task that has no next occurrence', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE });
const result = await db.transaction((tx) => completeTask(tx, A.userId, id, now));
expect(result).toMatchObject({ changed: true, task: { id, completed: true }, next: null });
});
it('completeTask returns changed: false, and no next, for a task already done', async () => {
const A = await newAccount();
const done = '2026-11-01T10:00:00.000Z';
const id = await newTask(A, { dueDate: DUE, recurrence: 'weekly', completedAt: done });
const result = await db.transaction((tx) => completeTask(tx, A.userId, id, now));
expect(result).toMatchObject({ changed: false, task: { id, completed: true, completedAt: new Date(done) } });
expect(result).not.toHaveProperty('next');
});
it('reopenTask returns changed: true, then changed: false for a task already open', async () => {
const A = await newAccount();
const id = await newTask(A, { completedAt: '2026-11-01T10:00:00.000Z' });
expect(await db.transaction((tx) => reopenTask(tx, A.userId, id, now)))
.toMatchObject({ changed: true, task: { id, completed: false, completedAt: null, updatedAt: now } });
const again = await db.transaction((tx) => reopenTask(tx, A.userId, id, new Date(LATER)));
expect(again).toMatchObject({ changed: false, task: { id, completed: false, completedAt: null, updatedAt: now } });
});
it('both return null for a task that is deleted, unknown or of another account', async () => {
const A = await newAccount();
const B = await newAccount();
const ids = [
await newTask(A, { deletedAt: '2026-11-10T09:00:00.000Z' }),
await newTask(A, { completedAt: '2026-11-01T10:00:00.000Z', deletedAt: '2026-11-10T09:00:00.000Z' }),
await newTask(B),
await newTask(B, { completedAt: '2026-11-01T10:00:00.000Z' }),
u(),
];
for (const id of ids) {
expect(await db.transaction((tx) => completeTask(tx, A.userId, id, now)), id).toBeNull();
expect(await db.transaction((tx) => reopenTask(tx, A.userId, id, now)), id).toBeNull();
}
});
it('write in the transaction they receive: a rollback of the caller undoes the completion and the occurrence', async () => {
const A = await newAccount();
const id = await newTask(A, { dueDate: DUE, recurrence: 'weekly' });
const before = await stored(id);
await expect(db.transaction(async (tx) => {
const result = await completeTask(tx, A.userId, id, now);
expect(result).toMatchObject({ changed: true, next: { completed: false } });
// What a refused journal line would do in an MCP tool (#203).
throw new Error('journal line refused');
})).rejects.toThrow('journal line refused');
expect(await stored(id)).toEqual(before);
expect(await occurrences(A, [id])).toEqual([]);
});
it('taskWrites.ts neither imports the database client, nor opens a transaction, nor notifies', () => {
const source = fs.readFileSync(path.join(__dirname, '../../../lib/taskWrites.ts'), 'utf8');
expect(source).toMatch(/^export async function completeTask\(/m);
expect(source).not.toMatch(/db\/client|\bdb\.transaction\b|notifyUserChanged/);
});
});

View file

@ -0,0 +1,95 @@
import { afterEach, describe, it, expect } from 'vitest';
import { RECURRENCES, isRecurrence, nextOccurrence, type Recurrence } from './recurrence';
// Next occurrence of a recurring task (#201): a day, seven days, a month or a
// year later at the same UTC time, ends of months as date-fns. The parity with
// the app's own code is in src/test/sync/recurrence.test.ts.
const next = (due: string, recurrence: Recurrence) => nextOccurrence(new Date(due), recurrence).toISOString();
// [due date, recurrence, next occurrence]
const CASES: [string, Recurrence, string][] = [
// January 31: the last day of February, 28 days in 2027 and 29 in 2028.
['2027-01-31T12:00:00.000Z', 'monthly', '2027-02-28T12:00:00.000Z'],
['2028-01-31T12:00:00.000Z', 'monthly', '2028-02-29T12:00:00.000Z'],
['2027-01-30T12:00:00.000Z', 'monthly', '2027-02-28T12:00:00.000Z'],
['2027-01-28T12:00:00.000Z', 'monthly', '2027-02-28T12:00:00.000Z'],
['2027-01-31T12:00:00.000Z', 'daily', '2027-02-01T12:00:00.000Z'],
['2027-01-31T12:00:00.000Z', 'weekly', '2027-02-07T12:00:00.000Z'],
['2027-01-31T12:00:00.000Z', 'yearly', '2028-01-31T12:00:00.000Z'],
// The last day of a month is not kept from one month to the next.
['2027-02-28T12:00:00.000Z', 'monthly', '2027-03-28T12:00:00.000Z'],
['2027-03-31T12:00:00.000Z', 'monthly', '2027-04-30T12:00:00.000Z'],
// February 29: February 28 a year later, and no February 29 from a February 28.
['2028-02-29T12:00:00.000Z', 'yearly', '2029-02-28T12:00:00.000Z'],
['2028-02-29T12:00:00.000Z', 'monthly', '2028-03-29T12:00:00.000Z'],
['2028-02-29T12:00:00.000Z', 'weekly', '2028-03-07T12:00:00.000Z'],
['2028-02-29T12:00:00.000Z', 'daily', '2028-03-01T12:00:00.000Z'],
['2027-02-28T12:00:00.000Z', 'yearly', '2028-02-28T12:00:00.000Z'],
['2028-02-28T12:00:00.000Z', 'daily', '2028-02-29T12:00:00.000Z'],
// December 31: into the next year.
['2027-12-31T12:00:00.000Z', 'daily', '2028-01-01T12:00:00.000Z'],
['2027-12-31T12:00:00.000Z', 'weekly', '2028-01-07T12:00:00.000Z'],
['2027-12-31T12:00:00.000Z', 'monthly', '2028-01-31T12:00:00.000Z'],
['2027-12-31T12:00:00.000Z', 'yearly', '2028-12-31T12:00:00.000Z'],
// The UTC time is kept, to the millisecond, across the clock changes of
// Quebec (March 14 and November 7 in 2027): the local time moves by an hour.
['2027-03-13T14:30:15.250Z', 'daily', '2027-03-14T14:30:15.250Z'],
['2027-03-13T14:30:15.250Z', 'weekly', '2027-03-20T14:30:15.250Z'],
['2027-02-20T14:30:15.250Z', 'monthly', '2027-03-20T14:30:15.250Z'],
['2026-11-15T14:30:15.250Z', 'yearly', '2027-11-15T14:30:15.250Z'],
['2027-11-06T13:05:00.000Z', 'daily', '2027-11-07T13:05:00.000Z'],
['2027-11-06T13:05:00.000Z', 'weekly', '2027-11-13T13:05:00.000Z'],
['2027-10-20T13:05:00.000Z', 'monthly', '2027-11-20T13:05:00.000Z'],
// An evening in Quebec (March 30 at 23:00) is the next day in UTC: the day
// of the month is the UTC one, March 31, and April has 30 days.
['2027-03-31T03:00:00.000Z', 'monthly', '2027-04-30T03:00:00.000Z'],
['2027-01-01T00:00:00.000Z', 'daily', '2027-01-02T00:00:00.000Z'],
['2027-12-31T23:59:59.999Z', 'monthly', '2028-01-31T23:59:59.999Z'],
];
describe('nextOccurrence', () => {
// The result must not depend on the time zone of the runtime: one test
// replays the table under several zones.
const zone = process.env.TZ;
afterEach(() => {
if (zone === undefined) delete process.env.TZ;
else process.env.TZ = zone;
});
it.each(CASES)('%s, %s: %s', (due, recurrence, expected) => {
expect(next(due, recurrence)).toBe(expected);
});
it('computes in UTC whatever the time zone of the runtime', () => {
for (const tz of ['America/Toronto', 'UTC', 'Asia/Tokyo', 'Pacific/Pago_Pago']) {
process.env.TZ = tz;
for (const [due, recurrence, expected] of CASES) {
expect(next(due, recurrence), `${tz}, ${due}, ${recurrence}`).toBe(expected);
}
}
});
it('leaves the date it receives untouched', () => {
for (const recurrence of RECURRENCES) {
const due = new Date('2027-01-31T12:00:00.000Z');
nextOccurrence(due, recurrence);
expect(due.toISOString(), recurrence).toBe('2027-01-31T12:00:00.000Z');
}
});
});
describe('isRecurrence', () => {
it('lists the four recurrences of the app', () => {
expect([...RECURRENCES]).toEqual(['daily', 'weekly', 'monthly', 'yearly']);
});
it.each(RECURRENCES)('accepts %s', (recurrence) => {
expect(isRecurrence(recurrence)).toBe(true);
});
it.each(['hourly', 'Daily', 'daily ', '', 'toString', null, undefined, 7])('refuses %j', (value) => {
expect(isRecurrence(value)).toBe(false);
});
});

62
web/src/lib/recurrence.ts Normal file
View file

@ -0,0 +1,62 @@
// Next occurrence of a recurring task, computed by the companion (#201).
//
// The server does not know the user's time zone: it computes in UTC, and the
// next occurrence falls a day, seven days, a month or a year later at the same
// UTC time. The app computes it with date-fns in the local time of the device
// (src/shared/recurrence.ts) and keeps the local time instead. The two differ
// in two cases:
// - across a clock change (in Quebec, the second Sunday of March and the first
// Sunday of November), the local time of a recurrence computed here moves by
// one hour, where the app keeps it. A due date typed without a time is
// stored at noon UTC (dueDate.ts) and stays there: 7:00 in winter, 8:00 in
// summer;
// - the day of the month is read in UTC. A due date set in the evening in
// Quebec (from 19:00 in winter, 20:00 in summer) is already the next day in
// UTC: at the end of a month, a monthly or yearly recurrence computed here
// can then fall a day away from the one the app computes (March 30 at 23:00
// gives April 29 at 23:00 here, April 30 at 23:00 in the app).
//
// Ends of months follow date-fns (addMonths, addYears): the day of the month
// is kept when the target month has it, and the last day of that month is
// taken otherwise. January 31 plus a month is the last day of February,
// February 29 plus a year is February 28.
//
// Under TZ=UTC, date-fns gives the same instants as this module:
// web/src/test/sync/recurrence.test.ts compares the two.
export const RECURRENCES = ['daily', 'weekly', 'monthly', 'yearly'] as const;
export type Recurrence = (typeof RECURRENCES)[number];
// The `recurrence` column is free text (a client of POST /api/sync, or of the
// REST routes, writes what it wants): only these four values recur.
export function isRecurrence(value: unknown): value is Recurrence {
return (RECURRENCES as readonly unknown[]).includes(value);
}
const DAY_MS = 24 * 60 * 60 * 1000;
function addUtcMonths(date: Date, months: number): Date {
const day = date.getUTCDate();
// Day 0 of the month that follows the target month: the last day of the
// target month, at the UTC time of `date`.
const lastDay = new Date(date.getTime());
lastDay.setUTCMonth(date.getUTCMonth() + months + 1, 0);
if (day >= lastDay.getUTCDate()) return lastDay;
const next = new Date(date.getTime());
next.setUTCFullYear(lastDay.getUTCFullYear(), lastDay.getUTCMonth(), day);
return next;
}
export function nextOccurrence(date: Date, recurrence: Recurrence): Date {
switch (recurrence) {
case 'daily':
return new Date(date.getTime() + DAY_MS);
case 'weekly':
return new Date(date.getTime() + 7 * DAY_MS);
case 'monthly':
return addUtcMonths(date, 1);
case 'yearly':
return addUtcMonths(date, 12);
}
}

View file

@ -2,7 +2,9 @@ import { db } from '@/db/client';
import { slTasks, slTaskTags } from '@/db/schema';
import { eq, and, or, isNull, inArray } from 'drizzle-orm';
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
// The transaction a write runs in. Exported for taskWrites.ts (#201), whose
// functions take it as their first argument and never open one themselves.
export type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
// Lock rule for sl_task_tags (#196): every transaction that writes a link for
// a task locks that task's row first, FOR NO KEY UPDATE (the lock its

127
web/src/lib/taskWrites.ts Normal file
View file

@ -0,0 +1,127 @@
import { and, eq, isNull, sql } from 'drizzle-orm';
import { slTasks } from '@/db/schema';
import { isRecurrence, nextOccurrence } from './recurrence';
import type { Tx } from './taskDelete';
// Task writes shared by the site (PUT /api/tasks/[id]) and by the MCP tools
// (#203, #204), so that both paths do the same thing (#201).
//
// Contract of every function of this module:
// - the transaction `tx` is the first argument, then `userId`. The caller
// opens the transaction and may write more in it (the journal line of an
// MCP tool, #203). A function never opens one and never queries outside
// `tx`: from inside an open transaction, a query on the pool leaves on
// another connection in production and waits for its lock on PGlite;
// - no notification: the caller notifies once, after its transaction commits;
// - no import of the database client: `tx` is the only way to the database;
// - every statement filters on `userId`, and a deleted task is not a task;
// - the result is `{ changed, ... }`, or null when the row does not exist, is
// deleted or belongs to another account. `changed: false` means that
// nothing was written.
export type TaskRow = typeof slTasks.$inferSelect;
export type CompleteTaskResult =
// `next` is the occurrence that was created, null when the task has none.
| { changed: true; task: TaskRow; next: TaskRow | null }
// The task was already done.
| { changed: false; task: TaskRow };
export type ReopenTaskResult = { changed: boolean; task: TaskRow };
// PostgreSQL reads the ISO text drizzle sends for a timestamp, and that text
// only holds the years up to 9999 in UTC (see `storable` in dueDate.ts): an
// occurrence past it cannot be written.
const LAST_STORABLE_YEAR = 9999;
// The live task `taskId` of the account.
function ownTask(userId: string, taskId: string) {
return and(eq(slTasks.id, taskId), eq(slTasks.userId, userId), isNull(slTasks.deletedAt));
}
// Complete a task and, for a recurring task with a due date, create its next
// occurrence, as toggleComplete does in the app (src/db/repository/tasks.ts).
//
// The next occurrence takes the title, the notes, the priority, the list and
// the recurrence of the task, without its tags and without a parent (the
// occurrence of a recurring subtask is a top-level task). It is due one period
// after the due date of the task, not after `now`: completing an overdue task
// gives an occurrence that may be overdue too. It goes to the end of the list.
// A recurrence outside RECURRENCES creates nothing, and so does an occurrence
// that would fall after the year 9999.
export async function completeTask(
tx: Tx,
userId: string,
taskId: string,
now = new Date(),
): Promise<CompleteTaskResult | null> {
// The move from open to done is this single statement. Of two calls for the
// same task, replayed or concurrent, only one gets the row back (the second
// waits for the first, then no longer matches `completed = false`): only one
// creates the next occurrence.
const [task] = await tx.update(slTasks)
.set({ completed: true, completedAt: now, updatedAt: now })
.where(and(ownTask(userId, taskId), eq(slTasks.completed, false)))
.returning();
if (!task) {
// Already done, or not a live task of the account.
const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId));
return current ? { changed: false, task: current } : null;
}
const dueDate = task.dueDate && isRecurrence(task.recurrence)
? nextOccurrence(task.dueDate, task.recurrence)
: null;
if (!dueDate || dueDate.getUTCFullYear() > LAST_STORABLE_YEAR) {
return { changed: true, task, next: null };
}
// End of the list, as createTask does in the app: one more than the largest
// position of the live top-level tasks of the list, done or not.
const [{ last }] = await tx
.select({ last: sql<number>`coalesce(max(${slTasks.position}), 0)`.mapWith(Number) })
.from(slTasks)
.where(and(
eq(slTasks.userId, userId),
eq(slTasks.listId, task.listId),
isNull(slTasks.parentId),
isNull(slTasks.deletedAt),
));
const [next] = await tx.insert(slTasks)
.values({
userId,
title: task.title,
notes: task.notes,
priority: task.priority,
dueDate,
listId: task.listId,
recurrence: task.recurrence,
position: last + 1,
createdAt: now,
updatedAt: now,
})
.returning();
return { changed: true, task, next };
}
// Reopen a task: `completed` false, `completedAt` null. The next occurrence
// that completeTask created stays, as in the app: nothing links the two tasks.
export async function reopenTask(
tx: Tx,
userId: string,
taskId: string,
now = new Date(),
): Promise<ReopenTaskResult | null> {
const [task] = await tx.update(slTasks)
.set({ completed: false, completedAt: null, updatedAt: now })
.where(and(ownTask(userId, taskId), eq(slTasks.completed, true)))
.returning();
if (task) return { changed: true, task };
// Already open, or not a live task of the account.
const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId));
return current ? { changed: false, task: current } : null;
}

View file

@ -0,0 +1,117 @@
import { afterEach, describe, it, expect } from 'vitest';
// Parity of the next occurrence (#201): nextOccurrence of the companion
// (web/src/lib/recurrence.ts, UTC, no date-fns) against getNextOccurrence of
// the app (src/shared/recurrence.ts, date-fns, local time of the runtime).
// This file lives in the folder of the sync harness because its config loads
// the app code and date-fns from the root node_modules; it does not use the
// harness itself.
//
// The two only agree when the local time is UTC. Neither web/package.json nor
// the config sets TZ, and the development machine is in America/Toronto: the
// first statement of this file sets it, before any Date and before the app
// code is loaded. vitest runs each test file in its own process (pool
// `forks`), so the assignment takes effect and stays in this file.
process.env.TZ = 'UTC';
const { getNextOccurrence, RECURRENCE_OPTIONS } = await import('@/src/shared/recurrence');
const { RECURRENCES, nextOccurrence } = await import('@/lib/recurrence');
type Recurrence = (typeof RECURRENCES)[number];
const DATES = [
// Ends of months
'2027-01-28T12:00:00.000Z',
'2027-01-29T12:00:00.000Z',
'2027-01-30T12:00:00.000Z',
'2027-01-31T12:00:00.000Z',
'2028-01-31T12:00:00.000Z',
'2027-02-28T12:00:00.000Z',
'2027-03-31T12:00:00.000Z',
'2027-05-31T08:15:30.500Z',
'2027-08-31T00:00:00.000Z',
'2027-10-31T23:59:59.999Z',
'2027-11-30T18:45:00.000Z',
'2027-12-31T12:00:00.000Z',
'2027-12-31T23:59:59.999Z',
// February 29
'2028-02-28T12:00:00.000Z',
'2028-02-29T12:00:00.000Z',
'2028-02-29T00:00:00.000Z',
'2024-02-29T21:10:00.000Z',
// Across the March clock change of Quebec (2027-03-14, 07:00 UTC)
'2027-03-13T12:00:00.000Z',
'2027-03-13T14:30:15.250Z',
'2027-03-14T06:30:00.000Z',
'2027-03-07T12:00:00.000Z',
'2027-02-20T17:00:00.000Z',
'2026-11-15T12:00:00.000Z',
// Across the November clock change of Quebec (2027-11-07, 06:00 UTC)
'2027-11-06T12:00:00.000Z',
'2027-11-06T13:05:00.000Z',
'2027-11-07T05:30:00.000Z',
'2027-10-31T12:00:00.000Z',
'2027-10-20T16:00:00.000Z',
'2027-06-15T12:00:00.000Z',
// Evenings in Quebec, already the next day in UTC
'2026-11-16T04:00:00.123Z',
'2027-03-31T03:00:00.000Z',
'2027-02-01T04:00:00.000Z',
];
describe('time zone of this file', () => {
it('is UTC, whatever the zone of the machine', () => {
// Local noon is noon UTC, in winter and in summer.
expect(new Date(2027, 0, 15, 12).toISOString()).toBe('2027-01-15T12:00:00.000Z');
expect(new Date(2027, 6, 15, 12).toISOString()).toBe('2027-07-15T12:00:00.000Z');
});
});
describe('nextOccurrence of the companion against getNextOccurrence of the app, under TZ=UTC', () => {
it('knows the same recurrences, in the same order', () => {
expect([...RECURRENCES]).toEqual(RECURRENCE_OPTIONS);
});
it.each([...RECURRENCES])('%s: the same instants', (recurrence) => {
const companion = DATES.map((due) => `${due} -> ${nextOccurrence(new Date(due), recurrence).toISOString()}`);
const app = DATES.map((due) => `${due} -> ${getNextOccurrence(new Date(due), recurrence).toISOString()}`);
expect(companion).toEqual(app);
});
});
// What the header of web/src/lib/recurrence.ts says, measured: outside UTC the
// app keeps the local time and the day of the local month, the companion the
// UTC time and the day of the UTC month.
describe('in Quebec (America/Toronto), the companion and the app differ', () => {
// Each test sets the zone of Quebec, then the zone of the file comes back:
// the one its first statement set, read here and not written again, so that
// these tests cannot stand in for that statement.
const zone = process.env.TZ;
afterEach(() => {
if (zone === undefined) delete process.env.TZ;
else process.env.TZ = zone;
});
// [due date, recurrence, next occurrence of the companion, of the app]
const CASES: [string, Recurrence, string, string][] = [
// March 13 at 9:00 (EST), the day before the clocks move forward:
// 10:00 on March 14 for the companion, 9:00 for the app.
['2027-03-13T14:00:00.000Z', 'daily', '2027-03-14T14:00:00.000Z', '2027-03-14T13:00:00.000Z'],
// November 6 at 9:00 (EDT), the day before the clocks move back:
// 8:00 on November 7 for the companion, 9:00 for the app.
['2027-11-06T13:00:00.000Z', 'daily', '2027-11-07T13:00:00.000Z', '2027-11-07T14:00:00.000Z'],
// A due date typed on the site, noon UTC: 7:00 in winter, 8:00 in summer
// for the companion; the app would keep 7:00.
['2027-03-13T12:00:00.000Z', 'weekly', '2027-03-20T12:00:00.000Z', '2027-03-20T11:00:00.000Z'],
// March 30 at 23:00 (EDT), already March 31 in UTC: April 29 at 23:00 for
// the companion, April 30 at 23:00 for the app.
['2027-03-31T03:00:00.000Z', 'monthly', '2027-04-30T03:00:00.000Z', '2027-05-01T03:00:00.000Z'],
];
it.each(CASES)('%s, %s', (due, recurrence, companion, app) => {
process.env.TZ = 'America/Toronto';
expect(nextOccurrence(new Date(due), recurrence).toISOString()).toBe(companion);
expect(getNextOccurrence(new Date(due), recurrence).toISOString()).toBe(app);
});
});