Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

Move costs, reservations and accommodations onto the decorators

Maurice010242b1072c
diff --git a/server/src/nest/budget/budget.module.ts b/server/src/nest/budget/budget.module.ts
index 46c30c578..1a5fc539d 100644
--- a/server/src/nest/budget/budget.module.ts
+++ b/server/src/nest/budget/budget.module.ts
@@ -4,15 +4,18 @@ import { BudgetService } from './budget.service';
import { BudgetMcp } from './budget.mcp';
import { ExchangeRatesService } from './exchange-rates.service';
import { ExchangeRatesRpc } from './exchange-rates.rpc';
+import { CostsRpc } from './costs.rpc';
+import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
+import { RealtimeModule } from '../realtime/realtime.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { AuthModule } from '../auth/auth.module';
/** Budget domain (S4 — Phase 2 trip sub-domain). Registered in AppModule.
* BudgetMcp carries the decorator-registered MCP tools + resources. */
@Module({
- imports: [PermissionsModule, AuthModule],
+ imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [BudgetController],
- providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc],
+ providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc, CostsRpc],
// For in-container consumers (PluginHostDepsFactory, TripsService,
// ReservationsService, BookingImportService).
exports: [BudgetService, ExchangeRatesService],
diff --git a/server/src/nest/budget/costs.rpc.ts b/server/src/nest/budget/costs.rpc.ts
new file mode 100644
index 000000000..44402d233
--- /dev/null
+++ b/server/src/nest/budget/costs.rpc.ts
@@ -0,0 +1,121 @@
+import { budgetCreateItemRequestSchema, budgetUpdateItemRequestSchema } from '@trek/shared';
+import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
+import { PluginGuards } from '../plugins/host/plugin-guards.service';
+import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
+import { num } from '../plugins/host/rpc-params';
+import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
+import { RealtimeService } from '../realtime/realtime.service';
+import { DatabaseService } from '../database/database.service';
+import { listTripsForUser } from '../trips/trips.bridge';
+import { ADDON_IDS } from '../../addons';
+import { BudgetService } from './budget.service';
+
+/** Costs are budget items, and the app edits them under 'budget_edit'. */
+const BUDGET_EDIT_ACTION = 'budget_edit';
+
+/**
+ * The cost surface a plugin may reach (#plugins). "Costs" are budget items, so every
+ * method additionally requires the Costs addon to be enabled, matching the app, where
+ * a disabled addon means there is simply nothing to read or write.
+ *
+ * Note where the addon check sits in each method. costs.getByTrip runs it INSIDE the
+ * membership callback, so a caller without trip access is told about the trip and not
+ * about the addon; costs.listMine runs it first, because there is no trip to check.
+ * The two orderings are deliberate and were preserved on the move.
+ *
+ * The writes keep their own refusal messages ("no permission to edit costs on trip N")
+ * rather than going through requireTripEdit, which says "no permission to edit trip N".
+ */
+@PluginController()
+export class CostsRpc {
+ constructor(
+ private readonly budget: BudgetService,
+ private readonly db: DatabaseService,
+ private readonly realtime: RealtimeService,
+ private readonly guards: PluginGuards,
+ ) {}
+
+ @PluginMethod('costs.getByTrip', { permission: 'db:read:costs' })
+ getByTrip(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ return this.guards.tripRead(params, ctx, () => {
+ this.requireBudgetAddon();
+ return this.budget.listBudgetItems(num(params.tripId, 'tripId'));
+ });
+ }
+
+ @PluginMethod('costs.listMine', { permission: 'db:read:costs' })
+ listMine(_params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ // Cross-trip aggregate. The acting user is host-bound; a job or onLoad is refused
+ // the same way tripRead refuses one.
+ if (ctx.actingUserId === undefined) throw new ForbiddenResource('cost reads require an authenticated user context');
+ this.requireBudgetAddon();
+ // Through the bridge, not by injection: see the note on listTripsForUser.
+ const trips = listTripsForUser(ctx.actingUserId);
+ return trips.flatMap((t) => this.budget.listBudgetItems(t.id));
+ }
+
+ @PluginMethod('costs.create', { permission: 'db:write:costs' })
+ async create(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
+ const tripId = num(params.tripId, 'tripId');
+ const actor = this.requireCostActor(ctx);
+ this.requireBudgetAddon();
+ const parsed = budgetCreateItemRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid cost: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ this.requireCostEdit(tripId, actor);
+ // BudgetService.create freezes the FX rate and resolves members/payers, so the
+ // plugin path produces the same row the web app would.
+ const item = await this.budget.create(String(tripId), parsed.data);
+ this.realtime.broadcast(tripId, 'budget:created', { item });
+ return item;
+ }
+
+ @PluginMethod('costs.update', { permission: 'db:write:costs' })
+ async update(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
+ const tripId = num(params.tripId, 'tripId');
+ const itemId = num(params.itemId, 'itemId');
+ const actor = this.requireCostActor(ctx);
+ this.requireBudgetAddon();
+ const parsed = budgetUpdateItemRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid cost: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ this.requireCostEdit(tripId, actor);
+ // update re-freezes the FX rate on a currency change, exactly like create.
+ const item = await this.budget.update(String(itemId), String(tripId), parsed.data);
+ if (item == null) throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`);
+ this.realtime.broadcast(tripId, 'budget:updated', { item });
+ return item;
+ }
+
+ @PluginMethod('costs.delete', { permission: 'db:write:costs' })
+ delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const itemId = num(params.itemId, 'itemId');
+ const actor = this.requireCostActor(ctx);
+ this.requireBudgetAddon();
+ this.requireCostEdit(tripId, actor);
+ if (!this.budget.remove(String(itemId), String(tripId))) {
+ throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`);
+ }
+ this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
+ return { deleted: true };
+ }
+
+ /** The writes say "cost writes", not the "<noun> writes" requireActor produces. */
+ private requireCostActor(ctx: PluginRpcContext): number {
+ if (ctx.actingUserId === undefined) {
+ throw new ForbiddenResource('cost writes require an authenticated user context');
+ }
+ return ctx.actingUserId;
+ }
+
+ private requireBudgetAddon(): void {
+ this.guards.requireAddon(ADDON_IDS.BUDGET, 'costs');
+ }
+
+ /** Trip access plus budget_edit, with the cost-specific refusal message. */
+ private requireCostEdit(tripId: number, userId: number): void {
+ if (!this.db.canAccessTrip(tripId, userId)) throw new ForbiddenResource(`no access to trip ${tripId}`);
+ if (!this.guards.canEditAs(BUDGET_EDIT_ACTION, tripId, userId)) {
+ throw new ForbiddenResource(`no permission to edit costs on trip ${tripId}`);
+ }
+ }
+}
diff --git a/server/src/nest/days/accommodations.rpc.ts b/server/src/nest/days/accommodations.rpc.ts
new file mode 100644
index 000000000..6f15275b2
--- /dev/null
+++ b/server/src/nest/days/accommodations.rpc.ts
@@ -0,0 +1,108 @@
+import { accommodationCreateRequestSchema, accommodationUpdateRequestSchema } from '@trek/shared';
+import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
+import { PluginGuards } from '../plugins/host/plugin-guards.service';
+import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
+import { num } from '../plugins/host/rpc-params';
+import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
+import { RealtimeService } from '../realtime/realtime.service';
+import { DaysService } from './days.service';
+
+/**
+ * Accommodations hold db:write:accommodations but are gated on 'day_edit', NOT on
+ * reservation_edit. The blocks live in the day service and the REST path guards them
+ * the same way; the decorator makes the mismatch visible instead of burying it.
+ */
+const ACCOMMODATION_EDIT_ACTION = 'day_edit';
+
+type AccommodationInput = {
+ place_id?: number | string;
+ start_day_id?: number | string;
+ end_day_id?: number | string;
+ check_in?: string | null;
+ check_in_end?: string | null;
+ check_out?: string | null;
+ confirmation?: string | null;
+ notes?: string | null;
+};
+
+/**
+ * The lodging-block surface a plugin may reach (#plugins).
+ *
+ * Everything delegates to DaysService, so the auto-created partner hotel reservation,
+ * the metadata sync on update and the delete cascade behave exactly like the
+ * accommodations REST controller, cascade broadcasts included.
+ */
+@PluginController()
+export class AccommodationsRpc {
+ constructor(
+ private readonly days: DaysService,
+ private readonly realtime: RealtimeService,
+ private readonly guards: PluginGuards,
+ ) {}
+
+ @PluginMethod('accommodations.create', { permission: 'db:write:accommodations' })
+ create(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const actor = this.guards.requireActor(ctx, 'accommodation');
+ const parsed = accommodationCreateRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid accommodation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
+ const input = parsed.data as AccommodationInput;
+ const placeId = Math.trunc(Number(input.place_id));
+ const startDayId = Math.trunc(Number(input.start_day_id));
+ const endDayId = Math.trunc(Number(input.end_day_id));
+ if (!placeId || !startDayId || !endDayId) throw new BadParams('place_id, start_day_id, and end_day_id are required');
+ // Verifies the place and both days belong to this trip.
+ const errors = this.days.validateAccommodationRefs(tripId, placeId, startDayId, endDayId);
+ if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
+ const accommodation = this.days.createAccommodation(tripId, {
+ place_id: placeId,
+ start_day_id: startDayId,
+ end_day_id: endDayId,
+ check_in: input.check_in ?? undefined,
+ check_in_end: input.check_in_end ?? undefined,
+ check_out: input.check_out ?? undefined,
+ confirmation: input.confirmation ?? undefined,
+ notes: input.notes ?? undefined,
+ });
+ this.realtime.broadcast(tripId, 'accommodation:created', { accommodation });
+ // The block creates a partner hotel reservation, so the bookings view refreshes too.
+ this.realtime.broadcast(tripId, 'reservation:created', {});
+ return accommodation;
+ }
+
+ @PluginMethod('accommodations.update', { permission: 'db:write:accommodations' })
+ update(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const accommodationId = num(params.accommodationId, 'accommodationId');
+ const actor = this.guards.requireActor(ctx, 'accommodation');
+ const parsed = accommodationUpdateRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid accommodation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
+ const existing = this.days.getAccommodation(accommodationId, tripId);
+ if (!existing) throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
+ const input = parsed.data as { place_id?: number; start_day_id?: number; end_day_id?: number; check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string };
+ const errors = this.days.validateAccommodationRefs(tripId, input.place_id, input.start_day_id, input.end_day_id);
+ if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
+ const accommodation = this.days.updateAccommodation(accommodationId, existing, input);
+ this.realtime.broadcast(tripId, 'accommodation:updated', { accommodation });
+ return accommodation;
+ }
+
+ @PluginMethod('accommodations.delete', { permission: 'db:write:accommodations' })
+ delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const accommodationId = num(params.accommodationId, 'accommodationId');
+ const actor = this.guards.requireActor(ctx, 'accommodation');
+ this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION);
+ if (!this.days.getAccommodation(accommodationId, tripId)) {
+ throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
+ }
+ // Deleting a block can take its partner reservation and budget item with it.
+ const { linkedReservationId, deletedBudgetItemId } = this.days.deleteAccommodation(accommodationId);
+ if (linkedReservationId) this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId });
+ if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId });
+ this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId });
+ return { deleted: true };
+ }
+}
diff --git a/server/src/nest/days/days.module.ts b/server/src/nest/days/days.module.ts
index aad299796..330ec9554 100644
--- a/server/src/nest/days/days.module.ts
+++ b/server/src/nest/days/days.module.ts
@@ -6,6 +6,7 @@ import { DayNotesController } from './day-notes.controller';
import { DayNotesService } from './day-notes.service';
import { DayNotesRpc } from './day-notes.rpc';
import { DaysRpc } from './days.rpc';
+import { AccommodationsRpc } from './accommodations.rpc';
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { DayNotesMcp } from './day-notes.mcp';
@@ -26,7 +27,7 @@ import { AuthModule } from '../auth/auth.module';
@Module({
imports: [PermissionsModule, QueryHelpersModule, PlacesModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [DaysController, DayNotesController],
- providers: [DaysService, DaysMcp, DayNotesService, DayNotesMcp, DayNotesRpc, DaysRpc],
+ providers: [DaysService, DaysMcp, DayNotesService, DayNotesMcp, DayNotesRpc, DaysRpc, AccommodationsRpc],
exports: [DaysService, DayNotesService],
})
export class DaysModule {}
diff --git a/server/src/nest/plugins/host/plugin-host-deps.factory.ts b/server/src/nest/plugins/host/plugin-host-deps.factory.ts
index 1596b13ee..f026e7cdf 100644
--- a/server/src/nest/plugins/host/plugin-host-deps.factory.ts
+++ b/server/src/nest/plugins/host/plugin-host-deps.factory.ts
@@ -184,16 +184,8 @@ export class PluginHostDepsFactory {
broadcastToUser: (userId, payload) => this.realtime.broadcastToUser(userId, { type: `plugin:${id}`, ...payload }),
audit: (entry) => appendAudit(this.db.connection, entry),
// --- Costs (budget items) ---
- budgetAddonEnabled: () => this.addons.isAddonEnabled(ADDON_IDS.BUDGET),
// Same gate as a REST/MCP budget mutation: the acting user must have trip
// access AND the 'budget_edit' permission for their global role.
- canEditCosts: (tripId, userId) => {
- const trip = this.db.canAccessTrip(tripId, userId);
- if (!trip) return false;
- const u = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
- if (!u) return false;
- return this.permissions.checkPermission('budget_edit', u.role ?? 'user', trip.user_id, userId, trip.user_id !== userId);
- },
// --- Read scopes (packing/files). Membership is checked by the host (tripRead);
// these just delegate to the same services the REST paths use. ---
// A file's bytes as base64, size-capped BEFORE the read so a 500MB video can't
@@ -314,38 +306,16 @@ export class PluginHostDepsFactory {
const r = this.db.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?').run(id, name);
return { cancelled: r.changes > 0 };
},
- listCostsForTrip: (tripId) => this.budget.listBudgetItems(tripId),
// Cross-trip: every accessible trip's budget items (membership predicate is
// baked into listTrips). Reuses the hydrated list so members/payers come too.
- listCostsForUser: (userId) => {
- const trips = this.trips.list(userId, null) as Array<{ id: number }>;
- return trips.flatMap((t) => this.budget.listBudgetItems(t.id));
- },
// Reuses BudgetService.create (frozen FX + members/payers), then broadcasts
// the same 'budget:created' event the controller emits so the web app updates
// live. No X-Socket-Id — a plugin has no originating socket.
- createCost: async (tripId, input) => {
- const item = await this.budget.create(String(tripId), input);
- this.realtime.broadcast(tripId, 'budget:created', { item });
- return item;
- },
// Reuses BudgetService.update (re-frozen FX on a currency change), then
// broadcasts the same 'budget:updated' event the REST controller emits. A
// missing item is a clean RESOURCE_FORBIDDEN (parity with updatePlace).
- updateCost: async (tripId, itemId, input) => {
- const item = await this.budget.update(String(itemId), String(tripId), input);
- if (item == null) throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`);
- this.realtime.broadcast(tripId, 'budget:updated', { item });
- return item;
- },
// Reuses BudgetService.remove, then broadcasts 'budget:deleted' with the
// numeric id — same payload the REST controller sends.
- deleteCost: (tripId, itemId) => {
- const deleted = this.budget.remove(String(itemId), String(tripId));
- if (!deleted) throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`);
- this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
- return { deleted: true };
- },
// --- Places (place_edit). Delegate to the same PlacesService the REST/MCP paths
// use, then broadcast the same events so open web sessions update live, and run
// the journey hooks places.controller runs on the same three writes: a journey
@@ -354,6 +324,7 @@ export class PluginHostDepsFactory {
// somebody reloads it. ---
// Consumed by the db:meta gate; the trip writes themselves have moved.
canEditTrip: (tripId, userId) => this.canEditTripAs('trip_edit', tripId, userId),
+ canEditReservations: (tripId, userId) => this.canEditTripAs('reservation_edit', tripId, userId),
canEditPlaces: (tripId, userId) => this.canEditTripAs('place_edit', tripId, userId),
// --- Days (day_edit). getDay scopes the row to the trip before any write. ---
canEditDays: (tripId, userId) => this.canEditTripAs('day_edit', tripId, userId),
@@ -373,41 +344,6 @@ export class PluginHostDepsFactory {
// --- Accommodations (lodging blocks, day_edit). Delegates to DaysService so the
// partner hotel reservation, the metadata sync and the delete cascade behave
// exactly like the accommodations REST controller, cascade broadcasts included. ---
- createAccommodation: (tripId, input) => {
- const i = input as { place_id: number | string; start_day_id: number | string; end_day_id: number | string; check_in?: string | null; check_in_end?: string | null; check_out?: string | null; confirmation?: string | null; notes?: string | null };
- const placeId = Math.trunc(Number(i.place_id));
- const startDayId = Math.trunc(Number(i.start_day_id));
- const endDayId = Math.trunc(Number(i.end_day_id));
- if (!placeId || !startDayId || !endDayId) throw new BadParams('place_id, start_day_id, and end_day_id are required');
- const errors = this.days.validateAccommodationRefs(tripId, placeId, startDayId, endDayId);
- if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
- const accommodation = this.days.createAccommodation(tripId, {
- place_id: placeId, start_day_id: startDayId, end_day_id: endDayId,
- check_in: i.check_in ?? undefined, check_in_end: i.check_in_end ?? undefined,
- check_out: i.check_out ?? undefined, confirmation: i.confirmation ?? undefined, notes: i.notes ?? undefined,
- });
- this.realtime.broadcast(tripId, 'accommodation:created', { accommodation });
- this.realtime.broadcast(tripId, 'reservation:created', {});
- return accommodation;
- },
- updateAccommodation: (tripId, accommodationId, input) => {
- const existing = this.days.getAccommodation(accommodationId, tripId);
- if (!existing) throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
- const i = input as { place_id?: number; start_day_id?: number; end_day_id?: number; check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string };
- const errors = this.days.validateAccommodationRefs(tripId, i.place_id, i.start_day_id, i.end_day_id);
- if (errors.length > 0) throw new ForbiddenResource(errors[0].message);
- const accommodation = this.days.updateAccommodation(accommodationId, existing, i);
- this.realtime.broadcast(tripId, 'accommodation:updated', { accommodation });
- return accommodation;
- },
- deleteAccommodation: (tripId, accommodationId) => {
- if (!this.days.getAccommodation(accommodationId, tripId)) throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
- const { linkedReservationId, deletedBudgetItemId } = this.days.deleteAccommodation(accommodationId);
- if (linkedReservationId) this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId });
- if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId });
- this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId });
- return { deleted: true };
- },
// --- User-scoped addon reads (the acting user's own data across all trips). Each
// reuses the same service the addon's REST/MCP path uses; the addon-enabled gate
// mirrors the app (a disabled addon has nothing to read). ---
@@ -508,37 +444,6 @@ export class PluginHostDepsFactory {
// --- Reservations (bookings, reservation_edit). Delegates to ReservationsService
// so the accommodation/budget-sync/notification/broadcast side effects match the
// web app EXACTLY. socketId is undefined — a plugin has no originating socket. ---
- canEditReservations: (tripId, userId) => this.canEditTripAs('reservation_edit', tripId, userId),
- createReservation: (tripId, input, actingUserId) => {
- const { reservation, accommodationCreated } = this.reservations.create(String(tripId), input as never);
- if (accommodationCreated) this.realtime.broadcast(tripId, 'accommodation:created', {}, undefined);
- const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
- this.reservations.syncBudgetOnCreate(String(tripId), reservation.id, i.title ?? '', i.type, i.create_budget_entry as never, undefined);
- this.realtime.broadcast(tripId, 'reservation:created', { reservation }, undefined);
- this.notifyBooking(actingUserId, tripId, i.title ?? '', i.type ?? '');
- return reservation;
- },
- updateReservation: (tripId, reservationId, input, actingUserId) => {
- const current = this.reservations.getReservation(String(reservationId), String(tripId));
- if (!current) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);
- const { reservation, accommodationChanged } = this.reservations.update(String(reservationId), String(tripId), input as never, current as never);
- if (accommodationChanged) this.realtime.broadcast(tripId, 'accommodation:updated', {}, undefined);
- const cur = current as { title: string; type?: string };
- const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
- this.reservations.syncBudgetOnUpdate(String(tripId), String(reservationId), i.title ?? '', i.type, cur.title, cur.type, i.create_budget_entry as never, undefined);
- this.realtime.broadcast(tripId, 'reservation:updated', { reservation }, undefined);
- this.notifyBooking(actingUserId, tripId, i.title || cur.title, i.type || cur.type || '');
- return reservation;
- },
- deleteReservation: (tripId, reservationId, actingUserId) => {
- const { deleted, accommodationDeleted, deletedBudgetItemId } = this.reservations.remove(String(reservationId), String(tripId));
- if (!deleted) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);
- if (accommodationDeleted) this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id }, undefined);
- if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, undefined);
- this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId: Number(reservationId) }, undefined);
- this.notifyBooking(actingUserId, tripId, deleted.title, deleted.type || '');
- return { deleted: true };
- },
// --- Plugin metadata (db:meta). A per-plugin namespaced key/value store keyed
// to a core entity; the plugin only ever sees rows tagged with its own id. ---
metaEntityTrip: (entityType, entityId) => {
diff --git a/server/src/nest/plugins/host/rpc-host.ts b/server/src/nest/plugins/host/rpc-host.ts
index 5303f121e..f371d30b6 100644
--- a/server/src/nest/plugins/host/rpc-host.ts
+++ b/server/src/nest/plugins/host/rpc-host.ts
@@ -87,9 +87,7 @@ export interface HostDeps {
/** Publish an event from this host's plugin to its subscribed dependents. */
emitPluginEvent(event: string, payload: unknown): void;
/** True when the Costs (budget) addon is enabled — gates all costs.* methods. */
- budgetAddonEnabled(): boolean;
/** True if the acting user may create costs on the trip (the 'budget_edit' permission). */
- canEditCosts(tripId: number, userId: number): boolean;
/** A trip's packing items visible to `userId` (#858 private-item filter), for `packing.list`. */
/** A trip's files (trash excluded), for `files.list`. */
/** One trip file's bytes as base64 (size-capped), for `files.getContent`. Throws if it's not on the trip or exceeds the cap. */
@@ -152,18 +150,15 @@ export interface HostDeps {
/** Update a day note (scoped to the day+trip); broadcasts dayNote:updated. */
/** Delete a day note (scoped to the day+trip); broadcasts dayNote:deleted. */
/** All budget items of one trip, hydrated with members/payers. */
- listCostsForTrip(tripId: number): unknown[];
/** All budget items across every trip the acting user can access. */
- listCostsForUser(userId: number): unknown[];
/** Create a budget item on a trip (and broadcast); returns the created item. */
- createCost(tripId: number, input: BudgetCreateItemRequest): unknown;
/** Update a budget item on a trip (and broadcast); returns the updated item. */
- updateCost(tripId: number, itemId: number, input: BudgetUpdateItemRequest): unknown;
/** Delete a budget item from a trip (and broadcast); returns { deleted: true }. */
- deleteCost(tripId: number, itemId: number): unknown;
// --- Places (the 'place_edit' permission) ---
/** Still needed by the db:meta gate, which has not moved yet. */
canEditTrip(tripId: number, userId: number): boolean;
+ /** Also still needed by the db:meta gate. */
+ canEditReservations(tripId: number, userId: number): boolean;
canEditPlaces(tripId: number, userId: number): boolean;
// --- Days + itinerary (the 'day_edit' permission) ---
canEditDays(tripId: number, userId: number): boolean;
@@ -180,19 +175,12 @@ export interface HostDeps {
/** A trip's lodging blocks (day_accommodations) with the joined place fields. */
// --- Accommodations write (the 'day_edit' permission, like the accommodations REST path) ---
/** Create a lodging block (auto-creates its partner hotel reservation + broadcasts); returns it. */
- createAccommodation(tripId: number, input: Record<string, unknown>): unknown;
/** Update a lodging block (syncs the partner reservation); throws if it isn't on the trip. */
- updateAccommodation(tripId: number, accommodationId: number, input: Record<string, unknown>): unknown;
/** Delete a lodging block (cascades the partner reservation/budget row); returns { deleted: true }. */
- deleteAccommodation(tripId: number, accommodationId: number): unknown;
// --- Reservations (the 'reservation_edit' permission) ---
- canEditReservations(tripId: number, userId: number): boolean;
/** Create a reservation (accommodation/budget side effects + broadcasts, as the web app); returns it. */
- createReservation(tripId: number, input: Record<string, unknown>, actingUserId: number): unknown;
/** Update a reservation on a trip (same side effects); returns it, or throws if it isn't on the trip. */
- updateReservation(tripId: number, reservationId: number, input: Record<string, unknown>, actingUserId: number): unknown;
/** Delete a reservation from a trip (same side effects); returns { deleted: true }. */
- deleteReservation(tripId: number, reservationId: number, actingUserId: number): unknown;
// --- Packing (the 'packing_edit' permission; #858 privacy-scoped broadcasts) ---
/** Create a packing item (owner = acting user); privacy-scoped packing:created broadcast; returns it. */
/** Update a packing item; four-case public<->private broadcast; throws if not on the trip. */
@@ -427,65 +415,8 @@ export class PluginRpcHost {
this.methods.set('journal.deleteJourney', (p, uid) => deps.deleteJournal(requireUid(uid), num(p.journeyId, 'journeyId')));
}
- if (has('db:read:costs')) {
- // "Costs" = budget items (trip-scoped). Same membership gate as trip reads;
- // additionally requires the Costs addon to be enabled (parity with the app,
- // where a disabled addon means there is nothing to read).
- this.methods.set('costs.getByTrip', (p, uid) =>
- this.tripRead(p, uid, () => {
- this.requireBudgetAddon();
- return deps.listCostsForTrip(num(p.tripId, 'tripId'));
- }),
- );
- // Cross-trip aggregate: every cost the acting user can access. The acting
- // user is host-bound; a job/onLoad (no user) is refused, same as tripRead.
- this.methods.set('costs.listMine', (p, uid) => {
- if (uid === undefined) throw new ForbiddenResource('cost reads require an authenticated user context');
- this.requireBudgetAddon();
- return deps.listCostsForUser(uid);
- });
- }
+ // costs.* now lives in src/nest/budget/costs.rpc.ts.
- if (has('db:write:costs')) {
- // The first plugin path that MUTATES core data. Gate it exactly like a
- // normal web-app/MCP budget write: addon enabled + trip access + the
- // 'budget_edit' permission for the host-bound acting user.
- this.methods.set('costs.create', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- if (uid === undefined) throw new ForbiddenResource('cost writes require an authenticated user context');
- this.requireBudgetAddon();
- const parsed = budgetCreateItemRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid cost: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
- if (!this.deps.canEditCosts(tripId, uid)) throw new ForbiddenResource(`no permission to edit costs on trip ${tripId}`);
- return deps.createCost(tripId, parsed.data);
- });
- // Same gate as costs.create — addon + trip access + the acting user's
- // 'budget_edit' permission — plus the item id. updateCost re-freezes the FX
- // rate through BudgetService.update exactly like the create path.
- this.methods.set('costs.update', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const itemId = num(p.itemId, 'itemId');
- if (uid === undefined) throw new ForbiddenResource('cost writes require an authenticated user context');
- this.requireBudgetAddon();
- const parsed = budgetUpdateItemRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid cost: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
- if (!this.deps.canEditCosts(tripId, uid)) throw new ForbiddenResource(`no permission to edit costs on trip ${tripId}`);
- return deps.updateCost(tripId, itemId, parsed.data);
- });
- // Deleting a cost is a budget write too: gated by db:write:costs and, per the
- // app, the acting user's 'budget_edit' permission on the trip.
- this.methods.set('costs.delete', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const itemId = num(p.itemId, 'itemId');
- if (uid === undefined) throw new ForbiddenResource('cost writes require an authenticated user context');
- this.requireBudgetAddon();
- if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
- if (!this.deps.canEditCosts(tripId, uid)) throw new ForbiddenResource(`no permission to edit costs on trip ${tripId}`);
- return deps.deleteCost(tripId, itemId);
- });
- }
// --- Core planner writes (#1429). Each mirrors costs.create: validate the
// input against the SAME @trek/shared schema the web app uses, then gate on
@@ -504,70 +435,9 @@ export class PluginRpcHost {
// daynotes.* now live in src/nest/days/day-notes.rpc.ts.
- if (has('db:write:reservations')) {
- // Bookings write. Gated exactly like the reservations REST/MCP path: trip
- // access + the 'reservation_edit' permission for the HOST-bound acting user.
- // The delegating deps reuse the real ReservationsService so the accommodation,
- // budget-sync, notification and broadcast side effects match the web app 1:1.
- this.methods.set('reservations.create', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const actor = this.requireActor(uid, 'reservation');
- const parsed = reservationCreateRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid reservation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- requireValidEndpoints((parsed.data as Record<string, unknown>).endpoints);
- this.requireTripEdit(tripId, actor, deps.canEditReservations);
- return deps.createReservation(tripId, parsed.data as Record<string, unknown>, actor);
- });
- this.methods.set('reservations.update', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const reservationId = num(p.reservationId, 'reservationId');
- const actor = this.requireActor(uid, 'reservation');
- const parsed = reservationUpdateRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid reservation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- requireValidEndpoints((parsed.data as Record<string, unknown>).endpoints);
- this.requireTripEdit(tripId, actor, deps.canEditReservations);
- return deps.updateReservation(tripId, reservationId, parsed.data as Record<string, unknown>, actor);
- });
- this.methods.set('reservations.delete', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const reservationId = num(p.reservationId, 'reservationId');
- const actor = this.requireActor(uid, 'reservation');
- this.requireTripEdit(tripId, actor, deps.canEditReservations);
- return deps.deleteReservation(tripId, reservationId, actor);
- });
- }
+ // reservations.* now lives in src/nest/reservations/reservations.rpc.ts.
- if (has('db:write:accommodations')) {
- // Lodging blocks (day_accommodations). Gated exactly like the accommodations
- // REST path: trip access + the 'day_edit' permission — NOT reservation_edit;
- // the blocks live in the day service and REST guards them the same way. The
- // wiring reuses dayService, so the auto-created partner hotel reservation,
- // the metadata sync on update and the cascade broadcasts match the web app.
- this.methods.set('accommodations.create', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const actor = this.requireActor(uid, 'accommodation');
- const parsed = accommodationCreateRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid accommodation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- this.requireTripEdit(tripId, actor, deps.canEditDays);
- return deps.createAccommodation(tripId, parsed.data as Record<string, unknown>);
- });
- this.methods.set('accommodations.update', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const accommodationId = num(p.accommodationId, 'accommodationId');
- const actor = this.requireActor(uid, 'accommodation');
- const parsed = accommodationUpdateRequestSchema.safeParse(p.input);
- if (!parsed.success) throw new BadParams(`invalid accommodation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
- this.requireTripEdit(tripId, actor, deps.canEditDays);
- return deps.updateAccommodation(tripId, accommodationId, parsed.data as Record<string, unknown>);
- });
- this.methods.set('accommodations.delete', (p, uid) => {
- const tripId = num(p.tripId, 'tripId');
- const accommodationId = num(p.accommodationId, 'accommodationId');
- const actor = this.requireActor(uid, 'accommodation');
- this.requireTripEdit(tripId, actor, deps.canEditDays);
- return deps.deleteAccommodation(tripId, accommodationId);
- });
- }
+ // accommodations.* now lives in src/nest/days/accommodations.rpc.ts.
// packing.* now lives in src/nest/packing/packing.rpc.ts.
@@ -763,13 +633,6 @@ export class PluginRpcHost {
return read(actingUserId);
}
- /** Refuse costs.* calls when the Costs (budget) addon is disabled. */
- private requireBudgetAddon(): void {
- if (!this.deps.budgetAddonEnabled()) {
- throw new ForbiddenResource('the costs addon is disabled');
- }
- }
-
/**
* Every write needs a HOST-bound acting user. A job / onLoad (no user) or a call
* with a forged/unknown invocation id resolves to undefined and is refused — a
diff --git a/server/src/nest/reservations/reservations.module.ts b/server/src/nest/reservations/reservations.module.ts
index 748327ee6..79a6e5d53 100644
--- a/server/src/nest/reservations/reservations.module.ts
+++ b/server/src/nest/reservations/reservations.module.ts
@@ -4,6 +4,9 @@ import { DaysModule } from '../days/days.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { ReservationsController } from './reservations.controller';
import { ReservationsService } from './reservations.service';
+import { ReservationsRpc } from './reservations.rpc';
+import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
+import { RealtimeModule } from '../realtime/realtime.module';
import { ReservationsMcp } from './reservations.mcp';
import { AccommodationsController } from './accommodations.controller';
import { AccommodationsService } from './accommodations.service';
@@ -19,9 +22,9 @@ import { AuthModule } from '../auth/auth.module';
@Module({
// DaysModule: AccommodationsService + ReservationsMcp inject DaysService.
// BudgetModule: ReservationsService + ReservationsMcp inject BudgetService (budget-sync seam).
- imports: [DaysModule, PermissionsModule, BudgetModule, AuthModule],
+ imports: [DaysModule, PermissionsModule, BudgetModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [ReservationsController, AccommodationsController, UpcomingReservationsController],
- providers: [ReservationsService, AccommodationsService, ReservationsMcp],
+ providers: [ReservationsService, AccommodationsService, ReservationsMcp, ReservationsRpc],
// For in-container consumers (PluginHostDepsFactory, TripsService, BookingImportService).
exports: [ReservationsService],
})
diff --git a/server/src/nest/reservations/reservations.rpc.ts b/server/src/nest/reservations/reservations.rpc.ts
new file mode 100644
index 000000000..af62326d0
--- /dev/null
+++ b/server/src/nest/reservations/reservations.rpc.ts
@@ -0,0 +1,104 @@
+import {
+ reservationCreateRequestSchema,
+ reservationEndpointsInputSchema,
+ reservationUpdateRequestSchema,
+} from '@trek/shared';
+import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
+import { PluginGuards } from '../plugins/host/plugin-guards.service';
+import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
+import { num } from '../plugins/host/rpc-params';
+import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
+import { RealtimeService } from '../realtime/realtime.service';
+import { ReservationsService } from './reservations.service';
+
+const RESERVATION_EDIT_ACTION = 'reservation_edit';
+
+/**
+ * The reservation surface a plugin may reach (#plugins).
+ *
+ * Everything delegates to ReservationsService, so the accommodation side effects, the
+ * budget sync, the booking notification and the broadcasts match the web app one for
+ * one. A booking write is rarely just one row: creating one can create an
+ * accommodation and a budget item, and deleting one can remove both again.
+ */
+@PluginController()
+export class ReservationsRpc {
+ constructor(
+ private readonly reservations: ReservationsService,
+ private readonly realtime: RealtimeService,
+ private readonly guards: PluginGuards,
+ ) {}
+
+ @PluginMethod('reservations.create', { permission: 'db:write:reservations' })
+ create(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const actor = this.guards.requireActor(ctx, 'reservation');
+ const parsed = reservationCreateRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid reservation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ const input = parsed.data as Record<string, unknown>;
+ this.requireValidEndpoints(input.endpoints);
+ this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);
+ const { reservation, accommodationCreated } = this.reservations.create(String(tripId), input as never);
+ if (accommodationCreated) this.realtime.broadcast(tripId, 'accommodation:created', {}, undefined);
+ const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
+ this.reservations.syncBudgetOnCreate(String(tripId), reservation.id, i.title ?? '', i.type, i.create_budget_entry as never, undefined);
+ this.realtime.broadcast(tripId, 'reservation:created', { reservation }, undefined);
+ this.notifyBooking(actor, tripId, i.title ?? '', i.type ?? '');
+ return reservation;
+ }
+
+ @PluginMethod('reservations.update', { permission: 'db:write:reservations' })
+ update(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const reservationId = num(params.reservationId, 'reservationId');
+ const actor = this.guards.requireActor(ctx, 'reservation');
+ const parsed = reservationUpdateRequestSchema.safeParse(params.input);
+ if (!parsed.success) throw new BadParams(`invalid reservation: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ const input = parsed.data as Record<string, unknown>;
+ this.requireValidEndpoints(input.endpoints);
+ this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);
+ const current = this.reservations.getReservation(String(reservationId), String(tripId));
+ if (!current) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);
+ const { reservation, accommodationChanged } = this.reservations.update(String(reservationId), String(tripId), input as never, current as never);
+ if (accommodationChanged) this.realtime.broadcast(tripId, 'accommodation:updated', {}, undefined);
+ const cur = current as { title: string; type?: string };
+ const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
+ this.reservations.syncBudgetOnUpdate(String(tripId), String(reservationId), i.title ?? '', i.type, cur.title, cur.type, i.create_budget_entry as never, undefined);
+ this.realtime.broadcast(tripId, 'reservation:updated', { reservation }, undefined);
+ this.notifyBooking(actor, tripId, i.title || cur.title, i.type || cur.type || '');
+ return reservation;
+ }
+
+ @PluginMethod('reservations.delete', { permission: 'db:write:reservations' })
+ delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
+ const tripId = num(params.tripId, 'tripId');
+ const reservationId = num(params.reservationId, 'reservationId');
+ const actor = this.guards.requireActor(ctx, 'reservation');
+ this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);
+ const { deleted, accommodationDeleted, deletedBudgetItemId } = this.reservations.remove(String(reservationId), String(tripId));
+ if (!deleted) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);
+ if (accommodationDeleted) this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id }, undefined);
+ if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, undefined);
+ this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId }, undefined);
+ this.notifyBooking(actor, tripId, deleted.title, deleted.type || '');
+ return { deleted: true };
+ }
+
+ /**
+ * The reservation body is passthrough by contract, but a malformed `endpoints`
+ * array would otherwise fail deep in the service (NOT NULL mid-transaction) or be
+ * dropped silently on missing coordinates. Both are miserable to debug from a
+ * plugin, so the shape is pinned up front. Absent stays absent: omitted means keep,
+ * [] means delete all.
+ */
+ private requireValidEndpoints(value: unknown): void {
+ if (value === undefined) return;
+ const parsed = reservationEndpointsInputSchema.safeParse(value);
+ if (!parsed.success) throw new BadParams(`invalid endpoints: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
+ }
+
+ /** Fire-and-forget, exactly as the REST controller sends it, so it never blocks the write. */
+ private notifyBooking(actingUserId: number, tripId: number, booking: string, type: string): void {
+ this.reservations.notifyBookingChange(tripId, actingUserId, booking, type);
+ }
+}
diff --git a/server/src/nest/trips/trips.bridge.ts b/server/src/nest/trips/trips.bridge.ts
index fdbb32bd4..18dfba6f3 100644
--- a/server/src/nest/trips/trips.bridge.ts
+++ b/server/src/nest/trips/trips.bridge.ts
@@ -71,3 +71,13 @@ export function listMembers(tripId: string | number, tripOwnerId: number) {
export function getTripSummary(tripId: number, viewerUserId?: number) {
return trips.getTripSummary(tripId, viewerUserId);
}
+
+/**
+ * Every trip the user can access. Used by CostsRpc for the cross-trip cost feed:
+ * BudgetModule cannot import TripsModule, because TripsModule already imports
+ * BudgetModule, and injecting it would need a forwardRef'd cycle. Same reason
+ * budget.mcp.ts reaches for this file.
+ */
+export function listTripsForUser(userId: number) {
+ return trips.list(userId, null) as Array<{ id: number }>;
+}
diff --git a/server/tests/helpers/rpc-host-deps.ts b/server/tests/helpers/rpc-host-deps.ts
index 33aab7fad..426c82ab9 100644
--- a/server/tests/helpers/rpc-host-deps.ts
+++ b/server/tests/helpers/rpc-host-deps.ts
@@ -12,6 +12,9 @@ import { PlacesRpc } from '../../src/nest/places/places.rpc';
import { DaysRpc } from '../../src/nest/days/days.rpc';
import { ItineraryRpc } from '../../src/nest/assignments/itinerary.rpc';
import { TripsRpc } from '../../src/nest/trips/trips.rpc';
+import { CostsRpc } from '../../src/nest/budget/costs.rpc';
+import { ReservationsRpc } from '../../src/nest/reservations/reservations.rpc';
+import { AccommodationsRpc } from '../../src/nest/days/accommodations.rpc';
/**
* The stubbed HostDeps every plugin router test builds on. It used to live inside
@@ -198,5 +201,8 @@ export function allRpcControllers(): object[] {
new DaysRpc(anyService(), anyService(), anyService()),
new ItineraryRpc(anyService(), anyService(), anyService()),
new TripsRpc(anyService(), anyService(), anyService(), anyService(), anyService(), anyService(), anyService()),
+ new CostsRpc(anyService(), anyService(), anyService(), anyService()),
+ new ReservationsRpc(anyService(), anyService(), anyService()),
+ new AccommodationsRpc(anyService(), anyService(), anyService()),
];
}
diff --git a/server/tests/unit/budget/costs.rpc.test.ts b/server/tests/unit/budget/costs.rpc.test.ts
new file mode 100644
index 000000000..3c88be986
--- /dev/null
+++ b/server/tests/unit/budget/costs.rpc.test.ts
@@ -0,0 +1,151 @@
+/**
+ * The cost plugin surface after it moved onto @PluginMethod. This is the first
+ * addon-gated domain, and the addon check sits in a different place in each of the
+ * two reads: inside the membership callback for costs.getByTrip, before everything
+ * for costs.listMine. Both orderings are asserted, because swapping them changes
+ * which refusal a caller sees.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
+import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
+import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
+import { CostsRpc } from '../../../src/nest/budget/costs.rpc';
+import { BudgetModule } from '../../../src/nest/budget/budget.module';
+import type { BudgetService } from '../../../src/nest/budget/budget.service';
+import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
+import type { DatabaseService } from '../../../src/nest/database/database.service';
+import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
+import type { AddonsService } from '../../../src/nest/addons/addons.service';
+import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
+import { makeDeps } from '../../helpers/rpc-host-deps';
+
+vi.mock('../../../src/nest/trips/trips.bridge', () => ({
+ listTripsForUser: vi.fn(() => [{ id: 1 }, { id: 2 }]),
+}));
+
+const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
+
+/** Trip 1 belongs to user 42, cost 5 sits on it, and the addon is on unless said otherwise. */
+function build(opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean } = {}) {
+ const budget = {
+ listBudgetItems: vi.fn((tripId: number) => [{ id: 5, trip_id: tripId }]),
+ create: vi.fn(async (tripId: string, i: Record<string, unknown>) => ({ id: 9, trip_id: tripId, ...i })),
+ update: vi.fn(async () => (opts.missing ? null : { id: 5, name: 'Hotel' })),
+ remove: vi.fn(() => !opts.missing),
+ } as unknown as BudgetService & Record<string, ReturnType<typeof vi.fn>>;
+ const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
+ const db = {
+ canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
+ prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
+ } as unknown as DatabaseService;
+ const guards = new PluginGuards(
+ db,
+ { checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
+ { isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService,
+ );
+ const rpc = new CostsRpc(budget, db, realtime, guards);
+ const host = (...grants: string[]) =>
+ new PluginRpcHost('p', new Set(grants.length ? grants : ['db:read:costs', 'db:write:costs']), makeDeps(), createTestPluginRegistry([rpc]));
+ return { budget, realtime, host };
+}
+
+describe('CostsRpc reads', () => {
+ it('COSTS-RPC-001 getByTrip is membership-checked and addon-gated', async () => {
+ const f = build();
+ expect((await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)).ok).toBe(true);
+ expect(((await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
+ });
+
+ it('COSTS-RPC-002 getByTrip reports the TRIP first when both would fail', async () => {
+ // The addon check runs inside the membership callback, so a caller without trip
+ // access never learns whether the addon is on. Reversing the two would leak that.
+ const f = build({ addonOn: false });
+ const res = (await f.host().dispatch(req('costs.getByTrip', { tripId: 2 }), 42)) as RpcError;
+ expect(res.error.message).toBe('no access to trip 2');
+ });
+
+ it('COSTS-RPC-003 getByTrip reports the addon once the trip checks out', async () => {
+ const f = build({ addonOn: false });
+ const res = (await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)) as RpcError;
+ expect(res.error.message).toBe('the costs addon is disabled');
+ expect(f.budget.listBudgetItems).not.toHaveBeenCalled();
+ });
+
+ it('COSTS-RPC-004 listMine checks the user first, then the addon', async () => {
+ const f = build({ addonOn: false });
+ // No trip to check here, so the userless refusal comes first and the addon second.
+ expect(((await f.host().dispatch(req('costs.listMine'), undefined)) as RpcError).error.message)
+ .toBe('cost reads require an authenticated user context');
+ expect(((await f.host().dispatch(req('costs.listMine'), 42)) as RpcError).error.message)
+ .toBe('the costs addon is disabled');
+ });
+
+ it('COSTS-RPC-005 listMine aggregates across every accessible trip', async () => {
+ const f = build();
+ const res = await f.host().dispatch(req('costs.listMine'), 42);
+ expect(res.ok).toBe(true);
+ expect(f.budget.listBudgetItems).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('CostsRpc writes', () => {
+ it('COSTS-RPC-006 every write needs the addon, trip access and budget_edit', async () => {
+ const f = build();
+ expect((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42)).ok).toBe(true);
+ const off = build({ addonOn: false });
+ expect(((await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
+ .toBe('the costs addon is disabled');
+ const noEdit = build({ canEdit: false });
+ expect(((await noEdit.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.message)
+ .toBe('no permission to edit costs on trip 1');
+ });
+
+ it('COSTS-RPC-007 the refusal says "costs on trip", not the generic trip message', async () => {
+ // requireTripEdit would say "no permission to edit trip 1"; shipped plugins read
+ // these strings, so the cost-specific wording is kept.
+ const f = build({ canEdit: false });
+ for (const [method, params] of [
+ ['costs.create', { tripId: 1, input: { name: 'x', price: 1 } }],
+ ['costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }],
+ ['costs.delete', { tripId: 1, itemId: 5 }],
+ ] as const) {
+ expect(((await f.host().dispatch(req(method, params), 42)) as RpcError).error.message)
+ .toBe('no permission to edit costs on trip 1');
+ }
+ });
+
+ it('COSTS-RPC-008 a userless write says "cost writes"', async () => {
+ const f = build();
+ expect(((await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), undefined)) as RpcError).error.message)
+ .toBe('cost writes require an authenticated user context');
+ });
+
+ it('COSTS-RPC-009 db:read:costs does not unlock a write', async () => {
+ const f = build();
+ expect(((await f.host('db:read:costs').dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42)) as RpcError).error.code)
+ .toBe('PERMISSION_DENIED');
+ });
+
+ it('COSTS-RPC-010 a missing item is RESOURCE_FORBIDDEN, naming it', async () => {
+ const f = build({ missing: true });
+ expect(((await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 404, input: { name: 'x' } }), 42)) as RpcError).error.message)
+ .toBe('no cost 404 on trip 1');
+ expect(((await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 404 }), 42)) as RpcError).error.message)
+ .toBe('no cost 404 on trip 1');
+ });
+
+ it('COSTS-RPC-011 each write broadcasts its event, a refused one broadcasts nothing', async () => {
+ const f = build();
+ await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 10 } }), 42);
+ await f.host().dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'x' } }), 42);
+ await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
+ expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['budget:created', 'budget:updated', 'budget:deleted']);
+ const off = build({ addonOn: false });
+ await off.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'x', price: 1 } }), 42);
+ expect(off.realtime.broadcast).not.toHaveBeenCalled();
+ });
+
+ it('COSTS-RPC-012 the class is listed in its module providers', () => {
+ expect(Reflect.getMetadata('providers', BudgetModule) as unknown[]).toContain(CostsRpc);
+ });
+});
diff --git a/server/tests/unit/plugins/plugin-host-deps.factory.test.ts b/server/tests/unit/plugins/plugin-host-deps.factory.test.ts
index 32c6128b9..7a4b11e1f 100644
--- a/server/tests/unit/plugins/plugin-host-deps.factory.test.ts
+++ b/server/tests/unit/plugins/plugin-host-deps.factory.test.ts
@@ -465,38 +465,8 @@ describe('host-deps factory — planner write + metadata deps', () => {
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 2, key: 'k', value: 1 })).error.code).toBe('RESOURCE_FORBIDDEN');
});
- it('costs deps: create + reads wired through the budget service and addon gate', async () => {
- const h = host('db:read:costs', 'db:write:costs');
- expect((await call(h, 'costs.create', { tripId: 1, input: { name: 'Hotel' } })).ok).toBe(true);
- expect(broadcast).toHaveBeenCalledWith(1, 'budget:created', expect.anything());
- expect((await call(h, 'costs.getByTrip', { tripId: 1 })).ok).toBe(true);
- expect((await call(h, 'costs.listMine', {})).ok).toBe(true);
- });
-
- it('costs deps: update wired through BudgetService.update + broadcasts budget:updated', async () => {
- const h = host('db:write:costs');
- expect((await call(h, 'costs.update', { tripId: 1, itemId: 9, input: { name: 'Hostel' } })).ok).toBe(true);
- expect(broadcast).toHaveBeenCalledWith(1, 'budget:updated', expect.anything());
- });
-
- it('costs deps: update of a missing item is RESOURCE_FORBIDDEN', async () => {
- const h = host('db:write:costs');
- expect((await call(h, 'costs.update', { tripId: 1, itemId: 404, input: { name: 'X' } })).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
- it('costs deps: delete wired through BudgetService.remove + broadcasts budget:deleted', async () => {
- const h = host('db:write:costs');
- const res = await call(h, 'costs.delete', { tripId: 1, itemId: 9 });
- expect(res.ok).toBe(true);
- expect(res.result).toMatchObject({ deleted: true });
- expect(broadcast).toHaveBeenCalledWith(1, 'budget:deleted', { itemId: 9 });
- });
-
- it('costs deps: delete of a missing item is RESOURCE_FORBIDDEN', async () => {
- const h = host('db:write:costs');
- expect((await call(h, 'costs.delete', { tripId: 1, itemId: 404 })).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
+ // costs, reservations and accommodations left this factory with the decorator
+ // migration; the cases now run in tests/unit/budget/ and tests/unit/reservations/.
it('users.getById is scoped to people the acting user shares a trip with', async () => {
const h = host('db:read:users');
expect((await call(h, 'users.getById', { id: 6 }, 5)).ok).toBe(true); // 5 (owner) + 6 (member) share trip 1
@@ -515,47 +485,9 @@ describe('host-deps factory — reservations, day notes, cross-trip + addon read
});
afterAll(() => closePluginDataDb('w15'));
- it('reservations create/update/delete run the real side-effect wiring; a missing one is refused', async () => {
- const h = host('db:write:reservations');
- expect((await call(h, 'reservations.create', { tripId: 1, input: { title: 'Flight' } })).ok).toBe(true);
- // title 'Stay' drives the accommodationCreated branch of the wiring
- expect((await call(h, 'reservations.create', { tripId: 1, input: { title: 'Stay' } })).ok).toBe(true);
- expect(broadcast).toHaveBeenCalledWith(1, 'reservation:created', expect.anything(), undefined);
- expect((await call(h, 'reservations.update', { tripId: 1, reservationId: 40, input: { title: 'New' } })).ok).toBe(true);
- expect((await call(h, 'reservations.update', { tripId: 1, reservationId: 404, input: { title: 'X' } })).error.code).toBe('RESOURCE_FORBIDDEN');
- expect((await call(h, 'reservations.delete', { tripId: 1, reservationId: 40 })).ok).toBe(true);
- expect((await call(h, 'reservations.delete', { tripId: 1, reservationId: 404 })).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
// daynotes.* left this factory with the decorator migration; the cases now run in
// tests/unit/days/day-notes.rpc.test.ts against DayNotesRpc.
- it('accommodations create validates refs, creates via DaysService and emits the cascade broadcasts', async () => {
- const h = host('db:write:accommodations');
- const good = await call(h, 'accommodations.create', { tripId: 1, input: { place_id: 7, start_day_id: 3, end_day_id: 4, check_in: '15:00' } });
- expect(good.ok).toBe(true);
- expect(broadcast).toHaveBeenCalledWith(1, 'accommodation:created', expect.anything());
- // the auto-created partner hotel reservation announces itself, like the REST path
- expect(broadcast).toHaveBeenCalledWith(1, 'reservation:created', {});
- // a place/day of another trip is refused before anything is written
- expect((await call(h, 'accommodations.create', { tripId: 1, input: { place_id: 999, start_day_id: 3, end_day_id: 4 } })).error.code).toBe('RESOURCE_FORBIDDEN');
- expect((await call(h, 'accommodations.create', { tripId: 1, input: { place_id: 7, start_day_id: 88, end_day_id: 4 } })).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
- it('accommodations update/delete scope the row to the trip; delete cascades reservation + budget broadcasts', async () => {
- const h = host('db:write:accommodations');
- expect((await call(h, 'accommodations.update', { tripId: 1, accommodationId: 60, input: { notes: 'late checkout' } })).ok).toBe(true);
- expect(broadcast).toHaveBeenCalledWith(1, 'accommodation:updated', expect.anything());
- expect((await call(h, 'accommodations.update', { tripId: 1, accommodationId: 404, input: {} })).error.code).toBe('RESOURCE_FORBIDDEN');
- const del = await call(h, 'accommodations.delete', { tripId: 1, accommodationId: 61 });
- expect(del.ok).toBe(true);
- expect(del.result).toMatchObject({ deleted: true });
- expect(broadcast).toHaveBeenCalledWith(1, 'reservation:deleted', { reservationId: 40 });
- expect(broadcast).toHaveBeenCalledWith(1, 'budget:deleted', { itemId: 9 });
- expect(broadcast).toHaveBeenCalledWith(1, 'accommodation:deleted', { accommodationId: 61 });
- expect((await call(h, 'accommodations.delete', { tripId: 1, accommodationId: 404 })).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
it('addon reads delegate, and a disabled addon is refused', async () => {
const h = host('db:read:journal', 'db:read:atlas', 'db:read:vacay', 'db:read:collections');
expect((await call(h, 'journal.listMine', {})).ok).toBe(true);
diff --git a/server/tests/unit/plugins/rpc-coverage.test.ts b/server/tests/unit/plugins/rpc-coverage.test.ts
index 2ae64f175..2de6fa4d0 100644
--- a/server/tests/unit/plugins/rpc-coverage.test.ts
+++ b/server/tests/unit/plugins/rpc-coverage.test.ts
@@ -54,13 +54,21 @@ describe('plugin RPC coverage ledger', () => {
// Update these two numbers in every rollout PR. They make the diff state the size
// of the move out loud, which is the number a reviewer wants to see.
const total = KNOWN_METHODS.length + UNCONDITIONAL_METHODS.length;
- expect(fromRegistry.size).toBe(50);
- expect(legacy.size).toBe(total - 50);
+ expect(fromRegistry.size).toBe(61);
+ expect(legacy.size).toBe(total - 61);
});
it('RPCLEDGER-006 the migrated methods are exactly the ones this PR claims', () => {
expect([...fromRegistry].sort()).toEqual([
+ 'accommodations.create',
+ 'accommodations.delete',
+ 'accommodations.update',
'categories.list',
+ 'costs.create',
+ 'costs.delete',
+ 'costs.getByTrip',
+ 'costs.listMine',
+ 'costs.update',
'daynotes.create',
'daynotes.delete',
'daynotes.list',
@@ -89,7 +97,10 @@ describe('plugin RPC coverage ledger', () => {
'places.delete',
'places.update',
'rates.get',
+ 'reservations.create',
+ 'reservations.delete',
'reservations.listMine',
+ 'reservations.update',
'tags.create',
'tags.delete',
'tags.list',
diff --git a/server/tests/unit/plugins/rpc-host.test.ts b/server/tests/unit/plugins/rpc-host.test.ts
index 98d80805d..78d0b3c67 100644
--- a/server/tests/unit/plugins/rpc-host.test.ts
+++ b/server/tests/unit/plugins/rpc-host.test.ts
@@ -117,78 +117,7 @@ describe('PluginRpcHost — capability enforcement', () => {
expect(deps.data.close).toHaveBeenCalled();
});
- it('reservations.create needs db:write:reservations + reservation_edit, membership-checked', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:reservations']), deps);
- const good = await host.dispatch(req('reservations.create', { tripId: 1, input: { title: 'Hotel Tokyo' } }), 42);
- expect(ok(good)).toBe(true);
- expect(deps.createReservation).toHaveBeenCalledWith(1, expect.objectContaining({ title: 'Hotel Tokyo' }), 42);
- // a trip the acting user cannot edit -> forbidden, and the dep is never reached
- const forbidden = await host.dispatch(req('reservations.create', { tripId: 2, input: { title: 'x' } }), 42);
- expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
- it('reservations.create refuses a job/onLoad (no acting user) and invalid input', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:reservations']), deps);
- const noUser = await host.dispatch(req('reservations.create', { tripId: 1, input: { title: 'x' } }), undefined);
- expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- const bad = await host.dispatch(req('reservations.create', { tripId: 1, input: {} }), 42);
- expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
- expect(deps.createReservation).not.toHaveBeenCalled();
- });
-
- it('reservations.delete is gated the same way (edit permission + membership)', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:reservations']), deps);
- const good = await host.dispatch(req('reservations.delete', { tripId: 1, reservationId: 40 }), 42);
- expect(ok(good)).toBe(true);
- expect(deps.deleteReservation).toHaveBeenCalledWith(1, 40, 42);
- const forbidden = await host.dispatch(req('reservations.delete', { tripId: 2, reservationId: 1 }), 42);
- expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- });
-
- it('reservations.create/update pin the endpoint STRUCTURE but stay permissive like the service', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:reservations']), deps);
- const goodEp = [{ role: 'from', name: 'HND', lat: 35.55, lng: 139.78, code: 'HND' }];
- const good = await host.dispatch(req('reservations.create', { tripId: 1, input: { title: 'Flight', endpoints: goodEp } }), 42);
- expect(ok(good)).toBe(true);
- // A structurally-wrong endpoint (bad role enum) or a non-array is refused up front.
- for (const endpoints of [[{ role: 'banana', name: 'x', lat: 1, lng: 2 }], 'nope']) {
- const bad = await host.dispatch(req('reservations.update', { tripId: 1, reservationId: 40, input: { endpoints } }), 42);
- expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
- }
- // But a coord-less endpoint is NOT rejected — it's accepted and dropped downstream,
- // exactly like the REST/importer path (no breaking change vs 3.2.1).
- const coordless = await host.dispatch(req('reservations.update', { tripId: 1, reservationId: 40, input: { endpoints: [{ role: 'to', name: 'x' }] } }), 42);
- expect(ok(coordless)).toBe(true);
- // [] is the documented delete-all and stays valid
- const clear = await host.dispatch(req('reservations.update', { tripId: 1, reservationId: 40, input: { endpoints: [] } }), 42);
- expect(ok(clear)).toBe(true);
- });
-
- it('accommodations.* need db:write:accommodations + day_edit, membership-checked', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:accommodations']), deps);
- const input = { place_id: 7, start_day_id: 3, end_day_id: 4 };
- const good = await host.dispatch(req('accommodations.create', { tripId: 1, input }), 42);
- expect(ok(good)).toBe(true);
- expect(deps.createAccommodation).toHaveBeenCalledWith(1, expect.objectContaining(input));
- // gated by day_edit (accommodations live in the day service), not reservation_edit
- (deps.canEditDays as ReturnType<typeof vi.fn>).mockReturnValueOnce(false);
- const noEdit = await host.dispatch(req('accommodations.create', { tripId: 1, input }), 42);
- expect((noEdit as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- const forbidden = await host.dispatch(req('accommodations.update', { tripId: 2, accommodationId: 11, input: {} }), 42);
- expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- const noUser = await host.dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), undefined);
- expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- const bad = await host.dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 7 } }), 42);
- expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
- const del = await host.dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), 42);
- expect(ok(del)).toBe(true);
- expect(deps.deleteAccommodation).toHaveBeenCalledWith(1, 11);
- // and none of it is reachable without the grant
- const ungranted = new PluginRpcHost('p', new Set(['db:write:reservations']), deps);
- const denied = await ungranted.dispatch(req('accommodations.create', { tripId: 1, input }), 42);
- expect((denied as RpcError).error.code).toBe('PERMISSION_DENIED');
- });
-
+ // The costs, reservation and accommodation cases moved to their domain suites.
it('user-scoped addon reads (journal/atlas/vacay) need a bound user; a job is refused', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:journal', 'db:read:atlas', 'db:read:vacay']), deps);
expect(ok(await host.dispatch(req('journal.listMine'), 42))).toBe(true);
@@ -362,177 +291,6 @@ describe('PluginRpcHost — capability enforcement', () => {
// ── Costs (budget items): db:read:costs / db:write:costs ────────────────────
- it('db:read:costs reads a trip the acting user can access', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.getByTrip', { tripId: 1 }), 42);
- expect(ok(res)).toBe(true);
- expect((res as RpcResponse).result).toEqual([{ id: 5, trip_id: 1, name: 'Hotel', total_price: 100 }]);
- expect(deps.listCostsForTrip).toHaveBeenCalledWith(1);
- });
-
- it('db:read:costs is membership-checked before the read (non-member → RESOURCE_FORBIDDEN)', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.getByTrip', { tripId: 1 }), 99);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.listCostsForTrip).not.toHaveBeenCalled();
- });
-
- it('costs are RESOURCE_FORBIDDEN when the Costs addon is disabled', async () => {
- (deps.budgetAddonEnabled as ReturnType<typeof vi.fn>).mockReturnValue(false);
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.getByTrip', { tripId: 1 }), 42);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.listCostsForTrip).not.toHaveBeenCalled();
- });
-
- it('costs.listMine returns costs across every accessible trip', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.listMine', {}), 42);
- expect(ok(res)).toBe(true);
- expect((res as RpcResponse).result).toEqual([
- { id: 5, trip_id: 1, name: 'Hotel' },
- { id: 6, trip_id: 2, name: 'Food' },
- ]);
- expect(deps.listCostsForUser).toHaveBeenCalledWith(42);
- });
-
- it('costs.listMine with no bound acting user is RESOURCE_FORBIDDEN (jobs / forged calls)', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.listMine', {}), undefined);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.listCostsForUser).not.toHaveBeenCalled();
- });
-
- it('costs.getByTrip is PERMISSION_DENIED without db:read:costs', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
- const res = await host.dispatch(req('costs.getByTrip', { tripId: 1 }), 42);
- expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
- });
-
- it('db:write:costs creates a cost when the user may edit the trip', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', total_price: 120 } }), 42);
- expect(ok(res)).toBe(true);
- expect((res as RpcResponse).result).toMatchObject({ id: 9, trip_id: 1, name: 'Hotel', total_price: 120 });
- expect(deps.createCost).toHaveBeenCalledWith(1, expect.objectContaining({ name: 'Hotel', total_price: 120 }));
- });
-
- it('db:write:costs is RESOURCE_FORBIDDEN without the budget_edit permission', async () => {
- (deps.canEditCosts as ReturnType<typeof vi.fn>).mockReturnValue(false);
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel' } }), 42);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.createCost).not.toHaveBeenCalled();
- });
-
- it('db:write:costs on a trip the user cannot access is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel' } }), 99);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.createCost).not.toHaveBeenCalled();
- });
-
- it('db:write:costs with an invalid payload is BAD_PARAMS', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- // name is required (min length 1) by budgetCreateItemRequestSchema
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { total_price: 5 } }), 42);
- expect((res as RpcError).error.code).toBe('BAD_PARAMS');
- expect(deps.createCost).not.toHaveBeenCalled();
- });
-
- it('db:write:costs with no bound acting user is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel' } }), undefined);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.createCost).not.toHaveBeenCalled();
- });
-
- it('costs.create is PERMISSION_DENIED without db:write:costs', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel' } }), 42);
- expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
- });
-
- it('db:write:costs updates a cost when the user may edit the trip', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'Hostel' } }), 42);
- expect(ok(res)).toBe(true);
- expect((res as RpcResponse).result).toMatchObject({ id: 5, trip_id: 1, name: 'Hostel' });
- expect(deps.updateCost).toHaveBeenCalledWith(1, 5, expect.objectContaining({ name: 'Hostel' }));
- });
-
- it('costs.update is RESOURCE_FORBIDDEN without the budget_edit permission', async () => {
- (deps.canEditCosts as ReturnType<typeof vi.fn>).mockReturnValue(false);
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'X' } }), 42);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.updateCost).not.toHaveBeenCalled();
- });
-
- it('costs.update on a trip the user cannot access is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'X' } }), 99);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.updateCost).not.toHaveBeenCalled();
- });
-
- it('costs.update with an invalid payload is BAD_PARAMS', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- // total_price must be a number per budgetUpdateItemRequestSchema.
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { total_price: 'nope' } }), 42);
- expect((res as RpcError).error.code).toBe('BAD_PARAMS');
- expect(deps.updateCost).not.toHaveBeenCalled();
- });
-
- it('costs.update with no bound acting user is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'X' } }), undefined);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.updateCost).not.toHaveBeenCalled();
- });
-
- it('costs.update is PERMISSION_DENIED without db:write:costs', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.update', { tripId: 1, itemId: 5, input: { name: 'X' } }), 42);
- expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
- });
-
- it('db:write:costs deletes a cost when the user may edit the trip', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
- expect(ok(res)).toBe(true);
- expect((res as RpcResponse).result).toMatchObject({ deleted: true });
- expect(deps.deleteCost).toHaveBeenCalledWith(1, 5);
- });
-
- it('costs.delete is RESOURCE_FORBIDDEN without the budget_edit permission', async () => {
- (deps.canEditCosts as ReturnType<typeof vi.fn>).mockReturnValue(false);
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.deleteCost).not.toHaveBeenCalled();
- });
-
- it('costs.delete on a trip the user cannot access is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 99);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.deleteCost).not.toHaveBeenCalled();
- });
-
- it('costs.delete with no bound acting user is RESOURCE_FORBIDDEN', async () => {
- const host = new PluginRpcHost('p', new Set(['db:write:costs']), deps);
- const res = await host.dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), undefined);
- expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
- expect(deps.deleteCost).not.toHaveBeenCalled();
- });
-
- it('costs.delete is PERMISSION_DENIED without db:write:costs', async () => {
- const host = new PluginRpcHost('p', new Set(['db:read:costs']), deps);
- const res = await host.dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42);
- expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
- });
-
// --- Planner writes (#1429) ---
// The places, days and itinerary cases moved to their own domain suites.
it('places.create is PERMISSION_DENIED without db:write:places', async () => {
diff --git a/server/tests/unit/reservations/bookings.rpc.test.ts b/server/tests/unit/reservations/bookings.rpc.test.ts
new file mode 100644
index 000000000..7d78df649
--- /dev/null
+++ b/server/tests/unit/reservations/bookings.rpc.test.ts
@@ -0,0 +1,191 @@
+/**
+ * The booking plugin surfaces after they moved onto @PluginMethod: reservations and
+ * the lodging blocks.
+ *
+ * Both are cascade-heavy, which is the point of most cases here. Creating a
+ * reservation can create an accommodation and a budget item; deleting one can remove
+ * both again; and deleting a lodging block can take its partner reservation and its
+ * budget item with it. Every one of those side effects is a broadcast the web app
+ * relies on, so they are asserted by event name and order.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
+import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
+import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
+import { ReservationsRpc } from '../../../src/nest/reservations/reservations.rpc';
+import { ReservationsModule } from '../../../src/nest/reservations/reservations.module';
+import { AccommodationsRpc } from '../../../src/nest/days/accommodations.rpc';
+import { DaysModule } from '../../../src/nest/days/days.module';
+import type { ReservationsService } from '../../../src/nest/reservations/reservations.service';
+import type { DaysService } from '../../../src/nest/days/days.service';
+import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
+import type { DatabaseService } from '../../../src/nest/database/database.service';
+import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
+import type { AddonsService } from '../../../src/nest/addons/addons.service';
+import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
+import { makeDeps } from '../../helpers/rpc-host-deps';
+
+const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
+const events = (r: { broadcast: ReturnType<typeof vi.fn> }) => r.broadcast.mock.calls.map((c) => c[1]);
+
+/** Trip 1 belongs to user 42; reservation 5 and accommodation 11 sit on it. */
+function build(opts: { canEdit?: boolean; cascade?: boolean; seenActions?: string[] } = {}) {
+ const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };
+ const reservations = {
+ create: vi.fn(() => ({ reservation: { id: 40 }, accommodationCreated: !!opts.cascade })),
+ getReservation: vi.fn((id: string) => (id === '5' ? { id: 5, title: 'Hotel', type: 'lodging' } : undefined)),
+ update: vi.fn(() => ({ reservation: { id: 5 }, accommodationChanged: !!opts.cascade })),
+ remove: vi.fn((id: string) =>
+ id === '5'
+ ? { deleted: { title: 'Hotel', type: 'lodging', accommodation_id: opts.cascade ? 11 : null }, accommodationDeleted: !!opts.cascade, deletedBudgetItemId: opts.cascade ? 7 : null }
+ : { deleted: null, accommodationDeleted: false, deletedBudgetItemId: null },
+ ),
+ syncBudgetOnCreate: vi.fn(),
+ syncBudgetOnUpdate: vi.fn(),
+ notifyBookingChange: vi.fn(),
+ } as unknown as ReservationsService & Record<string, ReturnType<typeof vi.fn>>;
+ const days = {
+ validateAccommodationRefs: vi.fn((_t: number, placeId?: number) => (placeId === 404 ? [{ message: 'place 404 is not on this trip' }] : [])),
+ createAccommodation: vi.fn(() => ({ id: 60 })),
+ getAccommodation: vi.fn((id: number) => (id === 11 ? { id: 11 } : undefined)),
+ updateAccommodation: vi.fn(() => ({ id: 11 })),
+ deleteAccommodation: vi.fn(() => ({ linkedReservationId: opts.cascade ? 40 : null, deletedBudgetItemId: opts.cascade ? 7 : null })),
+ } as unknown as DaysService & Record<string, ReturnType<typeof vi.fn>>;
+ const guards = new PluginGuards(
+ {
+ canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)),
+ prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
+ } as unknown as DatabaseService,
+ {
+ checkPermission: vi.fn((action: string) => {
+ opts.seenActions?.push(action);
+ return opts.canEdit ?? true;
+ }),
+ } as unknown as PermissionsService,
+ { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
+ );
+ const registry = createTestPluginRegistry([
+ new ReservationsRpc(reservations, realtime, guards),
+ new AccommodationsRpc(days, realtime, guards),
+ ]);
+ const host = (...grants: string[]) =>
+ new PluginRpcHost('p', new Set(grants.length ? grants : ['db:write:reservations', 'db:write:accommodations']), makeDeps(), registry);
+ return { reservations, days, realtime, host };
+}
+
+describe('ReservationsRpc', () => {
+ it('BOOK-RPC-001 writes need the grant, reservation_edit and a bound user', async () => {
+ const seen: string[] = [];
+ const f = build({ seenActions: seen });
+ expect((await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'Hotel', type: 'lodging' } }), 42)).ok).toBe(true);
+ expect(seen).toContain('reservation_edit');
+ const noUser = (await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'x', type: 'lodging' } }), undefined)) as RpcError;
+ expect(noUser.error.message).toBe('reservation writes require an authenticated user context');
+ });
+
+ it('BOOK-RPC-002 a malformed endpoints array is rejected up front', async () => {
+ const f = build();
+ const res = (await f.host().dispatch(
+ req('reservations.create', { tripId: 1, input: { title: 'Flight', type: 'flight', endpoints: [{ nonsense: true }] } }), 42,
+ )) as RpcError;
+ expect(res.error.code).toBe('BAD_PARAMS');
+ // Otherwise it fails deep in the service mid-transaction, or is silently dropped.
+ expect(f.reservations.create).not.toHaveBeenCalled();
+ });
+
+ it('BOOK-RPC-003 an absent endpoints field stays absent, which means "keep"', async () => {
+ const f = build();
+ expect((await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'Hotel', type: 'lodging' } }), 42)).ok).toBe(true);
+ });
+
+ it('BOOK-RPC-004 a missing reservation is RESOURCE_FORBIDDEN, naming it', async () => {
+ const f = build();
+ expect(((await f.host().dispatch(req('reservations.update', { tripId: 1, reservationId: 404, input: { title: 'x', type: 'lodging' } }), 42)) as RpcError).error.message)
+ .toBe('no reservation 404 on trip 1');
+ expect(((await f.host().dispatch(req('reservations.delete', { tripId: 1, reservationId: 404 }), 42)) as RpcError).error.message)
+ .toBe('no reservation 404 on trip 1');
+ });
+
+ it('BOOK-RPC-005 creating a lodging booking cascades into the accommodation event', async () => {
+ const f = build({ cascade: true });
+ await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'Hotel', type: 'lodging' } }), 42);
+ expect(events(f.realtime)).toEqual(['accommodation:created', 'reservation:created']);
+ });
+
+ it('BOOK-RPC-006 deleting one takes its accommodation and budget item with it', async () => {
+ const f = build({ cascade: true });
+ await f.host().dispatch(req('reservations.delete', { tripId: 1, reservationId: 5 }), 42);
+ expect(events(f.realtime)).toEqual(['accommodation:deleted', 'budget:deleted', 'reservation:deleted']);
+ });
+
+ it('BOOK-RPC-007 the budget sync and the booking notification both run', async () => {
+ const f = build();
+ await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'Hotel', type: 'lodging' } }), 42);
+ expect(f.reservations.syncBudgetOnCreate).toHaveBeenCalled();
+ expect(f.reservations.notifyBookingChange).toHaveBeenCalledWith(1, 42, 'Hotel', 'lodging');
+ });
+
+ it('BOOK-RPC-008 a refused write cascades nothing', async () => {
+ const f = build({ canEdit: false, cascade: true });
+ await f.host().dispatch(req('reservations.create', { tripId: 1, input: { title: 'x', type: 'lodging' } }), 42);
+ expect(f.realtime.broadcast).not.toHaveBeenCalled();
+ expect(f.reservations.notifyBookingChange).not.toHaveBeenCalled();
+ });
+
+ it('BOOK-RPC-009 the class is listed in its module providers', () => {
+ expect(Reflect.getMetadata('providers', ReservationsModule) as unknown[]).toContain(ReservationsRpc);
+ });
+});
+
+describe('AccommodationsRpc', () => {
+ it('BOOK-RPC-010 lodging blocks run under day_edit, NOT reservation_edit', async () => {
+ const seen: string[] = [];
+ const f = build({ seenActions: seen });
+ await f.host().dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 7, start_day_id: 3, end_day_id: 4 } }), 42);
+ // They hold db:write:accommodations but the app gates them on the day permission.
+ expect(seen).toEqual(['day_edit']);
+ });
+
+ it('BOOK-RPC-011 the three ids are required, and the schema rejects them first', async () => {
+ const f = build();
+ // The shared schema runs before the handler's own check, so a missing id is
+ // reported as a schema failure. The handler's check is the second line of
+ // defence, for values the schema lets through but the service cannot use.
+ const missing = (await f.host().dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 7 } }), 42)) as RpcError;
+ expect(missing.error.code).toBe('BAD_PARAMS');
+ const zero = (await f.host().dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 0, start_day_id: 0, end_day_id: 0 } }), 42)) as RpcError;
+ expect(zero.error.code).toBe('BAD_PARAMS');
+ expect(f.days.createAccommodation).not.toHaveBeenCalled();
+ });
+
+ it('BOOK-RPC-012 a place or day from another trip is refused with the validator message', async () => {
+ const f = build();
+ const res = (await f.host().dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 404, start_day_id: 3, end_day_id: 4 } }), 42)) as RpcError;
+ expect(res.error.message).toBe('place 404 is not on this trip');
+ expect(f.days.createAccommodation).not.toHaveBeenCalled();
+ });
+
+ it('BOOK-RPC-013 creating a block announces the partner reservation too', async () => {
+ const f = build();
+ await f.host().dispatch(req('accommodations.create', { tripId: 1, input: { place_id: 7, start_day_id: 3, end_day_id: 4 } }), 42);
+ expect(events(f.realtime)).toEqual(['accommodation:created', 'reservation:created']);
+ });
+
+ it('BOOK-RPC-014 deleting a block cascades to its reservation and budget item', async () => {
+ const f = build({ cascade: true });
+ await f.host().dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), 42);
+ expect(events(f.realtime)).toEqual(['reservation:deleted', 'budget:deleted', 'accommodation:deleted']);
+ });
+
+ it('BOOK-RPC-015 a missing block is RESOURCE_FORBIDDEN, naming it', async () => {
+ const f = build();
+ expect(((await f.host().dispatch(req('accommodations.update', { tripId: 1, accommodationId: 404, input: {} }), 42)) as RpcError).error.message)
+ .toBe('no accommodation 404 on trip 1');
+ expect(((await f.host().dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 404 }), 42)) as RpcError).error.message)
+ .toBe('no accommodation 404 on trip 1');
+ });
+
+ it('BOOK-RPC-016 the class is listed in its module providers', () => {
+ expect(Reflect.getMetadata('providers', DaysModule) as unknown[]).toContain(AccommodationsRpc);
+ });
+});