From e3922b76d8fc5d7ce7781b93dc41fc3a56a9eaff Mon Sep 17 00:00:00 2001 From: Maurice Date: Sun, 6 Dec 2026 17:20:49 +0100 Subject: [PATCH] fix(atlas): reconcile offline country and region changes together Keep country and region reads in step with queued writes and with the mark source held by the server. Reconcile a delete already applied elsewhere before removing it from the account queue. --- client/src/repo/atlasRepo.offline.test.ts | 33 +++- client/src/repo/atlasRepo.ts | 9 +- client/src/sync/atlasSnapshot.test.ts | 66 +++++-- client/src/sync/atlasSnapshot.ts | 185 +++++++++++++----- client/src/sync/userMutationQueue.ts | 10 +- server/scripts/size-baseline.json | 2 +- .../VisitedCountries.repository.ts | 18 +- server/src/nest/atlas/atlas-offline-state.ts | 19 ++ server/src/nest/atlas/atlas.controller.ts | 8 +- server/src/nest/atlas/atlas.service.ts | 56 +++--- server/src/nest/atlas/visit-dates.ts | 11 ++ server/tests/e2e/atlas.e2e.test.ts | 20 ++ .../VisitedCountries.repository.test.ts | 1 + 13 files changed, 328 insertions(+), 110 deletions(-) create mode 100644 server/src/nest/atlas/atlas-offline-state.ts diff --git a/client/src/repo/atlasRepo.offline.test.ts b/client/src/repo/atlasRepo.offline.test.ts index 78056a275..d1b89e4b2 100644 --- a/client/src/repo/atlasRepo.offline.test.ts +++ b/client/src/repo/atlasRepo.offline.test.ts @@ -138,7 +138,7 @@ describe('atlasRepo writes offline', () => { setOnline(true); const regions = await atlasRepo.regions(); - expect(regions.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false }); + expect(regions.PT).toBeUndefined(); expect(regions.ES).toEqual([ { code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }, ]); @@ -194,6 +194,37 @@ describe('atlasRepo writes online', () => { await expect(atlasRepo.addBucketItem({ name: 'Faro' })).resolves.toEqual({ id: 9, name: 'Faro' }); }); + it('FE-REPO-ATLAS-025: a wish removed elsewhere stays gone after the queued delete gets a 404', async () => { + await readOnline(); + setOnline(false); + await atlasRepo.deleteBucketItem(7); + + server.use(http.delete('/api/addons/atlas/bucket-list/7', () => new HttpResponse(null, { status: 404 }))); + setOnline(true); + await mutationQueue.flush(); + setOnline(false); + + expect(await offlineDb.userMutationQueue.count()).toBe(0); + expect(await atlasRepo.bucketList()).toEqual([{ id: 8, name: 'Madeira' }]); + }); + + it('FE-REPO-ATLAS-026: replaying a region removal refreshes a legacy country read with unknown provenance', async () => { + await readOnline(); + setOnline(false); + await atlasRepo.unmarkRegion('PT-11'); + + server.use( + http.delete('/api/addons/atlas/region/PT-11/mark', () => HttpResponse.json({ success: true })), + http.get('/api/addons/atlas/stats', () => HttpResponse.json({ countries: [STATS.countries[1]] })) + ); + setOnline(true); + await mutationQueue.flush(); + setOnline(false); + + expect(await atlasRepo.stats()).toEqual({ countries: [STATS.countries[1]] }); + expect(await atlasRepo.regions()).toEqual({}); + }); + it('FE-REPO-ATLAS-021: online behind an older queued write, a write waits in line', async () => { await readOnline(); setAuthed(false); // the flush stays off, so the line is visible diff --git a/client/src/repo/atlasRepo.ts b/client/src/repo/atlasRepo.ts index 95f1178d4..9db98cadf 100644 --- a/client/src/repo/atlasRepo.ts +++ b/client/src/repo/atlasRepo.ts @@ -127,7 +127,7 @@ async function write(spec: WriteSpec): Promise { headers: { 'X-Idempotency-Key': id }, }); if (account === offlineDb.name) { - await reconcileAtlasWrite({ ...spec, ids: {}, body, createdAt: Date.now() }).catch(() => undefined); + await reconcileAtlasWrite({ ...spec, body }).catch(() => undefined); } return; } catch (err) { @@ -174,12 +174,15 @@ export const atlasRepo = { }, async stats(): Promise { - return readThrough('stats', async () => (await apiClient.get('/addons/atlas/stats')).data as unknown); + return readThrough( + 'stats', + async () => (await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } })).data as unknown + ); }, async regions(): Promise> { return readThrough('regions', async () => { - const res = await apiClient.get('/addons/atlas/regions'); + const res = await apiClient.get('/addons/atlas/regions', { params: { offline: 1 } }); return (res.data?.regions ?? {}) as Record; }); }, diff --git a/client/src/sync/atlasSnapshot.test.ts b/client/src/sync/atlasSnapshot.test.ts index ed2ead864..bade98804 100644 --- a/client/src/sync/atlasSnapshot.test.ts +++ b/client/src/sync/atlasSnapshot.test.ts @@ -45,7 +45,13 @@ const region = (code: string, method: 'POST' | 'DELETE', body: unknown = null) = }); interface Stats { - countries: Array<{ code: string; status?: string; placeCount?: number; tripCount?: number }>; + countries: Array<{ + code: string; + status?: string; + placeCount?: number; + tripCount?: number; + offline?: { directMark: boolean; placeStatus: string | null }; + }>; stats?: Record; continents?: Record; continentsPlanned?: Record; @@ -107,12 +113,16 @@ describe('countries over the stats read', () => { it('FE-ATLAS2-DATA-005: marking a country already visited changes nothing, also one without a status', async () => { await queued(country('PT')); const data = baseStats(); + data.countries[0].offline = { directMark: true, placeStatus: 'visited' }; expect(await withWaitingWrites('stats', data)).toBe(data); await clearAll(); const noStatus: Stats = { countries: [{ code: 'FR' }], stats: { totalCountries: 1 } }; await queued(country('FR')); - expect(await withWaitingWrites('stats', noStatus)).toEqual(noStatus); + expect(await withWaitingWrites('stats', noStatus)).toEqual({ + countries: [{ code: 'FR', offline: { directMark: true, placeStatus: null } }], + stats: { totalCountries: 1 }, + }); }); it('FE-ATLAS2-DATA-006: a read without a countries list is not touched', async () => { @@ -240,6 +250,7 @@ describe('regions', () => { placeCount: 4, status: 'visited', manuallyMarked: true, + placeStatus: 'visited', }); expect(out.PT).toHaveLength(2); }); @@ -261,10 +272,10 @@ describe('regions', () => { expect(await withWaitingWrites('regions', null)).toBeNull(); }); - it('FE-ATLAS2-DATA-021: unmarking a region with places keeps it, only the manual flag goes', async () => { + it('FE-ATLAS2-DATA-021: unmarking hides a region even when it has places', async () => { await queued(region('PT-11', 'DELETE')); const out = (await withWaitingWrites('regions', regions())) as ReturnType; - expect(out.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false, placeCount: 4 }); + expect(out.PT.map((r) => r.code)).toEqual(['PT-13']); }); it('FE-ATLAS2-DATA-022: unmarking a region without places drops it', async () => { @@ -280,11 +291,41 @@ describe('regions', () => { expect(await withWaitingWrites('regions', null)).toBeNull(); }); - it('FE-ATLAS2-DATA-024: a country write or a PUT on a region leaves the regions read alone', async () => { + it('FE-ATLAS2-DATA-024: unmarking a country clears its manual regions but keeps its places', async () => { await queued(country('PT', 'DELETE')); await queued({ ...region('PT-11', 'POST', { country_code: 'PT' }), method: 'PUT' }); const data = regions(); - expect(await withWaitingWrites('regions', data)).toBe(data); + expect(await withWaitingWrites('regions', data)).toEqual({ PT: [data.PT[0]] }); + }); + + it('FE-ATLAS2-DATA-033: a region added offline also marks its country visited', async () => { + await queued(region('JP-13', 'POST', { country_code: 'JP', name: 'Tokyo' })); + + const stats = (await withWaitingWrites('stats', baseStats())) as Stats; + expect(stats.countries.find((c) => c.code === 'JP')).toMatchObject({ + status: 'visited', + offline: { directMark: false, placeStatus: null }, + }); + expect(stats.stats?.totalCountries).toBe(2); + }); + + it('FE-ATLAS2-DATA-034: a country loses its last region in queue order unless it has its own mark', async () => { + await keepAtlasPart('regions', regions()); + await queued(region('PT-11', 'DELETE')); + await queued(region('PT-13', 'DELETE')); + const data = baseStats(); + data.countries[0].offline = { directMark: false, placeStatus: 'planned' }; + + expect(await withWaitingWrites('stats', data)).toMatchObject({ + countries: [ + { code: 'PT', status: 'planned' }, + { code: 'ES', status: 'planned' }, + ], + stats: { totalCountries: 0, totalCountriesPlanned: 2 }, + }); + + data.countries[0].offline.directMark = true; + expect(await withWaitingWrites('stats', data)).toBe(data); }); }); @@ -320,15 +361,12 @@ describe('a write that went through', () => { await keepAtlasPart('flights', { routes: [] }); await keepAtlasPart('bucketList', [{ id: 7 }, { id: 9 }]); - await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 }); + await reconcileAtlasWrite({ ...country('JP'), body: null }); await reconcileAtlasWrite({ resource: ATLAS_RESOURCE.bucket, entity: `${ATLAS_RESOURCE.bucket}:9`, method: 'DELETE', - ids: {}, body: null, - createdAt: 2, - answer: { success: true }, }); const stats = (await keptAtlasPart('stats'))?.data as Stats; @@ -339,10 +377,14 @@ describe('a write that went through', () => { it('FE-ATLAS2-DATA-029: laying the same write in twice changes nothing more', async () => { await keepAtlasPart('regions', {}); - const w = { ...region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }), ids: {}, createdAt: 1 }; + const w = region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }); + await keepAtlasPart('stats', baseStats()); await reconcileAtlasWrite(w); const once = (await keptAtlasPart('regions'))?.data; + const stats = (await keptAtlasPart('stats'))?.data; await reconcileAtlasWrite(w); + expect((await keptAtlasPart('stats'))?.data).toEqual(stats); + expect(stats).toMatchObject({ countries: [{ code: 'PT' }, { code: 'ES', status: 'visited' }] }); expect((await keptAtlasPart('regions'))?.data).toEqual(once); expect(once).toEqual({ ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }], @@ -350,7 +392,7 @@ describe('a write that went through', () => { }); it('FE-ATLAS2-DATA-030: with nothing kept there is nothing to change', async () => { - await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 }); + await reconcileAtlasWrite({ ...country('JP'), body: null }); expect(await offlineDb.atlasSnapshot.count()).toBe(0); }); }); diff --git a/client/src/sync/atlasSnapshot.ts b/client/src/sync/atlasSnapshot.ts index 932944beb..e7f4a0777 100644 --- a/client/src/sync/atlasSnapshot.ts +++ b/client/src/sync/atlasSnapshot.ts @@ -14,7 +14,8 @@ * Every step here is idempotent: a read that raced a replay may already hold * the write, and laying it over once more must change nothing. */ -import { continentForCountry } from '@trek/shared'; +import { continentForCountry, type VisitStatus } from '@trek/shared'; +import { apiClient } from '../api/client'; import { offlineDb, type AtlasSnapshotPart, type UserQueuedMutation } from '../db/offlineDb'; /** The resources of the Atlas writes in the account queue. */ @@ -24,13 +25,7 @@ export const ATLAS_RESOURCE = { bucket: 'atlasBucket', } as const; -/** A write as it is laid over a read: a queued row, or a write that just went through with the server's answer. */ -type AtlasWrite = Pick< - UserQueuedMutation, - 'resource' | 'method' | 'entity' | 'ids' | 'body' | 'tempId' | 'createdAt' -> & { - answer?: unknown; -}; +type AtlasWrite = Pick; type Fields = Record; @@ -51,7 +46,8 @@ function keyOf(w: AtlasWrite): string { interface StatsCountry { code: string; - status?: string; + status?: VisitStatus; + offline?: { directMark: boolean; placeStatus?: VisitStatus | null }; placeCount?: number; tripCount?: number; } @@ -75,49 +71,75 @@ function total(s: StatsShape, key: string, by: number): Record c.code === code); const status = known?.status ?? (known ? 'visited' : null); - if (status === 'visited') return data; + const offline = { directMark: directMark || !!known?.offline?.directMark, placeStatus: placeStatusOf(known) }; + if (status === 'visited') { + // An older read cannot tell what marked the country. A regional mark cannot settle that. + if (!directMark || known?.offline?.directMark) return data; + return { ...s, countries: s.countries.map((c) => (c.code === code ? { ...c, offline } : c)) }; + } + const continent = continentForCountry(code); - const visited: StatsCountry & Fields = { - code, - tripCount: 0, - placeCount: 0, + const visited = { + ...(known ?? { code, tripCount: 0, placeCount: 0 }), firstVisit: null, lastVisit: null, - status: 'visited', + status: 'visited' as const, + offline, }; const next: StatsShape = { ...s, - countries: known - ? s.countries.map((c) => (c.code === code ? { ...c, status: 'visited' } : c)) - : [...s.countries, visited], + countries: known ? s.countries.map((c) => (c.code === code ? visited : c)) : [...s.countries, visited], stats: total(s, 'totalCountries', 1), continents: bump(s.continents, continent, 1), }; + if (status === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', -1) }; if (status !== 'planned') return next; return { ...next, - stats: { ...next.stats, totalCountriesPlanned: Math.max(0, (s.stats?.totalCountriesPlanned ?? 0) - 1) }, + stats: total(next, 'totalCountriesPlanned', -1), continentsPlanned: bump(s.continentsPlanned, continent, -1), }; } -/** The manual mark taken back: a country with no trip and no place in it leaves the map. */ +/** A direct unmark leaves the country painted by its own places, if any. */ function unmarkCountry(data: unknown, code: string): unknown { const s = asStats(data); const known = s?.countries.find((c) => c.code === code); if (!s || !known || (known.status ?? 'visited') !== 'visited') return data; - if ((known.placeCount ?? 0) > 0 || (known.tripCount ?? 0) > 0) return data; - return { + const placeStatus = placeStatusOf(known); + if (placeStatus === undefined) return data; + const continent = continentForCountry(code); + const next: StatsShape = { ...s, - countries: s.countries.filter((c) => c.code !== code), + countries: placeStatus + ? s.countries.map((c) => + c.code === code ? { ...c, status: placeStatus, offline: { directMark: false, placeStatus } } : c + ) + : s.countries.filter((c) => c.code !== code), stats: total(s, 'totalCountries', -1), - continents: bump(s.continents, continentForCountry(code), -1), + continents: bump(s.continents, continent, -1), + }; + if (placeStatus === 'visited') { + return { ...s, countries: next.countries }; + } + if (placeStatus === 'idea') return { ...next, stats: total(next, 'totalCountriesIdea', 1) }; + if (placeStatus !== 'planned') return next; + return { + ...next, + stats: total(next, 'totalCountriesPlanned', 1), + continentsPlanned: bump(s.continentsPlanned, continent, 1), }; } @@ -127,7 +149,9 @@ interface RegionRow { code: string; name: string; placeCount: number; - status?: string; + status?: VisitStatus; + /** The status the region's places give it without the mark. */ + placeStatus?: VisitStatus; /** Marked by hand, the server's own name for it. */ manuallyMarked?: boolean; } @@ -143,32 +167,77 @@ function markRegion(data: unknown, code: string, name: string, countryCode: stri if (!regions) return data; const rows = regions[countryCode] ?? []; const known = rows.find((r) => r.code === code); - if (known?.status === 'visited' && known.manuallyMarked) return data; - const marked: RegionRow = { ...(known ?? { code, name, placeCount: 0 }), status: 'visited', manuallyMarked: true }; + if (known?.status === 'visited' && (known.manuallyMarked || known.placeStatus)) return data; + const placeStatus = known?.placeCount ? (known.placeStatus ?? known.status) : undefined; + const marked: RegionRow = { + ...(known ?? { code, name, placeCount: 0 }), + status: 'visited', + manuallyMarked: true, + ...(placeStatus ? { placeStatus } : {}), + }; return { ...regions, [countryCode]: known ? rows.map((r) => (r.code === code ? marked : r)) : [...rows, marked] }; } +function countryOfRegion(regions: Regions, code: string): string | undefined { + return Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code)); +} + +/** The server hides an explicitly removed region, even if it has places. */ function unmarkRegion(data: unknown, code: string): unknown { const regions = asRegions(data); - const country = regions && Object.keys(regions).find((cc) => (regions[cc] ?? []).some((r) => r.code === code)); - if (!regions || !country) return data; - // A region with places in it stays visited by them; only the manual mark goes. - const rows = regions[country] - .map((r) => (r.code === code ? { ...r, manuallyMarked: false } : r)) - .filter((r) => r.code !== code || r.placeCount > 0); - return { ...regions, [country]: rows }; + if (!regions) return data; + const country = countryOfRegion(regions, code); + if (!country) return data; + const rows = regions[country].filter((r) => r.code !== code); + if (rows.length) return { ...regions, [country]: rows }; + const remaining = { ...regions }; + delete remaining[country]; + return remaining; +} + +function clearCountryRegions(data: unknown, country: string): unknown { + const regions = asRegions(data); + const current = regions?.[country]; + if (!regions || !current) return data; + const withPlaces = current + .filter((r) => r.placeCount > 0) + .map((r) => { + const { placeStatus, ...row } = r; + delete row.manuallyMarked; + return placeStatus ? { ...row, status: placeStatus } : row; + }); + if (withPlaces.length) return { ...regions, [country]: withPlaces }; + const remaining = { ...regions }; + delete remaining[country]; + return remaining; } // ── One write over one read ─────────────────────────────────────────────────── -function applyToStats(data: unknown, w: AtlasWrite): unknown { - if (w.resource !== ATLAS_RESOURCE.country) return data; - if (w.method === 'POST') return markCountry(data, keyOf(w)); - if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w)); - return data; +function lastRegionCountry(data: unknown, w: AtlasWrite): string | undefined { + if (w.resource !== ATLAS_RESOURCE.region || w.method !== 'DELETE') return; + const regions = asRegions(data); + const country = regions && countryOfRegion(regions, keyOf(w)); + if (regions && country && regions[country].length === 1) return country; +} + +function applyToStats(data: unknown, w: AtlasWrite, regions: unknown): unknown { + if (w.resource === ATLAS_RESOURCE.country) { + if (w.method === 'POST') return markCountry(data, keyOf(w), true); + if (w.method === 'DELETE') return unmarkCountry(data, keyOf(w)); + } + if (w.resource === ATLAS_RESOURCE.region && w.method === 'POST') { + const code = text(fields(w.body).country_code); + if (code) return markCountry(data, code, false); + } + const country = lastRegionCountry(regions, w); + if (!country) return data; + const row = asStats(data)?.countries.find((c) => c.code === country); + return row?.offline?.directMark === false ? unmarkCountry(data, country) : data; } function applyToRegions(data: unknown, w: AtlasWrite): unknown { + if (w.resource === ATLAS_RESOURCE.country && w.method === 'DELETE') return clearCountryRegions(data, keyOf(w)); if (w.resource !== ATLAS_RESOURCE.region) return data; const body = fields(w.body); const country = text(body.country_code); @@ -178,10 +247,10 @@ function applyToRegions(data: unknown, w: AtlasWrite): unknown { } /** What one Atlas read reads as once the write is laid over it. */ -function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite): unknown { +function applyAtlasWrite(part: AtlasSnapshotPart, data: unknown, w: AtlasWrite, regions?: unknown): unknown { switch (part) { case 'stats': - return applyToStats(data, w); + return applyToStats(data, w, regions); case 'regions': return applyToRegions(data, w); case 'bucketList': { @@ -205,7 +274,15 @@ async function waitingWrites(): Promise { /** A read with every Atlas write still on its way laid over it, in the order they were made. */ export async function withWaitingWrites(part: AtlasSnapshotPart, data: unknown): Promise { const writes = await waitingWrites(); - return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data); + if (part !== 'stats' || !writes.some((w) => w.resource === ATLAS_RESOURCE.region && w.method === 'DELETE')) { + return writes.reduce((out, w) => applyAtlasWrite(part, out, w), data); + } + let regions = (await keptAtlasPart('regions'))?.data ?? {}; + for (const w of writes) { + data = applyToStats(data, w, regions); + regions = applyToRegions(regions, w); + } + return data; } /** Keep a read's answer as the server gave it. */ @@ -218,13 +295,27 @@ export async function keptAtlasPart(part: AtlasSnapshotPart): Promise<{ data: un return offlineDb.atlasSnapshot.get(part); } -/** A write that went through: its answer is laid into every kept read, so it stays once the device is offline again. */ +/** Apply a write the server accepted to the kept reads. */ export async function reconcileAtlasWrite(w: AtlasWrite): Promise { - await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => { + const account = offlineDb.name; + const needsStats = await offlineDb.transaction('rw', offlineDb.atlasSnapshot, async () => { const rows = await offlineDb.atlasSnapshot.toArray(); + const regions = rows.find((row) => row.part === 'regions')?.data; for (const row of rows) { - const next = applyAtlasWrite(row.part, row.data, w); + const next = applyAtlasWrite(row.part, row.data, w, regions); if (next !== row.data) await offlineDb.atlasSnapshot.put({ part: row.part, data: next }); } + const country = lastRegionCountry(regions, w); + const stats = rows.find((row) => row.part === 'stats')?.data; + const known = country && asStats(stats)?.countries.find((c) => c.code === country); + return !!known && !known.offline; }); + // An old snapshot cannot distinguish a direct mark from a country's last region. + if (!needsStats || account !== offlineDb.name) return; + try { + const { data } = await apiClient.get('/addons/atlas/stats', { params: { offline: 1 } }); + if (account === offlineDb.name) await keepAtlasPart('stats', data); + } catch { + // The mutation already synced. The next online read can refresh this snapshot. + } } diff --git a/client/src/sync/userMutationQueue.ts b/client/src/sync/userMutationQueue.ts index 855f8fd43..9f6bc076d 100644 --- a/client/src/sync/userMutationQueue.ts +++ b/client/src/sync/userMutationQueue.ts @@ -97,6 +97,9 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise { const status = (err as { response?: { status?: number } } | null)?.response?.status; // A delete of something the server no longer has did what it set out to do. if (status === 404 && row.method === 'DELETE') { + const account = offlineDb.name; + if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row); + if (account !== offlineDb.name) return 'stop'; await offlineDb.userMutationQueue.delete(row.id); return 'done'; } @@ -119,6 +122,7 @@ async function settle(row: UserQueuedMutation, err: unknown): Promise { async function replay(row: UserQueuedMutation, idMap: Map): Promise { const ids = resolveIds(row, idMap); if (!ids) return park(row, 'unresolved temp id (dependent create did not sync)'); + const account = offlineDb.name; await offlineDb.userMutationQueue.update(row.id, { status: 'syncing', syncingSince: Date.now() }); try { const response = await apiClient.request({ @@ -127,13 +131,15 @@ async function replay(row: UserQueuedMutation, idMap: Map): Prom data: row.body, headers: { 'X-Idempotency-Key': row.id }, }); + if (account !== offlineDb.name) return 'stop'; const realId = row.tempId === undefined ? undefined : createdId(response.data); if (row.tempId !== undefined && realId !== undefined) await learnId(row.tempId, realId, idMap); - if (row.resource.startsWith('atlas')) await reconcileAtlasWrite({ ...row, ids, answer: response.data }); + if (row.resource.startsWith('atlas')) await reconcileAtlasWrite(row); + if (account !== offlineDb.name) return 'stop'; await offlineDb.userMutationQueue.delete(row.id); return 'done'; } catch (err: unknown) { - return settle(row, err); + return account === offlineDb.name ? settle(row, err) : 'stop'; } } diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index aca2e2c8d..cb58d9fc1 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -5,7 +5,7 @@ "src/db/repositories/Reservations.repository.ts": 1538, "src/db/repositories/Trips.repository.ts": 1101, "src/db/repositories/Users.repository.ts": 1403, - "src/nest/atlas/atlas.service.ts": 1166, + "src/nest/atlas/atlas.service.ts": 1163, "src/nest/auth/auth.service.ts": 1114, "src/nest/budget/budget.service.ts": 1607, "src/nest/collections/collections.service.ts": 1386, diff --git a/server/src/db/repositories/VisitedCountries.repository.ts b/server/src/db/repositories/VisitedCountries.repository.ts index 579c5f1ad..f91798038 100644 --- a/server/src/db/repositories/VisitedCountries.repository.ts +++ b/server/src/db/repositories/VisitedCountries.repository.ts @@ -61,20 +61,18 @@ export class VisitedCountriesRepository extends TrekRepository return rows.map((row) => ({ ...row, source: publicSource(row.source) })); } - /** - * AT5/AT7/AT43 (`stats`'s no-trip early return, `stats`'s manual-country - * merge, `getTravelStats`'s manual-country merge — three identical-text - * call sites) — `SELECT country_code FROM visited_countries WHERE user_id - * = ?`. Returns the bare code list; every one of the three callers only - * ever reads `.country_code` off the legacy row shape. - */ + /** The user's visited codes (AT5/AT7/AT43). */ async listCodesForUser(userId: number): Promise { - const rows = await this.writeDb() + return (await this.listMarksForUser(userId)).map((row) => row.country_code); + } + + /** The offline projection needs the stored source to distinguish a country's own mark. */ + async listMarksForUser(userId: number): Promise[]> { + return this.writeDb() .selectFrom('visited_countries') - .select('country_code') + .select(['country_code', 'source']) .where('user_id', '=', userId) .execute(); - return rows.map((r) => r.country_code); } /** AT8/AT9 (`countryPlaces`'s no-trip early return, `countryPlaces`'s mark lookup — identical text) — `SELECT source FROM visited_countries WHERE user_id = ? AND country_code = ?`. */ diff --git a/server/src/nest/atlas/atlas-offline-state.ts b/server/src/nest/atlas/atlas-offline-state.ts new file mode 100644 index 000000000..e31029a0b --- /dev/null +++ b/server/src/nest/atlas/atlas-offline-state.ts @@ -0,0 +1,19 @@ +import type { VisitStatus } from '@trek/shared'; + +export interface AtlasRegionRow { + code: string; + name: string; + placeCount: number; + status: VisitStatus; + manuallyMarked?: boolean; + placeStatus?: VisitStatus; +} + +/** State the client needs when a mark is removed while offline. */ +export function atlasCountryOfflineState( + include: boolean, + source: string | undefined, + placeStatus: VisitStatus | null, +) { + return include ? { offline: { directMark: source !== undefined && source !== 'region', placeStatus } } : {}; +} diff --git a/server/src/nest/atlas/atlas.controller.ts b/server/src/nest/atlas/atlas.controller.ts index 71afa9156..3628c34a6 100644 --- a/server/src/nest/atlas/atlas.controller.ts +++ b/server/src/nest/atlas/atlas.controller.ts @@ -83,14 +83,14 @@ export class AtlasController { } @Get('stats') - async stats(@CurrentUser() user: User) { - return this.atlas.stats(user.id); + async stats(@CurrentUser() user: User, @Query('offline') offline?: string) { + return offline === '1' ? this.atlas.stats(user.id, true) : this.atlas.stats(user.id); } @Get('regions') @Header('Cache-Control', 'no-cache, no-store') - async regions(@CurrentUser() user: User) { - return this.atlas.visitedRegions(user.id); + async regions(@CurrentUser() user: User, @Query('offline') offline?: string) { + return offline === '1' ? this.atlas.visitedRegions(user.id, true) : this.atlas.visitedRegions(user.id); } /** diff --git a/server/src/nest/atlas/atlas.service.ts b/server/src/nest/atlas/atlas.service.ts index a18819f1f..ca0a2bfe4 100644 --- a/server/src/nest/atlas/atlas.service.ts +++ b/server/src/nest/atlas/atlas.service.ts @@ -37,7 +37,8 @@ import type { RegionInfo } from './atlas-geo'; import { isCountryName } from './known-countries'; import { cityFromAddress } from './city-from-address'; import { transferEndpointIds } from './transfer-endpoints'; -import { countryVisitDates } from './visit-dates'; +import { countryVisitDates, daysBetween } from './visit-dates'; +import { atlasCountryOfflineState, type AtlasRegionRow } from './atlas-offline-state'; import { placeCountryResolver } from './place-countries'; import { haversineKm } from '../common/geo'; import { CountryVisits, latestPerCoordinate } from './atlas-visit-order'; @@ -51,17 +52,6 @@ type CachedRegionRow = LocatedPlace & { country_code: string; region_code: strin /** How many cached rows the #2527 repair checks before it lets other work run. */ const REPAIR_YIELD_EVERY = 200; -/** - * Whole days from `today` to `isoDate`, both `YYYY-MM-DD` in UTC: the legacy - * `CAST(julianday(start_date) - julianday(date('now')) AS INTEGER)` (#2542), - * truncated toward zero the same way. - */ -function daysBetween(today: string, isoDate: string): number { - const from = Date.parse(`${today.slice(0, 10)}T00:00:00Z`); - const to = Date.parse(`${isoDate.slice(0, 10)}T00:00:00Z`); - return Math.trunc((to - from) / 86_400_000); -} - /** * A reservation endpoint plus the two booking columns that decide whether it may * take part in layover pairing at all (see transfer-endpoints.ts). Structurally @@ -327,16 +317,23 @@ export class AtlasService { // ── Stats ───────────────────────────────────────────────────────────────── - async stats(userId: number) { + async stats(userId: number, includeOfflineState = false) { const trips = await this.getUserTrips(userId); const tripIds = trips.map((t) => t.id); if (tripIds.length === 0) { const hiddenOnly = await this.getHiddenCountries(userId); - const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT5 - const countries = manualCountryCodes - .filter((code) => !hiddenOnly.has(code)) - .map((code) => ({ code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null })); + const marks = await this.visitedCountries.listMarksForUser(userId); // AT5 + const countries = marks + .filter((mark) => !hiddenOnly.has(mark.country_code)) + .map((mark) => ({ + code: mark.country_code, + placeCount: 0, + tripCount: 0, + firstVisit: null, + lastVisit: null, + ...atlasCountryOfflineState(includeOfflineState, mark.source, null), + })); return { countries, trips: [], @@ -405,8 +402,9 @@ export class AtlasService { const hidden = await this.getHiddenCountries(userId); // Merge manually marked countries - const manualCountryCodes = await this.visitedCountries.listCodesForUser(userId); // AT7 - for (const code of manualCountryCodes) { + const marks = await this.visitedCountries.listMarksForUser(userId); // AT7 + const markSources = new Map(marks.map((mark) => [mark.country_code, mark.source])); + for (const code of markSources.keys()) { if (hidden.has(code)) continue; const existing = countries.find((c) => c.code === code); if (existing) { @@ -547,7 +545,12 @@ export class AtlasService { const firstYear = tripYears.size > 0 ? Math.min(...tripYears) : null; return { - countries, + countries: includeOfflineState + ? countries.map((c) => ({ + ...c, + ...atlasCountryOfflineState(true, markSources.get(c.code), countrySet.get(c.code)?.status ?? null), + })) + : countries, stats: { totalTrips: trips.length, totalPlaces: footprint.totalPlaces, @@ -747,12 +750,7 @@ export class AtlasService { // ── Visited regions ─────────────────────────────────────────────────────── - async visitedRegions(userId: number): Promise<{ - regions: Record< - string, - { code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[] - >; - }> { + async visitedRegions(userId: number, includeOfflineState = false): Promise<{ regions: Record }> { const trips = await this.getUserTrips(userId); const tripIds = trips.map((t) => t.id); const places = await this.getPlacesForTrips(tripIds); @@ -795,10 +793,7 @@ export class AtlasService { } } - const result: Record< - string, - { code: string; name: string; placeCount: number; status: VisitStatus; manuallyMarked?: boolean }[] - > = {}; + const result: Record = {}; for (const [country, regions] of Object.entries(regionMap)) { result[country] = [...regions.values()]; } @@ -809,6 +804,7 @@ export class AtlasService { if (!result[r.country_code]) result[r.country_code] = []; const existing = result[r.country_code].find((x) => x.code === r.region_code); if (existing) { + if (includeOfflineState) existing.placeStatus = existing.status; existing.status = 'visited'; } else { result[r.country_code].push({ diff --git a/server/src/nest/atlas/visit-dates.ts b/server/src/nest/atlas/visit-dates.ts index 6f6a567b5..8c9d3581b 100644 --- a/server/src/nest/atlas/visit-dates.ts +++ b/server/src/nest/atlas/visit-dates.ts @@ -38,3 +38,14 @@ export function countryVisitDates( } return { firstVisit, lastVisit }; } + +/** + * Whole days from `today` to `isoDate`, both `YYYY-MM-DD` in UTC: the legacy + * `CAST(julianday(start_date) - julianday(date('now')) AS INTEGER)` (#2542), + * truncated toward zero the same way. + */ +export function daysBetween(today: string, isoDate: string): number { + const from = Date.parse(`${today.slice(0, 10)}T00:00:00Z`); + const to = Date.parse(`${isoDate.slice(0, 10)}T00:00:00Z`); + return Math.trunc((to - from) / 86_400_000); +} diff --git a/server/tests/e2e/atlas.e2e.test.ts b/server/tests/e2e/atlas.e2e.test.ts index 3d1640f83..5660055f5 100644 --- a/server/tests/e2e/atlas.e2e.test.ts +++ b/server/tests/e2e/atlas.e2e.test.ts @@ -119,6 +119,26 @@ describe('Atlas e2e (real auth guard + real service + temp SQLite)', () => { await deleteRows(orm, VisitedCountries, { user: userId }); }); + it('returns mark provenance only when requested for offline use', async () => { + await markCountryVisited(orm, userId, 'JP'); + await request(server) + .post('/api/addons/atlas/region/DE-BY/mark') + .set('Cookie', sessionCookie(userId)) + .send({ name: 'Bayern', country_code: 'DE' }) + .expect(200); + + const res = await request(server).get('/api/addons/atlas/stats?offline=1').set('Cookie', sessionCookie(userId)); + expect(res.status).toBe(200); + expect(res.body.countries).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'JP', offline: { directMark: true, placeStatus: null } }), + expect.objectContaining({ code: 'DE', offline: { directMark: false, placeStatus: null } }), + ]), + ); + await deleteRows(orm, VisitedRegions, { user: userId }); + await deleteRows(orm, VisitedCountries, { user: userId }); + }); + it('200 (not 201) on POST country mark, with upper-cased code written to the db', async () => { const res = await request(server).post('/api/addons/atlas/country/de/mark').set('Cookie', sessionCookie(userId)); expect(res.status).toBe(200); diff --git a/server/tests/unit/db/repositories/VisitedCountries.repository.test.ts b/server/tests/unit/db/repositories/VisitedCountries.repository.test.ts index 67d9e33b6..be6ae2604 100644 --- a/server/tests/unit/db/repositories/VisitedCountries.repository.test.ts +++ b/server/tests/unit/db/repositories/VisitedCountries.repository.test.ts @@ -90,6 +90,7 @@ describe('VisitedCountriesRepository: countries that came in through a region (# expect((await findRow(t, VisitedCountries, { user: user.id, country_code: 'NO' }))?.source).toBe('region'); expect(await repo.findSource(user.id, 'NO')).toEqual({ source: 'manual' }); + expect(await repo.listMarksForUser(user.id)).toEqual([{ country_code: 'NO', source: 'region' }]); expect((await repo.listForUser(user.id)).map((r) => r.source)).toEqual(['manual']); expect(await repo.hasOwnMark(user.id, 'NO')).toBe(false); });