mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
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:
@@ -4,6 +4,7 @@ import {
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
@@ -28,6 +29,8 @@ import {
|
||||
BudgetReorderCategoriesDto,
|
||||
BudgetCreateSettlementDto,
|
||||
BudgetUpdateSettlementDto,
|
||||
BudgetFreezeRatesDto,
|
||||
BudgetSettlementQueryDto,
|
||||
} from './budget.dto';
|
||||
|
||||
/**
|
||||
@@ -37,8 +40,9 @@ import {
|
||||
* every handler verifies trip access (404); mutations check 'budget_edit' (403);
|
||||
* create is 201, the rest 200; bespoke 404 bodies reproduced; mutations
|
||||
* broadcast over WebSocket with the forwarded X-Socket-Id. Static sub-routes
|
||||
* (summary, settlement, reorder/*) are declared before /:id so they win over the
|
||||
* param. Updating total_price on a reservation-linked item syncs the price back.
|
||||
* (summary, settlement, freeze-rates, reorder/*) are declared before /:id so they
|
||||
* win over the param. Updating total_price on a reservation-linked item syncs the
|
||||
* price back.
|
||||
*
|
||||
* Bodies are validated against the @trek/shared budget schemas via budget.dto.ts
|
||||
* (global ZodValidationPipe). This replaced the legacy bespoke 400s ('Name is
|
||||
@@ -66,14 +70,16 @@ export class BudgetController {
|
||||
return { summary: await this.budget.perPersonSummary(tripId) };
|
||||
}
|
||||
|
||||
// `base_rate` is the caller's own quote for the display currency (units per 1 trip
|
||||
// currency), used only when the server has none; a malformed one is a 400.
|
||||
@Get('settlement')
|
||||
settlement(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('tripId') tripId: string,
|
||||
@Query('base') base?: string,
|
||||
@Query() query: BudgetSettlementQueryDto,
|
||||
) {
|
||||
return this.budget.settlement(tripId, base, trip.currency || 'EUR');
|
||||
return this.budget.settlement(tripId, query.base, trip.currency || 'EUR', query.base_rate);
|
||||
}
|
||||
|
||||
@Get('settlements')
|
||||
@@ -91,7 +97,10 @@ export class BudgetController {
|
||||
) {
|
||||
const settlement = await this.budget.createSettlement(
|
||||
tripId,
|
||||
{ from_user_id: body.from_user_id, to_user_id: body.to_user_id, amount: body.amount, currency: body.currency, settled_at: body.settled_at },
|
||||
{
|
||||
from_user_id: body.from_user_id, to_user_id: body.to_user_id, amount: body.amount,
|
||||
currency: body.currency, settled_at: body.settled_at, fallback_fx: body.fallback_fx,
|
||||
},
|
||||
user.id,
|
||||
);
|
||||
// A party who is not on this trip gets the same answer as a settlement that
|
||||
@@ -118,6 +127,7 @@ export class BudgetController {
|
||||
amount: body.amount,
|
||||
currency: body.currency,
|
||||
settled_at: body.settled_at,
|
||||
fallback_fx: body.fallback_fx,
|
||||
});
|
||||
if (!settlement) {
|
||||
throw new HttpException({ error: 'Settlement not found' }, 404);
|
||||
@@ -141,6 +151,33 @@ export class BudgetController {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeze a rate onto every foreign row that has none frozen yet, the ones the
|
||||
* settlement lists as `unconverted` and the ones it still converts at today's rate:
|
||||
* the server's own rate first, `fallback_fx` (the browser's) for a currency it cannot
|
||||
* quote. A frozen row, a row in the trip currency and a row without a currency are
|
||||
* never touched. The same service call as the freeze_budget_rates MCP tool, which
|
||||
* lends no rates. 409 when the trip currency changed while the rates were fetched;
|
||||
* nothing is written then.
|
||||
*/
|
||||
@RequirePermission('budget_edit')
|
||||
@Post('freeze-rates')
|
||||
@HttpCode(200)
|
||||
async freezeRates(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Body() body: BudgetFreezeRatesDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const healed = await this.budget.freezeMissingRates(tripId, body.fallback_fx);
|
||||
if (!healed) {
|
||||
throw new HttpException({ error: 'The trip currency changed. Reload and try again.' }, 409);
|
||||
}
|
||||
for (const item of healed.items) this.budget.broadcast(tripId, 'budget:updated', { item }, socketId);
|
||||
for (const settlement of healed.settlements) this.budget.broadcast(tripId, 'budget:settlement-updated', { settlement }, socketId);
|
||||
return healed;
|
||||
}
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Post()
|
||||
async create(
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
budgetReorderCategoriesRequestSchema,
|
||||
budgetCreateSettlementRequestSchema,
|
||||
budgetUpdateSettlementRequestSchema,
|
||||
budgetFreezeRatesRequestSchema,
|
||||
budgetSettlementQuerySchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
@@ -26,3 +28,6 @@ export class BudgetReorderItemsDto extends createZodDto(budgetReorderItemsReques
|
||||
export class BudgetReorderCategoriesDto extends createZodDto(budgetReorderCategoriesRequestSchema) {}
|
||||
export class BudgetCreateSettlementDto extends createZodDto(budgetCreateSettlementRequestSchema) {}
|
||||
export class BudgetUpdateSettlementDto extends createZodDto(budgetUpdateSettlementRequestSchema) {}
|
||||
export class BudgetFreezeRatesDto extends createZodDto(budgetFreezeRatesRequestSchema) {}
|
||||
/** GET …/settlement query (`base`, and `base_rate` coerced from the query string). */
|
||||
export class BudgetSettlementQueryDto extends createZodDto(budgetSettlementQuerySchema) {}
|
||||
|
||||
@@ -72,7 +72,8 @@ function formatCents(cents: number): string {
|
||||
* through the freeze-then-write composites so REST and MCP can't diverge on
|
||||
* the #1445 FX freeze, and the settlement resource resolves the trip currency
|
||||
* and live rates like get_settlement_summary instead of silently defaulting
|
||||
* to an unconverted EUR base.
|
||||
* to an unconverted EUR base. freeze_budget_rates has no legacy counterpart; it
|
||||
* is the REST freeze-rates route without the rate table a browser may lend.
|
||||
*/
|
||||
@McpController()
|
||||
export class BudgetMcp {
|
||||
@@ -177,7 +178,7 @@ export class BudgetMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'create_budget_item',
|
||||
description: 'Add a budget/expense item to a trip. The cost is split equally among member_ids (omit to split across all trip members, or pass [] for a planning-only entry with no split); for an uneven split, give `members` the amount each participant owes instead. Use `payers` to record who actually paid and how much. Ask the user which trip members share this expense and who paid (resolve user IDs with list_trip_members) rather than guessing.',
|
||||
description: 'Add a budget/expense item to a trip. The cost is split equally among member_ids (omit to split across all trip members, or pass [] for a planning-only entry with no split); for an uneven split, give `members` the amount each participant owes instead. Use `payers` to record who actually paid and how much. Ask the user which trip members share this expense and who paid (resolve user IDs with list_trip_members) rather than guessing. A foreign currency is frozen at the exchange rate the server quotes today; when the server has none, the expense counts in no balance or total and is listed under `unconverted` in get_settlement_summary until freeze_budget_rates pins one.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
name: z.string().min(1).max(200),
|
||||
@@ -249,7 +250,7 @@ export class BudgetMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'update_budget_item',
|
||||
description: 'Update an existing budget/expense item in a trip. You can also re-split it (equally via member_ids, unevenly via members), change the currency it was entered in, move it to another date, and record who actually paid via payers (amounts in the expense currency). When changing who shares an expense or who paid, ask the user rather than guessing; resolve user IDs with list_trip_members.',
|
||||
description: 'Update an existing budget/expense item in a trip. You can also re-split it (equally via member_ids, unevenly via members), change the currency it was entered in, move it to another date, and record who actually paid via payers (amounts in the expense currency). When changing who shares an expense or who paid, ask the user rather than guessing; resolve user IDs with list_trip_members. A foreign currency is frozen at the exchange rate the server quotes today; when the server has none, the expense counts in no balance or total and is listed under `unconverted` in get_settlement_summary until freeze_budget_rates pins one.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
itemId: z.number().int().positive(),
|
||||
@@ -396,7 +397,7 @@ export class BudgetMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'get_settlement_summary',
|
||||
description: "See each member's net balance, the suggested payments to settle shared expenses, and what the trip finally costs each member once every reimbursement is accounted for (`finalBudgets`, each figure with the rows it is made of under `sources`). Amounts are in the trip's base currency. Call this before recording a settlement so you know who should pay whom and how much.",
|
||||
description: "See each member's net balance, the suggested payments to settle shared expenses, and what the trip finally costs each member once every reimbursement is accounted for (`finalBudgets`, each figure with the rows it is made of under `sources`). Amounts are in `summary.currency`: the `base` asked for when the server can quote it, otherwise the trip's base currency. An expense or payment in a foreign currency with no exchange rate is left out of every figure and listed under `summary.unconverted` (item_ids, settlement_ids, currencies); freeze_budget_rates pins today's rate on those. Call this before recording a settlement so you know who should pay whom and how much.",
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
base: z.string().max(10).optional().describe('ISO currency code to compute balances in; defaults to the trip currency'),
|
||||
@@ -431,7 +432,7 @@ export class BudgetMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'create_settlement',
|
||||
description: "Record a settle-up payment: from_user_id paid to_user_id the given amount to settle shared expenses. The amount is in the trip's base currency unless `currency` says otherwise. Use get_settlement_summary first to find who owes whom and how much.",
|
||||
description: "Record a settle-up payment: from_user_id paid to_user_id the given amount to settle shared expenses. The amount is in the trip's base currency unless `currency` says otherwise. Use get_settlement_summary first to find who owes whom and how much. When the server has no exchange rate for a foreign `currency`, the payment counts in no balance and is listed under `unconverted` in get_settlement_summary until freeze_budget_rates pins one.",
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
from_user_id: z.number().int().positive().describe('User ID of the member who paid'),
|
||||
@@ -461,7 +462,7 @@ export class BudgetMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'update_settlement',
|
||||
description: 'Update a recorded settle-up payment (who paid, who received, the amount and the currency it was made in). Every field is a full replace, so restate the ones that stay the same.',
|
||||
description: 'Update a recorded settle-up payment (who paid, who received, the amount and the currency it was made in). Every field is a full replace, so restate the ones that stay the same. When the server has no exchange rate for a foreign `currency`, the payment counts in no balance and is listed under `unconverted` in get_settlement_summary until freeze_budget_rates pins one.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
settlementId: z.number().int().positive(),
|
||||
@@ -511,6 +512,31 @@ export class BudgetMcp {
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
// --- EXCHANGE RATES ---
|
||||
|
||||
@Tool({
|
||||
name: 'freeze_budget_rates',
|
||||
description: "Pin today's server exchange rate on every expense and settle-up payment of a trip that is in a foreign currency and has no rate frozen yet. That takes in the rows get_settlement_summary lists under `unconverted`, which count in no balance or total until then, and also foreign rows it still converts at today's live rate. Rows that already carry a frozen rate, rows in the trip currency and rows without a currency are never touched, and no rate is taken from the caller. Returns the rows it froze (`items`, `settlements`) and the currencies the server could not quote (`unresolved`), whose rows stay unfrozen.",
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: budgetAddonOn,
|
||||
access: { group: 'budget', mode: 'write' },
|
||||
})
|
||||
async freezeBudgetRates({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('budget_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
// The same service call as POST …/budget/freeze-rates, without a lent rate table:
|
||||
// a rate from an MCP caller is never frozen, like everywhere else on this surface.
|
||||
const healed = await this.budget.freezeMissingRates(tripId);
|
||||
if (!healed) return errorResult('The trip currency changed. Reload and try again.');
|
||||
for (const item of healed.items) this.guards.safeBroadcast(tripId, 'budget:updated', { item });
|
||||
for (const settlement of healed.settlements) this.guards.safeBroadcast(tripId, 'budget:settlement-updated', { settlement });
|
||||
return ok(healed);
|
||||
}
|
||||
|
||||
// --- RESOURCES ---
|
||||
|
||||
@ResourceTemplate({
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService, type TripAccess } from '../database/database.service';
|
||||
import type { BudgetParticipantFinal, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import type { BudgetFallbackFx, BudgetParticipantFinal, BudgetUnconverted, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { byCodeUnit } from '../common/compare';
|
||||
import type { User, BudgetItem, BudgetItemMember, BudgetItemPayer, BudgetItemReceipt } from '../../types';
|
||||
import { ExchangeRatesService } from './exchange-rates.service';
|
||||
|
||||
@@ -89,41 +90,58 @@ function allocateDisplayCents(cents: number[], factor: number, total = Math.roun
|
||||
}
|
||||
|
||||
/**
|
||||
* An amount of a row, in the row's own currency, in the trip currency. The rate frozen
|
||||
* when the row was entered wins (#1335), so a booked expense keeps the value it was
|
||||
* booked at. A row written before the freeze existed (rate 1 or none) converts through
|
||||
* today's `rates`, units of each currency per 1 of their base, and without them stays
|
||||
* as it is. Pre-rework rows store currency = NULL, which means the trip's own.
|
||||
* What `exchange_rate` holds on a row whose rate was never frozen. The column is
|
||||
* `REAL NOT NULL DEFAULT 1`, so without a migration 1 is the only way to store "no
|
||||
* rate". It is read in exactly two places, isFrozenRate and UNFROZEN_SQL; nothing
|
||||
* else in this file compares a rate with 1.
|
||||
*/
|
||||
const NOT_FROZEN_RATE = 1;
|
||||
|
||||
/** Whether a stored rate is one that was frozen, rather than the "not frozen" sentinel. */
|
||||
function isFrozenRate(rate: number | null | undefined): rate is number {
|
||||
return rate != null && Number.isFinite(rate) && rate > 0 && rate !== NOT_FROZEN_RATE;
|
||||
}
|
||||
|
||||
/** The SQL twin of `!isFrozenRate(exchange_rate)`, for the row tables' own column. */
|
||||
const UNFROZEN_SQL = '(exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)';
|
||||
|
||||
/**
|
||||
* How an amount of a row, in the row's own currency, becomes trip currency, or null when
|
||||
* nothing can convert it. The rate frozen when the row was entered wins (#1335), so a
|
||||
* booked expense keeps the value it was booked at. A row written before the freeze
|
||||
* existed (no frozen rate) converts through today's `rates`, units of each currency per
|
||||
* 1 of their base. Pre-rework rows store currency = NULL, which means the trip's own.
|
||||
*
|
||||
* A foreign row with neither is left out by every caller and reported, rather than read
|
||||
* as if it were already in the trip currency: 8,920,000 VND counted as that many dollars
|
||||
* swamps every balance on the trip.
|
||||
*
|
||||
* The settlement nets with it and every trip total adds up with it, so the two can never
|
||||
* read the same rows differently.
|
||||
*/
|
||||
function toTripAmount(
|
||||
amount: number,
|
||||
function tripConverter(
|
||||
itemCurrency: string | null | undefined,
|
||||
itemRate: number | null | undefined,
|
||||
tripCurrency: string,
|
||||
rates: Record<string, number> | null,
|
||||
): number {
|
||||
): ((amount: number) => number) | null {
|
||||
const cur = (itemCurrency || tripCurrency).toUpperCase();
|
||||
if (cur === tripCurrency) return amount;
|
||||
if (itemRate != null && itemRate > 0 && itemRate !== 1) return amount / itemRate;
|
||||
if (!rates) return amount;
|
||||
const rCur = rates[cur];
|
||||
const rTrip = rates[tripCurrency];
|
||||
if (rCur && rCur > 0 && rTrip && rTrip > 0) return (amount / rCur) * rTrip;
|
||||
return amount;
|
||||
if (cur === tripCurrency) return amount => amount;
|
||||
if (isFrozenRate(itemRate)) return amount => amount / itemRate;
|
||||
const rCur = rates?.[cur];
|
||||
const rTrip = rates?.[tripCurrency];
|
||||
if (rCur && rCur > 0 && rTrip && rTrip > 0) return amount => (amount / rCur) * rTrip;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Units of `to` per 1 `from`, from a set of rates quoted against any base (each rate is
|
||||
* units of that currency per 1 base). 1 when either quote is missing, which leaves an
|
||||
* amount as it is, the way every conversion here degrades without rates.
|
||||
* units of that currency per 1 base). Null when either quote is missing.
|
||||
*/
|
||||
function quoteRatio(rates: Record<string, number> | null, to: string, from: string): number {
|
||||
function quoteRatio(rates: Record<string, number> | null, to: string, from: string): number | null {
|
||||
const rTo = rates?.[to];
|
||||
const rFrom = rates?.[from];
|
||||
return rTo && rTo > 0 && rFrom && rFrom > 0 ? rTo / rFrom : 1;
|
||||
return rTo && rTo > 0 && rFrom && rFrom > 0 ? rTo / rFrom : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -375,18 +393,25 @@ export class BudgetService {
|
||||
* "units of the item/display currency per 1 trip currency" — the settlement
|
||||
* converts with it via `amount / rate`.
|
||||
*
|
||||
* Only freezes for a foreign currency with no explicit rate; degrades to live
|
||||
* rates if the fetch fails. On update it (re)freezes only when the currency
|
||||
* changes (checked against `budget_items`), so an unrelated edit never moves
|
||||
* money. Callers must invoke this *before* the (synchronous) DB write — the raw
|
||||
* create/update stay sync because better-sqlite3 transactions can't await.
|
||||
* Only freezes for a foreign currency with no explicit rate. The server's own rate
|
||||
* comes first; `fallback_fx`, rates the caller lent for this write, only fills a
|
||||
* currency the server cannot quote (resolveRate). With neither, a new row is
|
||||
* stored unfrozen and left out of every figure until a rate turns up. On update it
|
||||
* (re)freezes only when the currency changes (checked against `budget_items`), so
|
||||
* an unrelated edit never moves money, and a change with no rate at all resets the
|
||||
* row to unfrozen instead of keeping the old currency's rate. `fallback_fx` is taken
|
||||
* off `data` either way, so it never reaches the write. Callers must invoke this
|
||||
* *before* the (synchronous) DB write: the raw create/update stay sync because
|
||||
* better-sqlite3 transactions can't await.
|
||||
*/
|
||||
async freezeForeignRate(
|
||||
tripId: string | number,
|
||||
data: { currency?: string | null; exchange_rate?: number },
|
||||
data: { currency?: string | null; exchange_rate?: number; fallback_fx?: BudgetFallbackFx },
|
||||
existingItemId?: string | number,
|
||||
existingCurrency?: string | null,
|
||||
): Promise<void> {
|
||||
const fallback = data.fallback_fx;
|
||||
delete data.fallback_fx;
|
||||
if (data.exchange_rate != null) return; // an explicit rate from the caller wins
|
||||
const cur = (data.currency || '').toUpperCase();
|
||||
if (!cur) return; // currency not being set in this request
|
||||
@@ -397,16 +422,98 @@ export class BudgetService {
|
||||
if (existingCurrency !== undefined) {
|
||||
prior = (existingCurrency || '').toUpperCase();
|
||||
} else if (existingItemId != null) {
|
||||
const existing = this.db.get<{ currency?: string }>('SELECT currency FROM budget_items WHERE id = ?', existingItemId);
|
||||
const existing = this.db.get<{ currency?: string }>('SELECT currency FROM budget_items WHERE id = ? AND trip_id = ?', existingItemId, tripId);
|
||||
if (existing) prior = (existing.currency || '').toUpperCase();
|
||||
}
|
||||
if (prior !== undefined && prior === cur) return; // currency unchanged
|
||||
const trip = this.db.get<{ currency?: string }>('SELECT currency FROM trips WHERE id = ?', tripId);
|
||||
const tripCur = (trip?.currency || 'EUR').toUpperCase();
|
||||
const tripCur = this.tripCurrency(tripId);
|
||||
if (cur === tripCur) return; // same as the trip currency → no conversion to freeze
|
||||
const rates = await this.exchangeRates.getRates(tripCur);
|
||||
const r = rates?.[cur];
|
||||
if (r && r > 0) data.exchange_rate = r;
|
||||
const rate = this.resolveRate(tripCur, cur, await this.exchangeRates.getRates(tripCur), fallback);
|
||||
if (rate !== null) data.exchange_rate = rate;
|
||||
// The update SQL keeps the stored rate when none is sent, which left the old
|
||||
// currency's rate on the row (a USD 1.08 on a VND bill) and counted it as frozen.
|
||||
else if (prior !== undefined) data.exchange_rate = NOT_FROZEN_RATE;
|
||||
}
|
||||
|
||||
/** The trip's currency, upper case, EUR when it has none (the default the app reads). */
|
||||
private tripCurrency(tripId: string | number): string {
|
||||
const trip = this.db.get<{ currency?: string | null }>('SELECT currency FROM trips WHERE id = ?', tripId);
|
||||
return (trip?.currency || 'EUR').toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* The rate to freeze `cur` at on a `tripCur` trip: the server's own quote, else the one
|
||||
* the caller lent, but only while the lent table is quoted against the trip currency
|
||||
* (a table against the old currency after a switch would freeze the wrong figure).
|
||||
* A result that is not a usable frozen rate, exactly 1 among them, counts as none.
|
||||
*/
|
||||
private resolveRate(
|
||||
tripCur: string,
|
||||
cur: string,
|
||||
serverRates: Record<string, number> | null,
|
||||
fallback: BudgetFallbackFx | undefined,
|
||||
): number | null {
|
||||
const own = serverRates?.[cur];
|
||||
if (isFrozenRate(own)) return own;
|
||||
const lent = fallback && fallback.base.toUpperCase() === tripCur ? fallback.rates[cur] : undefined;
|
||||
return isFrozenRate(lent) ? lent : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeze a rate onto every expense and transfer in a foreign currency that never
|
||||
* froze one: the rows the settlement lists as `unconverted`, and also those it still
|
||||
* converts at today's live rate. Today's server rate first, `fallback` (rates the
|
||||
* caller holds) for what the server cannot quote. A row that is frozen, in the trip
|
||||
* currency or without a currency is never touched, so a second call heals nothing.
|
||||
*
|
||||
* The write is a compare-and-set in one transaction: only rows that are still
|
||||
* unfrozen are updated, and nothing is written when the trip currency changed while
|
||||
* the rates were fetched (null, so the caller can say so). A healthy trip with
|
||||
* nothing pending returns before any fetch.
|
||||
*/
|
||||
async freezeMissingRates(
|
||||
tripId: string | number,
|
||||
fallback?: BudgetFallbackFx,
|
||||
): Promise<{ items: BudgetItem[]; settlements: NonNullable<ReturnType<BudgetService['getSettlement']>>[]; unresolved: string[] } | null> {
|
||||
const tripCur = this.tripCurrency(tripId);
|
||||
const pendingWhere = `trip_id = ? AND currency IS NOT NULL AND currency != '' AND UPPER(currency) != ? AND ${UNFROZEN_SQL}`;
|
||||
const pending = this.db.all<{ cur: string }>(`
|
||||
SELECT UPPER(currency) AS cur FROM budget_items WHERE ${pendingWhere}
|
||||
UNION
|
||||
SELECT UPPER(currency) AS cur FROM budget_settlements WHERE ${pendingWhere}
|
||||
ORDER BY cur
|
||||
`, tripId, tripCur, tripId, tripCur).map(r => r.cur);
|
||||
if (pending.length === 0) return { items: [], settlements: [], unresolved: [] };
|
||||
|
||||
const serverRates = await this.exchangeRates.getRates(tripCur);
|
||||
const resolved: [string, number][] = [];
|
||||
const unresolved: string[] = [];
|
||||
for (const cur of pending) {
|
||||
const rate = this.resolveRate(tripCur, cur, serverRates, fallback);
|
||||
if (rate === null) unresolved.push(cur);
|
||||
else resolved.push([cur, rate]);
|
||||
}
|
||||
if (resolved.length === 0) return { items: [], settlements: [], unresolved };
|
||||
|
||||
const written = this.db.transaction(() => {
|
||||
if (this.tripCurrency(tripId) !== tripCur) return null;
|
||||
const ids = { budget_items: [] as number[], budget_settlements: [] as number[] };
|
||||
for (const table of ['budget_items', 'budget_settlements'] as const) {
|
||||
const where = `trip_id = ? AND UPPER(currency) = ? AND ${UNFROZEN_SQL}`;
|
||||
for (const [cur, rate] of resolved) {
|
||||
ids[table].push(...this.db.all<{ id: number }>(`SELECT id FROM ${table} WHERE ${where}`, tripId, cur).map(r => r.id));
|
||||
this.db.run(`UPDATE ${table} SET exchange_rate = ? WHERE ${where}`, rate, tripId, cur);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
});
|
||||
if (!written) return null;
|
||||
|
||||
return {
|
||||
items: written.budget_items.sort((a, b) => a - b).map(id => this.getBudgetItem(id, tripId)).filter(i => i !== null),
|
||||
settlements: written.budget_settlements.sort((a, b) => a - b).map(id => this.getSettlement(id, tripId)).filter(s => s !== null),
|
||||
unresolved,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -943,18 +1050,19 @@ export class BudgetService {
|
||||
JOIN users u ON bm.user_id = u.id
|
||||
WHERE bi.trip_id = ?
|
||||
`, tripId);
|
||||
const toTripCents = (amount: number, item: { currency: string | null; exchange_rate: number | null }) =>
|
||||
Math.round(toTripAmount(amount, item.currency, item.exchange_rate, tripCurrency, rates) * 100);
|
||||
|
||||
const people = new Map<number, { user_id: number; username: string; avatar: string | null; assigned: number; paid: number; items_count: number }>();
|
||||
for (const item of items) {
|
||||
const own = members.filter(m => m.budget_item_id === item.id);
|
||||
if (own.length === 0) continue;
|
||||
// A foreign row nothing can convert counts for nobody, as in the settlement.
|
||||
const convert = tripConverter(item.currency, item.exchange_rate, tripCurrency, rates);
|
||||
if (!convert) continue;
|
||||
const toTripCents = (amount: number) => Math.round(convert(amount) * 100);
|
||||
// A member with an amount of their own owes exactly that; the rest split the
|
||||
// total evenly, as the query this replaces did.
|
||||
const equal = this.splitEqualShares(toTripCents(item.total_price || 0, item), own, item.id);
|
||||
const equal = this.splitEqualShares(toTripCents(item.total_price || 0), own, item.id);
|
||||
for (const m of own) {
|
||||
const share = m.amount !== null && m.amount !== undefined ? toTripCents(m.amount, item) : (equal[m.user_id] || 0);
|
||||
const share = m.amount !== null && m.amount !== undefined ? toTripCents(m.amount) : (equal[m.user_id] || 0);
|
||||
let p = people.get(m.user_id);
|
||||
if (!p) {
|
||||
p = { user_id: m.user_id, username: m.username, avatar: m.avatar, assigned: 0, paid: 0, items_count: 0 };
|
||||
@@ -980,17 +1088,24 @@ export class BudgetService {
|
||||
* What the trip's expenses add up to in the trip currency, overall and per category
|
||||
* (#2525). Every row is converted once, the way the settlement converts it, and
|
||||
* rounded to a whole cent before anything is added. Summing total_price as stored adds
|
||||
* dollars to euros and labels the result with the trip currency.
|
||||
* dollars to euros and labels the result with the trip currency. A foreign row nothing
|
||||
* can convert is left out and its id listed under `unconverted`.
|
||||
*/
|
||||
tripTotals(tripId: string | number, tripCurrency: string, rates: Record<string, number> | null = null): { total: number; byCategory: Record<string, number> } {
|
||||
tripTotals(tripId: string | number, tripCurrency: string, rates: Record<string, number> | null = null): { total: number; byCategory: Record<string, number>; unconverted: number[] } {
|
||||
const trip = (tripCurrency || 'EUR').toUpperCase();
|
||||
const rows = this.db.all<{ category: string | null; total_price: number | null; currency: string | null; exchange_rate: number | null }>(
|
||||
'SELECT category, total_price, currency, exchange_rate FROM budget_items WHERE trip_id = ? ORDER BY id', tripId,
|
||||
const rows = this.db.all<{ id: number; category: string | null; total_price: number | null; currency: string | null; exchange_rate: number | null }>(
|
||||
'SELECT id, category, total_price, currency, exchange_rate FROM budget_items WHERE trip_id = ? ORDER BY id', tripId,
|
||||
);
|
||||
let total = 0;
|
||||
const byCategory: Record<string, number> = {};
|
||||
const unconverted: number[] = [];
|
||||
for (const r of rows) {
|
||||
const cents = Math.round(toTripAmount(r.total_price || 0, r.currency, r.exchange_rate, trip, rates) * 100);
|
||||
const convert = tripConverter(r.currency, r.exchange_rate, trip, rates);
|
||||
if (!convert) {
|
||||
unconverted.push(r.id);
|
||||
continue;
|
||||
}
|
||||
const cents = Math.round(convert(r.total_price || 0) * 100);
|
||||
total += cents;
|
||||
const cat = r.category || '';
|
||||
byCategory[cat] = (byCategory[cat] || 0) + cents;
|
||||
@@ -998,6 +1113,7 @@ export class BudgetService {
|
||||
return {
|
||||
total: total / 100,
|
||||
byCategory: Object.fromEntries(Object.entries(byCategory).map(([cat, cents]) => [cat, cents / 100])),
|
||||
unconverted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1011,7 +1127,7 @@ export class BudgetService {
|
||||
const unbooked = this.db.get(`
|
||||
SELECT 1 FROM budget_items
|
||||
WHERE trip_id = ? AND currency IS NOT NULL AND currency != '' AND UPPER(currency) != ?
|
||||
AND (exchange_rate IS NULL OR exchange_rate <= 0 OR exchange_rate = 1)
|
||||
AND ${UNFROZEN_SQL}
|
||||
LIMIT 1
|
||||
`, tripId, trip);
|
||||
return unbooked ? this.exchangeRates.getRates(trip) : null;
|
||||
@@ -1066,13 +1182,19 @@ export class BudgetService {
|
||||
* behind each figure (`sources`) travel with it, in the same display cents: an
|
||||
* expense list converted again on the client with today's rate would not add up
|
||||
* to a figure that was booked at the rate frozen on entry.
|
||||
*
|
||||
* A row nothing can convert (a foreign currency with no frozen rate and no live
|
||||
* one) is left out whole and listed under `unconverted`, so Σ balances stays 0.
|
||||
* `currency` says what the amounts are in: the display currency when there is a
|
||||
* quote for it (the rates, else `baseRate`, the caller's own units of display
|
||||
* currency per 1 trip currency), otherwise the trip currency.
|
||||
*/
|
||||
calculateSettlement(
|
||||
tripId: string | number,
|
||||
opts: { base?: string; rates?: Record<string, number> | null; tripCurrency?: string } = {},
|
||||
opts: { base?: string; rates?: Record<string, number> | null; tripCurrency?: string; baseRate?: number } = {},
|
||||
) {
|
||||
const base = (opts.base || opts.tripCurrency || 'EUR').toUpperCase();
|
||||
const tripCurrency = (opts.tripCurrency || base).toUpperCase();
|
||||
const requested = (opts.base || opts.tripCurrency || 'EUR').toUpperCase();
|
||||
const tripCurrency = (opts.tripCurrency || requested).toUpperCase();
|
||||
const rates = opts.rates ?? null;
|
||||
// Net the whole settlement in the trip's canonical currency and convert the final
|
||||
// totals to the display currency once, instead of netting in the (moving) display
|
||||
@@ -1085,8 +1207,8 @@ export class BudgetService {
|
||||
// Prefer the FX rate frozen at entry time (#1335): a settled expense keeps the rate
|
||||
// it was booked at, so a later live-rate drift doesn't re-open it with a residual.
|
||||
// Legacy rows without a frozen rate convert via base with live rates.
|
||||
const toTrip = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number =>
|
||||
toTripAmount(amount, itemCurrency, itemRate, tripCurrency, rates);
|
||||
const converterFor = (itemCurrency: string | null | undefined, itemRate?: number | null) =>
|
||||
tripConverter(itemCurrency, itemRate, tripCurrency, rates);
|
||||
// trip-currency → display currency, applied once to the final netted totals.
|
||||
// Held as a plain factor so it is exactly linear: the balances are converted as
|
||||
// one set (allocateDisplayCents) rather than one at a time, which is what keeps
|
||||
@@ -1098,29 +1220,32 @@ export class BudgetService {
|
||||
// the display currency converts back to exactly what was typed (#2525). Taken the
|
||||
// other way round, from the display currency's quote, the two quotes are not exact
|
||||
// inverses and 12,345.67 USD came back as 12,346.06.
|
||||
const displayFactor = base === tripCurrency ? 1 : quoteRatio(rates, base, tripCurrency);
|
||||
//
|
||||
// Without a quote, the caller's own figure for the pair (`baseRate`) stands in for
|
||||
// the missing display quote, and for nothing else: a row with a currency of its own
|
||||
// is never converted with it. Like a live quote, it also reads a legacy transfer
|
||||
// without a currency, which is taken to be in the display currency. With neither,
|
||||
// the answer stays in the trip currency and says so, rather than printing trip cents
|
||||
// as the display currency.
|
||||
const baseRate = opts.baseRate != null && Number.isFinite(opts.baseRate) && opts.baseRate > 0 ? opts.baseRate : null;
|
||||
const quoted = requested === tripCurrency ? 1 : (quoteRatio(rates, requested, tripCurrency) ?? baseRate);
|
||||
const currency = quoted === null ? tripCurrency : requested;
|
||||
const displayFactor = quoted ?? 1;
|
||||
// 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
|
||||
// toTrip for expenses. Legacy rows (currency = NULL) have no frozen rate, so fall
|
||||
// back to the old behaviour: assume they were entered in the current display base
|
||||
// and convert with live rates.
|
||||
const settleToTrip = (amount: number, sCurrency?: string | null, sRate?: number | null): number => {
|
||||
if (sCurrency) {
|
||||
const cur = sCurrency.toUpperCase();
|
||||
if (cur === tripCurrency) return amount;
|
||||
if (sRate != null && sRate > 0 && sRate !== 1) return amount / sRate;
|
||||
// Frozen currency but no usable rate (fetch failed at settle time): live fallback.
|
||||
if (rates) {
|
||||
const rCur = rates[cur];
|
||||
const rTrip = rates[tripCurrency];
|
||||
if (rCur && rCur > 0 && rTrip && rTrip > 0) return (amount / rCur) * rTrip;
|
||||
}
|
||||
return amount;
|
||||
}
|
||||
// The inverse of the display factor, so such a transfer reads back as entered.
|
||||
return amount / displayFactor;
|
||||
};
|
||||
// the expenses; a frozen currency without a usable rate falls back to live rates,
|
||||
// and without those the transfer is left out like an expense. Legacy rows
|
||||
// (currency = NULL) have no frozen rate, so fall back to the old behaviour: assume
|
||||
// they were entered in the current display base and convert with live rates.
|
||||
const settleConverterFor = (sCurrency?: string | null, sRate?: number | null) =>
|
||||
sCurrency
|
||||
? tripConverter(sCurrency, sRate, tripCurrency, rates)
|
||||
// The inverse of the display factor, so such a transfer reads back as entered.
|
||||
: (amount: number) => amount / displayFactor;
|
||||
const unconvertedItems: number[] = [];
|
||||
const unconvertedSettlements: number[] = [];
|
||||
const unconvertedCurrencies = new Set<string>();
|
||||
|
||||
const items = this.db.all<BudgetItem>('SELECT * FROM budget_items WHERE trip_id = ?', tripId);
|
||||
const allMembers = this.db.all<BudgetItemMember & { budget_item_id: number }>(`
|
||||
@@ -1141,8 +1266,6 @@ 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 toTripCents = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number =>
|
||||
Math.round(toTrip(amount, itemCurrency, itemRate) * 100);
|
||||
const balances: Record<number, { user_id: number; username: string; avatar_url: string | null; cents: 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 };
|
||||
@@ -1167,6 +1290,15 @@ export class BudgetService {
|
||||
const finalUnit = (exactTripCents: number) => (displayFactor === 1 ? Math.round(exactTripCents) : exactTripCents);
|
||||
|
||||
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);
|
||||
if (!convert) {
|
||||
unconvertedItems.push(item.id);
|
||||
unconvertedCurrencies.add((item.currency || '').toUpperCase());
|
||||
continue;
|
||||
}
|
||||
const toTripCents = (amount: number): number => Math.round(convert(amount) * 100);
|
||||
const members = allMembers.filter(m => m.budget_item_id === item.id);
|
||||
const payers = allPayers.filter(p => p.budget_item_id === item.id);
|
||||
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
|
||||
@@ -1194,7 +1326,7 @@ export class BudgetService {
|
||||
// refund (#2176) — is debited by the same arithmetic: their credit is negative.
|
||||
let creditCents = 0;
|
||||
for (const p of payers) {
|
||||
const exact = toTrip(p.amount, item.currency, item.exchange_rate) * 100;
|
||||
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);
|
||||
@@ -1216,7 +1348,7 @@ export class BudgetService {
|
||||
const equalShares = !hasCustomSplit ? this.splitEqualShares(creditCents, members, item.id) : {};
|
||||
for (const m of members) {
|
||||
const memberShare = hasCustomSplit && m.amount !== null && m.amount !== undefined
|
||||
? toTripCents(m.amount, item.currency, item.exchange_rate)
|
||||
? toTripCents(m.amount)
|
||||
: (equalShares[m.user_id] || 0);
|
||||
ensure(m.user_id, m).cents -= memberShare;
|
||||
}
|
||||
@@ -1233,9 +1365,15 @@ export class BudgetService {
|
||||
return balances[id];
|
||||
};
|
||||
for (const s of settlements) {
|
||||
const convert = settleConverterFor(s.currency, s.exchange_rate);
|
||||
if (!convert) {
|
||||
unconvertedSettlements.push(s.id);
|
||||
unconvertedCurrencies.add((s.currency || '').toUpperCase());
|
||||
continue;
|
||||
}
|
||||
// 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 = settleToTrip(s.amount, s.currency, s.exchange_rate) * 100;
|
||||
const exact = convert(s.amount) * 100;
|
||||
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;
|
||||
@@ -1327,6 +1465,12 @@ export class BudgetService {
|
||||
},
|
||||
};
|
||||
}) satisfies BudgetParticipantFinal[],
|
||||
currency,
|
||||
unconverted: {
|
||||
item_ids: unconvertedItems,
|
||||
settlement_ids: unconvertedSettlements,
|
||||
currencies: [...unconvertedCurrencies].sort(byCodeUnit),
|
||||
} satisfies BudgetUnconverted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1441,22 +1585,25 @@ export class BudgetService {
|
||||
* trip currency's own quote, the one every entry rate was frozen from, so a same-day
|
||||
* amount in the display currency round-trips to the cent and paying what settle-up
|
||||
* offers closes the balance (#2525). The display currency's quote only stands in when
|
||||
* the trip's cannot be fetched.
|
||||
* the trip's cannot be fetched, and `baseRate` (the caller's own units of display
|
||||
* currency per 1 trip currency) only when neither can. It only stands in for that
|
||||
* missing display quote, which also reads a legacy transfer without a currency (taken
|
||||
* to be in the display currency, as with a live quote).
|
||||
*/
|
||||
async settlement(tripId: string | number, base: string | undefined, tripCurrency: string) {
|
||||
async settlement(tripId: string | number, base: string | undefined, tripCurrency: string, baseRate?: number) {
|
||||
const trip = (tripCurrency || 'EUR').toUpperCase();
|
||||
const effectiveBase = (base || trip).toUpperCase();
|
||||
const rates = (await this.exchangeRates.getRates(trip))
|
||||
?? (effectiveBase === trip ? null : await this.exchangeRates.getRates(effectiveBase));
|
||||
return this.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency: trip });
|
||||
return this.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency: trip, baseRate });
|
||||
}
|
||||
|
||||
async create(tripId: string, data: Parameters<BudgetService['createBudgetItem']>[1]) {
|
||||
async create(tripId: string, data: Parameters<BudgetService['createBudgetItem']>[1] & { fallback_fx?: BudgetFallbackFx }) {
|
||||
await this.freezeForeignRate(tripId, data);
|
||||
return this.createBudgetItem(tripId, data);
|
||||
}
|
||||
|
||||
async update(id: string | number, tripId: string | number, data: Parameters<BudgetService['updateBudgetItem']>[2]) {
|
||||
async update(id: string | number, tripId: string | number, data: Parameters<BudgetService['updateBudgetItem']>[2] & { fallback_fx?: BudgetFallbackFx }) {
|
||||
await this.freezeForeignRate(tripId, data, id);
|
||||
return this.updateBudgetItem(id, tripId, data);
|
||||
}
|
||||
@@ -1482,7 +1629,7 @@ export class BudgetService {
|
||||
return roster.has(data.from_user_id) && roster.has(data.to_user_id);
|
||||
}
|
||||
|
||||
async createSettlement(tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null }, userId: number) {
|
||||
async createSettlement(tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null; fallback_fx?: BudgetFallbackFx }, userId: number) {
|
||||
if (!this.settlementPartiesOnTrip(tripId, data)) return null;
|
||||
// Freeze the FX rate for the display currency the amount was entered in so the
|
||||
// transfer keeps cancelling its expense when live rates drift (#1445).
|
||||
@@ -1490,7 +1637,7 @@ export class BudgetService {
|
||||
return this.insertSettlement(tripId, data, userId);
|
||||
}
|
||||
|
||||
async updateSettlement(id: string | number, tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null }) {
|
||||
async updateSettlement(id: string | number, tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null; fallback_fx?: BudgetFallbackFx }) {
|
||||
// Pass the settlement's stored currency so an edit that doesn't change it keeps
|
||||
// the already-frozen rate (#1445) — otherwise a live-rate drift would re-open a
|
||||
// settled position on an unrelated edit.
|
||||
|
||||
@@ -8,14 +8,16 @@ import { Injectable } from '@nestjs/common';
|
||||
* settlement request never hammers the upstream. Rates are "units of X per 1
|
||||
* base", so an amount in currency C converts to base as `amount / rates[C]`.
|
||||
*
|
||||
* Everything degrades gracefully: if the fetch fails (offline, upstream down),
|
||||
* callers get `null`/identity conversion and amounts are treated as already in
|
||||
* the base currency rather than throwing.
|
||||
* Everything degrades without throwing: if the fetch fails (offline, upstream
|
||||
* down), callers get `null`. Budget rows that already froze a rate still convert;
|
||||
* a foreign row that did not is left out of the figures and reported rather than
|
||||
* read as if it were already in the base currency. A failed fetch is not
|
||||
* remembered: the next request for that base asks the upstream again.
|
||||
*
|
||||
* Moved from the legacy `services/exchangeRateService.ts` (the budget-domain
|
||||
* fold): identical cache/coalescing behavior, `||` falsy-coercion defaults and
|
||||
* null degradation. The cache and inflight maps are deliberately MODULE-scoped,
|
||||
* not instance fields — the DI singleton and the out-of-container instances
|
||||
* not instance fields: the DI singleton and the out-of-container instances
|
||||
* (the trips/airtrail/auth bridges each construct their own) wrap the same
|
||||
* upstream feed, so they must share one cache (same reasoning as the
|
||||
* permissions-cache.ts cache).
|
||||
|
||||
@@ -73,6 +73,8 @@ export class TripReadModelService {
|
||||
total: totals.total,
|
||||
by_category: totals.byCategory,
|
||||
currency: trip.currency,
|
||||
// Rows in a foreign currency with no rate to convert them: in no total above.
|
||||
unconverted_item_ids: totals.unconverted,
|
||||
};
|
||||
|
||||
// Thread the viewer so another member's private/personal packing items (#858)
|
||||
|
||||
@@ -63,9 +63,13 @@ export class TripPromptsMcp {
|
||||
.join('\n');
|
||||
const memberCount = Math.max(1, [summary.members?.owner, ...(summary.members?.collaborators || [])].filter(Boolean).length);
|
||||
const perPerson = (total / memberCount).toFixed(2);
|
||||
// Rows no rate could convert are in none of the figures above; say so rather than
|
||||
// let the total pass for the whole trip.
|
||||
const uncounted = budget?.unconverted_item_ids?.length || 0;
|
||||
const uncountedLine = uncounted > 0 ? `\n\n${uncounted} expense(s) not counted yet: no exchange rate.` : '';
|
||||
return {
|
||||
description: `Budget overview for "${trip?.title || tripId}"`,
|
||||
messages: [{ role: 'user' as const, content: { type: 'text' as const, text: `# Budget: ${trip?.title || 'Trip'}\n\n**Total: ${total} ${currency}** (${perPerson} ${currency} per person)\n\n${lines || 'No expenses recorded.'}` } }],
|
||||
messages: [{ role: 'user' as const, content: { type: 'text' as const, text: `# Budget: ${trip?.title || 'Trip'}\n\n**Total: ${total} ${currency}** (${perPerson} ${currency} per person)\n\n${lines || 'No expenses recorded.'}${uncountedLine}` } }],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user