mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
Split the trip aggregate root into its parts
TripsService injected fourteen other services. Almost all of them were there for two read aggregates - the MCP trip summary and the offline bundle - and for the member roster, not for anything the write path does. Reading is what fans out; writing is not. Membership goes to trip-members/: listMembers, addMember, removeMember, transferOwnership and the four guest methods, plus the six routes, which keep their paths. It is a NEW module, not the trip-membership/ leaf next door: deleting a guest erases their plugin data and re-splits their expenses, so it needs auth and budget, and AuthModule already imports that leaf. Giving it those dependencies there would have closed a hard cycle. This one is a sink - nothing imports it back except trips. The read aggregates go to trip-read-model/, which is where the nine-service fan-out now lives. What is left is the write core plus day generation, on eight parameters instead of fourteen: database, reservations, days, permissions, budget, vacay, realtime, unsplash. The last four are all reachable from updateTrip's date-shift transaction, which is why the count does not fall to three. Trips still reaches budget through ReservationsModule, so trips.bridge.ts survives this. Saying otherwise would have been the easy claim to make and it would not have been true.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import type { User } from '../../types';
|
||||
import { TripMembersService } from './trip-members.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { getClientIp } from '../audit/client-ip';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
import { TripAddMemberDto, TripTransferOwnershipDto, TripCreateGuestDto, TripRenameGuestDto } from '../trips/trips.dto';
|
||||
|
||||
/**
|
||||
* /api/trips/:id/{members,transfer,guests} — who is on a trip.
|
||||
*
|
||||
* Same prefix as TripsController but a separate class in a separate module:
|
||||
* every route here is at least one segment deeper than the @Get(':id') it sits
|
||||
* beside, so there is no ambiguity, and TripInviteLinkController has served
|
||||
* /api/trips/:tripId/invite-link from its own module for as long.
|
||||
*
|
||||
* No class-level TripAccessGuard on purpose. Guards run before pipes, so one
|
||||
* here would answer the trip 404 before the body pipe could answer its 400, and
|
||||
* the e2e cases pin that order. The inline canAccessTrip checks are the ones
|
||||
* that moved, unchanged.
|
||||
*/
|
||||
@Controller('api/trips')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class TripMembersController {
|
||||
constructor(private readonly roster: TripMembersService, private readonly audit: AuditService) {}
|
||||
|
||||
@Get(':id/members')
|
||||
members(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
const { owner, members } = this.roster.listMembers(id, access.user_id);
|
||||
return { owner, members, current_user_id: user.id };
|
||||
}
|
||||
|
||||
@Post(':id/members')
|
||||
@HttpCode(201)
|
||||
addMember(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripAddMemberDto) {
|
||||
const { identifier } = body;
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (!this.roster.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) {
|
||||
throw new HttpException({ error: 'No permission to manage members' }, 403);
|
||||
}
|
||||
try {
|
||||
const result = this.roster.addMember(id, identifier, access.user_id, user.id);
|
||||
this.roster.notifyInvite(id, user, result.targetUserId, result.tripTitle, result.member.email);
|
||||
return { member: result.member };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id/members/:userId')
|
||||
removeMember(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
const targetId = parseInt(userId);
|
||||
if (targetId !== user.id && !this.roster.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) {
|
||||
throw new HttpException({ error: 'No permission to remove members' }, 403);
|
||||
}
|
||||
this.roster.removeMember(id, targetId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Post(':id/transfer')
|
||||
transferOwnership(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id') id: string,
|
||||
@Body() body: TripTransferOwnershipDto,
|
||||
@Req() req: Request,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const { newOwnerId } = body;
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
// Owner-only: handing over a trip is reserved for its actual owner, not just
|
||||
// anyone who can manage members.
|
||||
if (access.user_id !== user.id) {
|
||||
throw new HttpException({ error: 'Only the owner can transfer ownership' }, 403);
|
||||
}
|
||||
try {
|
||||
const result = this.roster.transferOwnership(id, newOwnerId, user.id);
|
||||
this.audit.writeAudit({ userId: user.id, action: 'trip.transfer_ownership', ip: getClientIp(req), details: { tripId: Number(id), trip: result.tripTitle, from: result.fromEmail, to: result.toEmail } });
|
||||
// Nudge everyone viewing the trip to re-read it so the new ownership and the
|
||||
// recomputed permissions take effect live.
|
||||
const updatedTrip = this.roster.getTripForViewer(id, user.id);
|
||||
this.roster.broadcast(id, 'trip:updated', { trip: updatedTrip }, socketId);
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the trip or throws 404, then asserts the caller is its owner (guest CRUD, #1362). */
|
||||
private requireOwner(id: string, user: User): void {
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (access.user_id !== user.id) {
|
||||
throw new HttpException({ error: 'Only the owner can manage guests' }, 403);
|
||||
}
|
||||
}
|
||||
|
||||
@Post(':id/guests')
|
||||
@HttpCode(201)
|
||||
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripCreateGuestDto) {
|
||||
this.requireOwner(id, user);
|
||||
// Whitespace-only names still 400 with the legacy body — the service throws
|
||||
// ValidationError('Guest name is required') after trimming.
|
||||
try {
|
||||
// No notifyInvite: a guest has no inbox.
|
||||
return this.roster.createGuest(id, body.name, user.id);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Put(':id/guests/:userId')
|
||||
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: TripRenameGuestDto) {
|
||||
this.requireOwner(id, user);
|
||||
try {
|
||||
if (!this.roster.renameGuest(id, parseInt(userId), body.name)) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof HttpException) throw e;
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id/guests/:userId')
|
||||
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
this.requireOwner(id, user);
|
||||
if (!this.roster.deleteGuest(id, parseInt(userId))) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TripMembersController } from './trip-members.controller';
|
||||
import { TripMembersService } from './trip-members.service';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { BudgetModule } from '../budget/budget.module';
|
||||
|
||||
/**
|
||||
* The member/guest roster of a trip.
|
||||
*
|
||||
* A sink module: it imports auth (for the plugin-data erasure a deleted guest
|
||||
* triggers) and budget (for the expense re-split that goes with it), and nothing
|
||||
* imports it back except trips. That is what keeps it legal — trip-membership/
|
||||
* next door cannot do the same, because AuthModule imports *that* one, so giving
|
||||
* it these dependencies would close the cycle.
|
||||
*/
|
||||
@Module({
|
||||
imports: [DatabaseModule, PermissionsModule, RealtimeModule, AuditModule, AuthModule, BudgetModule],
|
||||
controllers: [TripMembersController],
|
||||
providers: [TripMembersService],
|
||||
exports: [TripMembersService],
|
||||
})
|
||||
export class TripMembersModule {}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { User } from '../../types';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { UserCleanupService } from '../auth/user-cleanup.service';
|
||||
import { BudgetService } from '../budget/budget.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { TRIP_SELECT } from '../trips/trips.service';
|
||||
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { emitUserDeleted } from '../../plugin-user-lifecycle';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
|
||||
export interface AddMemberResult {
|
||||
member: { id: number; username: string; email: string; avatar?: string | null; role: string; avatar_url: string | null };
|
||||
targetUserId: number;
|
||||
tripTitle: string;
|
||||
}
|
||||
|
||||
export interface TransferOwnershipResult {
|
||||
tripTitle: string;
|
||||
fromEmail: string;
|
||||
toEmail: string;
|
||||
}
|
||||
|
||||
// ── Guest members (#1362) ───────────────────────────────
|
||||
//
|
||||
// A guest is a credential-less users row (is_guest=1) joined into trip_members, so
|
||||
// it is assignable everywhere a real member is (budget splits, packing, to-dos, day
|
||||
// participants) yet can never authenticate (the auth/global-list guards exclude
|
||||
// is_guest=1). The display name lives in users.username so every existing JOIN that
|
||||
// renders a member name shows the guest correctly; a synthetic, non-deliverable
|
||||
// email keeps the UNIQUE/NOT NULL constraints satisfied.
|
||||
|
||||
export interface GuestMember {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
role: 'member';
|
||||
is_guest: true;
|
||||
avatar_url: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who is on a trip: real members, the owner handover, and the credential-less
|
||||
* guests (#1362).
|
||||
*
|
||||
* Its own domain because it was one of three places that could put somebody on
|
||||
* a trip, and because it is the reason TripsService reached for the auth and
|
||||
* budget domains at all: deleting a guest erases their plugin data and re-splits
|
||||
* the expenses they were part of.
|
||||
*
|
||||
* NOT the same module as trip-membership/. That one is a deliberate leaf with no
|
||||
* imports, and AuthModule imports it — so it can never depend on auth or budget
|
||||
* without closing a cycle. This module is a sink: it imports both and nothing
|
||||
* imports it back except trips.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TripMembersService {
|
||||
constructor(
|
||||
private readonly dbs: DatabaseService,
|
||||
private readonly budget: BudgetService,
|
||||
private readonly userCleanup: UserCleanupService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
return this.dbs.connection;
|
||||
}
|
||||
|
||||
canAccessTrip(tripId: string | number, userId: number) {
|
||||
return this.dbs.canAccessTrip(tripId, userId) as { user_id: number } | null | undefined;
|
||||
}
|
||||
|
||||
can(action: string, role: string, ownerId: number | null, userId: number, isMember: boolean): boolean {
|
||||
return this.permissions.checkPermission(action, role, ownerId, userId, isMember);
|
||||
}
|
||||
|
||||
broadcast<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
|
||||
this.realtime.broadcast(tripId, event, payload, socketId);
|
||||
}
|
||||
|
||||
/** The trip in list shape, for the re-read a handover broadcasts. Same query the
|
||||
* trip routes use, imported rather than copied so the two cannot drift. */
|
||||
getTripForViewer(tripId: string | number, userId: number) {
|
||||
return this.db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId });
|
||||
}
|
||||
|
||||
/** Fire-and-forget trip-invite notification (mirrors the route's dynamic import). */
|
||||
notifyInvite(tripId: string, actor: User, targetUserId: number, tripTitle: string, inviteeEmail: string): void {
|
||||
import('../notifications/notifications.bridge').then(({ send }) => {
|
||||
send({
|
||||
event: 'trip_invite',
|
||||
actorId: actor.id,
|
||||
scope: 'user',
|
||||
targetId: targetUserId,
|
||||
params: { trip: tripTitle, actor: actor.email, invitee: inviteeEmail, tripId: String(tripId) },
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
// ── Members ───────────────────────────────────────────────────────────────
|
||||
|
||||
listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
// u.is_guest rides along (#1362) so guests stay assignable everywhere a member is,
|
||||
// while the UI can badge them and suppress owner-only actions. The owner is never a guest.
|
||||
const members = this.db.prepare(`
|
||||
SELECT u.id, COALESCE(u.display_name, u.username) AS username, u.email, u.avatar, u.is_guest,
|
||||
CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END as role,
|
||||
m.added_at,
|
||||
COALESCE(ib.display_name, ib.username) as invited_by_username
|
||||
FROM trip_members m
|
||||
JOIN users u ON u.id = m.user_id
|
||||
LEFT JOIN users ib ON ib.id = m.invited_by
|
||||
WHERE m.trip_id = ?
|
||||
ORDER BY m.added_at ASC
|
||||
`).all(tripOwnerId, tripId) as { id: number; username: string; email: string; avatar: string | null; is_guest: number; role: string; added_at: string; invited_by_username: string | null }[];
|
||||
|
||||
// Quirk fix on top of the 1:1 move: the owner row prefers display_name like
|
||||
// every member row does (the legacy query read the raw username only).
|
||||
const owner = this.db.prepare('SELECT id, COALESCE(display_name, username) AS username, email, avatar FROM users WHERE id = ?').get(tripOwnerId) as Pick<User, 'id' | 'username' | 'email' | 'avatar'>;
|
||||
|
||||
return {
|
||||
owner: { ...owner, role: 'owner', is_guest: false, avatar_url: avatarUrl(owner) },
|
||||
members: members.map(m => ({ ...m, is_guest: !!m.is_guest, avatar_url: avatarUrl(m) })),
|
||||
};
|
||||
}
|
||||
|
||||
addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): AddMemberResult {
|
||||
if (!identifier) throw new ValidationError('Email or username required');
|
||||
|
||||
// Guests (#1362) are not invitable accounts — exclude them so a trip-scoped guest
|
||||
// can never be resolved (and re-attached to another trip) through the invite box.
|
||||
const target = this.db.prepare(
|
||||
'SELECT id, username, email, avatar FROM users WHERE (email = ? OR username = ?) AND COALESCE(is_guest, 0) = 0'
|
||||
).get(identifier.trim(), identifier.trim()) as Pick<User, 'id' | 'username' | 'email' | 'avatar'> | undefined;
|
||||
|
||||
if (!target) throw new NotFoundError('User not found');
|
||||
|
||||
if (target.id === tripOwnerId)
|
||||
throw new ValidationError('Trip owner is already a member');
|
||||
|
||||
const existing = this.db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, target.id);
|
||||
if (existing) throw new ValidationError('User already has access');
|
||||
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, target.id, invitedByUserId);
|
||||
|
||||
const tripInfo = this.db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined;
|
||||
|
||||
return {
|
||||
member: { ...target, role: 'member', avatar_url: avatarUrl(target) },
|
||||
targetUserId: target.id,
|
||||
tripTitle: tripInfo?.title || 'Untitled',
|
||||
};
|
||||
}
|
||||
|
||||
removeMember(tripId: string | number, targetUserId: number): void {
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, targetUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand a trip over to one of its existing members (#973). The new owner must
|
||||
* already be a member; afterwards they hold `trips.user_id` and the former owner
|
||||
* becomes a regular member, so nobody loses access. Runs in a transaction so the
|
||||
* owner pointer and the membership rows never diverge.
|
||||
*/
|
||||
transferOwnership(
|
||||
tripId: string | number,
|
||||
newOwnerId: number,
|
||||
currentOwnerId: number,
|
||||
): TransferOwnershipResult {
|
||||
const trip = this.db.prepare('SELECT id, title, user_id FROM trips WHERE id = ?').get(tripId) as { id: number; title: string; user_id: number } | undefined;
|
||||
if (!trip) throw new NotFoundError('Trip not found');
|
||||
if (trip.user_id !== currentOwnerId) throw new ValidationError('Only the owner can transfer ownership');
|
||||
if (newOwnerId === currentOwnerId) throw new ValidationError('You already own this trip');
|
||||
|
||||
const newOwner = this.db.prepare('SELECT id, email, is_guest FROM users WHERE id = ?').get(newOwnerId) as { id: number; email: string; is_guest?: number } | undefined;
|
||||
if (!newOwner) throw new NotFoundError('User not found');
|
||||
// A guest (#1362) can never log in, so it must never become the owner of a trip.
|
||||
if (newOwner.is_guest) throw new ValidationError('Cannot transfer ownership to a guest');
|
||||
|
||||
const isMember = this.db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, newOwnerId);
|
||||
if (!isMember) throw new ValidationError('New owner must be a trip member');
|
||||
|
||||
const fromEmail = (this.db.prepare('SELECT email FROM users WHERE id = ?').get(currentOwnerId) as { email: string } | undefined)?.email || '';
|
||||
|
||||
const run = this.db.transaction(() => {
|
||||
this.db.prepare('UPDATE trips SET user_id = ? WHERE id = ?').run(newOwnerId, tripId);
|
||||
// The new owner is no longer a plain member…
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, newOwnerId);
|
||||
// …and the former owner keeps access as a member.
|
||||
this.db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, currentOwnerId, newOwnerId);
|
||||
});
|
||||
run();
|
||||
|
||||
return { tripTitle: trip.title, fromEmail, toEmail: newOwner.email };
|
||||
}
|
||||
|
||||
// ── Guest members (#1362) ───────────────────────────────────────────────────
|
||||
|
||||
/** username is UNIQUE across all users — keep the typed name but disambiguate guests
|
||||
* that happen to share it (e.g. two "Anna"s) with a numeric suffix. */
|
||||
createGuest(tripId: string | number, name: string, invitedByUserId: number): { member: GuestMember } {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
|
||||
// The human name lives in display_name (not unique — two trips can each have a
|
||||
// "Jake", #1446); username is a uuid handle only for the UNIQUE constraint and is
|
||||
// never shown (member views COALESCE display_name over it).
|
||||
const email = `guest-${randomUUID()}@guests.invalid`;
|
||||
const username = `guest-${randomUUID()}`;
|
||||
|
||||
const create = this.db.transaction(() => {
|
||||
const res = this.db.prepare(
|
||||
"INSERT INTO users (username, email, password_hash, role, is_guest, display_name) VALUES (?, ?, '', 'user', 1, ?)"
|
||||
).run(username, email, display);
|
||||
const guestId = Number(res.lastInsertRowid);
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, guestId, invitedByUserId);
|
||||
return guestId;
|
||||
});
|
||||
const guestId = create();
|
||||
|
||||
return { member: { id: guestId, username: display, email, role: 'member', is_guest: true, avatar_url: null } };
|
||||
}
|
||||
|
||||
/** Confirms a user id is a guest of THIS trip, so guest mutations stay trip-scoped. */
|
||||
private guestOfTrip(tripId: string | number, guestUserId: number): boolean {
|
||||
return !!this.db.prepare(
|
||||
'SELECT u.id FROM users u JOIN trip_members m ON m.user_id = u.id WHERE u.id = ? AND m.trip_id = ? AND u.is_guest = 1'
|
||||
).get(guestUserId, tripId);
|
||||
}
|
||||
|
||||
renameGuest(tripId: string | number, guestUserId: number, name: string): boolean {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
|
||||
// Rename only the display name — no global-uniqueness dedup, so a rename to a name
|
||||
// another trip's guest already uses no longer produces "Name 2" (#1446).
|
||||
this.db.prepare('UPDATE users SET display_name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND is_guest = 1').run(display, guestUserId);
|
||||
return true;
|
||||
}
|
||||
|
||||
deleteGuest(tripId: string | number, guestUserId: number): boolean {
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
// A guest is still a user id a plugin may hold data for, so erase that too — the
|
||||
// host-side per-user tables + a durable own-db erasure per granted plugin — exactly
|
||||
// like a full account deletion (otherwise a deleted guest's plugin data lingers).
|
||||
this.userCleanup.erasePluginUserData(guestUserId);
|
||||
// Quirk fix on top of the 1:1 move: the budget re-split and the user delete
|
||||
// run in one transaction, so a failure mid-flow can't leave the expense
|
||||
// divisors re-derived for a guest that still exists (or vice versa). The
|
||||
// plugin-side erasure/notification keep their order around it.
|
||||
this.db.transaction(() => {
|
||||
// Re-split the expenses they were part of before the cascade takes their member
|
||||
// rows away — the divisor is denormalized and cannot follow a foreign key (#1553).
|
||||
this.budget.removeUserFromBudgetItems(guestUserId);
|
||||
// Deleting the guest's users row cascades its membership and every assignment join
|
||||
// (trip_members, budget/packing/assignment links) via the ON DELETE foreign keys.
|
||||
this.db.prepare('DELETE FROM users WHERE id = ? AND is_guest = 1').run(guestUserId);
|
||||
})();
|
||||
emitUserDeleted(guestUserId); // deliver the erasure to any active plugin now
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TripReadModelService } from './trip-read-model.service';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { DaysModule } from '../days/days.module';
|
||||
import { AccommodationsModule } from '../accommodations/accommodations.module';
|
||||
import { BudgetModule } from '../budget/budget.module';
|
||||
import { PackingModule } from '../packing/packing.module';
|
||||
import { ReservationsModule } from '../reservations/reservations.module';
|
||||
import { CollabModule } from '../collab/collab.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { TodoModule } from '../todo/todo.module';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
import { TripMembersModule } from '../trip-members/trip-members.module';
|
||||
|
||||
/** Where the trip read aggregates keep their fan-out, so the write path does not
|
||||
* have to carry it. Nothing imports this except trips. */
|
||||
@Module({
|
||||
imports: [
|
||||
DatabaseModule, TripMembersModule, DaysModule, AccommodationsModule, BudgetModule,
|
||||
PackingModule, ReservationsModule, CollabModule, PlacesModule, TodoModule, FilesModule,
|
||||
],
|
||||
providers: [TripReadModelService],
|
||||
exports: [TripReadModelService],
|
||||
})
|
||||
export class TripReadModelModule {}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { DaysService } from '../days/days.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { BudgetService } from '../budget/budget.service';
|
||||
import { PackingService } from '../packing/packing.service';
|
||||
import { ReservationsService } from '../reservations/reservations.service';
|
||||
import { CollabService } from '../collab/collab.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { TodoService } from '../todo/todo.service';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { TripMembersService } from '../trip-members/trip-members.service';
|
||||
|
||||
/**
|
||||
* The two read aggregates over a trip: the MCP summary and the offline bundle.
|
||||
*
|
||||
* They were the reason TripsService injected nine other domain services while
|
||||
* its write path needs a handful. Reading is the fan-out; the writing core is
|
||||
* not. Split apart, the aggregate root talks to database, permissions, realtime
|
||||
* and the four domains its own updates touch, and everything that only ever
|
||||
* appeared inside a summary lives here.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TripReadModelService {
|
||||
constructor(
|
||||
private readonly dbs: DatabaseService,
|
||||
private readonly members: TripMembersService,
|
||||
private readonly days: DaysService,
|
||||
private readonly accommodations: AccommodationsService,
|
||||
private readonly budget: BudgetService,
|
||||
private readonly packing: PackingService,
|
||||
private readonly reservations: ReservationsService,
|
||||
private readonly collab: CollabService,
|
||||
private readonly places: PlacesService,
|
||||
private readonly todo: TodoService,
|
||||
private readonly files: FilesService,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
return this.dbs.connection;
|
||||
}
|
||||
|
||||
private getOwner(tripId: string | number): { user_id: number } | undefined {
|
||||
return this.db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined;
|
||||
}
|
||||
|
||||
// ── Trip summary (used by MCP get_trip_summary tool) ──────────────────────
|
||||
|
||||
getTripSummary(tripId: number, viewerUserId?: number) {
|
||||
const trip = this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Record<string, unknown> | undefined;
|
||||
if (!trip) return null;
|
||||
|
||||
const ownerRow = this.getOwner(tripId);
|
||||
if (!ownerRow) return null;
|
||||
const { owner, members } = this.members.listMembers(tripId, ownerRow.user_id);
|
||||
|
||||
const { days: rawDays } = this.days.list(tripId);
|
||||
const days = rawDays.map(({ notes_items, ...day }) => ({ ...day, notes: notes_items }));
|
||||
|
||||
const accommodations = this.accommodations.list(tripId);
|
||||
|
||||
const budgetItems = this.budget.listBudgetItems(tripId);
|
||||
const budget = {
|
||||
items: budgetItems,
|
||||
item_count: budgetItems.length,
|
||||
total: budgetItems.reduce((sum, i) => sum + (i.total_price || 0), 0),
|
||||
currency: trip.currency,
|
||||
};
|
||||
|
||||
// Thread the viewer so another member's private/personal packing items (#858)
|
||||
// stay hidden — without it listItems returns the UNFILTERED list.
|
||||
const packingItems = this.packing.listItems(tripId, viewerUserId);
|
||||
const packing = {
|
||||
items: packingItems,
|
||||
total: packingItems.length,
|
||||
checked: (packingItems as { checked: number }[]).filter(i => i.checked).length,
|
||||
};
|
||||
|
||||
const reservations = this.reservations.list(tripId);
|
||||
const collab_notes = this.collab.listNotes(tripId);
|
||||
|
||||
return {
|
||||
trip,
|
||||
members: { owner, collaborators: members },
|
||||
days,
|
||||
accommodations,
|
||||
budget,
|
||||
packing,
|
||||
reservations,
|
||||
collab_notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Bundle / notifications (route helpers) ────────────────────────────────
|
||||
|
||||
/** Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). */
|
||||
bundle(tripId: string, trip: { user_id: number }, viewerId: number) {
|
||||
const { days } = this.days.list(tripId);
|
||||
const { owner, members } = this.members.listMembers(tripId, trip.user_id);
|
||||
return {
|
||||
trip,
|
||||
days,
|
||||
places: this.places.list(String(tripId), {}),
|
||||
// Scope to the requesting member so other members' private packing items
|
||||
// (#858) never land in this viewer's offline cache.
|
||||
packingItems: this.packing.listItems(tripId, viewerId),
|
||||
todoItems: this.todo.listItems(tripId),
|
||||
budgetItems: this.budget.listBudgetItems(tripId),
|
||||
reservations: this.reservations.list(tripId),
|
||||
files: this.files.listFiles(tripId, false),
|
||||
accommodations: this.accommodations.list(tripId),
|
||||
members: [owner, ...(members || [])].filter(Boolean),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import { PlacesService } from '../places/places.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { UserCleanupService } from '../auth/user-cleanup.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { TripMembersService } from '../trip-members/trip-members.service';
|
||||
import { TripReadModelService } from '../trip-read-model/trip-read-model.service';
|
||||
|
||||
/**
|
||||
* Non-Nest entry point for the trip domain — for the two consumers that cannot
|
||||
@@ -44,22 +46,35 @@ const dbs = () => new DatabaseService(db);
|
||||
const photoCache = new PlacePhotoCacheService(dbs(), new RuntimeEnvService());
|
||||
const journeyDomain = new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs()));
|
||||
const budget = new BudgetService(dbs(), new PermissionsService(dbs()), new ExchangeRatesService(), new RealtimeService());
|
||||
const permissions = new PermissionsService(dbs());
|
||||
const realtime = new RealtimeService();
|
||||
const days = new DaysService(dbs(), permissions, realtime, new QueryHelpersService(dbs()));
|
||||
const accommodations = new AccommodationsService(dbs(), permissions, realtime);
|
||||
const reservations = new ReservationsService(dbs(), permissions, budget, realtime);
|
||||
const places = new PlacesService(dbs(), permissions, realtime, new MapsService(dbs(), photoCache), new QueryHelpersService(dbs()), new UnsplashService(dbs(), new RuntimeEnvService()), photoCache, journeyDomain);
|
||||
const trips = new TripsService(
|
||||
dbs(),
|
||||
new TodoService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
|
||||
new PackingService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
|
||||
new FilesService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
|
||||
new ReservationsService(dbs(), new PermissionsService(dbs()), budget, new RealtimeService()),
|
||||
new DaysService(dbs(), new PermissionsService(dbs()), new RealtimeService(), new QueryHelpersService(dbs())),
|
||||
new PermissionsService(dbs()),
|
||||
reservations,
|
||||
days,
|
||||
permissions,
|
||||
budget,
|
||||
new CollabService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
|
||||
new VacayService(dbs(), new RealtimeService()),
|
||||
new RealtimeService(),
|
||||
new PlacesService(dbs(), new PermissionsService(dbs()), new RealtimeService(), new MapsService(dbs(), photoCache), new QueryHelpersService(dbs()), new UnsplashService(dbs(), new RuntimeEnvService()), photoCache, journeyDomain),
|
||||
new VacayService(dbs(), realtime),
|
||||
realtime,
|
||||
new UnsplashService(dbs(), new RuntimeEnvService()),
|
||||
new UserCleanupService(dbs()),
|
||||
new AccommodationsService(dbs(), new PermissionsService(dbs()), new RealtimeService()),
|
||||
);
|
||||
const members = new TripMembersService(dbs(), budget, new UserCleanupService(dbs()), permissions, realtime);
|
||||
const readModel = new TripReadModelService(
|
||||
dbs(),
|
||||
members,
|
||||
days,
|
||||
accommodations,
|
||||
budget,
|
||||
new PackingService(dbs(), permissions, realtime),
|
||||
reservations,
|
||||
new CollabService(dbs(), permissions, realtime),
|
||||
places,
|
||||
new TodoService(dbs(), permissions, realtime),
|
||||
new FilesService(dbs(), permissions, realtime),
|
||||
);
|
||||
|
||||
export function getTripOwner(tripId: string | number) {
|
||||
@@ -67,11 +82,11 @@ export function getTripOwner(tripId: string | number) {
|
||||
}
|
||||
|
||||
export function listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
return trips.listMembers(tripId, tripOwnerId);
|
||||
return members.listMembers(tripId, tripOwnerId);
|
||||
}
|
||||
|
||||
export function getTripSummary(tripId: number, viewerUserId?: number) {
|
||||
return trips.getTripSummary(tripId, viewerUserId);
|
||||
return readModel.getTripSummary(tripId, viewerUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,6 +36,7 @@ import { NotFoundError, ValidationError } from './trips.service';
|
||||
import { TripCreateDto, TripUpdateDto, TripCopyDto, TripAddMemberDto, TripTransferOwnershipDto, TripCreateGuestDto, TripRenameGuestDto } from './trips.dto';
|
||||
import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
import { CalendarService } from '../calendar/calendar.service';
|
||||
import { TripReadModelService } from '../trip-read-model/trip-read-model.service';
|
||||
|
||||
const MAX_COVER_SIZE = 20 * 1024 * 1024;
|
||||
const coversDir = path.join(__dirname, '../../../uploads/covers');
|
||||
@@ -73,7 +74,7 @@ const addDays = (d: Date, n: number) => { const r = new Date(d); r.setDate(r.get
|
||||
export class TripsController {
|
||||
// calendar last: the hand-wired construction sites in the tests stay positional,
|
||||
// so a new dependency does not touch the ones that never reach the ICS route.
|
||||
constructor(private readonly trips: TripsService, private readonly audit: AuditService, private readonly env: RuntimeEnvService, private readonly unsplash: UnsplashService, private readonly calendar: CalendarService) {}
|
||||
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) {}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: User, @Query('archived') archived?: string) {
|
||||
@@ -253,142 +254,13 @@ export class TripsController {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Get(':id/members')
|
||||
members(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
const { owner, members } = this.trips.listMembers(id, access.user_id);
|
||||
return { owner, members, current_user_id: user.id };
|
||||
}
|
||||
|
||||
@Post(':id/members')
|
||||
@HttpCode(201)
|
||||
addMember(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripAddMemberDto) {
|
||||
const { identifier } = body;
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (!this.trips.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) {
|
||||
throw new HttpException({ error: 'No permission to manage members' }, 403);
|
||||
}
|
||||
try {
|
||||
const result = this.trips.addMember(id, identifier, access.user_id, user.id);
|
||||
this.trips.notifyInvite(id, user, result.targetUserId, result.tripTitle, result.member.email);
|
||||
return { member: result.member };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id/members/:userId')
|
||||
removeMember(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
const targetId = parseInt(userId);
|
||||
if (targetId !== user.id && !this.trips.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id)) {
|
||||
throw new HttpException({ error: 'No permission to remove members' }, 403);
|
||||
}
|
||||
this.trips.removeMember(id, targetId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Post(':id/transfer')
|
||||
transferOwnership(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id') id: string,
|
||||
@Body() body: TripTransferOwnershipDto,
|
||||
@Req() req: Request,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const { newOwnerId } = body;
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
// Owner-only: handing over a trip is reserved for its actual owner, not just
|
||||
// anyone who can manage members.
|
||||
if (access.user_id !== user.id) {
|
||||
throw new HttpException({ error: 'Only the owner can transfer ownership' }, 403);
|
||||
}
|
||||
try {
|
||||
const result = this.trips.transferOwnership(id, newOwnerId, user.id);
|
||||
this.audit.writeAudit({ userId: user.id, action: 'trip.transfer_ownership', ip: getClientIp(req), details: { tripId: Number(id), trip: result.tripTitle, from: result.fromEmail, to: result.toEmail } });
|
||||
// Nudge everyone viewing the trip to re-read it so the new ownership and the
|
||||
// recomputed permissions take effect live.
|
||||
const updatedTrip = this.trips.get(id, user.id);
|
||||
this.trips.broadcast(id, 'trip:updated', { trip: updatedTrip }, socketId);
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the trip or throws 404, then asserts the caller is its owner (guest CRUD, #1362). */
|
||||
private requireOwner(id: string, user: User): void {
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (access.user_id !== user.id) {
|
||||
throw new HttpException({ error: 'Only the owner can manage guests' }, 403);
|
||||
}
|
||||
}
|
||||
|
||||
@Post(':id/guests')
|
||||
@HttpCode(201)
|
||||
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripCreateGuestDto) {
|
||||
this.requireOwner(id, user);
|
||||
// Whitespace-only names still 400 with the legacy body — the service throws
|
||||
// ValidationError('Guest name is required') after trimming.
|
||||
try {
|
||||
// No notifyInvite: a guest has no inbox.
|
||||
return this.trips.createGuest(id, body.name, user.id);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Put(':id/guests/:userId')
|
||||
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: TripRenameGuestDto) {
|
||||
this.requireOwner(id, user);
|
||||
try {
|
||||
if (!this.trips.renameGuest(id, parseInt(userId), body.name)) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof HttpException) throw e;
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id/guests/:userId')
|
||||
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
this.requireOwner(id, user);
|
||||
if (!this.trips.deleteGuest(id, parseInt(userId))) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Get(':id/bundle')
|
||||
bundle(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const trip = this.trips.get(id, user.id) as { user_id: number } | undefined;
|
||||
if (!trip) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
return this.trips.bundle(id, trip, user.id);
|
||||
return this.readModel.bundle(id, trip, user.id);
|
||||
}
|
||||
|
||||
@Get(':id/export.ics')
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { CalendarService } from '../calendar/calendar.service';
|
||||
import { TripMembersService } from '../trip-members/trip-members.service';
|
||||
import { TripReadModelService } from '../trip-read-model/trip-read-model.service';
|
||||
import { isAddonEnabled, getCollabFeatures } from '../addons/addons.bridge';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { safeBroadcast, MAX_MCP_TRIP_DAYS, noAccess, hasTripPermission, permissionDenied } from '../../mcp/tools/_shared';
|
||||
@@ -67,6 +69,8 @@ export class TripsMcp {
|
||||
// Appended, not inserted: the hand-wired MCP test harnesses build this
|
||||
// positionally, so an earlier slot would silently shift every one of them.
|
||||
private readonly calendar: CalendarService,
|
||||
private readonly members: TripMembersService,
|
||||
private readonly readModel: TripReadModelService,
|
||||
) {}
|
||||
|
||||
// --- TRIPS ---
|
||||
@@ -204,7 +208,7 @@ export class TripsMcp {
|
||||
})
|
||||
async getTripSummary({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
const summary = this.trips.getTripSummary(tripId, ctx.userId);
|
||||
const summary = this.readModel.getTripSummary(tripId, ctx.userId);
|
||||
if (!summary) return noAccess();
|
||||
const R = canReadTrips(ctx.scopes);
|
||||
// Addon availability gates
|
||||
@@ -275,7 +279,7 @@ export class TripsMcp {
|
||||
if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
const ownerRow = this.trips.getOwner(tripId);
|
||||
if (!ownerRow) return noAccess();
|
||||
const { owner, members } = this.trips.listMembers(tripId, ownerRow.user_id);
|
||||
const { owner, members } = this.members.listMembers(tripId, ownerRow.user_id);
|
||||
return ok({ owner, members });
|
||||
}
|
||||
|
||||
@@ -296,7 +300,7 @@ export class TripsMcp {
|
||||
if (!ownerRow || ownerRow.user_id !== ctx.userId)
|
||||
return { content: [{ type: 'text' as const, text: 'Only the trip owner can add members.' }], isError: true };
|
||||
try {
|
||||
const result = this.trips.addMember(tripId, identifier, ownerRow.user_id, ctx.userId);
|
||||
const result = this.members.addMember(tripId, identifier, ownerRow.user_id, ctx.userId);
|
||||
safeBroadcast(tripId, 'member:added', { member: result.member });
|
||||
return ok({ member: result.member });
|
||||
} catch (err) {
|
||||
@@ -321,7 +325,7 @@ export class TripsMcp {
|
||||
const ownerRow = this.trips.getOwner(tripId);
|
||||
if (!ownerRow || ownerRow.user_id !== ctx.userId)
|
||||
return { content: [{ type: 'text' as const, text: 'Only the trip owner can remove members.' }], isError: true };
|
||||
this.trips.removeMember(tripId, memberId);
|
||||
this.members.removeMember(tripId, memberId);
|
||||
safeBroadcast(tripId, 'member:removed', { userId: memberId });
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -407,7 +411,7 @@ export class TripsMcp {
|
||||
if (id === null || !this.trips.canAccessTrip(id, ctx.userId)) return accessDenied(uri.href);
|
||||
const ownerRow = this.trips.getOwner(id);
|
||||
if (!ownerRow) return accessDenied(uri.href);
|
||||
const { owner, members } = this.trips.listMembers(id, ownerRow.user_id);
|
||||
const { owner, members } = this.members.listMembers(id, ownerRow.user_id);
|
||||
return jsonContent(uri.href, { owner, members });
|
||||
}
|
||||
|
||||
@@ -425,7 +429,7 @@ export class TripsMcp {
|
||||
if (!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 = this.trips.getTripSummary(tripId, ctx.userId);
|
||||
const summary = this.readModel.getTripSummary(tripId, ctx.userId);
|
||||
if (!summary) {
|
||||
return { messages: [{ role: 'user' as const, content: { type: 'text' as const, text: 'Trip not found.' } }] };
|
||||
}
|
||||
|
||||
@@ -22,11 +22,13 @@ import { TripsMcp } from './trips.mcp';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { CalendarModule } from '../calendar/calendar.module';
|
||||
import { AccommodationsModule } from '../accommodations/accommodations.module';
|
||||
import { TripMembersModule } from '../trip-members/trip-members.module';
|
||||
import { TripReadModelModule } from '../trip-read-model/trip-read-model.module';
|
||||
|
||||
/** Trips aggregate root (C1 — Phase 3). Uses exact strangler prefixes so it does
|
||||
* not capture the nested sub-domain mounts (collab, files, ...). */
|
||||
@Module({
|
||||
imports: [TodoModule, PackingModule, FilesModule, ReservationsModule, DaysModule, PermissionsModule, AuditModule, BudgetModule, CollabModule, VacayModule, PlacesModule, AuthModule, AppConfigModule, UnsplashModule, RealtimeModule, PluginGuardsModule, TripMembershipModule, CalendarModule, AccommodationsModule],
|
||||
imports: [TodoModule, PackingModule, FilesModule, ReservationsModule, DaysModule, PermissionsModule, AuditModule, BudgetModule, CollabModule, VacayModule, PlacesModule, AuthModule, AppConfigModule, UnsplashModule, RealtimeModule, PluginGuardsModule, TripMembershipModule, CalendarModule, AccommodationsModule, TripMembersModule, TripReadModelModule],
|
||||
controllers: [TripsController],
|
||||
providers: [TripsService, TripsMcp, TripsRpc],
|
||||
// Exported for FeedsModule (ICS feeds) and PluginsModule (RPC host injection).
|
||||
|
||||
@@ -9,6 +9,7 @@ import { DatabaseService } from '../database/database.service';
|
||||
import { ReservationsService } from '../reservations/reservations.service';
|
||||
import { DaysService } from '../days/days.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { TripMembersService } from '../trip-members/trip-members.service';
|
||||
import { TripMembershipService } from '../trip-membership/trip-membership.service';
|
||||
import { TripsService, NotFoundError, ValidationError } from './trips.service';
|
||||
|
||||
@@ -40,6 +41,7 @@ export class TripsRpc {
|
||||
private readonly guards: PluginGuards,
|
||||
// Appended: the hand-wired plugin-host harnesses build this positionally.
|
||||
private readonly accommodations: AccommodationsService,
|
||||
private readonly roster: TripMembersService,
|
||||
) {}
|
||||
|
||||
@PluginMethod('trips.getById', { permission: 'db:read:trips' })
|
||||
@@ -183,7 +185,7 @@ export class TripsRpc {
|
||||
// Ownership transfer is a separate, deliberate action.
|
||||
const trip = this.db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined;
|
||||
if (trip && trip.user_id === targetUserId) throw new ForbiddenResource('cannot remove the trip owner');
|
||||
this.trips.removeMember(tripId, targetUserId);
|
||||
this.roster.removeMember(tripId, targetUserId);
|
||||
return { removed: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,14 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { ActiveTrip, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import type { Trip, User } from '../../types';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { UserCleanupService } from '../auth/user-cleanup.service';
|
||||
import { emitUserDeleted } from '../../plugin-user-lifecycle';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { DaysService } from '../days/days.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { PackingService } from '../packing/packing.service';
|
||||
import { TodoService } from '../todo/todo.service';
|
||||
import { BudgetService } from '../budget/budget.service';
|
||||
import { ReservationsService } from '../reservations/reservations.service';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { CollabService } from '../collab/collab.service';
|
||||
import { VacayService } from '../vacay/vacay.service';
|
||||
import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
@@ -111,7 +101,10 @@ export interface GuestMember {
|
||||
}
|
||||
|
||||
/**
|
||||
* Trip aggregate root, DI-native. The SQL moved 1:1 from the legacy
|
||||
* Trip aggregate root, DI-native. Membership, the calendar export and the two
|
||||
* read aggregates live in their own domains now; what is left is the write core
|
||||
* plus day generation, which is why the constructor is eight parameters instead
|
||||
* of fourteen. The SQL moved 1:1 from the legacy
|
||||
* services/tripService.ts: identical statements, the `||` falsy-coercion
|
||||
* defaults, the post-write TRIP_SELECT re-selects and the mixed
|
||||
* named/positional parameter styles are all preserved byte-for-byte.
|
||||
@@ -127,21 +120,13 @@ export interface GuestMember {
|
||||
export class TripsService {
|
||||
constructor(
|
||||
private readonly dbs: DatabaseService,
|
||||
private readonly todo: TodoService,
|
||||
private readonly packing: PackingService,
|
||||
private readonly files: FilesService,
|
||||
private readonly reservations: ReservationsService,
|
||||
private readonly days: DaysService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly budget: BudgetService,
|
||||
private readonly collab: CollabService,
|
||||
private readonly vacay: VacayService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly places: PlacesService,
|
||||
private readonly unsplash: UnsplashService,
|
||||
private readonly userCleanup: UserCleanupService,
|
||||
// Appended: the hand-wired construction sites stay positional.
|
||||
private readonly accommodations: AccommodationsService,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
@@ -691,253 +676,6 @@ export class TripsService {
|
||||
return this.db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId: newTripId });
|
||||
}
|
||||
|
||||
// ── Members ───────────────────────────────────────────────────────────────
|
||||
|
||||
listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
// u.is_guest rides along (#1362) so guests stay assignable everywhere a member is,
|
||||
// while the UI can badge them and suppress owner-only actions. The owner is never a guest.
|
||||
const members = this.db.prepare(`
|
||||
SELECT u.id, COALESCE(u.display_name, u.username) AS username, u.email, u.avatar, u.is_guest,
|
||||
CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END as role,
|
||||
m.added_at,
|
||||
COALESCE(ib.display_name, ib.username) as invited_by_username
|
||||
FROM trip_members m
|
||||
JOIN users u ON u.id = m.user_id
|
||||
LEFT JOIN users ib ON ib.id = m.invited_by
|
||||
WHERE m.trip_id = ?
|
||||
ORDER BY m.added_at ASC
|
||||
`).all(tripOwnerId, tripId) as { id: number; username: string; email: string; avatar: string | null; is_guest: number; role: string; added_at: string; invited_by_username: string | null }[];
|
||||
|
||||
// Quirk fix on top of the 1:1 move: the owner row prefers display_name like
|
||||
// every member row does (the legacy query read the raw username only).
|
||||
const owner = this.db.prepare('SELECT id, COALESCE(display_name, username) AS username, email, avatar FROM users WHERE id = ?').get(tripOwnerId) as Pick<User, 'id' | 'username' | 'email' | 'avatar'>;
|
||||
|
||||
return {
|
||||
owner: { ...owner, role: 'owner', is_guest: false, avatar_url: avatarUrl(owner) },
|
||||
members: members.map(m => ({ ...m, is_guest: !!m.is_guest, avatar_url: avatarUrl(m) })),
|
||||
};
|
||||
}
|
||||
|
||||
addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): AddMemberResult {
|
||||
if (!identifier) throw new ValidationError('Email or username required');
|
||||
|
||||
// Guests (#1362) are not invitable accounts — exclude them so a trip-scoped guest
|
||||
// can never be resolved (and re-attached to another trip) through the invite box.
|
||||
const target = this.db.prepare(
|
||||
'SELECT id, username, email, avatar FROM users WHERE (email = ? OR username = ?) AND COALESCE(is_guest, 0) = 0'
|
||||
).get(identifier.trim(), identifier.trim()) as Pick<User, 'id' | 'username' | 'email' | 'avatar'> | undefined;
|
||||
|
||||
if (!target) throw new NotFoundError('User not found');
|
||||
|
||||
if (target.id === tripOwnerId)
|
||||
throw new ValidationError('Trip owner is already a member');
|
||||
|
||||
const existing = this.db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, target.id);
|
||||
if (existing) throw new ValidationError('User already has access');
|
||||
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, target.id, invitedByUserId);
|
||||
|
||||
const tripInfo = this.db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined;
|
||||
|
||||
return {
|
||||
member: { ...target, role: 'member', avatar_url: avatarUrl(target) },
|
||||
targetUserId: target.id,
|
||||
tripTitle: tripInfo?.title || 'Untitled',
|
||||
};
|
||||
}
|
||||
|
||||
removeMember(tripId: string | number, targetUserId: number): void {
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, targetUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand a trip over to one of its existing members (#973). The new owner must
|
||||
* already be a member; afterwards they hold `trips.user_id` and the former owner
|
||||
* becomes a regular member, so nobody loses access. Runs in a transaction so the
|
||||
* owner pointer and the membership rows never diverge.
|
||||
*/
|
||||
transferOwnership(
|
||||
tripId: string | number,
|
||||
newOwnerId: number,
|
||||
currentOwnerId: number,
|
||||
): TransferOwnershipResult {
|
||||
const trip = this.db.prepare('SELECT id, title, user_id FROM trips WHERE id = ?').get(tripId) as { id: number; title: string; user_id: number } | undefined;
|
||||
if (!trip) throw new NotFoundError('Trip not found');
|
||||
if (trip.user_id !== currentOwnerId) throw new ValidationError('Only the owner can transfer ownership');
|
||||
if (newOwnerId === currentOwnerId) throw new ValidationError('You already own this trip');
|
||||
|
||||
const newOwner = this.db.prepare('SELECT id, email, is_guest FROM users WHERE id = ?').get(newOwnerId) as { id: number; email: string; is_guest?: number } | undefined;
|
||||
if (!newOwner) throw new NotFoundError('User not found');
|
||||
// A guest (#1362) can never log in, so it must never become the owner of a trip.
|
||||
if (newOwner.is_guest) throw new ValidationError('Cannot transfer ownership to a guest');
|
||||
|
||||
const isMember = this.db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, newOwnerId);
|
||||
if (!isMember) throw new ValidationError('New owner must be a trip member');
|
||||
|
||||
const fromEmail = (this.db.prepare('SELECT email FROM users WHERE id = ?').get(currentOwnerId) as { email: string } | undefined)?.email || '';
|
||||
|
||||
const run = this.db.transaction(() => {
|
||||
this.db.prepare('UPDATE trips SET user_id = ? WHERE id = ?').run(newOwnerId, tripId);
|
||||
// The new owner is no longer a plain member…
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, newOwnerId);
|
||||
// …and the former owner keeps access as a member.
|
||||
this.db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, currentOwnerId, newOwnerId);
|
||||
});
|
||||
run();
|
||||
|
||||
return { tripTitle: trip.title, fromEmail, toEmail: newOwner.email };
|
||||
}
|
||||
|
||||
// ── Guest members (#1362) ───────────────────────────────────────────────────
|
||||
|
||||
/** username is UNIQUE across all users — keep the typed name but disambiguate guests
|
||||
* that happen to share it (e.g. two "Anna"s) with a numeric suffix. */
|
||||
createGuest(tripId: string | number, name: string, invitedByUserId: number): { member: GuestMember } {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
|
||||
// The human name lives in display_name (not unique — two trips can each have a
|
||||
// "Jake", #1446); username is a uuid handle only for the UNIQUE constraint and is
|
||||
// never shown (member views COALESCE display_name over it).
|
||||
const email = `guest-${randomUUID()}@guests.invalid`;
|
||||
const username = `guest-${randomUUID()}`;
|
||||
|
||||
const create = this.db.transaction(() => {
|
||||
const res = this.db.prepare(
|
||||
"INSERT INTO users (username, email, password_hash, role, is_guest, display_name) VALUES (?, ?, '', 'user', 1, ?)"
|
||||
).run(username, email, display);
|
||||
const guestId = Number(res.lastInsertRowid);
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, guestId, invitedByUserId);
|
||||
return guestId;
|
||||
});
|
||||
const guestId = create();
|
||||
|
||||
return { member: { id: guestId, username: display, email, role: 'member', is_guest: true, avatar_url: null } };
|
||||
}
|
||||
|
||||
/** Confirms a user id is a guest of THIS trip, so guest mutations stay trip-scoped. */
|
||||
private guestOfTrip(tripId: string | number, guestUserId: number): boolean {
|
||||
return !!this.db.prepare(
|
||||
'SELECT u.id FROM users u JOIN trip_members m ON m.user_id = u.id WHERE u.id = ? AND m.trip_id = ? AND u.is_guest = 1'
|
||||
).get(guestUserId, tripId);
|
||||
}
|
||||
|
||||
renameGuest(tripId: string | number, guestUserId: number, name: string): boolean {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
|
||||
// Rename only the display name — no global-uniqueness dedup, so a rename to a name
|
||||
// another trip's guest already uses no longer produces "Name 2" (#1446).
|
||||
this.db.prepare('UPDATE users SET display_name = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND is_guest = 1').run(display, guestUserId);
|
||||
return true;
|
||||
}
|
||||
|
||||
deleteGuest(tripId: string | number, guestUserId: number): boolean {
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
// A guest is still a user id a plugin may hold data for, so erase that too — the
|
||||
// host-side per-user tables + a durable own-db erasure per granted plugin — exactly
|
||||
// like a full account deletion (otherwise a deleted guest's plugin data lingers).
|
||||
this.userCleanup.erasePluginUserData(guestUserId);
|
||||
// Quirk fix on top of the 1:1 move: the budget re-split and the user delete
|
||||
// run in one transaction, so a failure mid-flow can't leave the expense
|
||||
// divisors re-derived for a guest that still exists (or vice versa). The
|
||||
// plugin-side erasure/notification keep their order around it.
|
||||
this.db.transaction(() => {
|
||||
// Re-split the expenses they were part of before the cascade takes their member
|
||||
// rows away — the divisor is denormalized and cannot follow a foreign key (#1553).
|
||||
this.budget.removeUserFromBudgetItems(guestUserId);
|
||||
// Deleting the guest's users row cascades its membership and every assignment join
|
||||
// (trip_members, budget/packing/assignment links) via the ON DELETE foreign keys.
|
||||
this.db.prepare('DELETE FROM users WHERE id = ? AND is_guest = 1').run(guestUserId);
|
||||
})();
|
||||
emitUserDeleted(guestUserId); // deliver the erasure to any active plugin now
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Trip summary (used by MCP get_trip_summary tool) ──────────────────────
|
||||
|
||||
getTripSummary(tripId: number, viewerUserId?: number) {
|
||||
const trip = this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Record<string, unknown> | undefined;
|
||||
if (!trip) return null;
|
||||
|
||||
const ownerRow = this.getOwner(tripId);
|
||||
if (!ownerRow) return null;
|
||||
const { owner, members } = this.listMembers(tripId, ownerRow.user_id);
|
||||
|
||||
const { days: rawDays } = this.days.list(tripId);
|
||||
const days = rawDays.map(({ notes_items, ...day }) => ({ ...day, notes: notes_items }));
|
||||
|
||||
const accommodations = this.accommodations.list(tripId);
|
||||
|
||||
const budgetItems = this.budget.listBudgetItems(tripId);
|
||||
const budget = {
|
||||
items: budgetItems,
|
||||
item_count: budgetItems.length,
|
||||
total: budgetItems.reduce((sum, i) => sum + (i.total_price || 0), 0),
|
||||
currency: trip.currency,
|
||||
};
|
||||
|
||||
// Thread the viewer so another member's private/personal packing items (#858)
|
||||
// stay hidden — without it listItems returns the UNFILTERED list.
|
||||
const packingItems = this.packing.listItems(tripId, viewerUserId);
|
||||
const packing = {
|
||||
items: packingItems,
|
||||
total: packingItems.length,
|
||||
checked: (packingItems as { checked: number }[]).filter(i => i.checked).length,
|
||||
};
|
||||
|
||||
const reservations = this.reservations.list(tripId);
|
||||
const collab_notes = this.collab.listNotes(tripId);
|
||||
|
||||
return {
|
||||
trip,
|
||||
members: { owner, collaborators: members },
|
||||
days,
|
||||
accommodations,
|
||||
budget,
|
||||
packing,
|
||||
reservations,
|
||||
collab_notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Bundle / notifications (route helpers) ────────────────────────────────
|
||||
|
||||
/** Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). */
|
||||
bundle(tripId: string, trip: { user_id: number }, viewerId: number) {
|
||||
const { days } = this.days.list(tripId);
|
||||
const { owner, members } = this.listMembers(tripId, trip.user_id);
|
||||
return {
|
||||
trip,
|
||||
days,
|
||||
places: this.places.list(String(tripId), {}),
|
||||
// Scope to the requesting member so other members' private packing items
|
||||
// (#858) never land in this viewer's offline cache.
|
||||
packingItems: this.packing.listItems(tripId, viewerId),
|
||||
todoItems: this.todo.listItems(tripId),
|
||||
budgetItems: this.budget.listBudgetItems(tripId),
|
||||
reservations: this.reservations.list(tripId),
|
||||
files: this.files.listFiles(tripId, false),
|
||||
accommodations: this.accommodations.list(tripId),
|
||||
members: [owner, ...(members || [])].filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
/** Fire-and-forget trip-invite notification (mirrors the route's dynamic import). */
|
||||
notifyInvite(tripId: string, actor: User, targetUserId: number, tripTitle: string, inviteeEmail: string): void {
|
||||
import('../notifications/notifications.bridge').then(({ send }) => {
|
||||
send({
|
||||
event: 'trip_invite',
|
||||
actorId: actor.id,
|
||||
scope: 'user',
|
||||
targetId: targetUserId,
|
||||
params: { trip: tripTitle, actor: actor.email, invitee: inviteeEmail, tripId: String(tripId) },
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Defined in common/ so calendar and maps can raise them without importing the
|
||||
|
||||
Reference in New Issue
Block a user