mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(trips): deleting a guest keeps the costs adding up instead of dropping their payments
A guest's payer rows and recorded payments hung on the users row by ON DELETE CASCADE, so deleting the guest wiped money that had really moved: expenses they paid were left without a payer, settled payments reopened, and a custom or receipt split lost the guest's share so the balances no longer summed to zero. Deleting a guest who paid for an expense or is part of a recorded payment is now refused with a 409 (REST and the delete_trip_guest MCP tool, same text), and the share dialog says to change the payer or delete the payment first. Otherwise the guest's share is handed on: an equal split re-splits as before, a custom amount goes to the others by largest remainder in the currency's smallest step (members without an amount get one, so the expense stays a custom split), and a receipt drops the guest from its lines and is split again like the cost editor does. A legacy paid_by_user_id is cleared as on account deletion. Account deletion goes through the same re-split. The confirmation text in all languages and the wiki say what really happens. Refs #2604
This commit is contained in:
@@ -89,3 +89,20 @@ export const COLLAB_POLL_OPTIONS: JsonColumn<unknown[]> = {
|
||||
schema: z.array(z.unknown()),
|
||||
fallback: () => [],
|
||||
};
|
||||
|
||||
/**
|
||||
* An expense's itemized receipt (#1658): each line's price as typed and the user
|
||||
* ids in on it. The client writes it; the server only reads it to take a departed
|
||||
* guest off the lines, so every key it does not know is kept as it is.
|
||||
*/
|
||||
export const BUDGET_ITEM_TICKET: JsonColumn<{ items: { price?: string | number; parts?: number[] }[] } | null> = {
|
||||
column: 'budget_items.ticket_json',
|
||||
schema: z
|
||||
.object({
|
||||
items: z.array(
|
||||
z.looseObject({ price: z.union([z.string(), z.number()]).optional(), parts: z.array(z.number()).optional() }),
|
||||
),
|
||||
})
|
||||
.loose(),
|
||||
fallback: () => null,
|
||||
};
|
||||
|
||||
@@ -196,6 +196,16 @@ export class BudgetItemMembersRepository extends TrekRepository<BudgetItemMember
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** `UPDATE budget_item_members SET amount = ? WHERE budget_item_id = ? AND user_id = ?`. */
|
||||
async setAmount(budget_item_id: number, user_id: number, amount: number | null): Promise<void> {
|
||||
await this.kysely<BudgetItemMembersKyselyDB>()
|
||||
.updateTable('budget_item_members')
|
||||
.set({ amount })
|
||||
.where('budget_item_id', '=', budget_item_id)
|
||||
.where('user_id', '=', user_id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** BG35/BG38/BG59 — `DELETE FROM budget_item_members WHERE budget_item_id = ?` (replace-all before a re-insert). */
|
||||
async deleteForItem(budget_item_id: number): Promise<void> {
|
||||
await this.kysely<BudgetItemMembersKyselyDB>()
|
||||
|
||||
@@ -94,6 +94,17 @@ export class BudgetItemPayersRepository extends TrekRepository<BudgetItemPayers>
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** How many expenses a user paid any part of, a refund's negative share included (#2176): `SELECT COUNT(*) FROM budget_item_payers WHERE user_id = ? AND amount <> 0`. */
|
||||
async countNonZeroForUser(user_id: number): Promise<number> {
|
||||
const row = await this.kysely<BudgetItemPayersKyselyDB>()
|
||||
.selectFrom('budget_item_payers')
|
||||
.select((eb) => eb.fn.countAll<number>().as('count'))
|
||||
.where('user_id', '=', user_id)
|
||||
.where('amount', '<>', 0)
|
||||
.executeTakeFirst();
|
||||
return Number(row?.count ?? 0);
|
||||
}
|
||||
|
||||
/** BG4 — `DELETE FROM budget_item_payers WHERE budget_item_id = ?` (replace-all before a re-insert). */
|
||||
async deleteForItem(budget_item_id: number): Promise<void> {
|
||||
await this.kysely<BudgetItemPayersKyselyDB>()
|
||||
|
||||
@@ -306,6 +306,11 @@ export class BudgetItemsRepository extends TrekRepository<BudgetItems> {
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** `UPDATE budget_items SET ticket_json = ? WHERE id = ?`. */
|
||||
async setTicketJson(id: number, ticket_json: string | null): Promise<void> {
|
||||
await this.kysely<BudgetKyselyDB>().updateTable('budget_items').set({ ticket_json }).where('id', '=', id).execute();
|
||||
}
|
||||
|
||||
/** BG83 (`reorderItems`, looped) — `UPDATE budget_items SET sort_order = ? WHERE id = ? AND trip_id = ?`. */
|
||||
async setSortOrder(id: number | string, trip_id: number | string, sort_order: number): Promise<void> {
|
||||
await this.kysely<BudgetKyselyDB>()
|
||||
|
||||
@@ -179,6 +179,16 @@ export class BudgetSettlementsRepository extends TrekRepository<BudgetSettlement
|
||||
await this.kysely<BudgetSettlementsKyselyDB>().deleteFrom('budget_settlements').where('id', '=', id).execute();
|
||||
}
|
||||
|
||||
/** How many recorded payments a user sent or received: `SELECT COUNT(*) FROM budget_settlements WHERE from_user_id = ? OR to_user_id = ?`. */
|
||||
async countForUser(user_id: number): Promise<number> {
|
||||
const row = await this.kysely<BudgetSettlementsKyselyDB>()
|
||||
.selectFrom('budget_settlements')
|
||||
.select((eb) => eb.fn.countAll<number>().as('count'))
|
||||
.where((eb) => eb.or([eb('from_user_id', '=', user_id), eb('to_user_id', '=', user_id)]))
|
||||
.executeTakeFirst();
|
||||
return Number(row?.count ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* `UPDATE budget_settlements SET created_by_user_id = NULL WHERE
|
||||
* created_by_user_id = ?`. The column has no ON DELETE action, so deleting a
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { currencyDecimals, splitEqualShares, splitTicketLines, toMinor } from '@trek/shared';
|
||||
|
||||
/** A member row of one expense as the re-split reads it. */
|
||||
export interface DepartureMember {
|
||||
user_id: number;
|
||||
amount: number | null;
|
||||
}
|
||||
|
||||
/** The decoded `ticket_json` of an expense, every key the server does not read kept as it is. */
|
||||
export interface DepartureTicket {
|
||||
items: { price?: string | number; parts?: number[] }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* What an expense's split becomes when one of its members leaves for good (a
|
||||
* deleted guest or account, #2604), so the shares still add up to what they did.
|
||||
*
|
||||
* An equal split needs nothing here: the members left divide the payer credit
|
||||
* among themselves. A split by amount hands the leaver's amount to everyone
|
||||
* left, largest remainder in the smallest step the currency is shown in, and
|
||||
* gives each of them an amount of their own: a member without one pays nothing
|
||||
* on a custom split, and leaving them at null would quietly turn the expense
|
||||
* back into an equal one. A split by receipt takes the leaver off every line and
|
||||
* splits the lines again the way the cost editor does, so the receipt and the
|
||||
* amounts agree the next time it is opened; a line only the leaver was on is
|
||||
* then carried by everyone left on the receipt. Should that not account for the
|
||||
* same total (a receipt nobody else is on, or amounts edited past the receipt),
|
||||
* the amount is handed on as for a custom split instead.
|
||||
*
|
||||
* `amounts` is null when no member amount changes, `ticket` when the receipt does not.
|
||||
*/
|
||||
export function shareAfterLeaving(
|
||||
itemId: number,
|
||||
members: readonly DepartureMember[],
|
||||
leaverId: number,
|
||||
currency: string,
|
||||
ticket: DepartureTicket | null,
|
||||
): { amounts: Record<number, number> | null; ticket: DepartureTicket | null } {
|
||||
const staying = members.filter((m) => m.user_id !== leaverId);
|
||||
const leaver = members.find((m) => m.user_id === leaverId);
|
||||
const onReceipt = ticket?.items.some((line) => line.parts?.includes(leaverId)) ?? false;
|
||||
const nextTicket =
|
||||
ticket && onReceipt
|
||||
? {
|
||||
...ticket,
|
||||
items: ticket.items.map((line) => ({ ...line, parts: (line.parts ?? []).filter((id) => id !== leaverId) })),
|
||||
}
|
||||
: null;
|
||||
if (!leaver || staying.length === 0 || !members.some((m) => m.amount !== null))
|
||||
return { amounts: null, ticket: nextTicket };
|
||||
|
||||
const before = members.reduce((sum, m) => sum + toMinor(m.amount ?? 0), 0);
|
||||
if (nextTicket) {
|
||||
const { shares, totalMinor } = splitTicketLines(
|
||||
nextTicket.items.map((line) => ({ price: line.price ?? '', parts: line.parts })),
|
||||
);
|
||||
const covered = staying.reduce((sum, m) => sum + (shares[m.user_id] ?? 0), 0);
|
||||
if (totalMinor === before && covered === totalMinor) {
|
||||
return {
|
||||
amounts: Object.fromEntries(staying.map((m) => [m.user_id, (shares[m.user_id] ?? 0) / 100])),
|
||||
ticket: nextTicket,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const leaving = toMinor(leaver.amount ?? 0);
|
||||
const decimals = currencyDecimals(currency);
|
||||
const step = decimals < 2 && leaving % 10 ** (2 - decimals) === 0 ? 10 ** (2 - decimals) : 1;
|
||||
const extra = splitEqualShares(leaving / step, staying, itemId);
|
||||
const amounts = Object.fromEntries(
|
||||
staying.map((m) => [m.user_id, (toMinor(m.amount ?? 0) + (extra[m.user_id] ?? 0) * step) / 100]),
|
||||
);
|
||||
return { amounts, ticket: nextTicket };
|
||||
}
|
||||
|
||||
/** The refusal REST and MCP answer when a guest who moved money is to be deleted (#2604). */
|
||||
export const GUEST_HAS_PAYMENTS =
|
||||
'This guest paid for an expense or is part of a recorded payment. Change the payer or delete the payment first.';
|
||||
@@ -27,8 +27,10 @@ import { Trips } from '../../db/entities/Trips.entity';
|
||||
import type { TripsRepository, TripAccess } from '../../db/repositories/Trips.repository';
|
||||
import { TripMembers } from '../../db/entities/TripMembers.entity';
|
||||
import type { TripMembersRepository } from '../../db/repositories/TripMembers.repository';
|
||||
import { RESERVATION_METADATA } from '../../db/json-columns';
|
||||
import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { BUDGET_ITEM_TICKET, RESERVATION_METADATA } from '../../db/json-columns';
|
||||
import { decodeJson, decodeJsonResult, encodeJson } from '../../utils/json-column';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { GUEST_HAS_PAYMENTS, shareAfterLeaving } from './budget-departure.helpers';
|
||||
|
||||
type Trip = TripAccess;
|
||||
|
||||
@@ -1005,13 +1007,26 @@ export class BudgetService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears a guest's traces before the users row goes, refusing while money they moved is
|
||||
* on the books: the cascade would take their payer rows and recorded payments with it (#2604).
|
||||
*/
|
||||
async releaseGuest(userId: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
const paid = await this.budgetItemPayersRepo.countNonZeroForUser(userId);
|
||||
if (paid + (await this.budgetSettlementsRepo.countForUser(userId)) > 0) {
|
||||
throw new DomainError(409, GUEST_HAS_PAYMENTS, { code: 'guest_has_payments' });
|
||||
}
|
||||
await this.budgetItemsRepo.clearPaidByUser(userId);
|
||||
await this.budgetSettlementsRepo.clearCreatedBy(userId);
|
||||
await this.removeUserFromBudgetItems(userId);
|
||||
});
|
||||
}
|
||||
|
||||
async removeUserFromBudgetItems(userId: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
const itemIds = await this.budgetItemMembersRepo.listItemIdsForUser(userId);
|
||||
if (itemIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(itemIds.map(itemId => this.handOnShare(itemId, userId)));
|
||||
await this.budgetItemMembersRepo.deleteForUser(userId);
|
||||
|
||||
for (const itemId of itemIds) {
|
||||
@@ -1021,6 +1036,19 @@ export class BudgetService {
|
||||
});
|
||||
}
|
||||
|
||||
/** Hands a departing member's custom or receipt share to the rest of the split, see {@link shareAfterLeaving}. */
|
||||
private async handOnShare(itemId: number, userId: number): Promise<void> {
|
||||
const item = await this.budgetItemsRepo.findById(itemId);
|
||||
if (!item) return;
|
||||
const ticket = decodeJsonResult(BUDGET_ITEM_TICKET, item.ticket_json);
|
||||
const currency = item.currency || (await this.tripsRepo.getCurrency(item.trip_id)) || 'EUR';
|
||||
const members = await this.budgetItemMembersRepo.listForItem(itemId);
|
||||
const next = shareAfterLeaving(itemId, members, userId, currency, ticket.ok ? ticket.value : null);
|
||||
if (next.ticket) await this.budgetItemsRepo.setTicketJson(itemId, encodeJson(BUDGET_ITEM_TICKET, next.ticket));
|
||||
const amounts = Object.entries(next.amounts ?? {});
|
||||
await Promise.all(amounts.map(([id, amount]) => this.budgetItemMembersRepo.setAmount(itemId, Number(id), amount)));
|
||||
}
|
||||
|
||||
/**
|
||||
* R2-class fix (same as `FilesService`'s — flagged, mutation-tested): the
|
||||
* legacy trip-scoping guard (BG68) and the write (BG69) were two separate
|
||||
|
||||
@@ -298,18 +298,21 @@ export class TripMembersService {
|
||||
|
||||
async deleteGuest(tripId: string | number, guestUserId: number): Promise<boolean> {
|
||||
if (!(await this.guestOfTrip(tripId, guestUserId))) return false;
|
||||
// The plugin erasure, the budget re-split and the user delete run in one
|
||||
// The budget check and re-split, the plugin erasure and the user delete run in one
|
||||
// transaction, so a failure mid-flow can't leave the expense divisors re-derived,
|
||||
// or the guest's plugin rows erased, for a guest that still exists (or vice
|
||||
// versa). The plugin notification goes out after the commit.
|
||||
await this.uow.transactional(async () => {
|
||||
// A guest who paid for something or is part of a recorded payment is refused with a
|
||||
// 409 before anything is touched: the cascade would take that money off the books
|
||||
// (#2604). Otherwise the expenses they were part of are re-split before the cascade
|
||||
// takes their member rows away, the divisor and the custom amounts cannot follow a
|
||||
// foreign key (#1553).
|
||||
await this.budget.releaseGuest(guestUserId);
|
||||
// A guest is still a user id a plugin may hold data for, so erase that too (the
|
||||
// host-side per-user tables plus a durable own-db erasure per granted plugin), exactly
|
||||
// like a full account deletion; otherwise a deleted guest's plugin data lingers.
|
||||
await this.userCleanup.erasePluginUserData(guestUserId);
|
||||
// Re-split the expenses they were part of before the cascade takes their member
|
||||
// rows away — the divisor is denormalized and cannot follow a foreign key (#1553).
|
||||
await this.budget.removeUserFromBudgetItems(guestUserId);
|
||||
// Deleting the guest's users row cascades its membership and every assignment join
|
||||
// (trip_members, budget/packing/assignment links) via the ON DELETE foreign keys.
|
||||
await this.usersRepo.deleteGuest(guestUserId);
|
||||
|
||||
@@ -610,7 +610,7 @@ export class TripsMcp {
|
||||
@Tool({
|
||||
name: 'delete_trip_guest',
|
||||
description:
|
||||
'Remove a guest from a trip. This deletes the guest outright (they exist only for this trip) and re-splits any expenses they were part of. Only the trip owner can do this.',
|
||||
'Remove a guest from a trip. This deletes the guest outright (they exist only for this trip) and hands their share of any expense to the others in its split. Refused while the guest paid for an expense or is part of a recorded payment: change the payer or delete the payment first. Only the trip owner can do this.',
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
guestId: idSchema.describe('User ID of the guest, from list_trip_members'),
|
||||
|
||||
Reference in New Issue
Block a user