chore: move trip backend to proper DI

Fold the legacy tripService SQL into TripsService; port the trips MCP registrar/resources/trip-summary prompt to trips.mcp.ts and the share-link tools to share.mcp.ts (predicate access for the trips:delete/trips:share/canReadTrips gates, deprecation notice via the attach ctx); adopt trips.dto.ts and clear the seven allow-list entries; delete todo/share bridges with their last consumers. Includes the trailing quirk fixes: transactional deleteTrip/deleteGuest, owner display_name in listMembers.
This commit is contained in:
jubnl
2026-07-29 01:53:40 +02:00
parent a3c2cfa4b2
commit 530c7cb005
34 changed files with 3576 additions and 1804 deletions
+7 -3
View File
@@ -42,10 +42,13 @@ const SAMPLE_ICS =
'BEGIN:VEVENT\r\nUID:trek-trip-x@trek\r\nDTSTAMP:20260101T000000Z\r\n' +
'DTSTART;VALUE=DATE:20260101\r\nDTEND;VALUE=DATE:20260102\r\nSUMMARY:Sample\r\nEND:VEVENT\r\n' +
'END:VCALENDAR\r\n';
const { exportICS } = vi.hoisted(() => ({ exportICS: vi.fn() }));
vi.mock('../../src/services/tripService', () => ({ exportICS }));
// Since the trip fold, FeedsService injects TripsService — the mock is a spy on
// the container singleton (created in beforeAll, after build()).
const exportICS = vi.fn();
import { FeedsModule } from '../../src/nest/feeds/feeds.module';
import { TripsService } from '../../src/nest/trips/trips.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
const BASE = 'https://trek.example.test';
@@ -56,7 +59,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
let prevAppUrl: string | undefined;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, FeedsModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, RealtimeModule, FeedsModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
@@ -70,6 +73,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
seedUser(db as never, { id: 1, username: 'e2e-user' });
seedUser(db as never, { id: 2, username: 'other-user', email: 'other@example.test' });
app = await build();
vi.spyOn(app.get(TripsService), 'exportICS').mockImplementation(exportICS as never);
server = app.getHttpServer();
});
+56 -24
View File
@@ -1,8 +1,8 @@
/**
* Trips module e2e — exercises the migrated /api/trips aggregate-root endpoints
* through the real JwtAuthGuard against a temp SQLite db. tripService, the bundle
* list-services, auditLog, demo, the permission check, canAccessTrip and the
* WebSocket broadcast are mocked.
* through the real JwtAuthGuard against a temp SQLite db. TripsService runs its
* real (DI-native) SQL — trips/trip_members/days DDL below; auditLog, demo, the
* permission check, canAccessTrip and the WebSocket broadcast are mocked.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
import request from 'supertest';
@@ -21,7 +21,25 @@ const { db } = vi.hoisted(() => {
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
avatar TEXT, display_name TEXT, is_guest INTEGER NOT NULL DEFAULT 0);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
// TripsService runs its real SQL (DI-native since the trip fold) — full trip
// column set for TRIP_SELECT + create/update/delete, plus the membership and
// day-content tables generateDays/listMembers/deleteTrip touch.
tmp.exec(`CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, title TEXT NOT NULL,
description TEXT, start_date TEXT, end_date TEXT, currency TEXT DEFAULT 'EUR', is_archived INTEGER DEFAULT 0,
cover_image TEXT, reminder_days INTEGER DEFAULT 3, feed_token TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE trip_members (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
user_id INTEGER NOT NULL, invited_by INTEGER, added_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE day_assignments (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
place_id INTEGER NOT NULL, order_index INTEGER DEFAULT 0, notes TEXT, reservation_status TEXT,
reservation_notes TEXT, reservation_datetime TEXT, assignment_time TEXT, assignment_end_time TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
tmp.exec(`CREATE TABLE day_notes (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,
trip_id INTEGER NOT NULL, text TEXT, time TEXT, icon TEXT, sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
// deleteTrip cleans up synced journey entries before dropping the trip row.
tmp.exec(`CREATE TABLE journey_entries (id INTEGER PRIMARY KEY AUTOINCREMENT, journey_id INTEGER,
source_trip_id INTEGER, source_place_id INTEGER, type TEXT NOT NULL);`);
// bundle()'s todoItems now runs TodoService's real SQL (DI-injected, no mock).
tmp.exec(`CREATE TABLE todo_items (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
name TEXT NOT NULL, checked INTEGER NOT NULL DEFAULT 0, category TEXT, sort_order INTEGER NOT NULL DEFAULT 0,
@@ -92,15 +110,8 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
// PermissionsService singleton (created in beforeAll, after build()).
let checkPermission: MockInstance;
const { tripSvc } = vi.hoisted(() => ({
tripSvc: {
listTrips: vi.fn(), createTrip: vi.fn(), getTrip: vi.fn(), updateTrip: vi.fn(), deleteTrip: vi.fn(),
getTripRaw: vi.fn(), getTripOwner: vi.fn(), deleteOldCover: vi.fn(), updateCoverImage: vi.fn(),
listMembers: vi.fn(), addMember: vi.fn(), removeMember: vi.fn(), exportICS: vi.fn(), copyTripById: vi.fn(),
verifyTripAccess: vi.fn(), NotFoundError: class NotFoundError extends Error {}, ValidationError: class ValidationError extends Error {}, TRIP_SELECT: 'SELECT',
},
}));
vi.mock('../../src/services/tripService', () => tripSvc);
// TripsService itself is real since the trip fold — no tripService mock; the
// trips/trip_members/days DDL above serves its SQL.
// bundle()'s days + accommodations now run DaysService's real SQL (DI-injected,
// no mock) — the days/places/day_accommodations/reservations DDL above serves them.
vi.mock('../../src/services/placeService', () => ({ listPlaces: () => [] }));
@@ -131,13 +142,13 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
vi.spyOn(app.get(BudgetService), 'listBudgetItems').mockReturnValue([]);
vi.spyOn(app.get(BudgetService), 'rebaseTripCurrency').mockResolvedValue();
server = app.getHttpServer();
tripSvc.listTrips.mockReturnValue([{ id: 1, title: 'T' }]);
tripSvc.createTrip.mockReturnValue({ trip: { id: 9 }, tripId: 9, reminderDays: 0 });
tripSvc.getTrip.mockImplementation((id: string) => (id === '9' ? { id: 9, user_id: 1 } : undefined));
tripSvc.listMembers.mockReturnValue({ owner: { id: 1 }, members: [] });
});
beforeEach(() => {
db.prepare('DELETE FROM trips').run();
db.prepare('DELETE FROM trip_members').run();
db.prepare('DELETE FROM days').run();
db.prepare('DELETE FROM audit_log').run();
canAccessTrip.mockReturnValue({ user_id: 1 });
checkPermission.mockReturnValue(true);
});
@@ -146,20 +157,28 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
await app.close();
});
const seedTrip = (title = 'T', userId = 1) =>
Number(db.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?)').run(userId, title).lastInsertRowid);
it('401 without a cookie', async () => {
expect((await request(server).get('/api/trips')).status).toBe(401);
});
it('200 list', async () => {
it('200 list (real TRIP_SELECT: is_owner + counts)', async () => {
const tripId = seedTrip('T');
const res = await request(server).get('/api/trips').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ trips: [{ id: 1, title: 'T' }] });
expect(res.body.trips).toHaveLength(1);
expect(res.body.trips[0]).toMatchObject({ id: tripId, title: 'T', is_owner: 1, day_count: 0, place_count: 0, shared_count: 0 });
});
it('201 create, 403 without permission', async () => {
it('201 create (real insert + day generation), 403 without permission', async () => {
const ok = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
expect(ok.status).toBe(201);
expect(ok.body).toEqual({ trip: { id: 9 } });
// The dateless create seeds the default 7 placeholder days.
expect(ok.body.trip).toMatchObject({ title: 'T', currency: 'EUR', day_count: 7, is_owner: 1 });
const dayRows = db.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(ok.body.trip.id) as { n: number };
expect(dayRows.n).toBe(7);
// The DI-native AuditService wrote the real row (audit_log DDL above).
const audit = db.prepare("SELECT user_id FROM audit_log WHERE action = 'trip.create'").get() as { user_id: number };
expect(audit).toEqual({ user_id: 1 });
@@ -174,9 +193,22 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
expect(res.body).toEqual({ error: 'Trip not found' });
});
it('200 bundle for an accessible trip', async () => {
const res = await request(server).get('/api/trips/9/bundle').set('Cookie', sessionCookie(1));
it('200 bundle for an accessible trip (real member list)', async () => {
const tripId = seedTrip('B');
const res = await request(server).get(`/api/trips/${tripId}/bundle`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ trip: { id: 9 }, days: [], members: [{ id: 1 }] });
expect(res.body).toMatchObject({ trip: { id: tripId }, days: [], members: [{ id: 1, role: 'owner' }] });
});
it('200 delete cleans up synced journey entries (real SQL)', async () => {
const tripId = seedTrip('D');
db.prepare("INSERT INTO journey_entries (journey_id, source_trip_id, type) VALUES (1, ?, 'skeleton')").run(tripId);
const filledId = Number(db.prepare("INSERT INTO journey_entries (journey_id, source_trip_id, type) VALUES (1, ?, 'story')").run(tripId).lastInsertRowid);
const res = await request(server).delete(`/api/trips/${tripId}`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM trips WHERE id = ?').get(tripId)).toBeUndefined();
expect(db.prepare("SELECT id FROM journey_entries WHERE type = 'skeleton'").get()).toBeUndefined();
expect((db.prepare('SELECT source_trip_id FROM journey_entries WHERE id = ?').get(filledId) as { source_trip_id: number | null }).source_trip_id).toBeNull();
});
});