mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat: quality of life sweep from the feature discussions
Small requests from the discussions, each built end to end: planner and map (cycling mode, date first headings, clear a day, stay times per day, off-route stops, map lock, compact unplanned markers, pending stays, cable car, transit quick picks), places (location filter, category from OSM, open in maps, geo: link, image from an attachment, enrichment on file import, places near a pin, place name language, Amap first in China), lists and costs (packed counter, inherited sharing, Markdown to-dos, payment notes, bookings CSV, my plan PDF), sharing (unplanned places, travel only, without photos), journey (photo zoom, drafts, photo order, trip suggestion, day jump), atlas (region counter, region bucket list, places per country), vacay half company holidays, studio copy and paste plus the book's own layouts, and RESTORE_FROM_BACKUP for a first start restore.
This commit is contained in:
@@ -247,6 +247,12 @@ describe('deriveBackup', () => {
|
||||
expect(deriveBackup({}).maxDecompressedMb).toBe(5 * 1024);
|
||||
expect(deriveBackup({ ENCRYPTION_KEY: 'x' }).encryptionKeyFromEnv).toBe(true);
|
||||
});
|
||||
|
||||
it('reads RESTORE_FROM_BACKUP as a trimmed path, and blank as unset (#1089)', () => {
|
||||
expect(deriveBackup({}).restoreFromBackup).toBeNull();
|
||||
expect(deriveBackup({ RESTORE_FROM_BACKUP: ' ' }).restoreFromBackup).toBeNull();
|
||||
expect(deriveBackup({ RESTORE_FROM_BACKUP: ' /app/data/b.zip ' }).restoreFromBackup).toBe('/app/data/b.zip');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveNet', () => {
|
||||
|
||||
@@ -285,6 +285,46 @@ describe('Tool: unassign_place', () => {
|
||||
// reorder_day_assignments
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: clear_day_assignments (#2470)', () => {
|
||||
it('removes every place from the day and broadcasts each removal', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const a1 = createDayAssignment(testDb, day.id, place.id);
|
||||
const a2 = createDayAssignment(testDb, day.id, place.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const data = parseToolResult(await h.client.callTool({ name: 'clear_day_assignments', arguments: { tripId: trip.id, dayId: day.id } })) as any;
|
||||
expect(data.success).toBe(true);
|
||||
expect([...data.removedIds].sort()).toEqual([a1.id, a2.id].sort());
|
||||
expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ?').get(day.id)).toEqual({ n: 0 });
|
||||
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:deleted', { assignmentId: a1.id, dayId: day.id });
|
||||
});
|
||||
});
|
||||
|
||||
it('returns an error for a day on another trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const otherTrip = createTrip(testDb, user.id);
|
||||
const foreignDay = createDay(testDb, otherTrip.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'clear_day_assignments', arguments: { tripId: trip.id, dayId: foreignDay.id } });
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns access denied for non-member', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const trip = createTrip(testDb, other.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'clear_day_assignments', arguments: { tripId: trip.id, dayId: day.id } });
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: reorder_day_assignments', () => {
|
||||
it('reorders assignments by updating order_index', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -138,6 +138,20 @@ describe('Tool: unmark_country_visited', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: create_bucket_list_item', () => {
|
||||
it('stores a wished-for region and refuses one outside its country (#1901)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const ok = parseToolResult(await h.client.callTool({
|
||||
name: 'create_bucket_list_item', arguments: { name: 'Bayern', country_code: 'DE', region_code: 'DE-BY' },
|
||||
})) as any;
|
||||
expect(ok.item.region_code).toBe('DE-BY');
|
||||
const bad = await h.client.callTool({
|
||||
name: 'create_bucket_list_item', arguments: { name: 'Berlin', country_code: 'FR', region_code: 'DE-BE' },
|
||||
});
|
||||
expect(bad.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a bucket list item with all fields', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
|
||||
@@ -641,6 +641,22 @@ describe('Tool: update_budget_item (currency)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('records and edits a note on the payment (#2340)', async () => {
|
||||
const { user, other, trip } = tripWithTwo();
|
||||
await withHarness(user.id, async (h) => {
|
||||
const created = parseToolResult(await h.client.callTool({
|
||||
name: 'create_settlement',
|
||||
arguments: { tripId: trip.id, from_user_id: other.id, to_user_id: user.id, amount: 20, note: 'Cash' },
|
||||
})) as any;
|
||||
expect(created.settlement.note).toBe('Cash');
|
||||
const updated = parseToolResult(await h.client.callTool({
|
||||
name: 'update_settlement',
|
||||
arguments: { tripId: trip.id, settlementId: created.settlement.id, from_user_id: other.id, to_user_id: user.id, amount: 20, note: 'Bank transfer' },
|
||||
})) as any;
|
||||
expect(updated.settlement.note).toBe('Bank transfer');
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a currency that is not a code', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -143,6 +143,21 @@ describe('Tool: update_journey_entry', () => {
|
||||
expect(Array.isArray(data.entry.photos)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a draft and publishes it, as the REST route does (#696)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const journey = (parseToolResult(await h.client.callTool({ name: 'create_journey', arguments: { title: 'J' } })) as any).journey;
|
||||
const draft = (parseToolResult(await h.client.callTool({
|
||||
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'Rough', is_draft: true },
|
||||
})) as any).entry;
|
||||
expect(draft.is_draft).toBe(true);
|
||||
const published = (parseToolResult(await h.client.callTool({
|
||||
name: 'update_journey_entry', arguments: { entryId: draft.id, is_draft: false },
|
||||
})) as any).entry;
|
||||
expect(published.is_draft).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: update_journey_preferences', () => {
|
||||
@@ -391,6 +406,19 @@ describe('journey write tools', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('reorder_journey_entry_photos refuses ids that are not the entry photos (#824)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const journey = await seedJourney(h);
|
||||
const entry = (parseToolResult(await h.client.callTool({
|
||||
name: 'create_journey_entry', arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'A' },
|
||||
})) as any).entry;
|
||||
expect((await h.client.callTool({
|
||||
name: 'reorder_journey_entry_photos', arguments: { entryId: entry.id, orderedIds: [999999] },
|
||||
})).isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('contributor tools add, re-role and remove; each refuses a foreign journey', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: guest } = createUser(testDb);
|
||||
|
||||
@@ -63,6 +63,37 @@ async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>)
|
||||
// set_leg_transport_mode
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: set_assignment_route_excluded (#2532)', () => {
|
||||
it('takes a stop out of the route and puts it back, broadcasting each change', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const assignment = createDayAssignment(testDb, day.id, place.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const out = parseToolResult(await h.client.callTool({ name: 'set_assignment_route_excluded', arguments: { tripId: trip.id, assignmentId: assignment.id, excluded: true } })) as any;
|
||||
expect(out.assignment.route_excluded).toBe(true);
|
||||
expect(testDb.prepare('SELECT route_excluded FROM day_assignments WHERE id = ?').get(assignment.id)).toEqual({ route_excluded: 1 });
|
||||
const back = parseToolResult(await h.client.callTool({ name: 'set_assignment_route_excluded', arguments: { tripId: trip.id, assignmentId: assignment.id, excluded: false } })) as any;
|
||||
expect(back.assignment.route_excluded).toBe(false);
|
||||
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'assignment:updated', expect.any(Object));
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an assignment of another trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, other.id);
|
||||
const place = createPlace(testDb, other.id);
|
||||
const assignment = createDayAssignment(testDb, day.id, place.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'set_assignment_route_excluded', arguments: { tripId: trip.id, assignmentId: assignment.id, excluded: true } });
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: set_leg_transport_mode', () => {
|
||||
it('sets the outgoing leg mode (default direction)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -301,6 +301,19 @@ describe('Tool: update_packing_item', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('counts packed pieces like the REST route does (#2296)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const item = createPackingItem(testDb, trip.id, { name: 'Shirts' });
|
||||
await withHarness(user.id, async (h) => {
|
||||
await h.client.callTool({ name: 'update_packing_item', arguments: { tripId: trip.id, itemId: item.id, quantity: 4 } });
|
||||
const partial = parseToolResult(await h.client.callTool({ name: 'update_packing_item', arguments: { tripId: trip.id, itemId: item.id, packed_quantity: 3 } })) as any;
|
||||
expect(partial.item).toMatchObject({ packed_quantity: 3, checked: 0 });
|
||||
const full = parseToolResult(await h.client.callTool({ name: 'update_packing_item', arguments: { tripId: trip.id, itemId: item.id, packed_quantity: 4 } })) as any;
|
||||
expect(full.item).toMatchObject({ packed_quantity: null, checked: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
it('broadcasts packing:updated event', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -219,6 +219,23 @@ describe('Tool: create_place', () => {
|
||||
// update_place
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: set_place_image_from_file (#1242)', () => {
|
||||
it('refuses a file that is no picture, and one from another trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const pdf = Number(testDb.prepare("INSERT INTO trip_files (trip_id, filename, original_name, mime_type) VALUES (?, 'a.pdf', 'a.pdf', 'application/pdf')").run(trip.id).lastInsertRowid);
|
||||
const foreign = Number(testDb.prepare("INSERT INTO trip_files (trip_id, filename, original_name, mime_type) VALUES (?, 'b.jpg', 'b.jpg', 'image/jpeg')").run(other.id).lastInsertRowid);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const notImage = await h.client.callTool({ name: 'set_place_image_from_file', arguments: { tripId: trip.id, placeId: place.id, fileId: pdf } });
|
||||
expect(notImage.isError).toBe(true);
|
||||
const notFound = await h.client.callTool({ name: 'set_place_image_from_file', arguments: { tripId: trip.id, placeId: place.id, fileId: foreign } });
|
||||
expect(notFound.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: update_place', () => {
|
||||
it('updates specific fields and preserves others', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -259,6 +259,19 @@ describe('Tool: update_display_settings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('writes place_language, clears it with "", and refuses a language TREK does not offer (#1799)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const set = parseToolResult(await update(h, { place_language: 'en' })) as any;
|
||||
expect(set.settings.place_language).toBe('en');
|
||||
const refused = await update(h, { place_language: 'klingon' });
|
||||
expect(refused.isError).toBe(true);
|
||||
expect(readSetting(user.id, 'place_language')).toBe('en');
|
||||
const cleared = parseToolResult(await update(h, { place_language: '' })) as any;
|
||||
expect(cleared.settings.place_language).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
it('writes week_start and refuses a day outside the three the app offers (#2029)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
|
||||
@@ -71,6 +71,16 @@ describe('Tool: get_share_link', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('stores the two narrowing options like the REST route (#1712)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
await h.client.callTool({ name: 'create_share_link', arguments: { tripId: trip.id, share_travel_only: true, share_hide_images: true } });
|
||||
const link = parseToolResult(await h.client.callTool({ name: 'get_share_link', arguments: { tripId: trip.id } })) as any;
|
||||
expect(link.link).toMatchObject({ share_travel_only: true, share_hide_images: true });
|
||||
});
|
||||
});
|
||||
|
||||
it('returns access denied for a non-member trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
|
||||
@@ -422,6 +422,44 @@ describe('Tool: get_place_details', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// search_nearby_places (#976)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: search_nearby_places', () => {
|
||||
it('lists what the index holds around the point, nearest first with the distance', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
trekNearbyMock.mockClear();
|
||||
trekNearbyMock.mockResolvedValueOnce([
|
||||
{ gers: 'n-2', name: 'Farther', lat: 48.8611, lng: 2.3364, address: null, contact: null },
|
||||
{ gers: 'n-1', name: 'Closer', lat: 48.8607, lng: 2.3376, address: null, contact: null },
|
||||
]);
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'search_nearby_places',
|
||||
arguments: { lat: 48.8606, lng: 2.3376, radius: 200, limit: 5 },
|
||||
});
|
||||
const data = parseToolResult(result) as any;
|
||||
expect(data.source).toBe('trek-places');
|
||||
expect(data.places.map((p: any) => p.name)).toEqual(['Closer', 'Farther']);
|
||||
expect(data.places[0].distance_m).toBe(11);
|
||||
expect(trekNearbyMock).toHaveBeenCalledWith(48.8606, 2.3376, { radius: 200, limit: 5 });
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a circle wider than the REST route allows', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'search_nearby_places',
|
||||
arguments: { lat: 48.8606, lng: 2.3376, radius: 5001 },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// search_pois (#30)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -478,6 +478,16 @@ describe('Tool: toggle_company_holiday', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('makes a half company holiday like the REST route (#2439)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const data = parseToolResult(await h.client.callTool({
|
||||
name: 'toggle_company_holiday', arguments: { date: '2025-12-24', half: true },
|
||||
})) as any;
|
||||
expect(data).toMatchObject({ action: 'added', fraction: 0.5 });
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks demo user', async () => {
|
||||
process.env.DEMO_MODE = 'true';
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
|
||||
@@ -64,9 +64,39 @@ describe('DayAssignmentsController (parity with the legacy day-assignments route
|
||||
expect(new DayAssignmentsController(s).remove(user, '5', '3', '9', 'sock')).toEqual({ success: true });
|
||||
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
|
||||
});
|
||||
|
||||
it('DELETE / (clear day) 404 day, else empties the day and announces every removal (#2470)', () => {
|
||||
expect(thrown(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).clear(user, '5', '3'))).toEqual({ status: 404, body: { error: 'Day not found' } });
|
||||
const clearDay = vi.fn().mockReturnValue([7, 8]); const broadcast = vi.fn(); const reconcile = vi.fn();
|
||||
const s = svc({ clearDay, broadcast, reconcile } as Partial<AssignmentsService>);
|
||||
expect(new DayAssignmentsController(s).clear(user, '5', '3', 'sock')).toEqual({ success: true, removedIds: [7, 8] });
|
||||
expect(clearDay).toHaveBeenCalledWith('3');
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:deleted', { assignmentId: 7, dayId: 3 }, 'sock');
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:deleted', { assignmentId: 8, dayId: 3 }, 'sock');
|
||||
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
|
||||
});
|
||||
|
||||
it('DELETE / on an already empty day succeeds without a journey reconcile', () => {
|
||||
const reconcile = vi.fn(); const broadcast = vi.fn();
|
||||
const s = svc({ clearDay: vi.fn().mockReturnValue([]), reconcile, broadcast } as Partial<AssignmentsService>);
|
||||
expect(new DayAssignmentsController(s).clear(user, '5', '3')).toEqual({ success: true, removedIds: [] });
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
expect(reconcile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AssignmentOpsController (parity with the per-assignment op routes)', () => {
|
||||
it('PUT /:id/route takes a stop out of the route and back, scoped to the trip (#2532)', () => {
|
||||
const setRouteExcluded = vi.fn().mockReturnValue({ id: 9, route_excluded: true })
|
||||
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), setRouteExcluded } as Partial<AssignmentsService>)
|
||||
const controller = new AssignmentOpsController(s)
|
||||
expect(controller.route(user, '5', '9', { excluded: true }, 'sock')).toEqual({ assignment: { id: 9, route_excluded: true } })
|
||||
expect(setRouteExcluded).toHaveBeenCalledWith('9', true)
|
||||
expect(s.broadcast).toHaveBeenCalledWith('5', 'assignment:updated', { assignment: { id: 9, route_excluded: true } }, 'sock')
|
||||
vi.mocked(s.getAssignmentForTrip).mockReturnValue(undefined)
|
||||
expect(thrown(() => controller.route(user, '5', '9', { excluded: false }))).toEqual({ status: 404, body: { error: 'Assignment not found' } })
|
||||
});
|
||||
|
||||
it('scopes explicit day ends to the trip and broadcasts the saved visit', () => {
|
||||
const setEndDay = vi.fn().mockReturnValue({ id: 9, end_day: true });
|
||||
const s = svc({ getAssignmentForTrip: vi.fn().mockReturnValue({ id: 9 }), setEndDay });
|
||||
|
||||
@@ -249,6 +249,26 @@ describe('deleteAssignment / reorderAssignments', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearDay (#2470)', () => {
|
||||
it('ASG-SVC-013b: removes every place of the day, leaves other days alone, returns the ids', () => {
|
||||
const { trip, day, place } = fixture();
|
||||
const otherDay = createDay(testDb, trip.id);
|
||||
const a1 = createDayAssignment(testDb, day.id, place.id);
|
||||
const a2 = createDayAssignment(testDb, day.id, place.id);
|
||||
const kept = createDayAssignment(testDb, otherDay.id, place.id);
|
||||
|
||||
expect(svc.clearDay(day.id).sort()).toEqual([a1.id, a2.id].sort());
|
||||
expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ?').get(day.id)).toEqual({ n: 0 });
|
||||
expect(testDb.prepare('SELECT id FROM day_assignments WHERE id = ?').get(kept.id)).toEqual({ id: kept.id });
|
||||
expect(testDb.prepare('SELECT id FROM days WHERE id = ?').get(day.id)).toEqual({ id: day.id });
|
||||
});
|
||||
|
||||
it('ASG-SVC-013c: an empty day clears to an empty list', () => {
|
||||
const { day } = fixture();
|
||||
expect(svc.clearDay(day.id)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getAssignmentForTrip / moveAssignment ─────────────────────────────────────
|
||||
|
||||
describe('getAssignmentForTrip', () => {
|
||||
@@ -667,5 +687,15 @@ describe('setLegTransportMode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('setRouteExcluded (#2532)', () => {
|
||||
it('ASG-SVC-025b: keeps the stop but flags it out of the route, and back', () => {
|
||||
const { day, place } = fixture();
|
||||
const a = createDayAssignment(testDb, day.id, place.id);
|
||||
expect(svc.getAssignmentWithPlace(a.id)!.route_excluded).toBe(false);
|
||||
expect(svc.setRouteExcluded(a.id, true)!.route_excluded).toBe(true);
|
||||
expect(svc.setRouteExcluded(a.id, false)!.route_excluded).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ASG-SVC-026 pinned the deleted assignments.bridge and died with it — the
|
||||
// same paths are covered on the service above and via places.mcp injection.
|
||||
|
||||
@@ -128,6 +128,12 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', ()
|
||||
expect(createBucketItem).toHaveBeenCalledWith(8, { name: 'Tokyo', lat: 35, lng: 139, country_code: undefined, notes: undefined, target_date: undefined });
|
||||
});
|
||||
|
||||
it('forwards a wished-for region, as the MCP tool does (#1901)', () => {
|
||||
const createBucketItem = vi.fn().mockReturnValue({ id: 2 });
|
||||
makeController({ createBucketItem }).createBucketItem(user, { name: 'Bayern', country_code: 'DE', region_code: 'DE-BY' });
|
||||
expect(createBucketItem).toHaveBeenCalledWith(8, expect.objectContaining({ country_code: 'DE', region_code: 'DE-BY' }));
|
||||
});
|
||||
|
||||
it('404 on update of a missing item', () => {
|
||||
const updateBucketItem = vi.fn().mockReturnValue(null);
|
||||
return thrown(() => makeController({ updateBucketItem }).updateBucketItem(user, '9', { name: 'X' })).then((r) =>
|
||||
|
||||
@@ -42,7 +42,7 @@ import { createUser, createTrip, createReservation } from '../../helpers/factori
|
||||
import { getCountryFromCoords, getCountryFromAddress, isPointInCountryBox, reverseGeocodeCountry, getRegionGeo, getCountryGeo } from '../../../src/nest/atlas/atlas-geo';
|
||||
import { cacheKeyFor, getCached, setCached } from '../../../src/nest/geo/nominatim.client';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { AtlasService, BucketItemExistsError } from '../../../src/nest/atlas/atlas.service';
|
||||
import { AtlasService, BucketItemExistsError, bucketRegionCode } from '../../../src/nest/atlas/atlas.service';
|
||||
|
||||
// Direct construction over the shared test connection — no TestingModule (repo
|
||||
// convention for DI-native service unit tests).
|
||||
@@ -1340,6 +1340,17 @@ describe('atlas quirk fixes', () => {
|
||||
expect(unmarked.marked_source).toBeNull();
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-031b: keeps a wished-for region of the same country, drops any other (#1901)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const bavaria = atlas.createBucketItem(user.id, { name: 'Bayern', country_code: 'DE', region_code: 'de-by' }) as { region_code: string | null };
|
||||
expect(bavaria.region_code).toBe('DE-BY');
|
||||
const foreign = atlas.createBucketItem(user.id, { name: 'Berlin', country_code: 'FR', region_code: 'DE-BE' }) as { region_code: string | null };
|
||||
expect(foreign.region_code).toBeNull();
|
||||
const noCountry = atlas.createBucketItem(user.id, { name: 'Somewhere', region_code: 'DE-HH' }) as { region_code: string | null };
|
||||
expect(noCountry.region_code).toBeNull();
|
||||
expect(bucketRegionCode('DE-BY; DROP', 'DE')).toBeNull();
|
||||
});
|
||||
|
||||
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 };
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* BOOT-RESTORE-001..007 — restoring a backup on a first start (#1089).
|
||||
*
|
||||
* Real files, a real archive and a real SQLite file: what is being protected is
|
||||
* the order of things on disk, and a mocked filesystem would only confirm the
|
||||
* calls this file makes. The plugin staging is the one seam stubbed, because
|
||||
* it moves trees under the plugin roots of the machine running the tests.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import archiver from 'archiver';
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
const { stageMock } = vi.hoisted(() => ({ stageMock: vi.fn() }));
|
||||
vi.mock('../../../src/nest/plugins/plugin-backup', () => ({ stageExtractedPluginTrees: stageMock }));
|
||||
|
||||
import { BootRestoreError, restoreOnFirstBoot } from '../../../src/nest/backup/boot-restore';
|
||||
|
||||
let root: string;
|
||||
let dataDir: string;
|
||||
let dbFile: string;
|
||||
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-boot-restore-'));
|
||||
dataDir = path.join(root, 'data');
|
||||
fs.mkdirSync(dataDir);
|
||||
dbFile = path.join(dataDir, 'travel.db');
|
||||
stageMock.mockClear();
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** A database with the tables every TREK has, and one user to recognise it by. */
|
||||
function trekDb(file: string, tables = ['users', 'trips', 'trip_members', 'places', 'days']) {
|
||||
const db = new Database(file);
|
||||
for (const t of tables) db.exec(`CREATE TABLE ${t} (id INTEGER PRIMARY KEY, name TEXT)`);
|
||||
if (tables.includes('users')) db.prepare('INSERT INTO users (name) VALUES (?)').run('from-backup');
|
||||
db.close();
|
||||
}
|
||||
|
||||
async function archive(entries: Record<string, string | { file: string }>): Promise<string> {
|
||||
const zipPath = path.join(root, 'backup.zip');
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const out = fs.createWriteStream(zipPath);
|
||||
const zip = archiver('zip');
|
||||
out.on('close', () => resolve());
|
||||
zip.on('error', reject);
|
||||
zip.pipe(out);
|
||||
for (const [name, content] of Object.entries(entries)) {
|
||||
if (typeof content === 'string') zip.append(content, { name });
|
||||
else zip.file(content.file, { name });
|
||||
}
|
||||
void zip.finalize();
|
||||
});
|
||||
return zipPath;
|
||||
}
|
||||
|
||||
async function goodArchive(extra: Record<string, string> = {}) {
|
||||
const src = path.join(root, 'src.db');
|
||||
trekDb(src);
|
||||
return archive({ 'travel.db': { file: src }, '.encryption_key': 'a'.repeat(64), 'uploads/covers/c.jpg': 'jpeg', ...extra });
|
||||
}
|
||||
|
||||
describe('restoreOnFirstBoot', () => {
|
||||
it('BOOT-RESTORE-001: without the variable nothing happens', async () => {
|
||||
expect(await restoreOnFirstBoot({ archive: null, dbFile, dataDir })).toEqual({ restored: false, reason: 'unset' });
|
||||
expect(fs.existsSync(dbFile)).toBe(false);
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-002: on a first start the backup\'s database, key and uploads are put in place', async () => {
|
||||
const zipPath = await goodArchive();
|
||||
|
||||
const out = await restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir });
|
||||
|
||||
expect(out.restored).toBe(true);
|
||||
const db = new Database(dbFile, { readonly: true });
|
||||
expect(db.prepare('SELECT name FROM users').get()).toEqual({ name: 'from-backup' });
|
||||
db.close();
|
||||
expect(fs.readFileSync(path.join(dataDir, '.encryption_key'), 'utf8')).toBe('a'.repeat(64));
|
||||
if (!out.restored) throw new Error('unreachable');
|
||||
expect(fs.readFileSync(path.join(out.uploads!, 'covers', 'c.jpg'), 'utf8')).toBe('jpeg');
|
||||
expect(stageMock).toHaveBeenCalledWith(out.staging);
|
||||
expect(fs.existsSync(`${dbFile}.restore-tmp`)).toBe(false);
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-003: with a database already there the backup is left alone, so a restart never rolls back', async () => {
|
||||
const zipPath = await goodArchive();
|
||||
trekDb(dbFile, ['users', 'trips', 'trip_members', 'places', 'days']);
|
||||
const before = fs.readFileSync(dbFile);
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
expect(await restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir })).toEqual({ restored: false, reason: 'database-exists' });
|
||||
expect(fs.readFileSync(dbFile).equals(before)).toBe(true);
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('only restored on a first start'));
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-004: a missing archive stops the start instead of coming up empty', async () => {
|
||||
await expect(restoreOnFirstBoot({ archive: path.join(root, 'nope.zip'), dbFile, dataDir }))
|
||||
.rejects.toBeInstanceOf(BootRestoreError);
|
||||
expect(fs.existsSync(dbFile)).toBe(false);
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-005: an archive without a database is refused and leaves no scratch behind', async () => {
|
||||
const zipPath = await archive({ 'notes.txt': 'hello' });
|
||||
await expect(restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir }))
|
||||
.rejects.toThrow('RESTORE_FROM_BACKUP: Invalid backup: travel.db not found');
|
||||
expect(fs.existsSync(dbFile)).toBe(false);
|
||||
expect(fs.readdirSync(dataDir).filter(n => n.startsWith('restore-boot-'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-006: a database that is not a TREK one is refused', async () => {
|
||||
const src = path.join(root, 'other.db');
|
||||
trekDb(src, ['users']);
|
||||
const zipPath = await archive({ 'travel.db': { file: src } });
|
||||
await expect(restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir }))
|
||||
.rejects.toThrow('missing required table: trips');
|
||||
expect(fs.existsSync(dbFile)).toBe(false);
|
||||
});
|
||||
|
||||
it('BOOT-RESTORE-007: an entry escaping the archive is refused', async () => {
|
||||
const zipPath = await archive({ '../escape.txt': 'x', 'travel.db': 'not a db' });
|
||||
await expect(restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir }))
|
||||
.rejects.toThrow(/escapes the archive root|not a valid SQLite database/);
|
||||
expect(fs.existsSync(dbFile)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -119,6 +119,17 @@ describe('BudgetController (parity with the legacy /api/trips/:tripId/budget rou
|
||||
expect(updateSettlement).toHaveBeenCalledWith('3', '5', expect.objectContaining({ currency: 'EUR', fallback_fx }));
|
||||
});
|
||||
|
||||
it('POST and PUT /settlements forward the note, as the MCP tools do (#2340)', async () => {
|
||||
const createSettlement = vi.fn().mockResolvedValue({ id: 3 });
|
||||
const updateSettlement = vi.fn().mockResolvedValue({ id: 3 });
|
||||
const svc = makeService({ createSettlement, updateSettlement } as Partial<BudgetService>);
|
||||
const body = { from_user_id: 1, to_user_id: 2, amount: 10, note: 'Cash' };
|
||||
await new BudgetController(svc).createSettlement(user, '5', body);
|
||||
expect(createSettlement).toHaveBeenCalledWith('5', expect.objectContaining({ note: 'Cash' }), user.id);
|
||||
await new BudgetController(svc).updateSettlement(user, '5', '3', body);
|
||||
expect(updateSettlement).toHaveBeenCalledWith('3', '5', expect.objectContaining({ note: 'Cash' }));
|
||||
});
|
||||
|
||||
it('DELETE /settlements/:id 404 when missing', () => {
|
||||
const svc = makeService({ deleteSettlement: vi.fn().mockReturnValue(false) } as Partial<BudgetService>);
|
||||
expect(thrown(() => new BudgetController(svc).deleteSettlement(user, '5', '7'))).toEqual({
|
||||
|
||||
@@ -571,6 +571,20 @@ describe('settlement parties are confined to the trip', () => {
|
||||
expect(created).toMatchObject({ from_user_id: bob.id, to_user_id: alice.id });
|
||||
});
|
||||
|
||||
it('BUDGET-SVC-DB-030b: keeps a trimmed note on a payment and clears a blank one (#2340)', async () => {
|
||||
const { user: alice } = createUser(testDb, { username: 'alice' });
|
||||
const { user: bob } = createUser(testDb, { username: 'bob' });
|
||||
const trip = createTrip(testDb, alice.id);
|
||||
addTripMember(testDb, trip.id, bob.id);
|
||||
|
||||
const created = await budget.createSettlement(trip.id, { from_user_id: bob.id, to_user_id: alice.id, amount: 10, note: ' Bank transfer ' }, alice.id);
|
||||
expect(created).toMatchObject({ note: 'Bank transfer' });
|
||||
const kept = await budget.updateSettlement(created!.id, trip.id, { from_user_id: bob.id, to_user_id: alice.id, amount: 11 });
|
||||
expect(kept).toMatchObject({ amount: 11, note: 'Bank transfer' });
|
||||
const cleared = await budget.updateSettlement(created!.id, trip.id, { from_user_id: bob.id, to_user_id: alice.id, amount: 11, note: '' });
|
||||
expect(cleared).toMatchObject({ note: null });
|
||||
});
|
||||
|
||||
it('BUDGET-SVC-DB-031: drops an off-trip payer from an item instead of refusing it', () => {
|
||||
const { user: alice } = createUser(testDb, { username: 'alice' });
|
||||
const { user: outsider } = createUser(testDb, { username: 'outsider' });
|
||||
|
||||
@@ -692,6 +692,16 @@ describe('updateEntry', () => {
|
||||
* be the boolean on the way out as well as the integer on the way in, and
|
||||
* the broadcast has to say the same thing the answer does.
|
||||
*/
|
||||
it('creates and toggles a draft, answering the flag as a boolean (#696)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const created = svc.createEntry(journey.id, user.id, { entry_date: '2026-03-01', title: 'Rough', is_draft: true });
|
||||
expect(created!.is_draft).toBe(true);
|
||||
const published = svc.updateEntry(created!.id, user.id, { is_draft: false });
|
||||
expect(published!.is_draft).toBe(false);
|
||||
expect((testDb.prepare('SELECT is_draft FROM journey_entries WHERE id = ?').get(created!.id) as { is_draft: number }).is_draft).toBe(0);
|
||||
});
|
||||
|
||||
it('switches a stop off and back on, and answers with the flag as a boolean', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
@@ -1667,6 +1677,45 @@ function insertEntry(journeyId: number, authorId: number, opts: { entry_date: st
|
||||
return { id: Number(res.lastInsertRowid) };
|
||||
}
|
||||
|
||||
describe('reorderEntryPhotos (#824)', () => {
|
||||
function photoOn(journeyId: number, entryIds: number[], order = 0): number {
|
||||
const trek = testDb.prepare("INSERT INTO trek_photos (provider, file_path, created_at) VALUES ('local', '/p.jpg', ?)").run(Date.now()).lastInsertRowid;
|
||||
const gp = Number(testDb.prepare('INSERT INTO journey_photos (journey_id, photo_id, sort_order, created_at) VALUES (?, ?, 0, ?)').run(journeyId, trek, Date.now()).lastInsertRowid);
|
||||
for (const entryId of entryIds) testDb.prepare('INSERT INTO journey_entry_photos (entry_id, journey_photo_id, sort_order, created_at) VALUES (?, ?, ?, ?)').run(entryId, gp, order, Date.now());
|
||||
return gp;
|
||||
}
|
||||
const orderOf = (entryId: number) =>
|
||||
(testDb.prepare('SELECT journey_photo_id FROM journey_entry_photos WHERE entry_id = ? ORDER BY sort_order').all(entryId) as { journey_photo_id: number }[]).map(r => r.journey_photo_id);
|
||||
|
||||
it('JOURNEY-SVC-089b: orders the photos of one entry and leaves the same photo elsewhere alone', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const a = insertEntry(journey.id, user.id, { entry_date: '2026-08-01' });
|
||||
const b = insertEntry(journey.id, user.id, { entry_date: '2026-08-02' });
|
||||
const p1 = photoOn(journey.id, [a.id, b.id], 0);
|
||||
const p2 = photoOn(journey.id, [a.id], 1);
|
||||
const p3 = photoOn(journey.id, [a.id], 2);
|
||||
expect(svc.reorderEntryPhotos(a.id, user.id, [p3, p1, p2])).toBe(true);
|
||||
expect(orderOf(a.id)).toEqual([p3, p1, p2]);
|
||||
expect(testDb.prepare('SELECT sort_order FROM journey_entry_photos WHERE entry_id = ? AND journey_photo_id = ?').get(b.id, p1)).toEqual({ sort_order: 0 });
|
||||
});
|
||||
|
||||
it('JOURNEY-SVC-089c: refuses a list that is not exactly the photos of the entry, and a stranger', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const a = insertEntry(journey.id, user.id, { entry_date: '2026-08-01' });
|
||||
const p1 = photoOn(journey.id, [a.id]);
|
||||
const p2 = photoOn(journey.id, [a.id]);
|
||||
const other = photoOn(journey.id, []);
|
||||
expect(svc.reorderEntryPhotos(a.id, user.id, [p1])).toBe(false);
|
||||
expect(svc.reorderEntryPhotos(a.id, user.id, [p1, other])).toBe(false);
|
||||
expect(svc.reorderEntryPhotos(a.id, user.id, [p1, p1])).toBe(false);
|
||||
expect(svc.reorderEntryPhotos(a.id, stranger.id, [p2, p1])).toBe(false);
|
||||
expect(svc.reorderEntryPhotos(999999, user.id, [p2, p1])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reorderEntries', () => {
|
||||
it('JOURNEY-SVC-089: reorder persists and listEntries returns requested order regardless of entry_time', () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -496,6 +496,29 @@ describe('getPublicJourney', () => {
|
||||
expect(result!.entries[0].title).toBe('Visible Entry');
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-018b: leaves drafts and the photos only they hold off the public page (#696)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const published = createJourneyEntry(testDb, journey.id, user.id, { title: 'Published', entry_date: '2026-01-10' });
|
||||
const draft = createJourneyEntry(testDb, journey.id, user.id, { title: 'Draft', entry_date: '2026-01-11' });
|
||||
testDb.prepare('UPDATE journey_entries SET is_draft = 1 WHERE id = ?').run(draft.id);
|
||||
const shownPhoto = insertJourneyPhoto(published.id, { ownerId: user.id });
|
||||
const draftPhoto = insertJourneyPhoto(draft.id, { ownerId: user.id });
|
||||
// A photo on both a draft and a published entry is published.
|
||||
const sharedPhoto = insertJourneyPhoto(draft.id, { ownerId: user.id, filePath: '/photos/both.jpg' });
|
||||
const sharedRow = testDb.prepare('SELECT id FROM journey_photos WHERE photo_id = ?').get(sharedPhoto) as { id: number };
|
||||
testDb.prepare('INSERT INTO journey_entry_photos (entry_id, journey_photo_id, sort_order, created_at) VALUES (?, ?, 1, 0)').run(published.id, sharedRow.id);
|
||||
const { token } = svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: true, share_gallery: true });
|
||||
|
||||
const result = svc.getPublicJourney(token)!;
|
||||
expect(result.entries.map((e: any) => e.title)).toEqual(['Published']);
|
||||
expect(result.stats.entries).toBe(1);
|
||||
const galleryIds = (result as any).gallery.map((p: any) => p.photo_id).sort();
|
||||
expect(galleryIds).toEqual([shownPhoto, sharedPhoto].sort());
|
||||
expect(svc.validateShareTokenForPhoto(token, draftPhoto)).toBeNull();
|
||||
expect(svc.validateShareTokenForPhoto(token, shownPhoto)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-019: enriches entries with parsed tags and photos', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
|
||||
@@ -397,6 +397,14 @@ describe('JourneyController', () => {
|
||||
expect(ctl(svc({ reorderEntries: vi.fn().mockReturnValue(true) } as Partial<JourneyService>)).reorderEntries(user, '9', { orderedIds: [3, 1, 2] })).toEqual({ success: true });
|
||||
});
|
||||
|
||||
it('reorderEntryPhotos forwards the order and answers 404 when refused (#824)', () => {
|
||||
const reorderEntryPhotos = vi.fn().mockReturnValue(true);
|
||||
expect(ctl(svc({ reorderEntryPhotos } as Partial<JourneyService>)).reorderEntryPhotos(user, '12', { orderedIds: [3, 1] }, 'sock')).toEqual({ success: true });
|
||||
expect(reorderEntryPhotos).toHaveBeenCalledWith(12, user.id, [3, 1], 'sock');
|
||||
expect(thrown(() => ctl(svc({ reorderEntryPhotos: vi.fn().mockReturnValue(false) } as Partial<JourneyService>)).reorderEntryPhotos(user, '12', { orderedIds: [3] })))
|
||||
.toEqual({ status: 404, body: { error: 'Entry not found' } });
|
||||
});
|
||||
|
||||
it('restoreSuggestions answers with the count, and refuses a viewer the same way its siblings do', () => {
|
||||
const restore = vi.fn().mockReturnValue({ restored: 3 });
|
||||
expect(ctl(svc({ restoreDismissedSuggestions: restore } as Partial<JourneyService>)).restoreSuggestions(user, '9')).toEqual({ restored: 3 });
|
||||
|
||||
@@ -63,6 +63,7 @@ vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => (
|
||||
import { db } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { MapsService } from '../../../src/nest/maps/maps.service';
|
||||
import { trekPlacesSearch } from '../../../src/nest/maps/trek-places.client';
|
||||
import {
|
||||
AmapPlacesProvider,
|
||||
AmapTipStash,
|
||||
@@ -894,6 +895,122 @@ describe('MapsService with Amap in the keyed slot', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('MapsService: Amap first inside China when picked outright (#1636)', () => {
|
||||
const BEIJING = { lat: 39.9087, lng: 116.3975, radius: 20000 };
|
||||
const PARIS = { lat: 48.8584, lng: 2.2945, radius: 20000 };
|
||||
const BEIJING_BOX = { low: { lat: 39.8, lng: 116.3 }, high: { lat: 40.0, lng: 116.5 } };
|
||||
let spies: { mockRestore: () => void }[] = [];
|
||||
afterEach(() => {
|
||||
spies.forEach(s => s.mockRestore());
|
||||
spies = [];
|
||||
vi.mocked(trekPlacesSearch).mockClear();
|
||||
});
|
||||
function osmAnswers(places: Record<string, unknown>[]) {
|
||||
const spy = vi.spyOn(svc, 'searchNominatim').mockResolvedValue(places as never);
|
||||
spies.push(spy);
|
||||
return spy;
|
||||
}
|
||||
const amapPoi = () => ok({ pois: [{ id: 'B1', name: '天安门', location: TIANANMEN_LOCATION }] });
|
||||
|
||||
it('AMAP-095: picked outright and searching around Beijing, Amap answers before the index and OpenStreetMap', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
const osm = osmAnswers([{ name: 'Tiananmen (OSM)' }]);
|
||||
const fetchSpy = vi.fn().mockResolvedValue(amapPoi());
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.searchPlaces(1, '天安门', 'zh', BEIJING);
|
||||
|
||||
expect(result.source).toBe('amap');
|
||||
expect(result.places[0].amap_poi_id).toBe('amap:B1');
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
expect(osm).not.toHaveBeenCalled();
|
||||
expect(trekPlacesSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('AMAP-096: an empty Amap answer hands the search on, and Amap is not asked a second time', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
osmAnswers([]);
|
||||
const fetchSpy = vi.fn().mockResolvedValue(ok({ count: '0', pois: [] }));
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.searchPlaces(1, 'nothing here', 'zh', BEIJING);
|
||||
|
||||
expect(result).toEqual({ places: [], source: 'amap' });
|
||||
expect(trekPlacesSearch).toHaveBeenCalled();
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('AMAP-097: a search centred outside China keeps the usual order, so the Eiffel Tower does not land in Macau', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
osmAnswers([{ name: 'Tour Eiffel' }]);
|
||||
const fetchSpy = vi.fn().mockResolvedValue(amapPoi());
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.searchPlaces(1, 'Eiffel Tower', 'en', PARIS);
|
||||
|
||||
expect(result.places[0].name).toBe('Tour Eiffel');
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('AMAP-098: Amap holding the slot only by default (auto) changes nothing', async () => {
|
||||
mockProviderGet.mockReturnValue(undefined);
|
||||
keys({ amap: 'akey' });
|
||||
osmAnswers([{ name: 'Tiananmen (OSM)' }]);
|
||||
const fetchSpy = vi.fn().mockResolvedValue(amapPoi());
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.searchPlaces(1, '天安门', 'zh', BEIJING);
|
||||
|
||||
expect(result.places[0].name).toBe('Tiananmen (OSM)');
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('AMAP-099: a failing Amap drops through to the index and OpenStreetMap with a warning', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
osmAnswers([{ name: 'Tiananmen (OSM)' }]);
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
spies.push(warn);
|
||||
spies.push(vi.spyOn(console, 'error').mockImplementation(() => {}));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(amapError('10003')));
|
||||
|
||||
const result = await svc.searchPlaces(1, '天安门', 'zh', BEIJING);
|
||||
|
||||
expect(result.places[0].name).toBe('Tiananmen (OSM)');
|
||||
expect(warn).toHaveBeenCalledWith('Amap search failed, falling back:', expect.any(String));
|
||||
});
|
||||
|
||||
it('AMAP-100: suggestions around Beijing come from Amap first, once', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
const fetchSpy = vi.fn().mockResolvedValue(ok({ tips: [{ id: 'T1', name: '天安门', district: '北京市东城区' }] }));
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.autocompletePlaces(1, '天安', 'zh', BEIJING_BOX);
|
||||
|
||||
expect(result.source).toBe('amap');
|
||||
expect(result.suggestions[0].placeId).toBe('amap:T1');
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
expect(trekPlacesSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('AMAP-101: empty Amap suggestions hand on to the index and are not asked for again', async () => {
|
||||
mockProviderGet.mockReturnValue({ value: 'amap' });
|
||||
keys({ amap: 'akey' });
|
||||
const fetchSpy = vi.fn().mockResolvedValue(ok({ tips: [] }));
|
||||
vi.stubGlobal('fetch', fetchSpy);
|
||||
|
||||
const result = await svc.autocompletePlaces(1, 'zzz', 'zh', BEIJING_BOX);
|
||||
|
||||
expect(result).toEqual({ suggestions: [], source: 'amap' });
|
||||
expect(trekPlacesSearch).toHaveBeenCalled();
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AmapTipStash', () => {
|
||||
it('AMAP-090: a tip is forgotten once its ten minutes are up', () => {
|
||||
const tips = new AmapTipStash();
|
||||
|
||||
@@ -80,6 +80,26 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /nearby', () => {
|
||||
it('forwards the point, the circle, the count and the language', async () => {
|
||||
const nearbyPlaces = vi.fn().mockResolvedValue({ places: [], source: 'trek-places' });
|
||||
const res = await makeController({ nearbyPlaces }).nearby(user, { lat: 52.5, lng: 13.4, radius: 300, limit: 5 }, 'de');
|
||||
expect(res).toEqual({ places: [], source: 'trek-places' });
|
||||
expect(nearbyPlaces).toHaveBeenCalledWith(3, 52.5, 13.4, { radius: 300, limit: 5, lang: 'de' });
|
||||
});
|
||||
|
||||
it('maps a provider error to its status, and anything else to 500', async () => {
|
||||
const refused = vi.fn().mockRejectedValue(withError(429, 'Quota exceeded'));
|
||||
expect(await thrown(() => makeController({ nearbyPlaces: refused }).nearby(user, { lat: 1, lng: 2 }))).toEqual({
|
||||
status: 429, body: { error: 'Quota exceeded' },
|
||||
});
|
||||
const broken = vi.fn().mockRejectedValue('boom');
|
||||
expect(await thrown(() => makeController({ nearbyPlaces: broken }).nearby(user, { lat: 1, lng: 2 }))).toEqual({
|
||||
status: 500, body: { error: 'Nearby search error' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /area', () => {
|
||||
const BOX = { minLat: 54, minLng: 12, maxLat: 54.2, maxLng: 12.3 };
|
||||
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* MAPS-NEARBY-001..010 — places around a point, nearest first (#976).
|
||||
*
|
||||
* Three sources in the search's own order: the index, Google with a key, then
|
||||
* OpenStreetMap. What matters is that each answer reads the same (the search
|
||||
* record plus `distance_m`, nearest first), and that Google, which bills per
|
||||
* call, is asked only when the index had nothing and never twice for one spot.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
const { mockNearby } = vi.hoisted(() => ({
|
||||
mockNearby: vi.fn(async (_lat: number, _lng: number, _opts?: { radius?: number; limit?: number }): Promise<unknown[]> => []),
|
||||
}));
|
||||
vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../src/nest/maps/trek-places.client')>()),
|
||||
trekPlacesNearby: mockNearby,
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) }));
|
||||
|
||||
import { MapsService } from '../../../src/nest/maps/maps.service';
|
||||
import {
|
||||
nearbyCacheKey,
|
||||
nearbyOverpassQuery,
|
||||
nearestFirst,
|
||||
overpassNearbyRecords,
|
||||
} from '../../../src/nest/maps/maps-nearby.helpers';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
|
||||
|
||||
const indexRow = (gers: string, name: string, lat: number, lng: number) => ({
|
||||
gers,
|
||||
name,
|
||||
lat,
|
||||
lng,
|
||||
category: 'cafe',
|
||||
categoryPath: null,
|
||||
confidence: 0.9,
|
||||
address: { freeform: 'Pariser Platz 1', locality: 'Berlin', postcode: '10117', region: null, country: 'DE' },
|
||||
contact: null,
|
||||
brand: null,
|
||||
source: 'overture',
|
||||
hours: null,
|
||||
distanceMetres: 0,
|
||||
});
|
||||
|
||||
const ORIGINAL_TREK_PLACES = process.env.TREK_PLACES_ENABLED;
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
// Every case asks about its own spot: the answers are cached per process, and a
|
||||
// shared point would make the second case read the first one's answer.
|
||||
let spot = 0;
|
||||
function nextPoint() {
|
||||
spot += 1;
|
||||
return { lat: 10 + spot / 10, lng: 20 + spot / 10 };
|
||||
}
|
||||
|
||||
function make(opts: { index?: boolean; google?: boolean } = {}) {
|
||||
if (opts.index === false) process.env.TREK_PLACES_ENABLED = 'false';
|
||||
else delete process.env.TREK_PLACES_ENABLED;
|
||||
const database = { get: vi.fn(() => undefined) } as unknown as DatabaseService;
|
||||
const svc = new MapsService(database, {} as PlacePhotoCacheService);
|
||||
vi.spyOn(svc, 'keyedProvider').mockReturnValue(
|
||||
opts.google ? ({ id: 'google', key: 'test-key', source: 'user-row' } as ReturnType<MapsService['keyedProvider']>) : null,
|
||||
);
|
||||
return svc;
|
||||
}
|
||||
|
||||
const jsonResponse = (body: unknown, ok = true, status = 200) => ({ ok, status, json: async () => body });
|
||||
|
||||
beforeEach(() => {
|
||||
mockNearby.mockReset();
|
||||
mockNearby.mockResolvedValue([]);
|
||||
warn.mockClear();
|
||||
error.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
if (ORIGINAL_TREK_PLACES === undefined) delete process.env.TREK_PLACES_ENABLED;
|
||||
else process.env.TREK_PLACES_ENABLED = ORIGINAL_TREK_PLACES;
|
||||
});
|
||||
|
||||
describe('MapsService.nearbyPlaces', () => {
|
||||
it('MAPS-NEARBY-001: the index answers first, nearest first, with the distance on each record', async () => {
|
||||
const p = nextPoint();
|
||||
mockNearby.mockResolvedValue([
|
||||
indexRow('far', 'Far Cafe', p.lat + 0.003, p.lng),
|
||||
indexRow('near', 'Near Cafe', p.lat + 0.0005, p.lng),
|
||||
]);
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const out = await make({ google: true }).nearbyPlaces(1, p.lat, p.lng, { radius: 800, limit: 5 });
|
||||
|
||||
expect(mockNearby).toHaveBeenCalledWith(p.lat, p.lng, { radius: 800, limit: 5 });
|
||||
expect(out.source).toBe('trek-places');
|
||||
expect(out.places.map(r => r.name)).toEqual(['Near Cafe', 'Far Cafe']);
|
||||
expect(out.places[0].distance_m).toBe(56);
|
||||
expect(out.places[0].osm_id).toBe('gers:near');
|
||||
// A key is there, and still not spent.
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-002: with nothing in the index, Google is asked by distance inside the circle', async () => {
|
||||
const p = nextPoint();
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
places: [
|
||||
{ id: 'g-far', displayName: { text: 'Far' }, location: { latitude: p.lat + 0.002, longitude: p.lng } },
|
||||
{ id: 'g-shut', displayName: { text: 'Shut' }, location: { latitude: p.lat, longitude: p.lng }, businessStatus: 'CLOSED_PERMANENTLY' },
|
||||
{ id: 'g-near', displayName: { text: 'Near' }, formattedAddress: 'Somewhere 1', location: { latitude: p.lat + 0.0001, longitude: p.lng } },
|
||||
],
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const out = await make({ google: true }).nearbyPlaces(1, p.lat, p.lng, { lang: 'de' });
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toContain('places:searchNearby');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
maxResultCount: 20,
|
||||
rankPreference: 'DISTANCE',
|
||||
languageCode: 'de',
|
||||
locationRestriction: { circle: { center: { latitude: p.lat, longitude: p.lng }, radius: 500 } },
|
||||
});
|
||||
expect(out.source).toBe('google');
|
||||
expect(out.places.map(r => r.google_place_id)).toEqual(['g-near', 'g-far']);
|
||||
expect(out.places[0]).toMatchObject({ name: 'Near', address: 'Somewhere 1', distance_m: 11, source: 'google' });
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-003: a Google refusal is an error with its status, not an empty list', async () => {
|
||||
const p = nextPoint();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ error: { message: 'Quota exceeded' } }, false, 429)));
|
||||
|
||||
await expect(make({ google: true }).nearbyPlaces(1, p.lat, p.lng)).rejects.toMatchObject({
|
||||
message: 'Quota exceeded',
|
||||
status: 429,
|
||||
});
|
||||
expect(error).toHaveBeenCalledWith(expect.stringContaining('searchNearby failed with 429 userId=1 keySource=user-row'));
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-004: without a key OpenStreetMap answers, in the asked language, nearest first', async () => {
|
||||
const p = nextPoint();
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
elements: [
|
||||
{ type: 'node', id: 2, lat: p.lat + 0.001, lon: p.lng, tags: { name: 'Museum', 'name:de': 'Das Museum', tourism: 'museum' } },
|
||||
{ type: 'way', id: 3, center: { lat: p.lat + 0.0002, lon: p.lng }, tags: { name: 'Bakery', shop: 'bakery' } },
|
||||
],
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const out = await make().nearbyPlaces(1, p.lat, p.lng, { radius: 300, lang: 'de' });
|
||||
|
||||
const body = decodeURIComponent(String((fetchMock.mock.calls[0][1] as RequestInit).body));
|
||||
expect(body).toContain(`around:300,${p.lat},${p.lng}`);
|
||||
expect(out.source).toBe('openstreetmap');
|
||||
expect(out.places.map(r => r.name)).toEqual(['Bakery', 'Das Museum']);
|
||||
expect(out.places[0]).toMatchObject({ osm_id: 'way:3', category: 'shop_bakery', distance_m: 22 });
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-005: a failing index drops through to the next source and says so', async () => {
|
||||
const p = nextPoint();
|
||||
mockNearby.mockRejectedValue(new Error('index down'));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ elements: [] })));
|
||||
|
||||
const out = await make().nearbyPlaces(1, p.lat, p.lng);
|
||||
|
||||
expect(out).toEqual({ places: [], source: 'openstreetmap' });
|
||||
expect(warn).toHaveBeenCalledWith('TREK Places nearby failed, falling back:', 'index down');
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-006: with the index switched off it is never asked', async () => {
|
||||
const p = nextPoint();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ elements: [] })));
|
||||
|
||||
await make({ index: false }).nearbyPlaces(1, p.lat, p.lng);
|
||||
|
||||
expect(mockNearby).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-007: the same spot asked twice costs one lookup', async () => {
|
||||
const p = nextPoint();
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ places: [] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const svc = make({ google: true });
|
||||
|
||||
await svc.nearbyPlaces(1, p.lat, p.lng);
|
||||
await svc.nearbyPlaces(1, p.lat + 0.00001, p.lng);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(mockNearby).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('nearby helpers', () => {
|
||||
it('MAPS-NEARBY-008: the Overpass question is a named place of a visitable kind inside the circle, capped', () => {
|
||||
const q = nearbyOverpassQuery(52.5, 13.4, 250.4, 10);
|
||||
expect(q).toContain('nwr(around:250,52.5,13.4)[name][~"^(amenity|tourism|shop|leisure|historic)$"~"."];');
|
||||
expect(q).toContain('out center tags 30;');
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-009: unnamed, placeless and shut places are left out; the kind reads like a search category', () => {
|
||||
const origin = { lat: 0, lng: 0 };
|
||||
const out = overpassNearbyRecords([
|
||||
{ type: 'node', id: 1, lat: 0, lon: 0, tags: { amenity: 'bench' } },
|
||||
{ type: 'node', id: 2, tags: { name: 'Nowhere', amenity: 'cafe' } },
|
||||
{ type: 'node', id: 3, lat: 0, lon: 0, tags: { name: 'Gone', amenity: 'bar', disused: 'yes' } },
|
||||
{ type: 'node', id: 4, lat: 0, lon: 0.001, tags: { int_name: 'Park', leisure: 'park', website: 'park.example', 'addr:street': 'Main', 'addr:housenumber': '5' } },
|
||||
{ type: 'node', id: 5, lat: 0, lon: 0, tags: { name: 'Shopish', shop: 'yes', tourism: 'artwork' } },
|
||||
], origin, 'en', 10);
|
||||
expect(out.map(r => r.name)).toEqual(['Shopish', 'Park']);
|
||||
expect(out[0].category).toBe('artwork');
|
||||
expect(out[1]).toMatchObject({ address: 'Main 5', website: 'https://park.example', category: 'park', distance_m: 111 });
|
||||
});
|
||||
|
||||
it('MAPS-NEARBY-010: records without a position are dropped and the list keeps to the limit; the cache key rounds to ten metres', () => {
|
||||
const out = nearestFirst(
|
||||
[{ name: 'a', lat: 0, lng: 0.002 }, { name: 'b', lat: null, lng: null }, { name: 'c', lat: 0, lng: 0.001 }],
|
||||
{ lat: 0, lng: 0 },
|
||||
1,
|
||||
);
|
||||
expect(out).toEqual([{ name: 'c', lat: 0, lng: 0.001, distance_m: 111 }]);
|
||||
expect(nearbyCacheKey(52.516312, 13.377712, 500, 20, 'de')).toBe(nearbyCacheKey(52.51634, 13.37768, 500, 20, 'de'));
|
||||
expect(nearbyCacheKey(52.5163, 13.3777, 500, 20, 'de')).not.toBe(nearbyCacheKey(52.5163, 13.3777, 500, 20, 'en'));
|
||||
});
|
||||
});
|
||||
@@ -883,6 +883,23 @@ describe('searchNominatim (fetch stubbed)', () => {
|
||||
expect((results[1] as any).lat).toBeNull();
|
||||
expect((results[1] as any).lng).toBeNull();
|
||||
});
|
||||
|
||||
it('MAPS-108b: carries what the place is, with a shop named as one (#2282)', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [
|
||||
{ osm_type: 'node', osm_id: '5', lat: '52.5', lon: '13.4', name: 'Adlon', class: 'tourism', type: 'hotel' },
|
||||
{ osm_type: 'node', osm_id: '6', lat: '52.5', lon: '13.4', name: 'Bäcker', class: 'shop', type: 'bakery' },
|
||||
{ osm_type: 'node', osm_id: '7', lat: '52.5', lon: '13.4', name: 'Hut', class: 'building', type: 'yes' },
|
||||
{ osm_type: 'node', osm_id: '8', lat: '52.5', lon: '13.4', name: 'Bare' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
const results = await svc.searchNominatim('x');
|
||||
expect(results.map((r: any) => r.category)).toEqual(['hotel', 'shop_bakery', null, null]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── fetchOverpassDetails (fetch stubbed) ─────────────────────────────────────
|
||||
|
||||
@@ -209,6 +209,13 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'packing:updated', { item: { id: 9, name: 'X' } }, 'sock');
|
||||
});
|
||||
|
||||
it('forwards a packed count to the service, as the MCP tool does (#2296)', () => {
|
||||
const updateItem = vi.fn().mockReturnValue({ id: 9, packed_quantity: 3 });
|
||||
const svc = makeService({ updateItem, broadcast: vi.fn() } as Partial<PackingService>);
|
||||
new PackingController(svc).update(user, '5', '9', { packed_quantity: 3 });
|
||||
expect(updateItem).toHaveBeenCalledWith('5', '9', expect.objectContaining({ packed_quantity: 3 }), ['packed_quantity'], undefined, user.id);
|
||||
});
|
||||
|
||||
it('keeps a private update scoped to the owner (#858)', () => {
|
||||
const updateItem = vi.fn().mockReturnValue({ id: 9, name: 'X', is_private: 1, owner_id: 1 });
|
||||
const broadcast = vi.fn();
|
||||
|
||||
@@ -683,6 +683,23 @@ describe('legacy-quirk fixes', () => {
|
||||
// Omitted key leaves the quantity unchanged.
|
||||
expect((svc.updateItem(trip.id, item.id, { name: 'Wool socks' }, ['name'], undefined, user.id) as any).quantity).toBe(999);
|
||||
});
|
||||
|
||||
it('PACK-SVC-053b: a packed count keeps the box in step (#2296)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const item = svc.createItem(trip.id, { name: 'Shirts', quantity: 10 }, user.id) as any;
|
||||
const put = (data: Record<string, unknown>) => svc.updateItem(trip.id, item.id, data, Object.keys(data), undefined, user.id) as any;
|
||||
|
||||
expect(put({ packed_quantity: 7 })).toMatchObject({ packed_quantity: 7, checked: 0 });
|
||||
// Reaching the quantity ticks the item off and drops the partial count.
|
||||
expect(put({ packed_quantity: 12 })).toMatchObject({ packed_quantity: null, checked: 1 });
|
||||
// Unticking starts over from nothing.
|
||||
expect(put({ checked: 0 })).toMatchObject({ packed_quantity: null, checked: 0 });
|
||||
expect(put({ packed_quantity: 6 })).toMatchObject({ packed_quantity: 6, checked: 0 });
|
||||
// A quantity lowered to the count finishes the item; a rename leaves it alone.
|
||||
expect(put({ name: 'Tees' })).toMatchObject({ packed_quantity: 6, checked: 0 });
|
||||
expect(put({ quantity: 5 })).toMatchObject({ quantity: 5, packed_quantity: null, checked: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Create-path fields + bag trip scope (#2154) ───────────────────────────────
|
||||
|
||||
@@ -97,6 +97,24 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
});
|
||||
});
|
||||
|
||||
describe('file import enrichment (#2536)', () => {
|
||||
const file = { buffer: Buffer.from('gpx'), originalname: 'r.gpx' } as Express.Multer.File;
|
||||
it('hands the imported places to the Google pass only when asked', async () => {
|
||||
const enrichImportedFilePlaces = vi.fn();
|
||||
const s = svc({
|
||||
importGpx: vi.fn().mockReturnValue({ places: [{ id: 1 }], count: 1, skipped: 0 }),
|
||||
importMapFile: vi.fn().mockResolvedValue({ places: [{ id: 2 }], count: 1, summary: { totalPlacemarks: 1 } }),
|
||||
broadcast: vi.fn(), enrichImportedFilePlaces,
|
||||
} as Partial<PlacesService>);
|
||||
const c = new PlacesController(s, new RuntimeEnvService(), storageStub);
|
||||
c.importGpx(user, '5', file, {});
|
||||
expect(enrichImportedFilePlaces).not.toHaveBeenCalled();
|
||||
c.importGpx(user, '5', file, { enrich: 'true' });
|
||||
await c.importMap(user, '5', file, { enrich: 'true' });
|
||||
expect(enrichImportedFilePlaces.mock.calls).toEqual([['5', user.id, [{ id: 1 }]], ['5', user.id, [{ id: 2 }]]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /import/map', () => {
|
||||
const file = { buffer: Buffer.from('<kml/>'), originalname: 'm.kml' } as Express.Multer.File;
|
||||
it('400 without a file', async () => {
|
||||
@@ -547,3 +565,23 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /:id/image/from-file (#1242)', () => {
|
||||
it('maps every refusal to its status and broadcasts a success', async () => {
|
||||
const make = (result: unknown, extra: Partial<PlacesService> = {}) =>
|
||||
new PlacesController(svc({ setImageFromFile: vi.fn().mockResolvedValue(result), ...extra } as Partial<PlacesService>), new RuntimeEnvService(), storageStub);
|
||||
expect(await thrownAsync(() => make('not_found').imageFromFile(user, '5', '9', { file_id: 3 }))).toEqual({ status: 404, body: { error: 'File not found' } });
|
||||
expect(await thrownAsync(() => make('not_image').imageFromFile(user, '5', '9', { file_id: 3 }))).toEqual({ status: 400, body: { error: 'Only jpg, png, gif, webp images allowed' } });
|
||||
expect(await thrownAsync(() => make('too_large').imageFromFile(user, '5', '9', { file_id: 3 }))).toEqual({ status: 400, body: { error: 'Image too large' } });
|
||||
expect(await thrownAsync(() => make(null).imageFromFile(user, '5', '9', { file_id: 3 }))).toEqual({ status: 404, body: { error: 'Place not found' } });
|
||||
const broadcast = vi.fn(); const onUpdated = vi.fn()
|
||||
expect(await make({ id: 9 }, { broadcast, onUpdated } as Partial<PlacesService>).imageFromFile(user, '5', '9', { file_id: 3 }, 'sock')).toEqual({ place: { id: 9 } })
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'place:updated', { place: { id: 9 } }, 'sock')
|
||||
expect(onUpdated).toHaveBeenCalledWith(9)
|
||||
});
|
||||
|
||||
it('403 without place_edit', async () => {
|
||||
expect(await thrownAsync(() => new PlacesController(svc({ canEdit: vi.fn().mockReturnValue(false) }), new RuntimeEnvService(), storageStub).imageFromFile(user, '5', '9', { file_id: 3 }))).toEqual({ status: 403, body: { error: 'No permission' } });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -165,6 +165,20 @@ describe('list', () => {
|
||||
expect(places[0].name).toBe('Eiffel Tower');
|
||||
});
|
||||
|
||||
it('PLACE-SVC-005b — carries where each place lies: the cached region, else the bundled borders (#2537)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const berlin = createPlace(testDb, trip.id, { name: 'Brandenburger Tor', lat: 52.5163, lng: 13.3777 });
|
||||
const paris = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.8606, lng: 2.3376 });
|
||||
const nowhere = createPlace(testDb, trip.id, { name: 'Unplaced' });
|
||||
testDb.prepare('UPDATE places SET lat = NULL, lng = NULL, address = NULL WHERE id = ?').run(nowhere.id);
|
||||
testDb.prepare('INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, ?, ?, ?)').run(berlin.id, 'DE', 'DE-BE', 'Berlin');
|
||||
const byId = new Map((svc.list(String(trip.id), {}) as any[]).map(p => [p.id, p]));
|
||||
expect(byId.get(berlin.id)).toMatchObject({ country_code: 'DE', region_name: 'Berlin' });
|
||||
expect(byId.get(paris.id)).toMatchObject({ country_code: 'FR', region_name: null });
|
||||
expect(byId.get(nowhere.id)!.country_code).toBeNull();
|
||||
});
|
||||
|
||||
it('PLACE-SVC-005 — attaches tags array to each place (empty when none)', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
@@ -1284,6 +1298,13 @@ describe('enrichImportedPlaces', () => {
|
||||
expect(searchPlaces).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PLACE-SVC-058b — a file import enriches its points, never its paths (#2536)', async () => {
|
||||
const service = enrichSvc({ getMapsKey: vi.fn(() => null) });
|
||||
const spy = vi.spyOn(service, 'enrichImportedPlaces').mockResolvedValue();
|
||||
service.enrichImportedFilePlaces('1', 1, [{ id: 1 }, { id: 2, route_geometry: '[[1,2],[3,4]]' }]);
|
||||
expect(spy).toHaveBeenCalledWith('1', 1, [{ id: 1 }]);
|
||||
});
|
||||
|
||||
it('PLACE-SVC-059 — no-ops for an empty batch without touching the provider', async () => {
|
||||
const getMapsKey = vi.fn(() => 'key');
|
||||
await enrichSvc({ getMapsKey }).enrichImportedPlaces('1', 1, []);
|
||||
@@ -1439,6 +1460,36 @@ describe('zero-valued numeric fields', () => {
|
||||
|
||||
// ── LIKE metacharacter escaping (#1745) ───────────────────────────────────────
|
||||
|
||||
describe('setImageFromFile (#1242)', () => {
|
||||
const attach = (tripId: number, name: string, mime: string, size = 3) => {
|
||||
fs.writeFileSync(path.join(placesStorageFx.root, name), 'img');
|
||||
return Number(testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name, file_size, mime_type) VALUES (?, ?, ?, ?, ?)').run(tripId, name, name, size, mime).lastInsertRowid);
|
||||
};
|
||||
|
||||
it('PLACE-SVC-IMGFILE-001 — copies an attached picture in as the place image', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const fileId = attach(trip.id, 'holiday.jpg', 'image/jpeg');
|
||||
const updated = await svc.setImageFromFile(String(trip.id), String(place.id), fileId) as any;
|
||||
expect(updated.image_url).toMatch(/^\/uploads\/places\/[0-9a-f-]+\.jpg$/);
|
||||
expect(fs.existsSync(path.join(placesStorageFx.root, path.basename(updated.image_url)))).toBe(true);
|
||||
// A copy: the attachment itself is still there.
|
||||
expect(fs.existsSync(path.join(placesStorageFx.root, 'holiday.jpg'))).toBe(true);
|
||||
});
|
||||
|
||||
it('PLACE-SVC-IMGFILE-002 — refuses a file of another trip, a document and an oversized image', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
expect(await svc.setImageFromFile(String(trip.id), String(place.id), attach(other.id, 'x.jpg', 'image/jpeg'))).toBe('not_found');
|
||||
expect(await svc.setImageFromFile(String(trip.id), String(place.id), attach(trip.id, 'ticket.pdf', 'application/pdf'))).toBe('not_image');
|
||||
expect(await svc.setImageFromFile(String(trip.id), String(place.id), attach(trip.id, 'vector.svg', 'image/svg+xml'))).toBe('not_image');
|
||||
expect(await svc.setImageFromFile(String(trip.id), String(place.id), attach(trip.id, 'huge.jpg', 'image/jpeg', 50 * 1024 * 1024))).toBe('too_large');
|
||||
});
|
||||
});
|
||||
|
||||
describe('list search escaping', () => {
|
||||
it('PLACE-SVC-068 — a % or _ in the search term matches literally, not as a wildcard', () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isTravelBooking, travelOnly, withoutImages } from '../../../src/nest/share/share-view.helpers';
|
||||
|
||||
const snapshot = () => ({
|
||||
assignments: {
|
||||
1: [{ accommodation_id: null, place: { id: 10, image_url: 'a.jpg' } }, { accommodation_id: 5, place: { id: 20, image_url: 'b.jpg' } }],
|
||||
2: [{ accommodation_id: null, place: { id: 10, image_url: 'a.jpg' } }],
|
||||
},
|
||||
dayNotes: { 1: [{ id: 1 }] },
|
||||
places: [{ id: 10, image_url: 'a.jpg' }, { id: 20, image_url: 'b.jpg' }],
|
||||
reservations: [{ type: 'flight' }, { type: 'restaurant' }, { type: 'hotel' }, { type: 'cable_car' }, { type: null }],
|
||||
});
|
||||
|
||||
describe('share view helpers (#1712)', () => {
|
||||
it('SHARE-VIEW-001: knows travel bookings from the rest', () => {
|
||||
expect(['flight', 'train', 'ferry', 'cable_car', 'hotel'].every(isTravelBooking)).toBe(true);
|
||||
expect(['restaurant', 'tour', 'event', 'parking', undefined, 3].some(isTravelBooking)).toBe(false);
|
||||
});
|
||||
|
||||
it('SHARE-VIEW-002: travel only keeps the stay stops, the stay places and the travel bookings', () => {
|
||||
const out = travelOnly(snapshot(), new Set([20]));
|
||||
expect(out.assignments).toEqual({ 1: [{ accommodation_id: 5, place: { id: 20, image_url: 'b.jpg' } }] });
|
||||
expect(out.dayNotes).toEqual({});
|
||||
expect(out.places.map(p => p.id)).toEqual([20]);
|
||||
expect(out.reservations.map(r => r.type)).toEqual(['flight', 'hotel', 'cable_car']);
|
||||
});
|
||||
|
||||
it('SHARE-VIEW-003: without images clears every photo and leaves the rest alone', () => {
|
||||
const data = snapshot();
|
||||
const out = withoutImages(data);
|
||||
expect(out.places.every(p => p.image_url === null)).toBe(true);
|
||||
expect(Object.values(out.assignments).flat().every(a => a.place?.image_url === null)).toBe(true);
|
||||
expect(out.reservations).toBe(data.reservations);
|
||||
expect(data.places[0].image_url).toBe('a.jpg');
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,12 @@ describe('TripShareController', () => {
|
||||
expect(updatedRes.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('POST forwards the two narrowing options, as the MCP tool does (#1712)', () => {
|
||||
const createOrUpdate = vi.fn().mockReturnValue({ token: 't', created: true });
|
||||
new TripShareController(svc({ createOrUpdate } as Partial<ShareService>)).create(user, '5', { share_travel_only: true, share_hide_images: true }, res());
|
||||
expect(createOrUpdate).toHaveBeenCalledWith('5', user.id, expect.objectContaining({ share_travel_only: true, share_hide_images: true }));
|
||||
});
|
||||
|
||||
it('GET 404 without access, 403 without share_manage, returns info or a null token', () => {
|
||||
expect(thrown(() => new TripShareController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) })).get(user, '5'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
|
||||
// Reading returns the token itself, so it needs the same permission as
|
||||
|
||||
@@ -53,6 +53,7 @@ import { runMigrations } from '../../../src/db/migrations';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import {
|
||||
createUser, createTrip, addTripMember, createDay, createPlace, createDayAssignment,
|
||||
createDayAccommodation, createDayNote, createReservation,
|
||||
} from '../../helpers/factories';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
@@ -202,6 +203,8 @@ describe('get and remove', () => {
|
||||
share_packing: true,
|
||||
share_budget: false,
|
||||
share_collab: false,
|
||||
share_travel_only: false,
|
||||
share_hide_images: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -254,6 +257,7 @@ describe('getSharedTripData', () => {
|
||||
);
|
||||
expect(data.permissions).toEqual({
|
||||
share_map: true, share_bookings: true, share_packing: true, share_budget: true, share_collab: true,
|
||||
share_travel_only: false, share_hide_images: false,
|
||||
});
|
||||
expect(data.days).toHaveLength(1);
|
||||
const entries = data.assignments[day.id];
|
||||
@@ -352,6 +356,40 @@ describe('getSharedTripData', () => {
|
||||
expect(data.collab).toEqual([]);
|
||||
});
|
||||
|
||||
it('SHARE-SVC-019b: travel and stays only keeps transport, hotels and the stay stops (#1712)', () => {
|
||||
const { trip, token } = seedSharedTrip({ share_travel_only: true });
|
||||
const day = createDay(testDb, trip.id);
|
||||
const museum = createPlace(testDb, trip.id, { name: 'Museum' });
|
||||
const hotel = createPlace(testDb, trip.id, { name: 'Hotel' });
|
||||
const stay = createDayAccommodation(testDb, trip.id, hotel.id, day.id, day.id);
|
||||
createDayAssignment(testDb, day.id, museum.id);
|
||||
const stayStop = createDayAssignment(testDb, day.id, hotel.id);
|
||||
testDb.prepare('UPDATE day_assignments SET accommodation_id = ? WHERE id = ?').run(stay.id, stayStop.id);
|
||||
createDayNote(testDb, day.id, trip.id);
|
||||
for (const type of ['flight', 'hotel', 'restaurant', 'tour']) createReservation(testDb, trip.id, { type, title: type });
|
||||
|
||||
const data = svc.getSharedTripData(token)!;
|
||||
expect(data.permissions.share_travel_only).toBe(true);
|
||||
expect(data.assignments[day.id].map((a: any) => a.place.name)).toEqual(['Hotel']);
|
||||
expect(data.dayNotes).toEqual({});
|
||||
expect(data.places.map((p: any) => p.name)).toEqual(['Hotel']);
|
||||
expect(data.reservations.map((r: any) => r.type).sort()).toEqual(['flight', 'hotel']);
|
||||
});
|
||||
|
||||
it('SHARE-SVC-019c: without photos drops every place image and refuses the photo route (#1712)', async () => {
|
||||
const { trip, token } = seedSharedTrip({ share_hide_images: true });
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
|
||||
testDb.prepare("UPDATE places SET image_url = '/api/maps/place-photo/abc/bytes' WHERE id = ?").run(place.id);
|
||||
createDayAssignment(testDb, day.id, place.id);
|
||||
|
||||
const data = svc.getSharedTripData(token)!;
|
||||
expect(data.places[0].image_url).toBeNull();
|
||||
expect(data.assignments[day.id][0].place.image_url).toBeNull();
|
||||
serveKey.mockReturnValue('photos-google/abc');
|
||||
await expect(svc.getSharedPlacePhotoKey(token, 'abc')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('SHARE-SVC-020: baseCurrency falls back trip currency → EUR, with the owner default_currency winning (#1361)', () => {
|
||||
const { user, trip, token } = seedSharedTrip();
|
||||
expect(svc.getSharedTripData(token)!.baseCurrency).toBe('EUR');
|
||||
|
||||
@@ -697,6 +697,38 @@ describe('toggleCompanyHoliday', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('half company holidays (#2439)', () => {
|
||||
const entryOf = (planId: number, date: string) =>
|
||||
testDb.prepare('SELECT fraction FROM vacay_entries WHERE plan_id = ? AND date = ?').get(planId, date) as { fraction: number } | undefined;
|
||||
const holidayOf = (planId: number, date: string) =>
|
||||
testDb.prepare('SELECT fraction FROM vacay_company_holidays WHERE plan_id = ? AND date = ?').get(planId, date) as { fraction: number } | undefined;
|
||||
|
||||
it('VACAY-SVC-036b: a half company holiday halves a whole vacation day instead of wiping it', () => {
|
||||
const { user, plan } = setupUserWithPlan();
|
||||
svc.toggleEntry(user.id, plan.id, '2025-12-24', 1);
|
||||
expect(svc.toggleCompanyHoliday(plan.id, '2025-12-24', 'Christmas Eve', undefined, 0.5)).toEqual({ action: 'added', fraction: 0.5 });
|
||||
expect(entryOf(plan.id, '2025-12-24')?.fraction).toBe(0.5);
|
||||
expect(holidayOf(plan.id, '2025-12-24')?.fraction).toBe(0.5);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-036c: the other size converts the holiday, the same size clears it', () => {
|
||||
const { user, plan } = setupUserWithPlan();
|
||||
svc.toggleCompanyHoliday(plan.id, '2025-12-31', undefined, undefined, 0.5);
|
||||
svc.toggleEntry(user.id, plan.id, '2025-12-31', 0.5);
|
||||
expect(svc.toggleCompanyHoliday(plan.id, '2025-12-31', undefined, undefined, 1)).toEqual({ action: 'updated', fraction: 1 });
|
||||
expect(entryOf(plan.id, '2025-12-31')).toBeUndefined();
|
||||
expect(svc.toggleCompanyHoliday(plan.id, '2025-12-31', undefined, undefined, 1)).toEqual({ action: 'removed' });
|
||||
expect(holidayOf(plan.id, '2025-12-31')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('VACAY-SVC-036d: leave on a half company holiday is half a day, whatever was asked', () => {
|
||||
const { user, plan } = setupUserWithPlan();
|
||||
testDb.prepare('UPDATE vacay_plans SET company_holidays_enabled = 1 WHERE id = ?').run(plan.id);
|
||||
svc.toggleCompanyHoliday(plan.id, '2025-12-24', undefined, undefined, 0.5);
|
||||
expect(svc.toggleEntry(user.id, plan.id, '2025-12-24', 1)).toMatchObject({ action: 'added', fraction: 0.5 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── acceptInvite / declineInvite / cancelInvite ───────────────────────────────
|
||||
|
||||
describe('acceptInvite', () => {
|
||||
|
||||
Reference in New Issue
Block a user