mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 18:54:17 +00:00
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.
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -61,20 +61,18 @@ export class VisitedCountriesRepository extends TrekRepository<VisitedCountries>
|
||||
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<string[]> {
|
||||
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<Pick<VisitedCountryRow, 'country_code' | 'source'>[]> {
|
||||
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 = ?`. */
|
||||
|
||||
@@ -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 } } : {};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<string, AtlasRegionRow[]> }> {
|
||||
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<string, AtlasRegionRow[]> = {};
|
||||
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({
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user