chore: move day backend to proper DI

This commit is contained in:
jubnl
2026-07-27 20:57:01 +02:00
parent e62628bf93
commit 2d1eec76c3
35 changed files with 1491 additions and 1123 deletions
+9 -64
View File
@@ -1,13 +1,15 @@
/**
* Unit tests for MCP resources (resources.ts).
* Tests all 9 legacy-registrar resources via InMemoryTransport + Client
* Tests all 7 legacy-registrar resources via InMemoryTransport + Client
* (trek://categories moved to the DI-discovered CategoriesMcp — see
* tools-categories.test.ts; trek://trips/{tripId}/todos moved to TodoMcp —
* see tools-todos.test.ts; trek://trips/{tripId}/packing and .../packing/bags
* moved to PackingMcp — see tools-packing.test.ts;
* trek://trips/{tripId}/days/{dayId}/notes moved to DayNotesMcp — see
* tools-notes.test.ts; trek://trips/{tripId}/collab-notes moved to CollabMcp —
* see tools-notes.test.ts).
* see tools-notes.test.ts; trek://trips/{tripId}/days and
* .../accommodations moved to DaysMcp — see tools-days.test.ts and
* tools-days-accommodations.test.ts).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
@@ -46,7 +48,7 @@ vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, addTripMember, createBudgetItem, createReservation, createCollabNote, createBucketListItem, createVisitedCountry, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { createUser, createTrip, createPlace, addTripMember, createBudgetItem, createReservation, createCollabNote, createBucketListItem, createVisitedCountry } from '../../helpers/factories';
import { createMcpHarness, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
@@ -151,38 +153,8 @@ describe('Resource: trek://trips/{tripId}', () => {
});
});
describe('Resource: trek://trips/{tripId}/days', () => {
it('returns days with assignments in order', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, day1.id, place.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const days = parseResourceResult(result) as any[];
expect(days).toHaveLength(2);
expect(days[0].day_number).toBe(1);
expect(days[0].assignments).toHaveLength(1);
expect(days[1].day_number).toBe(2);
expect(days[1].assignments).toHaveLength(0);
});
});
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}/days` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// 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 () => {
@@ -250,35 +222,8 @@ describe('Resource: trek://trips/{tripId}/budget', () => {
// The trek://trips/{tripId}/days/{dayId}/notes resource moved to the
// DI-discovered DayNotesMcp — see tools-notes.test.ts.
describe('Resource: trek://trips/{tripId}/accommodations', () => {
it('returns accommodations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' });
createDayAccommodation(testDb, trip.id, place.id, day1.id, day2.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].place_name).toBe('Grand Hotel');
});
});
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}/accommodations` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// The trek://trips/{tripId}/accommodations resource moved to the
// DI-discovered DaysMcp — see tools-days-accommodations.test.ts.
describe('Resource: trek://trips/{tripId}/members', () => {
it('returns owner and collaborators', async () => {
@@ -1,7 +1,10 @@
/**
* Unit tests for MCP day and accommodation tools:
* create_day, delete_day,
* create_accommodation, update_accommodation, delete_accommodation.
* create_accommodation, create_place_accommodation, update_accommodation,
* delete_accommodation — plus the trek://trips/{tripId}/accommodations
* resource (moved from resources.test.ts when the legacy registrar was
* ported to the DI-discovered DaysMcp).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -15,7 +18,18 @@ const { testDb, dbMock } = vi.hoisted(() => {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
// Real-SQL implementation: create_place_accommodation's createPlace
// returns getPlaceWithTags(placeId) — a null stub would make the tool's
// atomic branch throw before the accommodation insert.
getPlaceWithTags: (placeId: number | string) => {
const place = 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) as { category_id: number | null; category_name: string; category_color: string; category_icon: string } | undefined;
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) =>
@@ -38,7 +52,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAccommodation } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -294,3 +308,79 @@ describe('Tool: delete_accommodation', () => {
});
});
});
// ---------------------------------------------------------------------------
// create_place_accommodation
// ---------------------------------------------------------------------------
describe('Tool: create_place_accommodation', () => {
it('creates the place and the accommodation atomically and broadcasts both', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
await withHarness(user.id, async (h) => {
const result = await h.client.callTool({
name: 'create_place_accommodation',
arguments: {
tripId: trip.id, name: 'Ryokan Sakura', start_day_id: day.id, end_day_id: day.id,
check_in: '15:00', accommodation_notes: 'Tatami room',
},
});
const data = parseToolResult(result) as { place: { id: number; name: string }; accommodation: { id: number } };
expect(data.place.name).toBe('Ryokan Sakura');
expect(data.accommodation).toMatchObject({ place_id: data.place.id, start_day_id: day.id, end_day_id: day.id, notes: 'Tatami room' });
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'place:created', expect.objectContaining({ place: expect.anything() }));
expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'accommodation:created', expect.objectContaining({ accommodation: expect.anything() }));
// The partner hotel reservation rides along.
const linked = testDb.prepare('SELECT type FROM reservations WHERE accommodation_id = ?').get(data.accommodation.id) as { type: string };
expect(linked.type).toBe('hotel');
});
});
it('reports the day-validation errors without creating anything', 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_place_accommodation',
arguments: { tripId: trip.id, name: 'Nowhere Inn', start_day_id: 99999, end_day_id: 99999 },
});
expect(result.isError).toBe(true);
expect(testDb.prepare('SELECT COUNT(*) as n FROM places WHERE trip_id = ?').get(trip.id)).toMatchObject({ n: 0 });
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/accommodations resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/accommodations', () => {
it('returns accommodations for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' });
createDayAccommodation(testDb, trip.id, place.id, day1.id, day2.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/accommodations` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].place_name).toBe('Grand Hotel');
});
});
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}/accommodations` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
+43 -3
View File
@@ -1,5 +1,7 @@
/**
* Unit tests for MCP day tools: update_day.
* Unit tests for the DI-discovered DaysMcp: the update_day tool and the
* trek://trips/{tripId}/days resource (moved from resources.test.ts when the
* legacy registrar was ported).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -35,8 +37,8 @@ vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createUser, createTrip, createDay, createPlace, createDayAssignment } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -140,3 +142,41 @@ describe('Tool: update_day', () => {
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/days resource (moved from resources.test.ts)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/days', () => {
it('returns days with assignments in order', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day1 = createDay(testDb, trip.id, { day_number: 1 });
const day2 = createDay(testDb, trip.id, { day_number: 2 });
const place = createPlace(testDb, trip.id);
createDayAssignment(testDb, day1.id, place.id);
void day2;
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days` });
const days = parseResourceResult(result) as any[];
expect(days).toHaveLength(2);
expect(days[0].day_number).toBe(1);
expect(days[0].assignments).toHaveLength(1);
expect(days[1].day_number).toBe(2);
expect(days[1].assignments).toHaveLength(0);
});
});
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}/days` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
@@ -3,7 +3,7 @@ import { HttpException } from '@nestjs/common';
import { DaysController } from '../../../src/nest/days/days.controller';
import { DayNotesController } from '../../../src/nest/days/day-notes.controller';
import { DayNoteCreateDto, DayNoteUpdateDto } from '../../../src/nest/days/day-notes.dto';
import { DayReorderError } from '../../../src/services/dayService';
import { DayReorderError } from '../../../src/nest/days/days.service';
import type { DaysService } from '../../../src/nest/days/days.service';
import type { DayNotesService } from '../../../src/nest/days/day-notes.service';
import type { User } from '../../../src/types';
@@ -1,5 +1,7 @@
/**
* Unit tests for dayService — DAY-SVC-001 through DAY-SVC-030.
* Unit tests for the DI-native DaysService — DAY-SVC-001 through DAY-SVC-026
* moved 1:1 from the legacy tests/unit/services/dayService.test.ts;
* DAY-SVC-027 through DAY-SVC-032 pin the days.bridge delegation.
* Uses a real in-memory SQLite DB so SQL logic is exercised faithfully.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -39,26 +41,23 @@ vi.mock('../../../src/config', () => ({
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { DaysService, addDays } from '../../../src/nest/days/days.service';
import {
verifyTripAccess,
getAssignmentsForDay,
listDays,
createDay as svcCreateDay,
getDay,
updateDay,
deleteDay,
listAccommodations,
validateAccommodationRefs,
createAccommodation,
getAccommodation,
updateAccommodation,
deleteAccommodation,
} from '../../../src/services/dayService';
getDay as bridgeGetDay,
listDays as bridgeListDays,
listAccommodations as bridgeListAccommodations,
restampReservationDates as bridgeRestampReservationDates,
resyncAccommodationDays as bridgeResyncAccommodationDays,
} from '../../../src/nest/days/days.bridge';
const svc = new DaysService(new DatabaseService(testDb));
beforeAll(() => {
createTables(testDb);
@@ -79,7 +78,7 @@ describe('verifyTripAccess', () => {
it('DAY-SVC-001 — returns trip row for owner', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = verifyTripAccess(trip.id, user.id) as any;
const result = svc.verifyTripAccess(trip.id, user.id) as any;
expect(result).toBeDefined();
expect(result.id).toBe(trip.id);
});
@@ -88,7 +87,7 @@ describe('verifyTripAccess', () => {
const { user: owner } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
expect(verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
expect(svc.verifyTripAccess(trip.id, stranger.id)).toBeFalsy();
});
});
@@ -99,7 +98,7 @@ describe('getAssignmentsForDay', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
expect(getAssignmentsForDay(day.id)).toEqual([]);
expect(svc.getAssignmentsForDay(day.id)).toEqual([]);
});
it('DAY-SVC-004 — returns assignments with nested place object', () => {
@@ -109,7 +108,7 @@ describe('getAssignmentsForDay', () => {
const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower', lat: 48.8, lng: 2.3 }) as any;
createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
const assignments = getAssignmentsForDay(day.id) as any[];
const assignments = svc.getAssignmentsForDay(day.id) as any[];
expect(assignments).toHaveLength(1);
expect(assignments[0].place).toBeDefined();
expect(assignments[0].place.name).toBe('Eiffel Tower');
@@ -123,7 +122,7 @@ describe('getAssignmentsForDay', () => {
const place = createPlace(testDb, trip.id, { name: 'No Tags' }) as any;
createDayAssignment(testDb, day.id, place.id);
const assignments = getAssignmentsForDay(day.id) as any[];
const assignments = svc.getAssignmentsForDay(day.id) as any[];
expect(Array.isArray(assignments[0].place.tags)).toBe(true);
});
@@ -136,19 +135,19 @@ describe('getAssignmentsForDay', () => {
createDayAssignment(testDb, day.id, p1.id, { order_index: 2 });
createDayAssignment(testDb, day.id, p2.id, { order_index: 1 });
const assignments = getAssignmentsForDay(day.id) as any[];
const assignments = svc.getAssignmentsForDay(day.id) as any[];
expect(assignments[0].place.name).toBe('First');
expect(assignments[1].place.name).toBe('Second');
});
});
// ── listDays ──────────────────────────────────────────────────────────────────
// ── list ──────────────────────────────────────────────────────────────────────
describe('listDays', () => {
describe('list', () => {
it('DAY-SVC-007 — returns { days: [] } for trip with no days', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = listDays(trip.id) as any;
const result = svc.list(trip.id) as any;
expect(result.days).toEqual([]);
});
@@ -156,20 +155,20 @@ describe('listDays', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id);
const result = listDays(trip.id) as any;
const result = svc.list(trip.id) as any;
expect(result.days).toHaveLength(1);
expect(Array.isArray(result.days[0].assignments)).toBe(true);
});
});
// ── createDay ─────────────────────────────────────────────────────────────────
// ── create ────────────────────────────────────────────────────────────────────
describe('createDay (service)', () => {
describe('create (service)', () => {
it('DAY-SVC-009 — creates a day with auto-incremented day_number', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const d1 = svcCreateDay(trip.id) as any;
const d2 = svcCreateDay(trip.id) as any;
const d1 = svc.create(trip.id) as any;
const d2 = svc.create(trip.id) as any;
expect(d1.day_number).toBe(1);
expect(d2.day_number).toBe(2);
});
@@ -177,20 +176,20 @@ describe('createDay (service)', () => {
it('DAY-SVC-010 — returns day with empty assignments array', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = svcCreateDay(trip.id) as any;
const day = svc.create(trip.id) as any;
expect(Array.isArray(day.assignments)).toBe(true);
expect(day.assignments).toHaveLength(0);
});
});
// ── getDay / updateDay / deleteDay ────────────────────────────────────────────
// ── getDay / update / remove ──────────────────────────────────────────────────
describe('getDay', () => {
it('DAY-SVC-011 — returns day when id and tripId match', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const found = getDay(day.id, trip.id) as any;
const found = svc.getDay(day.id, trip.id) as any;
expect(found).toBeDefined();
expect(found.id).toBe(day.id);
});
@@ -198,16 +197,16 @@ describe('getDay', () => {
it('DAY-SVC-012 — returns undefined for non-existent day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getDay(99999, trip.id)).toBeUndefined();
expect(svc.getDay(99999, trip.id)).toBeUndefined();
});
});
describe('updateDay', () => {
describe('update', () => {
it('DAY-SVC-013 — updates notes and returns updated day with assignments', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const updated = updateDay(day.id, day, { notes: 'Updated notes' }) as any;
const updated = svc.update(day.id, day, { notes: 'Updated notes' }) as any;
expect(updated.notes).toBe('Updated notes');
expect(Array.isArray(updated.assignments)).toBe(true);
});
@@ -216,18 +215,18 @@ describe('updateDay', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const updated = updateDay(day.id, day, { title: 'Day 1 - City Tour' }) as any;
const updated = svc.update(day.id, day, { title: 'Day 1 - City Tour' }) as any;
expect(updated.title).toBe('Day 1 - City Tour');
});
});
describe('deleteDay', () => {
describe('remove', () => {
it('DAY-SVC-015 — deletes the day', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
deleteDay(day.id);
expect(getDay(day.id, trip.id)).toBeUndefined();
svc.remove(day.id);
expect(svc.getDay(day.id, trip.id)).toBeUndefined();
});
});
@@ -239,7 +238,7 @@ describe('validateAccommodationRefs', () => {
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = validateAccommodationRefs(trip.id, place.id, day.id, day.id);
const errors = svc.validateAccommodationRefs(trip.id, place.id, day.id, day.id);
expect(errors).toHaveLength(0);
});
@@ -247,7 +246,7 @@ describe('validateAccommodationRefs', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const errors = validateAccommodationRefs(trip.id, 99999, day.id, day.id);
const errors = svc.validateAccommodationRefs(trip.id, 99999, day.id, day.id);
expect(errors.some((e: any) => e.field === 'place_id')).toBe(true);
});
@@ -256,7 +255,7 @@ describe('validateAccommodationRefs', () => {
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const errors = validateAccommodationRefs(trip.id, place.id, 99999, day.id);
const errors = svc.validateAccommodationRefs(trip.id, place.id, 99999, day.id);
expect(errors.some((e: any) => e.field === 'start_day_id')).toBe(true);
});
});
@@ -270,7 +269,7 @@ describe('createAccommodation', () => {
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' }) as any;
const accom = createAccommodation(trip.id, {
const accom = svc.createAccommodation(trip.id, {
place_id: place.id,
start_day_id: day.id,
end_day_id: day.id,
@@ -288,7 +287,7 @@ describe('createAccommodation', () => {
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'City Hotel' }) as any;
const accom = createAccommodation(trip.id, {
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
@@ -308,7 +307,7 @@ describe('getAccommodation', () => {
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id) as any;
const found = getAccommodation(accom.id, trip.id) as any;
const found = svc.getAccommodation(accom.id, trip.id) as any;
expect(found).toBeDefined();
expect(found.id).toBe(accom.id);
});
@@ -316,7 +315,7 @@ describe('getAccommodation', () => {
it('DAY-SVC-022 — returns undefined for non-existent accommodation', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(getAccommodation(99999, trip.id)).toBeUndefined();
expect(svc.getAccommodation(99999, trip.id)).toBeUndefined();
});
});
@@ -328,12 +327,12 @@ describe('updateAccommodation', () => {
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const existing = getAccommodation(accom.id, trip.id)!;
const updated = updateAccommodation(accom.id, existing as any, { check_in: '16:00', check_out: '12:00' }) as any;
const existing = svc.getAccommodation(accom.id, trip.id)!;
const updated = svc.updateAccommodation(accom.id, existing as any, { check_in: '16:00', check_out: '12:00' }) as any;
expect(updated).toBeDefined();
// Verify linked reservation metadata was synced
@@ -349,15 +348,15 @@ describe('updateAccommodation', () => {
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
confirmation: 'ABC123',
}) as any;
const existing = getAccommodation(accom.id, trip.id)!;
updateAccommodation(accom.id, existing as any, { check_in: '14:00' });
const existing = svc.getAccommodation(accom.id, trip.id)!;
svc.updateAccommodation(accom.id, existing as any, { check_in: '14:00' });
const row = getAccommodation(accom.id, trip.id) as any;
const row = svc.getAccommodation(accom.id, trip.id) as any;
expect(row.confirmation).toBe('ABC123');
});
});
@@ -370,17 +369,17 @@ describe('deleteAccommodation', () => {
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
const place = createPlace(testDb, trip.id, { name: 'Hotel' }) as any;
const accom = createAccommodation(trip.id, {
const accom = svc.createAccommodation(trip.id, {
place_id: place.id, start_day_id: day.id, end_day_id: day.id,
}) as any;
const reservation = testDb.prepare('SELECT id FROM reservations WHERE accommodation_id = ?').get(accom.id) as any;
const result = deleteAccommodation(accom.id);
const result = svc.deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBe(reservation.id);
// Accommodation is gone
expect(getAccommodation(accom.id, trip.id)).toBeUndefined();
expect(svc.getAccommodation(accom.id, trip.id)).toBeUndefined();
// Reservation is gone
const deletedRes = testDb.prepare('SELECT id FROM reservations WHERE id = ?').get(reservation.id);
@@ -397,7 +396,86 @@ describe('deleteAccommodation', () => {
// Remove the auto-created reservation so there's no linked one
testDb.prepare('DELETE FROM reservations WHERE accommodation_id = ?').run(accom.id);
const result = deleteAccommodation(accom.id);
const result = svc.deleteAccommodation(accom.id);
expect(result.linkedReservationId).toBeNull();
});
});
// ── days.bridge delegation (out-of-container consumers) ───────────────────────
describe('days.bridge', () => {
it('DAY-SVC-027 — getDay delegates to DaysService.getDay', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
expect(bridgeGetDay(day.id, trip.id)!.id).toBe(day.id);
expect(bridgeGetDay(99999, trip.id)).toBeUndefined();
});
it('DAY-SVC-028 — listDays delegates to DaysService.list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createDay(testDb, trip.id);
const result = bridgeListDays(trip.id);
expect(result.days).toHaveLength(1);
expect(Array.isArray(result.days[0].assignments)).toBe(true);
});
it('DAY-SVC-029 — listAccommodations delegates to DaysService.listAccommodations', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id);
const place = createPlace(testDb, trip.id, { name: 'Ryokan' });
createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
const rows = bridgeListAccommodations(trip.id) as { place_name: string }[];
expect(rows).toHaveLength(1);
expect(rows[0].place_name).toBe('Ryokan');
});
it('DAY-SVC-030 — addDays stays UTC-only across month and year rollovers', () => {
expect(addDays('2026-02-27', 3)).toBe('2026-03-02');
expect(addDays('2026-12-31', 1)).toBe('2027-01-01');
expect(addDays('2026-06-07', -7)).toBe('2026-05-31');
});
it('DAY-SVC-031 — restampReservationDates re-stamps a booking onto its day\'s new date', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id, { date: '2026-01-01' });
testDb.prepare(
'INSERT INTO reservations (trip_id, day_id, title, reservation_time) VALUES (?, ?, ?, ?)'
).run(trip.id, day.id, 'Dinner', '2026-01-01T19:00');
bridgeRestampReservationDates(
trip.id,
new Map([[day.id, '2026-01-01']]),
new Map([[day.id, '2026-01-05']]),
);
const row = testDb.prepare('SELECT reservation_time FROM reservations WHERE trip_id = ?').get(trip.id) as { reservation_time: string };
expect(row.reservation_time).toBe('2026-01-05T19:00');
});
it('DAY-SVC-032 — resyncAccommodationDays re-anchors a stay to the day holding its old date', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const d1 = createDay(testDb, trip.id, { date: '2026-01-01' });
const d2 = createDay(testDb, trip.id, { date: '2026-01-02' });
const place = createPlace(testDb, trip.id, { name: 'Hotel' });
const accom = createDayAccommodation(testDb, trip.id, place.id, d1.id, d1.id);
// The trip's range shifted: d1 now holds 01-02 and d2 holds 01-03; the day
// holding the stay's old date (01-01) no longer exists → the stay stays
// glued to its rows, but a range where d2 takes over 01-01 re-anchors it.
testDb.prepare('UPDATE days SET date = ? WHERE id = ?').run('2026-01-02', d1.id);
testDb.prepare('UPDATE days SET date = ? WHERE id = ?').run('2026-01-01', d2.id);
testDb.prepare('UPDATE days SET day_number = 0 WHERE id = ?').run(d2.id);
bridgeResyncAccommodationDays(trip.id, new Map([[d1.id, '2026-01-01'], [d2.id, '2026-01-02']]));
const row = testDb.prepare('SELECT start_day_id, end_day_id FROM day_accommodations WHERE id = ?').get(accom.id) as { start_day_id: number; end_day_id: number };
expect(row.start_day_id).toBe(d2.id);
expect(row.end_day_id).toBe(d2.id);
});
});
+3 -2
View File
@@ -25,7 +25,6 @@ const { tripSvc } = vi.hoisted(() => ({
},
}));
vi.mock('../../../src/services/tripService', () => tripSvc);
vi.mock('../../../src/services/dayService', () => ({ listDays: () => ({ days: [1] }), listAccommodations: () => [] }));
vi.mock('../../../src/services/placeService', () => ({ listPlaces: () => [] }));
vi.mock('../../../src/services/budgetService', () => ({
listBudgetItems: () => [],
@@ -36,6 +35,7 @@ import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { FilesService } from '../../../src/nest/files/files.service';
import type { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import type { DaysService } from '../../../src/nest/days/days.service';
import { rebaseTripCurrency } from '../../../src/services/budgetService';
const todoStub = { listItems: () => [] } as unknown as TodoService;
@@ -43,7 +43,8 @@ const packingListItems = vi.fn(() => []);
const packingStub = { listItems: packingListItems } as unknown as PackingService;
const filesStub = { listFiles: () => [] } as unknown as FilesService;
const reservationsStub = { list: () => [] } as unknown as ReservationsService;
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub, packingStub, filesStub, reservationsStub); }
const daysStub = { list: () => ({ days: [1] }), listAccommodations: () => [] } as unknown as DaysService;
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub, packingStub, filesStub, reservationsStub, daysStub); }
beforeEach(() => vi.clearAllMocks());
describe('TripsService (wrapper delegation + bundle/copy/notify helpers)', () => {
@@ -4,7 +4,7 @@
* per-plugin data db is cached, a granted db:own call works through the wired
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
* DI-native domains (budget/reservations/tags/categories/todo/packing/
* day-notes/assignments/oauth/llm-config/files/collab/vacay) are
* day-notes/days/assignments/oauth/llm-config/files/collab/vacay) are
* constructor-injected stubs; legacy services/* domains stay path-mocked until
* their own DI migration lands.
*/
@@ -91,12 +91,14 @@ vi.mock('../../../src/services/placeService', () => ({
updatePlace: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
deletePlace: vi.fn((_tid: string, pid: string) => pid !== '99'),
}));
vi.mock('../../../src/services/dayService', () => ({
createDay: vi.fn((tid: number) => ({ id: 20, trip_id: tid, assignments: [] })),
// Days are a constructor-injected stub (same behaviors as the old path mock,
// mapped onto the DaysService method names).
const daysStub = {
create: vi.fn((tid: number) => ({ id: 20, trip_id: tid, assignments: [] })),
getDay: vi.fn((id: number) => (id === 99 ? undefined : { id, title: null })),
updateDay: vi.fn((id: number) => ({ id, assignments: [] })),
deleteDay: vi.fn(),
listDays: vi.fn((tid: number) => ({ days: [{ id: 3, trip_id: Number(tid), day_number: 1, assignments: [], notes_items: [] }] })),
update: vi.fn((id: number) => ({ id, assignments: [] })),
remove: vi.fn(),
list: vi.fn((tid: number) => ({ days: [{ id: 3, trip_id: Number(tid), day_number: 1, assignments: [], notes_items: [] }] })),
listAccommodations: vi.fn((tid: number) => [{ id: 11, trip_id: Number(tid), place_name: 'Ryokan' }]),
// place 999 / day 88 don't belong to the trip
validateAccommodationRefs: vi.fn((_tid: number, placeId?: number, startDayId?: number, endDayId?: number) => {
@@ -109,7 +111,7 @@ vi.mock('../../../src/services/dayService', () => ({
getAccommodation: vi.fn((id: number) => (Number(id) === 404 ? undefined : { id: Number(id), place_id: 7, start_day_id: 3, end_day_id: 4 })),
updateAccommodation: vi.fn((id: number, _existing: unknown, fields: Record<string, unknown>) => ({ id: Number(id), ...fields })),
deleteAccommodation: vi.fn((id: number) => (Number(id) === 61 ? { linkedReservationId: 40, deletedBudgetItemId: 9 } : { linkedReservationId: null, deletedBudgetItemId: null })),
}));
} as unknown as DaysService;
// Assignments is a constructor-injected stub (same behaviors as the old path mock).
const assignmentsStub = {
createAssignment: vi.fn((dayId: number, placeId: number, notes: string | null) => ({ id: 30, day_id: dayId, place_id: placeId, notes })),
@@ -311,6 +313,7 @@ import type { CategoriesService } from '../../../src/nest/categories/categories.
import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { DayNotesService } from '../../../src/nest/days/day-notes.service';
import type { DaysService } from '../../../src/nest/days/days.service';
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.service';
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
@@ -322,7 +325,7 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
// The factory under test, wired exactly like PluginsModule does — but with the
// DI-native domain services replaced by the stubs above. The shim keeps the
// ~45 historical call sites unchanged and supplies a default no-op router.
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub);
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
@@ -591,7 +594,7 @@ describe('host-deps factory — reservations, day notes, cross-trip + addon read
expect(acc.result).toEqual([{ id: 11, trip_id: 1, place_name: 'Ryokan' }]);
});
it('accommodations create validates refs, creates via dayService and emits the cascade broadcasts', async () => {
it('accommodations create validates refs, creates via DaysService and emits the cascade broadcasts', async () => {
const h = host('db:write:accommodations');
const good = await call(h, 'accommodations.create', { tripId: 1, input: { place_id: 7, start_day_id: 3, end_day_id: 4, check_in: '15:00' } });
expect(good.ok).toBe(true);
@@ -35,9 +35,13 @@ import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createReservation, createPlace, createDay, createDayAssignment, createDayNote, addTripMember } from '../../helpers/factories';
import { exportICS, generateDays, deleteOldCover, updateTrip, transferOwnership, createGuest, renameGuest, deleteGuest, listMembers, addMember } from '../../../src/services/tripService';
import { createAccommodation } from '../../../src/services/dayService';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { DaysService } from '../../../src/nest/days/days.service';
import fs from 'fs';
const daysSvc = new DaysService(new DatabaseService(testDb));
const createAccommodation = daysSvc.createAccommodation.bind(daysSvc);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);