fix(sync): initialMerge sends completedAt and pulls the server state after its push

initialMerge now builds its task data with mergeTaskData (syncRules.ts),
which adds completedAt in ISO when the task has one. After remapping the
local Inbox, it sets lastSyncAt to SYNC_EPOCH and pulls the whole account,
so the merging device receives the other devices' data and the server side
effects of the merge (archived Inbox, moved tasks). A failed pull leaves
lastSyncAt at SYNC_EPOCH and the next fullSync retries it.

Refs #150

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-24 14:27:32 -04:00
commit ef91366266
4 changed files with 68 additions and 15 deletions

View file

@ -111,6 +111,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts`
- Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149
- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une ligne locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`writeOutboxEntry`, action `update`). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149
- Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`)
- Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149
- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, #149
- Après un push ou un pull qui applique des changements, le widget est rafraîchi (`syncWidgetData`). — PR #66, `src/services/syncClient.ts`

View file

@ -15,6 +15,7 @@ import {
listUpdatePayload,
taskUpdatePayload,
tagUpdatePayload,
mergeTaskData,
} from '@/src/services/syncRules';
const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com';
@ -280,7 +281,8 @@ export async function fullSync(): Promise<void> {
/**
* First-time sync: merge all local data to server.
* Creates an Inbox on the server, remaps the local hardcoded Inbox ID,
* then pushes all lists, tasks, tags, and task-tag relations.
* then pushes all lists, tasks, tags, and task-tag relations, and finally
* pulls the whole account from SYNC_EPOCH.
*/
export async function initialMerge(): Promise<void> {
const headers = await getAuthHeaders();
@ -325,23 +327,12 @@ export async function initialMerge(): Promise<void> {
// 4. Push tasks (remap listId if it pointed to the old inbox)
for (const task of allTasks) {
const remappedListId = idMap[task.listId] || task.listId;
const remappedParentId = task.parentId || undefined;
operations.push({
idempotencyKey: randomUUID(),
entityType: 'task',
entityId: task.id,
action: 'create',
data: {
title: task.title,
notes: task.notes,
completed: task.completed,
priority: task.priority,
dueDate: task.dueDate ? task.dueDate.toISOString() : undefined,
listId: remappedListId,
parentId: remappedParentId,
position: task.position,
recurrence: task.recurrence,
},
data: mergeTaskData(task, remappedListId),
});
}
@ -389,8 +380,12 @@ export async function initialMerge(): Promise<void> {
});
}
// 9. Mark sync timestamp
useSettingsStore.getState().setLastSyncAt(new Date().toISOString());
// 9. Pull the whole account: brings down the data of the other devices and
// the server side effects of the merge (archived Inbox, moved tasks).
// lastSyncAt is set to the epoch first, so that a failed pull is replayed
// from the epoch by the next fullSync.
useSettingsStore.getState().setLastSyncAt(SYNC_EPOCH);
await pullChanges(SYNC_EPOCH);
}
/**

View file

@ -157,6 +157,27 @@ export function taskUpdatePayload(task: TaskRow): Payload {
};
}
/**
* Task data pushed by initialMerge (action `create`), with listId taken from
* the caller (the local Inbox is remapped to its server id). dueDate,
* completedAt and parentId are left out when empty: the server dates a
* completed task without completedAt itself (#146).
*/
export function mergeTaskData(task: TaskRow, listId: string): Payload {
return {
title: task.title,
notes: task.notes,
completed: task.completed,
completedAt: toIso(task.completedAt) ?? undefined,
priority: task.priority,
dueDate: toIso(task.dueDate) ?? undefined,
listId,
parentId: task.parentId || undefined,
position: task.position,
recurrence: task.recurrence,
};
}
/** Synced fields of a tag, as pushed by an outbox `update`. */
export function tagUpdatePayload(tag: TagRow): Payload {
return {

View file

@ -18,6 +18,7 @@ import {
listUpdatePayload,
taskUpdatePayload,
tagUpdatePayload,
mergeTaskData,
} from '../src/services/syncRules.ts';
const ID = '11111111-1111-4111-8111-111111111111';
@ -203,3 +204,38 @@ test('tagUpdatePayload returns the synced tag fields', () => {
const tag = pulledTagValues(ID, { name: 'urgent', color: '#E57373', created_at: SERVER_CREATED, updated_at: SERVER_UPDATED });
assert.deepEqual(tagUpdatePayload(tag), { id: ID, name: 'urgent', color: '#E57373' });
});
const MERGE_LIST_ID = '33333333-3333-4333-8333-333333333333';
const roundTrip = (o) => JSON.parse(JSON.stringify(o));
test('mergeTaskData sends completedAt in ISO for a completed task with a date', () => {
const task = pulledTaskValues(ID, taskPayload(), { createdAt: LOCAL_CREATED, calendarEventId: 'cal-42' });
assert.deepEqual(roundTrip(mergeTaskData(task, MERGE_LIST_ID)), {
title: 'Acheter du pain',
notes: 'complet',
completed: true,
completedAt: '2026-10-21T09:00:00.000Z',
priority: 2,
dueDate: '2026-10-25T00:00:00.000Z',
listId: MERGE_LIST_ID,
position: 3,
recurrence: 'weekly',
});
});
test('mergeTaskData leaves out completedAt, dueDate and parentId when empty', () => {
const task = pulledTaskValues(ID, taskPayload({ completed: false, completed_at: null, due_date: null }));
const data = roundTrip(mergeTaskData(task, MERGE_LIST_ID));
assert.equal('completedAt' in data, false);
assert.equal('dueDate' in data, false);
assert.equal('parentId' in data, false);
assert.equal(data.completed, false);
});
test('mergeTaskData takes listId from its parameter and keeps parentId', () => {
const task = pulledTaskValues(ID, taskPayload({ parent_id: LIST_ID }));
const data = mergeTaskData(task, MERGE_LIST_ID);
assert.equal(data.listId, MERGE_LIST_ID);
assert.notEqual(data.listId, task.listId);
assert.equal(data.parentId, LIST_ID);
});