fix(costs): freeze the FX rate so settled expenses don't reopen when rates drift (#1335)

Settle-up transfers are stored as fixed amounts, but a foreign-currency expense was re-converted with live rates on every settlement calc. When the rate drifted, the fixed transfer no longer cancelled the re-valued expense and a few-cent residual re-opened the settled position. Foreign-currency expenses now freeze the live rate at entry time into the existing budget_items.exchange_rate column, and the settlement converts with that frozen rate when working in the trip currency. Legacy rows (exchange_rate = 1) keep using live rates, so historical data is unchanged until re-edited; rate fetch failures fall back to live rates.
This commit is contained in:
Maurice
2026-06-27 17:09:39 +02:00
committed by Maurice
parent 2277f28a57
commit aa91f009ad
6 changed files with 99 additions and 25 deletions
+4 -4
View File
@@ -136,7 +136,7 @@ export class BudgetController {
}
@Post()
create(
async create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { name?: string; category?: string; total_price?: number; persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null; reservation_id?: number },
@@ -147,7 +147,7 @@ export class BudgetController {
if (!body.name) {
throw new HttpException({ error: 'Name is required' }, 400);
}
const item = this.budget.create(tripId, body as { name: string });
const item = await this.budget.create(tripId, body as { name: string });
this.budget.broadcast(tripId, 'budget:created', { item }, socketId);
return { item };
}
@@ -181,7 +181,7 @@ export class BudgetController {
}
@Put(':id')
update(
async update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@@ -190,7 +190,7 @@ export class BudgetController {
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const updated = this.budget.update(id, tripId, body);
const updated = await this.budget.update(id, tripId, body);
if (!updated) {
throw new HttpException({ error: 'Budget item not found' }, 404);
}
+30 -2
View File
@@ -41,11 +41,39 @@ export class BudgetService {
return svc.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
}
create(tripId: string, data: Parameters<typeof svc.createBudgetItem>[1]) {
// Freeze the live FX rate at entry time into budget_items.exchange_rate so a settled
// position isn't re-opened when live rates drift later (#1335). Only for a foreign
// currency with no explicit rate; degrades to live rates if the fetch fails. On update
// it (re)freezes only when the currency changes, so an unrelated edit never moves money.
private async freezeForeignRate(
tripId: string,
data: { currency?: string | null; exchange_rate?: number },
existingItemId?: string,
): Promise<void> {
if (data.exchange_rate != null) return; // an explicit rate from the caller wins
const cur = (data.currency || '').toUpperCase();
if (!cur) return; // currency not being set in this request
if (existingItemId != null) {
const existing = db.prepare('SELECT currency FROM budget_items WHERE id = ?')
.get(existingItemId) as { currency?: string } | undefined;
if (existing && (existing.currency || '').toUpperCase() === cur) return; // currency unchanged
}
const trip = db.prepare('SELECT currency FROM trips WHERE id = ?')
.get(tripId) as { currency?: string } | undefined;
const tripCur = (trip?.currency || 'EUR').toUpperCase();
if (cur === tripCur) return; // same as the trip currency → no conversion to freeze
const rates = await getRates(tripCur);
const r = rates?.[cur];
if (r && r > 0) data.exchange_rate = r;
}
async create(tripId: string, data: Parameters<typeof svc.createBudgetItem>[1]) {
await this.freezeForeignRate(tripId, data);
return svc.createBudgetItem(tripId, data);
}
update(id: string, tripId: string, data: Parameters<typeof svc.updateBudgetItem>[2]) {
async update(id: string, tripId: string, data: Parameters<typeof svc.updateBudgetItem>[2]) {
await this.freezeForeignRate(tripId, data, id);
return svc.updateBudgetItem(id, tripId, data);
}
+12 -4
View File
@@ -349,9 +349,17 @@ export function calculateSettlement(
const rates = opts.rates ?? null;
// Amount in some currency → base. Pre-rework rows store currency = NULL, which
// means "the trip's own currency". rates[X] = units of X per 1 base.
const toBase = (amount: number, itemCurrency: string | null | undefined): number => {
const toBase = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number => {
const cur = (itemCurrency || tripCurrency).toUpperCase();
if (cur === base || !rates) return amount;
if (cur === base) return amount;
// Prefer the FX rate frozen at entry time (#1335): a settled expense keeps the rate it
// was booked at, so a later live-rate drift doesn't re-open it with a few-cent residual.
// The stored rate is units of item-currency per 1 trip-currency, so it only applies when
// converting to the trip's own currency; otherwise (and for legacy rows) use live rates.
if (base === tripCurrency && itemRate != null && itemRate > 0 && itemRate !== 1) {
return amount / itemRate;
}
if (!rates) return amount;
const r = rates[cur];
return r && r > 0 ? amount / r : amount;
};
@@ -384,11 +392,11 @@ export function calculateSettlement(
const payers = allPayers.filter(p => p.budget_item_id === item.id);
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
const paidBase = payers.reduce((a, p) => a + toBase(p.amount > 0 ? p.amount : 0, item.currency), 0);
const paidBase = payers.reduce((a, p) => a + toBase(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate), 0);
const sharePerMember = paidBase / members.length;
// Payers are credited what they actually paid (converted to base)…
for (const p of payers) ensure(p.user_id, p).balance += toBase(p.amount > 0 ? p.amount : 0, item.currency);
for (const p of payers) ensure(p.user_id, p).balance += toBase(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
// …and every split participant owes an equal share of the base total.
for (const m of members) ensure(m.user_id, m).balance -= sharePerMember;
}