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
+96
View File
@@ -1,5 +1,11 @@
import {
budgetCreateItemRequestSchema,
budgetUpdateItemRequestSchema,
budgetCreateSettlementRequestSchema,
budgetUpdateSettlementRequestSchema,
budgetFreezeRatesRequestSchema,
budgetSettlementQuerySchema,
budgetUnconvertedSchema,
budgetUpdateMembersRequestSchema,
budgetToggleMemberPaidRequestSchema,
budgetReorderItemsRequestSchema,
@@ -61,3 +67,93 @@ describe('typeToCostCategory', () => {
expect(typeToCostCategory('taxi')).toBe('transport');
});
});
describe('fallback_fx (rates lent for a write)', () => {
const fx = { base: 'AUD', rates: { VND: 18241.3 } };
it('is optional on all four write bodies and kept when well formed', () => {
const cases = [
[budgetCreateItemRequestSchema, { name: 'Pho' }],
[budgetUpdateItemRequestSchema, {}],
[budgetCreateSettlementRequestSchema, { from_user_id: 1, to_user_id: 2, amount: 10 }],
[budgetUpdateSettlementRequestSchema, { from_user_id: 1, to_user_id: 2, amount: 10 }],
] as const;
for (const [schema, body] of cases) {
expect(schema.safeParse(body).success).toBe(true);
const parsed = schema.safeParse({ ...body, fallback_fx: fx });
expect(parsed.success).toBe(true);
expect(parsed.data?.fallback_fx).toEqual(fx);
}
});
const accepted = (fallback_fx: unknown) =>
budgetCreateItemRequestSchema.safeParse({ name: 'Pho', fallback_fx }).success;
it('refuses a base or a currency that is not three upper-case letters', () => {
expect(accepted({ base: 'aud', rates: { VND: 1.5 } })).toBe(false);
expect(accepted({ base: 'AUDX', rates: { VND: 1.5 } })).toBe(false);
expect(accepted({ base: 'AUD', rates: { vnd: 1.5 } })).toBe(false);
expect(accepted({ base: 'AUD', rates: { VNDX: 1.5 } })).toBe(false);
});
it('refuses a rate that is zero, negative, NaN, infinite or above 1e9', () => {
for (const rate of [0, -1, Number.NaN, Number.POSITIVE_INFINITY, 1e9 + 1]) {
expect(accepted({ base: 'AUD', rates: { VND: rate } })).toBe(false);
}
expect(accepted({ base: 'AUD', rates: { VND: 1e9 } })).toBe(true);
expect(accepted({ base: 'AUD', rates: { VND: 1e-9 } })).toBe(true);
});
it('refuses an empty table and one with more than 200 currencies', () => {
// AAA, AAB, … : n distinct three-letter codes.
const codes = (n: number) =>
Object.fromEntries(
Array.from({ length: n }, (_, i) => [
String.fromCharCode(65 + Math.floor(i / 676), 65 + (Math.floor(i / 26) % 26), 65 + (i % 26)),
1.5,
]),
);
expect(accepted({ base: 'AUD', rates: {} })).toBe(false);
expect(accepted({ base: 'AUD', rates: codes(200) })).toBe(true);
expect(accepted({ base: 'AUD', rates: codes(201) })).toBe(false);
});
});
describe('budgetFreezeRatesRequestSchema', () => {
it('accepts an empty body and a well-formed fallback table', () => {
expect(budgetFreezeRatesRequestSchema.safeParse({}).success).toBe(true);
expect(
budgetFreezeRatesRequestSchema.safeParse({ fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }).success,
).toBe(true);
expect(budgetFreezeRatesRequestSchema.safeParse({ fallback_fx: { base: 'AUD', rates: { VND: 0 } } }).success).toBe(
false,
);
});
});
describe('budgetSettlementQuerySchema', () => {
it('coerces base_rate from the query string and leaves base as it came', () => {
expect(budgetSettlementQuerySchema.parse({})).toEqual({});
expect(budgetSettlementQuerySchema.parse({ base: 'eur', base_rate: '0.61' })).toEqual({
base: 'eur',
base_rate: 0.61,
});
});
it('refuses a base_rate that is not a positive number in range', () => {
for (const base_rate of ['abc', '0', '-1', '1e10', '']) {
expect(budgetSettlementQuerySchema.safeParse({ base_rate }).success).toBe(false);
}
});
});
describe('budgetUnconvertedSchema', () => {
it('lists row ids and currencies', () => {
expect(budgetUnconvertedSchema.safeParse({ item_ids: [3], settlement_ids: [], currencies: ['VND'] }).success).toBe(
true,
);
expect(budgetUnconvertedSchema.safeParse({ item_ids: ['3'], settlement_ids: [], currencies: [] }).success).toBe(
false,
);
});
});
+87 -1
View File
@@ -1,3 +1,5 @@
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
@@ -113,6 +115,9 @@ export type BudgetItemReceipt = z.infer<typeof budgetItemReceiptSchema>;
* plus the embedded `members` (equal-split participants), `payers` and `receipts` arrays.
* total_price is the sum of payer amounts in `currency`; `exchange_rate` converts
* that to the trip base currency (NULL currency + rate 1 = base currency).
* On a row in another currency, rate 1 means the rate was never frozen: the
* server converts it with today's rate, and without one leaves it out of every
* figure and lists it under the settlement's `unconverted`.
*/
export const budgetItemSchema = z.object({
id: z.number(),
@@ -151,6 +156,29 @@ const memberInputSchema = z.object({
amount: z.number().nullable().optional(),
});
const currencyCodeSchema = z.string().regex(/^[A-Z]{3}$/);
/**
* A rate table the caller already holds (the client's cached rates), lent to the
* server for a write. `rates` are units of each currency per 1 `base`, which is
* how a frozen `exchange_rate` reads when `base` is the trip currency.
*
* The server uses a rate from here only for a currency it cannot quote itself,
* and only while `base` is the trip's current currency; its own rate always wins,
* and a rate already frozen or sent as `exchange_rate` is never replaced.
*/
export const budgetFallbackFxSchema = z.object({
base: currencyCodeSchema,
rates: z.record(currencyCodeSchema, z.number().finite().min(1e-9).max(1e9)).refine(
(rates) => {
const n = Object.keys(rates).length;
return n >= 1 && n <= 200;
},
{ message: 'rates must hold between 1 and 200 currencies' },
),
});
export type BudgetFallbackFx = z.infer<typeof budgetFallbackFxSchema>;
export const budgetCreateItemRequestSchema = z.object({
name: z.string().min(1),
category: z.string().optional(),
@@ -176,6 +204,8 @@ export const budgetCreateItemRequestSchema = z.object({
place_id: z.number().optional(),
// Receipt files to link to this expense
receipt_file_ids: z.array(z.number()).optional(),
// Rates to freeze a foreign currency with when the server has none of its own.
fallback_fx: budgetFallbackFxSchema.optional(),
});
export type BudgetCreateItemRequest = z.infer<typeof budgetCreateItemRequestSchema>;
@@ -199,6 +229,7 @@ export const budgetUpdateItemRequestSchema = z.object({
// null lets go of the link and keeps the expense. Omitted leaves it as is.
reservation_id: z.number().int().positive().nullable().optional(),
place_id: z.number().int().positive().nullable().optional(),
fallback_fx: budgetFallbackFxSchema.optional(),
});
export type BudgetUpdateItemRequest = z.infer<typeof budgetUpdateItemRequestSchema>;
@@ -213,7 +244,9 @@ export type BudgetUpdatePayersRequest = z.infer<typeof budgetUpdatePayersRequest
* given amount, entered in the payer's display `currency`. `exchange_rate` is the
* live rate frozen at settle time (units of that currency per 1 trip currency), so
* a settled position stays balanced when live rates drift (#1445). Legacy rows
* have currency = null / exchange_rate = 1 and convert with live rates. Creating
* have currency = null / exchange_rate = 1 and convert with live rates. A row in
* another currency with rate 1 was never frozen: without a live rate it is left
* out of the balances and listed under the settlement's `unconverted`. Creating
* one marks a suggested flow as paid; deleting it (undo) brings the flow back.
*/
export const budgetSettlementSchema = z.object({
@@ -247,6 +280,8 @@ export const budgetCreateSettlementRequestSchema = z.object({
// The day the transfer happened. Null when the caller sets none; the ledger then
// uses the day it was recorded, which is where every older payment already sits.
settled_at: z.string().nullable().optional(),
// Rates to freeze `currency` with when the server has none of its own.
fallback_fx: budgetFallbackFxSchema.optional(),
});
export type BudgetCreateSettlementRequest = z.infer<typeof budgetCreateSettlementRequestSchema>;
@@ -257,9 +292,60 @@ export const budgetUpdateSettlementRequestSchema = z.object({
amount: z.number(),
currency: z.string().nullable().optional(),
settled_at: z.string().nullable().optional(),
fallback_fx: budgetFallbackFxSchema.optional(),
});
export type BudgetUpdateSettlementRequest = z.infer<typeof budgetUpdateSettlementRequestSchema>;
/**
* POST …/budget/freeze-rates: pin a rate on every row in a foreign currency that
* has none frozen yet, not only the rows the settlement lists under `unconverted`
* but also those it still converts at today's rate. The server's own rate comes
* first; `fallback_fx` only fills a currency it cannot quote. A row that is frozen,
* in the trip currency or without a currency is never touched, so a second call
* never moves a rate the first one froze.
*/
export const budgetFreezeRatesRequestSchema = z.object({
fallback_fx: budgetFallbackFxSchema.optional(),
});
export type BudgetFreezeRatesRequest = z.infer<typeof budgetFreezeRatesRequestSchema>;
/** The rows the call froze, and the currencies no rate was found for. */
export const budgetFreezeRatesResponseSchema = z.object({
items: z.array(budgetItemSchema),
settlements: z.array(budgetSettlementSchema),
unresolved: z.array(z.string()),
});
export type BudgetFreezeRatesResponse = z.infer<typeof budgetFreezeRatesResponseSchema>;
/**
* GET …/budget/settlement query. `base` is the display currency. `base_rate` is
* units of it per 1 trip currency, from the caller's own rates; the server uses
* it only when it cannot quote that pair itself, and then only in place of the
* missing display quote. That quote also reads a legacy transfer without a
* currency, which is taken to be in the display currency, as with a live quote.
*/
export const budgetSettlementQuerySchema = z.object({
base: z.string().optional(),
base_rate: z.coerce.number().finite().min(1e-9).max(1e9).optional(),
});
export type BudgetSettlementQuery = z.infer<typeof budgetSettlementQuerySchema>;
/**
* What the settlement left out because no rate could convert it: expenses and
* transfers in a foreign currency with no frozen rate, while no live rate for
* that currency is to be had. Such a row counts in none of the figures, so the
* balances still add up to zero. `currencies` are upper case, deduplicated and
* sorted. The settlement also says which `currency` its amounts are in: the
* display currency asked for, or the trip currency when that one cannot be
* quoted.
*/
export const budgetUnconvertedSchema = z.object({
item_ids: z.array(idSchema),
settlement_ids: z.array(idSchema),
currencies: z.array(z.string()),
});
export type BudgetUnconverted = z.infer<typeof budgetUnconvertedSchema>;
/**
* What the trip actually costs one participant, as GET …/budget/settlement
* returns it alongside the balances and the suggested flows.