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() 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 ?
{totalCard}
: (
- } tone="owe" - foot={totals.owe > 0.01 + foot={!balancesKnown ? balancesUnknown() + : totals.owe > 0.01 ? f.from.user_id === me).map(f => f.to.user_id)} lead={t('costs.to')} Avatar={Avatar} name={personName} /> : {t('costs.allSettled')}} /> - } tone="owed" - foot={totals.owed > 0.01 + foot={!balancesKnown ? balancesUnknown() + : totals.owed > 0.01 ? f.to.user_id === me).map(f => f.from.user_id)} lead={t('costs.from')} Avatar={Avatar} name={personName} /> : {t('costs.nothingOwed')}} /> } tone="unfinished" foot={totals.outstandingCount > 0 ? {totals.outstandingCount} {t('costs.outstandingItems', { count: totals.outstandingCount })} - : !settlement?.flows?.length && {t('costs.allSettled')}} /> + : balancesKnown && !settlement?.flows?.length && {t('costs.allSettled')}} /> {totalCard}
)} @@ -443,6 +445,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps ) + // The owe and owed cards say why their figure is missing instead of claiming zero. + function balancesUnknown() { + return {t(settlementError ? 'common.unknownError' : 'common.loading')} + } + // 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
{t('costs.youOwe')}
{t('costs.youOweSub')}
-
{bigMoney(totals.owe, 16, 'var(--c-ink3)')}
+
{balancesKnown ? bigMoney(totals.owe, 16, 'var(--c-ink3)') : UNKNOWN_AMOUNT}
{t('costs.youreOwed')}
{t('costs.youreOwedSub')}
-
{bigMoney(totals.owed, 16, 'var(--c-ink3)')}
+
{balancesKnown ? bigMoney(totals.owed, 16, 'var(--c-ink3)') : UNKNOWN_AMOUNT}
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) => ( { 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({ )) ) : ( - {formatMoney(amount, currency, locale)} + {amount == null ? UNKNOWN_AMOUNT : formatMoney(amount, currency, locale)} )}
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) {
{t('costs.youOwe')}
{t('costs.youOweSub')}
-
0.5 ? STATUS_COLOR.danger : 'var(--m-ink)' }}> - {formatMoney(totals.owe, base, locale)} +
0.5 ? STATUS_COLOR.danger : 'var(--m-ink)' }}> + {balancesKnown ? formatMoney(totals.owe, base, locale) : UNKNOWN_AMOUNT}
@@ -180,8 +181,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
{t('costs.youreOwed')}
{t('costs.youreOwedSub')}
-
0.5 ? STATUS_COLOR.confirmed : 'var(--m-ink)' }}> - {formatMoney(totals.owed, base, locale)} +
0.5 ? STATUS_COLOR.confirmed : 'var(--m-ink)' }}> + {balancesKnown ? formatMoney(totals.owed, base, locale) : UNKNOWN_AMOUNT}