fix(sync): pulled rows keep local-only fields and newer offline edits
Move the construction of pulled rows into a pure, import-free module
(src/services/syncRules.ts) executed by node --test:
- pulled{List,Task,Tag}Values always build the full row; an existing row
keeps its local createdAt, and a task keeps its calendarEventId (the
server has no such column, so the pull used to null it);
- keepLocal: in a whole-account pull (since === SYNC_EPOCH), a local row
strictly newer than the server copy is left untouched and re-queued in
the outbox, so edits made while signed out survive the reconnection;
- server deletions still always apply; task-tag links are unchanged.
fullSync and initialReset use SYNC_EPOCH. REVIEW.md lists syncRules.ts
in the Haut table (Sync zone) with the new rules, and the smoke test
keeps the module import-free.
Refs #149
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d2289806a4
commit
0b8bf144df
7 changed files with 438 additions and 52 deletions
|
|
@ -28,7 +28,7 @@ Motifs : chemins depuis la racine. `*` ne traverse jamais un `/` ; `**/` vaut z
|
|||
|---|---|---|
|
||||
| `src/lib/{authToken,logtoConfig,validation}.ts`, `web/src/lib/{auth,logto,api}.ts`, `web/src/middleware.ts`, `web/src/app/api/logto/**`, `web/src/app/auth/**` | toujours | Authentification |
|
||||
| `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts`, `web/server.ts` | toujours | API et isolation des comptes |
|
||||
| `src/services/syncClient.ts`, `src/db/repository/outbox.ts` | toujours | Sync |
|
||||
| `src/services/{syncClient,syncRules}.ts`, `src/db/repository/outbox.ts` | toujours | Sync |
|
||||
| `src/db/{schema,client}.ts`, `src/db/migrations/**`, `web/src/db/{schema,client,seed}.ts`, `web/src/db/migrations/**`, `drizzle.config.ts`, `web/drizzle.config.ts`, `sql-transformer.js` | toujours | Migrations et données |
|
||||
| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`) | Migrations et données, Authentification, Sync |
|
||||
| `app/(tabs)/settings.tsx` | le diff touche la connexion, l'activation de la sync (`initialMerge`, `initialReset`, `setSyncEnabled`) ou la vérification des mises à jour (`releases/latest`, asset `.apk`) | Sync, Release |
|
||||
|
|
@ -109,6 +109,10 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
|
|||
- `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`
|
||||
- `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`
|
||||
- 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
|
||||
- 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`
|
||||
|
||||
### Migrations et données
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
"version": "1.6.6",
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs",
|
||||
"test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ HIGH_ALWAYS = [
|
|||
"web/src/lib/{auth,logto,api}.ts", "web/src/middleware.ts",
|
||||
"web/src/app/api/logto/**", "web/src/app/auth/**",
|
||||
"web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts", "web/server.ts",
|
||||
"src/services/syncClient.ts", "src/db/repository/outbox.ts",
|
||||
"src/services/{syncClient,syncRules}.ts", "src/db/repository/outbox.ts",
|
||||
"src/db/{schema,client}.ts", "src/db/migrations/**",
|
||||
"web/src/db/{schema,client,seed}.ts", "web/src/db/migrations/**",
|
||||
"drizzle.config.ts", "web/drizzle.config.ts", "sql-transformer.js",
|
||||
|
|
|
|||
|
|
@ -5,6 +5,17 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore';
|
|||
import { getAccessToken } from '@/src/lib/authToken';
|
||||
import { randomUUID } from '@/src/lib/uuid';
|
||||
import { syncWidgetData } from '@/src/services/widgetSync';
|
||||
import { writeOutboxEntry } from '@/src/db/repository/outbox';
|
||||
import {
|
||||
SYNC_EPOCH,
|
||||
keepLocal,
|
||||
pulledListValues,
|
||||
pulledTaskValues,
|
||||
pulledTagValues,
|
||||
listUpdatePayload,
|
||||
taskUpdatePayload,
|
||||
tagUpdatePayload,
|
||||
} from '@/src/services/syncRules';
|
||||
|
||||
const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com';
|
||||
const INBOX_ID = '00000000-0000-0000-0000-000000000001';
|
||||
|
|
@ -124,7 +135,7 @@ export async function pullChanges(since: string): Promise<void> {
|
|||
let appliedChanges = 0;
|
||||
for (const change of data.changes) {
|
||||
try {
|
||||
await applyChange(change);
|
||||
await applyChange(change, since);
|
||||
appliedChanges++;
|
||||
} catch (err) {
|
||||
console.warn(`[sync] failed to apply change for ${change.entity_type}/${change.entity_id}:`, err);
|
||||
|
|
@ -145,18 +156,18 @@ export async function pullChanges(since: string): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
async function applyChange(change: SyncPullChange): Promise<void> {
|
||||
async function applyChange(change: SyncPullChange, since: string): Promise<void> {
|
||||
const { entity_type, action, payload, entity_id } = change;
|
||||
|
||||
switch (entity_type) {
|
||||
case 'list':
|
||||
await applyListChange(entity_id, action, payload);
|
||||
await applyListChange(entity_id, action, payload, since);
|
||||
break;
|
||||
case 'task':
|
||||
await applyTaskChange(entity_id, action, payload);
|
||||
await applyTaskChange(entity_id, action, payload, since);
|
||||
break;
|
||||
case 'tag':
|
||||
await applyTagChange(entity_id, action, payload);
|
||||
await applyTagChange(entity_id, action, payload, since);
|
||||
break;
|
||||
case 'task_tag':
|
||||
await applyTaskTagChange(entity_id, action, payload);
|
||||
|
|
@ -164,80 +175,66 @@ async function applyChange(change: SyncPullChange): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
async function applyListChange(id: string, action: string, payload: Record<string, unknown>) {
|
||||
async function applyListChange(id: string, action: string, payload: Record<string, unknown>, since: string) {
|
||||
if (action === 'delete') {
|
||||
await db.delete(lists).where(eq(lists.id, id));
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = await db.select().from(lists).where(eq(lists.id, id));
|
||||
const values = {
|
||||
id,
|
||||
name: payload.name as string,
|
||||
color: (payload.color as string) ?? null,
|
||||
icon: (payload.icon as string) ?? null,
|
||||
position: (payload.position as number) ?? 0,
|
||||
isInbox: (payload.is_inbox as boolean) ?? false,
|
||||
createdAt: new Date(payload.created_at as string),
|
||||
updatedAt: new Date(payload.updated_at as string),
|
||||
};
|
||||
const [local] = await db.select().from(lists).where(eq(lists.id, id));
|
||||
if (keepLocal(local, payload, since)) {
|
||||
// Newer offline edit: keep it and push it back to the server
|
||||
await writeOutboxEntry('list', id, 'update', listUpdatePayload(local));
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.length > 0) {
|
||||
const values = pulledListValues(id, payload, local);
|
||||
if (local) {
|
||||
await db.update(lists).set(values).where(eq(lists.id, id));
|
||||
} else {
|
||||
await db.insert(lists).values(values);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyTaskChange(id: string, action: string, payload: Record<string, unknown>) {
|
||||
async function applyTaskChange(id: string, action: string, payload: Record<string, unknown>, since: string) {
|
||||
if (action === 'delete') {
|
||||
await db.delete(taskTags).where(eq(taskTags.taskId, id));
|
||||
await db.delete(tasks).where(eq(tasks.id, id));
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = await db.select().from(tasks).where(eq(tasks.id, id));
|
||||
const values = {
|
||||
id,
|
||||
title: payload.title as string,
|
||||
notes: (payload.notes as string) ?? null,
|
||||
completed: (payload.completed as boolean) ?? false,
|
||||
completedAt: payload.completed_at ? new Date(payload.completed_at as string) : null,
|
||||
priority: (payload.priority as number) ?? 0,
|
||||
dueDate: payload.due_date ? new Date(payload.due_date as string) : null,
|
||||
listId: payload.list_id as string,
|
||||
parentId: (payload.parent_id as string) ?? null,
|
||||
position: (payload.position as number) ?? 0,
|
||||
recurrence: (payload.recurrence as string) ?? null,
|
||||
calendarEventId: (payload.calendar_event_id as string) ?? null,
|
||||
createdAt: new Date(payload.created_at as string),
|
||||
updatedAt: new Date(payload.updated_at as string),
|
||||
};
|
||||
const [local] = await db.select().from(tasks).where(eq(tasks.id, id));
|
||||
if (keepLocal(local, payload, since)) {
|
||||
// Newer offline edit: keep it and push it back to the server
|
||||
await writeOutboxEntry('task', id, 'update', taskUpdatePayload(local));
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Keeps the local createdAt and calendarEventId (absent from the server)
|
||||
const values = pulledTaskValues(id, payload, local);
|
||||
if (local) {
|
||||
await db.update(tasks).set(values).where(eq(tasks.id, id));
|
||||
} else {
|
||||
await db.insert(tasks).values(values);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyTagChange(id: string, action: string, payload: Record<string, unknown>) {
|
||||
async function applyTagChange(id: string, action: string, payload: Record<string, unknown>, since: string) {
|
||||
if (action === 'delete') {
|
||||
await db.delete(taskTags).where(eq(taskTags.tagId, id));
|
||||
await db.delete(tags).where(eq(tags.id, id));
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = await db.select().from(tags).where(eq(tags.id, id));
|
||||
const values = {
|
||||
id,
|
||||
name: payload.name as string,
|
||||
color: (payload.color as string) ?? '#4A90A4',
|
||||
createdAt: new Date(payload.created_at as string),
|
||||
updatedAt: payload.updated_at ? new Date(payload.updated_at as string) : null,
|
||||
};
|
||||
const [local] = await db.select().from(tags).where(eq(tags.id, id));
|
||||
if (keepLocal(local, payload, since)) {
|
||||
// Newer offline edit: keep it and push it back to the server
|
||||
await writeOutboxEntry('tag', id, 'update', tagUpdatePayload(local));
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.length > 0) {
|
||||
const values = pulledTagValues(id, payload, local);
|
||||
if (local) {
|
||||
await db.update(tags).set(values).where(eq(tags.id, id));
|
||||
} else {
|
||||
await db.insert(tags).values(values);
|
||||
|
|
@ -273,7 +270,7 @@ export async function fullSync(): Promise<void> {
|
|||
try {
|
||||
await pushChanges();
|
||||
|
||||
const since = useSettingsStore.getState().lastSyncAt ?? '1970-01-01T00:00:00.000Z';
|
||||
const since = useSettingsStore.getState().lastSyncAt ?? SYNC_EPOCH;
|
||||
await pullChanges(since);
|
||||
} catch (err) {
|
||||
console.warn('[sync] fullSync error:', err);
|
||||
|
|
@ -411,7 +408,7 @@ export async function initialReset(): Promise<void> {
|
|||
await db.delete(syncOutbox);
|
||||
|
||||
// 2. Pull everything from server
|
||||
await pullChanges('1970-01-01T00:00:00.000Z');
|
||||
await pullChanges(SYNC_EPOCH);
|
||||
|
||||
// 3. Ensure we have a local inbox (the server may have created one)
|
||||
const serverLists = await db.select().from(lists);
|
||||
|
|
|
|||
167
src/services/syncRules.ts
Normal file
167
src/services/syncRules.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
// Pure rules for applying pulled sync changes to local rows.
|
||||
//
|
||||
// This module MUST stay import-free and use only erasable TypeScript syntax
|
||||
// (no enum, namespace or parameter properties): tests/syncRules.test.mjs loads
|
||||
// it with Node's native type stripping, where the `@/` alias and the
|
||||
// React Native packages are unavailable. The row types below are structural
|
||||
// copies of the Drizzle rows in src/db/schema.ts. The smoke test locks the
|
||||
// zero-import rule.
|
||||
|
||||
/** `since` value of a pull that fetches the whole account (first sync). */
|
||||
export const SYNC_EPOCH = '1970-01-01T00:00:00.000Z';
|
||||
|
||||
type Payload = Record<string, unknown>;
|
||||
|
||||
export interface ListRow {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string | null;
|
||||
icon: string | null;
|
||||
position: number;
|
||||
isInbox: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface TaskRow {
|
||||
id: string;
|
||||
title: string;
|
||||
notes: string | null;
|
||||
completed: boolean;
|
||||
completedAt: Date | null;
|
||||
priority: number;
|
||||
dueDate: Date | null;
|
||||
listId: string;
|
||||
parentId: string | null;
|
||||
position: number;
|
||||
recurrence: string | null;
|
||||
calendarEventId: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface TagRow {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
}
|
||||
|
||||
// Local-only fields a pull must never overwrite on an existing row.
|
||||
interface LocalCreated {
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
interface LocalTask extends LocalCreated {
|
||||
calendarEventId: string | null;
|
||||
}
|
||||
|
||||
interface LocalStamped {
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
}
|
||||
|
||||
function toIso(d: Date | null | undefined): string | null {
|
||||
return d ? new Date(d).toISOString() : null;
|
||||
}
|
||||
|
||||
/** Full list row from a pulled payload, keeping the local createdAt. */
|
||||
export function pulledListValues(id: string, payload: Payload, local?: LocalCreated): ListRow {
|
||||
return {
|
||||
id,
|
||||
name: payload.name as string,
|
||||
color: (payload.color as string) ?? null,
|
||||
icon: (payload.icon as string) ?? null,
|
||||
position: (payload.position as number) ?? 0,
|
||||
isInbox: (payload.is_inbox as boolean) ?? false,
|
||||
createdAt: local ? local.createdAt : new Date(payload.created_at as string),
|
||||
updatedAt: new Date(payload.updated_at as string),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Full task row from a pulled payload. createdAt and calendarEventId come
|
||||
* from the local row when there is one: the server has no calendar column,
|
||||
* and its createdAt is the time of the first push.
|
||||
*/
|
||||
export function pulledTaskValues(id: string, payload: Payload, local?: LocalTask): TaskRow {
|
||||
return {
|
||||
id,
|
||||
title: payload.title as string,
|
||||
notes: (payload.notes as string) ?? null,
|
||||
completed: (payload.completed as boolean) ?? false,
|
||||
completedAt: payload.completed_at ? new Date(payload.completed_at as string) : null,
|
||||
priority: (payload.priority as number) ?? 0,
|
||||
dueDate: payload.due_date ? new Date(payload.due_date as string) : null,
|
||||
listId: payload.list_id as string,
|
||||
parentId: (payload.parent_id as string) ?? null,
|
||||
position: (payload.position as number) ?? 0,
|
||||
recurrence: (payload.recurrence as string) ?? null,
|
||||
calendarEventId: local ? local.calendarEventId : null,
|
||||
createdAt: local ? local.createdAt : new Date(payload.created_at as string),
|
||||
updatedAt: new Date(payload.updated_at as string),
|
||||
};
|
||||
}
|
||||
|
||||
/** Full tag row from a pulled payload, keeping the local createdAt. */
|
||||
export function pulledTagValues(id: string, payload: Payload, local?: LocalCreated): TagRow {
|
||||
return {
|
||||
id,
|
||||
name: payload.name as string,
|
||||
color: (payload.color as string) ?? '#4A90A4',
|
||||
createdAt: local ? local.createdAt : new Date(payload.created_at as string),
|
||||
updatedAt: payload.updated_at ? new Date(payload.updated_at as string) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a pulled update must leave the local row untouched: only in a
|
||||
* whole-account pull (since === SYNC_EPOCH, after sign-out or on first sync),
|
||||
* when the local row was changed strictly after the server copy. Offline
|
||||
* edits are not in the outbox, so the caller re-queues the local row.
|
||||
* A tag without updatedAt is compared by its createdAt.
|
||||
*/
|
||||
export function keepLocal(local: LocalStamped | null | undefined, payload: Payload, since: string): boolean {
|
||||
if (since !== SYNC_EPOCH || !local) return false;
|
||||
const localTime = new Date(local.updatedAt ?? local.createdAt).getTime();
|
||||
const serverTime = new Date(payload.updated_at as string).getTime();
|
||||
return localTime > serverTime;
|
||||
}
|
||||
|
||||
/** Synced fields of a list, as pushed by an outbox `update`. */
|
||||
export function listUpdatePayload(list: ListRow): Payload {
|
||||
return {
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
color: list.color,
|
||||
icon: list.icon,
|
||||
position: list.position,
|
||||
};
|
||||
}
|
||||
|
||||
/** Synced fields of a task, as pushed by an outbox `update`. */
|
||||
export function taskUpdatePayload(task: TaskRow): Payload {
|
||||
return {
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
notes: task.notes,
|
||||
completed: task.completed,
|
||||
completedAt: toIso(task.completedAt),
|
||||
priority: task.priority,
|
||||
dueDate: toIso(task.dueDate),
|
||||
listId: task.listId,
|
||||
parentId: task.parentId,
|
||||
position: task.position,
|
||||
recurrence: task.recurrence,
|
||||
};
|
||||
}
|
||||
|
||||
/** Synced fields of a tag, as pushed by an outbox `update`. */
|
||||
export function tagUpdatePayload(tag: TagRow): Payload {
|
||||
return {
|
||||
id: tag.id,
|
||||
name: tag.name,
|
||||
color: tag.color,
|
||||
};
|
||||
}
|
||||
|
|
@ -168,6 +168,19 @@ check('feedback.ts stays import-free (protects type-stripping test path)', () =>
|
|||
);
|
||||
});
|
||||
|
||||
// The pull rules of the sync client (src/services/syncRules.ts) are executed
|
||||
// by tests/syncRules.test.mjs through node's type stripping. A bare package
|
||||
// import (drizzle-orm) would still load under node and keep that test green,
|
||||
// so the zero-import rule is locked here.
|
||||
check('syncRules.ts stays import-free (protects type-stripping test path)', () => {
|
||||
const imports = staticImportsOf('src/services/syncRules.ts');
|
||||
assert.deepEqual(
|
||||
imports,
|
||||
[],
|
||||
`syncRules.ts must have zero imports, found: ${imports.join(', ')}`
|
||||
);
|
||||
});
|
||||
|
||||
// --- Build toolchain guards ---
|
||||
// A blanket `npm audit fix` (PR #118) once rewrote hundreds of lock entries:
|
||||
// babel-preset-expo and @expo/metro-config lost their root hoisting and a
|
||||
|
|
|
|||
205
tests/syncRules.test.mjs
Normal file
205
tests/syncRules.test.mjs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
// Execution tests for the pull rules of the sync client. Runs on plain node
|
||||
// via the built-in test runner + native TS type-stripping (Node >= 22.18):
|
||||
//
|
||||
// node --test tests/syncRules.test.mjs
|
||||
//
|
||||
// This EXECUTES the real helpers from src/services/syncRules.ts (kept
|
||||
// import-free so type-stripping can load it). The zero-import guard lives in
|
||||
// smoke.test.cjs.
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
SYNC_EPOCH,
|
||||
pulledListValues,
|
||||
pulledTaskValues,
|
||||
pulledTagValues,
|
||||
keepLocal,
|
||||
listUpdatePayload,
|
||||
taskUpdatePayload,
|
||||
tagUpdatePayload,
|
||||
} from '../src/services/syncRules.ts';
|
||||
|
||||
const ID = '11111111-1111-4111-8111-111111111111';
|
||||
const LIST_ID = '22222222-2222-4222-8222-222222222222';
|
||||
const SERVER_CREATED = '2026-10-20T10:00:00.000Z';
|
||||
const SERVER_UPDATED = '2026-10-22T10:00:00.000Z';
|
||||
const LOCAL_CREATED = new Date('2026-01-05T08:00:00.000Z');
|
||||
const LATER_SINCE = '2026-10-21T00:00:00.000Z';
|
||||
|
||||
const taskPayload = (over = {}) => ({
|
||||
title: 'Acheter du pain',
|
||||
notes: 'complet',
|
||||
completed: true,
|
||||
completed_at: '2026-10-21T09:00:00.000Z',
|
||||
priority: 2,
|
||||
due_date: '2026-10-25T00:00:00.000Z',
|
||||
list_id: LIST_ID,
|
||||
parent_id: null,
|
||||
position: 3,
|
||||
recurrence: 'weekly',
|
||||
created_at: SERVER_CREATED,
|
||||
updated_at: SERVER_UPDATED,
|
||||
...over,
|
||||
});
|
||||
|
||||
test('SYNC_EPOCH is the 1970 ISO literal', () => {
|
||||
assert.equal(SYNC_EPOCH, '1970-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
test('pulledTaskValues keeps createdAt and calendarEventId of an existing row', () => {
|
||||
const v = pulledTaskValues(ID, taskPayload({ calendar_event_id: 'server-cal' }), {
|
||||
createdAt: LOCAL_CREATED,
|
||||
calendarEventId: 'cal-42',
|
||||
});
|
||||
assert.equal(v.createdAt.toISOString(), LOCAL_CREATED.toISOString());
|
||||
assert.equal(v.calendarEventId, 'cal-42');
|
||||
assert.equal(v.updatedAt.toISOString(), SERVER_UPDATED);
|
||||
});
|
||||
|
||||
test('pulledTaskValues without a local row takes the payload createdAt and a null calendarEventId', () => {
|
||||
const v = pulledTaskValues(ID, taskPayload({ calendar_event_id: 'server-cal' }));
|
||||
assert.equal(v.createdAt.toISOString(), SERVER_CREATED);
|
||||
assert.equal(v.calendarEventId, null);
|
||||
});
|
||||
|
||||
test('pulledTaskValues converts the payload like the previous applyTaskChange', () => {
|
||||
const v = pulledTaskValues(ID, taskPayload());
|
||||
assert.deepEqual(v, {
|
||||
id: ID,
|
||||
title: 'Acheter du pain',
|
||||
notes: 'complet',
|
||||
completed: true,
|
||||
completedAt: new Date('2026-10-21T09:00:00.000Z'),
|
||||
priority: 2,
|
||||
dueDate: new Date('2026-10-25T00:00:00.000Z'),
|
||||
listId: LIST_ID,
|
||||
parentId: null,
|
||||
position: 3,
|
||||
recurrence: 'weekly',
|
||||
calendarEventId: null,
|
||||
createdAt: new Date(SERVER_CREATED),
|
||||
updatedAt: new Date(SERVER_UPDATED),
|
||||
});
|
||||
});
|
||||
|
||||
test('pulledTaskValues defaults: null dates, priority 0, position 0, not completed', () => {
|
||||
const v = pulledTaskValues(ID, {
|
||||
title: 't',
|
||||
list_id: LIST_ID,
|
||||
completed_at: null,
|
||||
due_date: null,
|
||||
created_at: SERVER_CREATED,
|
||||
updated_at: SERVER_UPDATED,
|
||||
});
|
||||
assert.equal(v.completedAt, null);
|
||||
assert.equal(v.dueDate, null);
|
||||
assert.equal(v.priority, 0);
|
||||
assert.equal(v.position, 0);
|
||||
assert.equal(v.completed, false);
|
||||
assert.equal(v.notes, null);
|
||||
assert.equal(v.parentId, null);
|
||||
assert.equal(v.recurrence, null);
|
||||
});
|
||||
|
||||
test('pulledListValues keeps the local createdAt and applies the defaults', () => {
|
||||
const payload = { name: 'Courses', created_at: SERVER_CREATED, updated_at: SERVER_UPDATED };
|
||||
const kept = pulledListValues(LIST_ID, payload, { createdAt: LOCAL_CREATED });
|
||||
assert.equal(kept.createdAt.toISOString(), LOCAL_CREATED.toISOString());
|
||||
const fresh = pulledListValues(LIST_ID, payload);
|
||||
assert.deepEqual(fresh, {
|
||||
id: LIST_ID,
|
||||
name: 'Courses',
|
||||
color: null,
|
||||
icon: null,
|
||||
position: 0,
|
||||
isInbox: false,
|
||||
createdAt: new Date(SERVER_CREATED),
|
||||
updatedAt: new Date(SERVER_UPDATED),
|
||||
});
|
||||
const inbox = pulledListValues(LIST_ID, { ...payload, is_inbox: true, position: 4, color: '#C17767', icon: 'inbox' });
|
||||
assert.equal(inbox.isInbox, true);
|
||||
assert.equal(inbox.position, 4);
|
||||
assert.equal(inbox.color, '#C17767');
|
||||
assert.equal(inbox.icon, 'inbox');
|
||||
});
|
||||
|
||||
test('pulledTagValues keeps the local createdAt and defaults the color to #4A90A4', () => {
|
||||
const payload = { name: 'urgent', created_at: SERVER_CREATED, updated_at: SERVER_UPDATED };
|
||||
const kept = pulledTagValues(ID, payload, { createdAt: LOCAL_CREATED });
|
||||
assert.equal(kept.createdAt.toISOString(), LOCAL_CREATED.toISOString());
|
||||
assert.equal(kept.color, '#4A90A4');
|
||||
const fresh = pulledTagValues(ID, payload);
|
||||
assert.equal(fresh.createdAt.toISOString(), SERVER_CREATED);
|
||||
assert.equal(fresh.updatedAt.toISOString(), SERVER_UPDATED);
|
||||
assert.equal(pulledTagValues(ID, { ...payload, color: '#8BA889' }).color, '#8BA889');
|
||||
assert.equal(pulledTagValues(ID, { name: 'x', created_at: SERVER_CREATED }).updatedAt, null);
|
||||
});
|
||||
|
||||
test('keepLocal is true only from SYNC_EPOCH with a strictly newer local row', () => {
|
||||
const payload = { updated_at: SERVER_UPDATED };
|
||||
const newer = { createdAt: LOCAL_CREATED, updatedAt: new Date('2026-10-23T10:00:00.000Z') };
|
||||
const equal = { createdAt: LOCAL_CREATED, updatedAt: new Date(SERVER_UPDATED) };
|
||||
const older = { createdAt: LOCAL_CREATED, updatedAt: new Date('2026-10-21T10:00:00.000Z') };
|
||||
assert.equal(keepLocal(newer, payload, SYNC_EPOCH), true);
|
||||
assert.equal(keepLocal(equal, payload, SYNC_EPOCH), false, 'equal timestamps: the server wins');
|
||||
assert.equal(keepLocal(older, payload, SYNC_EPOCH), false);
|
||||
assert.equal(keepLocal(undefined, payload, SYNC_EPOCH), false);
|
||||
assert.equal(keepLocal(newer, payload, LATER_SINCE), false, 'incremental pull: the server wins');
|
||||
});
|
||||
|
||||
test('keepLocal compares a tag without updatedAt by its createdAt', () => {
|
||||
const payload = { updated_at: SERVER_UPDATED };
|
||||
assert.equal(
|
||||
keepLocal({ createdAt: new Date('2026-10-23T10:00:00.000Z'), updatedAt: null }, payload, SYNC_EPOCH),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
keepLocal({ createdAt: new Date('2026-10-21T10:00:00.000Z'), updatedAt: null }, payload, SYNC_EPOCH),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('listUpdatePayload returns the synced list fields', () => {
|
||||
const list = pulledListValues(LIST_ID, {
|
||||
name: 'Courses',
|
||||
color: '#4A90A4',
|
||||
icon: 'cart',
|
||||
position: 2,
|
||||
is_inbox: false,
|
||||
created_at: SERVER_CREATED,
|
||||
updated_at: SERVER_UPDATED,
|
||||
});
|
||||
assert.deepEqual(listUpdatePayload(list), {
|
||||
id: LIST_ID,
|
||||
name: 'Courses',
|
||||
color: '#4A90A4',
|
||||
icon: 'cart',
|
||||
position: 2,
|
||||
});
|
||||
});
|
||||
|
||||
test('taskUpdatePayload returns the synced task fields with ISO dates', () => {
|
||||
const task = pulledTaskValues(ID, taskPayload(), { createdAt: LOCAL_CREATED, calendarEventId: 'cal-42' });
|
||||
assert.deepEqual(taskUpdatePayload(task), {
|
||||
id: 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: LIST_ID,
|
||||
parentId: null,
|
||||
position: 3,
|
||||
recurrence: 'weekly',
|
||||
});
|
||||
const open = taskUpdatePayload({ ...task, completed: false, completedAt: null, dueDate: null });
|
||||
assert.equal(open.completedAt, null);
|
||||
assert.equal(open.dueDate, null);
|
||||
});
|
||||
|
||||
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' });
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue