Migrate TREK 3 to NestJS + React 19 with a shared Zod contract layer

Brownfield strangler migration of the backend onto NestJS modules
(auth, trips, days, places, assignments, packing, todo, budget,
reservations, collab, files, photos, journey, share, settings, backup,
oidc, oauth, admin, atlas, vacay, weather, airports, maps, categories,
tags, notifications, system-notices) served through a per-prefix
dispatcher, keeping the existing SQLite/better-sqlite3 DB and JWT
httpOnly cookie auth, with behavioural parity for every route.

Client: React 19 upgrade, "page = wiring container + data hook"
pattern across all pages, per-domain Zustand stores bound to
@trek/shared contracts, and decomposition of the large components
(DayPlanSidebar, PackingListPanel, CollabNotes, FileManager,
MemoriesPanel, PlacesSidebar, CollabChat, SystemNoticeModal,
BudgetPanel, PlaceFormModal, ...) into focused render units backed by
in-file hooks.

Apply the shared global request pipeline (helmet/CSP, CORS, HSTS,
forced HTTPS, the global MFA policy and request logging) to the NestJS
instance as well, so a migrated route is protected identically to the
legacy fallback rather than bypassing it.
This commit is contained in:
Maurice
2026-05-30 02:39:26 +02:00
parent 6d2dd37414
commit fc7d8b5d12
347 changed files with 31278 additions and 10381 deletions
+183
View File
@@ -0,0 +1,183 @@
import {
Body,
Controller,
Delete,
Get,
Headers,
HttpException,
Param,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import type { User } from '../../types';
import { BudgetService } from './budget.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
/**
* /api/trips/:tripId/budget — trip-scoped expense planner.
*
* Byte-identical to the legacy Express route (server/src/routes/budget.ts):
* every handler verifies trip access (404); mutations check 'budget_edit' (403);
* create is 201, the rest 200; bespoke 400/404 bodies reproduced; mutations
* broadcast over WebSocket with the forwarded X-Socket-Id. Static sub-routes
* (summary, settlement, reorder/*) are declared before /:id so they win over the
* param. Updating total_price on a reservation-linked item syncs the price back.
*/
@Controller('api/trips/:tripId/budget')
@UseGuards(JwtAuthGuard)
export class BudgetController {
constructor(private readonly budget: BudgetService) {}
private requireTrip(tripId: string, user: User) {
const trip = this.budget.verifyTripAccess(tripId, user.id);
if (!trip) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
return trip;
}
private requireEdit(trip: ReturnType<BudgetService['verifyTripAccess']>, user: User): void {
if (!this.budget.canEdit(trip!, user)) {
throw new HttpException({ error: 'No permission' }, 403);
}
}
@Get()
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
return { items: this.budget.list(tripId) };
}
@Get('summary/per-person')
perPerson(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
return { summary: this.budget.perPersonSummary(tripId) };
}
@Get('settlement')
settlement(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
return this.budget.settlement(tripId);
}
@Post()
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { name?: string; category?: string; total_price?: number; persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (!body.name) {
throw new HttpException({ error: 'Name is required' }, 400);
}
const item = this.budget.create(tripId, body as { name: string });
this.budget.broadcast(tripId, 'budget:created', { item }, socketId);
return { item };
}
@Put('reorder/items')
reorderItems(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body('orderedIds') orderedIds: number[],
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
this.budget.reorderItems(tripId, orderedIds);
this.budget.broadcast(tripId, 'budget:reordered', { orderedIds }, socketId);
return { success: true };
}
@Put('reorder/categories')
reorderCategories(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body('orderedCategories') orderedCategories: string[],
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
this.budget.reorderCategories(tripId, orderedCategories);
this.budget.broadcast(tripId, 'budget:reordered', { orderedCategories }, socketId);
return { success: true };
}
@Put(':id')
update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: Record<string, unknown>,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const updated = this.budget.update(id, tripId, body);
if (!updated) {
throw new HttpException({ error: 'Budget item not found' }, 404);
}
if (updated.reservation_id && body.total_price !== undefined) {
this.budget.syncReservationPrice(tripId, updated.reservation_id, updated.total_price, socketId);
}
this.budget.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
return { item: updated };
}
@Put(':id/members')
updateMembers(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body('user_ids') userIds: unknown,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (!Array.isArray(userIds)) {
throw new HttpException({ error: 'user_ids must be an array' }, 400);
}
const result = this.budget.updateMembers(id, tripId, userIds);
if (!result) {
throw new HttpException({ error: 'Budget item not found' }, 404);
}
this.budget.broadcast(tripId, 'budget:members-updated', { itemId: Number(id), members: result.members, persons: result.item.persons }, socketId);
return { members: result.members, item: result.item };
}
@Put(':id/members/:userId/paid')
toggleMemberPaid(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Param('userId') userId: string,
@Body('paid') paid: boolean,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const member = this.budget.toggleMemberPaid(id, userId, paid);
this.budget.broadcast(tripId, 'budget:member-paid-updated', { itemId: Number(id), userId: Number(userId), paid: paid ? 1 : 0 }, socketId);
return { member };
}
@Delete(':id')
remove(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (!this.budget.remove(id, tripId)) {
throw new HttpException({ error: 'Budget item not found' }, 404);
}
this.budget.broadcast(tripId, 'budget:deleted', { itemId: Number(id) }, socketId);
return { success: true };
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { BudgetController } from './budget.controller';
import { BudgetService } from './budget.service';
/** Budget domain (S4 — Phase 2 trip sub-domain). Registered in AppModule. */
@Module({
controllers: [BudgetController],
providers: [BudgetService],
})
export class BudgetModule {}
+89
View File
@@ -0,0 +1,89 @@
import { Injectable } from '@nestjs/common';
import { db } from '../../db/database';
import { broadcast } from '../../websocket';
import { checkPermission } from '../../services/permissions';
import type { User } from '../../types';
import * as svc from '../../services/budgetService';
type Trip = NonNullable<ReturnType<typeof svc.verifyTripAccess>>;
/**
* Thin Nest wrapper around the existing budget service. Trip-access, the
* 'budget_edit' permission, the SQL, settlement maths and the WebSocket
* broadcasts all reuse the legacy code unchanged.
*/
@Injectable()
export class BudgetService {
verifyTripAccess(tripId: string, userId: number) {
return svc.verifyTripAccess(tripId, userId);
}
canEdit(trip: Trip, user: User): boolean {
return checkPermission('budget_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id);
}
broadcast(tripId: string, event: string, payload: Record<string, unknown>, socketId: string | undefined): void {
broadcast(tripId, event, payload, socketId);
}
list(tripId: string) {
return svc.listBudgetItems(tripId);
}
perPersonSummary(tripId: string) {
return svc.getPerPersonSummary(tripId);
}
settlement(tripId: string) {
return svc.calculateSettlement(tripId);
}
create(tripId: string, data: Parameters<typeof svc.createBudgetItem>[1]) {
return svc.createBudgetItem(tripId, data);
}
update(id: string, tripId: string, data: Parameters<typeof svc.updateBudgetItem>[2]) {
return svc.updateBudgetItem(id, tripId, data);
}
remove(id: string, tripId: string): boolean {
return svc.deleteBudgetItem(id, tripId);
}
updateMembers(id: string, tripId: string, userIds: number[]) {
return svc.updateMembers(id, tripId, userIds);
}
toggleMemberPaid(id: string, userId: string, paid: boolean) {
return svc.toggleMemberPaid(id, userId, paid);
}
reorderItems(tripId: string, orderedIds: number[]): void {
svc.reorderBudgetItems(tripId, orderedIds);
}
reorderCategories(tripId: string, orderedCategories: string[]): void {
svc.reorderBudgetCategories(tripId, orderedCategories);
}
/**
* Mirrors the legacy PUT /:id side effect: when a price-linked budget item's
* total_price changes, write it into the reservation's metadata and broadcast
* reservation:updated. Non-fatal — a failure here never breaks the budget update.
*/
syncReservationPrice(tripId: string, reservationId: number, totalPrice: number, socketId: string | undefined): void {
try {
const reservation = db.prepare(
'SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?',
).get(reservationId, tripId) as { id: number; metadata: string | null } | undefined;
if (!reservation) return;
const meta = reservation.metadata ? JSON.parse(reservation.metadata) : {};
meta.price = String(totalPrice);
db.prepare('UPDATE reservations SET metadata = ? WHERE id = ?').run(JSON.stringify(meta), reservation.id);
const updatedRes = db.prepare('SELECT * FROM reservations WHERE id = ?').get(reservation.id);
broadcast(tripId, 'reservation:updated', { reservation: updatedRes }, socketId);
} catch (err) {
console.error('[budget] Failed to sync price to reservation:', err);
}
}
}