Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(costs): count an expense in the display currency as typed

Mauricea37a9c0fa803
diff --git a/client/src/components/Budget/costsModel.ts b/client/src/components/Budget/costsModel.ts
index 2f3ef9a49..1c3b00c8e 100644
--- a/client/src/components/Budget/costsModel.ts
+++ b/client/src/components/Budget/costsModel.ts
@@ -32,7 +32,7 @@ export function currencyOf(e: BudgetItem, ctx: CostsCtx): string {
/** An amount of this expense in the display currency, at the rate the expense was booked at. */
export function booked(amount: number, e: BudgetItem, ctx: CostsCtx): number {
- return convertBooked(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.convert);
+ return convertBooked(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.convert, ctx.displayCurrency);
}
/**
@@ -132,7 +132,14 @@ function paymentCurrency(s: CostsSettlement, ctx: CostsCtx): string {
/** A recorded payment in the display currency, at the rate frozen when it was settled (#1445). */
export function paymentAmount(s: CostsSettlement, ctx: CostsCtx): number {
- return convertBooked(s.amount, paymentCurrency(s, ctx), s.exchange_rate, ctx.tripCurrency, ctx.convert);
+ return convertBooked(
+ s.amount,
+ paymentCurrency(s, ctx),
+ s.exchange_rate,
+ ctx.tripCurrency,
+ ctx.convert,
+ ctx.displayCurrency
+ );
}
/** The line under a payment shown converted, explained the way an expense's is (#2525). */
diff --git a/client/src/components/Budget/expenseFx.test.ts b/client/src/components/Budget/expenseFx.test.ts
index 88f10067c..fe09ac349 100644
--- a/client/src/components/Budget/expenseFx.test.ts
+++ b/client/src/components/Budget/expenseFx.test.ts
@@ -23,9 +23,14 @@ describe('editingCurrencyOf', () => {
describe('expenseFxPreview', () => {
it('previews an edit that keeps the currency at the rate frozen on entry', () => {
- const fx = expenseFxPreview({ ...base, total: 801.76, currency: 'USD' })!
+ const fx = expenseFxPreview({ ...base, total: 801.76, currency: 'USD', base: 'GBP' })!
expect(fx.inTrip).toBeCloseTo(685.26, 2)
- expect(fx.shown).toBeCloseTo(791.55, 2)
+ expect(fx.shown).toBeCloseTo(convert(801.76 / 1.17, 'EUR'), 2)
+ })
+
+ it('has nothing to preview for a bill in the display currency, which counts as typed (#2965)', () => {
+ // Frozen at 1.17 while a euro buys 1.1551 today: still the dollars typed.
+ expect(expenseFxPreview({ ...base, total: 801.76, currency: 'USD', base: 'USD' })).toBeNull()
})
it('has nothing to preview for a bill in the display currency that reads back as typed', () => {
@@ -47,8 +52,8 @@ describe('expenseFxPreview', () => {
describe('splitShareLabel', () => {
it('prints the entered share, then the share the row lends or borrows', () => {
- const fx = expenseFxPreview({ ...base, total: 801.76, currency: 'USD' })
- expect(splitShareLabel(400.88, 'USD', fx, 2, 'USD', 'en-US')).toBe('$400.88 → $395.77')
+ const fx = expenseFxPreview({ ...base, total: 1700, currency: 'JPY', editing: null })
+ expect(splitShareLabel(850, 'JPY', fx, 2, 'USD', 'en-US')).toBe(`${formatMoney(850, 'JPY', 'en-US')} → ${formatMoney(convert(1700, 'JPY') / 2, 'USD', 'en-US')}`)
// Read in the trip currency, the share is the booked euros.
const inEur = expenseFxPreview({ ...base, base: 'EUR', total: 801.76, currency: 'USD' })
expect(splitShareLabel(400.88, 'USD', inEur, 2, 'EUR', 'en-US')).toBe(`$400.88 → ${formatMoney(342.63, 'EUR', 'en-US')}`)
diff --git a/client/src/components/Budget/expenseFx.ts b/client/src/components/Budget/expenseFx.ts
index 3315dabd2..8f1eccb14 100644
--- a/client/src/components/Budget/expenseFx.ts
+++ b/client/src/components/Budget/expenseFx.ts
@@ -1,6 +1,6 @@
import { bookedInTrip, useExchangeRates } from '../../hooks/useExchangeRates'
import { useTripStore } from '../../store/tripStore'
-import { currencyDecimals, formatMoney } from '../../utils/formatters'
+import { formatMoney } from '../../utils/formatters'
/**
* The conversion preview of the expense editors, shared by the desktop ExpenseModal and the
@@ -33,8 +33,8 @@ export interface ExpenseFx {
* What the amount being edited will count as. An edit that keeps the currency keeps the rate
* frozen when the expense was entered (the server re-freezes only when the currency changes),
* so it is previewed at that rate, the way the list will show it after the save. Anything
- * else is previewed at today's rate. Null when there is nothing to convert, including a bill
- * in the display currency that still reads back as typed.
+ * else is previewed at today's rate. Null when there is nothing to convert, and for a bill in
+ * the display currency, which counts as typed (#2965).
*/
export function expenseFxPreview(args: {
total: number
@@ -46,12 +46,9 @@ export function expenseFxPreview(args: {
convert: (amount: number, from: string | null | undefined) => number
}): ExpenseFx | null {
const { total, currency, editing, editingCurrency, tripCurrency, base, convert } = args
- if (total === 0) return null
+ if (total === 0 || currency === base) return null
const inTrip = editing && currency === editingCurrency ? bookedInTrip(total, currency, editing.exchange_rate, tripCurrency) : null
- if (currency === base && inTrip == null) return null
const shown = inTrip == null ? convert(total, currency) : convert(inTrip, tripCurrency)
- const unit = 10 ** currencyDecimals(base)
- if (currency === base && Math.round(shown * unit) === Math.round(total * unit)) return null
return { inTrip, shown: inTrip != null && tripCurrency === base ? null : shown }
}
diff --git a/client/src/hooks/useExchangeRates.test.ts b/client/src/hooks/useExchangeRates.test.ts
index b096fb3da..4c589ac8a 100644
--- a/client/src/hooks/useExchangeRates.test.ts
+++ b/client/src/hooks/useExchangeRates.test.ts
@@ -182,10 +182,9 @@ describe('convertBooked', () => {
expect(convertBooked(100, 'eur', 1, 'EUR', live)).toBe(100)
})
- // #2525: a euro trip read in dollars, the bill entered in dollars. It was booked at 685.26
- // EUR, and that is what the balances and settle-up net and then show at today's rate. The
- // row has to show the same figure, or paying back the "you lent" it printed reopens the trip.
- it('reads an amount in the display currency through the trip currency too', () => {
+ // #2525: a euro trip read in dollars, the bill entered in dollars. Without the display
+ // currency the row goes through the trip currency at its frozen rate, as before.
+ it('reads an amount through the trip currency when no display currency is given', () => {
const liveUsd = (amount: number, from: string | null | undefined): number => {
const rates: Record<string, number> = { USD: 1, EUR: 1 / 1.1398 }
const r = rates[(from || 'USD').toUpperCase()]
@@ -197,6 +196,19 @@ describe('convertBooked', () => {
// Without a booked rate there is nothing to go through, and dollars stay dollars.
expect(convertBooked(801.76, 'USD', 1, 'EUR', liveUsd)).toBe(801.76)
})
+
+ // #2965: read in dollars, a bill entered in dollars counts as typed, as the balances net it.
+ it('shows a row in the display currency as typed, whatever rate it was frozen at', () => {
+ const liveUsd = (amount: number, from: string | null | undefined): number => {
+ const rates: Record<string, number> = { USD: 1, EUR: 1 / 1.1398 }
+ const r = rates[(from || 'USD').toUpperCase()]
+ return r && r > 0 ? amount / r : amount
+ }
+ expect(convertBooked(801.76, 'USD', 1.17, 'EUR', liveUsd, 'USD')).toBe(801.76)
+ expect(convertBooked(801.76, 'usd', 1.17, 'EUR', liveUsd, 'USD')).toBe(801.76)
+ // Another currency still goes through the trip currency.
+ expect(convertBooked(801.76, 'USD', 1.17, 'EUR', liveUsd, 'GBP')).toBeCloseTo((801.76 / 1.17) * 1.1398, 6)
+ })
})
describe('bookedInTrip', () => {
diff --git a/client/src/hooks/useExchangeRates.ts b/client/src/hooks/useExchangeRates.ts
index e78bc77fd..9218e5b64 100644
--- a/client/src/hooks/useExchangeRates.ts
+++ b/client/src/hooks/useExchangeRates.ts
@@ -133,8 +133,13 @@ export function convertBooked(
frozenRate: number | null | undefined,
tripCurrency: string,
convertLive: (amount: number, from: string | null | undefined) => number,
+ displayCurrency?: string,
): number {
const trip = (tripCurrency || 'EUR').toUpperCase()
+ // A row entered in the display currency is shown as typed (#2965): through the
+ // trip currency at its frozen rate and back at today's, it drifted off the
+ // amount entered, and the balances (which net such rows as typed) disagreed.
+ if (displayCurrency && (rowCurrency || trip).toUpperCase() === displayCurrency.toUpperCase()) return amount
const inTrip = bookedInTrip(amount, rowCurrency, frozenRate, trip)
if (inTrip != null) return convertLive(inTrip, trip)
// A NULL currency means the trip's own, and then there was never anything to freeze.
diff --git a/client/src/pages/sharedTrip/SharedListsViews.tsx b/client/src/pages/sharedTrip/SharedListsViews.tsx
index 89323b4cc..49842e525 100644
--- a/client/src/pages/sharedTrip/SharedListsViews.tsx
+++ b/client/src/pages/sharedTrip/SharedListsViews.tsx
@@ -92,7 +92,7 @@ export function SharedCostsView({ items, base, tripCurrency, convert }: CostsPro
const { t, locale } = useTranslation()
if (items.length === 0) return <EmptySection icon={<Wallet size={22} />} text={t('shared.emptyCosts')} />
const amountOf = (i: Expense) => Number.parseFloat(String(i.total_price ?? '')) || 0
- const valueOf = (i: Expense) => convertBooked(amountOf(i), i.currency, i.exchange_rate, tripCurrency, convert)
+ const valueOf = (i: Expense) => convertBooked(amountOf(i), i.currency, i.exchange_rate, tripCurrency, convert, base)
// In the reader's own number format with the currency's code: a public page has
// no idea where its reader is, and "$" alone does not say which dollar.
// Whole cents: a converted amount otherwise printed a third decimal.
diff --git a/server/src/nest/budget/budget.service.ts b/server/src/nest/budget/budget.service.ts
index 4469f92c3..130429986 100644
--- a/server/src/nest/budget/budget.service.ts
+++ b/server/src/nest/budget/budget.service.ts
@@ -1124,6 +1124,15 @@ export class BudgetService {
// Every figure goes out in whole steps of that currency: whole won or yen (#2604).
const displayUnit = 10 ** Math.max(0, 2 - currencyDecimals(currency));
const toDisplay = (cents: number[], total?: number) => allocateDisplayCents(cents, displayFactor, total, displayUnit);
+ // An expense entered in the display currency itself is owed in that currency
+ // (#2965). Booked through the trip currency at its frozen rate and back at
+ // today's, 1,081.09 EUR on a yen trip came back a day later as 1,078.86 EUR,
+ // and a repayment of exactly what was typed left 2.23 EUR owed. Such rows are
+ // netted apart, in whole display cents as entered; every other row still nets
+ // in trip cents and converts once, so Σ balances stays 0 in both halves.
+ const direct = currency !== tripCurrency ? currency : null;
+ const isDirect = (rowCurrency: string | null | undefined) =>
+ direct !== null && (rowCurrency || tripCurrency).toUpperCase() === direct;
// A recorded settle-up amount is entered in whatever display currency the payer
// was viewing. New rows capture that currency and the rate frozen at settle time
// (#1445), so a settled position stays balanced when live rates drift — mirroring
@@ -1149,9 +1158,15 @@ export class BudgetService {
// and rounded to a cent once, at the boundary — from there on the ledger is
// integer arithmetic, so Σ(balances) is exactly 0 and no sub-cent residual can
// build up behind the two-decimal figures the user sees (#1382).
- const balances: Record<number, { user_id: number; username: string; avatar_url: string | null; cents: number }> = {};
+ // `direct` is the half in display cents (#2965), see isDirect above.
+ const balances: Record<
+ number,
+ { user_id: number; username: string; avatar_url: string | null; cents: number; direct: number }
+ > = {};
const ensure = (id: number, src: { username?: string; avatar?: string | null }) => {
- if (!balances[id]) balances[id] = { user_id: id, username: src.username || '', avatar_url: avatarUrl(src), cents: 0 };
+ if (!balances[id]) {
+ balances[id] = { user_id: id, username: src.username || '', avatar_url: avatarUrl(src), cents: 0, direct: 0 };
+ }
return balances[id];
};
// The two halves of the balance, kept apart so the per-person final budget can
@@ -1161,10 +1176,16 @@ export class BudgetService {
// are derived from.
const frontedCents: Record<number, number> = {};
const reimbursedCents: Record<number, number> = {};
+ const frontedDirect: Record<number, number> = {};
+ const reimbursedDirect: Record<number, number> = {};
// ...and the rows they are made of, so the breakdown lists them in these same
// cents rather than converting the expense list a second time on the client.
- const frontedRows: Record<number, { item_id: number; cents: number }[]> = {};
- const movedRows: Record<number, { settlement_id: number; from_user_id: number; to_user_id: number; cents: number }[]> = {};
+ // `cents` is the trip-cent part each row is converted from, `direct` the part already in display cents.
+ const frontedRows: Record<number, { item_id: number; cents: number; direct: number }[]> = {};
+ const movedRows: Record<
+ number,
+ { settlement_id: number; from_user_id: number; to_user_id: number; cents: number; direct: number }[]
+ > = {};
// Read in the trip currency, those figures are the ledger's own trip cents. Read in
// another one, they are built from each row's unrounded trip amount instead: a trip
// cent is worth more than a dollar cent on a euro trip, so a bill of 12,345.67 USD
@@ -1175,7 +1196,8 @@ export class BudgetService {
for (const item of items) {
// Before anything else, planning-only and unpaid rows included: a row no rate can
// convert is reported whole and moves nothing, credits and shares alike.
- const convert = converterFor(item.currency, item.exchange_rate);
+ const inDisplay = isDirect(item.currency);
+ const convert = inDisplay ? (amount: number) => amount : converterFor(item.currency, item.exchange_rate);
if (!convert) {
unconvertedItems.push(item.id);
unconvertedCurrencies.add((item.currency || '').toUpperCase());
@@ -1210,9 +1232,16 @@ export class BudgetService {
for (const p of payers) {
const exact = convert(p.amount) * 100;
const paid = Math.round(exact);
- ensure(p.user_id, p).cents += paid;
- frontedCents[p.user_id] = (frontedCents[p.user_id] || 0) + finalUnit(exact);
- if (paid !== 0) (frontedRows[p.user_id] ??= []).push({ item_id: item.id, cents: finalUnit(exact) });
+ const payer = ensure(p.user_id, p);
+ if (inDisplay) {
+ payer.direct += paid;
+ frontedDirect[p.user_id] = (frontedDirect[p.user_id] || 0) + paid;
+ if (paid !== 0) (frontedRows[p.user_id] ??= []).push({ item_id: item.id, cents: 0, direct: paid });
+ } else {
+ payer.cents += paid;
+ frontedCents[p.user_id] = (frontedCents[p.user_id] || 0) + finalUnit(exact);
+ if (paid !== 0) (frontedRows[p.user_id] ??= []).push({ item_id: item.id, cents: finalUnit(exact), direct: 0 });
+ }
creditCents += paid;
}
// …and each split participant owes their share — a custom per-member amount
@@ -1231,7 +1260,9 @@ export class BudgetService {
? customSplitCents(members, convert, creditCents, sumMinor(payers.map(p => p.amount)))
: splitEqualShares(creditCents, members, item.id);
for (const m of members) {
- ensure(m.user_id, m).cents -= shares[m.user_id] || 0;
+ const member = ensure(m.user_id, m);
+ if (inDisplay) member.direct -= shares[m.user_id] || 0;
+ else member.cents -= shares[m.user_id] || 0;
}
}
@@ -1242,7 +1273,9 @@ export class BudgetService {
// surfaces as an amount still to square up instead of silently vanishing.
const settlements = await this.listSettlements(tripId);
const ensureSettled = (id: number, username: string | undefined, avatar_url: string | null | undefined) => {
- if (!balances[id]) balances[id] = { user_id: id, username: username || '', avatar_url: avatar_url ?? null, cents: 0 };
+ if (!balances[id]) {
+ balances[id] = { user_id: id, username: username || '', avatar_url: avatar_url ?? null, cents: 0, direct: 0 };
+ }
return balances[id];
};
for (const s of settlements) {
@@ -1252,12 +1285,26 @@ export class BudgetService {
unconvertedCurrencies.add((s.currency || '').toUpperCase());
continue;
}
+ const from = ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url);
+ const to = ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url);
+ // A transfer in the display currency first pays what the payer owes the
+ // receiver in display-currency expenses, as typed (#2965); only the rest
+ // goes through the trip currency at its frozen rate, which keeps a debt
+ // in the trip currency settled when rates move (#1445).
+ const total = Math.round(s.amount * 100);
+ const room = isDirect(s.currency) ? Math.max(0, Math.min(-from.direct, to.direct)) : 0;
+ const paidDirect = total > 0 ? Math.min(total, room) : 0;
+ from.direct += paidDirect;
+ to.direct -= paidDirect;
+ reimbursedDirect[s.to_user_id] = (reimbursedDirect[s.to_user_id] || 0) + paidDirect;
+ reimbursedDirect[s.from_user_id] = (reimbursedDirect[s.from_user_id] || 0) - paidDirect;
// Rounded to a trip cent per transfer, so recording one in a display currency
// can't leave a sliver of a cent behind to accumulate over a trip's lifetime.
- const exact = convert(s.amount) * 100;
+ const rest = total === 0 ? 0 : (total - paidDirect) / total;
+ const exact = convert(s.amount) * 100 * rest;
const inTrip = Math.round(exact);
- ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url).cents += inTrip;
- ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url).cents -= inTrip;
+ from.cents += inTrip;
+ to.cents -= inTrip;
// Net of the transfers in both directions: sending one back is a reimbursement
// received in reverse, and netting them is what keeps the final budget's
// subtraction equal to the balance it is taken from.
@@ -1265,23 +1312,32 @@ export class BudgetService {
reimbursedCents[s.to_user_id] = (reimbursedCents[s.to_user_id] || 0) + shown;
reimbursedCents[s.from_user_id] = (reimbursedCents[s.from_user_id] || 0) - shown;
const moved = { settlement_id: s.id, from_user_id: s.from_user_id, to_user_id: s.to_user_id };
- (movedRows[s.to_user_id] ??= []).push({ ...moved, cents: shown });
- (movedRows[s.from_user_id] ??= []).push({ ...moved, cents: -shown });
+ (movedRows[s.to_user_id] ??= []).push({ ...moved, cents: shown, direct: paidDirect });
+ (movedRows[s.from_user_id] ??= []).push({ ...moved, cents: -shown, direct: -paidDirect });
}
// Into the display currency as one set, then simplify — balances and flows are
// derived from the same integers, so what the balances say is owed is exactly
// what "Settle up" offers to move, down to the last cent (#1382).
const ledger = Object.values(balances);
- const displayCents = toDisplay(ledger.map(b => b.cents));
+ // The trip-cent half converts as one set; the direct half is display cents already.
+ const displayCents = toDisplay(ledger.map(b => b.cents)).map((cents, i) => cents + ledger[i].direct);
// Each component of the final budget is re-denominated as its own set, for the
// same reason the balances are: rounding one person at a time lets the column
// drift away from the figure it converted from. The final itself is then
// subtracted in display cents rather than converted separately, so the three
// lines the breakdown shows always add up to the total beside them, whatever
// currency the viewer picked.
- const frontedDisplayCents = toDisplay(ledger.map(b => frontedCents[b.user_id] || 0));
- const reimbursedDisplayCents = toDisplay(ledger.map(b => reimbursedCents[b.user_id] || 0));
+ const frontedViaTrip = toDisplay(ledger.map(b => frontedCents[b.user_id] || 0));
+ const reimbursedViaTrip = toDisplay(ledger.map(b => reimbursedCents[b.user_id] || 0));
+ const frontedDisplayCents = frontedViaTrip.map((cents, i) => cents + (frontedDirect[ledger[i].user_id] || 0));
+ const reimbursedDisplayCents = reimbursedViaTrip.map((cents, i) => cents + (reimbursedDirect[ledger[i].user_id] || 0));
+ // A row list against its figure: the trip-cent parts split the converted half
+ // the same largest-remainder way, the direct parts are added as they are.
+ const rowsToDisplay = <R extends { cents: number; direct: number }>(rows: R[], viaTrip: number) => {
+ const converted = toDisplay(rows.map(r => r.cents), viaTrip);
+ return rows.map((r, k) => converted[k] + r.direct);
+ };
// Calculate optimized payment flows (greedy algorithm)
const people = ledger
@@ -1323,8 +1379,8 @@ export class BudgetService {
// figure as the target, so each list adds up to the line it sits under.
const fronted = frontedRows[b.user_id] || [];
const moved = movedRows[b.user_id] || [];
- const frontedDisplay = toDisplay(fronted.map(r => r.cents), frontedDisplayCents[i]);
- const movedDisplay = toDisplay(moved.map(r => r.cents), reimbursedDisplayCents[i]);
+ const frontedDisplay = rowsToDisplay(fronted, frontedViaTrip[i]);
+ const movedDisplay = rowsToDisplay(moved, reimbursedViaTrip[i]);
return {
user_id: b.user_id, username: b.username, avatar_url: b.avatar_url,
expenses: frontedDisplayCents[i] / 100,
@@ -1333,7 +1389,12 @@ export class BudgetService {
final: (frontedDisplayCents[i] - reimbursedDisplayCents[i] - displayCents[i]) / 100,
sources: {
fronted: fronted.map((r, k) => ({ item_id: r.item_id, cents: frontedDisplay[k] })),
- moved: moved.map((r, k) => ({ ...r, cents: movedDisplay[k] })),
+ moved: moved.map((r, k) => ({
+ settlement_id: r.settlement_id,
+ from_user_id: r.from_user_id,
+ to_user_id: r.to_user_id,
+ cents: movedDisplay[k],
+ })),
// The flows are display cents already, and the greedy pass drains every
// balance completely, so the flows on a person's side sum to their balance.
outstanding: flows
diff --git a/server/tests/unit/nest/budget.service.calc.test.ts b/server/tests/unit/nest/budget.service.calc.test.ts
index ba30a783a..b78437726 100644
--- a/server/tests/unit/nest/budget.service.calc.test.ts
+++ b/server/tests/unit/nest/budget.service.calc.test.ts
@@ -1268,7 +1268,7 @@ describe('calculateSettlement: unconverted rows', () => {
it('baseRate never converts a row', async () => {
await setupDb(
- [{ ...makeItem(1, 100), currency: 'EUR', exchange_rate: 1 } as BudgetItem],
+ [{ ...makeItem(1, 100), currency: 'USD', exchange_rate: 1 } as BudgetItem],
[makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
[makePayer(1, 1, 100, 'alice')],
);
@@ -1280,9 +1280,25 @@ describe('calculateSettlement: unconverted rows', () => {
baseRate: 0.61,
});
expect(result.currency).toBe('EUR');
- expect(result.unconverted).toEqual({ item_ids: [1], settlement_ids: [], currencies: ['EUR'] });
+ expect(result.unconverted).toEqual({ item_ids: [1], settlement_ids: [], currencies: ['USD'] });
expect(result.balances).toEqual([]);
});
+
+ it('a bill in the display currency needs no rate at all: it counts as typed (#2965)', async () => {
+ await setupDb(
+ [{ ...makeItem(1, 100), currency: 'EUR', exchange_rate: 1 } as BudgetItem],
+ [makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')],
+ [makePayer(1, 1, 100, 'alice')],
+ );
+ const result = await budget.calculateSettlement(1, {
+ base: 'EUR',
+ tripCurrency: 'AUD',
+ rates: null,
+ baseRate: 0.61,
+ });
+ expect(result.unconverted).toEqual(none);
+ expect(result.balances.map((b) => b.balance)).toEqual([50, -50]);
+ });
});
// ── Currencies shown without decimals (#2604) ────────────────────────────────
@@ -1546,3 +1562,75 @@ describe('applySettlementUpdate', () => {
expect(res).toMatchObject({ id: 7, from_user_id: 2, to_user_id: 1, amount: 10.13 });
});
});
+
+// ── A bill in the display currency counts as typed (#2965) ──────────────────
+// A yen trip read in euros, the flight entered in euros: booked through the yen
+// at its frozen rate and back at today's, 1,081.09 EUR came back as 1,078.86 EUR
+// a day later, and repaying exactly what was typed left 2.23 EUR owed.
+
+describe('calculateSettlement: bills in the display currency (#2965)', () => {
+ // The flight was frozen at 176.37 yen per euro; today a euro buys 176.73.
+ const flight = () => [{ ...makeItem(1, 1081.09), currency: 'EUR', exchange_rate: 1 / 176.37 } as BudgetItem];
+ const pair = () => [makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob')];
+ const paid = () => [makePayer(1, 1, 1081.09, 'alice')];
+ const today = { base: 'EUR', tripCurrency: 'JPY', rates: { JPY: 1, EUR: 1 / 176.73 } };
+
+ it('owes half of what was typed, whatever the rate did since', async () => {
+ await setupDb(flight(), pair(), paid());
+ const result = await budget.calculateSettlement(1, today);
+ expect(result.currency).toBe('EUR');
+ expect(centSum(result.balances.map((b) => b.balance))).toBe(0);
+ const [alice, bob] = result.balances.map((b) => b.balance);
+ expect([540.54, 540.55]).toContain(alice);
+ expect(bob).toBe(-alice);
+ const fronted = result.finalBudgets.find((f) => f.user_id === 1)!;
+ expect(fronted.expenses).toBe(1081.09);
+ expect(fronted.sources.fronted).toEqual([{ item_id: 1, cents: 108109 }]);
+ });
+
+ it('a repayment of exactly what is owed in euros squares the trip, frozen at any rate', async () => {
+ await setupDb(flight(), pair(), paid());
+ const owed = (await budget.calculateSettlement(1, today)).flows[0].amount;
+ // Bob pays the euros the flow names, frozen at today's yen rate.
+ await setupDb(flight(), pair(), paid(), [makeSettlementRow(5, 2, 1, owed, 'EUR', 1 / 176.73)]);
+ for (const eurPerYen of [1 / 176.73, 1 / 170, 1 / 185]) {
+ const result = await budget.calculateSettlement(1, { ...today, rates: { JPY: 1, EUR: eurPerYen } });
+ expect(result.balances.map((b) => b.balance)).toEqual([0, 0]);
+ expect(result.flows).toEqual([]);
+ for (const f of result.finalBudgets) expect(f.final).toBeCloseTo(f.user_id === 1 ? 1081.09 - owed : owed, 2);
+ }
+ });
+
+ it('a euro payment beyond the euro debt pays the yen debt at its frozen rate (#1445 stays)', async () => {
+ // A yen dinner on top: Bob owes 540.55 EUR for the flight and 5,000 yen for dinner.
+ await setupDb(
+ [...flight(), { ...makeItem(2, 10000) } as BudgetItem],
+ [...pair(), makeMember(2, 1, 'alice'), makeMember(2, 2, 'bob')],
+ [...paid(), makePayer(2, 1, 10000, 'alice')],
+ );
+ const before = await budget.calculateSettlement(1, today);
+ const owed = before.flows[0].amount;
+ await setupDb(
+ [...flight(), { ...makeItem(2, 10000) } as BudgetItem],
+ [...pair(), makeMember(2, 1, 'alice'), makeMember(2, 2, 'bob')],
+ [...paid(), makePayer(2, 1, 10000, 'alice')],
+ [makeSettlementRow(5, 2, 1, owed, 'EUR', 1 / 176.73)],
+ );
+ // Settled at today's rate it squares the trip; the yen part keeps its frozen rate,
+ // so it stays within a cent when the yen moves afterwards.
+ const now = await budget.calculateSettlement(1, today);
+ expect(now.balances.map((b) => b.balance)).toEqual([0, 0]);
+ const later = await budget.calculateSettlement(1, { ...today, rates: { JPY: 1, EUR: 1 / 160 } });
+ for (const b of later.balances) expect(Math.abs(b.balance)).toBeLessThanOrEqual(0.01);
+ expect(centSum(later.balances.map((b) => b.balance))).toBe(0);
+ });
+
+ it('read in the trip currency nothing changes: the bill goes through its frozen rate', async () => {
+ await setupDb(flight(), pair(), paid());
+ const result = await budget.calculateSettlement(1, { base: 'JPY', tripCurrency: 'JPY', rates: null });
+ expect(result.currency).toBe('JPY');
+ // 1,081.09 EUR at 176.37 is 190,672 yen (whole yen), half each.
+ expect(centSum(result.balances.map((b) => b.balance))).toBe(0);
+ expect(Math.abs(result.balances[0].balance)).toBeCloseTo(95336, -1);
+ });
+});