feat(budget): link existing expenses to bookings and places, several per booking

Discussion #2084: a cost bought later (the seat upgrade for a flight) could
not be tied to the booking it belongs to, and a booking held one expense.

- The Costs block of the booking, transport and place forms lists every
  linked expense with edit, unlink (the expense stays in Costs) and delete,
  and offers the expenses that belong nowhere yet under Link existing
  expense. The phone sheets get the same block in their own design, and
  their Files row lists the attached files and links an existing one.
- PUT /budget/:id, update_budget_item (MCP) and costs.update (plugin RPC)
  take reservation_id / place_id; create and update refuse an id from
  another trip on all three paths.
- The booking's mirrored price is the sum of its expenses when they share
  one currency (none counts as the trip's), else the first one, with that
  currency, and follows every change to a linked expense. The booking
  form's price field leaves a booking with several expenses alone.
- Deleting a booking deletes all of its linked expenses and broadcasts each
  one, also from the MCP delete tools.
- Cards show the price with its currency.
- Booking and transport dialogs: Booking Type and Travelers as dropdowns at
  the top, the URL beside Files (transports gain the URL field). The row is
  one shared component; linking and unlinking files go through the store.

Help center pictures and texts for the booking, transport and expense
guides are redone in all 27 languages, five Costs labels that were still
English in 16 languages are translated, and the wiki follows.
This commit is contained in:
Maurice
2026-09-25 15:34:32 +02:00
parent 1f79776070
commit 8864edda18
188 changed files with 4800 additions and 1124 deletions
@@ -603,8 +603,7 @@ export class AccommodationsService {
const linkedRes = this.db.all<{ id: number }>('SELECT id FROM reservations WHERE accommodation_id = ?', Number(id));
const deletedBudgetItemIds: number[] = [];
for (const res of linkedRes) {
const linkedBudget = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE reservation_id = ?', res.id);
if (linkedBudget) {
for (const linkedBudget of this.db.all<{ id: number }>('SELECT id FROM budget_items WHERE reservation_id = ?', res.id)) {
this.db.run('DELETE FROM budget_items WHERE id = ?', linkedBudget.id);
deletedBudgetItemIds.push(linkedBudget.id);
}
+11 -3
View File
@@ -149,7 +149,11 @@ export class BudgetController {
@Body() body: BudgetCreateItemDto,
@Headers('x-socket-id') socketId?: string,
) {
const refusal = this.budget.linkRefusal(tripId, body);
if (refusal) throw new HttpException({ error: refusal }, 400);
const item = await this.budget.create(tripId, body);
// A booking mirrors the total of its expenses (#2084); a new one adds to it.
if (item.reservation_id) this.budget.resyncReservationPrice(tripId, item.reservation_id, socketId);
this.budget.broadcast(tripId, 'budget:created', { item }, socketId);
return { item };
}
@@ -189,13 +193,15 @@ export class BudgetController {
@Body() body: BudgetUpdateItemDto,
@Headers('x-socket-id') socketId?: string,
) {
const refusal = this.budget.linkRefusal(tripId, body);
if (refusal) throw new HttpException({ error: refusal }, 400);
// The booking an expense leaves also needs its price worked out again.
const before = body.reservation_id !== undefined ? this.budget.getBudgetItem(id, tripId) : null;
const updated = await 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.resyncLinkedPrices(tripId, before?.reservation_id, updated, body, socketId);
this.budget.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
return { item: updated };
}
@@ -230,6 +236,8 @@ export class BudgetController {
if (!item) {
throw new HttpException({ error: 'Budget item not found' }, 404);
}
// The payers derive the total, which the linked booking mirrors.
if (item.reservation_id) this.budget.resyncReservationPrice(tripId, item.reservation_id, socketId);
this.budget.broadcast(tripId, 'budget:updated', { item }, socketId);
return { item };
}
+9 -3
View File
@@ -264,17 +264,19 @@ export class BudgetMcp {
days: z.number().int().positive().nullable().optional(),
expense_date: z.string().max(40).nullable().optional().describe('Date the expense occurred, YYYY-MM-DD; null clears it. Omit to leave unchanged.'),
note: z.string().max(500).nullable().optional(),
reservation_id: z.number().int().positive().nullable().optional().describe('Booking or transport on this trip to link the expense to (a booking can carry several); null unlinks it and keeps the expense. Omit to leave unchanged.'),
place_id: z.number().int().positive().nullable().optional().describe('Place on this trip to link the expense to; null unlinks it and keeps the expense. Omit to leave unchanged.'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: budgetAddonOn,
access: { group: 'budget', mode: 'write' },
})
async updateBudgetItem(
{ tripId, itemId, name, category, total_price, currency, member_ids, members, payers, persons, days, expense_date, note }: {
{ tripId, itemId, name, category, total_price, currency, member_ids, members, payers, persons, days, expense_date, note, reservation_id, place_id }: {
tripId: number; itemId: number; name?: string; category?: string; total_price?: number; currency?: string | null;
member_ids?: number[]; members?: { user_id: number; amount: number }[];
payers?: { user_id: number; amount: number }[]; persons?: number | null; days?: number | null;
expense_date?: string | null; note?: string | null;
expense_date?: string | null; note?: string | null; reservation_id?: number | null; place_id?: number | null;
},
ctx: McpContext,
) {
@@ -282,6 +284,8 @@ export class BudgetMcp {
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('budget_edit', tripId, ctx.userId)) return permissionDenied();
if (members !== undefined && member_ids !== undefined) return errorResult('Pass either members (uneven split) or member_ids (equal split), not both.');
const refusal = this.budget.linkRefusal(tripId, { reservation_id, place_id });
if (refusal) return errorResult(refusal);
if (members !== undefined) {
// An edit that leaves the total alone still has to reconcile against it, so
// the stored figure stands in when the call does not restate one.
@@ -292,8 +296,10 @@ export class BudgetMcp {
}
// Freeze-then-write composite: a currency change re-freezes the rate at entry
// time (#1445) on the same code path the REST update uses.
const item = await this.budget.update(itemId, tripId, { name, category, total_price, currency, member_ids, members, payers, persons, days, expense_date, note });
const before = reservation_id !== undefined ? this.budget.getBudgetItem(itemId, tripId) : null;
const item = await this.budget.update(itemId, tripId, { name, category, total_price, currency, member_ids, members, payers, persons, days, expense_date, note, reservation_id, place_id });
if (!item) return errorResult('Budget item not found.');
this.budget.resyncLinkedPrices(tripId, before?.reservation_id, item, { total_price, reservation_id });
this.guards.safeBroadcast(tripId, 'budget:updated', { item });
return ok({ item });
}
+81 -7
View File
@@ -559,6 +559,8 @@ export class BudgetService {
persons?: number | null; days?: number | null; note?: string | null; sort_order?: number; expense_date?: string | null;
ticket_json?: string | null;
receipt_file_ids?: number[];
reservation_id?: number | null;
place_id?: number | null;
},
) {
return this.db.transaction(() => {
@@ -583,7 +585,9 @@ export class BudgetService {
note = CASE WHEN ? THEN ? ELSE note END,
ticket_json = CASE WHEN ? THEN ? ELSE ticket_json END,
sort_order = CASE WHEN ? IS NOT NULL THEN ? ELSE sort_order END,
expense_date = CASE WHEN ? THEN ? ELSE expense_date END
expense_date = CASE WHEN ? THEN ? ELSE expense_date END,
reservation_id = CASE WHEN ? THEN ? ELSE reservation_id END,
place_id = CASE WHEN ? THEN ? ELSE place_id END
WHERE id = ?
`,
data.category || null,
@@ -597,6 +601,8 @@ export class BudgetService {
ticketTouched ? 1 : 0, ticketTouched ? ticket : null,
data.sort_order !== undefined ? 1 : null, data.sort_order !== undefined ? data.sort_order : 0,
data.expense_date !== undefined ? 1 : 0, data.expense_date !== undefined ? (data.expense_date || null) : null,
data.reservation_id !== undefined ? 1 : 0, data.reservation_id ?? null,
data.place_id !== undefined ? 1 : 0, data.place_id ?? null,
id,
);
@@ -709,15 +715,77 @@ export class BudgetService {
this.unlinkReceipts(id);
this.db.run('DELETE FROM budget_items WHERE id = ?', id);
// The booking keeps a copy of this expense's total in its metadata, and
// the reservation update path preserves that copy across edits. With the
// expense gone there is nothing left to mirror, so drop it here rather
// than leave a price on the card that no longer has anything behind it.
if (item.reservation_id) this.clearReservationPrice(tripId, item.reservation_id);
// The booking keeps a copy of its expenses' total in its metadata, and
// the reservation update path preserves that copy across edits. With this
// expense gone the copy is worked out again from what is still linked, and
// dropped when nothing is, rather than leave a price on the card that no
// longer has anything behind it.
if (item.reservation_id) this.resyncReservationPrice(tripId, item.reservation_id);
return true;
});
}
/**
* After an update, the bookings whose mirrored price may have moved: the one
* the expense is linked to when its total changed, and on a re-link both the
* booking it left and the one it joined.
*/
resyncLinkedPrices(
tripId: string | number,
previousReservationId: number | null | undefined,
updated: { reservation_id?: number | null },
data: { total_price?: number; reservation_id?: number | null },
socketId?: string,
): void {
const affected = new Set<number>();
if (data.reservation_id !== undefined && previousReservationId) affected.add(previousReservationId);
// Not only a new total: the currency and the payers (which derive the total)
// move the booking's price as well, so any edit of a linked expense resyncs.
if (updated.reservation_id) affected.add(updated.reservation_id);
for (const reservationId of affected) this.resyncReservationPrice(tripId, reservationId, socketId);
}
/**
* Why a link from an expense can't be made, or null when it can: a booking or
* a place it points at has to exist on the same trip (#2084). REST and MCP
* both ask this before they write, so neither can reach into another trip.
*/
linkRefusal(tripId: string | number, data: { reservation_id?: number | null; place_id?: number | null }): string | null {
if (data.reservation_id != null && !this.db.get('SELECT id FROM reservations WHERE id = ? AND trip_id = ?', data.reservation_id, tripId)) {
return 'reservation_id does not belong to this trip.';
}
if (data.place_id != null && !this.db.get('SELECT id FROM places WHERE id = ? AND trip_id = ?', data.place_id, tripId)) {
return 'place_id does not belong to this trip.';
}
return null;
}
/**
* Works the booking's mirrored price out again from every expense linked to
* it (#2084): their sum while they share one currency, the first one's total
* when they don't (a sum across currencies would be meaningless), and no
* price at all once none is linked. One expense gives exactly the old mirror.
*/
resyncReservationPrice(tripId: string | number, reservationId: number, socketId?: string): void {
const linked = this.db.all<{ total_price: number | null; currency: string | null }>(
'SELECT total_price, currency FROM budget_items WHERE trip_id = ? AND reservation_id = ? ORDER BY id',
tripId, reservationId,
);
if (linked.length === 0) {
this.clearReservationPrice(tripId, reservationId);
return;
}
// No currency means the trip's, and a code is a code whatever its case, so
// an expense in EUR and one without a currency on a EUR trip do add up.
const tripCurrency = (this.db.get<{ currency: string | null }>('SELECT currency FROM trips WHERE id = ?', tripId)?.currency || '').toUpperCase();
const codeOf = (currency: string | null) => (currency || tripCurrency).toUpperCase();
const oneCurrency = new Set(linked.map(row => codeOf(row.currency))).size === 1;
const total = oneCurrency ? sumMoney(linked.map(row => row.total_price || 0)) : (linked[0].total_price || 0);
// Either way the figure is in the first expense's currency; none means the trip's.
const allInTripCurrency = oneCurrency && linked.every(row => !row.currency);
this.syncReservationPrice(String(tripId), reservationId, total, socketId, allInTripCurrency ? null : codeOf(linked[0].currency) || null);
}
/**
* The counterpart to syncReservationPrice: take the mirrored total back off
* the booking. Non-fatal, exactly like the writer.
@@ -1317,7 +1385,7 @@ export class BudgetService {
* 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 {
syncReservationPrice(tripId: string, reservationId: number, totalPrice: number, socketId: string | undefined, currency?: string | null): void {
try {
const reservation = this.db.get<{ id: number; metadata: string | null }>(
'SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?',
@@ -1329,6 +1397,12 @@ export class BudgetService {
// it is linked to — and so a row stamped before #1964 heals on the next
// edit. The panels print this string as it stands.
meta.price = String(Math.round(totalPrice * 100) / 100);
// The card names the currency beside the figure (#2084). An expense in the
// trip's own currency carries none, and neither does its mirror then.
if (currency !== undefined) {
if (currency) meta.priceCurrency = currency.toUpperCase();
else delete meta.priceCurrency;
}
this.db.run('UPDATE reservations SET metadata = ? WHERE id = ?', JSON.stringify(meta), reservation.id);
const updatedRes = this.db.get('SELECT * FROM reservations WHERE id = ?', reservation.id);
this.realtime.broadcast(tripId, 'reservation:updated', { reservation: updatedRes }, socketId);
+11
View File
@@ -65,9 +65,11 @@ export class CostsRpc {
const parsed = budgetCreateItemRequestSchema.safeParse(params.input);
if (!parsed.success) throw new BadParams(`invalid cost: ${schemaMessage(parsed.error)}`);
this.requireCostEdit(tripId, actor);
this.refuseForeignLinks(tripId, parsed.data);
// 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);
if (item.reservation_id) this.budget.resyncReservationPrice(tripId, item.reservation_id);
this.realtime.broadcast(tripId, 'budget:created', { item });
return item;
}
@@ -81,13 +83,22 @@ export class CostsRpc {
const parsed = budgetUpdateItemRequestSchema.safeParse(params.input);
if (!parsed.success) throw new BadParams(`invalid cost: ${schemaMessage(parsed.error)}`);
this.requireCostEdit(tripId, actor);
this.refuseForeignLinks(tripId, parsed.data);
const before = parsed.data.reservation_id !== undefined ? this.budget.getBudgetItem(itemId, tripId) : null;
// 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.budget.resyncLinkedPrices(tripId, before?.reservation_id, item, parsed.data);
this.realtime.broadcast(tripId, 'budget:updated', { item });
return item;
}
/** A booking or place the cost links to has to be on the same trip, as over REST and MCP. */
private refuseForeignLinks(tripId: number, data: { reservation_id?: number | null; place_id?: number | null }): void {
const refusal = this.budget.linkRefusal(tripId, data);
if (refusal) throw new ForbiddenResource(refusal);
}
@PluginMethod('costs.delete', { permission: 'db:write:costs' })
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const tripId = num(params.tripId, 'tripId');
@@ -150,15 +150,15 @@ export class ReservationsController {
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const { deleted, accommodationDeleted, deletedBudgetItemId } = this.reservations.remove(id, tripId);
const { deleted, accommodationDeleted, deletedBudgetItemIds } = this.reservations.remove(id, tripId);
if (!deleted) {
throw new HttpException({ error: 'Reservation not found' }, 404);
}
if (accommodationDeleted) {
this.reservations.broadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id }, socketId);
}
if (deletedBudgetItemId) {
this.reservations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId);
for (const itemId of deletedBudgetItemIds) {
this.reservations.broadcast(tripId, 'budget:deleted', { itemId }, socketId);
}
this.reservations.broadcast(tripId, 'reservation:deleted', { reservationId: Number(id) }, socketId);
this.reservations.notifyBookingChange(tripId, user.id, deleted.title, deleted.type || '');
@@ -472,11 +472,12 @@ export class ReservationsMcp {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
const { deleted, accommodationDeleted } = this.reservations.remove(reservationId, tripId);
const { deleted, accommodationDeleted, deletedBudgetItemIds } = this.reservations.remove(reservationId, tripId);
if (!deleted) return errorResult('Reservation not found.');
if (accommodationDeleted) {
this.guards.safeBroadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id });
}
for (const itemId of deletedBudgetItemIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
this.guards.safeBroadcast(tripId, 'reservation:deleted', { reservationId });
return ok({ success: true });
}
@@ -902,8 +903,9 @@ export class ReservationsMcp {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
const { deleted } = this.reservations.remove(reservationId, tripId);
const { deleted, deletedBudgetItemIds } = this.reservations.remove(reservationId, tripId);
if (!deleted) return errorResult('Transport not found.');
for (const itemId of deletedBudgetItemIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
this.guards.safeBroadcast(tripId, 'reservation:deleted', { reservationId });
return ok({ success: true });
}
@@ -77,10 +77,10 @@ export class ReservationsRpc {
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));
const { deleted, accommodationDeleted, deletedBudgetItemIds } = 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);
for (const itemId of deletedBudgetItemIds) this.realtime.broadcast(tripId, 'budget:deleted', { itemId }, undefined);
this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId }, undefined);
this.notifyBooking(actor, tripId, deleted.title, deleted.type || '');
return { deleted: true };
@@ -987,12 +987,12 @@ export class ReservationsService {
/** The accommodation + budget-item + reservation deletes are one logical
* cascade — all-or-nothing. */
remove(id: string | number, tripId: string | number): { deleted: { id: number; title: string; type: string; accommodation_id: number | null } | undefined; accommodationDeleted: boolean; deletedBudgetItemId: number | null } {
remove(id: string | number, tripId: string | number): { deleted: { id: number; title: string; type: string; accommodation_id: number | null } | undefined; accommodationDeleted: boolean; deletedBudgetItemId: number | null; deletedBudgetItemIds: number[] } {
const removed = this.db.transaction(() => {
const reservation = this.db.get<{ id: number; title: string; type: string; accommodation_id: number | null }>(
'SELECT id, title, type, accommodation_id FROM reservations WHERE id = ? AND trip_id = ?', id, tripId
);
if (!reservation) return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null, stayMirror: noStayMirror() };
if (!reservation) return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null, deletedBudgetItemIds: [], stayMirror: noStayMirror() };
let accommodationDeleted = false;
let stayMirror = noStayMirror();
@@ -1015,13 +1015,16 @@ export class ReservationsService {
}
}
const linkedBudget = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id);
if (linkedBudget) {
this.db.run('DELETE FROM budget_items WHERE id = ?', linkedBudget.id);
// A booking can carry several expenses (#2084); every one of them goes with it.
const deletedBudgetItemIds = this.db
.all<{ id: number }>('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id)
.map(item => item.id);
if (deletedBudgetItemIds.length > 0) {
this.db.run(`DELETE FROM budget_items WHERE id IN (${deletedBudgetItemIds.map(() => '?').join(', ')})`, ...deletedBudgetItemIds);
}
this.db.run('DELETE FROM reservations WHERE id = ?', id);
return { deleted: reservation, accommodationDeleted, deletedBudgetItemId: linkedBudget ? linkedBudget.id : null, stayMirror };
return { deleted: reservation, accommodationDeleted, deletedBudgetItemId: deletedBudgetItemIds[0] ?? null, deletedBudgetItemIds, stayMirror };
});
const { stayMirror, ...answer } = removed;
this.announceStayMirror(tripId, stayMirror);
@@ -1049,14 +1052,13 @@ export class ReservationsService {
// but only if it still carries the auto-derived category (so a manual pick in
// the Costs editor is preserved). Runs regardless of create_budget_entry.
if (type && currentType && type !== currentType) {
const linked = this.db.get<{ id: number; category: string }>('SELECT id, category FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id);
if (linked) {
const oldCat = typeToCostCategory(currentType);
const newCat = typeToCostCategory(type);
if (oldCat !== newCat && linked.category === oldCat) {
const updated = this.budget.updateBudgetItem(linked.id, tripId, { category: newCat });
this.realtime.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
}
const oldCat = typeToCostCategory(currentType);
const newCat = typeToCostCategory(type);
// Every linked expense (#2084), each only while it still has the derived category.
const linked = this.db.all<{ id: number; category: string }>('SELECT id, category FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id);
for (const item of oldCat === newCat ? [] : linked.filter(i => i.category === oldCat)) {
const updated = this.budget.updateBudgetItem(item.id, tripId, { category: newCat });
this.realtime.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
}
}
@@ -1064,6 +1066,10 @@ export class ReservationsService {
// expense, so leave any linked item alone. Expenses are managed from the
// booking's Costs section / the Costs tab, not by re-saving the booking.
if (!entry) return;
// The price field speaks for a single expense. With several linked (#2084)
// it has none to mean, so they are managed from the Costs block only.
const linkedCount = this.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id)?.n ?? 0;
if (linkedCount > 1) return;
if (!(Number(entry.total_price) > 0)) {
// Explicit clear (total_price 0/empty) — drop the linked item.