chore: move place backend to proper DI

Fold the 1029-line services/placeService.ts into the DI-native PlacesService:
the CRUD + ratings SQL, the GPX/KML/KMZ importers and the Google/Naver list
importers become methods over the injected DatabaseService, byte-identical
statements, COALESCE semantics and the If-Match conflict protocol (#1135).
The pure half — frozen XML parsers, the KMZ unpacker, the dedup predicates,
the Google hex-id parsers, reclaimPhotoCache — moves to places.helpers.ts
(maps.helpers precedent).

The 10-tool mcp/tools/places.ts registrar plus the trek://trips/{tripId}/places
resource move onto the decorator registry as places.mcp.ts. search_place travels
with them because its gate is places:read, not the read-only geo group, and now
injects MapsService. TripsService, DaysMcp, BookingImportService and the plugin
RPC host (PluginHostDepsFactory's 21st constructor dep) all inject PlacesService,
so the domain needs no bridge at all. The two assignments.bridge imports that
places.mcp.ts keeps are a deliberate cycle break: AssignmentsModule imports
DaysModule and DaysModule now imports PlacesModule for days.mcp.ts's place
creation, so injecting AssignmentsService there would close
DaysModule -> PlacesModule -> AssignmentsModule -> DaysModule. Same seam
reservations.mcp.ts uses, same trade trips.bridge.ts documents.

Also folds services/placeEnrichment.ts in — its DB/websocket/Maps half becomes
PlacesService methods over the injected DatabaseService/RealtimeService/
MapsService, its pure match selector joins places.helpers.ts — which retires
nest/maps/maps.bridge.ts with its last consumer.

Adopts places.dto.ts for the seven grandfathered body contracts and clears every
PlacesController entry from body-contract-allow-list.ts. Two consequences worth
knowing: the bespoke 400s 'Place name is required', 'ids must be an array of
numbers' and 'URL is required' are now the ZodValidationPipe envelope, and
because a pipe runs before the handler a malformed body 400s ahead of the
trip-access 404 it used to follow — the same trade the todo and trips migrations
took. placeBulkUpdateRequestSchema.ids drops .min(1) so the endpoint's
empty-list short-circuit stays reachable.

Fixes four defects the relocation had faithfully carried, each with a
failing-first regression test:

- create dropped lat/lng of exactly 0, so a place on the equator or the prime
  meridian lost its coordinates (`x || null` cannot tell absent from zero).
- duration_minutes: 0 was unsettable — replaced by the 60-minute default on
  create, and read as "absent" by COALESCE on update.
- the journey delete hook fired on unscoped ids: DELETE /:id, POST /bulk-delete
  and the delete_place MCP tool could detach another trip's journey entries for
  an id they then refused. All three scope first via the new
  PlacesService.scopedIds, mirroring the guard PluginHostDepsFactory already had.
  bulk_delete_places also moves its hook ahead of the DELETE —
  journey_entries.source_place_id is ON DELETE SET NULL, so running it afterwards
  left the entries as orphans.
- the place search treated % and _ as LIKE wildcards; a bare % returned the whole
  trip. The three clauses now carry ESCAPE with the term escaped.

Plus hardening on the Google list fetch: the response is capped at 8 MB
(declared content-length and post-read length, the transit.service precedent)
and its JSON.parse is guarded, so a malformed provider payload produces the
existing 'Invalid list data received from Google Maps' 400 instead of throwing.

Quirks deliberately preserved: the non-COALESCE route_color (#776),
currency/transport_mode staying unclearable, importGpx returning null for a file
that parses but yields no usable geometry, update skipping the If-Match check
when the stored updated_at is null, and every string-valued `x || null`.

Tests move with their case IDs: placeService.test.ts and the wrapper suite merge
into unit/nest/places.service.test.ts, kmzUnpack into places.helpers.test.ts,
placeEnrichment into places.enrichment.test.ts. The places e2e converts to the
DI-native pattern (real SQL against temp-db DDL), tools-places.test.ts is kept
and extended so it exercises the decorator path through the test registry, and
the plugin-host and booking-import path mocks become constructor stubs.
This commit is contained in:
jubnl
2026-07-30 17:07:12 +02:00
parent 57017b8aed
commit 4f0f80ad69
47 changed files with 3914 additions and 2840 deletions
+3 -29
View File
@@ -86,35 +86,9 @@ async function withHarness(userId: number, fn: (harness: McpHarness) => Promise<
// The trek://trips/{tripId}/days resource moved to the DI-discovered
// DaysMcp — see tools-days.test.ts.
describe('Resource: trek://trips/{tripId}/places', () => {
it('returns all places for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const places = parseResourceResult(result) as any[];
expect(places).toHaveLength(2);
const names = places.map((p) => p.name);
expect(names).toContain('Eiffel Tower');
expect(names).toContain('Louvre');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// 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
+319 -9
View File
@@ -1,6 +1,11 @@
/**
* Unit tests for MCP place tools: create_place, update_place, delete_place, search_place.
* (list_categories moved to tools-categories.test.ts with the CategoriesMcp migration.)
*
* Since the place DI fold these run through the decorator-driven PlacesMcp in
* src/nest/places/places.mcp.ts — the harness attaches it via the hand-wired
* registry in tests/helpers/mcp-test-controllers.ts, so the assertions below
* exercise the @Tool/@ResourceTemplate path instead of the deleted registrar.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -39,20 +44,17 @@ const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
const { searchPlacesMock } = vi.hoisted(() => ({ searchPlacesMock: vi.fn() }));
// The maps bridge is what the legacy places registrar (and placeEnrichment, in
// the same import graph) consume since the maps DI fold — mock every export it
// provides so the named imports resolve.
vi.mock('../../../src/nest/maps/maps.bridge', () => ({
searchPlaces: searchPlacesMock,
getMapsKey: vi.fn(() => null),
getPlacePhoto: vi.fn(async () => ({ photoUrl: null, attribution: null })),
}));
// PlacesMcp and PlacesService both inject MapsService (search_place and the
// import enrichment), so the geo calls are stubbed on the prototype — see
// beforeEach — rather than through a module mock.
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPlace, createDay, createDayAssignment, createJourney } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { PlacesService } from '../../../src/nest/places/places.service';
/** Link a journey to a trip so journey-skeleton sync has a target. */
function linkJourney(journeyId: number, tripId: number) {
@@ -71,6 +73,7 @@ beforeEach(() => {
resetTestDb(testDb);
broadcastMock.mockClear();
searchPlacesMock.mockClear();
vi.spyOn(MapsService.prototype, 'searchPlaces').mockImplementation(searchPlacesMock as never);
delete process.env.DEMO_MODE;
});
@@ -512,3 +515,310 @@ describe('Tool: list_places', () => {
});
});
});
// ---------------------------------------------------------------------------
// rate_place (#1435)
// ---------------------------------------------------------------------------
describe('Tool: rate_place', () => {
it('stores the acting user\'s vote and reports the aggregate', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 4 } });
const data = parseToolResult(result) as any;
expect(data.place.id).toBe(place.id);
const rows = testDb.prepare('SELECT user_id, rating FROM place_ratings WHERE place_id = ?').all(place.id);
expect(rows).toEqual([{ user_id: user.id, rating: 4 }]);
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:updated', expect.any(Object));
});
});
it('an omitted rating clears the vote', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
await withHarness(user.id, async (h) => {
await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 5 } });
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id } });
const data = parseToolResult(result) as any;
expect(data.place.id).toBe(place.id);
const rows = testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id) as { n: number };
expect(rows.n).toBe(0);
});
});
it('returns error for a place outside the trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const place = createPlace(testDb, other.id, { name: 'Elsewhere' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'rate_place', arguments: { tripId: trip.id, placeId: place.id, rating: 3 } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// bulk_delete_places
// ---------------------------------------------------------------------------
describe('Tool: bulk_delete_places', () => {
it('deletes the trip-scoped ids, skips foreign ones and broadcasts each', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const a = createPlace(testDb, trip.id, { name: 'A' });
const b = createPlace(testDb, trip.id, { name: 'B' });
const foreign = createPlace(testDb, other.id, { name: 'Foreign' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'bulk_delete_places',
arguments: { tripId: trip.id, placeIds: [a.id, b.id, foreign.id] },
});
const data = parseToolResult(result) as any;
expect(data.count).toBe(2);
expect(data.deleted.sort()).toEqual([a.id, b.id].sort());
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:deleted', { placeId: a.id, _source: 'mcp' });
// The other trip's place survives.
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(foreign.id)).toBeTruthy();
});
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
const place = createPlace(testDb, trip.id, { name: 'Theirs' });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [place.id] } });
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/places resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/places', () => {
it('returns all places for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const places = parseResourceResult(result) as any[];
expect(places).toHaveLength(2);
const names = places.map((p) => p.name);
expect(names).toContain('Eiffel Tower');
expect(names).toContain('Louvre');
});
});
// The ?assignment= filter the description advertises is read off
// uri.searchParams inside the handler, but the SDK's template matcher rejects
// a URI carrying a query string before the handler runs — same as the legacy
// resource this was moved from, so it stays untested here.
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/places` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// ---------------------------------------------------------------------------
// import_places_from_url
// ---------------------------------------------------------------------------
describe('Tool: import_places_from_url', () => {
it('imports a google list, broadcasts each place and reports the count', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spy = vi.spyOn(PlacesService.prototype, 'importGoogleList').mockResolvedValue({
places: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }] as never,
listName: 'Weekend',
skipped: 3,
});
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://maps.app.goo.gl/x', source: 'google-list' },
});
const data = parseToolResult(result) as any;
expect(data).toMatchObject({ count: 2, listName: 'Weekend', skipped: 3 });
expect(spy).toHaveBeenCalledWith(String(trip.id), 'https://maps.app.goo.gl/x');
expect(broadcastMock).toHaveBeenCalledTimes(2);
});
spy.mockRestore();
});
it('surfaces the naver importer\'s { error, status } as a tool error', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spy = vi.spyOn(PlacesService.prototype, 'importNaverList').mockResolvedValue({ error: 'List is empty or could not be read', status: 400 });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://naver.me/x', source: 'naver-list' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('List is empty or could not be read');
});
spy.mockRestore();
});
it('returns access denied for non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'import_places_from_url',
arguments: { tripId: trip.id, url: 'https://maps.app.goo.gl/x', source: 'google-list' },
});
expect(result.isError).toBe(true);
});
});
});
// ---------------------------------------------------------------------------
// create_and_assign_place failure path
// ---------------------------------------------------------------------------
describe('Tool: create_and_assign_place (failure paths)', () => {
it('reports a missing day without writing the place', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_and_assign_place',
arguments: { tripId: trip.id, dayId: 99999, name: 'Nowhere' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('Day not found.');
expect(testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });
});
});
it('rolls the transaction back and reports failure when the place write throws', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const spy = vi.spyOn(PlacesService.prototype, 'create').mockImplementation(() => { throw new Error('db exploded'); });
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_and_assign_place',
arguments: { tripId: trip.id, dayId: day.id, name: 'Doomed' },
});
expect(result.isError).toBe(true);
expect((result.content as { text: string }[])[0].text).toBe('Failed to create place and assignment.');
expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ?').get(day.id)).toEqual({ n: 0 });
});
spy.mockRestore();
});
});
// ---------------------------------------------------------------------------
// Journey-hook scoping + ordering on the delete paths (#1745)
// ---------------------------------------------------------------------------
/** Materialise a skeleton entry for an assigned place (same shape the sync writes). */
function seedSkeleton(journeyId: number, tripId: number, placeId: number, userId: number, name: string) {
testDb.prepare(
`INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, entry_date, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, 'skeleton', ?, ?, 0, ?, ?)`,
).run(journeyId, tripId, placeId, userId, name, '2026-05-01', Date.now(), Date.now());
}
describe('journey hooks on the MCP delete paths', () => {
it("delete_place leaves a foreign trip's journey skeleton alone", async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, other.id);
const foreign = createPlace(testDb, other.id, { name: 'Theirs' });
const day = createDay(testDb, other.id);
createDayAssignment(testDb, day.id, foreign.id);
seedSkeleton(journey.id, other.id, foreign.id, user.id, 'Theirs');
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'delete_place', arguments: { tripId: trip.id, placeId: foreign.id } });
expect(result.isError).toBe(true);
});
// The other trip's skeleton entry still points at its place, and the row lives.
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(foreign.id)).toBeDefined();
});
// Without the ordering fix the hook ran AFTER the DELETE, by which point
// journey_entries.source_place_id was already NULL (ON DELETE SET NULL) — so
// the entry survived as an orphan instead of being removed. Asserting on the
// entry count, not on source_place_id, is what tells the two apart.
it('bulk_delete_places detaches the skeletons before the rows go', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Doomed' });
const day = createDay(testDb, trip.id);
createDayAssignment(testDb, day.id, place.id);
seedSkeleton(journey.id, trip.id, place.id, user.id, 'Doomed');
expect(skeletonFor(journey.id, place.id)).toBeDefined();
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [place.id] } });
expect((parseToolResult(result) as any).count).toBe(1);
});
// The hook ran while the row still existed, so the entry is gone — not
// lingering with a NULL source_place_id.
expect(skeletonFor(journey.id, place.id)).toBeUndefined();
expect(testDb.prepare('SELECT COUNT(*) AS n FROM journey_entries WHERE journey_id = ?').get(journey.id)).toEqual({ n: 0 });
});
// The MCP bulk path already scoped correctly (it looped over removeMany's
// trip-scoped result), so this is a guard against the scoping regressing when
// the hook moved ahead of the delete — not a fix for a live bug.
it('bulk_delete_places leaves a foreign trip\'s skeleton alone', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const journey = createJourney(testDb, user.id);
linkJourney(journey.id, other.id);
const foreign = createPlace(testDb, other.id, { name: 'Theirs' });
const day = createDay(testDb, other.id);
createDayAssignment(testDb, day.id, foreign.id);
seedSkeleton(journey.id, other.id, foreign.id, user.id, 'Theirs');
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({ name: 'bulk_delete_places', arguments: { tripId: trip.id, placeIds: [foreign.id] } });
expect((parseToolResult(result) as any).count).toBe(0);
});
expect(skeletonFor(journey.id, foreign.id)).toBeDefined();
});
});
@@ -9,7 +9,6 @@ import { DatabaseService } from '../../../../src/nest/database/database.service'
vi.mock('../../../../src/websocket', () => ({ broadcast: vi.fn() }));
const permissionsStub = { checkPermission: vi.fn(() => true) };
vi.mock('../../../../src/services/tripAccess', () => ({ verifyTripAccess: vi.fn() }));
vi.mock('../../../../src/services/placeService', () => ({ createPlace: vi.fn() }));
import { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
@@ -23,7 +22,10 @@ function make(opts: { kit?: boolean; ai?: boolean; extract?: any; parse?: any })
// budget/addons/realtime/maps ride the confirm() path only — the preview()
// tests never reach them, so stubs beyond the positional slots aren't needed.
const maps = { searchNominatim: vi.fn() };
return { svc: new BookingImportService(extractor as any, llmParse as any, new DatabaseService(dbConn), reservations as never, permissionsStub as never, undefined as never, undefined as never, undefined as never, maps as never), extractor, llmParse, reservations, maps };
// Places became a constructor dep with the place DI fold (was a path mock of
// services/placeService); only confirm() reaches it, so a bare create stub does.
const places = { create: vi.fn() };
return { svc: new BookingImportService(extractor as any, llmParse as any, new DatabaseService(dbConn), reservations as never, permissionsStub as never, undefined as never, undefined as never, undefined as never, maps as never, places as never), extractor, llmParse, reservations, maps, places };
}
beforeEach(() => vi.clearAllMocks());
+4 -39
View File
@@ -2247,42 +2247,7 @@ describe('controller-facing wrappers delegate to the folded methods', () => {
});
});
// ── maps.bridge delegation ────────────────────────────────────────────────────
describe('maps.bridge delegation', () => {
it('MAPS-104: getMapsKey delegates to the shared MapsService instance', async () => {
const bridge = await import('../../../src/nest/maps/maps.bridge');
const spy = vi.spyOn(MapsService.prototype, 'getMapsKey').mockReturnValueOnce('bridged-key');
try {
expect(bridge.getMapsKey(7)).toBe('bridged-key');
expect(spy).toHaveBeenCalledWith(7);
} finally {
spy.mockRestore();
}
});
it('MAPS-105: searchPlaces delegates with all args', async () => {
const bridge = await import('../../../src/nest/maps/maps.bridge');
const spy = vi.spyOn(MapsService.prototype, 'searchPlaces').mockResolvedValueOnce({ places: [], source: 'osm' });
try {
await expect(bridge.searchPlaces(7, 'berlin', 'de', { lat: 1, lng: 2, radius: 3 })).resolves.toEqual({
places: [],
source: 'osm',
});
expect(spy).toHaveBeenCalledWith(7, 'berlin', 'de', { lat: 1, lng: 2, radius: 3 });
} finally {
spy.mockRestore();
}
});
it('MAPS-106: getPlacePhoto delegates with coords and name', async () => {
const bridge = await import('../../../src/nest/maps/maps.bridge');
const spy = vi.spyOn(MapsService.prototype, 'getPlacePhoto').mockResolvedValueOnce({ photoUrl: null, attribution: null });
try {
await expect(bridge.getPlacePhoto(7, 'p1', 1.5, 2.5, 'Spot')).resolves.toEqual({ photoUrl: null, attribution: null });
expect(spy).toHaveBeenCalledWith(7, 'p1', 1.5, 2.5, 'Spot');
} finally {
spy.mockRestore();
}
});
});
// The maps.bridge delegation cases (MAPS-104..106) died with the bridge itself:
// its last two consumers — the legacy placeEnrichment helper and the places MCP
// registrar — both folded into the DI-native places domain, which injects
// MapsService directly.
@@ -11,6 +11,9 @@ function svc(o: Partial<PlacesService> = {}): PlacesService {
return {
verifyTripAccess: vi.fn().mockReturnValue(trip), canEdit: vi.fn().mockReturnValue(true), broadcast: vi.fn(),
onCreated: vi.fn(), onUpdated: vi.fn(), onDeleted: vi.fn(),
// Trip-scoping reads the delete paths run before firing the journey hook
// (#1745); default to "everything belongs to the trip".
get: vi.fn().mockReturnValue({ id: 9 }), scopedIds: vi.fn((_t: string, ids: number[]) => ids),
...o,
} as unknown as PlacesService;
}
@@ -51,9 +54,11 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
expect(canEdit).not.toHaveBeenCalled();
});
it('403 without place_edit, 400 without name, then creates + hooks', () => {
// The legacy 'Place name is required' 400 is gone: placeCreateRequestSchema
// pins `name`, so the ZodValidationPipe rejects a nameless body before the
// handler runs (see the e2e suite for the envelope it produces).
it('403 without place_edit, then creates + hooks', () => {
expect(thrown(() => new PlacesController(svc({ canEdit: vi.fn().mockReturnValue(false) })).create(user, '5', { name: 'Spot' }))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new PlacesController(svc()).create(user, '5', {}))).toEqual({ status: 400, body: { error: 'Place name is required' } });
const create = vi.fn().mockReturnValue({ id: 9 }); const broadcast = vi.fn(); const onCreated = vi.fn();
const s = svc({ create, broadcast, onCreated } as Partial<PlacesService>);
expect(new PlacesController(s).create(user, '5', { name: 'Spot' }, 'sock')).toEqual({ place: { id: 9 } });
@@ -136,58 +141,70 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
});
describe('POST /import/google-list + naver-list', () => {
it('400 without a url', async () => {
expect(await thrownAsync(() => new PlacesController(svc()).importGoogle(user, '5', undefined))).toEqual({ status: 400, body: { error: 'URL is required' } });
});
it('400 when url is the wrong type (not a string)', async () => {
expect(await thrownAsync(() => new PlacesController(svc()).importNaver(user, '5', 123))).toEqual({ status: 400, body: { error: 'URL is required' } });
});
// The legacy 'URL is required' 400 is gone: placeImportListRequestSchema
// pins `url`, so the ZodValidationPipe rejects a urlless body before the
// handler runs.
it('maps a service { error, status } to the same response', async () => {
const s = svc({ importGoogleList: vi.fn().mockResolvedValue({ error: 'List is empty', status: 400 }) } as Partial<PlacesService>);
expect(await thrownAsync(() => new PlacesController(s).importGoogle(user, '5', 'http://x'))).toEqual({ status: 400, body: { error: 'List is empty' } });
expect(await thrownAsync(() => new PlacesController(s).importGoogle(user, '5', { url: 'http://x' }))).toEqual({ status: 400, body: { error: 'List is empty' } });
});
it('imports a naver list and returns the count + listName', async () => {
const s = svc({ importNaverList: vi.fn().mockResolvedValue({ places: [{ id: 1 }], listName: 'Trip', skipped: 2 }), broadcast: vi.fn() } as Partial<PlacesService>);
expect(await new PlacesController(s).importNaver(user, '5', 'http://x')).toEqual({ places: [{ id: 1 }], count: 1, listName: 'Trip', skipped: 2 });
expect(await new PlacesController(s).importNaver(user, '5', { url: 'http://x' })).toEqual({ places: [{ id: 1 }], count: 1, listName: 'Trip', skipped: 2 });
});
it('forwards the enrich flag + userId and broadcasts each imported place', async () => {
const importGoogleList = vi.fn().mockResolvedValue({ places: [{ id: 1 }, { id: 2 }], listName: 'L', skipped: 0 });
const broadcast = vi.fn();
const s = svc({ importGoogleList, broadcast } as Partial<PlacesService>);
expect(await new PlacesController(s).importGoogle(user, '5', 'http://x', 'true', 'sock')).toEqual({ places: [{ id: 1 }, { id: 2 }], count: 2, listName: 'L', skipped: 0 });
expect(await new PlacesController(s).importGoogle(user, '5', { url: 'http://x', enrich: true }, 'sock')).toEqual({ places: [{ id: 1 }, { id: 2 }], count: 2, listName: 'L', skipped: 0 });
expect(importGoogleList).toHaveBeenCalledWith('5', 'http://x', { enrich: true, userId: 1 });
expect(broadcast).toHaveBeenCalledTimes(2);
});
it('wraps a thrown Error in the provider-specific 400 (Google)', async () => {
const s = svc({ importGoogleList: vi.fn().mockRejectedValue(new Error('network down')) } as Partial<PlacesService>);
expect(await thrownAsync(() => new PlacesController(s).importGoogle(user, '5', 'http://x'))).toEqual({
expect(await thrownAsync(() => new PlacesController(s).importGoogle(user, '5', { url: 'http://x' }))).toEqual({
status: 400, body: { error: 'Failed to import Google Maps list. Make sure the list is shared publicly.' },
});
});
it('wraps a non-Error rejection in the provider-specific 400 (Naver)', async () => {
const s = svc({ importNaverList: vi.fn().mockRejectedValue('weird') } as Partial<PlacesService>);
expect(await thrownAsync(() => new PlacesController(s).importNaver(user, '5', 'http://x'))).toEqual({
expect(await thrownAsync(() => new PlacesController(s).importNaver(user, '5', { url: 'http://x' }))).toEqual({
status: 400, body: { error: 'Failed to import Naver Maps list. Make sure the list is shared publicly.' },
});
});
});
describe('POST /bulk-delete', () => {
it('400 when ids is not an array of numbers', () => {
expect(thrown(() => new PlacesController(svc()).bulkDelete(user, '5', ['a']))).toEqual({ status: 400, body: { error: 'ids must be an array of numbers' } });
});
// The legacy 'ids must be an array of numbers' 400 is gone:
// placeBulkDeleteRequestSchema types the array, so the pipe rejects a bad
// element before the handler runs.
it('returns empty for an empty list without touching the service', () => {
const removeMany = vi.fn();
expect(new PlacesController(svc({ removeMany } as Partial<PlacesService>)).bulkDelete(user, '5', [])).toEqual({ deleted: [], count: 0 });
expect(new PlacesController(svc({ removeMany } as Partial<PlacesService>)).bulkDelete(user, '5', { ids: [] })).toEqual({ deleted: [], count: 0 });
expect(removeMany).not.toHaveBeenCalled();
});
it('deletes, fires hooks + broadcasts per deleted id', () => {
const removeMany = vi.fn().mockReturnValue([1, 2]); const onDeleted = vi.fn(); const broadcast = vi.fn();
const s = svc({ removeMany, onDeleted, broadcast } as Partial<PlacesService>);
expect(new PlacesController(s).bulkDelete(user, '5', [1, 2], 'sock')).toEqual({ deleted: [1, 2], count: 2 });
const scopedIds = vi.fn().mockReturnValue([1, 2]);
const s = svc({ removeMany, onDeleted, broadcast, scopedIds } as Partial<PlacesService>);
expect(new PlacesController(s).bulkDelete(user, '5', { ids: [1, 2] }, 'sock')).toEqual({ deleted: [1, 2], count: 2 });
expect(onDeleted).toHaveBeenCalledTimes(2);
expect(broadcast).toHaveBeenCalledTimes(2);
});
// #1745: the hook keys on the place id alone, so an id from another trip
// would detach that trip's journey entries even though removeMany skips it.
it('fires the journey hook only for ids that belong to the trip, ahead of the delete', () => {
const removeMany = vi.fn().mockReturnValue([1]);
const scopedIds = vi.fn().mockReturnValue([1]);
const onDeleted = vi.fn();
const s = svc({ removeMany, scopedIds, onDeleted, broadcast: vi.fn() } as Partial<PlacesService>);
new PlacesController(s).bulkDelete(user, '5', { ids: [1, 99] });
expect(scopedIds).toHaveBeenCalledWith('5', [1, 99]);
expect(onDeleted).toHaveBeenCalledTimes(1);
expect(onDeleted).toHaveBeenCalledWith(1);
expect(onDeleted.mock.invocationCallOrder[0]).toBeLessThan(removeMany.mock.invocationCallOrder[0]);
});
});
describe('POST /bulk-update', () => {
@@ -195,9 +212,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
expect(thrown(() => new PlacesController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) })).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(thrown(() => new PlacesController(svc({ canEdit: vi.fn().mockReturnValue(false) })).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 403, body: { error: 'No permission' } });
});
it('400 when ids is not an array of numbers', () => {
expect(thrown(() => new PlacesController(svc()).bulkUpdate(user, '5', { ids: ['a'] }))).toEqual({ status: 400, body: { error: 'ids must be an array of numbers' } });
});
// Same as bulk-delete: placeBulkUpdateRequestSchema types `ids`, so the
// pipe owns that 400 now. `.min(1)` was deliberately left off the schema so
// the empty-list short-circuit below stays reachable.
it('400 when no patch field is present', () => {
expect(thrown(() => new PlacesController(svc()).bulkUpdate(user, '5', { ids: [1] }))).toEqual({ status: 400, body: { error: 'Provide at least one field to update' } });
});
@@ -281,12 +298,25 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
it('DELETE /:id fires the hook then 404 / success', () => {
const onDeleted = vi.fn();
expect(thrown(() => new PlacesController(svc({ remove: vi.fn().mockReturnValue(false), onDeleted } as Partial<PlacesService>)).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
const remove = vi.fn().mockReturnValue(false);
expect(thrown(() => new PlacesController(svc({ remove, onDeleted } as Partial<PlacesService>)).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(onDeleted).toHaveBeenCalledWith(9);
expect(onDeleted.mock.invocationCallOrder[0]).toBeLessThan(remove.mock.invocationCallOrder[0]);
const s = svc({ remove: vi.fn().mockReturnValue(true), broadcast: vi.fn() } as Partial<PlacesService>);
expect(new PlacesController(s).remove(user, '5', '9')).toEqual({ success: true });
});
// #1745: a place on another trip must 404 without the hook ever running —
// onPlaceDeleted keys on the place id alone, so it would detach that trip's
// journey entries.
it('DELETE /:id 404s a foreign place before the journey hook runs', () => {
const onDeleted = vi.fn(); const remove = vi.fn();
const s = svc({ get: vi.fn().mockReturnValue(null), onDeleted, remove } as Partial<PlacesService>);
expect(thrown(() => new PlacesController(s).remove(user, '5', '99'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(onDeleted).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
});
it('GET /:id/image maps service error + returns photos', async () => {
const s = svc({ searchImage: vi.fn().mockResolvedValue({ photos: [{ url: 'x' }] }) } as Partial<PlacesService>);
expect(await new PlacesController(s).image(user, '5', '9')).toEqual({ photos: [{ url: 'x' }] });
@@ -2,20 +2,14 @@
* Unit tests for the import-enrichment match selector (#886).
* Covers PENRICH-001 to PENRICH-004 — the coordinate-validation guard that
* prevents a name search from overwriting an imported place with the wrong POI.
*
* Moved from tests/unit/services/placeEnrichment.test.ts when the helper folded
* into the places domain: the selector is pure, so it now lives in
* places.helpers.ts and needs no DB/websocket/Maps stubbing at all.
*/
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect } from 'vitest';
// placeEnrichment pulls in the DB, websocket and the maps bridge at import time;
// stub them so the pure match selector can be tested in isolation.
vi.mock('../../../src/db/database', () => ({ db: {}, getPlaceWithTags: () => null }));
vi.mock('../../../src/websocket', () => ({ broadcast: () => {} }));
vi.mock('../../../src/nest/maps/maps.bridge', () => ({
getMapsKey: () => null,
searchPlaces: async () => ({ places: [], source: 'none' }),
getPlacePhoto: async () => ({ photoUrl: '', attribution: null }),
}));
import { pickEnrichmentMatch } from '../../../src/services/placeEnrichment';
import { pickEnrichmentMatch } from '../../../src/nest/places/places.helpers';
const target = { lat: 48.85, lng: 2.35 };
@@ -0,0 +1,169 @@
/**
* Unit tests for the pure places helpers (moved from
* tests/unit/services/kmzUnpack.test.ts when placeService went DI-native — the
* KMZ unpacker touches no DB, so it lives in places.helpers.ts).
*/
import { describe, it, expect, vi } from 'vitest';
import path from 'path';
import fs from 'fs';
vi.mock('../../../src/db/database', () => ({
db: { prepare: vi.fn() },
getPlaceWithTags: vi.fn(),
}));
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import {
COORD_DEDUP_TOLERANCE,
googleMapsFeatureIdFromItem,
googleMapsHexId,
isPlaceDuplicate,
KMZ_DECOMPRESSED_SIZE_LIMIT,
mapWithConcurrency,
trackInsertedInDedupSet,
trimOrNull,
unpackKmzToKml,
type DedupSet,
} from '../../../src/nest/places/places.helpers';
const KMZ_FIXTURE = path.join(__dirname, '../../fixtures/test.kmz');
describe('unpackKmzToKml', () => {
it('extracts the KML entry from a valid KMZ', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
const kmlBuffer = await unpackKmzToKml(kmzBuffer);
expect(kmlBuffer.length).toBeGreaterThan(0);
expect(kmlBuffer.toString('utf-8')).toContain('<kml');
});
it('rejects a KMZ whose KML entry exceeds the decompressed size limit', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
// test.kmz contains a KML with uncompressedSize 634 — set limit to 1 byte
await expect(unpackKmzToKml(kmzBuffer, 1)).rejects.toThrow('exceeds the maximum allowed decompressed size');
});
it('rejects a KMZ that contains no KML file', async () => {
// Craft a minimal ZIP containing only a non-KML entry using raw ZIP bytes
// We use the test GPX fixture (a real file) re-zipped via Node's zlib/archiver
// Simplest: a KMZ whose only file has a .txt extension
const Archiver = await import('archiver');
const archiver = Archiver.default;
const { PassThrough } = await import('stream');
const chunks: Buffer[] = [];
const output = new PassThrough();
output.on('data', (chunk) => chunks.push(chunk));
const archive = archiver('zip', { zlib: { level: 1 } });
archive.pipe(output);
archive.append(Buffer.from('not a kml'), { name: 'data.txt' });
await archive.finalize();
const zipBuffer = Buffer.concat(chunks);
await expect(unpackKmzToKml(zipBuffer)).rejects.toThrow('does not contain a KML file');
});
it('rejects a buffer that is not a valid ZIP archive', async () => {
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toThrow('Invalid KMZ archive');
});
it('exports KMZ_DECOMPRESSED_SIZE_LIMIT as 50 MB', () => {
expect(KMZ_DECOMPRESSED_SIZE_LIMIT).toBe(50 * 1024 * 1024);
});
});
// ── Import dedup predicates ───────────────────────────────────────────────────
const emptyDedup = (): DedupSet => ({ names: new Set(), coords: [] });
describe('isPlaceDuplicate / trackInsertedInDedupSet', () => {
it('matches a named place case- and whitespace-insensitively', () => {
const dedup = emptyDedup();
trackInsertedInDedupSet({ name: ' Eiffel Tower ', lat: 1, lng: 2 }, dedup);
expect(isPlaceDuplicate({ name: 'eiffel tower', lat: null, lng: null }, dedup)).toBe(true);
expect(isPlaceDuplicate({ name: 'Louvre', lat: null, lng: null }, dedup)).toBe(false);
});
it('falls back to coordinate proximity for unnamed places', () => {
const dedup = emptyDedup();
// No name — tracked by coordinates instead.
trackInsertedInDedupSet({ name: null, lat: 48.85, lng: 2.35 }, dedup);
expect(dedup.names.size).toBe(0);
expect(isPlaceDuplicate({ name: undefined, lat: 48.85 + COORD_DEDUP_TOLERANCE / 2, lng: 2.35 }, dedup)).toBe(true);
expect(isPlaceDuplicate({ name: undefined, lat: 48.9, lng: 2.35 }, dedup)).toBe(false);
});
it('a named candidate never falls through to the coordinate check', () => {
const dedup = emptyDedup();
trackInsertedInDedupSet({ name: null, lat: 48.85, lng: 2.35 }, dedup);
// Same spot, but it carries a name — name lookup misses, so it is not a dup.
expect(isPlaceDuplicate({ name: 'Named', lat: 48.85, lng: 2.35 }, dedup)).toBe(false);
});
it('a candidate with neither a name nor coordinates is never a duplicate', () => {
expect(isPlaceDuplicate({ name: null, lat: null, lng: null }, emptyDedup())).toBe(false);
});
});
// ── Google Maps feature ids ───────────────────────────────────────────────────
describe('googleMapsHexId / googleMapsFeatureIdFromItem', () => {
it('passes an already-hex id through lower-cased', () => {
expect(googleMapsHexId('0x882BF179E806D471')).toBe('0x882bf179e806d471');
});
it("converts Google's signed 64-bit decimals to unsigned hex", () => {
expect(googleMapsHexId('-8634542354666695567')).toBe('0x882bf179e806d471');
expect(googleMapsHexId(255)).toBe('0xff');
});
it('rejects anything that is not a hex or decimal id', () => {
expect(googleMapsHexId('not-an-id')).toBeNull();
expect(googleMapsHexId(null)).toBeNull();
expect(googleMapsHexId({})).toBeNull();
});
it('reads the ftid pair from either item slot, else null', () => {
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1', '0x2']]])).toBe('0x1:0x2');
expect(googleMapsFeatureIdFromItem([null, null, null, null, null, null, null, [null, ['0x3', '0x4']]])).toBe('0x3:0x4');
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1']]])).toBeNull();
expect(googleMapsFeatureIdFromItem('not an array')).toBeNull();
});
});
// ── Enrichment plumbing ───────────────────────────────────────────────────────
describe('mapWithConcurrency / trimOrNull', () => {
it('visits every item and never runs more than `limit` at once', async () => {
const items = [1, 2, 3, 4, 5, 6, 7];
const seen: number[] = [];
let inFlight = 0;
let peak = 0;
await mapWithConcurrency(items, 3, async (n) => {
inFlight += 1;
peak = Math.max(peak, inFlight);
await Promise.resolve();
seen.push(n);
inFlight -= 1;
});
expect(seen.sort((a, b) => a - b)).toEqual(items);
expect(peak).toBeLessThanOrEqual(3);
});
it('is a no-op for an empty list', async () => {
const fn = vi.fn();
await mapWithConcurrency([], 3, fn);
expect(fn).not.toHaveBeenCalled();
});
it('trimOrNull keeps real strings and nulls everything else', () => {
expect(trimOrNull(' Paris ')).toBe('Paris');
expect(trimOrNull(' ')).toBeNull();
expect(trimOrNull(42)).toBeNull();
expect(trimOrNull(undefined)).toBeNull();
});
});
File diff suppressed because it is too large Load Diff
@@ -63,6 +63,8 @@ import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.se
import { CollabService } from '../../../src/nest/collab/collab.service';
import { VacayService } from '../../../src/nest/vacay/vacay.service';
import { TripsService } from '../../../src/nest/trips/trips.service';
import { PlacesService } from '../../../src/nest/places/places.service';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { getTripOwner, listMembers as bridgeListMembers } from '../../../src/nest/trips/trips.bridge';
import fs from 'fs';
@@ -71,6 +73,7 @@ import fs from 'fs';
const dbs = () => new DatabaseService(testDb);
const budgetSvc = new BudgetService(dbs(), new PermissionsService(dbs()), new ExchangeRatesService(), new RealtimeService());
const daysSvc = new DaysService(dbs(), new PermissionsService(dbs()), new RealtimeService());
const placesSvc = new PlacesService(dbs(), new PermissionsService(dbs()), new RealtimeService(), new MapsService(dbs()));
const createAccommodation = daysSvc.createAccommodation.bind(daysSvc);
const svc = new TripsService(
@@ -85,6 +88,7 @@ const svc = new TripsService(
new CollabService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
new VacayService(dbs(), new RealtimeService()),
new RealtimeService(),
placesSvc,
);
beforeAll(() => {
@@ -1200,6 +1204,7 @@ describe('quirk fixes', () => {
new CollabService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
new VacayService(dbs(), new RealtimeService()),
new RealtimeService(),
placesSvc,
);
}
@@ -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)
* permissions/trips/places)
* are constructor-injected stubs; legacy services/* domains stay path-mocked
* until their own DI migration lands.
*/
@@ -75,17 +75,22 @@ const permissionsStub = { checkPermission } as unknown as PermissionsService;
const exchangeRatesStub = {
getRates: vi.fn(async (base: string) => ({ [base]: 1, USD: 1.08, GBP: 0.85 })),
} as unknown as ExchangeRatesService;
vi.mock('../../../src/services/placeService', () => ({
createPlace: vi.fn((tid: string, body: Record<string, unknown>) => ({ id: 10, trip_id: Number(tid), ...body })),
updatePlace: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
deletePlace: vi.fn((_tid: string, pid: string) => pid !== '99'),
// Places are a constructor-injected stub since the place fold (same behaviors
// as the old services/placeService path mock, mapped onto the PlacesService
// method names). `remove` is asserted by invocation order against the journey
// hook, so it stays a vi.fn.
const removePlaceStub = vi.fn((_tid: string, pid: string) => pid !== '99');
const placesStub = {
create: vi.fn((tid: string, body: Record<string, unknown>) => ({ id: 10, trip_id: Number(tid), ...body })),
update: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
remove: removePlaceStub,
// Trip-scoped read the delete path uses to reject a foreign id before the
// journey hook runs — place 99 belongs to another trip.
getPlace: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
// trips.service (loaded for real since the trip fold) imports listPlaces for
// its offline bundle — the mock must carry every named export it pulls.
listPlaces: vi.fn(() => []),
}));
get: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
// trips.service (loaded for real since the trip fold) injects this for its
// offline bundle — the stub must carry every method it calls.
list: vi.fn(() => []),
} as unknown as PlacesService;
// Days are a constructor-injected stub (same behaviors as the old path mock,
// mapped onto the DaysService method names).
const daysStub = {
@@ -297,7 +302,6 @@ import { PluginHostDepsFactory, type PluginCallRouter } from '../../../src/nest/
import { getPluginDataDb, closePluginDataDb } from '../../../src/nest/plugins/host/plugin-host-state';
import { db as mockDb } from '../../../src/db/database';
import { onPlaceCreated, onPlaceUpdated, onPlaceDeleted } from '../../../src/services/journeyService';
import { deletePlace as deletePlaceSvc } from '../../../src/services/placeService';
import type { BudgetService } from '../../../src/nest/budget/budget.service';
import type { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import type { ReservationsService } from '../../../src/nest/reservations/reservations.service';
@@ -314,6 +318,7 @@ import type { FilesService } from '../../../src/nest/files/files.service';
import type { CollabService } from '../../../src/nest/collab/collab.service';
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 { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { NotFoundError, ValidationError } from '../../../src/nest/trips/trips.service';
@@ -336,7 +341,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);
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);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
@@ -443,7 +448,7 @@ describe('host-deps factory — planner write + metadata deps', () => {
const created = vi.mocked(onPlaceCreated);
const updated = vi.mocked(onPlaceUpdated);
const deleted = vi.mocked(onPlaceDeleted);
const removePlace = vi.mocked(deletePlaceSvc);
const removePlace = removePlaceStub;
[created, updated, deleted, removePlace].forEach((m) => m.mockClear());
expect((await call(h, 'places.create', { tripId: 1, input: { name: 'P' } })).ok).toBe(true);
@@ -38,14 +38,16 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { updatePlace, createPlace } from '../../../src/services/placeService';
import { isUpdateConflict } from '../../../src/services/conflictResult';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { PlacesService } from '../../../src/nest/places/places.service';
import { MapsService } from '../../../src/nest/maps/maps.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
const packing = new PackingService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService());
const places = new PlacesService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService(), new MapsService(new DatabaseService(testDb)));
beforeAll(() => {
createTables(testDb);
@@ -61,17 +63,17 @@ afterAll(() => {
});
function freshPlace(tripId: number) {
const place = createPlace(String(tripId), { name: 'Original' }) as { id: number; updated_at: string };
const place = places.create(String(tripId), { name: 'Original' }) as unknown as { id: number; updated_at: string };
return place;
}
describe('updatePlace — optimistic concurrency', () => {
describe('PlacesService.update — optimistic concurrency', () => {
it('updates normally when no If-Match token is sent (back-compat)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' });
const result = places.update(String(trip.id), String(place.id), { name: 'Edited' });
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
@@ -81,7 +83,7 @@ describe('updatePlace — optimistic concurrency', () => {
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
const result = places.update(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
@@ -91,7 +93,7 @@ describe('updatePlace — optimistic concurrency', () => {
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = updatePlace(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
const result = places.update(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
expect(isUpdateConflict(result)).toBe(true);
if (isUpdateConflict(result)) {
expect((result.server as { name: string }).name).toBe('Original');
@@ -104,7 +106,7 @@ describe('updatePlace — optimistic concurrency', () => {
it('returns null for a place that does not exist', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlace(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
expect(places.update(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
});
});
@@ -1,61 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import path from 'path';
import fs from 'fs';
vi.mock('../../../src/db/database', () => ({
db: { prepare: vi.fn() },
getPlaceWithTags: vi.fn(),
}));
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { unpackKmzToKml, KMZ_DECOMPRESSED_SIZE_LIMIT } from '../../../src/services/placeService';
const KMZ_FIXTURE = path.join(__dirname, '../../fixtures/test.kmz');
describe('unpackKmzToKml', () => {
it('extracts the KML entry from a valid KMZ', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
const kmlBuffer = await unpackKmzToKml(kmzBuffer);
expect(kmlBuffer.length).toBeGreaterThan(0);
expect(kmlBuffer.toString('utf-8')).toContain('<kml');
});
it('rejects a KMZ whose KML entry exceeds the decompressed size limit', async () => {
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
// test.kmz contains a KML with uncompressedSize 634 — set limit to 1 byte
await expect(unpackKmzToKml(kmzBuffer, 1)).rejects.toThrow('exceeds the maximum allowed decompressed size');
});
it('rejects a KMZ that contains no KML file', async () => {
// Craft a minimal ZIP containing only a non-KML entry using raw ZIP bytes
// We use the test GPX fixture (a real file) re-zipped via Node's zlib/archiver
// Simplest: a KMZ whose only file has a .txt extension
const Archiver = await import('archiver');
const archiver = Archiver.default;
const { PassThrough } = await import('stream');
const chunks: Buffer[] = [];
const output = new PassThrough();
output.on('data', (chunk) => chunks.push(chunk));
const archive = archiver('zip', { zlib: { level: 1 } });
archive.pipe(output);
archive.append(Buffer.from('not a kml'), { name: 'data.txt' });
await archive.finalize();
const zipBuffer = Buffer.concat(chunks);
await expect(unpackKmzToKml(zipBuffer)).rejects.toThrow('does not contain a KML file');
});
it('rejects a buffer that is not a valid ZIP archive', async () => {
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toThrow('Invalid KMZ archive');
});
it('exports KMZ_DECOMPRESSED_SIZE_LIMIT as 50 MB', () => {
expect(KMZ_DECOMPRESSED_SIZE_LIMIT).toBe(50 * 1024 * 1024);
});
});
@@ -1,840 +0,0 @@
/**
* Unit tests for placeService — PLACE-SVC-001 through PLACE-SVC-025.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
* External fetches are mocked where needed.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
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: any) => {
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-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// Spy on the photo-cache reclaim hook so delete tests assert the wiring without
// touching disk. The removal logic itself is covered in placePhotoCache.test.ts.
const { removeIfUnreferencedSpy } = vi.hoisted(() => ({ removeIfUnreferencedSpy: vi.fn() }));
vi.mock('../../../src/services/placePhotoCache', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/services/placePhotoCache')>()),
removeIfUnreferenced: removeIfUnreferencedSpy,
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPlace, createCategory, createTag } from '../../helpers/factories';
import path from 'path';
import fs from 'fs';
import { listPlaces, createPlace as svcCreatePlace, getPlace, updatePlace, updatePlacesMany, deletePlace, importGpx, importKmlPlaces, importGoogleList, searchPlaceImage, ratePlace } from '../../../src/services/placeService';
import { PLACE_IMAGES_DIR } from '../../../src/services/placeImage';
const GPX_FIXTURE = path.join(__dirname, '../../fixtures/test.gpx');
const KML_FIXTURE = path.join(__dirname, '../../fixtures/test.kml');
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── listPlaces ────────────────────────────────────────────────────────────────
describe('listPlaces', () => {
it('PLACE-SVC-001 — returns empty array when trip has no places', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(listPlaces(String(trip.id), {})).toEqual([]);
});
it('PLACE-SVC-002 — returns all places for a trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Alpha' });
createPlace(testDb, trip.id, { name: 'Beta' });
const places = listPlaces(String(trip.id), {}) as any[];
expect(places).toHaveLength(2);
});
it('PLACE-SVC-003 — does not return places from other trips', () => {
const { user } = createUser(testDb);
const t1 = createTrip(testDb, user.id);
const t2 = createTrip(testDb, user.id);
createPlace(testDb, t1.id, { name: 'T1 Place' });
createPlace(testDb, t2.id, { name: 'T2 Place' });
const places = listPlaces(String(t1.id), {}) as any[];
expect(places).toHaveLength(1);
expect(places[0].name).toBe('T1 Place');
});
it('PLACE-SVC-004 — filters by search term (name)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
createPlace(testDb, trip.id, { name: 'Louvre Museum' });
const places = listPlaces(String(trip.id), { search: 'Eiffel' }) as any[];
expect(places).toHaveLength(1);
expect(places[0].name).toBe('Eiffel Tower');
});
it('PLACE-SVC-005 — attaches tags array to each place (empty when none)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPlace(testDb, trip.id, { name: 'No Tags' });
const places = listPlaces(String(trip.id), {}) as any[];
expect(Array.isArray(places[0].tags)).toBe(true);
expect(places[0].tags).toHaveLength(0);
});
it('PLACE-SVC-006 — attaches category object when place has a category', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const cat = createCategory(testDb, { name: 'Museum', user_id: user.id }) as any;
const place = createPlace(testDb, trip.id, { name: 'Art Museum' }) as any;
testDb.prepare('UPDATE places SET category_id = ? WHERE id = ?').run(cat.id, place.id);
const places = listPlaces(String(trip.id), {}) as any[];
expect(places[0].category).toBeDefined();
expect(places[0].category.name).toBe('Museum');
});
});
// ── createPlace (via service) ─────────────────────────────────────────────────
describe('createPlace (service)', () => {
it('PLACE-SVC-007 — creates a place and returns it with tags array', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = svcCreatePlace(String(trip.id), { name: 'New Place', lat: 48.8, lng: 2.3 }) as any;
expect(place).toBeDefined();
expect(place.name).toBe('New Place');
expect(Array.isArray(place.tags)).toBe(true);
});
it('PLACE-SVC-008 — creates a place with tags', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag = createTag(testDb, user.id, { name: 'Highlight' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Tagged Place', tags: [tag.id] }) as any;
expect(place.tags).toHaveLength(1);
expect(place.tags[0].id).toBe(tag.id);
});
it('PLACE-SVC-009 — place is associated with correct trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = svcCreatePlace(String(trip.id), { name: 'My Place' }) as any;
const row = testDb.prepare('SELECT trip_id FROM places WHERE id = ?').get(place.id) as any;
expect(row.trip_id).toBe(trip.id);
});
});
// ── getPlace ──────────────────────────────────────────────────────────────────
describe('getPlace', () => {
it('PLACE-SVC-010 — returns the place when tripId and placeId match', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Find Me' }) as any;
const found = getPlace(String(trip.id), String(place.id)) as any;
expect(found).toBeDefined();
expect(found.name).toBe('Find Me');
});
it('PLACE-SVC-011 — returns null when place belongs to different trip', () => {
const { user } = createUser(testDb);
const t1 = createTrip(testDb, user.id);
const t2 = createTrip(testDb, user.id);
const place = createPlace(testDb, t1.id, { name: 'T1 Place' }) as any;
expect(getPlace(String(t2.id), String(place.id))).toBeNull();
});
it('PLACE-SVC-012 — returns null for non-existent placeId', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getPlace(String(trip.id), '99999')).toBeNull();
});
});
// ── updatePlace ───────────────────────────────────────────────────────────────
describe('updatePlace', () => {
it('PLACE-SVC-013 — updates place name and lat/lng', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Old', lat: 0, lng: 0 }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { name: 'New', lat: 48.8, lng: 2.3 }) as any;
expect(updated.name).toBe('New');
expect(updated.lat).toBe(48.8);
expect(updated.lng).toBe(2.3);
});
it('PLACE-SVC-014 — returns null for non-existent place', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlace(String(trip.id), '99999', { name: 'Ghost' })).toBeNull();
});
it('PLACE-SVC-015 — updates tags (replaces old set)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag1 = createTag(testDb, user.id, { name: 'Old Tag' }) as any;
const tag2 = createTag(testDb, user.id, { name: 'New Tag' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Taggable', tags: [tag1.id] }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { tags: [tag2.id] }) as any;
expect(updated.tags).toHaveLength(1);
expect(updated.tags[0].id).toBe(tag2.id);
});
it('PLACE-SVC-016 — clears tags when tags: [] is passed', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag = createTag(testDb, user.id, { name: 'Temp' }) as any;
const place = svcCreatePlace(String(trip.id), { name: 'Untaggable', tags: [tag.id] }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { tags: [] }) as any;
expect(updated.tags).toHaveLength(0);
});
// ── Track colour (#776) ─────────────────────────────────────────────────────
it('PLACE-SVC-052 — stores a picked route_color', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
const updated = updatePlace(String(trip.id), String(place.id), { route_color: '#e11d48' }) as any;
expect(updated.route_color).toBe('#e11d48');
});
it('PLACE-SVC-053 — an explicit null clears it again (the reset to auto)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
updatePlace(String(trip.id), String(place.id), { route_color: '#e11d48' });
// Guards the COALESCE trap: name/currency/transport_mode can never be
// emptied, and route_color built that way would be a one-way door.
const cleared = updatePlace(String(trip.id), String(place.id), { route_color: null }) as any;
expect(cleared.route_color).toBeNull();
});
it('PLACE-SVC-054 — an unrelated update leaves the colour alone', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
updatePlace(String(trip.id), String(place.id), { route_color: '#059669' });
const renamed = updatePlace(String(trip.id), String(place.id), { name: 'Hike' }) as any;
expect(renamed.name).toBe('Hike');
expect(renamed.route_color).toBe('#059669');
});
it('PLACE-SVC-055 — createPlace carries geometry and colour instead of dropping them', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const created = svcCreatePlace(String(trip.id), {
name: 'Restored track',
route_geometry: '[[48.0,2.0],[49.0,3.0]]',
route_color: '#7c3aed',
}) as any;
expect(created.route_geometry).toBe('[[48.0,2.0],[49.0,3.0]]');
expect(created.route_color).toBe('#7c3aed');
});
});
// ── updatePlacesMany ────────────────────────────────────────────────────────────
describe('updatePlacesMany', () => {
it('PLACE-SVC-039 — applies the same fields to many places, preserving the rest', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createPlace(testDb, trip.id, { name: 'A' }) as any;
const b = createPlace(testDb, trip.id, { name: 'B' }) as any;
const c = createPlace(testDb, trip.id, { name: 'C' }) as any;
const updated = updatePlacesMany(String(trip.id), [a.id, b.id, c.id], { notes: 'visited', transport_mode: 'walking' });
expect(updated).toHaveLength(3);
for (const p of updated) {
expect((p as any).notes).toBe('visited');
expect((p as any).transport_mode).toBe('walking');
}
// Only the provided fields change — names are untouched.
expect(updated.map(p => (p as any).name).sort()).toEqual(['A', 'B', 'C']);
});
it('PLACE-SVC-040 — skips ids that are not in the trip and reports the rest', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const mine = createPlace(testDb, trip.id, { name: 'Mine' }) as any;
const foreign = createPlace(testDb, other.id, { name: 'Foreign' }) as any;
const updated = updatePlacesMany(String(trip.id), [mine.id, foreign.id, 99999], { notes: 'tagged' });
expect(updated).toHaveLength(1);
expect((updated[0] as any).id).toBe(mine.id);
// The place from the other trip stays untouched.
expect((getPlace(String(other.id), String(foreign.id)) as any).notes).toBeNull();
});
it('PLACE-SVC-041 — returns [] for an empty id list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(updatePlacesMany(String(trip.id), [], { notes: 'x' })).toEqual([]);
});
});
// ── deletePlace ───────────────────────────────────────────────────────────────
describe('deletePlace', () => {
it('PLACE-SVC-017 — deletes a place and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'To Delete' }) as any;
expect(deletePlace(String(trip.id), String(place.id))).toBe(true);
expect(getPlace(String(trip.id), String(place.id))).toBeNull();
});
it('PLACE-SVC-018 — returns false for non-existent place', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(deletePlace(String(trip.id), '99999')).toBe(false);
});
it('PLACE-SVC-019 — deleting one place does not remove others', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const p1 = createPlace(testDb, trip.id, { name: 'Keep' }) as any;
const p2 = createPlace(testDb, trip.id, { name: 'Remove' }) as any;
deletePlace(String(trip.id), String(p2.id));
const remaining = listPlaces(String(trip.id), {}) as any[];
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe(p1.id);
});
it('PLACE-SVC-019b — reclaims the photo cache for the deleted place', () => {
removeIfUnreferencedSpy.mockClear();
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'With Photo' }) as any;
testDb.prepare('UPDATE places SET google_place_id = ? WHERE id = ?').run('ChIJgid', place.id);
deletePlace(String(trip.id), String(place.id));
expect(removeIfUnreferencedSpy).toHaveBeenCalledWith('ChIJgid');
});
});
// ── importGpx ─────────────────────────────────────────────────────────────────
describe('importGpx', () => {
it('PLACE-SVC-020 — returns null when buffer has no <gpx> root', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = importGpx(String(trip.id), Buffer.from('<not-gpx/>'));
expect(result).toBeNull();
});
it('PLACE-SVC-021 — imports <wpt> waypoints as places', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<wpt lat="48.8566" lon="2.3522"><name>Paris</name></wpt>
<wpt lat="51.5074" lon="-0.1278"><name>London</name></wpt>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(2);
expect(result.places[0].name).toBe('Paris');
expect(result.places[1].name).toBe('London');
});
it('PLACE-SVC-022 — imports <rte> as a single polyline-place with routeGeometry', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<rte>
<name>My Route</name>
<rtept lat="48.8566" lon="2.3522"><name>Start</name></rtept>
<rtept lat="51.5074" lon="-0.1278"><name>End</name></rtept>
</rte>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('My Route');
expect(result.places[0].lat).toBe(48.8566);
expect(result.places[0].lng).toBe(2.3522);
expect(result.places[0].route_geometry).toBeTruthy();
const coords = JSON.parse(result.places[0].route_geometry);
expect(coords).toHaveLength(2);
});
it('PLACE-SVC-023 — imports <trk> track as a single place with routeGeometry', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk>
<name>My Track</name>
<trkseg>
<trkpt lat="48.8566" lon="2.3522"><ele>100</ele></trkpt>
<trkpt lat="48.8570" lon="2.3530"><ele>102</ele></trkpt>
</trkseg>
</trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('My Track');
const geometry = JSON.parse(result.places[0].route_geometry);
expect(Array.isArray(geometry)).toBe(true);
expect(geometry).toHaveLength(2);
});
it('PLACE-SVC-024 — <wpt> and <trk> together: waypoints plus track appended', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<wpt lat="48.8566" lon="2.3522"><name>POI</name></wpt>
<trk>
<name>Track</name>
<trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg>
</trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
// 1 wpt + 1 trk
expect(result.places).toHaveLength(2);
const trackPlace = result.places.find((p: any) => p.name === 'Track') as any;
expect(trackPlace).toBeDefined();
const geometry = JSON.parse(trackPlace.route_geometry);
expect(geometry).toHaveLength(2);
});
it('PLACE-SVC-025 — returns null when GPX has no usable elements', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1"></gpx>`);
const result = importGpx(String(trip.id), gpx);
expect(result).toBeNull();
});
it('PLACE-SVC-037 — multiple unnamed tracks in one file get distinct names instead of collapsing to one', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
<trk><trkseg>
<trkpt lat="40.0000" lon="-3.0000"></trkpt>
<trkpt lat="40.1000" lon="-3.1000"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx) as any;
expect(result.places).toHaveLength(2);
const names = result.places.map((p: any) => p.name);
expect(new Set(names).size).toBe(2);
});
it('PLACE-SVC-038 — unnamed tracks fall back to the source filename', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const gpx = Buffer.from(`<?xml version="1.0"?><gpx version="1.1">
<trk><trkseg>
<trkpt lat="48.8566" lon="2.3522"></trkpt>
<trkpt lat="48.8570" lon="2.3530"></trkpt>
</trkseg></trk>
</gpx>`);
const result = importGpx(String(trip.id), gpx, { defaultName: 'morning-hike.gpx' }) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].name).toBe('morning-hike');
});
});
// ── importGoogleList ──────────────────────────────────────────────────────────
describe('importGoogleList', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('PLACE-SVC-026 — returns error when list ID cannot be extracted from URL', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await importGoogleList(String(trip.id), 'https://example.com/no-id-here') as any;
expect(result.error).toMatch(/Could not extract list ID/);
expect(result.status).toBe(400);
});
it('PLACE-SVC-026b — a single-place link gives a guiding error instead of the generic one (#1304)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const url = 'https://www.google.com/maps/place/Eiffel+Tower/@48.8584,2.2945,17z/data=!3m1';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.status).toBe(400);
expect(result.error).toMatch(/single place/i);
});
it('PLACE-SVC-027 — returns error when Google Maps API responds with non-ok status', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, text: async () => '', status: 502 }));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.error).toMatch(/Failed to fetch list/);
expect(result.status).toBe(502);
});
it('PLACE-SVC-028 — imports places from a valid Google Maps list response', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, null, [null, null, 48.8566, 2.3522]], 'Paris', null],
[null, [null, null, null, null, null, [null, null, 51.5074, -0.1278]], 'London', 'Great city'],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.listName).toBe('My Test List');
expect(result.places).toHaveLength(2);
expect(result.places[0].name).toBe('Paris');
expect(result.places[1].name).toBe('London');
});
it('PLACE-SVC-028b — stores a Google Maps ftid separately from google_place_id', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, '878 Weber St N', [null, null, 43.5118527, -80.5542617], ['-8634542354666695567', '-8822026229683971437']], "St. Jacobs Farmers' Market"],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.places).toHaveLength(1);
expect(result.places[0].google_place_id).toBeNull();
expect(result.places[0].google_ftid).toBe('0x882bf179e806d471:0x8591dde29c821a93');
});
it('PLACE-SVC-028c — backfills google_ftid when re-import skips a duplicate', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const existing = createPlace(testDb, trip.id, {
name: "St. Jacobs Farmers' Market",
lat: 43.5118527,
lng: -80.5542617,
}) as any;
const listPayload = [
[null, null, null, null, 'My Test List', null, null, null, [
[null, [null, null, null, null, '878 Weber St N', [null, null, 43.5118527, -80.5542617], ['-8634542354666695567', '-8822026229683971437']], "St. Jacobs Farmers' Market"],
]],
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
const row = testDb.prepare('SELECT google_place_id, google_ftid FROM places WHERE id = ?').get(existing.id) as any;
expect(result.places).toHaveLength(0);
expect(result.skipped).toBe(1);
expect(row.google_place_id).toBeNull();
expect(row.google_ftid).toBe('0x882bf179e806d471:0x8591dde29c821a93');
});
it('PLACE-SVC-029 — returns error when list items array is empty', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const listPayload = [[null, null, null, null, 'Empty List', null, null, null, []]];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
text: async () => 'prefix\n' + JSON.stringify(listPayload),
}));
const url = 'https://www.google.com/maps/placelists/list/ABC123DEF456';
const result = await importGoogleList(String(trip.id), url) as any;
expect(result.error).toBeDefined();
expect(result.status).toBe(400);
});
});
// ── searchPlaceImage ──────────────────────────────────────────────────────────
describe('searchPlaceImage', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('PLACE-SVC-030 — returns 404 when place does not exist', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = await searchPlaceImage(String(trip.id), '99999', user.id) as any;
expect(result.error).toBeDefined();
expect(result.status).toBe(404);
});
it('PLACE-SVC-031 — searches Unsplash without a stored API key', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' }) as any;
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
results: [
{ id: 'photo1', urls: { regular: 'https://img.example.com/1', thumb: 'https://img.example.com/t1' }, description: 'Tower', user: { name: 'Photographer' }, links: { html: 'https://unsplash.com/1' } },
],
}),
status: 200,
}));
const result = await searchPlaceImage(String(trip.id), String(place.id), user.id) as any;
expect(result.photos).toHaveLength(1);
const [url] = (fetch as any).mock.calls[0];
expect(url).toContain('https://unsplash.com/napi/search/photos?');
expect(url).not.toContain('client_id=');
});
it('PLACE-SVC-032 — returns photos when Unsplash API responds successfully', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' }) as any;
const mockPhotos = [
{ id: 'photo1', urls: { regular: 'https://img.example.com/1', thumb: 'https://img.example.com/t1' }, description: 'Tower', user: { name: 'Photographer' }, links: { html: 'https://unsplash.com/1' } },
];
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ results: mockPhotos }),
status: 200,
}));
const result = await searchPlaceImage(String(trip.id), String(place.id), user.id) as any;
expect(result.photos).toHaveLength(1);
expect(result.photos[0].id).toBe('photo1');
expect(result.photos[0].url).toBe('https://img.example.com/1');
expect(result.photos[0].photographer).toBe('Photographer');
});
});
// ── Import deduplication ──────────────────────────────────────────────────────
describe('importGpx deduplication', () => {
it('PLACE-SVC-033 — skips waypoints already in trip by name', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(GPX_FIXTURE);
// First import
const first = importGpx(String(trip.id), buf) as any;
expect(first.count).toBeGreaterThan(0);
// Second import — all names already present, nothing new created
const second = importGpx(String(trip.id), buf) as any;
expect(second.count).toBe(0);
expect(second.skipped).toBe(first.count);
// Total places in DB should equal first import count
const total = (listPlaces(String(trip.id), {}) as any[]).length;
expect(total).toBe(first.count);
});
it('PLACE-SVC-034 — imports new places while skipping existing ones', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(GPX_FIXTURE);
const first = importGpx(String(trip.id), buf) as any;
// Manually add a brand-new place so total > first.count
createPlace(testDb, trip.id, { name: 'Unique Extra Place', lat: 99, lng: 99 });
// Re-import: the fixture places are skipped, the extra place remains untouched
const second = importGpx(String(trip.id), buf) as any;
expect(second.count).toBe(0);
const total = (listPlaces(String(trip.id), {}) as any[]).length;
expect(total).toBe(first.count + 1);
});
});
describe('importKmlPlaces deduplication', () => {
it('PLACE-SVC-035 — skips placemarks already in trip by name', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const buf = fs.readFileSync(KML_FIXTURE);
const first = importKmlPlaces(String(trip.id), buf);
expect(first.count).toBeGreaterThan(0);
const second = importKmlPlaces(String(trip.id), buf);
expect(second.count).toBe(0);
expect(second.summary.skippedCount).toBeGreaterThanOrEqual(first.count);
expect(second.summary.warnings.some((w: string) => w.includes('skipped'))).toBe(true);
});
it('PLACE-SVC-036 — deduplicates within the same file (intra-batch)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Craft a KML with two placemarks sharing the same name
const kml = Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2"><Document>
<Placemark><name>Dupe Place</name><Point><coordinates>2.0,48.0,0</coordinates></Point></Placemark>
<Placemark><name>Dupe Place</name><Point><coordinates>2.1,48.1,0</coordinates></Point></Placemark>
</Document></kml>`);
const result = importKmlPlaces(String(trip.id), kml);
expect(result.count).toBe(1);
expect(result.summary.skippedCount).toBe(1);
});
});
// ── Custom place image reclaim (#1136) ──────────────────────────────────────────
describe('custom place image reclaim', () => {
function writePlaceImage(name: string): string {
fs.mkdirSync(PLACE_IMAGES_DIR, { recursive: true });
const filePath = path.join(PLACE_IMAGES_DIR, name);
fs.writeFileSync(filePath, 'jpeg-bytes');
return filePath;
}
it('PLACE-SVC-046 — replacing image_url unlinks the previous upload once unreferenced', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
const fileA = writePlaceImage('svc-replace-a.jpg');
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-replace-a.jpg', place.id);
expect(fs.existsSync(fileA)).toBe(true);
updatePlace(String(trip.id), String(place.id), { image_url: '/uploads/places/svc-replace-b.jpg' });
expect(fs.existsSync(fileA)).toBe(false);
});
it('PLACE-SVC-047 — clearing image_url to null unlinks the previous upload', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
const fileA = writePlaceImage('svc-clear.jpg');
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-clear.jpg', place.id);
expect(fs.existsSync(fileA)).toBe(true);
updatePlace(String(trip.id), String(place.id), { image_url: null } as any);
expect(fs.existsSync(fileA)).toBe(false);
});
it('PLACE-SVC-048 — deletePlace unlinks the uploaded image', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
const fileA = writePlaceImage('svc-delete.jpg');
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-delete.jpg', place.id);
expect(fs.existsSync(fileA)).toBe(true);
deletePlace(String(trip.id), String(place.id));
expect(fs.existsSync(fileA)).toBe(false);
});
it('PLACE-SVC-049 — a collection_places reference keeps the file when the trip place is deleted', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Shared Photo' }) as any;
const fileA = writePlaceImage('svc-shared.jpg');
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-shared.jpg', place.id);
// A saved-place in a collection holds the same uploaded file — the ref-count guard must protect it.
const col = testDb.prepare('INSERT INTO collections (owner_id, name) VALUES (?, ?)').run(user.id, 'Saved');
testDb.prepare('INSERT INTO collection_places (collection_id, owner_id, name, image_url) VALUES (?, ?, ?, ?)')
.run(col.lastInsertRowid, user.id, 'Shared Photo', '/uploads/places/svc-shared.jpg');
expect(fs.existsSync(fileA)).toBe(true);
deletePlace(String(trip.id), String(place.id));
expect(fs.existsSync(fileA)).toBe(true);
// resetTestDb does not clear collections; drop what this test inserted and its file.
testDb.exec('DELETE FROM collection_places; DELETE FROM collections;');
fs.unlinkSync(fileA);
});
// ── Collaborative ratings (#1435) ──────────────────────────────────────────
it('PLACE-SVC-050 — ratePlace stores one vote per user, replaces on re-vote, clears with null', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' }) as { id: number };
ratePlace(String(trip.id), String(place.id), user.id, 5);
let rows = testDb.prepare('SELECT rating FROM place_ratings WHERE place_id = ? AND user_id = ?').all(place.id, user.id) as { rating: number }[];
expect(rows).toEqual([{ rating: 5 }]);
ratePlace(String(trip.id), String(place.id), user.id, 2); // re-vote replaces via the UNIQUE upsert
rows = testDb.prepare('SELECT rating FROM place_ratings WHERE place_id = ? AND user_id = ?').all(place.id, user.id) as { rating: number }[];
expect(rows).toEqual([{ rating: 2 }]);
ratePlace(String(trip.id), String(place.id), user.id, null); // clear
const count = testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id) as { n: number };
expect(count.n).toBe(0);
});
it('PLACE-SVC-051 — ratePlace returns null and writes nothing when the place is not in the trip', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const otherTrip = createTrip(testDb, user.id);
const place = createPlace(testDb, otherTrip.id, { name: 'Elsewhere' }) as { id: number };
expect(ratePlace(String(trip.id), String(place.id), user.id, 4)).toBeNull();
const count = testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id) as { n: number };
expect(count.n).toBe(0);
});
});