From a0f50c83168da9370539319803feae93ae21001e Mon Sep 17 00:00:00 2001 From: jubnl Date: Tue, 22 Sep 2026 06:30:13 +0200 Subject: [PATCH] refactor(trip-read-model, trips, feeds): async DB-touching methods; transactions through UnitOfWork --- server/src/nest/feeds/feeds.controller.ts | 32 ++--- server/src/nest/feeds/feeds.mcp.ts | 16 +-- server/src/nest/feeds/feeds.service.ts | 24 ++-- .../trip-read-model.service.ts | 4 +- server/src/nest/trips/trip-prompts.mcp.ts | 2 +- server/src/nest/trips/trips.controller.ts | 42 +++--- server/src/nest/trips/trips.mcp.ts | 58 ++++----- server/src/nest/trips/trips.rpc.ts | 14 +- server/src/nest/trips/trips.service.ts | 40 +++--- server/tests/unit/nest/feeds.service.test.ts | 52 ++++---- .../tests/unit/nest/trips.controller.test.ts | 37 ++---- server/tests/unit/nest/trips.service.test.ts | 122 +++++++++--------- 12 files changed, 216 insertions(+), 227 deletions(-) diff --git a/server/src/nest/feeds/feeds.controller.ts b/server/src/nest/feeds/feeds.controller.ts index 4f9e21962..7346a09bc 100644 --- a/server/src/nest/feeds/feeds.controller.ts +++ b/server/src/nest/feeds/feeds.controller.ts @@ -92,23 +92,23 @@ export class TripFeedTokenController { constructor(private readonly feeds: FeedsService) {} @Get('token') - get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { - return this.feeds.getTripToken(tripId, user.id, resolveFeedBase(req)); + async get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { + return await this.feeds.getTripToken(tripId, user.id, resolveFeedBase(req)); } @Post('token') - generate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { - return this.feeds.generateTripToken(tripId, user.id, resolveFeedBase(req)); + async generate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { + return await this.feeds.generateTripToken(tripId, user.id, resolveFeedBase(req)); } @Put('token') - rotate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { - return this.feeds.rotateTripToken(tripId, user.id, resolveFeedBase(req)); + async rotate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) { + return await this.feeds.rotateTripToken(tripId, user.id, resolveFeedBase(req)); } @Delete('token') - disable(@CurrentUser() user: User, @Param('tripId') tripId: string) { - this.feeds.disableTripToken(tripId, user.id); + async disable(@CurrentUser() user: User, @Param('tripId') tripId: string) { + await this.feeds.disableTripToken(tripId, user.id); return { feed_url: null }; } } @@ -123,23 +123,23 @@ export class UserFeedTokenController { constructor(private readonly feeds: FeedsService) {} @Get('token') - get(@CurrentUser() user: User, @Req() req: Request) { - return this.feeds.getUserToken(user.id, resolveFeedBase(req)); + async get(@CurrentUser() user: User, @Req() req: Request) { + return await this.feeds.getUserToken(user.id, resolveFeedBase(req)); } @Post('token') - generate(@CurrentUser() user: User, @Req() req: Request) { - return this.feeds.generateUserToken(user.id, resolveFeedBase(req)); + async generate(@CurrentUser() user: User, @Req() req: Request) { + return await this.feeds.generateUserToken(user.id, resolveFeedBase(req)); } @Put('token') - rotate(@CurrentUser() user: User, @Req() req: Request) { - return this.feeds.rotateUserToken(user.id, resolveFeedBase(req)); + async rotate(@CurrentUser() user: User, @Req() req: Request) { + return await this.feeds.rotateUserToken(user.id, resolveFeedBase(req)); } @Delete('token') - disable(@CurrentUser() user: User) { - this.feeds.disableUserToken(user.id); + async disable(@CurrentUser() user: User) { + await this.feeds.disableUserToken(user.id); return { feed_url: null }; } } diff --git a/server/src/nest/feeds/feeds.mcp.ts b/server/src/nest/feeds/feeds.mcp.ts index 65a462a34..91917f12c 100644 --- a/server/src/nest/feeds/feeds.mcp.ts +++ b/server/src/nest/feeds/feeds.mcp.ts @@ -77,7 +77,7 @@ export class FeedsMcp { async getTripCalendarFeed({ tripId }: { tripId: number }, ctx: McpContext) { const denied = await this.denyTripFeed(tripId, ctx.userId); if ((await denied)) return denied; - return ok(this.feeds.getTripToken(String(tripId), ctx.userId, this.base())); + return ok(await this.feeds.getTripToken(String(tripId), ctx.userId, this.base())); } @Tool({ @@ -93,7 +93,7 @@ export class FeedsMcp { if (await this.isDemoUser(ctx.userId)) return demoDenied(); const denied = await this.denyTripFeed(tripId, ctx.userId); if ((await denied)) return denied; - return ok(this.feeds.generateTripToken(String(tripId), ctx.userId, this.base())); + return ok(await this.feeds.generateTripToken(String(tripId), ctx.userId, this.base())); } @Tool({ @@ -109,7 +109,7 @@ export class FeedsMcp { if (await this.isDemoUser(ctx.userId)) return demoDenied(); const denied = await this.denyTripFeed(tripId, ctx.userId); if ((await denied)) return denied; - return ok(this.feeds.rotateTripToken(String(tripId), ctx.userId, this.base())); + return ok(await this.feeds.rotateTripToken(String(tripId), ctx.userId, this.base())); } @Tool({ @@ -125,7 +125,7 @@ export class FeedsMcp { if (await this.isDemoUser(ctx.userId)) return demoDenied(); const denied = await this.denyTripFeed(tripId, ctx.userId); if ((await denied)) return denied; - this.feeds.disableTripToken(String(tripId), ctx.userId); + await this.feeds.disableTripToken(String(tripId), ctx.userId); // Matches the route, which answers the cleared token as a null URL. return ok({ feed_url: null }); } @@ -142,7 +142,7 @@ export class FeedsMcp { access: { group: 'trips', mode: 'share' }, }) async getAllTripsCalendarFeed(_input: Record, ctx: McpContext) { - return ok(this.feeds.getUserToken(ctx.userId, this.base())); + return ok(await this.feeds.getUserToken(ctx.userId, this.base())); } @Tool({ @@ -154,7 +154,7 @@ export class FeedsMcp { }) async enableAllTripsCalendarFeed(_input: Record, ctx: McpContext) { if (await this.isDemoUser(ctx.userId)) return demoDenied(); - return ok(this.feeds.generateUserToken(ctx.userId, this.base())); + return ok(await this.feeds.generateUserToken(ctx.userId, this.base())); } @Tool({ @@ -166,7 +166,7 @@ export class FeedsMcp { }) async rotateAllTripsCalendarFeed(_input: Record, ctx: McpContext) { if (await this.isDemoUser(ctx.userId)) return demoDenied(); - return ok(this.feeds.rotateUserToken(ctx.userId, this.base())); + return ok(await this.feeds.rotateUserToken(ctx.userId, this.base())); } @Tool({ @@ -178,7 +178,7 @@ export class FeedsMcp { }) async disableAllTripsCalendarFeed(_input: Record, ctx: McpContext) { if (await this.isDemoUser(ctx.userId)) return demoDenied(); - this.feeds.disableUserToken(ctx.userId); + await this.feeds.disableUserToken(ctx.userId); return ok({ feed_url: null }); } } diff --git a/server/src/nest/feeds/feeds.service.ts b/server/src/nest/feeds/feeds.service.ts index 7596f3df3..0403a332a 100644 --- a/server/src/nest/feeds/feeds.service.ts +++ b/server/src/nest/feeds/feeds.service.ts @@ -29,7 +29,7 @@ export class FeedsService { // ── Trip feed token ───────────────────────────────────────────────────── - private tripTokenRow(tripId: string, userId: number) { + private async tripTokenRow(tripId: string, userId: number) { return this.db .prepare( 'SELECT feed_token FROM trips WHERE id = ? AND (user_id = ? OR id IN (SELECT trip_id FROM trip_members WHERE user_id = ?))', @@ -37,8 +37,8 @@ export class FeedsService { .get(tripId, userId, userId) as { feed_token: string | null } | undefined; } - getTripToken(tripId: string, userId: number, base: string): { feed_url: string | null } { - const row = this.tripTokenRow(tripId, userId); + async getTripToken(tripId: string, userId: number, base: string): Promise<{ feed_url: string | null }> { + const row = await this.tripTokenRow(tripId, userId); return { feed_url: row?.feed_token ? feedUrl(row.feed_token, 'trip', base) : null }; } @@ -53,8 +53,8 @@ export class FeedsService { 'id = ? AND (user_id = ? OR id IN (SELECT trip_id FROM trip_members WHERE user_id = ?))'; /** Enable (idempotent): mint a token only if the trip has none yet. */ - generateTripToken(tripId: string, userId: number, base: string): { feed_url: string } { - const row = this.tripTokenRow(tripId, userId); + async generateTripToken(tripId: string, userId: number, base: string): Promise<{ feed_url: string }> { + const row = await this.tripTokenRow(tripId, userId); if (row?.feed_token) return { feed_url: feedUrl(row.feed_token, 'trip', base) }; const token = randomUUID(); this.db @@ -64,7 +64,7 @@ export class FeedsService { } /** Rotate: always issue a fresh token, invalidating the previous URL. */ - rotateTripToken(tripId: string, userId: number, base: string): { feed_url: string } { + async rotateTripToken(tripId: string, userId: number, base: string): Promise<{ feed_url: string }> { const token = randomUUID(); this.db .prepare(`UPDATE trips SET feed_token = ? WHERE ${FeedsService.REACHABLE}`) @@ -73,7 +73,7 @@ export class FeedsService { } /** Disable: clear the token so the public URL stops resolving. */ - disableTripToken(tripId: string, userId: number): void { + async disableTripToken(tripId: string, userId: number): Promise { this.db .prepare(`UPDATE trips SET feed_token = NULL WHERE ${FeedsService.REACHABLE}`) .run(tripId, userId, userId); @@ -81,28 +81,28 @@ export class FeedsService { // ── User (all-trips) feed token ────────────────────────────────────────── - getUserToken(userId: number, base: string): { feed_url: string | null } { + async getUserToken(userId: number, base: string): Promise<{ feed_url: string | null }> { const row = this.db.prepare('SELECT feed_token FROM users WHERE id = ?').get(userId) as | { feed_token: string | null } | undefined; return { feed_url: row?.feed_token ? feedUrl(row.feed_token, 'user', base) : null }; } - generateUserToken(userId: number, base: string): { feed_url: string } { - const existing = this.getUserToken(userId, base); + async generateUserToken(userId: number, base: string): Promise<{ feed_url: string }> { + const existing = await this.getUserToken(userId, base); if (existing.feed_url) return { feed_url: existing.feed_url }; const token = randomUUID(); this.db.prepare('UPDATE users SET feed_token = ? WHERE id = ?').run(token, userId); return { feed_url: feedUrl(token, 'user', base) }; } - rotateUserToken(userId: number, base: string): { feed_url: string } { + async rotateUserToken(userId: number, base: string): Promise<{ feed_url: string }> { const token = randomUUID(); this.db.prepare('UPDATE users SET feed_token = ? WHERE id = ?').run(token, userId); return { feed_url: feedUrl(token, 'user', base) }; } - disableUserToken(userId: number): void { + async disableUserToken(userId: number): Promise { this.db.prepare('UPDATE users SET feed_token = NULL WHERE id = ?').run(userId); } diff --git a/server/src/nest/trip-read-model/trip-read-model.service.ts b/server/src/nest/trip-read-model/trip-read-model.service.ts index ea71d22f0..b8eef8049 100644 --- a/server/src/nest/trip-read-model/trip-read-model.service.ts +++ b/server/src/nest/trip-read-model/trip-read-model.service.ts @@ -41,7 +41,7 @@ export class TripReadModelService { return this.dbs.connection; } - private getOwner(tripId: string | number): { user_id: number } | undefined { + private async getOwner(tripId: string | number): Promise<{ user_id: number } | undefined> { return this.db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined; } @@ -53,7 +53,7 @@ export class TripReadModelService { ); if (!trip) return null; - const ownerRow = this.getOwner(tripId); + const ownerRow = await this.getOwner(tripId); if (!ownerRow) return null; const { owner, members } = await this.members.listMembers(tripId, ownerRow.user_id); diff --git a/server/src/nest/trips/trip-prompts.mcp.ts b/server/src/nest/trips/trip-prompts.mcp.ts index a232cd078..a4f81f5a6 100644 --- a/server/src/nest/trips/trip-prompts.mcp.ts +++ b/server/src/nest/trips/trip-prompts.mcp.ts @@ -40,7 +40,7 @@ export class TripPromptsMcp { when: budgetAddonOn, }) async budgetOverviewPrompt({ tripId }: { tripId: number }, ctx: McpContext) { - if (!this.trips.canAccessTrip(tripId, ctx.userId)) { + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) { return { messages: [{ role: 'user' as const, content: { type: 'text' as const, text: 'Trip not found or access denied.' } }] }; } const summary = await this.readModel.getTripSummary(tripId, ctx.userId); diff --git a/server/src/nest/trips/trips.controller.ts b/server/src/nest/trips/trips.controller.ts index 23d09e9fa..ffc084240 100644 --- a/server/src/nest/trips/trips.controller.ts +++ b/server/src/nest/trips/trips.controller.ts @@ -70,8 +70,8 @@ export class TripsController { constructor(private readonly trips: TripsService, private readonly audit: AuditService, private readonly env: RuntimeEnvService, private readonly unsplash: UnsplashService, private readonly calendar: CalendarService, private readonly readModel: TripReadModelService, private readonly storage: StorageService) {} @Get() - list(@CurrentUser() user: User, @Query('archived') archived?: string) { - return { trips: this.trips.list(user.id, archived === '1' ? 1 : 0) }; + async list(@CurrentUser() user: User, @Query('archived') archived?: string) { + return { trips: await this.trips.list(user.id, archived === '1' ? 1 : 0) }; } /** @@ -79,8 +79,8 @@ export class TripsController { * a literal segment below it would never be reached. */ @Get('active') - active(@CurrentUser() user: User): ActiveTripResponse { - const row = this.trips.activeTrip(user.id); + async active(@CurrentUser() user: User): Promise { + const row = await this.trips.activeTrip(user.id); if (!row) return { trip: null }; const { id, title, start_date, end_date } = row; return { trip: { id, title, start_date, end_date } }; @@ -118,7 +118,7 @@ export class TripsController { } const parsedDayCount = day_count ? Math.min(Math.max(Number(day_count) || 7, 1), MAX_TRIP_DAYS) : undefined; try { - const { trip, tripId, reminderDays } = this.trips.create(user.id, { title, description, start_date, end_date, currency, reminder_days, day_count: parsedDayCount }); + const { trip, tripId, reminderDays } = await this.trips.create(user.id, { title, description, start_date, end_date, currency, reminder_days, day_count: parsedDayCount }); await this.audit.writeAudit({ userId: user.id, action: 'trip.create', ip: getClientIp(req), details: { tripId, title, reminder_days: reminderDays === 0 ? 'none' : `${reminderDays} days` } }); if (reminderDays > 0) logInfo(`${user.email} set ${reminderDays}-day reminder for trip "${title}"`); return { trip }; @@ -129,8 +129,8 @@ export class TripsController { } @Get(':id') - get(@CurrentUser() user: User, @Param('id') id: string) { - const trip = this.trips.get(id, user.id); + async get(@CurrentUser() user: User, @Param('id') id: string) { + const trip = await this.trips.get(id, user.id); if (!trip) { throw new HttpException({ error: 'Trip not found' }, 404); } @@ -139,7 +139,7 @@ export class TripsController { @Put(':id') async update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripUpdateDto, @Req() req: Request, @Headers('x-socket-id') socketId?: string) { - const access = this.trips.canAccessTrip(id, user.id); + const access = await this.trips.canAccessTrip(id, user.id); if (!access) { throw new HttpException({ error: 'Trip not found' }, 404); } @@ -167,7 +167,7 @@ export class TripsController { } } const oldCover = body.cover_image !== undefined - ? (this.trips.getRaw(id) as { cover_image: string | null } | undefined)?.cover_image + ? ((await this.trips.getRaw(id)) as { cover_image: string | null } | undefined)?.cover_image : undefined; try { const result = await this.trips.update(id, user.id, body, user.role); @@ -197,14 +197,14 @@ export class TripsController { if (isDemoWriteBlocked(this.env, user.email)) { throw new HttpException(DEMO_WRITE_ERROR, 403); } - const access = this.trips.canAccessTrip(id, user.id); + const access = await this.trips.canAccessTrip(id, user.id); if (!access?.user_id) { throw new HttpException({ error: 'Trip not found' }, 404); } if (!(await this.trips.can('trip_cover_upload', user.role, access.user_id, user.id, access.user_id !== user.id))) { throw new HttpException({ error: 'No permission to change the cover image' }, 403); } - const trip = this.trips.getRaw(id) as { cover_image: string | null } | undefined; + const trip = (await this.trips.getRaw(id)) as { cover_image: string | null } | undefined; if (!trip) { throw new HttpException({ error: 'Trip not found' }, 404); } @@ -216,7 +216,7 @@ export class TripsController { await this.storage.put('covers', file.filename, { tmpPath: file.path }); await this.trips.deleteOldCover(trip.cover_image); const coverUrl = `/uploads/covers/${file.filename}`; - this.trips.updateCoverImage(id, coverUrl); + await this.trips.updateCoverImage(id, coverUrl); return { cover_image: coverUrl }; } @@ -226,14 +226,14 @@ export class TripsController { if (!(await this.trips.can('trip_create', user.role, null, user.id, false))) { throw new HttpException({ error: 'No permission to create trips' }, 403); } - if (!this.trips.canAccessTrip(id, user.id)) { + if (!(await this.trips.canAccessTrip(id, user.id))) { throw new HttpException({ error: 'Trip not found' }, 404); } const { title } = body; try { - const newTripId = this.trips.copy(id, user.id, title); + const newTripId = await this.trips.copy(id, user.id, title); await this.audit.writeAudit({ userId: user.id, action: 'trip.copy', ip: getClientIp(req), details: { sourceTripId: Number(id), newTripId, title } }); - return { trip: this.trips.getCopiedTrip(newTripId, user.id) }; + return { trip: await this.trips.getCopiedTrip(newTripId, user.id) }; } catch { throw new HttpException({ error: 'Failed to copy trip' }, 500); } @@ -241,7 +241,7 @@ export class TripsController { @Delete(':id') async remove(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request, @Headers('x-socket-id') socketId?: string) { - const owner = this.trips.getOwner(id); + const owner = await this.trips.getOwner(id); if (!owner) { throw new HttpException({ error: 'Trip not found' }, 404); } @@ -249,13 +249,13 @@ export class TripsController { // exist, otherwise the 403 below turns sequential ids into an existence // oracle. Admins are exempt: they may delete trips they are not a member of, // which is what the isAdminDelete branch further down relies on. - if (user.role !== 'admin' && !this.trips.canAccessTrip(id, user.id)) { + if (user.role !== 'admin' && !(await this.trips.canAccessTrip(id, user.id))) { throw new HttpException({ error: 'Trip not found' }, 404); } if (!(await this.trips.can('trip_delete', user.role, owner.user_id, user.id, owner.user_id !== user.id))) { throw new HttpException({ error: 'No permission to delete this trip' }, 403); } - const info = this.trips.remove(id, user.id, user.role); + const info = await this.trips.remove(id, user.id, user.role); await this.audit.writeAudit({ userId: user.id, action: 'trip.delete', ip: getClientIp(req), details: { tripId: info.tripId, trip: info.title, ...(info.ownerEmail ? { owner: info.ownerEmail } : {}) } }); if (info.isAdminDelete && info.ownerEmail) logInfo(`Admin ${user.email} deleted trip "${info.title}" owned by ${info.ownerEmail}`); this.trips.broadcast(String(info.tripId), 'trip:deleted', { id: info.tripId }, socketId); @@ -263,8 +263,8 @@ export class TripsController { } @Get(':id/bundle') - bundle(@CurrentUser() user: User, @Param('id') id: string) { - const trip = this.trips.get(id, user.id) as { user_id: number } | undefined; + async bundle(@CurrentUser() user: User, @Param('id') id: string) { + const trip = (await this.trips.get(id, user.id)) as { user_id: number } | undefined; if (!trip) { throw new HttpException({ error: 'Trip not found' }, 404); } @@ -273,7 +273,7 @@ export class TripsController { @Get(':id/export.ics') async exportIcs(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response) { - if (!this.trips.canAccessTrip(id, user.id)) { + if (!(await this.trips.canAccessTrip(id, user.id))) { throw new HttpException({ error: 'Trip not found' }, 404); } try { diff --git a/server/src/nest/trips/trips.mcp.ts b/server/src/nest/trips/trips.mcp.ts index f8cdde40a..f3d9ec158 100644 --- a/server/src/nest/trips/trips.mcp.ts +++ b/server/src/nest/trips/trips.mcp.ts @@ -119,7 +119,7 @@ export class TripsMcp { return { content: [{ type: 'text' as const, text: 'End date must be after start date.' }], isError: true }; } try { - const { trip } = this.trips.create(ctx.userId, { title, description, start_date, end_date, currency, day_count, reminder_days }); + const { trip } = await this.trips.create(ctx.userId, { title, description, start_date, end_date, currency, day_count, reminder_days }); return ok({ trip }); } catch (err) { if (err instanceof ValidationError) return errorResult(err.message); @@ -160,7 +160,7 @@ export class TripsMcp { ctx: McpContext, ) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); if (!(await this.guards.hasTripPermission('trip_edit', tripId, ctx.userId))) return permissionDenied(); if (clear_dates && (start_date || end_date)) return errorResult('clear_dates cannot be combined with start_date or end_date.'); @@ -224,8 +224,8 @@ export class TripsMcp { }) async deleteTrip({ tripId }: { tripId: number }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.isOwner(tripId, ctx.userId)) return noAccess(); - this.trips.remove(tripId, ctx.userId, 'user'); + if (!(await this.trips.isOwner(tripId, ctx.userId))) return noAccess(); + await this.trips.remove(tripId, ctx.userId, 'user'); return ok({ success: true, tripId }); } @@ -241,7 +241,7 @@ export class TripsMcp { }) async listTrips({ include_archived }: { include_archived?: boolean }, ctx: McpContext) { const notice = ctx.getDeprecationNotice ? ctx.getDeprecationNotice() : null; - const trips = this.trips.list(ctx.userId, include_archived ? null : 0); + const trips = await this.trips.list(ctx.userId, include_archived ? null : 0); if (notice) return { isError: true as const, content: [ @@ -263,7 +263,7 @@ export class TripsMcp { annotations: TOOL_ANNOTATIONS_READONLY, }) async getTripSummary({ tripId }: { tripId: number }, ctx: McpContext) { - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); const summary = await this.readModel.getTripSummary(tripId, ctx.userId); if (!summary) return noAccess(); const R = canReadTrips(ctx.scopes); @@ -332,8 +332,8 @@ export class TripsMcp { access: (ctx) => canReadTrips(ctx.scopes), }) async listTripMembers({ tripId }: { tripId: number }, ctx: McpContext) { - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow) return noAccess(); const { owner, members } = await this.members.listMembers(tripId, ownerRow.user_id); return ok({ owner, members }); @@ -351,8 +351,8 @@ export class TripsMcp { }) async addTripMember({ tripId, identifier }: { tripId: number; identifier: string }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow) return noAccess(); // member_manage rather than a hardcoded owner test: the action is admin-lowerable // in the permission matrix, and POST /api/trips/:id/members has always honoured @@ -380,7 +380,7 @@ export class TripsMcp { }) async removeTripMember({ tripId, memberId }: { tripId: number; memberId: number }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); // Giving up your own access is not member management, so it carries no permission // requirement: the same self-removal bypass DELETE /api/trips/:id/members/:userId has. if (memberId !== ctx.userId && !(await this.guards.hasTripPermission('member_manage', tripId, ctx.userId))) @@ -401,8 +401,8 @@ export class TripsMcp { }) async leaveTrip({ tripId }: { tripId: number }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow) return noAccess(); // removeMember only deletes a trip_members row, and the owner has none, so an // owner calling this would get a success that changed nothing. Say so instead. @@ -435,8 +435,8 @@ export class TripsMcp { }) async createTripGuest({ tripId, name }: { tripId: number; name: string }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow || ownerRow.user_id !== ctx.userId) return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true }; try { @@ -463,8 +463,8 @@ export class TripsMcp { }) async renameTripGuest({ tripId, guestId, name }: { tripId: number; guestId: number; name: string }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow || ownerRow.user_id !== ctx.userId) return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true }; try { @@ -489,8 +489,8 @@ export class TripsMcp { }) async deleteTripGuest({ tripId, guestId }: { tripId: number; guestId: number }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); - const ownerRow = this.trips.getOwner(tripId); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); + const ownerRow = await this.trips.getOwner(tripId); if (!ownerRow || ownerRow.user_id !== ctx.userId) return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true }; if (!(await this.members.deleteGuest(tripId, guestId))) @@ -511,10 +511,10 @@ export class TripsMcp { }) async copyTrip({ tripId, title }: { tripId: number; title?: string }, ctx: McpContext) { if (await this.auth.isDemoUser(ctx.userId)) return demoDenied(); - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); try { - const newTripId = this.trips.copy(tripId, ctx.userId, title); - const newTrip = this.trips.canAccessTrip(newTripId, ctx.userId); + const newTripId = await this.trips.copy(tripId, ctx.userId, title); + const newTrip = await this.trips.canAccessTrip(newTripId, ctx.userId); return ok({ trip: { id: newTripId, ...newTrip } }); } catch { return { content: [{ type: 'text' as const, text: 'Failed to copy trip.' }], isError: true }; @@ -531,7 +531,7 @@ export class TripsMcp { access: (ctx) => canReadTrips(ctx.scopes), }) async exportTripIcs({ tripId }: { tripId: number }, ctx: McpContext) { - if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess(); + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) return noAccess(); try { const { ics, filename } = await this.calendar.exportICS(tripId); return ok({ ics, filename }); @@ -550,7 +550,7 @@ export class TripsMcp { access: (ctx) => canReadTrips(ctx.scopes), }) async tripsResource(uri: URL, ctx: McpContext) { - const trips = this.trips.list(ctx.userId, 0); + const trips = await this.trips.list(ctx.userId, 0); return jsonContent(uri.href, trips); } @@ -563,8 +563,8 @@ export class TripsMcp { }) async tripResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { const id = parseId(tripId); - if (id === null || !this.trips.canAccessTrip(id, ctx.userId)) return accessDenied(uri.href); - const trip = this.trips.get(id, ctx.userId); + if (id === null || !(await this.trips.canAccessTrip(id, ctx.userId))) return accessDenied(uri.href); + const trip = await this.trips.get(id, ctx.userId); return jsonContent(uri.href, trip); } @@ -577,8 +577,8 @@ export class TripsMcp { }) async tripMembersResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { const id = parseId(tripId); - if (id === null || !this.trips.canAccessTrip(id, ctx.userId)) return accessDenied(uri.href); - const ownerRow = this.trips.getOwner(id); + if (id === null || !(await this.trips.canAccessTrip(id, ctx.userId))) return accessDenied(uri.href); + const ownerRow = await this.trips.getOwner(id); if (!ownerRow) return accessDenied(uri.href); const { owner, members } = await this.members.listMembers(id, ownerRow.user_id); return jsonContent(uri.href, { owner, members }); @@ -595,7 +595,7 @@ export class TripsMcp { }, }) async tripSummaryPrompt({ tripId }: { tripId: number }, ctx: McpContext) { - if (!this.trips.canAccessTrip(tripId, ctx.userId)) { + if (!(await this.trips.canAccessTrip(tripId, ctx.userId))) { return { messages: [{ role: 'user' as const, content: { type: 'text' as const, text: 'Trip not found or access denied.' } }] }; } const summary = await this.readModel.getTripSummary(tripId, ctx.userId); diff --git a/server/src/nest/trips/trips.rpc.ts b/server/src/nest/trips/trips.rpc.ts index 1d015dd64..e0cd6f84f 100644 --- a/server/src/nest/trips/trips.rpc.ts +++ b/server/src/nest/trips/trips.rpc.ts @@ -45,7 +45,7 @@ export class TripsRpc { ) {} @PluginMethod('trips.getById', { permission: 'db:read:trips' }) - getById(params: Record, ctx: PluginRpcContext): unknown { + async getById(params: Record, ctx: PluginRpcContext): Promise { return this.guards.tripRead(params, ctx, () => // db:read:trips is a read grant on the trip, not on the credential that // publishes it anonymously — see withoutFeedToken. @@ -54,7 +54,7 @@ export class TripsRpc { } @PluginMethod('trips.getPlaces', { permission: 'db:read:trips' }) - getPlaces(params: Record, ctx: PluginRpcContext): unknown { + async getPlaces(params: Record, ctx: PluginRpcContext): Promise { // The trip's place POOL. Places carry no itinerary position of their own // (day_id/order_index live on day_assignments), so order by created_at like the // REST list does. trips.getDays is the day-ordered itinerary. @@ -87,11 +87,11 @@ export class TripsRpc { } @PluginMethod('trips.listMine', { permission: 'db:read:trips' }) - listMine(_params: Record, ctx: PluginRpcContext): unknown { + async listMine(_params: Record, ctx: PluginRpcContext): Promise { // Membership is baked into the service, so there is no tripId to check, but a // job or onLoad with no bound user is refused exactly like costs.listMine. if (ctx.actingUserId === undefined) throw new ForbiddenResource('trip reads require an authenticated user context'); - return this.trips.list(ctx.actingUserId, null); + return await this.trips.list(ctx.actingUserId, null); } @PluginMethod('reservations.listMine', { permission: 'db:read:trips' }) @@ -99,13 +99,13 @@ export class TripsRpc { if (ctx.actingUserId === undefined) { throw new ForbiddenResource('reservation reads require an authenticated user context'); } - const trips = this.trips.list(ctx.actingUserId, null) as Array<{ id: number }>; + const trips = (await this.trips.list(ctx.actingUserId, null)) as Array<{ id: number }>; const perTrip = await Promise.all(trips.map((t) => this.reservations.list(String(t.id)))); return perTrip.flat(); } @PluginMethod('trips.members', { permission: 'db:read:trips' }) - members(params: Record, ctx: PluginRpcContext): unknown { + async members(params: Record, ctx: PluginRpcContext): Promise { return this.guards.tripRead(params, ctx, () => this.db .prepare('SELECT u.id, u.username, u.display_name, u.avatar FROM trip_members tm JOIN users u ON u.id = tm.user_id WHERE tm.trip_id = ?') @@ -154,7 +154,7 @@ export class TripsRpc { this.guards.capStrings(parsed.data as Record, TRIP_STR_LIMITS); if (!(await this.canCreateTrip(actor))) throw new ForbiddenResource('no permission to create trips'); try { - return this.trips.create(actor, parsed.data as unknown as Parameters[1]).trip; + return (await this.trips.create(actor, parsed.data as unknown as Parameters[1])).trip; } catch (e) { if (e instanceof ValidationError) throw new BadParams(e.message); throw e; diff --git a/server/src/nest/trips/trips.service.ts b/server/src/nest/trips/trips.service.ts index 612d66910..5d91347aa 100644 --- a/server/src/nest/trips/trips.service.ts +++ b/server/src/nest/trips/trips.service.ts @@ -167,11 +167,11 @@ export class TripsService { return this.dbs.connection; } - canAccessTrip(tripId: string | number, userId: number) { + async canAccessTrip(tripId: string | number, userId: number): Promise<{ user_id: number } | null | undefined> { return this.dbs.canAccessTrip(tripId, userId) as { user_id: number } | null | undefined; } - isOwner(tripId: string | number, userId: number): boolean { + async isOwner(tripId: string | number, userId: number): Promise { return this.dbs.isOwner(tripId, userId); } @@ -185,7 +185,7 @@ export class TripsService { // ── Day generation ──────────────────────────────────────────────────────── - generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, dayCount?: number) { + async generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, dayCount?: number): Promise { const existing = this.db.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; day_number: number; date: string | null }[]; const setDayNumber = this.db.prepare('UPDATE days SET day_number = ? WHERE id = ?'); @@ -304,7 +304,7 @@ export class TripsService { // ── Trip CRUD ───────────────────────────────────────────────────────────── - list(userId: number, archived: number | null) { + async list(userId: number, archived: number | null) { if (archived === null) { return this.db.prepare(` ${TRIP_SELECT} @@ -321,7 +321,7 @@ export class TripsService { `).all({ userId, archived }); } - create(userId: number, data: CreateTripData) { + async create(userId: number, data: CreateTripData) { if (data.start_date && data.end_date) assertTripSpan(data.start_date, data.end_date); const rd = data.reminder_days !== undefined ? (Number(data.reminder_days) >= 0 && Number(data.reminder_days) <= 30 ? Number(data.reminder_days) : 3) @@ -333,13 +333,13 @@ export class TripsService { `).run(userId, data.title, data.description || null, data.start_date || null, data.end_date || null, data.currency || 'EUR', rd); const tripId = result.lastInsertRowid; - this.generateDays(tripId, data.start_date || null, data.end_date || null, data.day_count); + await this.generateDays(tripId, data.start_date || null, data.end_date || null, data.day_count); const trip = this.db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId }); return { trip, tripId: Number(tripId), reminderDays: rd }; } - get(tripId: string | number, userId: number) { + async get(tripId: string | number, userId: number) { return this.db.prepare(` ${TRIP_SELECT} LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId @@ -358,7 +358,7 @@ export class TripsService { * a startup redirect, so it reads four columns of one row instead of every * trip with its per-trip day/place counts. */ - activeTrip(userId: number, today = new Date().toISOString().slice(0, 10)) { + async activeTrip(userId: number, today = new Date().toISOString().slice(0, 10)) { return this.db.prepare(` SELECT t.id, t.title, t.start_date, t.end_date, CASE @@ -376,7 +376,7 @@ export class TripsService { `).get({ userId, today }) as ActiveTrip & { relevance: number } | undefined; } - getRaw(tripId: string | number): Trip | undefined { + async getRaw(tripId: string | number): Promise { return this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Trip | undefined; } @@ -384,7 +384,7 @@ export class TripsService { return this.unsplash.searchUnsplashPhotos(query, 9, await this.unsplash.getUnsplashKey(userId)); } - getOwner(tripId: string | number): { user_id: number } | undefined { + async getOwner(tripId: string | number): Promise<{ user_id: number } | undefined> { return this.db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined; } @@ -427,7 +427,7 @@ export class TripsService { (this.db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[]) .map(d => [d.id, d.date]), ); - this.generateDays(tripId, newStart || null, newEnd || null, dayCount); + await this.generateDays(tripId, newStart || null, newEnd || null, dayCount); if (data.date_shift_mode === 'shift_all') { // Explicit "shift everything": bookings stay glued to their (re-dated) day rows, // so re-stamp reservation_time to follow — same rules as reorderDays/insertDay. @@ -486,7 +486,7 @@ export class TripsService { async update(tripId: string | number, userId: number, body: UpdateTripData, role: string) { // A refused range must not leave the budget rebased onto a currency the trip // never took, so the dates are checked before the first write. - const trip = this.getRaw(tripId); + const trip = await this.getRaw(tripId); if (!trip) throw new NotFoundError('Trip not found'); this.resolveRange(trip, body); // Re-anchor the budget while the outgoing currency is still on the trip row, @@ -498,7 +498,7 @@ export class TripsService { // ── Delete ───────────────────────────────────────────────────────────────── - remove(tripId: string | number, userId: number, userRole: string): DeleteTripInfo { + async remove(tripId: string | number, userId: number, userRole: string): Promise { const trip = this.db.prepare('SELECT title, user_id FROM trips WHERE id = ?').get(tripId) as { title: string; user_id: number } | undefined; if (!trip) throw new NotFoundError('Trip not found'); @@ -511,7 +511,7 @@ export class TripsService { // Quirk fix on top of the 1:1 move: the three-statement delete runs in a // transaction, so a failure mid-flow can't leave journey entries detached // from a trip that still exists. - this.db.transaction(() => { + await this.uow.transactional(async () => { // Clean up journey entries synced from this trip before deleting // Delete skeleton entries (unfilled synced places) this.db.prepare(` @@ -525,7 +525,7 @@ export class TripsService { `).run(tripId); this.db.prepare('DELETE FROM trips WHERE id = ?').run(tripId); - })(); + }); return { tripId: Number(tripId), title: trip.title, ownerId: trip.user_id, isAdminDelete, ownerEmail }; } @@ -543,7 +543,7 @@ export class TripsService { }); } - updateCoverImage(tripId: string | number, coverUrl: string): void { + async updateCoverImage(tripId: string | number, coverUrl: string): Promise { this.db.prepare('UPDATE trips SET cover_image=?, updated_at=CURRENT_TIMESTAMP WHERE id=?').run(coverUrl, tripId); } @@ -557,13 +557,13 @@ export class TripsService { * (budget_item_members/payers incl. paid flags, assignment_participants). * Packing items and to-dos are reset to unchecked. Returns the new trip's ID. */ - copy(sourceTripId: string | number, newOwnerId: number, title?: string): number { + async copy(sourceTripId: string | number, newOwnerId: number, title?: string): Promise { const src = this.db.prepare('SELECT * FROM trips WHERE id = ?').get(sourceTripId) as any; if (!src) throw new NotFoundError('Trip not found'); const newTitle = title || src.title; - const fn = this.db.transaction(() => { + return await this.uow.transactional(async () => { const tripResult = this.db.prepare(` INSERT INTO trips (user_id, title, description, start_date, end_date, currency, cover_image, is_archived, reminder_days) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?) @@ -829,12 +829,10 @@ export class TripsService { return Number(newTripId); }); - - return fn(); } /** Re-read a freshly copied trip in list shape (mirrors the route's TRIP_SELECT query). */ - getCopiedTrip(newTripId: number, userId: number) { + async getCopiedTrip(newTripId: number, userId: number) { return this.db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId: newTripId }); } diff --git a/server/tests/unit/nest/feeds.service.test.ts b/server/tests/unit/nest/feeds.service.test.ts index 3405b2641..e80d632d2 100644 --- a/server/tests/unit/nest/feeds.service.test.ts +++ b/server/tests/unit/nest/feeds.service.test.ts @@ -121,13 +121,13 @@ describe('trip feed token lifecycle', () => { it('FEED-SVC-001: reports no URL while the trip has no token', async () => { const { user, tripId } = seedTrip(); - expect(svc.getTripToken(tripId, user.id, BASE)).toEqual({ feed_url: null }); + expect(await svc.getTripToken(tripId, user.id, BASE)).toEqual({ feed_url: null }); }); it('FEED-SVC-002: reports the absolute feed URL once a token exists', async () => { const { user, tripId } = seedTrip('tok-trip'); - expect(svc.getTripToken(tripId, user.id, BASE)).toEqual({ + expect(await svc.getTripToken(tripId, user.id, BASE)).toEqual({ feed_url: `${BASE}/api/feed/trip/tok-trip.ics`, }); }); @@ -137,7 +137,7 @@ describe('trip feed token lifecycle', () => { // otherwise produce https://host//api/feed/... which some clients reject. const { user, tripId } = seedTrip('tok-trip'); - expect(svc.getTripToken(tripId, user.id, `${BASE}/`).feed_url).toBe( + expect((await svc.getTripToken(tripId, user.id, `${BASE}/`)).feed_url).toBe( `${BASE}/api/feed/trip/tok-trip.ics`, ); }); @@ -148,7 +148,7 @@ describe('trip feed token lifecycle', () => { const { tripId } = seedTrip('tok-trip'); const { user: outsider } = createUser(testDb); - expect(svc.getTripToken(tripId, outsider.id, BASE)).toEqual({ feed_url: null }); + expect(await svc.getTripToken(tripId, outsider.id, BASE)).toEqual({ feed_url: null }); }); // Membership is what the service checks, and that stays true: whether the @@ -159,7 +159,7 @@ describe('trip feed token lifecycle', () => { const { user: member } = createUser(testDb); addTripMember(testDb, trip.id, member.id); - expect(svc.getTripToken(tripId, member.id, BASE).feed_url).toBe( + expect((await svc.getTripToken(tripId, member.id, BASE)).feed_url).toBe( `${BASE}/api/feed/trip/tok-trip.ics`, ); }); @@ -169,8 +169,8 @@ describe('trip feed token lifecycle', () => { // calendar client — that is what rotate is for. const { user, tripId } = seedTrip(); - const first = svc.generateTripToken(tripId, user.id, BASE); - const second = svc.generateTripToken(tripId, user.id, BASE); + const first = await svc.generateTripToken(tripId, user.id, BASE); + const second = await svc.generateTripToken(tripId, user.id, BASE); expect(first.feed_url).toMatch(new RegExp(`^${BASE}/api/feed/trip/[0-9a-f-]+\\.ics$`)); expect(second.feed_url).toBe(first.feed_url); @@ -178,10 +178,10 @@ describe('trip feed token lifecycle', () => { it('FEED-SVC-007: rotate issues a fresh token and the previous URL stops resolving', async () => { const { user, tripId } = seedTrip(); - const before = svc.generateTripToken(tripId, user.id, BASE).feed_url; + const before = (await svc.generateTripToken(tripId, user.id, BASE)).feed_url; const oldToken = before.match(/trip\/([0-9a-f-]+)\.ics$/)![1]; - const after = svc.rotateTripToken(tripId, user.id, BASE).feed_url; + const after = (await svc.rotateTripToken(tripId, user.id, BASE)).feed_url; expect(after).not.toBe(before); expect(await svc.buildTripIcs(oldToken)).toBeNull(); @@ -189,12 +189,12 @@ describe('trip feed token lifecycle', () => { it('FEED-SVC-008: disable clears the column so the public URL dies', async () => { const { user, tripId } = seedTrip(); - const url = svc.generateTripToken(tripId, user.id, BASE).feed_url; + const url = (await svc.generateTripToken(tripId, user.id, BASE)).feed_url; const token = url.match(/trip\/([0-9a-f-]+)\.ics$/)![1]; - svc.disableTripToken(tripId, user.id); + await svc.disableTripToken(tripId, user.id); - expect(svc.getTripToken(tripId, user.id, BASE)).toEqual({ feed_url: null }); + expect(await svc.getTripToken(tripId, user.id, BASE)).toEqual({ feed_url: null }); expect(await svc.buildTripIcs(token)).toBeNull(); }); @@ -204,13 +204,13 @@ describe('trip feed token lifecycle', () => { // a trip id it merely guessed. const { user, tripId } = seedTrip(); const { user: outsider } = createUser(testDb); - const mine = svc.generateTripToken(tripId, user.id, BASE).feed_url; + const mine = (await svc.generateTripToken(tripId, user.id, BASE)).feed_url; const myToken = mine.match(/trip\/([0-9a-f-]+)\.ics$/)![1]; - svc.rotateTripToken(tripId, outsider.id, BASE); - expect(svc.getTripToken(tripId, user.id, BASE).feed_url).toBe(mine); + await svc.rotateTripToken(tripId, outsider.id, BASE); + expect((await svc.getTripToken(tripId, user.id, BASE)).feed_url).toBe(mine); - svc.disableTripToken(tripId, outsider.id); + await svc.disableTripToken(tripId, outsider.id); expect(await svc.buildTripIcs(myToken)).not.toBeNull(); }); }); @@ -221,29 +221,29 @@ describe('user feed token lifecycle', () => { it('FEED-SVC-009: reports null before and the absolute URL after generation', async () => { const { user } = createUser(testDb); - expect(svc.getUserToken(user.id, BASE)).toEqual({ feed_url: null }); + expect(await svc.getUserToken(user.id, BASE)).toEqual({ feed_url: null }); - const generated = svc.generateUserToken(user.id, BASE).feed_url; + const generated = (await svc.generateUserToken(user.id, BASE)).feed_url; expect(generated).toMatch(new RegExp(`^${BASE}/api/feed/user/[0-9a-f-]+\\.ics$`)); - expect(svc.getUserToken(user.id, BASE).feed_url).toBe(generated); + expect((await svc.getUserToken(user.id, BASE)).feed_url).toBe(generated); }); it('FEED-SVC-010: generate is idempotent — the existing URL is returned unchanged', async () => { const { user } = createUser(testDb); - const first = svc.generateUserToken(user.id, BASE); - const second = svc.generateUserToken(user.id, BASE); + const first = await svc.generateUserToken(user.id, BASE); + const second = await svc.generateUserToken(user.id, BASE); expect(second.feed_url).toBe(first.feed_url); }); it('FEED-SVC-011: rotate issues a fresh token and the previous URL stops resolving', async () => { const { user } = createUser(testDb); - const before = svc.generateUserToken(user.id, BASE).feed_url; + const before = (await svc.generateUserToken(user.id, BASE)).feed_url; const oldToken = before.match(/user\/([0-9a-f-]+)\.ics$/)![1]; - const after = svc.rotateUserToken(user.id, BASE).feed_url; + const after = (await svc.rotateUserToken(user.id, BASE)).feed_url; expect(after).not.toBe(before); expect(await svc.buildUserIcs(oldToken)).toBeNull(); @@ -251,12 +251,12 @@ describe('user feed token lifecycle', () => { it('FEED-SVC-012: disable clears the column so the public URL dies', async () => { const { user } = createUser(testDb); - const url = svc.generateUserToken(user.id, BASE).feed_url; + const url = (await svc.generateUserToken(user.id, BASE)).feed_url; const token = url.match(/user\/([0-9a-f-]+)\.ics$/)![1]; - svc.disableUserToken(user.id); + await svc.disableUserToken(user.id); - expect(svc.getUserToken(user.id, BASE)).toEqual({ feed_url: null }); + expect(await svc.getUserToken(user.id, BASE)).toEqual({ feed_url: null }); expect(await svc.buildUserIcs(token)).toBeNull(); }); }); diff --git a/server/tests/unit/nest/trips.controller.test.ts b/server/tests/unit/nest/trips.controller.test.ts index 835008954..41eff79b3 100644 --- a/server/tests/unit/nest/trips.controller.test.ts +++ b/server/tests/unit/nest/trips.controller.test.ts @@ -58,15 +58,6 @@ function svc(o: Partial = {}): TripsService { type CreateBody = Parameters[1]; const prePipeCreateBody = (body: unknown) => body as CreateBody; -function thrown(fn: () => unknown): { status: number; body: unknown } { - try { fn(); } catch (err) { - expect(err).toBeInstanceOf(HttpException); - const e = err as HttpException; - return { status: e.getStatus(), body: e.getResponse() }; - } - throw new Error('expected throw'); -} - async function thrownAsync(fn: () => Promise): Promise<{ status: number; body: unknown }> { try { await fn(); } catch (err) { expect(err).toBeInstanceOf(HttpException); @@ -79,34 +70,34 @@ async function thrownAsync(fn: () => Promise): Promise<{ status: number beforeEach(() => vi.clearAllMocks()); describe('TripsController (parity with the legacy /api/trips route)', async () => { - it('GET / lists for the user with the archived flag', () => { + it('GET / lists for the user with the archived flag', async () => { const list = vi.fn().mockReturnValue([{ id: 1 }]); - expect(tc(svc({ list } as Partial)).list(user, '1')).toEqual({ trips: [{ id: 1 }] }); + expect(await tc(svc({ list } as Partial)).list(user, '1')).toEqual({ trips: [{ id: 1 }] }); expect(list).toHaveBeenCalledWith(1, 1); }); - it('GET / defaults the archived flag to 0 when not "1"', () => { + it('GET / defaults the archived flag to 0 when not "1"', async () => { const list = vi.fn().mockReturnValue([]); const c = tc(svc({ list } as Partial)); - c.list(user, undefined); + await c.list(user, undefined); expect(list).toHaveBeenLastCalledWith(1, 0); - c.list(user, '0'); + await c.list(user, '0'); expect(list).toHaveBeenLastCalledWith(1, 0); }); describe('GET /active (startup destination)', () => { - it('narrows the row to the contract shape and drops the sort helper', () => { + it('narrows the row to the contract shape and drops the sort helper', async () => { const activeTrip = vi.fn().mockReturnValue({ id: 7, title: 'Japan', start_date: '2026-09-01', end_date: '2026-09-14', relevance: 1, }); - const res = tc(svc({ activeTrip } as Partial)).active(user); + const res = await tc(svc({ activeTrip } as Partial)).active(user); expect(res).toEqual({ trip: { id: 7, title: 'Japan', start_date: '2026-09-01', end_date: '2026-09-14' } }); expect(activeTripResponseSchema.safeParse(res).success).toBe(true); expect(activeTrip).toHaveBeenCalledWith(1); }); - it('answers null instead of 404 when the user has no trip, so the caller can fall back', () => { - const res = tc(svc({ activeTrip: vi.fn().mockReturnValue(undefined) } as Partial)).active(user); + it('answers null instead of 404 when the user has no trip, so the caller can fall back', async () => { + const res = await tc(svc({ activeTrip: vi.fn().mockReturnValue(undefined) } as Partial)).active(user); expect(res).toEqual({ trip: null }); expect(activeTripResponseSchema.safeParse(res).success).toBe(true); }); @@ -204,13 +195,13 @@ describe('TripsController (parity with the legacy /api/trips route)', async () = }); }); - it('GET /:id 404 when missing', () => { - expect(thrown(() => tc(svc({ get: vi.fn().mockReturnValue(undefined) } as Partial)).get(user, '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); + it('GET /:id 404 when missing', async () => { + expect(await thrownAsync(() => tc(svc({ get: vi.fn().mockReturnValue(undefined) } as Partial)).get(user, '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); }); - it('GET /:id returns the trip when present', () => { + it('GET /:id returns the trip when present', async () => { const s = svc({ get: vi.fn().mockReturnValue({ id: 9 }) } as Partial); - expect(tc(s).get(user, '9')).toEqual({ trip: { id: 9 } }); + expect(await tc(s).get(user, '9')).toEqual({ trip: { id: 9 } }); }); describe('PUT /:id', () => { @@ -329,7 +320,7 @@ describe('TripsController (parity with the legacy /api/trips route)', async () = }); it('GET /:id/bundle 404 then aggregates', async () => { - expect(thrown(() => tc(svc({ get: vi.fn().mockReturnValue(undefined) } as Partial)).bundle(user, '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); + expect(await thrownAsync(() => tc(svc({ get: vi.fn().mockReturnValue(undefined) } as Partial)).bundle(user, '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); const bundle = vi.fn().mockReturnValue({ trip: { id: 9 }, days: [] }); const s = svc({ get: vi.fn().mockReturnValue({ user_id: 1 }) } as Partial); expect(await tc(s, undefined, { bundle }).bundle(user, '9')).toEqual({ trip: { id: 9 }, days: [] }); diff --git a/server/tests/unit/nest/trips.service.test.ts b/server/tests/unit/nest/trips.service.test.ts index 659e7c4fa..8459070fe 100644 --- a/server/tests/unit/nest/trips.service.test.ts +++ b/server/tests/unit/nest/trips.service.test.ts @@ -198,7 +198,7 @@ function addDaysIso(date: string, n: number) { // ── Tests ───────────────────────────────────────────────────────────────────── describe('generateDays', () => { - it('TRIP-SVC-010: full range shift preserves day assignments and notes positionally', () => { + it('TRIP-SVC-010: full range shift preserves day assignments and notes positionally', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' }); const daysBefore = getDays(trip.id); @@ -209,7 +209,7 @@ describe('generateDays', () => { const note = createDayNote(testDb, daysBefore[1].id, trip.id, { text: 'packed' }); // Shift forward 9 days — zero overlap with original dates - svc.generateDays(trip.id, '2025-06-10', '2025-06-14'); + await svc.generateDays(trip.id, '2025-06-10', '2025-06-14'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(5); @@ -226,7 +226,7 @@ describe('generateDays', () => { expect(getNotes(day2.id)[0].id).toBe(note.id); }); - it('TRIP-SVC-011: shrinking range deletes overflow days and their assignments (issue #909)', () => { + it('TRIP-SVC-011: shrinking range deletes overflow days and their assignments (issue #909)', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-07-01', end_date: '2025-07-05' }); const daysBefore = getDays(trip.id); @@ -237,20 +237,20 @@ describe('generateDays', () => { createDayAssignment(testDb, daysBefore[4].id, place.id); // Shrink from 5 to 3 days — surplus days and their content are removed - svc.generateDays(trip.id, '2025-07-01', '2025-07-03'); + await svc.generateDays(trip.id, '2025-07-01', '2025-07-03'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(3); expect(daysAfter.map(d => d.date)).toEqual(['2025-07-01', '2025-07-02', '2025-07-03']); }); - it('TRIP-SVC-016: shrinking range deletes empty overflow days (issue #909)', () => { + it('TRIP-SVC-016: shrinking range deletes empty overflow days (issue #909)', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-07-01', end_date: '2025-07-07' }); expect(getDays(trip.id)).toHaveLength(7); // Shrink 7 → 5; days 6 and 7 have no content - svc.generateDays(trip.id, '2025-07-01', '2025-07-05'); + await svc.generateDays(trip.id, '2025-07-01', '2025-07-05'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(5); @@ -259,7 +259,7 @@ describe('generateDays', () => { ]); }); - it('TRIP-SVC-012: growing range keeps existing day content and appends new empty days', () => { + it('TRIP-SVC-012: growing range keeps existing day content and appends new empty days', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-08-01', end_date: '2025-08-03' }); const daysBefore = getDays(trip.id); @@ -269,7 +269,7 @@ describe('generateDays', () => { const assignment = createDayAssignment(testDb, daysBefore[0].id, place.id); // Grow to 5 days - svc.generateDays(trip.id, '2025-08-01', '2025-08-05'); + await svc.generateDays(trip.id, '2025-08-01', '2025-08-05'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(5); @@ -286,25 +286,25 @@ describe('generateDays', () => { expect(getAssignments(daysAfter[4].id)).toHaveLength(0); }); - it('TRIP-SVC-062: a range longer than a year gets every one of its days (#2403)', () => { + it('TRIP-SVC-062: a range longer than a year gets every one of its days (#2403)', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-01-26', end_date: '2025-01-28' }); // The reporter's range: 368 days, and the days used to stop at 365. - svc.generateDays(trip.id, '2025-01-26', '2026-01-28'); + await svc.generateDays(trip.id, '2025-01-26', '2026-01-28'); const days = getDays(trip.id); expect(days).toHaveLength(368); expect(days[364].date).toBe('2026-01-25'); expect(days[367]).toMatchObject({ day_number: 368, date: '2026-01-28' }); }); - it('TRIP-SVC-063: a dateless day_count is clamped to MAX_TRIP_DAYS', () => { + it('TRIP-SVC-063: a dateless day_count is clamped to MAX_TRIP_DAYS', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id); - svc.generateDays(trip.id, null, null, MAX_TRIP_DAYS + 50); + await svc.generateDays(trip.id, null, null, MAX_TRIP_DAYS + 50); expect(getDays(trip.id)).toHaveLength(MAX_TRIP_DAYS); }); - it('TRIP-SVC-013: clearing dates converts all days to dateless without destroying assignments', () => { + it('TRIP-SVC-013: clearing dates converts all days to dateless without destroying assignments', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-09-01', end_date: '2025-09-04' }); const daysBefore = getDays(trip.id); @@ -314,7 +314,7 @@ describe('generateDays', () => { const assignment = createDayAssignment(testDb, daysBefore[1].id, place.id); // Clear both dates - svc.generateDays(trip.id, null, null); + await svc.generateDays(trip.id, null, null); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(4); @@ -327,7 +327,7 @@ describe('generateDays', () => { expect(getAssignments(formerDay2!.id)[0].id).toBe(assignment.id); }); - it('TRIP-SVC-014: partial overlap shift remaps by position (day 1→3 kept, 4-5 overflow)', () => { + it('TRIP-SVC-014: partial overlap shift remaps by position (day 1→3 kept, 4-5 overflow)', async () => { // Original: Jun 1-5. New: Jun 3-7 (overlap on Jun 3-5, but we map by position) const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { start_date: '2025-10-01', end_date: '2025-10-05' }); @@ -337,7 +337,7 @@ describe('generateDays', () => { for (const day of daysBefore) createDayAssignment(testDb, day.id, place.id); // Shift forward 2 days (partial overlap with original range) - svc.generateDays(trip.id, '2025-10-03', '2025-10-07'); + await svc.generateDays(trip.id, '2025-10-03', '2025-10-07'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(5); @@ -351,7 +351,7 @@ describe('generateDays', () => { } }); - it('TRIP-SVC-015: growing into dateless days reuses them; leftover dateless renumber without UNIQUE collision', () => { + it('TRIP-SVC-015: growing into dateless days reuses them; leftover dateless renumber without UNIQUE collision', async () => { // 3 dated days + 2 pre-existing dateless days. Resize to 4 dated days. // Main loop: dated[0..2] → positions 1-3, dateless[0] → position 4 (consumed). // Unused dateless: dateless[1] should land at position 5, NOT 4 (collision bug). @@ -372,7 +372,7 @@ describe('generateDays', () => { // Grow from 3 to 4 dated days — consumes dateless[0], leaves dateless[1] unused // This is the scenario that triggered the UNIQUE collision bug - svc.generateDays(trip.id, '2025-11-01', '2025-11-04'); + await svc.generateDays(trip.id, '2025-11-01', '2025-11-04'); const daysAfter = getDays(trip.id); expect(daysAfter).toHaveLength(5); @@ -391,11 +391,11 @@ describe('generateDays', () => { expect(nums).toEqual([1, 2, 3, 4, 5]); }); - it('TRIP-SVC-017: switching a dateless trip to a shorter dated range drops empty leftover days but keeps ones with content (#1083)', () => { + it('TRIP-SVC-017: switching a dateless trip to a shorter dated range drops empty leftover days but keeps ones with content (#1083)', async () => { const { user } = createUser(testDb); // A 7-day trip, then cleared to dateless placeholders (day_count = 7). const trip = createTrip(testDb, user.id, { start_date: '2025-12-01', end_date: '2025-12-07' }); - svc.generateDays(trip.id, null, null); + await svc.generateDays(trip.id, null, null); const dateless = getDays(trip.id); expect(dateless).toHaveLength(7); expect(dateless.every(d => d.date === null)).toBe(true); @@ -406,7 +406,7 @@ describe('generateDays', () => { // Now set an explicit 2-day range. The first two dateless days are reused for // the dates; the four empty leftovers must be removed, the one with content kept. - svc.generateDays(trip.id, '2026-01-10', '2026-01-11'); + await svc.generateDays(trip.id, '2026-01-10', '2026-01-11'); const daysAfter = getDays(trip.id); const dated = daysAfter.filter(d => d.date !== null); @@ -738,7 +738,7 @@ describe('folded trip CRUD', () => { expect(await readModelSvc.getTripSummary(99999)).toBeNull(); }); - it('TRIP-SVC-043: list returns owned + shared trips with is_owner, honoring the archived filter', () => { + it('TRIP-SVC-043: list returns owned + shared trips with is_owner, honoring the archived filter', async () => { const { user: owner } = createUser(testDb); const { user: other } = createUser(testDb); const own = createTrip(testDb, owner.id, { title: 'Mine' }); @@ -747,18 +747,18 @@ describe('folded trip CRUD', () => { const archived = createTrip(testDb, owner.id, { title: 'Old' }); testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archived.id); - const active = svc.list(owner.id, 0) as any[]; + const active = (await svc.list(owner.id, 0)) as any[]; expect(active.map(t => t.id).sort()).toEqual([own.id, shared.id].sort()); expect(active.find(t => t.id === own.id).is_owner).toBe(1); expect(active.find(t => t.id === shared.id).is_owner).toBe(0); - const all = svc.list(owner.id, null) as any[]; + const all = (await svc.list(owner.id, null)) as any[]; expect(all.map(t => t.id).sort()).toEqual([own.id, shared.id, archived.id].sort()); }); - it('TRIP-SVC-044: create applies || defaults, clamps reminder_days and generates days', () => { + it('TRIP-SVC-044: create applies || defaults, clamps reminder_days and generates days', async () => { const { user } = createUser(testDb); - const { trip, tripId, reminderDays } = svc.create(user.id, { + const { trip, tripId, reminderDays } = await svc.create(user.id, { title: 'New Trip', start_date: '2025-06-01', end_date: '2025-06-03', reminder_days: 99, }); expect(reminderDays).toBe(3); // out-of-range → default 3 @@ -766,18 +766,18 @@ describe('folded trip CRUD', () => { expect(getDays(tripId)).toHaveLength(3); }); - it('TRIP-SVC-064: create refuses a range past MAX_TRIP_DAYS and writes nothing', () => { + it('TRIP-SVC-064: create refuses a range past MAX_TRIP_DAYS and writes nothing', async () => { const { user } = createUser(testDb); const before = (testDb.prepare('SELECT COUNT(*) AS n FROM trips').get() as { n: number }).n; - expect(() => svc.create(user.id, { title: 'Decade', start_date: '2026-01-01', end_date: '2036-01-01' })) - .toThrow(`A trip can span at most ${MAX_TRIP_DAYS} days`); + await expect(svc.create(user.id, { title: 'Decade', start_date: '2026-01-01', end_date: '2036-01-01' })) + .rejects.toThrow(`A trip can span at most ${MAX_TRIP_DAYS} days`); expect((testDb.prepare('SELECT COUNT(*) AS n FROM trips').get() as { n: number }).n).toBe(before); // The longest allowed range goes through in full. - const { tripId } = svc.create(user.id, { title: 'Longest', start_date: '2026-01-01', end_date: addDaysIso('2026-01-01', MAX_TRIP_DAYS - 1) }); + const { tripId } = await svc.create(user.id, { title: 'Longest', start_date: '2026-01-01', end_date: addDaysIso('2026-01-01', MAX_TRIP_DAYS - 1) }); expect(getDays(tripId)).toHaveLength(MAX_TRIP_DAYS); }); - it('TRIP-SVC-045: remove deletes the trip, cleans skeleton journey entries and detaches filled ones', () => { + it('TRIP-SVC-045: remove deletes the trip, cleans skeleton journey entries and detaches filled ones', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id); const journeyId = Number(testDb.prepare( @@ -790,7 +790,7 @@ describe('folded trip CRUD', () => { "INSERT INTO journey_entries (journey_id, source_trip_id, author_id, type, title, entry_date, created_at, updated_at) VALUES (?, ?, ?, 'story', 'F', '2025-06-01', 0, 0)", ).run(journeyId, trip.id, user.id).lastInsertRowid); - const info = svc.remove(trip.id, user.id, 'user'); + const info = await svc.remove(trip.id, user.id, 'user'); expect(info).toMatchObject({ tripId: trip.id, ownerId: user.id, isAdminDelete: false }); expect(testDb.prepare('SELECT id FROM trips WHERE id = ?').get(trip.id)).toBeUndefined(); @@ -799,10 +799,10 @@ describe('folded trip CRUD', () => { expect(filled.source_trip_id).toBeNull(); // Missing trips throw the byte-identical error. - expect(() => svc.remove(99999, user.id, 'user')).toThrow('Trip not found'); + await expect(svc.remove(99999, user.id, 'user')).rejects.toThrow('Trip not found'); }); - it('TRIP-SVC-046: copy duplicates days/places/assignments and resets packing to unchecked', () => { + it('TRIP-SVC-046: copy duplicates days/places/assignments and resets packing to unchecked', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { title: 'Origin', start_date: '2025-06-01', end_date: '2025-06-02' }); const days = getDays(trip.id); @@ -810,7 +810,7 @@ describe('folded trip CRUD', () => { createDayAssignment(testDb, days[0].id, place.id); testDb.prepare("INSERT INTO packing_items (trip_id, name, checked) VALUES (?, 'Socks', 1)").run(trip.id); - const newTripId = svc.copy(trip.id, user.id, 'Clone'); + const newTripId = await svc.copy(trip.id, user.id, 'Clone'); const copied = testDb.prepare('SELECT title, is_archived FROM trips WHERE id = ?').get(newTripId) as any; expect(copied.title).toBe('Clone'); @@ -823,11 +823,11 @@ describe('folded trip CRUD', () => { expect(packing).toEqual([{ checked: 0 }]); // No title → source title (|| fallback). - const secondCopy = svc.copy(trip.id, user.id); + const secondCopy = await svc.copy(trip.id, user.id); expect((testDb.prepare('SELECT title FROM trips WHERE id = ?').get(secondCopy) as any).title).toBe('Origin'); }); - it('TRIP-SVC-061: copy carries the road-trip shaping, not just the places', () => { + it('TRIP-SVC-061: copy carries the road-trip shaping, not just the places', async () => { // A via is the road the traveller chose over the one the router prefers, and // a day track is the line a day was fitted to. Leaving them behind gave back // a trip that looks complete and quietly drives somewhere else — noticed @@ -846,7 +846,7 @@ describe('folded trip CRUD', () => { testDb.prepare('INSERT INTO roadtrip_day_tracks (day_id, place_id, stray_km) VALUES (?, ?, 1.5)') .run(days[0].id, track.id); - const newTripId = svc.copy(trip.id, user.id, 'Clone'); + const newTripId = await svc.copy(trip.id, user.id, 'Clone'); const newDays = getDays(newTripId); // The kind of stop each place is survives the copy. @@ -873,7 +873,7 @@ describe('folded trip CRUD', () => { expect(testDb.prepare('SELECT COUNT(*) c FROM roadtrip_vias WHERE day_id = ?').get(days[0].id)).toEqual({ c: 2 }); }); - it('TRIP-SVC-060: copying a trip keeps a staged booking staged', () => { + it('TRIP-SVC-060: copying a trip keeps a staged booking staged', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { title: 'Origin', start_date: '2025-06-01', end_date: '2025-06-02' }); testDb.prepare(`INSERT INTO reservations (trip_id, title, type, status, ingest_state) @@ -881,7 +881,7 @@ describe('folded trip CRUD', () => { testDb.prepare(`INSERT INTO reservations (trip_id, title, type, status) VALUES (?, 'Booked', 'flight', 'confirmed')`).run(trip.id); - const newTripId = svc.copy(trip.id, user.id, 'Clone'); + const newTripId = await svc.copy(trip.id, user.id, 'Clone'); // Without ingest_state on the duplicate INSERT the staged row falls back to // the column default and shows up in the copy's public feed. @@ -899,7 +899,7 @@ describe('folded trip CRUD', () => { * member's Personal or Shared item reappeared in the copy as a Common item * that everyone on the new trip could read (GHSA-vh2h-288v-ggch). */ - it("TRIP-SVC-046b: copy leaves other members' restricted packing items behind", () => { + it("TRIP-SVC-046b: copy leaves other members' restricted packing items behind", async () => { const { user: owner } = createUser(testDb); const { user: member } = createUser(testDb); const trip = createTrip(testDb, owner.id, { title: 'Origin', start_date: '2025-06-01', end_date: '2025-06-02' }); @@ -908,7 +908,7 @@ describe('folded trip CRUD', () => { ins.run(trip.id, "Owner's diary", 1, owner.id); // the owner's Personal ins.run(trip.id, "Member's meds", 1, member.id); // the copier's own Personal - const newTripId = svc.copy(trip.id, member.id, 'Copy'); + const newTripId = await svc.copy(trip.id, member.id, 'Copy'); const rows = testDb.prepare('SELECT name, is_private, owner_id FROM packing_items WHERE trip_id = ? ORDER BY name').all(newTripId) as any[]; // The owner's private row is gone, not relabelled as Common. @@ -918,7 +918,7 @@ describe('folded trip CRUD', () => { expect(rows.find(r => r.name === "Member's meds")).toMatchObject({ is_private: 1, owner_id: member.id }); }); - it('TRIP-SVC-059: copy remaps cross-links and carries splits/participants (smoke-test I-01)', () => { + it('TRIP-SVC-059: copy remaps cross-links and carries splits/participants (smoke-test I-01)', async () => { const { user: owner } = createUser(testDb); const { user: friend } = createUser(testDb); const trip = createTrip(testDb, owner.id, { title: 'Linked', start_date: '2025-06-01', end_date: '2025-06-02' }); @@ -946,7 +946,7 @@ describe('folded trip CRUD', () => { testDb.prepare('INSERT INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, 240)').run(itemId, owner.id); testDb.prepare("INSERT INTO todo_items (trip_id, name, checked) VALUES (?, 'Book transfer', 1)").run(trip.id); - const newTripId = svc.copy(trip.id, owner.id, 'Linked copy'); + const newTripId = await svc.copy(trip.id, owner.id, 'Linked copy'); // Budget → reservation link points at the copied reservation, not null / not the old id. const newItem = testDb.prepare('SELECT * FROM budget_items WHERE trip_id = ?').get(newTripId) as any; @@ -1020,7 +1020,7 @@ describe('TripsService wrapper helpers', () => { it('canAccessTrip delegates to the db helper; can() delegates to checkPermission; broadcast forwards', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id); - expect(svc.canAccessTrip(String(trip.id), user.id)).toMatchObject({ user_id: user.id }); + expect(await svc.canAccessTrip(String(trip.id), user.id)).toMatchObject({ user_id: user.id }); expect(await svc.can('trip_edit', 'user', user.id, user.id, false)).toBe(true); @@ -1028,10 +1028,10 @@ describe('TripsService wrapper helpers', () => { expect(broadcast).toHaveBeenCalledWith('9', 'trip:updated', { a: 1 }, 'sock'); }); - it('getCopiedTrip re-reads via the TRIP_SELECT query', () => { + it('getCopiedTrip re-reads via the TRIP_SELECT query', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { title: 'Copied' }); - const row = svc.getCopiedTrip(trip.id, user.id) as any; + const row = (await svc.getCopiedTrip(trip.id, user.id)) as any; expect(row.id).toBe(trip.id); expect(row.is_owner).toBe(1); }); @@ -1132,7 +1132,7 @@ describe('folded quirk branches', () => { expect(testDb.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(trip.id, invitee.id)).toBeUndefined(); }); - it('TRIP-SVC-050: copy remaps tags, accommodations, reservations, day notes, budget, bags and category order', () => { + it('TRIP-SVC-050: copy remaps tags, accommodations, reservations, day notes, budget, bags and category order', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { title: 'Deep', start_date: '2025-06-01', end_date: '2025-06-02' }); const days = getDays(trip.id); @@ -1153,7 +1153,7 @@ describe('folded quirk branches', () => { testDb.prepare("INSERT INTO todo_items (trip_id, name, checked) VALUES (?, 'Book', 1)").run(trip.id); testDb.prepare("INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, 'stay', 2)").run(trip.id); - const newTripId = svc.copy(trip.id, user.id); + const newTripId = await svc.copy(trip.id, user.id); const newDays = getDays(newTripId); expect(newDays).toHaveLength(2); @@ -1178,7 +1178,7 @@ describe('folded quirk branches', () => { expect((testDb.prepare('SELECT COUNT(*) AS n FROM day_notes WHERE trip_id = ?').get(newTripId) as any).n).toBe(1); // Missing source throws the byte-identical error. - expect(() => svc.copy(99999, user.id)).toThrow('Trip not found'); + await expect(svc.copy(99999, user.id)).rejects.toThrow('Trip not found'); }); }); @@ -1238,7 +1238,7 @@ describe('quirk fixes', () => { ).run(journeyId, trip.id, user.id); const broken = await failingTrips('DELETE FROM trips WHERE id = ?'); - expect(() => broken.remove(trip.id, user.id, 'user')).toThrow('boom'); + await expect(broken.remove(trip.id, user.id, 'user')).rejects.toThrow('boom'); // The skeleton cleanup rolled back with the failed delete. expect(testDb.prepare("SELECT id FROM journey_entries WHERE type = 'skeleton'").get()).toBeDefined(); @@ -1278,41 +1278,41 @@ describe('quirk fixes', () => { describe('activeTrip (startup destination)', () => { const TODAY = '2026-08-08'; - it('TRIP-SVC-054: prefers the trip running today over anything upcoming', () => { + it('TRIP-SVC-054: prefers the trip running today over anything upcoming', async () => { const { user } = createUser(testDb); createTrip(testDb, user.id, { title: 'soon', start_date: '2026-08-20', end_date: '2026-08-25' }); createTrip(testDb, user.id, { title: 'running', start_date: '2026-08-05', end_date: '2026-08-12' }); - expect(svc.activeTrip(user.id, TODAY)?.title).toBe('running'); + expect((await svc.activeTrip(user.id, TODAY))?.title).toBe('running'); }); - it('TRIP-SVC-055: without a running trip it takes the next one starting, earliest first', () => { + it('TRIP-SVC-055: without a running trip it takes the next one starting, earliest first', async () => { const { user } = createUser(testDb); createTrip(testDb, user.id, { title: 'late', start_date: '2026-12-01', end_date: '2026-12-10' }); createTrip(testDb, user.id, { title: 'soon', start_date: '2026-09-01', end_date: '2026-09-10' }); - expect(svc.activeTrip(user.id, TODAY)?.title).toBe('soon'); + expect((await svc.activeTrip(user.id, TODAY))?.title).toBe('soon'); }); - it('TRIP-SVC-056: falls back to the most recently started trip, undated ones last', () => { + it('TRIP-SVC-056: falls back to the most recently started trip, undated ones last', async () => { const { user } = createUser(testDb); createTrip(testDb, user.id, { title: 'undated' }); createTrip(testDb, user.id, { title: 'old', start_date: '2020-01-01', end_date: '2020-01-10' }); createTrip(testDb, user.id, { title: 'recent', start_date: '2026-07-01', end_date: '2026-07-10' }); - expect(svc.activeTrip(user.id, TODAY)?.title).toBe('recent'); + expect((await svc.activeTrip(user.id, TODAY))?.title).toBe('recent'); }); - it('TRIP-SVC-057: skips archived trips and returns undefined when nothing is left', () => { + it('TRIP-SVC-057: skips archived trips and returns undefined when nothing is left', async () => { const { user } = createUser(testDb); const archived = createTrip(testDb, user.id, { title: 'archived', start_date: '2026-08-05', end_date: '2026-08-12' }); testDb.prepare('UPDATE trips SET is_archived = 1 WHERE id = ?').run(archived.id); - expect(svc.activeTrip(user.id, TODAY)).toBeUndefined(); + expect(await svc.activeTrip(user.id, TODAY)).toBeUndefined(); }); - it('TRIP-SVC-058: sees shared trips but never another user\'s private ones', () => { + it('TRIP-SVC-058: sees shared trips but never another user\'s private ones', async () => { const { user: owner } = createUser(testDb); const { user: guest } = createUser(testDb); createTrip(testDb, owner.id, { title: 'private', start_date: '2026-08-05', end_date: '2026-08-12' }); const shared = createTrip(testDb, owner.id, { title: 'shared', start_date: '2026-09-01', end_date: '2026-09-10' }); addTripMember(testDb, shared.id, guest.id); - expect(svc.activeTrip(guest.id, TODAY)?.title).toBe('shared'); + expect((await svc.activeTrip(guest.id, TODAY))?.title).toBe('shared'); }); });