fix(costs): read an expense entered in the display currency as it was typed (#2525)

A euro trip read in dollars books a bill entered in dollars at the rate
of the day, from the euro's quote: 12,345.67 USD at 1.1398 is 10,831.44
EUR. The Costs screen and the settlement then turned those euros back
into dollars with the dollar's own quote, 1 / 0.87732. Frankfurter
rounds the two quotes separately, so they are not exact inverses, and
the bill read $12,346.05 the moment it was saved, a $250.00 one $250.01.
The error grows with the amount, which is why the large rows showed it
first. Paying back what settle-up offered for such a bill left the trip
open with the debt flipped the other way.

Both sides now convert trip money to the display currency with the trip
currency's own quote, the one every entry rate is frozen from. On the
server, settlement() fetches that quote for the REST route and for the
MCP get_settlement_summary tool, which now makes the same call, and a
legacy transfer without a currency reads back through the same factor.
On the client, useExchangeRates takes the trip currency as an anchor
and converts through its cached quote, falling back to the display
currency's while it is missing, so it works offline from cache and
needs no change to the settlement response. The final budget builds
each row from the unrounded trip amount, because a euro cent is worth
more than a dollar cent and 10,831.44 EUR came back as 12,345.68; the
balances and settle-up still net whole trip cents.

A same-day bill in the display currency now reads exactly as typed on
the row, the payer chip, the day header, the totals, Outstanding and
the final budget, on both shells and on the shared trip page, and
paying the amount settle-up offers leaves both balances at zero. When
the rate really moved, the row keeps the value the totals count, with
what was entered and the euros it was booked at underneath, "$801.76 ->
685,26 EUR". One helper builds that line for the desktop list, the
phone list, payments, the final budget breakdown and the shared page;
it prints nothing for an amount of 0 or a bill that reads as typed.

The expense editors share one module for their preview. The split
summary puts the share the row lends or borrows next to the entered
one, "$400.88 -> $390.53 each", and an expense saved without a currency
still opens in the trip currency. Both CSV exports add the amount in
the trip currency when it differs from the display currency.

Kept from before: the desktop totals recompute when rates arrive, a
booking's linked costs are labelled in the trip currency (every linked
row, the link picker and the phone's linked costs), a legacy
transfer is read in the display currency, the shared page reads the
frozen rate in whole cents, a booking import keeps the currency it was
quoted in at a rate frozen before the write (REST and plugin RPC), and
the MCP trip summary, the budget-overview prompt and the per-person
summary add every row up in trip cents at its frozen rate. The
packing-list prompt reads the trip title directly instead of building
the whole summary, which could wait on a rates fetch.
This commit is contained in:
Maurice
2026-09-25 19:48:12 +02:00
parent 6ed2561c63
commit 44a12e21fc
47 changed files with 1938 additions and 233 deletions
+106
View File
@@ -597,6 +597,112 @@ describe('SharedTripPage', () => {
});
});
describe('FE-PAGE-SHARED-043: a foreign expense reads at the rate it was booked at, as in Costs (#2525)', () => {
it('shows the frozen-rate value in whole cents, not today\'s rate', async () => {
// CHF so no earlier test has cached rates for this base. Today 1 CHF buys 1.1395
// USD; the expense froze 1.17 when it was entered. Costs reads 801.76 / 1.17 =
// 685.26 CHF. Today's rate alone gives 703.61, printed as "703.607".
server.use(
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([{ quote: 'USD', rate: 1.1395 }])),
http.get('/api/shared/:token', ({ params }) => {
if (params.token !== 'booked-token') return;
return HttpResponse.json({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01', end_date: '2026-07-05', currency: 'CHF' },
baseCurrency: 'CHF',
days: [], assignments: {}, dayNotes: {}, places: [], reservations: [], accommodations: [], packing: [],
budget: [
{ id: 1, name: 'Aparthotel Silver', total_price: 801.76, category: 'Accommodation', currency: 'USD', exchange_rate: 1.17 },
{ id: 2, name: 'Tram pass', total_price: 100, category: 'Transport', currency: null, exchange_rate: 1 },
],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
collab: [],
});
}),
);
renderSharedTrip('booked-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getByText('Aparthotel Silver')).toBeInTheDocument());
// Row and its category both read the booked value; the trip total adds the
// 100 CHF tram pass to it.
await waitFor(() => expect(screen.getAllByText('685.26 CHF')).toHaveLength(2));
expect(screen.getByText('785.26 CHF')).toBeInTheDocument();
expect(screen.queryByText(/703\.6/)).toBeNull();
// What was entered stays beside the converted row, as the Costs list shows it.
expect(screen.getByText('· 801.76 USD')).toBeInTheDocument();
});
it('reads a same-day bill in the display currency exactly as typed, with the trip currency\'s quote', async () => {
// ZAR trip read in USD (ZAR so no earlier test has cached its rates). The bill froze
// 0.05911 USD per rand, today's ZAR quote. The USD quote, 16.918 rand per dollar, is
// rounded on its own and is not its inverse.
server.use(
http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => {
const base = new URL(request.url).searchParams.get('base');
return HttpResponse.json(base === 'ZAR' ? [{ quote: 'USD', rate: 0.05911 }] : [{ quote: 'ZAR', rate: 16.918 }]);
}),
http.get('/api/shared/:token', ({ params }) => {
if (params.token !== 'same-day-token') return;
return HttpResponse.json({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01', end_date: '2026-07-05', currency: 'ZAR' },
baseCurrency: 'USD',
days: [], assignments: {}, dayNotes: {}, places: [], reservations: [], accommodations: [], packing: [],
budget: [
{ id: 1, name: 'Villa', total_price: 12345.67, category: 'Accommodation', currency: 'USD', exchange_rate: 0.05911 },
],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
collab: [],
});
}),
);
renderSharedTrip('same-day-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getAllByText('12,345.67 USD')).toHaveLength(3));
expect(screen.queryByText(/^· /)).toBeNull();
});
it('reads a bill in the display currency through the trip currency too, beside what was entered', async () => {
// The owner reads in USD on a CHF trip. The USD bill was booked at 685.26 CHF,
// which today is 780.86 USD, the figure Costs and its balances use; the CHF one
// converts at today's rate (100 CHF = 113.95 USD).
server.use(
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([{ quote: 'CHF', rate: 1 / 1.1395 }])),
http.get('/api/shared/:token', ({ params }) => {
if (params.token !== 'display-token') return;
return HttpResponse.json({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01', end_date: '2026-07-05', currency: 'CHF' },
baseCurrency: 'USD',
days: [], assignments: {}, dayNotes: {}, places: [], reservations: [], accommodations: [], packing: [],
budget: [
{ id: 1, name: 'Aparthotel Silver', total_price: 801.76, category: 'Accommodation', currency: 'USD', exchange_rate: 1.17 },
{ id: 2, name: 'Tram pass', total_price: 100, category: 'Transport', currency: null, exchange_rate: 1 },
],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
collab: [],
});
}),
);
renderSharedTrip('display-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getAllByText('113.95 USD')).toHaveLength(2));
expect(screen.getAllByText('780.86 USD')).toHaveLength(2);
expect(screen.getByText('894.81 USD')).toBeInTheDocument();
expect(screen.getByText('· 801.76 USD')).toBeInTheDocument();
expect(screen.getByText('· 100.00 CHF')).toBeInTheDocument();
});
});
// FE-PAGE-SHARED-021 to FE-PAGE-SHARED-037 drive the remaining render branches of
// the page: header variants, the permission-driven tab strip, and every item kind
// the day timeline, bookings, packing, costs and chat sections can produce.
+28 -9
View File
@@ -27,13 +27,14 @@ import { getCategoryIcon } from '../components/shared/categoryIcons';
import PublicLanguagePicker from '../components/shared/PublicLanguagePicker';
import { OFM_POSITRON, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, MAP_MAX_ZOOM, attributionForTile } from '../constants/mapDefaults';
import VectorBasemap from '../components/Map/VectorBasemap';
import { convertBooked, convertedLine } from '../hooks/useExchangeRates';
import { useTranslation } from '../i18n';
import { avatarSrc } from '../utils/avatarSrc';
import { safeHexColor } from '../utils/safeColor';
import { getMergedItems, getTransportForDay, hidesOnMiddleDay } from '../utils/dayMerge';
import { isDayInAccommodationRange } from '../utils/dayOrder';
import { getFlightLegs, getTrainLegs } from '../utils/flightLegs';
import { splitReservationDateTime } from '../utils/formatters';
import { currencyDecimals, splitReservationDateTime } from '../utils/formatters';
import { computeMapViewport, TILE_SIZE_RASTER } from '../utils/mapViewport';
import { resolveBasemap } from '../utils/tileUrl';
import { useSharedTrip } from './sharedTrip/useSharedTrip';
@@ -981,16 +982,31 @@ export default function SharedTripPage() {
{activeTab === 'budget' &&
(budget || []).length > 0 &&
(() => {
// Pre-rework rows store currency = NULL ("the trip's own currency"); convert
// each expense into the owner's display base via live FX, mirroring CostsPanel.
const curOf = (i: any) => i.currency || trip.currency || base;
// Pre-rework rows store currency = NULL ("the trip's own currency"). Each
// expense is read the way CostsPanel reads it (#2525): at the rate frozen when
// it was entered, into the trip currency, then into the owner's display base.
// Reading it at today's rate alone made the shared page disagree with the
// trip's own Costs tab.
type Expense = { total_price?: number | string | null; currency?: string | null; exchange_rate?: number | null };
const tripCurrency = String(trip.currency || base).toUpperCase();
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);
// Whole cents: a converted amount otherwise printed a third decimal.
const money = (v: number) =>
v.toLocaleString(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
// What was entered, beside a row shown converted, as the Costs list prints it.
const enteredOf = (i: Expense): string | null => {
const entered = convertedLine(amountOf(i), i.currency, i.exchange_rate, tripCurrency, base, valueOf(i))?.entered;
if (!entered) return null;
const d = currencyDecimals(entered.currency);
return `${entered.amount.toLocaleString(locale, { minimumFractionDigits: d, maximumFractionDigits: d })} ${entered.currency}`;
};
const grouped = (budget || []).reduce((g: any, i: any) => {
const c = i.category || t('shared.other');
(g[c] = g[c] || []).push(i);
return g;
}, {});
const sumIn = (items: any[]) =>
items.reduce((s: number, i: any) => s + convert(Number.parseFloat(i.total_price) || 0, curOf(i)), 0);
const sumIn = (items: any[]) => items.reduce((s: number, i: any) => s + valueOf(i), 0);
const total = sumIn(budget || []);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
@@ -1015,7 +1031,7 @@ export default function SharedTripPage() {
{t('shared.totalBudget')}
</div>
<div style={{ fontSize: 'calc(28px * var(--fs-scale-title, 1))', fontWeight: 700, marginTop: 4 }}>
{total.toLocaleString(locale, { minimumFractionDigits: 2 })} {base}
{money(total)} {base}
</div>
</div>
{/* By category */}
@@ -1045,7 +1061,7 @@ export default function SharedTripPage() {
className="text-[#6b7280]"
style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600 }}
>
{sumIn(items).toLocaleString(locale, { minimumFractionDigits: 2 })} {base}
{money(sumIn(items))} {base}
</span>
</div>
{items.map((item: any) => (
@@ -1061,13 +1077,16 @@ export default function SharedTripPage() {
>
<span className="text-[#111827]" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>
{item.name}
{item.total_price && enteredOf(item) ? (
<span className="text-content-faint"> · {enteredOf(item)}</span>
) : null}
</span>
<span
className="text-[#111827]"
style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}
>
{item.total_price
? `${convert(Number.parseFloat(item.total_price) || 0, curOf(item)).toLocaleString(locale, { minimumFractionDigits: 2 })} ${base}`
? `${money(valueOf(item))} ${base}`
: '—'}
</span>
</div>
+2 -1
View File
@@ -77,7 +77,8 @@ export function useSharedTrip() {
// Convert every expense into it via live FX, mirroring CostsPanel — a public
// viewer has no settings store, so the base comes from the payload (#1361).
const base = String(data?.baseCurrency || data?.trip?.currency || 'EUR').toUpperCase()
const { convert } = useExchangeRates(base)
// Anchored on the trip currency's quote, as the Costs tab converts (#2525).
const { convert } = useExchangeRates(base, data?.trip?.currency)
return {
data,