fix(budget): seed edit fields with two decimals and allow signed amounts for refunds (#2175, #2176)

This commit is contained in:
Maurice
2026-09-01 15:07:26 +02:00
committed by Maurice
parent 49b0ce28d5
commit d1aa573167
18 changed files with 717 additions and 78 deletions
+14 -9
View File
@@ -20,16 +20,20 @@ import { AddonsService } from '../addons/addons.service';
/** Legacy registrar gate: the whole budget surface rides the budget addon. */
const budgetAddonOn = addonGate(ADDON_IDS.BUDGET);
/** Reusable Zod shape for the per-payer amounts on a budget item. */
/**
* Reusable Zod shape for the per-payer amounts on a budget item. Amounts are
* signed like the REST contract's (#2176): a negative payer is the recipient
* of a refund recorded as a negative expense.
*/
const payersSchema = z.array(z.object({
user_id: z.number().int().positive(),
amount: z.number().nonnegative(),
amount: z.number(),
})).describe('Who actually paid, and how much each paid, in the expense currency. Ask the user; do not guess.');
/** Reusable Zod shape for an unequal split: what each participant owes. */
/** Reusable Zod shape for an unequal split: what each participant owes. Signed, like the REST contract (#2176). */
const splitMembersSchema = z.array(z.object({
user_id: z.number().int().positive(),
amount: z.number().nonnegative(),
amount: z.number(),
})).describe('Unequal split: what each participant owes, in the expense currency. The amounts must add up to the expense total. Ask the user; do not guess.');
function parseId(value: string | string[]): number | null {
@@ -116,9 +120,10 @@ export class BudgetMcp {
// Once payers are sent at all, the write path derives the total from them and
// an empty list therefore means zero, not "no opinion". Reading total_price
// here instead would certify a split against a figure the row never receives.
// Negative payers count with their sign (#2176) — the write path stores them.
if (payers !== undefined) {
const roster = this.db.rosterUserIds(tripId);
return sumCents(payers.filter(p => p.amount > 0 && roster.has(p.user_id)).map(p => p.amount));
return sumCents(payers.filter(p => p.amount !== 0 && roster.has(p.user_id)).map(p => p.amount));
}
if (total_price !== undefined) return toCents(total_price);
return fallbackCents;
@@ -151,7 +156,7 @@ export class BudgetMcp {
// certified here would not be the split stored. Refuse rather than let the
// difference surface on the balances screen.
if (payers) {
const payerStrangers = payers.filter(p => p.amount > 0 && !roster.has(p.user_id)).map(p => p.user_id);
const payerStrangers = payers.filter(p => p.amount !== 0 && !roster.has(p.user_id)).map(p => p.user_id);
if (payerStrangers.length > 0) {
return `payers contains user IDs that are not on this trip: ${payerStrangers.join(', ')}. Resolve them with list_trip_members.`;
}
@@ -177,7 +182,7 @@ export class BudgetMcp {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
total_price: z.number().nonnegative(),
total_price: z.number().describe('Signed: a negative total records a refund/partial reimbursement (#2176)'),
currency: z.string().max(10).nullable().optional().describe('ISO currency code (e.g. "EUR"); defaults to the trip currency'),
member_ids: z.array(z.number().int().positive()).optional().describe('Trip member user IDs splitting this expense equally. Omit to split across all trip members (owner + members); pass [] for no split.'),
members: splitMembersSchema.optional().describe('Uneven split: what each participant owes, in the expense currency. The amounts must add up to the expense total. Use this instead of member_ids, never alongside it.'),
@@ -250,7 +255,7 @@ export class BudgetMcp {
itemId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
category: z.string().max(100).optional(),
total_price: z.number().nonnegative().optional(),
total_price: z.number().optional(),
currency: z.string().max(10).nullable().optional().describe('ISO currency code the expense is in (e.g. "USD"); null puts it back in the trip currency. Changing it re-freezes the FX rate at today\'s rate.'),
member_ids: z.array(z.number().int().positive()).optional().describe('Trip member user IDs splitting this expense equally; replaces the current split. Omit to leave unchanged, pass [] for no split.'),
members: splitMembersSchema.optional().describe('Uneven split: what each participant owes, in the expense currency; replaces the current split. The amounts must add up to the expense total. Use this instead of member_ids, never alongside it.'),
@@ -302,7 +307,7 @@ export class BudgetMcp {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Budget category (e.g. Accommodation, Food, Transport)'),
total_price: z.number().nonnegative(),
total_price: z.number().describe('Signed: a negative total records a refund/partial reimbursement (#2176)'),
note: z.string().max(500).optional(),
userIds: z.array(z.number().int().positive()).optional().describe('User IDs splitting this item; omit to split across all trip members, or pass an empty array for no split'),
place_id: z.number().int().positive().optional().describe('Place on this trip the expense belongs to (the museum ticket for that museum), linking it in the planner'),
+21 -8
View File
@@ -157,14 +157,18 @@ export class BudgetService {
return new Set([...unique].filter(id => roster.has(id)));
}
/** Replace the payer rows of an item and keep total_price = sum of payer amounts. */
/**
* Replace the payer rows of an item and keep total_price = sum of payer amounts.
* A negative amount is a real payer — the recipient of a refund (#2176) — and
* is stored as such; only a zero (or NaN) amount says nothing and is dropped.
*/
private writeItemPayers(itemId: number | string, tripId: string | number, payers: { user_id: number; amount: number }[]) {
this.db.run('DELETE FROM budget_item_payers WHERE budget_item_id = ?', itemId);
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, ?)');
const known = this.rosterMemberIds(tripId, payers.map(p => p.user_id));
const accepted: number[] = [];
for (const p of payers) {
if (!(p.amount > 0) || !known.has(p.user_id)) continue;
if (!p.amount || !known.has(p.user_id)) continue;
insert.run(itemId, p.user_id, p.amount);
accepted.push(p.amount);
}
@@ -365,8 +369,9 @@ export class BudgetService {
}
// total_price is derived from explicit payers when given; otherwise the caller
// value (planning entries, or a bill no one has paid yet).
const payerTotal = sumMoney((data.payers || []).filter(p => p.amount > 0).map(p => p.amount));
// value (planning entries, or a bill no one has paid yet). Negative payer
// amounts (a refund's recipient, #2176) count like any other.
const payerTotal = sumMoney((data.payers || []).filter(p => p.amount !== 0).map(p => p.amount));
const total = data.payers && data.payers.length > 0 ? payerTotal : (data.total_price || 0);
const knownMembers = data.members ? this.rosterMemberIds(tripId, data.members.map(m => m.user_id)) : null;
@@ -644,6 +649,12 @@ export class BudgetService {
* 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;
@@ -755,10 +766,11 @@ export class BudgetService {
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
// Payers are credited what they actually paid (converted to trip currency with
// the item's stored exchange rate)…
// the item's stored exchange rate). A negative payer — the recipient of a
// refund (#2176) — is debited by the same arithmetic: their credit is negative.
let creditCents = 0;
for (const p of payers) {
const paid = toTripCents(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
const paid = toTripCents(p.amount, item.currency, item.exchange_rate);
ensure(p.user_id, p).cents += paid;
creditCents += paid;
}
@@ -770,9 +782,10 @@ export class BudgetService {
// from the payer sum), but converting the total separately would round to a
// different cent on a foreign-currency expense and leave the item off by one.
// With nobody down as a payer there is nothing to divide, so the recorded total
// stands in and an unpaid bill keeps reading as money owed.
// stands in and an unpaid bill keeps reading as money owed. Negative credits
// (a refund, #2176) divide the same way — only exactly zero falls back.
const hasCustomSplit = members.some(m => m.amount !== null && m.amount !== undefined);
const splitCents = creditCents > 0
const splitCents = creditCents !== 0
? creditCents
: toTripCents(item.total_price, item.currency, item.exchange_rate);
const equalShares = !hasCustomSplit ? this.splitEqualShares(splitCents, members, item.id) : {};