Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(costs): show the owe and owed cards as unknown instead of settled while the balances are

Maurice918efe35fe88
diff --git a/client/src/components/Budget/CostsPanel.summary.test.tsx b/client/src/components/Budget/CostsPanel.summary.test.tsx
index c2cd31250..703835df6 100644
--- a/client/src/components/Budget/CostsPanel.summary.test.tsx
+++ b/client/src/components/Budget/CostsPanel.summary.test.tsx
@@ -3,7 +3,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
-import { render, screen } from '../../../tests/helpers/render';
+import { render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
@@ -68,7 +68,10 @@ describe('CostsPanel: summary footers and won amounts (#2604)', () => {
it('FE-COSTS-2604-002: with nothing left to settle the outstanding card still says so', async () => {
mount([owedByBob()]);
await screen.findByText('Museum');
- expect(screen.getByRole('region', { name: 'Outstanding amount' })).toHaveTextContent("You're all settled up");
+ // Only once the settlement is read: until then nobody knows whether anything is left.
+ await waitFor(() =>
+ expect(screen.getByRole('region', { name: 'Outstanding amount' })).toHaveTextContent("You're all settled up")
+ );
});
it('FE-COSTS-2604-003: a single expense without a payer reads in the singular', async () => {
diff --git a/client/src/components/Budget/CostsPanel.test.tsx b/client/src/components/Budget/CostsPanel.test.tsx
index aff01472f..4b1f4d308 100644
--- a/client/src/components/Budget/CostsPanel.test.tsx
+++ b/client/src/components/Budget/CostsPanel.test.tsx
@@ -1084,9 +1084,11 @@ describe('CostsPanel — settle up', () => {
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
await screen.findByText('Balances')
- // Settle up, Balances and Final budget all hang off the one failed request.
- await waitFor(() => expect(screen.getAllByText('Unknown error')).toHaveLength(3))
+ // Settle up, Balances, Final budget and the owe and owed cards all hang off the one failed request.
+ await waitFor(() => expect(screen.getAllByText('Unknown error')).toHaveLength(5))
expect(screen.queryByText("Everyone's square")).toBeNull()
+ expect(screen.queryByText("You're all settled up")).toBeNull()
+ expect(screen.queryByText('Nothing owed to you')).toBeNull()
})
it('FE-W5COSTS-013: the "you owe" card lists who I still have to pay', async () => {
diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsx
index 2d806acec..bd0c5da6d 100644
--- a/client/src/components/Budget/CostsPanel.tsx
+++ b/client/src/components/Budget/CostsPanel.tsx
@@ -45,7 +45,7 @@ import { AddRowButton, EditorField, INPUT, PillSelect, Segmented, TEXTAREA } fro
import { CountPill, EYEBROW } from '../Planner/bookings/bookingParts'
import CostsToolbar, { type CostsView } from './CostsToolbar'
import CostsTable, { CostsTableSummary } from './CostsTable'
-import SummaryCard from './CostsSummaryCard'
+import SummaryCard, { UNKNOWN_AMOUNT } from './CostsSummaryCard'
interface CostsPanelProps {
tripId: number
@@ -74,7 +74,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// Display/base currency, the trip's own, the settlement, totals, filters and
// the ledger writes: the same ledger the phone tab runs on.
const {
- me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, knownNames, splitting,
+ me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, balancesKnown, knownNames, splitting,
search, setSearch, segment: filter, setSegment: setFilter, catFilter, setCatFilter, dayFilter, setDayFilter,
totals, filtered, filteredSettlements, catBreakdown, countedCount, leftOutLabel, toggleLeftOutCat, countAllCats, exportCsv: handleExportCsv,
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll, canSettle, setBase, baseOptions,
@@ -287,21 +287,23 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
- <SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={totals.owe} currency={base} locale={locale}
+ <SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale}
icon={<ArrowDown size={18} />} tone="owe"
- foot={totals.owe > 0.01
+ foot={!balancesKnown ? balancesUnknown()
+ : totals.owe > 0.01
? <FlowPills ids={(settlement?.flows || []).filter(f => f.from.user_id === me).map(f => f.to.user_id)} lead={t('costs.to')} Avatar={Avatar} name={personName} />
: <span className="text-content-faint">{t('costs.allSettled')}</span>} />
- <SummaryCard label={t('costs.youreOwed')} sub={t('costs.youreOwedSub')} amount={totals.owed} currency={base} locale={locale}
+ <SummaryCard label={t('costs.youreOwed')} sub={t('costs.youreOwedSub')} amount={balancesKnown ? totals.owed : null} currency={base} locale={locale}
icon={<ArrowUp size={18} />} tone="owed"
- foot={totals.owed > 0.01
+ foot={!balancesKnown ? balancesUnknown()
+ : totals.owed > 0.01
? <FlowPills ids={(settlement?.flows || []).filter(f => f.to.user_id === me).map(f => f.from.user_id)} lead={t('costs.from')} Avatar={Avatar} name={personName} />
: <span className="text-content-faint">{t('costs.nothingOwed')}</span>} />
<SummaryCard label={t('costs.outstanding')} sub={t('costs.outstandingSub')} amount={totals.outstanding} currency={base} locale={locale}
icon={<AlertCircle size={18} />} tone="unfinished"
foot={totals.outstandingCount > 0
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
- : !settlement?.flows?.length && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
+ : balancesKnown && !settlement?.flows?.length && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
{totalCard}
</div>)}
@@ -443,6 +445,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div>
)
+ // The owe and owed cards say why their figure is missing instead of claiming zero.
+ function balancesUnknown() {
+ return <span className="text-content-faint">{t(settlementError ? 'common.unknownError' : 'common.loading')}</span>
+ }
+
// Settle-up and Balances both come from the one settlement request, so they
// share the notice that says the numbers are missing rather than zero.
function loadFailed() {
@@ -521,13 +528,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<div style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', marginBottom: 10, background: '#dc262622', color: '#dc2626' }}><ArrowDown size={17} /></div>
<div className="text-content" style={{ fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t('costs.youOwe')}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))' }}>{t('costs.youOweSub')}</div>
- <div style={{ fontSize: 'calc(27px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 12, display: 'flex', alignItems: 'baseline', color: '#dc2626' }}>{bigMoney(totals.owe, 16, 'var(--c-ink3)')}</div>
+ <div style={{ fontSize: 'calc(27px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 12, display: 'flex', alignItems: 'baseline', color: '#dc2626' }}>{balancesKnown ? bigMoney(totals.owe, 16, 'var(--c-ink3)') : UNKNOWN_AMOUNT}</div>
</div>
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', marginBottom: 10, background: '#16a34a22', color: '#16a34a' }}><ArrowUp size={17} /></div>
<div className="text-content" style={{ fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t('costs.youreOwed')}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))' }}>{t('costs.youreOwedSub')}</div>
- <div style={{ fontSize: 'calc(27px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 12, display: 'flex', alignItems: 'baseline', color: '#16a34a' }}>{bigMoney(totals.owed, 16, 'var(--c-ink3)')}</div>
+ <div style={{ fontSize: 'calc(27px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1, marginTop: 12, display: 'flex', alignItems: 'baseline', color: '#16a34a' }}>{balancesKnown ? bigMoney(totals.owed, 16, 'var(--c-ink3)') : UNKNOWN_AMOUNT}</div>
</div>
</div>
diff --git a/client/src/components/Budget/CostsSummaryCard.test.tsx b/client/src/components/Budget/CostsSummaryCard.test.tsx
index b72ff4f12..8284b4052 100644
--- a/client/src/components/Budget/CostsSummaryCard.test.tsx
+++ b/client/src/components/Budget/CostsSummaryCard.test.tsx
@@ -1,12 +1,12 @@
-// FE-COSTS-CARD-001 to -002: the figure cards on top of the Costs panel
+// FE-COSTS-CARD-001 to -003: the figure cards on top of the Costs panel
import { render, screen, within } from '../../../tests/helpers/render';
import SummaryCard from './CostsSummaryCard';
-const card = (currency: string) => (
+const card = (currency: string, amount: number | null = 1234.5) => (
<SummaryCard
label="Total spend"
sub="Everything the trip has cost"
- amount={1234.5}
+ amount={amount}
currency={currency}
locale="en"
icon={null}
@@ -29,4 +29,11 @@ describe('CostsSummaryCard', () => {
render(card('EURO'));
expect(screen.getByRole('region', { name: 'Total spend' })).toHaveTextContent('1,234.50 EURO');
});
+
+ it('FE-COSTS-CARD-003: an unknown amount shows no figure, not a zero', () => {
+ render(card('USD', null));
+ const region = screen.getByRole('region', { name: 'Total spend' });
+ expect(region).toHaveTextContent('…');
+ expect(region).not.toHaveTextContent('$0.00');
+ });
});
diff --git a/client/src/components/Budget/CostsSummaryCard.tsx b/client/src/components/Budget/CostsSummaryCard.tsx
index 114fb94f9..329b99ad0 100644
--- a/client/src/components/Budget/CostsSummaryCard.tsx
+++ b/client/src/components/Budget/CostsSummaryCard.tsx
@@ -1,6 +1,9 @@
import { currencyDecimals, currencyLocale, formatMoney } from '../../utils/formatters';
import { fs } from '../shared/DialogShell';
+/** What a card shows for a balance that is still loading or could not be read. */
+export const UNKNOWN_AMOUNT = '…';
+
/** A tone's colour, from the status tokens the booking cards use. */
const TONE_COLOR = {
owe: 'var(--danger)',
@@ -26,7 +29,7 @@ export default function SummaryCard({
}: {
label: string;
sub: string;
- amount: number;
+ amount: number | null;
currency: string;
locale: string;
icon: React.ReactNode;
@@ -39,12 +42,15 @@ export default function SummaryCard({
let parts: Intl.NumberFormatPart[] | null = null;
try {
const d = currencyDecimals(currency);
- parts = new Intl.NumberFormat(currencyLocale(currency), {
- style: 'currency',
- currency: (currency || 'EUR').toUpperCase(),
- minimumFractionDigits: d,
- maximumFractionDigits: d,
- }).formatToParts(amount || 0);
+ parts =
+ amount == null
+ ? null
+ : new Intl.NumberFormat(currencyLocale(currency), {
+ style: 'currency',
+ currency: (currency || 'EUR').toUpperCase(),
+ minimumFractionDigits: d,
+ maximumFractionDigits: d,
+ }).formatToParts(amount || 0);
} catch {
parts = null;
}
@@ -92,7 +98,7 @@ export default function SummaryCard({
</span>
))
) : (
- <span>{formatMoney(amount, currency, locale)}</span>
+ <span>{amount == null ? UNKNOWN_AMOUNT : formatMoney(amount, currency, locale)}</span>
)}
</div>
<div className="mt-auto flex flex-wrap items-center gap-1.5 text-content-muted" style={fs(12.5, 'body')}>
diff --git a/client/src/components/Budget/useCostsLedger.test.ts b/client/src/components/Budget/useCostsLedger.test.ts
index f0b6db478..f8c06efa8 100644
--- a/client/src/components/Budget/useCostsLedger.test.ts
+++ b/client/src/components/Budget/useCostsLedger.test.ts
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
import { useCostsLedger } from './useCostsLedger';
import { useFreezeMissingRates } from './useFreezeMissingRates';
-// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-022
+// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-023
const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -394,24 +394,52 @@ describe('useCostsLedger: another currency for this trip (#1683)', () => {
expect(createMock()).not.toHaveBeenCalled();
localStorage.removeItem('trek:costs-currency:7');
});
- it('FE-BUDGET-LEDGER-022: the owe and owed cards count only flows read in the currency shown', async () => {
+ it('FE-BUDGET-LEDGER-022: the owe and owed cards count flows in the currency shown, and are unknown otherwise', async () => {
localStorage.removeItem('trek:costs-currency:7');
const { result } = setup();
await waitFor(() => expect(result.current.totals.owe).toBe(15));
expect(result.current.totals.owed).toBe(5);
+ expect(result.current.balancesKnown).toBe(true);
settlementMock().mockRejectedValueOnce(new Error('Settlement not available offline'));
act(() => result.current.setBase('JPY'));
await waitFor(() => expect(result.current.settlementError).toBe(true));
- expect(result.current.totals.owe).toBe(0);
- expect(result.current.totals.owed).toBe(0);
+ expect(result.current.balancesKnown).toBe(false);
+ // Flows answered in the trip currency go over at the rate the read sent along.
settlementMock().mockResolvedValueOnce({ ...SETTLEMENT, currency: 'EUR' });
act(() => result.current.loadSettlement());
await waitFor(() => expect(result.current.settlementError).toBe(false));
- expect(result.current.totals.owe).toBe(0);
+ expect(result.current.balancesKnown).toBe(true);
+ expect(result.current.totals.owe).toBe(17);
+ expect(result.current.totals.owed).toBe(6);
+ expect(result.current.canSettle).toBe(false);
settlementMock().mockResolvedValueOnce({ ...SETTLEMENT, currency: 'JPY' });
act(() => result.current.loadSettlement());
await waitFor(() => expect(result.current.totals.owe).toBe(15));
expect(result.current.totals.owed).toBe(5);
+ expect(result.current.canSettle).toBe(true);
+ localStorage.removeItem('trek:costs-currency:7');
+ });
+
+ it('FE-BUDGET-LEDGER-023: the balances are unknown while the first read runs and in a currency with no rate', async () => {
+ localStorage.removeItem('trek:costs-currency:7');
+ let answer: (s: CostsSettlementResponse) => void = () => undefined;
+ settlementMock().mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ answer = resolve;
+ })
+ );
+ const { result } = setup();
+ await waitFor(() => expect(settlementMock()).toHaveBeenCalledTimes(1));
+ expect(result.current.balancesKnown).toBe(false);
+ await act(async () => answer(SETTLEMENT));
+ await waitFor(() => expect(result.current.balancesKnown).toBe(true));
+ // An answer in neither the trip nor the display currency cannot be converted.
+ settlementMock().mockResolvedValueOnce({ ...SETTLEMENT, currency: 'GBP' });
+ act(() => result.current.setBase('JPY'));
+ await waitFor(() => expect(result.current.settlement).toEqual({ ...SETTLEMENT, currency: 'GBP' }));
+ expect(result.current.balancesKnown).toBe(false);
+ expect(result.current.totals.owe).toBe(0);
localStorage.removeItem('trek:costs-currency:7');
});
});
diff --git a/client/src/components/Budget/useCostsLedger.ts b/client/src/components/Budget/useCostsLedger.ts
index 2911e9364..c0c4c0d28 100644
--- a/client/src/components/Budget/useCostsLedger.ts
+++ b/client/src/components/Budget/useCostsLedger.ts
@@ -11,6 +11,7 @@ import type { TripStoreState } from '../../store/tripStore';
import { useServerPing } from '../../sync/useServerPing';
import type { BudgetItem, Trip } from '../../types';
import { downloadBlob } from '../../utils/fileDownload';
+import { currencyDecimals } from '../../utils/formatters';
import { localToday } from '../Planner/today';
import { COST_CAT_META } from './costsCategories';
import {
@@ -226,12 +227,22 @@ export function useCostsLedger({
const activeSegment = splitting ? segment : 'all';
// Names for people the expenses still name after they left the trip (#2604).
const knownNames = useMemo(() => knownPersonNames(budgetItems, settlement), [budgetItems, settlement]);
+ // The owe and owed cards print in the display currency. Flows the server answered in
+ // the trip currency go over at the rate the read sent along; while a read runs, after
+ // one failed or in any other currency the balances are unknown, which is not zero.
+ const shownFlows = useMemo(() => {
+ if (settlementError || !settlement) return null;
+ if (settledIn === base) return flows;
+ if (settledIn !== tripCurrency || displayPerTrip == null) return null;
+ const unit = 10 ** currencyDecimals(base);
+ return flows.map((f) => ({ ...f, amount: Math.round(f.amount * displayPerTrip * unit) / unit }));
+ }, [settlementError, settlement, settledIn, base, tripCurrency, displayPerTrip, flows]);
+ const balancesKnown = shownFlows != null;
// `ctx` carries the rates. They can land after the expenses, and without it in the
// deps the cards kept the sums they were first added up with while the rows moved on.
- // The owe and owed cards print in the display currency too, so they count the same flows.
const totals = useMemo(
- () => computeTotals(budgetItems, flowsInBase ? flows : [], ctx, shareOf, leftOutCats),
- [budgetItems, flowsInBase, flows, ctx, shareOf, leftOutCats]
+ () => computeTotals(budgetItems, shownFlows ?? [], ctx, shareOf, leftOutCats),
+ [budgetItems, shownFlows, ctx, shareOf, leftOutCats]
);
const filtered = useMemo(
() =>
@@ -355,6 +366,7 @@ export function useCostsLedger({
settlementError,
loadSettlement,
flows,
+ balancesKnown,
canSettle,
splitting,
knownNames,
diff --git a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
index 216e75d91..f0d1a8282 100644
--- a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
@@ -11,6 +11,7 @@ import { openFile } from '../../../../utils/fileDownload'
import MCostSheet from '../sheets/MCostSheet'
import { ReceiptPreviewModal } from '../../../../components/Budget/ReceiptPreviewModal'
import { useCostsLedger } from '../../../../components/Budget/useCostsLedger'
+import { UNKNOWN_AMOUNT } from '../../../../components/Budget/CostsSummaryCard'
import { useExpenseLinks } from '../../../../components/Budget/useExpenseLinks'
import { useCostsMode } from '../../../../components/Budget/useCostsMode'
import { CostsCurrencyPicker } from '../../../../components/Budget/CostsCurrencyPicker'
@@ -48,7 +49,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
// The display and trip currencies, the server-computed settlement, totals,
// filters and the ledger writes: the same ledger the desktop panel runs on.
const {
- me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, flows, splitting, knownNames,
+ me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, flows, balancesKnown, splitting, knownNames,
search, setSearch, segment, setSegment, catFilter, setCatFilter, dayFilter, setDayFilter,
totals, filtered, filteredSettlements, catBreakdown, leftOutLabel, toggleLeftOutCat, countAllCats, exportCsv: handleExportCsv,
deleteExpense, undoSettlement: handleUndoSettlement, setBase, baseOptions,
@@ -170,8 +171,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
</span>
<div className="mt-2 text-[0.8125rem] font-bold text-m-ink">{t('costs.youOwe')}</div>
<div className="font-geist text-[0.59375rem] text-m-faint">{t('costs.youOweSub')}</div>
- <div className="mt-auto pt-1 font-geist text-[1.1875rem] font-extrabold tabular-nums" style={{ color: totals.owe > 0.5 ? STATUS_COLOR.danger : 'var(--m-ink)' }}>
- {formatMoney(totals.owe, base, locale)}
+ <div className="mt-auto pt-1 font-geist text-[1.1875rem] font-extrabold tabular-nums" style={{ color: balancesKnown && totals.owe > 0.5 ? STATUS_COLOR.danger : 'var(--m-ink)' }}>
+ {balancesKnown ? formatMoney(totals.owe, base, locale) : UNKNOWN_AMOUNT}
</div>
</div>
<div className="flex flex-1 flex-col rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
@@ -180,8 +181,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
</span>
<div className="mt-2 text-[0.8125rem] font-bold text-m-ink">{t('costs.youreOwed')}</div>
<div className="font-geist text-[0.59375rem] text-m-faint">{t('costs.youreOwedSub')}</div>
- <div className="mt-auto pt-1 font-geist text-[1.1875rem] font-extrabold tabular-nums" style={{ color: totals.owed > 0.5 ? STATUS_COLOR.confirmed : 'var(--m-ink)' }}>
- {formatMoney(totals.owed, base, locale)}
+ <div className="mt-auto pt-1 font-geist text-[1.1875rem] font-extrabold tabular-nums" style={{ color: balancesKnown && totals.owed > 0.5 ? STATUS_COLOR.confirmed : 'var(--m-ink)' }}>
+ {balancesKnown ? formatMoney(totals.owed, base, locale) : UNKNOWN_AMOUNT}
</div>
</div>
</div>