refactor(budget): money arithmetic lives in shared and the settlement uses it

toMinor, sumMinor, splitEqualShares and currencyDecimals move to
shared/src/money. The budget service and its MCP tools call them instead of
private copies, and the share table both sides were pinned to becomes the
spec of the shared function. Stored values and every computed figure stay
the same.
This commit is contained in:
Maurice
2026-10-10 14:43:02 +02:00
parent e5a2af5999
commit 8d716aec2f
9 changed files with 177 additions and 94 deletions
+6 -14
View File
@@ -6,7 +6,7 @@ import {
} from '../../nest-mcp';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { z } from 'zod';
import { idSchema } from '@trek/shared';
import { idSchema, sumMinor, toMinor } from '@trek/shared';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
@@ -48,14 +48,6 @@ function parseId(value: string | string[]): number | null {
return Number.isInteger(n) && n > 0 ? n : null;
}
/** Money is compared in whole cents, never in floats (the budget money rule). */
function toCents(amount: number): number {
return Math.round(amount * 100);
}
function sumCents(amounts: number[]): number {
return amounts.reduce((sum, a) => sum + toCents(a), 0);
}
function formatCents(cents: number): string {
return (cents / 100).toFixed(2);
@@ -131,9 +123,9 @@ export class BudgetMcp {
// Negative payers count with their sign (#2176) — the write path stores them.
if (payers !== undefined) {
const roster = await this.tripMembers.rosterUserIds(tripId);
return sumCents(payers.filter(p => p.amount !== 0 && roster.has(p.user_id)).map(p => p.amount));
return sumMinor(payers.filter(p => p.amount !== 0 && roster.has(p.user_id)).map(p => p.amount));
}
if (total_price !== undefined) return toCents(total_price);
if (total_price !== undefined) return toMinor(total_price);
return fallbackCents;
}
@@ -169,7 +161,7 @@ export class BudgetMcp {
return `payers contains user IDs that are not on this trip: ${payerStrangers.join(', ')}. Resolve them with list_trip_members.`;
}
}
const splitCents = sumCents(members.map(m => m.amount));
const splitCents = sumMinor(members.map(m => m.amount));
if (splitCents !== totalCents) {
return `The split does not add up: the member amounts total ${formatCents(splitCents)} but the expense total is ${formatCents(totalCents)}. Adjust the amounts so they sum to the expense total.`;
}
@@ -216,7 +208,7 @@ export class BudgetMcp {
if (members !== undefined && member_ids !== undefined) return errorResult('Pass either members (uneven split) or member_ids (equal split), not both.');
if (place_id != null && !(await this.placeOnTrip(tripId, place_id))) return errorResult('place_id does not belong to this trip.');
if (members !== undefined) {
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toCents(total_price)), payers);
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toMinor(total_price)), payers);
if (refusal) return errorResult(refusal);
}
// The split participants are the members of an uneven split; the equal-split
@@ -296,7 +288,7 @@ export class BudgetMcp {
// the stored figure stands in when the call does not restate one.
const existing = await this.budget.getBudgetItem(itemId, tripId);
if (!existing) return errorResult('Budget item not found.');
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toCents(existing.total_price)), payers);
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toMinor(existing.total_price)), payers);
if (refusal) return errorResult(refusal);
}
// Freeze-then-write composite: a currency change re-freezes the rate at entry
+7 -41
View File
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { BudgetFallbackFx, BudgetParticipantFinal, BudgetUnconverted, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { splitEqualShares, sumMinor, toMinor } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
import { avatarUrl } from '../common/avatarUrl';
@@ -97,7 +98,7 @@ export function splitLegacyTicketNote(
* (toTripCents), applied to the one arithmetic that had been left in euros.
*/
function sumMoney(amounts: number[]): number {
return amounts.reduce((a, v) => a + Math.round(v * 100), 0) / 100;
return sumMinor(amounts) / 100;
}
/**
@@ -1043,10 +1044,10 @@ export class BudgetService {
// A foreign row nothing can convert counts for nobody, as in the settlement.
const convert = tripConverter(item.currency, item.exchange_rate, tripCurrency, rates);
if (!convert) continue;
const toTripCents = (amount: number) => Math.round(convert(amount) * 100);
const toTripCents = (amount: number) => toMinor(convert(amount));
// A member with an amount of their own owes exactly that; the rest split the
// total evenly, as the query this replaces did.
const equal = this.splitEqualShares(toTripCents(item.total_price || 0), own, item.id);
const equal = splitEqualShares(toTripCents(item.total_price || 0), own, item.id);
for (const m of own) {
const share = m.amount !== null && m.amount !== undefined ? toTripCents(m.amount) : (equal[m.user_id] || 0);
let p = people.get(m.user_id);
@@ -1089,7 +1090,7 @@ export class BudgetService {
unconverted.push(r.id);
continue;
}
const cents = Math.round(convert(r.total_price || 0) * 100);
const cents = toMinor(convert(r.total_price || 0));
total += cents;
const cat = r.category || '';
byCategory[cat] = (byCategory[cat] || 0) + cents;
@@ -1112,41 +1113,6 @@ export class BudgetService {
return unbooked ? this.exchangeRates.getRates(trip) : null;
}
/**
* Largest-remainder split of an expense across its participants. Takes and
* returns **whole cents**, so the shares add back up to the input exactly —
* the settlement ledger is netted in integer cents (#1382).
*
* The remainder cent rotates with the item id rather than always landing on the
* first member, so across several expenses the rounding evens out instead of
* always favouring the same person.
*
* Floor-based (`totalCents - baseCents * n`, never `%`), so a negative total —
* a refund split across its beneficiaries (#2176) — still yields a remainder
* in [0, n) and shares that sum back to the total exactly. The client mirror
* (CostsPanel.helpers.splitEqualShares) must stay share-for-share identical;
* the parity fixture in budget.service.calc.test.ts pins both sides.
*/
private splitEqualShares(totalCents: number, members: { user_id: number }[], itemId: number): Record<number, number> {
const n = members.length;
if (n === 0) return {};
const baseCents = Math.floor(totalCents / n);
const remainder = totalCents - baseCents * n;
const shares: Record<number, number> = {};
const sortedMembers = [...members].sort((a, b) => a.user_id - b.user_id);
const startIndex = itemId % n;
for (let i = 0; i < n; i++) {
const member = sortedMembers[i];
const hasExtraCent = ((i - startIndex + n) % n) < remainder;
shares[member.user_id] = baseCents + (hasExtraCent ? 1 : 0);
}
return shares;
}
/**
* Who owes whom (`balances` + the simplified `flows`), the recorded transfers
* (`settlements`), and what the trip ends up costing each participant
@@ -1267,7 +1233,7 @@ export class BudgetService {
unconvertedCurrencies.add((item.currency || '').toUpperCase());
continue;
}
const toTripCents = (amount: number): number => Math.round(convert(amount) * 100);
const toTripCents = (amount: number): number => toMinor(convert(amount));
const members = allMembers.filter(m => m.budget_item_id === item.id);
const payers = allPayers.filter(p => p.budget_item_id === item.id);
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
@@ -1314,7 +1280,7 @@ export class BudgetService {
// here since #2225. An item whose payers net to exactly zero still does, and
// divides zero, which is what it is worth.
const hasCustomSplit = members.some(m => m.amount !== null && m.amount !== undefined);
const equalShares = !hasCustomSplit ? this.splitEqualShares(creditCents, members, item.id) : {};
const equalShares = !hasCustomSplit ? splitEqualShares(creditCents, members, item.id) : {};
for (const m of members) {
const memberShare = hasCustomSplit && m.amount !== null && m.amount !== undefined
? toTripCents(m.amount)