mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
chore: move atlas backend to proper DI
Fold the 1612-line services/atlasService.ts into the DI-native AtlasService: the stats aggregation, visited countries/regions with the #1490 tombstone and cascade logic, and the bucket-list CRUD become methods over the injected DatabaseService. The ~750-line pure-geo half — the bundled admin0/admin1 boundary stores with their #1576 streaming builders, the point-in-polygon indexes, Nominatim geocoding with its shared throttle, and every module-scoped cache including the import-time unref'd cleanup interval — moves verbatim to the plain module atlas-geo.ts so the caches stay process-global across the container instance, the bridge instance and test helpers (assetPath re-anchored one directory deeper, the only non-verbatim line). The 10-tool mcp/tools/atlas.ts registrar plus all four atlas resources in mcp/resources.ts move onto the decorator registry as atlas.mcp.ts — the when: atlas-addon gate is parity here (legacy tools and resources both gated; the REST controller deliberately does not). resources.test.ts retires with its last two cases, which move to tools-atlas-expanded.test.ts. The plugin RPC host swaps its 9 atlas imports for the injected AtlasService (23rd constructor dep); a minimal 2-export atlas.bridge.ts serves the one legacy consumer, authService.getTravelStats, and dies when authService migrates. Adopts atlas.dto.ts over the existing shared schemas and clears all three AtlasController entries from body-contract-allow-list.ts: the hand-rolled 'name and country_code are required' 400 becomes the ZodValidationPipe envelope (todo/places trade) while the whitespace-only bucket name keeps its legacy 'Name is required' trim guard. Fixes the verified defects the relocation had faithfully carried, each with a regression test (ATLAS-SVC-031..036 plus two MCP casing cases): the four multi-statement mark/unmark writes now run in db.transaction() (the region cascade nests as a savepoint), the trip-less countryPlaces early return honours manually_marked, the '|| null' bindings that dropped lat/lng 0 and empty-string notes on bucket update become '?? null', the mutating bucket SQL is user-scoped, and the MCP region/country-places tools uppercase their codes to match REST. Quirks deliberately preserved: the detached GET-path place_regions backfill writes, getStats' two divergent return shapes, the import-time cache-cleanup interval, getCountryFromAddress's unvalidated bare 2-letter codes, and the whitespace-only-name silent no-op on bucket update. Tests move with their case IDs: atlasService.test.ts becomes unit/nest/atlas.service.test.ts (pure-geo imports from atlas-geo, DB calls through the constructed service, plus bridge-delegation cases), the atlas e2e converts to the DI-native pattern (real SQL against the full temp-db schema), and the plugin-host path mock becomes a constructor stub.
This commit is contained in:
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* Unit tests for MCP resources (resources.ts).
|
||||
* Tests the remaining legacy-registrar resources via InMemoryTransport + Client
|
||||
* (trek://trips, trek://trips/{tripId} and .../members moved to the
|
||||
* DI-discovered TripsMcp — see tools-trips.test.ts;
|
||||
* trek://trips/{tripId}/budget, .../budget/per-person and
|
||||
* .../budget/settlement moved to the DI-discovered BudgetMcp — see
|
||||
* tools-budget.test.ts and tools-budget-advanced.test.ts;
|
||||
* trek://categories moved to the DI-discovered CategoriesMcp — see
|
||||
* tools-categories.test.ts; trek://trips/{tripId}/todos moved to TodoMcp —
|
||||
* see tools-todos.test.ts; trek://trips/{tripId}/packing and .../packing/bags
|
||||
* moved to PackingMcp — see tools-packing.test.ts;
|
||||
* trek://trips/{tripId}/days/{dayId}/notes moved to DayNotesMcp — see
|
||||
* tools-notes.test.ts; trek://trips/{tripId}/collab-notes moved to CollabMcp —
|
||||
* see tools-notes.test.ts; trek://trips/{tripId}/days and
|
||||
* .../accommodations moved to DaysMcp — see tools-days.test.ts and
|
||||
* tools-days-accommodations.test.ts).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: (placeId: number) => {
|
||||
const place: any = db.prepare(`SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?`).get(placeId);
|
||||
if (!place) return null;
|
||||
const tags = db.prepare(`SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?`).all(placeId);
|
||||
return { ...place, category: place.category_id ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon } : null, tags };
|
||||
},
|
||||
canAccessTrip: (tripId: any, userId: number) =>
|
||||
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
|
||||
isOwner: (tripId: any, userId: number) =>
|
||||
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip, createPlace, addTripMember, createReservation, createCollabNote, createBucketListItem, createVisitedCountry } from '../../helpers/factories';
|
||||
import { createMcpHarness, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
async function withHarness(userId: number, fn: (harness: McpHarness) => Promise<void>) {
|
||||
const harness = await createMcpHarness({ userId, withTools: false, withResources: true });
|
||||
try {
|
||||
await fn(harness);
|
||||
} finally {
|
||||
await harness.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
// trek://trips and trek://trips/{tripId} moved to tools-trips.test.ts: they
|
||||
// now register via the nest-mcp registry inside registerTools (TripsMcp
|
||||
// @Resource/@ResourceTemplate), which this file's withTools: false harness
|
||||
// never attaches.
|
||||
|
||||
// The trek://trips/{tripId}/days resource moved to the DI-discovered
|
||||
// DaysMcp — see tools-days.test.ts.
|
||||
|
||||
// The trek://trips/{tripId}/places resource moved to the DI-discovered
|
||||
// PlacesMcp — its cases live in tools-places.test.ts (the registry attaches
|
||||
// via registerTools, which this withTools:false harness skips).
|
||||
|
||||
// The trek://trips/{tripId}/budget resource moved to the DI-discovered
|
||||
// src/nest/budget/budget.mcp.ts — its cases live in tools-budget.test.ts (the
|
||||
// registry attaches via registerTools, which this withTools:false harness skips).
|
||||
|
||||
// The trek://trips/{tripId}/packing and .../packing/bags resources moved to the
|
||||
// DI-discovered PackingMcp — see tools-packing.test.ts.
|
||||
|
||||
// The trek://trips/{tripId}/reservations resource moved to the DI-discovered
|
||||
// ReservationsMcp — see tools-reservations.test.ts.
|
||||
|
||||
// The trek://trips/{tripId}/days/{dayId}/notes resource moved to the
|
||||
// DI-discovered DayNotesMcp — see tools-notes.test.ts.
|
||||
|
||||
// The trek://trips/{tripId}/accommodations resource moved to the
|
||||
// DI-discovered DaysMcp — see tools-days-accommodations.test.ts.
|
||||
|
||||
// trek://trips/{tripId}/members moved to tools-trips.test.ts (TripsMcp
|
||||
// @ResourceTemplate) for the same reason.
|
||||
|
||||
// trek://trips/{tripId}/collab-notes moved to tools-notes.test.ts: it now
|
||||
// registers via the nest-mcp registry inside registerTools (CollabMcp
|
||||
// @ResourceTemplate), which this file's withTools: false harness never attaches.
|
||||
|
||||
// trek://categories moved to tools-categories.test.ts: it now registers via
|
||||
// the nest-mcp registry inside registerTools (CategoriesMcp @Resource), which
|
||||
// this file's withTools: false harness never attaches.
|
||||
|
||||
describe('Resource: trek://bucket-list', () => {
|
||||
it('returns only the current user\'s bucket list items', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
createBucketListItem(testDb, user.id, { name: 'Tokyo' });
|
||||
createBucketListItem(testDb, other.id, { name: 'Rome' });
|
||||
|
||||
await withHarness(user.id, async (harness) => {
|
||||
const result = await harness.client.readResource({ uri: 'trek://bucket-list' });
|
||||
const items = parseResourceResult(result) as any[];
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].name).toBe('Tokyo');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty array for user with no items', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
await withHarness(user.id, async (harness) => {
|
||||
const result = await harness.client.readResource({ uri: 'trek://bucket-list' });
|
||||
const items = parseResourceResult(result) as any[];
|
||||
expect(items).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resource: trek://visited-countries', () => {
|
||||
it('returns only the current user\'s visited countries', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
createVisitedCountry(testDb, user.id, 'FR');
|
||||
createVisitedCountry(testDb, user.id, 'JP');
|
||||
createVisitedCountry(testDb, other.id, 'DE');
|
||||
|
||||
await withHarness(user.id, async (harness) => {
|
||||
const result = await harness.client.readResource({ uri: 'trek://visited-countries' });
|
||||
const countries = parseResourceResult(result) as any[];
|
||||
expect(countries).toHaveLength(2);
|
||||
const codes = countries.map((c) => c.country_code);
|
||||
expect(codes).toContain('FR');
|
||||
expect(codes).toContain('JP');
|
||||
expect(codes).not.toContain('DE');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty array for user with no visited countries', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
await withHarness(user.id, async (harness) => {
|
||||
const result = await harness.client.readResource({ uri: 'trek://visited-countries' });
|
||||
const countries = parseResourceResult(result) as any[];
|
||||
expect(countries).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,7 @@ vi.mock('../../../src/nest/addons/addons.bridge', () => ({
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { createUser, createBucketListItem, createVisitedCountry } from '../../helpers/factories';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -66,8 +66,11 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>)
|
||||
try { await fn(h); } finally { await h.cleanup(); }
|
||||
}
|
||||
|
||||
// The atlas resources register via the nest-mcp registry inside registerTools
|
||||
// (AtlasMcp @Resource), so the harness must keep tools on for them to attach
|
||||
// (same shape as tools-vacay.test.ts's withResourceHarness).
|
||||
async function withResourceHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
|
||||
const h = await createMcpHarness({ userId, withTools: false, withResources: true });
|
||||
const h = await createMcpHarness({ userId, withResources: true });
|
||||
try { await fn(h); } finally { await h.cleanup(); }
|
||||
}
|
||||
|
||||
@@ -120,6 +123,28 @@ describe('Tool: list_visited_regions', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: mark_region_visited', () => {
|
||||
it('uppercases both codes like REST does (post-fold quirk fix)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'mark_region_visited',
|
||||
arguments: { regionCode: 'jp-13', regionName: 'Tokyo', countryCode: 'jp' },
|
||||
});
|
||||
const data = parseToolResult(result) as any;
|
||||
// Legacy stored 'jp-13'/'jp' verbatim, creating rows REST's uppercased
|
||||
// unmark could never hit; both codes now normalize.
|
||||
expect(data.region.code).toBe('JP-13');
|
||||
expect(data.region.country_code).toBe('JP');
|
||||
const unmark = await h.client.callTool({
|
||||
name: 'unmark_region_visited',
|
||||
arguments: { regionCode: 'jp-13' },
|
||||
});
|
||||
expect(parseToolResult(unmark)).toEqual({ success: true });
|
||||
const row = testDb.prepare('SELECT 1 FROM visited_regions WHERE user_id = ?').get(user.id);
|
||||
expect(row).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('inserts region and returns region object', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
@@ -204,6 +229,22 @@ describe('Tool: get_country_atlas_places', () => {
|
||||
expect(Array.isArray(data.places)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('uppercases the country code like REST does (post-fold quirk fix)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
|
||||
// A trip so countryPlaces reaches the visited_countries lookup pre-quirk-fix too.
|
||||
testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?)').run(user.id, 'Japan');
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'get_country_atlas_places',
|
||||
arguments: { countryCode: 'jp' },
|
||||
});
|
||||
const data = parseToolResult(result) as any;
|
||||
// Legacy passed 'jp' through verbatim and the lookup matched nothing.
|
||||
expect(data.manually_marked).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -314,3 +355,68 @@ describe('Resource: trek://atlas/regions', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Resource: trek://bucket-list (moved from resources.test.ts with the fold —
|
||||
// that suite's withTools:false harness never attaches registry resources)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Resource: trek://bucket-list', () => {
|
||||
it('returns only the current user\'s bucket list items', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
createBucketListItem(testDb, user.id, { name: 'Tokyo' });
|
||||
createBucketListItem(testDb, other.id, { name: 'Rome' });
|
||||
|
||||
await withResourceHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://bucket-list' });
|
||||
const items = parseResourceResult(result) as any[];
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].name).toBe('Tokyo');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty array for user with no items', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
await withResourceHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://bucket-list' });
|
||||
const items = parseResourceResult(result) as any[];
|
||||
expect(items).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Resource: trek://visited-countries (moved from resources.test.ts, same reason)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Resource: trek://visited-countries', () => {
|
||||
it('returns only the current user\'s visited countries', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
createVisitedCountry(testDb, user.id, 'FR');
|
||||
createVisitedCountry(testDb, user.id, 'JP');
|
||||
createVisitedCountry(testDb, other.id, 'DE');
|
||||
|
||||
await withResourceHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://visited-countries' });
|
||||
const countries = parseResourceResult(result) as any[];
|
||||
expect(countries).toHaveLength(2);
|
||||
const codes = countries.map((c) => c.country_code);
|
||||
expect(codes).toContain('FR');
|
||||
expect(codes).toContain('JP');
|
||||
expect(codes).not.toContain('DE');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty array for user with no visited countries', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
await withResourceHarness(user.id, async (h) => {
|
||||
const result = await h.client.readResource({ uri: 'trek://visited-countries' });
|
||||
const countries = parseResourceResult(result) as any[];
|
||||
expect(countries).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,15 +95,13 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', ()
|
||||
});
|
||||
|
||||
describe('region', () => {
|
||||
it('400 when name or country_code is missing', () => {
|
||||
const markRegion = vi.fn();
|
||||
return thrown(() => makeController({ markRegion }).markRegion(user, 'by', undefined, 'DE')).then((r) =>
|
||||
expect(r).toEqual({ status: 400, body: { error: 'name and country_code are required' } }));
|
||||
});
|
||||
// The legacy 'name and country_code are required' 400 is now produced by
|
||||
// the global ZodValidationPipe (atlas.dto.ts / markRegionRequestSchema)
|
||||
// before the handler runs — covered by the e2e suite.
|
||||
|
||||
it('marks a region, upper-casing both codes', () => {
|
||||
const markRegion = vi.fn();
|
||||
expect(makeController({ markRegion }).markRegion(user, 'by', 'Bavaria', 'de')).toEqual({ success: true });
|
||||
expect(makeController({ markRegion }).markRegion(user, 'by', { name: 'Bavaria', country_code: 'de' })).toEqual({ success: true });
|
||||
expect(markRegion).toHaveBeenCalledWith(8, 'BY', 'Bavaria', 'DE');
|
||||
});
|
||||
});
|
||||
|
||||
+189
-70
@@ -1,3 +1,12 @@
|
||||
/**
|
||||
* Unit tests for the DI-native AtlasService and the atlas-geo helper module —
|
||||
* ATLAS-UNIT-001..028 and ATLAS-SVC-001..028 moved 1:1 from the legacy
|
||||
* tests/unit/services/atlasService.test.ts (case IDs preserved), plus
|
||||
* ATLAS-SVC-029/030 pinning the atlas.bridge.ts delegation for the remaining
|
||||
* legacy consumer (authService). Uses a real in-memory SQLite DB so the SQL
|
||||
* logic is exercised faithfully; the pure-geo functions are imported straight
|
||||
* from atlas-geo (their caches are module-scoped there on purpose).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
// ── DB setup (real in-memory SQLite — same pattern as mcp unit tests) ────────
|
||||
@@ -31,7 +40,14 @@ import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createTrip, createReservation } from '../../helpers/factories';
|
||||
import { getStats, getCached, setCache, getCountryFromCoords, getCountryFromAddress, isPointInCountryBox, reverseGeocodeCountry, getRegionGeo, getCountryGeo, getCountryPlaces, getVisitedRegions, markCountryVisited, unmarkCountryVisited, markRegionVisited, unmarkRegionVisited } from '../../../src/services/atlasService';
|
||||
import { getCached, setCache, getCountryFromCoords, getCountryFromAddress, isPointInCountryBox, reverseGeocodeCountry, getRegionGeo, getCountryGeo } from '../../../src/nest/atlas/atlas-geo';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
|
||||
import { getCountryFromCoords as bridgeGetCountryFromCoords, getHiddenCountries as bridgeGetHiddenCountries } from '../../../src/nest/atlas/atlas.bridge';
|
||||
|
||||
// Direct construction over the shared test connection — no TestingModule (repo
|
||||
// convention for DI-native service unit tests).
|
||||
const atlas = new AtlasService(new DatabaseService(testDb));
|
||||
|
||||
function insertReservationEndpoint(
|
||||
db: any,
|
||||
@@ -82,7 +98,7 @@ describe('getStats', () => {
|
||||
// Place with no address and no coordinates → can't resolve country
|
||||
insertPlace(testDb, trip.id, 'Unknown Place', null);
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.mostVisited).toBeNull();
|
||||
expect(stats.countries).toEqual([]);
|
||||
@@ -100,7 +116,7 @@ describe('getStats', () => {
|
||||
}
|
||||
insertPlace(testDb, trip.id, 'Berlin Place', 'Some Street, Berlin, Germany');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.mostVisited).not.toBeNull();
|
||||
expect(stats.mostVisited!.code).toBe('FR');
|
||||
@@ -114,7 +130,7 @@ describe('getStats', () => {
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'AU');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.countries).toHaveLength(2);
|
||||
expect(stats.countries.map((c: { code: string }) => c.code).sort()).toEqual(['AU', 'JP']);
|
||||
@@ -127,7 +143,7 @@ describe('getStats', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Italy Trip' });
|
||||
insertPlace(testDb, trip.id, 'Colosseum', 'Piazza del Colosseo, Rome, Italy');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.mostVisited).not.toBeNull();
|
||||
expect(stats.mostVisited!.code).toBe('IT');
|
||||
@@ -142,7 +158,7 @@ describe('getStats', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'from', 0, 35.6762, 139.6503);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 1, 51.4700, -0.4543);
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
const codes = stats.countries.map((c: { code: string }) => c.code);
|
||||
expect(codes).toContain('JP');
|
||||
@@ -159,7 +175,7 @@ describe('getStats', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'stop', 1, 35.6762, 139.6503);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 2, -33.8688, 151.2093);
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
const codes = stats.countries.map((c: { code: string }) => c.code);
|
||||
expect(codes).toContain('BE');
|
||||
@@ -176,7 +192,7 @@ describe('getStats', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'from', 0, 50.9014, 4.4844);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 1, 36.6749, -4.4991);
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
const codes = stats.countries.map((c: { code: string }) => c.code);
|
||||
expect(codes).toContain('ES');
|
||||
@@ -351,12 +367,12 @@ describe('unmarkCountryVisited — tombstones', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'from', 0, 50.9014, 4.4844);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 1, 35.6762, 139.6503);
|
||||
|
||||
const before = await getStats(user.id);
|
||||
const before = await atlas.stats(user.id);
|
||||
expect(before.countries.map((c: { code: string }) => c.code)).toContain('JP');
|
||||
|
||||
unmarkCountryVisited(user.id, 'JP');
|
||||
atlas.unmarkCountry(user.id, 'JP');
|
||||
|
||||
const after = await getStats(user.id);
|
||||
const after = await atlas.stats(user.id);
|
||||
expect(after.countries.map((c: { code: string }) => c.code)).not.toContain('JP');
|
||||
// BE is untouched — removal is scoped to the one country.
|
||||
expect(after.countries.map((c: { code: string }) => c.code)).toContain('BE');
|
||||
@@ -369,11 +385,11 @@ describe('unmarkCountryVisited — tombstones', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'from', 0, 50.9014, 4.4844);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 1, 35.6762, 139.6503);
|
||||
|
||||
unmarkCountryVisited(user.id, 'JP');
|
||||
expect((await getStats(user.id)).countries.map((c: { code: string }) => c.code)).not.toContain('JP');
|
||||
atlas.unmarkCountry(user.id, 'JP');
|
||||
expect((await atlas.stats(user.id)).countries.map((c: { code: string }) => c.code)).not.toContain('JP');
|
||||
|
||||
markCountryVisited(user.id, 'JP');
|
||||
expect((await getStats(user.id)).countries.map((c: { code: string }) => c.code)).toContain('JP');
|
||||
atlas.markCountry(user.id, 'JP');
|
||||
expect((await atlas.stats(user.id)).countries.map((c: { code: string }) => c.code)).toContain('JP');
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-023: #1490 a removed country reappears once it has a real place', async () => {
|
||||
@@ -385,12 +401,12 @@ describe('unmarkCountryVisited — tombstones', () => {
|
||||
insertReservationEndpoint(testDb, reservation.id, 'from', 0, 50.9014, 4.4844);
|
||||
insertReservationEndpoint(testDb, reservation.id, 'to', 1, 35.6762, 139.6503);
|
||||
|
||||
unmarkCountryVisited(user.id, 'JP');
|
||||
expect((await getStats(user.id)).countries.map((c: { code: string }) => c.code)).not.toContain('JP');
|
||||
atlas.unmarkCountry(user.id, 'JP');
|
||||
expect((await atlas.stats(user.id)).countries.map((c: { code: string }) => c.code)).not.toContain('JP');
|
||||
|
||||
insertPlace(testDb, trip.id, 'Senso-ji', 'Asakusa, Tokyo, Japan');
|
||||
|
||||
const after = await getStats(user.id);
|
||||
const after = await atlas.stats(user.id);
|
||||
const jp = after.countries.find((c: { code: string }) => c.code === 'JP');
|
||||
expect(jp).toBeDefined();
|
||||
expect(jp!.placeCount).toBe(1);
|
||||
@@ -538,7 +554,7 @@ describe('getStats — extended', () => {
|
||||
const { user } = createUser(testDb);
|
||||
createTrip(testDb, user.id, { title: 'Short Trip', start_date: '2024-03-01', end_date: '2024-03-03' });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
// March 1, 2, 3 → diff = 2 + 1 = 3
|
||||
expect(stats.stats.totalDays).toBe(3);
|
||||
@@ -548,7 +564,7 @@ describe('getStats — extended', () => {
|
||||
const { user } = createUser(testDb);
|
||||
createTrip(testDb, user.id, { title: 'Dateless' });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.stats.totalDays).toBe(0);
|
||||
});
|
||||
@@ -558,7 +574,7 @@ describe('getStats — extended', () => {
|
||||
createTrip(testDb, user.id, { title: 'Japan Trip', start_date: '2024-01-01', end_date: '2024-01-10' });
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
const codes = stats.countries.map((c: any) => c.code);
|
||||
expect(codes).toContain('JP');
|
||||
@@ -571,7 +587,7 @@ describe('getStats — extended', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Past France Trip', start_date: '2023-05-01', end_date: '2023-05-10' });
|
||||
insertPlace(testDb, trip.id, 'Eiffel Tower', 'Champ de Mars, Paris, France');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.lastTrip).not.toBeNull();
|
||||
expect(stats.lastTrip!.countryCode).toBe('FR');
|
||||
@@ -584,7 +600,7 @@ describe('getStats — extended', () => {
|
||||
const futureDateStr = futureDate.toISOString().split('T')[0];
|
||||
createTrip(testDb, user.id, { title: 'Future Trip', start_date: futureDateStr });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.nextTrip).not.toBeNull();
|
||||
expect(stats.nextTrip!.daysUntil).toBeGreaterThan(0);
|
||||
@@ -596,7 +612,7 @@ describe('getStats — extended', () => {
|
||||
createTrip(testDb, user.id, { title: 'This Year', start_date: `${currentYear}-06-01`, end_date: `${currentYear}-06-10` });
|
||||
createTrip(testDb, user.id, { title: 'Last Year', start_date: `${currentYear - 1}-07-01`, end_date: `${currentYear - 1}-07-10` });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.streak).toBeGreaterThanOrEqual(1);
|
||||
expect(stats.firstYear).toBe(currentYear - 1);
|
||||
@@ -608,7 +624,7 @@ describe('getStats — extended', () => {
|
||||
createTrip(testDb, user.id, { title: 'This Year', start_date: `${currentYear}-03-01` });
|
||||
createTrip(testDb, user.id, { title: 'Last Year', start_date: `${currentYear - 1}-03-01` });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.tripsThisYear).toBe(1);
|
||||
});
|
||||
@@ -618,7 +634,7 @@ describe('getStats — extended', () => {
|
||||
const nextYear = new Date().getFullYear() + 1;
|
||||
createTrip(testDb, user.id, { title: 'Future', start_date: `${nextYear}-01-01`, end_date: `${nextYear}-01-10` });
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.lastTrip).toBeNull();
|
||||
});
|
||||
@@ -633,7 +649,7 @@ describe('getStats — extended', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'San Francisco Trip' });
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Hotel Pickwick', 37.7830549, -122.4066689, '85 5th St, San Francisco, CA');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
const codes = stats.countries.map((c: any) => c.code);
|
||||
expect(codes).toContain('US');
|
||||
@@ -647,7 +663,7 @@ describe('getStats — extended', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Past NY Trip', start_date: '2023-05-01', end_date: '2023-05-10' });
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Imperial Court Hotel', 40.7848394, -73.981643, '307 W 79th Street, New York, NY');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
|
||||
expect(stats.lastTrip).not.toBeNull();
|
||||
expect(stats.lastTrip!.countryCode).toBe('US');
|
||||
@@ -660,7 +676,7 @@ describe('getCountryPlaces', () => {
|
||||
it('ATLAS-UNIT-013: returns empty result when user has no trips', () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
const result = getCountryPlaces(user.id, 'FR');
|
||||
const result = atlas.countryPlaces(user.id, 'FR');
|
||||
|
||||
expect(result.places).toHaveLength(0);
|
||||
expect(result.trips).toHaveLength(0);
|
||||
@@ -673,7 +689,7 @@ describe('getCountryPlaces', () => {
|
||||
insertPlace(testDb, trip.id, 'Louvre', '75001 Paris, France');
|
||||
insertPlace(testDb, trip.id, 'Berlin Wall', 'Bernauer Str., Berlin, Germany');
|
||||
|
||||
const result = getCountryPlaces(user.id, 'FR');
|
||||
const result = atlas.countryPlaces(user.id, 'FR');
|
||||
|
||||
expect(result.places).toHaveLength(1);
|
||||
expect(result.places[0].name).toBe('Louvre');
|
||||
@@ -686,7 +702,7 @@ describe('getCountryPlaces', () => {
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
|
||||
createTrip(testDb, user.id, { title: 'Japan' });
|
||||
|
||||
const result = getCountryPlaces(user.id, 'JP');
|
||||
const result = atlas.countryPlaces(user.id, 'JP');
|
||||
|
||||
expect(result.manually_marked).toBe(true);
|
||||
});
|
||||
@@ -697,7 +713,7 @@ describe('getCountryPlaces', () => {
|
||||
// Paris coordinates (48.85°N, 2.35°E) — falls inside FR bounding box
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Secret Paris Spot', 48.85, 2.35);
|
||||
|
||||
const result = getCountryPlaces(user.id, 'FR');
|
||||
const result = atlas.countryPlaces(user.id, 'FR');
|
||||
|
||||
expect(result.places).toHaveLength(1);
|
||||
expect(result.places[0].name).toBe('Secret Paris Spot');
|
||||
@@ -710,7 +726,7 @@ describe('getVisitedRegions', () => {
|
||||
it('ATLAS-UNIT-017: returns empty regions object when user has no trips', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(result.regions).toEqual({});
|
||||
});
|
||||
@@ -720,7 +736,7 @@ describe('getVisitedRegions', () => {
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'DE');
|
||||
testDb.prepare('INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)').run(user.id, 'DE-BY', 'Bayern', 'DE');
|
||||
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(result.regions['DE']).toBeDefined();
|
||||
const codes = result.regions['DE'].map((r: any) => r.code);
|
||||
@@ -747,11 +763,11 @@ describe('getVisitedRegions', () => {
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Paris Hotel', 48.85, 2.35);
|
||||
|
||||
// First call triggers the background geocoding fire-and-forget
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
// Advance all pending timers (including the 1100ms Nominatim rate-limit delay)
|
||||
await vi.runAllTimersAsync();
|
||||
// Second call returns now-cached data
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(result.regions['FR']).toBeDefined();
|
||||
|
||||
@@ -771,7 +787,7 @@ describe('getVisitedRegions', () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
|
||||
vi.stubGlobal('fetch', mockFetch);
|
||||
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(result.regions['FR']).toBeDefined();
|
||||
@@ -791,11 +807,11 @@ describe('getVisitedRegions', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Manchester Trip' });
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Old Trafford', 53.4631, -2.2913);
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
// The background geocode is fire-and-forget; give its microtasks a turn to settle
|
||||
// before reading the now-cached result back.
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(result.regions['GB']).toBeDefined();
|
||||
@@ -815,11 +831,11 @@ describe('getVisitedRegions', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Barcelona Trip' });
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Sagrada Familia', 41.4036, 2.1744);
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
// The background geocode is fire-and-forget; give its microtasks a turn to settle
|
||||
// before reading the now-cached result back.
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(result.regions['ES']).toBeDefined();
|
||||
@@ -842,9 +858,9 @@ describe('getVisitedRegions', () => {
|
||||
'4 Gruusswiss, Bollendorf-Pont, Distrikt Gréiwemaacher 6555, Luxembourg'
|
||||
);
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(result.regions['LU']).toBeDefined();
|
||||
@@ -869,9 +885,9 @@ describe('getVisitedRegions', () => {
|
||||
'85 5th St, San Francisco, CA'
|
||||
);
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(result.regions['US']).toBeDefined();
|
||||
@@ -897,9 +913,9 @@ describe('getVisitedRegions', () => {
|
||||
const trip = createTrip(testDb, user.id, { title: 'Middle of the ocean' });
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Buoy', 10, -40);
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
await vi.runAllTimersAsync();
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(result.regions['GB']).toBeDefined();
|
||||
@@ -934,9 +950,9 @@ describe('getVisitedRegions', () => {
|
||||
// exercising this test's fetch/gate path.
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Weather buoy', 20, -35, '123 Nowhere Rd, JP');
|
||||
|
||||
await getVisitedRegions(user.id);
|
||||
await atlas.visitedRegions(user.id);
|
||||
await vi.runAllTimersAsync();
|
||||
const result = await getVisitedRegions(user.id);
|
||||
const result = await atlas.visitedRegions(user.id);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1); // fell through to Nominatim, not a fabricated JP match
|
||||
expect(result.regions['JP']).toBeUndefined();
|
||||
@@ -948,11 +964,11 @@ describe('getVisitedRegions', () => {
|
||||
// ── unmarkRegionVisited — tombstones + country cascade ──────────────────────
|
||||
|
||||
// Places are region-resolved by a fire-and-forget background task (see reverseGeocodeRegion
|
||||
// callers); a single getVisitedRegions() call returns before it settles. Populate the cache
|
||||
// callers); a single atlas.visitedRegions() call returns before it settles. Populate the cache
|
||||
// deterministically before asserting against it or calling unmarkRegionVisited (which reads
|
||||
// place_regions directly, not through this function).
|
||||
async function primeRegionCache(userId: number): Promise<void> {
|
||||
await getVisitedRegions(userId);
|
||||
await atlas.visitedRegions(userId);
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
|
||||
@@ -968,12 +984,12 @@ describe('unmarkRegionVisited — tombstones + country cascade', () => {
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Golden Gate Park', 37.7694, -122.4862);
|
||||
await primeRegionCache(user.id);
|
||||
|
||||
const before = await getVisitedRegions(user.id);
|
||||
const before = await atlas.visitedRegions(user.id);
|
||||
expect(before.regions['US']?.map((r: any) => r.code)).toContain('US-CA');
|
||||
|
||||
unmarkRegionVisited(user.id, 'US-CA');
|
||||
atlas.unmarkRegion(user.id, 'US-CA');
|
||||
|
||||
const after = await getVisitedRegions(user.id);
|
||||
const after = await atlas.visitedRegions(user.id);
|
||||
expect(after.regions['US']?.map((r: any) => r.code) ?? []).not.toContain('US-CA');
|
||||
});
|
||||
|
||||
@@ -983,11 +999,11 @@ describe('unmarkRegionVisited — tombstones + country cascade', () => {
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Golden Gate Park', 37.7694, -122.4862);
|
||||
await primeRegionCache(user.id);
|
||||
|
||||
unmarkRegionVisited(user.id, 'US-CA');
|
||||
expect((await getVisitedRegions(user.id)).regions['US']?.map((r: any) => r.code) ?? []).not.toContain('US-CA');
|
||||
atlas.unmarkRegion(user.id, 'US-CA');
|
||||
expect((await atlas.visitedRegions(user.id)).regions['US']?.map((r: any) => r.code) ?? []).not.toContain('US-CA');
|
||||
|
||||
markRegionVisited(user.id, 'US-CA', 'California', 'US');
|
||||
expect((await getVisitedRegions(user.id)).regions['US']?.map((r: any) => r.code)).toContain('US-CA');
|
||||
atlas.markRegion(user.id, 'US-CA', 'California', 'US');
|
||||
expect((await atlas.visitedRegions(user.id)).regions['US']?.map((r: any) => r.code)).toContain('US-CA');
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-026: hiding a country\'s only visible region also hides the country', async () => {
|
||||
@@ -998,14 +1014,14 @@ describe('unmarkRegionVisited — tombstones + country cascade', () => {
|
||||
// unmarkCountryVisited's own tombstone tests above use flight-endpoint-derived
|
||||
// countries rather than real places for the same reason.
|
||||
const { user } = createUser(testDb);
|
||||
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP'); // also auto-marks JP visited
|
||||
atlas.markRegion(user.id, 'JP-13', 'Tokyo', 'JP'); // also auto-marks JP visited
|
||||
|
||||
const beforeStats = await getStats(user.id);
|
||||
const beforeStats = await atlas.stats(user.id);
|
||||
expect(beforeStats.countries.map((c: any) => c.code)).toContain('JP');
|
||||
|
||||
unmarkRegionVisited(user.id, 'JP-13');
|
||||
atlas.unmarkRegion(user.id, 'JP-13');
|
||||
|
||||
const afterStats = await getStats(user.id);
|
||||
const afterStats = await atlas.stats(user.id);
|
||||
expect(afterStats.countries.map((c: any) => c.code)).not.toContain('JP');
|
||||
});
|
||||
|
||||
@@ -1016,25 +1032,128 @@ describe('unmarkRegionVisited — tombstones + country cascade', () => {
|
||||
insertPlaceWithCoords(testDb, trip.id, 'Philly hotel', 39.9527237, -75.1635262); // PA
|
||||
await primeRegionCache(user.id);
|
||||
|
||||
unmarkRegionVisited(user.id, 'US-MA');
|
||||
atlas.unmarkRegion(user.id, 'US-MA');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
expect(stats.countries.map((c: any) => c.code)).toContain('US');
|
||||
const regions = (await getVisitedRegions(user.id)).regions['US'].map((r: any) => r.code);
|
||||
const regions = (await atlas.visitedRegions(user.id)).regions['US'].map((r: any) => r.code);
|
||||
expect(regions).not.toContain('US-MA');
|
||||
expect(regions).toContain('US-PA');
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-028: re-marking a region whose country was cascade-hidden brings the country back too', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP');
|
||||
atlas.markRegion(user.id, 'JP-13', 'Tokyo', 'JP');
|
||||
|
||||
unmarkRegionVisited(user.id, 'JP-13');
|
||||
expect((await getStats(user.id)).countries.map((c: any) => c.code)).not.toContain('JP');
|
||||
atlas.unmarkRegion(user.id, 'JP-13');
|
||||
expect((await atlas.stats(user.id)).countries.map((c: any) => c.code)).not.toContain('JP');
|
||||
|
||||
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP');
|
||||
atlas.markRegion(user.id, 'JP-13', 'Tokyo', 'JP');
|
||||
|
||||
const stats = await getStats(user.id);
|
||||
const stats = await atlas.stats(user.id);
|
||||
expect(stats.countries.map((c: any) => c.code)).toContain('JP');
|
||||
});
|
||||
});
|
||||
|
||||
// ── atlas.bridge.ts delegation (the authService consumer path) ──────────────
|
||||
|
||||
describe('atlas.bridge delegation', () => {
|
||||
it('ATLAS-SVC-029: bridge getHiddenCountries reflects tombstones written through the service', () => {
|
||||
const { user } = createUser(testDb);
|
||||
atlas.unmarkCountry(user.id, 'JP');
|
||||
|
||||
// The bridge's own AtlasService instance runs over the db Proxy (mocked to
|
||||
// this suite's testDb), so it must see the same hidden_countries row.
|
||||
const hidden = bridgeGetHiddenCountries(user.id);
|
||||
expect(hidden.has('JP')).toBe(true);
|
||||
expect(hidden.has('FR')).toBe(false);
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-030: bridge getCountryFromCoords is the atlas-geo function (shared indexes)', () => {
|
||||
expect(bridgeGetCountryFromCoords).toBe(getCountryFromCoords);
|
||||
expect(bridgeGetCountryFromCoords(48.85, 2.35)).toBe('FR');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Quirks fixed after the DI fold (trailing fix(server) commit) ─────────────
|
||||
|
||||
describe('atlas quirk fixes', () => {
|
||||
it('ATLAS-SVC-031: countryPlaces reports manually_marked for a trip-less user', () => {
|
||||
// The legacy early return hardcoded manually_marked: false, so a user who
|
||||
// marked a country visited before creating any trip saw it as unmarked.
|
||||
const { user } = createUser(testDb);
|
||||
testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'JP');
|
||||
|
||||
const result = atlas.countryPlaces(user.id, 'JP');
|
||||
|
||||
expect(result).toEqual({ places: [], trips: [], manually_marked: true });
|
||||
expect(atlas.countryPlaces(user.id, 'FR').manually_marked).toBe(false);
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-032: updateBucketItem persists lat/lng of exactly 0 (equator/prime meridian)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const item = atlas.createBucketItem(user.id, { name: 'Null Island', lat: 10, lng: 10 }) as { id: number };
|
||||
|
||||
const updated = atlas.updateBucketItem(user.id, item.id, { lat: 0, lng: 0 }) as { lat: number; lng: number };
|
||||
|
||||
// The legacy `|| null` binding read 0 as "clear" and wrote NULL.
|
||||
expect(updated.lat).toBe(0);
|
||||
expect(updated.lng).toBe(0);
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-033: updateBucketItem persists an explicit empty-string notes value', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const item = atlas.createBucketItem(user.id, { name: 'Kyoto', notes: 'old notes' }) as { id: number };
|
||||
|
||||
const updated = atlas.updateBucketItem(user.id, item.id, { notes: '' }) as { notes: string | null };
|
||||
|
||||
// The legacy `|| null` binding collapsed '' to NULL.
|
||||
expect(updated.notes).toBe('');
|
||||
});
|
||||
|
||||
it("ATLAS-SVC-034: bucket update/delete cannot touch another user's row (user-scoped SQL)", () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const item = atlas.createBucketItem(user.id, { name: 'Mine' }) as { id: number; name: string };
|
||||
|
||||
expect(atlas.updateBucketItem(other.id, item.id, { name: 'Stolen' })).toBeNull();
|
||||
expect(atlas.deleteBucketItem(other.id, item.id)).toBe(false);
|
||||
const row = testDb.prepare('SELECT name FROM bucket_list WHERE id = ?').get(item.id) as { name: string };
|
||||
expect(row.name).toBe('Mine');
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-035: unmarkRegion is atomic — a failure mid-flow rolls the region delete back', () => {
|
||||
const { user } = createUser(testDb);
|
||||
atlas.markRegion(user.id, 'JP-13', 'Tokyo', 'JP');
|
||||
|
||||
// Force the tombstone insert (statement 2 of the flow) to fail by hiding
|
||||
// the hidden_regions table; the visited_regions DELETE must roll back.
|
||||
testDb.exec('ALTER TABLE hidden_regions RENAME TO hidden_regions_gone');
|
||||
try {
|
||||
expect(() => atlas.unmarkRegion(user.id, 'JP-13')).toThrow();
|
||||
} finally {
|
||||
testDb.exec('ALTER TABLE hidden_regions_gone RENAME TO hidden_regions');
|
||||
}
|
||||
|
||||
const row = testDb
|
||||
.prepare('SELECT 1 FROM visited_regions WHERE user_id = ? AND region_code = ?')
|
||||
.get(user.id, 'JP-13');
|
||||
expect(row).toBeDefined();
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-036: markCountry is atomic — a failure on the tombstone lift rolls the insert back', () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
testDb.exec('ALTER TABLE hidden_countries RENAME TO hidden_countries_gone');
|
||||
try {
|
||||
expect(() => atlas.markCountry(user.id, 'DE')).toThrow();
|
||||
} finally {
|
||||
testDb.exec('ALTER TABLE hidden_countries_gone RENAME TO hidden_countries');
|
||||
}
|
||||
|
||||
const row = testDb
|
||||
.prepare('SELECT 1 FROM visited_countries WHERE user_id = ? AND country_code = ?')
|
||||
.get(user.id, 'DE');
|
||||
expect(row).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
|
||||
* DI-native domains (budget/exchange-rates/reservations/tags/categories/todo/
|
||||
* packing/day-notes/days/assignments/oauth/llm-config/files/collab/vacay/
|
||||
* permissions/trips/places/collections)
|
||||
* permissions/trips/places/collections/atlas)
|
||||
* are constructor-injected stubs; legacy services/* domains stay path-mocked
|
||||
* until their own DI migration lands.
|
||||
*/
|
||||
@@ -256,17 +256,19 @@ vi.mock('../../../src/services/journeyService', () => ({
|
||||
updateEntry: vi.fn((entryId: number, _uid: number, data: unknown) => (entryId === 99 ? null : { id: entryId, ...(data as object) })),
|
||||
deleteEntry: vi.fn((entryId: number) => entryId !== 99),
|
||||
}));
|
||||
vi.mock('../../../src/services/atlasService', () => ({
|
||||
// Atlas is a constructor-injected stub since the atlas fold (same behaviors as
|
||||
// the old services/atlasService path mock, keyed by the service method names).
|
||||
const atlasStub = {
|
||||
listVisitedCountries: vi.fn(() => [{ country_code: 'JP' }]),
|
||||
listManuallyVisitedRegions: vi.fn(() => [{ region_code: 'JP-13' }]),
|
||||
listBucketList: vi.fn((uid: number) => [{ id: 5, user_id: uid, name: 'Kyoto' }]),
|
||||
markCountryVisited: vi.fn(),
|
||||
unmarkCountryVisited: vi.fn(),
|
||||
markRegionVisited: vi.fn(),
|
||||
unmarkRegionVisited: vi.fn(),
|
||||
bucketList: vi.fn((uid: number) => [{ id: 5, user_id: uid, name: 'Kyoto' }]),
|
||||
markCountry: vi.fn(),
|
||||
unmarkCountry: vi.fn(),
|
||||
markRegion: vi.fn(),
|
||||
unmarkRegion: vi.fn(),
|
||||
createBucketItem: vi.fn((uid: number, data: { name: string }) => ({ id: 110, user_id: uid, name: data.name })),
|
||||
deleteBucketItem: vi.fn((_uid: number, itemId: number) => Number(itemId) !== 404),
|
||||
}));
|
||||
} as unknown as AtlasService;
|
||||
// Collections is a constructor-injected stub since the collections fold (same
|
||||
// behaviors as the old services/collectionsService path mock — the service
|
||||
// throws status-tagged errors the factory maps onto the RPC error classes).
|
||||
@@ -321,6 +323,7 @@ import type { VacayService } from '../../../src/nest/vacay/vacay.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import type { CollectionsService } from '../../../src/nest/collections/collections.service';
|
||||
import type { AtlasService } from '../../../src/nest/atlas/atlas.service';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { NotFoundError, ValidationError } from '../../../src/nest/trips/trips.service';
|
||||
@@ -343,7 +346,7 @@ const tripsStub = {
|
||||
list: () => [{ id: 1 }],
|
||||
removeMember: vi.fn(),
|
||||
} as unknown as import('../../../src/nest/trips/trips.service').TripsService;
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub, permissionsStub, exchangeRatesStub, addonsStub, new RealtimeService(), tripsStub, placesStub, collectionsStub);
|
||||
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub, permissionsStub, exchangeRatesStub, addonsStub, new RealtimeService(), tripsStub, placesStub, collectionsStub, atlasStub);
|
||||
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
|
||||
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
|
||||
|
||||
|
||||
@@ -94,7 +94,8 @@ import {
|
||||
generateToken,
|
||||
getTravelStats,
|
||||
} from '../../../src/services/authService';
|
||||
import { unmarkCountryVisited } from '../../../src/services/atlasService';
|
||||
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { verifyJwtAndLoadUser } from '../../../src/middleware/auth';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -794,7 +795,7 @@ describe('getTravelStats', () => {
|
||||
|
||||
expect(getTravelStats(user.id).countries).toContain('JP');
|
||||
|
||||
unmarkCountryVisited(user.id, 'JP');
|
||||
new AtlasService(new DatabaseService(testDb)).unmarkCountry(user.id, 'JP');
|
||||
|
||||
const after = getTravelStats(user.id);
|
||||
expect(after.countries).not.toContain('JP');
|
||||
|
||||
Reference in New Issue
Block a user