fix(costs): leave out an expense no rate is known for instead of counting it 1:1

A foreign expense without a frozen rate is converted with today's rate.
When the server could not fetch rates itself, it counted the amount 1:1
in the trip currency, although the browser had the rates all along. A
VND bill on an AUD trip was settled as millions of AUD.

Such a row is now left out of the balances, flows, final budgets, trip
totals and per-person summaries. The settlement reports it under
`unconverted` and says which currency its figures are in; the trip
summary lists the ids and the budget prompt says how many are missing.

The browser lends the rates it already holds (`fallback_fx`) when it
saves an expense or a settle-up transfer, and to heal existing rows
through the new POST .../budget/freeze-rates route, which an editor's
Costs view calls for the rows the settlement left out. The server still
prefers its own rate, uses a lent one only while it is quoted against
the trip currency, and never replaces a frozen or explicit rate. The
settlement also takes the browser's display rate (`base_rate`) in place
of a display quote the server cannot fetch; the browser leaves out a
figure the query would refuse. The browser's own fetch gives up after
10 s.

Changing a row's currency while no rate is available no longer keeps
the old currency's rate; the row goes back to unfrozen.

MCP gets the same through the new freeze_budget_rates tool, which only
ever pins the server's own rate.
This commit is contained in:
Maurice
2026-09-26 12:41:05 +02:00
parent 99d7fb7f01
commit d1dc8542ac
32 changed files with 2071 additions and 137 deletions
@@ -15,6 +15,7 @@ import type { BudgetParticipantFinal } from '@trek/shared'
import type { BudgetItem } from '../../types'
import CostsPanel, { ExpenseModal } from './CostsPanel'
import { splitEqualShares, calculateTicketShares, type TicketItem } from './CostsPanel.helpers'
import { resetFreezeAttempts } from './useFreezeMissingRates'
const tripMembers = [
{ id: 1, username: 'alice', avatar_url: null },
@@ -2525,3 +2526,159 @@ describe('CostsPanel: a bill entered in the display currency (#2525)', () => {
await waitFor(() => expect(put).toMatchObject({ total_price: 100, currency: 'EUR' }))
})
})
// ── A bill the server cannot convert: VND on an AUD trip ────────────────────────
describe('CostsPanel: a bill the server cannot convert', () => {
// The reporter's setup: an AUD trip whose server cannot fetch rates while the browser
// can. An 8,920,000 VND dinner that never froze a rate was counted as 8,920,000 AUD.
// The settlement now leaves it out and lists it, and an editor's browser lends its AUD
// table to freeze a rate on it.
const pho = () => expense({
id: 501, name: 'Pho', category: 'food', total_price: 8920000, currency: 'VND', exchange_rate: 1,
expense_date: '2026-09-20',
payers: [{ user_id: 1, amount: 8920000 }],
members: [{ user_id: 1, username: 'alice' }, { user_id: 2, username: 'bob' }],
})
const leftOut = { balances: [], flows: [], settlements: [], currency: 'AUD', unconverted: { item_ids: [501], settlement_ids: [], currencies: ['VND'] } }
beforeEach(() => {
seedAlice()
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'AUD' } })
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'AUD' }) })
clearExchangeRateCache()
resetFreezeAttempts()
localStorage.setItem('trek_fx_AUD', JSON.stringify({ rates: { AUD: 1, VND: 18241.3, EUR: 0.61 }, ts: Date.now() }))
})
afterEach(clearExchangeRateCache)
it('FE-W5COSTS-090: VND/AUD regression: an editor heals the bill with the cached quote and the healed balances load', async () => {
let healed = false
const frozen: unknown[] = []
server.use(
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [pho()] })),
http.get('/api/trips/1/budget/settlement', () => HttpResponse.json(healed
? {
// 8,920,000 VND at 18,241.3 is 489.00 AUD, half of it Bob's.
balances: [
{ user_id: 1, username: 'alice', avatar_url: null, balance: 244.5 },
{ user_id: 2, username: 'bob', avatar_url: null, balance: -244.5 },
],
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 244.5 }],
settlements: [],
currency: 'AUD',
unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
}
: leftOut)),
http.post('/api/trips/1/budget/freeze-rates', async ({ request }) => {
frozen.push(await request.json())
healed = true
return HttpResponse.json({ items: [{ ...pho(), exchange_rate: 18241.3 }], settlements: [], unresolved: [] })
}),
)
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
// Only the currency the settlement is missing, at the rate the browser holds.
await waitFor(() => expect(frozen).toEqual([{ fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }]))
// The settlement is read again and Bob's half can be settled.
expect(await screen.findByRole('button', { name: 'Settle' })).toBeInTheDocument()
expect(screen.getAllByText(/244\.50/).length).toBeGreaterThan(0)
// Nothing on the page counts the bill as 8,920,000 dollars any more.
expect(screen.queryByText(/\$8,920,000/)).toBeNull()
expect(frozen).toHaveLength(1)
})
it('FE-W5COSTS-091: a viewer\'s browser never freezes anything', async () => {
seedStore(usePermissionsStore, { permissions: { budget_edit: 'admin' } })
let frozen = 0
server.use(http.post('/api/trips/1/budget/freeze-rates', () => {
frozen += 1
return HttpResponse.json({ items: [], settlements: [], unresolved: [] })
}))
mount([pho()], leftOut)
await screen.findByText('Pho')
await new Promise(r => setTimeout(r, 50))
expect(frozen).toBe(0)
})
it('FE-W5COSTS-092: settle-up in the display currency lends its rate and asks the settlement in it', async () => {
// Read in euros: the browser has the AUD table, the server has no quote at all.
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } })
const asked: { base: string | null; baseRate: string | null }[] = []
const posted: Record<string, unknown>[] = []
server.use(
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })),
http.get('/api/trips/1/budget/settlement', ({ request }) => {
const url = new URL(request.url)
asked.push({ base: url.searchParams.get('base'), baseRate: url.searchParams.get('base_rate') })
return HttpResponse.json({
balances: [], settlements: [], currency: 'EUR', unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 20 }],
})
}),
http.post('/api/trips/1/budget/settlements', async ({ request }) => {
posted.push(await request.json() as Record<string, unknown>)
return HttpResponse.json({ settlement: { id: 1 } })
}),
)
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
fireEvent.click(await screen.findByRole('button', { name: 'Settle' }))
await waitFor(() => expect(posted).toHaveLength(1))
// The transfer freezes at the rate the settlement was labelled with, so it cancels its
// flow to the cent.
expect(posted[0]).toMatchObject({ from_user_id: 2, to_user_id: 1, amount: 20, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
expect(asked.length).toBeGreaterThan(0)
expect(asked.every(a => a.base === 'EUR' && a.baseRate === '0.61')).toBe(true)
const settleAll = screen.getByRole('button', { name: 'Settle up' })
fireEvent.click(settleAll)
await waitFor(() => expect(posted).toHaveLength(2))
expect(posted[1]).toMatchObject({ amount: 20, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
})
it('FE-W5COSTS-093: a payment added by hand lends the rate for its currency too', async () => {
const user = userEvent.setup()
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } })
let posted: Record<string, unknown> | null = null
server.use(http.post('/api/trips/1/budget/settlements', async ({ request }) => {
posted = await request.json() as Record<string, unknown>
return HttpResponse.json({ settlement: { id: 1 } })
}))
mount([])
await user.click(await screen.findByRole('button', { name: 'Add payment' }))
await user.type(await screen.findByPlaceholderText('0.00'), '25')
const submits = screen.getAllByRole('button', { name: 'Add payment' })
await user.click(submits[submits.length - 1])
await waitFor(() => expect(posted).toBeTruthy())
expect(posted).toMatchObject({ amount: 25, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
})
it('FE-W5COSTS-094: a display rate the settlement query would refuse is not sent', async () => {
// A trip in gold read in rials: 2.6 billion rials to the ounce is past the 1e9 the query
// takes, and sent as `base_rate` it would fail the whole settlement with a 400.
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'XAU' }) })
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'IRR' } })
localStorage.setItem('trek_fx_XAU', JSON.stringify({ rates: { XAU: 1, IRR: 2.6e9 }, ts: Date.now() }))
localStorage.setItem('trek_fx_IRR', JSON.stringify({ rates: { IRR: 1, XAU: 1 / 2.6e9 }, ts: Date.now() }))
const asked: { base: string | null; baseRate: string | null }[] = []
server.use(
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })),
http.get('/api/trips/1/budget/settlement', ({ request }) => {
const url = new URL(request.url)
asked.push({ base: url.searchParams.get('base'), baseRate: url.searchParams.get('base_rate') })
return HttpResponse.json({
balances: [], flows: [], settlements: [], currency: 'XAU', unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
})
}),
)
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
await waitFor(() => expect(asked.length).toBeGreaterThan(0))
// Still asked in rials, only without the figure; the server answers in the trip
// currency when it has no quote of its own.
expect(asked.every(a => a.base === 'IRR' && a.baseRate === null)).toBe(true)
})
})
+24 -12
View File
@@ -9,8 +9,9 @@ import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { budgetApi } from '../../api/client'
import { saveWithReceipts } from './receiptUploads'
import { convertBooked, convertedLine, tripAmountOf, useExchangeRates } from '../../hooks/useExchangeRates'
import { convertBooked, convertedLine, tripAmountOf, useExchangeRates, withFallbackFx } from '../../hooks/useExchangeRates'
import { splitShareLabel, useExpenseFx } from './expenseFx'
import { useFreezeMissingRates } from './useFreezeMissingRates'
import { useIsMobile } from '../../hooks/useIsMobile'
import { formatMoney, currencyDecimals, currencyLocale, localizeAmountInput, amountToInputString } from '../../utils/formatters'
import { downloadBlob, openFile } from '../../utils/fileDownload'
@@ -22,7 +23,7 @@ import { SYMBOLS, currenciesWith, SPLIT_COLORS } from './BudgetPanel.constants'
import { amountPattern, calculateTicketShares, finalBudgetFor, finalBudgetSources, hasTicketSplit, NOTE_MAX, paidByUser, payersBalanced, readTicketItems, readUserNote, rebalancePayers, settlementDate, splitEqualShares, writeTicketItems, type TicketItem } from './CostsPanel.helpers'
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import { ReceiptPreviewModal } from './ReceiptPreviewModal'
import type { BudgetParticipantFinal } from '@trek/shared'
import type { BudgetParticipantFinal, BudgetUnconverted } from '@trek/shared'
import type { BudgetItem, BudgetItemReceipt } from '../../types'
import type { TripMember } from './BudgetPanelMemberChips'
import GuestBadge from '../shared/GuestBadge'
@@ -61,6 +62,11 @@ interface SettlementData {
// What the trip ends up costing each participant. Computed server-side off the
// same ledger as the balances, so the breakdown can't contradict them.
finalBudgets: BudgetParticipantFinal[]
// The currency the figures are in: the display currency, or the trip's own when
// neither the server nor `base_rate` could quote the pair.
currency?: string
// Rows no rate could convert, left out of every figure above.
unconverted?: BudgetUnconverted
}
// One row in the unified Costs ledger — either an expense or a settle-up payment,
@@ -88,7 +94,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// Pre-rework rows stored currency = NULL, meaning "the trip's own currency".
const tripCurrency = (trip?.currency || base).toUpperCase()
// Anchored on the trip currency's quote, the one the server books with (#2525).
const { convert } = useExchangeRates(base, tripCurrency)
const { convert, displayPerTrip } = useExchangeRates(base, tripCurrency)
const curOf = useCallback((e: BudgetItem) => (e.currency || tripCurrency), [tripCurrency])
const [settlement, setSettlement] = useState<SettlementData | null>(null)
// A failed settlement read leaves `settlement` null, which the empty views would
@@ -122,14 +128,20 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const fmt = useCallback((v: number, c = base) => formatMoney(v, c, locale), [base, locale])
const fmt0 = useCallback((v: number, c = base) => formatMoney(v, c, locale, { decimals: 0 }), [base, locale])
// The browser's own figure for the display currency goes along, for the server to
// answer in it when it cannot fetch a quote itself.
const loadSettlement = useCallback(() => {
budgetApi.settlement(tripId, base)
budgetApi.settlement(tripId, base, base !== tripCurrency ? displayPerTrip : null)
.then(s => { setSettlement(s); setSettlementError(false) })
.catch(() => setSettlementError(true))
}, [tripId, base])
}, [tripId, base, tripCurrency, displayPerTrip])
useEffect(() => { loadBudgetItems(tripId); loadSettlement() }, [tripId])
useEffect(() => { loadSettlement() }, [budgetItems.length, base])
useEffect(() => { loadSettlement() }, [budgetItems.length, loadSettlement])
// Rows the server could not count get a rate frozen from the browser's, and the
// settlement is read again once they count.
useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted: settlement?.unconverted, onHealed: loadSettlement })
// The bottom-nav "+" on the Costs tab opens the add-expense modal via ?create=expense.
const [searchParams, setSearchParams] = useSearchParams()
@@ -255,7 +267,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// ── settle actions ──────────────────────────────────────────────────────
const settleFlow = async (fromId: number, toId: number, amount: number) => {
try {
await budgetApi.createSettlement(tripId, { from_user_id: fromId, to_user_id: toId, amount, currency: base })
await budgetApi.createSettlement(tripId, withFallbackFx({ from_user_id: fromId, to_user_id: toId, amount, currency: base }, tripCurrency))
loadSettlement()
} catch { toast.error(t('common.unknownError')) }
}
@@ -266,7 +278,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const flows = settlement?.flows || []
if (!flows.length) return
try {
for (const f of flows) await budgetApi.createSettlement(tripId, { from_user_id: f.from.user_id, to_user_id: f.to.user_id, amount: f.amount, currency: base })
for (const f of flows) await budgetApi.createSettlement(tripId, withFallbackFx({ from_user_id: f.from.user_id, to_user_id: f.to.user_id, amount: f.amount, currency: base }, tripCurrency))
} catch { toast.error(t('common.unknownError')) }
// Refresh even when one transfer failed: the ones created before it are real,
// and leaving them in the flow list invites a second, doubled settle-up.
@@ -504,7 +516,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
)}
{(editingSettlement || addingPayment) && (
<SettlementModal tripId={tripId} people={people} me={me} editing={editingSettlement} currency={base}
<SettlementModal tripId={tripId} people={people} me={me} editing={editingSettlement} currency={base} tripCurrency={tripCurrency}
onClose={() => { setEditingSettlement(null); setAddingPayment(false) }}
onSaved={() => { setEditingSettlement(null); setAddingPayment(false); loadSettlement() }} />
)}
@@ -1142,8 +1154,8 @@ function FlowPills({ ids, lead, Avatar, name }: { ids: number[]; lead: string; A
// A transfer can be made in any currency — paying a rouble debt in euros is normal —
// so it carries its own, defaulting to the display currency. The server freezes its
// FX rate on write, the same way an expense's is frozen.
function SettlementModal({ tripId, people, me, editing, currency, onClose, onSaved }: {
tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; onClose: () => void; onSaved: () => void
function SettlementModal({ tripId, people, me, editing, currency, tripCurrency, onClose, onSaved }: {
tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; tripCurrency: string; onClose: () => void; onSaved: () => void
}) {
const { t } = useTranslation()
const toast = useToast()
@@ -1164,7 +1176,7 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav
const save = async () => {
if (!valid) return
setSaving(true)
const data = { from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency: cur, settled_at: day }
const data = withFallbackFx({ from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency: cur, settled_at: day }, tripCurrency)
try {
if (editing) await budgetApi.updateSettlement(tripId, editing.id, data)
else await budgetApi.createSettlement(tripId, data)
@@ -0,0 +1,123 @@
// FE-FREEZE-RATES-001 to FE-FREEZE-RATES-006
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import type { BudgetUnconverted } from '@trek/shared'
import { server } from '../../../tests/helpers/msw/server'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import { buildBudgetItem } from '../../../tests/helpers/factories'
import { useTripStore } from '../../store/tripStore'
import { setForcedOffline } from '../../sync/networkMode'
import { clearExchangeRateCache } from '../../hooks/useExchangeRates'
import { resetFreezeAttempts, useFreezeMissingRates } from './useFreezeMissingRates'
// The reporter's setup: an AUD trip whose server cannot fetch rates, and a VND bill that
// never froze one. The browser has today's AUD table.
const bill = () => buildBudgetItem({ id: 11, trip_id: 5, name: 'Pho', total_price: 8920000, currency: 'VND', exchange_rate: 1 })
const pending: BudgetUnconverted = { item_ids: [11], settlement_ids: [3], currencies: ['VND'] }
type Props = Parameters<typeof useFreezeMissingRates>[0]
function mountHook(over: Partial<Props> = {}) {
const onHealed = vi.fn()
const props: Props = { tripId: 5, tripCurrency: 'AUD', canEdit: true, unconverted: pending, onHealed, ...over }
const view = renderHook((p: Props) => useFreezeMissingRates(p), { initialProps: props })
return { ...view, onHealed, props }
}
let posted: unknown[] = []
function serveFreeze(reply: () => Response = () => HttpResponse.json({
items: [{ ...bill(), exchange_rate: 18241.3 }],
settlements: [{ id: 3, trip_id: 5, from_user_id: 2, to_user_id: 1, amount: 100000, currency: 'VND', exchange_rate: 18241.3 }],
unresolved: [],
})) {
server.use(http.post('/api/trips/5/budget/freeze-rates', async ({ request }) => {
posted.push(await request.json())
return reply()
}))
}
/** Lets a heal that was never going to send anything run to its end. */
const settle = () => act(async () => { await new Promise(r => setTimeout(r, 30)) })
beforeEach(() => {
resetAllStores()
resetFreezeAttempts()
clearExchangeRateCache()
posted = []
localStorage.setItem('trek_fx_AUD', JSON.stringify({ rates: { AUD: 1, VND: 18241.3, EUR: 0.61 }, ts: Date.now() }))
seedStore(useTripStore, { budgetItems: [bill()] })
serveFreeze()
})
afterEach(() => {
setForcedOffline(false)
vi.restoreAllMocks()
})
describe('useFreezeMissingRates', () => {
it('FE-FREEZE-RATES-001: lends the fresh rates for the listed currencies and reloads once rows count', async () => {
const { onHealed } = mountHook()
await waitFor(() => expect(onHealed).toHaveBeenCalledTimes(1))
// Only the currency the settlement is missing goes out, never the whole table.
expect(posted).toEqual([{ fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }])
expect(useTripStore.getState().budgetItems[0].exchange_rate).toBe(18241.3)
})
it('FE-FREEZE-RATES-002: asks once per set of rows, however often the settlement is read', async () => {
const { onHealed, props, rerender } = mountHook()
await waitFor(() => expect(onHealed).toHaveBeenCalledTimes(1))
// The same rows in another order, then again after a reload: nothing new to ask.
rerender({ ...props, unconverted: { item_ids: [11], settlement_ids: [3], currencies: ['VND'] } })
rerender({ ...props, unconverted: { settlement_ids: [3], item_ids: [11], currencies: ['VND'] } })
await settle()
expect(posted).toHaveLength(1)
// Another row is another attempt.
rerender({ ...props, unconverted: { item_ids: [11, 12], settlement_ids: [3], currencies: ['VND'] } })
await waitFor(() => expect(posted).toHaveLength(2))
})
it('FE-FREEZE-RATES-003: never asks for a viewer, offline, or with nothing left out', async () => {
mountHook({ canEdit: false })
mountHook({ unconverted: { item_ids: [], settlement_ids: [], currencies: [] } })
mountHook({ unconverted: undefined })
setForcedOffline(true)
mountHook({ unconverted: { item_ids: [21], settlement_ids: [], currencies: ['VND'] } })
await settle()
expect(posted).toEqual([])
})
it('FE-FREEZE-RATES-004: sends nothing when the browser has no rate for the currency either', async () => {
const { onHealed } = mountHook({ unconverted: { item_ids: [31], settlement_ids: [], currencies: ['JPY'] } })
await settle()
expect(posted).toEqual([])
expect(onHealed).not.toHaveBeenCalled()
})
it('FE-FREEZE-RATES-005: does not reload when the server froze nothing', async () => {
serveFreeze(() => HttpResponse.json({ items: [], settlements: [], unresolved: ['VND'] }))
const { onHealed } = mountHook()
await waitFor(() => expect(posted).toHaveLength(1))
await settle()
expect(onHealed).not.toHaveBeenCalled()
})
it('FE-FREEZE-RATES-006: a refused heal is logged, not thrown, and not retried in a loop', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
serveFreeze(() => HttpResponse.json({ error: 'The trip currency changed. Reload and try again.' }, { status: 409 }))
const { onHealed, props, rerender } = mountHook()
await waitFor(() => expect(warn).toHaveBeenCalled())
rerender({ ...props })
await settle()
expect(posted).toHaveLength(1)
expect(onHealed).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,73 @@
import { useEffect, useRef } from 'react'
import type { BudgetFallbackFx, BudgetUnconverted } from '@trek/shared'
import { fetchFreshRates, isSendableRate } from '../../hooks/useExchangeRates'
import { useTripStore } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
/**
* Every set of rows already tried, by trip, trip currency and ids. The settlement lists a
* row it cannot count until a rate is frozen on it; one the browser has no rate for either
* stays listed, and without this every reload of the settlement would ask again.
*/
const tried = new Set<string>()
/** Test-only: the attempts outlive a vitest file's individual tests. */
export function resetFreezeAttempts(): void {
tried.clear()
}
/**
* Heals the rows the settlement leaves out (`unconverted`): expenses and transfers in a
* foreign currency that never froze a rate, while the server cannot fetch one. That is the
* setup where the server's own fetch fails and the browser's works, so an editor's browser
* lends its fresh rates to POST …/budget/freeze-rates. The server still prefers its own rate
* and never touches a row that is frozen already.
*
* Runs for an editor only, online, and once per set of rows. No request goes out when the
* browser has no rate for any of the listed currencies either. `onHealed` runs when the
* server froze something, so the caller can reload the settlement.
*
* Deliberately not in the mutation queue: the heal is derived and idempotent, and a replay
* hours later would freeze a rate from another day.
*/
export function useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted, onHealed }: {
tripId: number
tripCurrency: string
canEdit: boolean
unconverted: BudgetUnconverted | null | undefined
onHealed: () => void
}): void {
const onHealedRef = useRef(onHealed)
useEffect(() => { onHealedRef.current = onHealed })
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => { mounted.current = false }
}, [])
const trip = (tripCurrency || '').toUpperCase()
const itemIds = [...(unconverted?.item_ids ?? [])].sort((a, b) => a - b).join(',')
const settlementIds = [...(unconverted?.settlement_ids ?? [])].sort((a, b) => a - b).join(',')
const currencies = (unconverted?.currencies ?? []).join(',')
useEffect(() => {
if (!canEdit || !trip || (!itemIds && !settlementIds) || isEffectivelyOffline()) return
const key = `${tripId}:${trip}:${itemIds}:${settlementIds}`
if (tried.has(key)) return
tried.add(key)
const heal = async (): Promise<void> => {
const rates = await fetchFreshRates(trip)
const lent: Record<string, number> = {}
for (const cur of currencies.split(',')) {
const rate = rates?.[cur]
if (isSendableRate(rate)) lent[cur] = rate
}
if (Object.keys(lent).length === 0) return
const fallback: BudgetFallbackFx = { base: trip, rates: lent }
const result = await useTripStore.getState().freezeMissingRates(tripId, fallback)
if (mounted.current && (result.items.length > 0 || result.settlements.length > 0)) onHealedRef.current()
}
heal().catch((err: unknown) => console.warn('Could not freeze the missing exchange rates:', err))
}, [canEdit, trip, tripId, itemIds, settlementIds, currencies])
}