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
@@ -8,10 +8,10 @@ import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetFooter, FormSheetHeader }
import { useTranslation } from '../../../../i18n'
import { useToast } from '../../../../components/shared/Toast'
import { useTripStore } from '../../../../store/tripStore'
import { useExchangeRates } from '../../../../hooks/useExchangeRates'
import { formatMoney, localizeAmountInput, amountToInputString } from '../../../../utils/formatters'
import { openFile } from '../../../../utils/fileDownload'
import { saveWithReceipts } from '../../../../components/Budget/receiptUploads'
import { splitShareLabel, useExpenseFx } from '../../../../components/Budget/expenseFx'
import { SYMBOLS, SPLIT_COLORS, currenciesWith } from '../../../../components/Budget/BudgetPanel.constants'
import { COST_CATEGORY_LIST, catMeta } from '../../../../components/Budget/costsCategories'
import { localToday } from '../../../../components/Planner/today'
@@ -58,8 +58,9 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
const { t, locale } = useTranslation()
const toast = useToast()
const { addBudgetItem, updateBudgetItem, deleteBudgetItem } = useTripStore()
const { convert } = useExchangeRates(base)
const sym = (c: string) => SYMBOLS[c] || (c + ' ')
// A saved expense without a currency opens in the trip's own (#2525), as on desktop.
const { tripCurrency: tripCur, editingCurrency, preview } = useExpenseFx(base, editing)
// Internal open flag so the exit animation still plays even though the parent
// unmounts us on close.
@@ -75,13 +76,13 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
const [cat, setCat] = useState<string>(editing ? catMeta(editing.category).key : (prefill?.category || 'food'))
const [catOpen, setCatOpen] = useState(false)
const [note, setNote] = useState(() => readUserNote(editing))
const [currency, setCurrency] = useState((editing?.currency || base).toUpperCase())
const [currency, setCurrency] = useState(editingCurrency)
const [day, setDay] = useState(editing?.expense_date || localToday())
// Edit and prefill seeds are padded to the currency's decimals (#2175), same
// as the desktop modal: a saved 4,90 must reopen as "4,90", not "4,9". A
// prefill has no currency of its own and is read as `base`.
const [total, setTotal] = useState<string>(() => {
if (editing) return editing.total_price ? amountToInputString(editing.total_price, (editing.currency || base).toUpperCase()) : ''
if (editing) return editing.total_price ? amountToInputString(editing.total_price, editingCurrency) : ''
if (prefill?.amount != null) return amountToInputString(prefill.amount, base)
return ''
})
@@ -151,6 +152,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
const ticketInfo = useMemo(() => calculateTicketShares(ticketItems), [ticketItems])
const totalNum = isTicketMode ? ticketInfo.total : (Number.parseFloat(total) || 0)
const fx = preview(totalNum, currency)
const splitSum = [...participants].reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0)
const customBalanced = Math.round(splitSum * 100) === Math.round(totalNum * 100)
const each = participants.size > 0 ? totalNum / participants.size : 0
@@ -404,12 +406,18 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
</div>
{/* CONVERSION HINT */}
{currency !== base && totalNum !== 0 && (
{fx && (
<div className="mt-2 flex flex-wrap items-center gap-2 rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[9px] text-[0.71875rem] text-m-muted">
<span>{formatMoney(totalNum, currency, locale)}</span>
<span className="text-m-faint">≈</span>
<span className="font-semibold text-m-ink">{formatMoney(convert(totalNum, currency), base, locale)}</span>
<span className="text-m-faint">· {t('costs.liveRate')}</span>
{fx.inTrip != null && <>
<span className="text-m-faint">→</span>
<span className={fx.shown == null ? 'font-semibold text-m-ink' : undefined}>{formatMoney(fx.inTrip, tripCur, locale)}</span>
</>}
{fx.shown != null && <>
<span className="text-m-faint">≈</span>
<span className="font-semibold text-m-ink">{formatMoney(fx.shown, base, locale)}</span>
<span className="text-m-faint">· {t('costs.liveRate')}</span>
</>}
</div>
)}
@@ -646,12 +654,12 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
<div className="mt-2 text-[0.71875rem]">
{splitMode === 'equally' ? (
<span className="text-m-faint">
{participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: sym(currency) + each.toFixed(2) })}
{participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, sym, locale) })}
</span>
) : (
<span className={`font-semibold ${customBalanced ? 'text-[color:var(--m-st-confirmed)]' : 'text-[color:var(--m-st-danger)]'}`}>
{customBalanced
? t('costs.splitSummary', { count: participants.size, amount: sym(currency) + each.toFixed(2) })
? t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, sym, locale) })
: `${sym(currency)}${splitSum.toFixed(2)} / ${sym(currency)}${totalNum.toFixed(2)}`}
</span>
)}
@@ -45,7 +45,8 @@ export default function MLinkedCosts({ reservationId = null, placeId = null, hin
const [picking, setPicking] = useState(false)
const [query, setQuery] = useState('')
const money = (item: BudgetItem) => formatMoney(item.total_price, item.currency || base, locale)
// In the expense's own currency; one saved without a currency is in the trip's (#2525).
const money = (item: BudgetItem) => formatMoney(item.total_price, item.currency || tripCurrency || base, locale)
const remove = async (item: BudgetItem) => {
if (!tripId) return
try { await deleteBudgetItem(tripId, item.id) } catch { toast.error(t('common.unknownError')) }
@@ -12,6 +12,7 @@ import { BookingCodeInput } from '../../../../components/shared/BookingCode'
import AirportSelect, { type Airport } from '../../../../components/Planner/AirportSelect'
import LocationSelect, { type LocationPoint } from '../../../../components/Planner/LocationSelect'
import { toLocationPicks } from '../../../../components/Planner/locationPicks'
import { importedPriceEntry } from '../../../../components/Planner/importedPrice'
import TransitSearchPanel from '../../../../components/Planner/TransitSearchPanel'
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
import MBookingFilesCosts from './MBookingFilesCosts'
@@ -572,11 +573,8 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
// Imported booking → auto-create the linked cost from the parsed price
// (only on create and only when a price is present).
if (!res && prefill && isBudgetEnabled) {
const pmeta = prefill.metadata && typeof prefill.metadata === 'object' ? (prefill.metadata as Record<string, unknown>) : {}
const price = Number(pmeta.price)
if (Number.isFinite(price) && price > 0) {
payload.create_budget_entry = { total_price: price, category: typeToCostCategory(form.type) }
}
const entry = importedPriceEntry(prefill.metadata, form.type)
if (entry) payload.create_budget_entry = entry
}
const saved = await saveTransport(payload)
// Persist the traveler assignment once we have the reservation id (from the
@@ -1,4 +1,4 @@
import { convertBooked } from '../../../../hooks/useExchangeRates'
import { convertBooked, convertedLine } from '../../../../hooks/useExchangeRates'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import {
AlertCircle, ArrowDown, ArrowLeftRight, ArrowRight, ArrowUp, Check, ChevronDown, ChevronUp,
@@ -14,7 +14,7 @@ import { downloadBlob, openFile } from '../../../../utils/fileDownload'
import { budgetApi } from '../../../../api/client'
import MCostSheet from '../sheets/MCostSheet'
import { ReceiptPreviewModal } from '../../../../components/Budget/ReceiptPreviewModal'
import { finalBudgetFor, finalBudgetSources, readUserNote, settlementDate } from '../../../../components/Budget/CostsPanel.helpers'
import { finalBudgetFor, finalBudgetSources, paidByUser, readUserNote, settlementDate } from '../../../../components/Budget/CostsPanel.helpers'
import { catMeta, COST_CAT_META } from '../../../../components/Budget/costsCategories'
import CustomSelect from '../../../../components/shared/CustomSelect'
import { CustomDatePicker } from '../../../../components/shared/CustomDateTimePicker'
@@ -27,8 +27,8 @@ import { Eyebrow, FIELD_CLS, FormSheetFooter, FormSheetHeader } from '../sheets/
import { CountPill, TabScroller } from './tabChrome'
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
import {
baseTotal, buildCostsCsv, categoryBreakdown, categoryFilterKeys, computeTotals, currencyOf,
dayFilterKeys, filterBudgetItems, filterSettlements, groupLedgerByDay, isUnfinished, memberShareOf, tint,
baseTotal, buildCostsCsv, categoryBreakdown, categoryFilterKeys, computeTotals,
dayFilterKeys, filterBudgetItems, filterSettlements, groupLedgerByDay, isUnfinished, lineOf, memberShareOf, tint,
type CostsCtx, type CostsSegment, type CostsSettlement, type CostsSettlementResponse,
} from './costsModel'
import type { BudgetParticipantFinal } from '@trek/shared'
@@ -55,8 +55,9 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
const tripCurrency = (trip?.currency || base).toUpperCase()
const { convert } = useExchangeRates(base)
const ctx: CostsCtx = useMemo(() => ({ me, tripCurrency, convert }), [me, tripCurrency, convert])
// Anchored on the trip currency's quote, the one the server books with (#2525).
const { convert } = useExchangeRates(base, tripCurrency)
const ctx: CostsCtx = useMemo(() => ({ me, tripCurrency, displayCurrency: base, convert }), [me, tripCurrency, base, convert])
const [settlement, setSettlement] = useState<CostsSettlementResponse | null>(null)
// A failed settlement read leaves `settlement` null, and the final budget would
@@ -339,7 +340,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
: <ChevronDown size={13} strokeWidth={2.2} className="flex-none text-m-faint" />}
</button>
{open && (
<FinalBudgetBreakdown row={row} items={budgetItems} base={base} locale={locale} t={t} personName={personName} />
<FinalBudgetBreakdown row={row} items={budgetItems} ctx={ctx} base={base} locale={locale} t={t} personName={personName} />
)}
</div>
)
@@ -622,8 +623,8 @@ function ExpenseRow({ item, ctx, base, locale, t, canEdit, onEdit, onDelete, onT
}) {
const meta = catMeta(item.category)
const Icon = meta.Icon
const cur = currencyOf(item, ctx)
const total = baseTotal(item, ctx)
const line = lineOf(item.total_price || 0, item, ctx, total)
const unfinished = isUnfinished(item, ctx)
const borderColor = tint(meta.color, 0.55)
const members = item.members || []
@@ -670,9 +671,9 @@ function ExpenseRow({ item, ctx, base, locale, t, canEdit, onEdit, onDelete, onT
</button>
)}
</div>
{cur !== base && (
{line && (
<div className="mt-[1px] truncate font-geist text-[0.59375rem] text-m-faint">
{formatMoney(item.total_price, cur, locale)} {'→'} {formatMoney(total, base, locale)}
{formatMoney(line.entered.amount, line.entered.currency, locale)} {'→'} {formatMoney(line.into.amount, line.into.currency, locale)}
</div>
)}
{members.length > 0 && (
@@ -756,7 +757,9 @@ function PaymentRow({ settlement, ctx, base, locale, t, personName, canEdit, onE
}) {
const cur = (settlement.currency || base).toUpperCase()
// At the rate it was settled at, not today's (#1445), matching the desktop ledger.
const amount = convertBooked(settlement.amount, settlement.currency, settlement.exchange_rate, ctx.tripCurrency, ctx.convert)
// A transfer without a currency was entered in the display currency, not the trip's.
const amount = convertBooked(settlement.amount, cur, settlement.exchange_rate, ctx.tripCurrency, ctx.convert)
const line = convertedLine(settlement.amount, cur, settlement.exchange_rate, ctx.tripCurrency, base, amount)
return (
<div className="mt-2 flex items-center gap-[6px]">
<div className="relative min-w-0 flex-1 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card px-3 py-[12px]">
@@ -767,9 +770,9 @@ function PaymentRow({ settlement, ctx, base, locale, t, personName, canEdit, onE
<div className="min-w-0 flex-1">
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{t('costs.payment')}</div>
<div className="truncate font-geist text-[0.65625rem] text-m-faint">{personName(settlement.from_user_id)} → {personName(settlement.to_user_id)}</div>
{cur !== base && (
{line && (
<div className="mt-[1px] truncate font-geist text-[0.59375rem] text-m-faint">
{formatMoney(settlement.amount, cur, locale)} {'→'} {formatMoney(amount, base, locale)}
{formatMoney(line.entered.amount, line.entered.currency, locale)} {'→'} {formatMoney(line.into.amount, line.into.currency, locale)}
</div>
)}
</div>
@@ -799,9 +802,10 @@ function PaymentRow({ settlement, ctx, base, locale, t, personName, canEdit, onE
* with the balances; each line is signed by what it does to the final, so the
* column reads as a subtraction and the rows add up to the line above them.
*/
function FinalBudgetBreakdown({ row, items, base, locale, t, personName }: {
function FinalBudgetBreakdown({ row, items, ctx, base, locale, t, personName }: {
row: BudgetParticipantFinal
items: BudgetItem[]
ctx: CostsCtx
base: string
locale: string
t: TFn
@@ -810,6 +814,12 @@ function FinalBudgetBreakdown({ row, items, base, locale, t, personName }: {
const signed = (v: number) => (v < 0 ? '−' : '+') + formatMoney(Math.abs(v), base, locale)
const { fronted, moved, outstanding } = finalBudgetSources(row, items)
const transfer = (fromId: number, toId: number) => `${personName(fromId)} → ${personName(toId)}`
// Beside a converted row's name, what was entered, as the list above names it (#2525).
const nameOf = (itemId: number, name: string, shown: number) => {
const e = items.find(i => i.id === itemId)
const entered = e ? lineOf(paidByUser(e, row.user_id), e, ctx, shown)?.entered : null
return entered ? `${name} · ${formatMoney(entered.amount, entered.currency, locale)}` : name
}
const line = (key: string, label: string, value: string) => (
<div key={key} className="flex items-baseline gap-2 py-[2px] font-geist text-[0.6875rem]">
<span className="min-w-0 flex-1 truncate text-m-muted">{label}</span>
@@ -828,7 +838,7 @@ function FinalBudgetBreakdown({ row, items, base, locale, t, personName }: {
{line('expenses', t('costs.finalExpenses'), signed(row.expenses))}
{line('reimbursed', t('costs.finalReimbursed'), signed(-row.reimbursed))}
{line('pending', t('costs.finalPending'), signed(-row.pending))}
{section(t('costs.finalExpenses'), fronted.map(r => line(`e${r.item_id}`, r.name, signed(r.amount))))}
{section(t('costs.finalExpenses'), fronted.map(r => line(`e${r.item_id}`, nameOf(r.item_id, r.name, r.amount), signed(r.amount))))}
{section(t('costs.finalReimbursed'), moved.map(r => line(`s${r.settlement_id}`, transfer(r.from_user_id, r.to_user_id), signed(-r.amount))))}
{section(t('costs.finalPending'), outstanding.map((r, i) => line(`f${i}`, transfer(r.from_user_id, r.to_user_id), signed(-r.amount))))}
</div>
@@ -1,7 +1,7 @@
import type { BudgetParticipantFinal, CostCategory } from '@trek/shared'
import { paidByUser, readUserNote, settlementDate, splitEqualShares } from '../../../../components/Budget/CostsPanel.helpers'
import { catMeta, COST_CATEGORY_LIST } from '../../../../components/Budget/costsCategories'
import { convertBooked } from '../../../../hooks/useExchangeRates'
import { convertBooked, convertedLine, tripAmountOf } from '../../../../hooks/useExchangeRates'
import { currencyDecimals } from '../../../../utils/formatters'
import type { BudgetItem } from '../../../../types'
@@ -19,6 +19,8 @@ export interface CostsCtx {
me: number
/** The trip's own currency — what a NULL `budget_items.currency` means. */
tripCurrency: string
/** The currency everything is shown in, the base `convert` converts to. */
displayCurrency: string
convert: (amount: number, currency: string | null | undefined) => number
}
@@ -32,6 +34,15 @@ export function booked(amount: number, e: BudgetItem, ctx: CostsCtx): number {
return convertBooked(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.convert)
}
/**
* The line under an amount of this expense the list shows converted, what was entered and
* where it went (#2525); null when there is nothing to explain. `shown` is the display
* value printed beside it.
*/
export function lineOf(amount: number, e: BudgetItem, ctx: CostsCtx, shown: number) {
return convertedLine(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.displayCurrency, shown)
}
/** Expense total converted to the display/base currency, at its booked rate. */
export function baseTotal(e: BudgetItem, ctx: CostsCtx): number {
return booked(e.total_price || 0, e, ctx)
@@ -315,12 +326,17 @@ export function buildCostsCsv(items: BudgetItem[], opts: CsvBuildOptions): { fil
}
}
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', `Amount (${opts.base})`, 'Note']
// Read in another currency than the trip's, what each row counts as in the trip currency
// too, the figure every sum is built from (#2525). Same columns as the desktop export.
const trip = opts.ctx.tripCurrency.toUpperCase()
const tripCol = trip !== opts.base.toUpperCase()
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', ...(tripCol ? [`Amount (${trip})`] : []), `Amount (${opts.base})`, 'Note']
const rows = [header.join(sep)]
const sorted = items.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || ''))
for (const e of sorted) {
const cur = currencyOf(e, opts.ctx)
const note = readUserNote(e)
const inTrip = tripAmountOf(e.total_price || 0, e.currency, e.exchange_rate, trip, opts.ctx.convert)
rows.push(
[
esc(fmtDate(e.expense_date || '')),
@@ -328,6 +344,7 @@ export function buildCostsCsv(items: BudgetItem[], opts: CsvBuildOptions): { fil
esc(opts.t(catMeta(e.category).labelKey)),
(e.total_price || 0).toFixed(currencyDecimals(cur)),
cur,
...(tripCol ? [inTrip.toFixed(currencyDecimals(trip))] : []),
baseTotal(e, opts.ctx).toFixed(currencyDecimals(opts.base)),
esc(note),
].join(sep),