From c9c419b4ad8803bb22514c6e4efe7be02501ada5 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 13 Nov 2026 09:43:42 +0100 Subject: [PATCH] feat(costs): leave out owing and settling on a trip of one (#2689) With one traveler every share is the whole amount, yet Costs showed owe, owed, outstanding, settle-up, balances and the final budget. A shared gate (showsSplitting) now hides that side on desktop and phone, unless the ledger still names someone else; the expense editor drops who paid and the split while the expense holds nothing more. The payment dialog moves into its own file to keep the panel under the size ratchet. --- client/scripts/feature-pairs.json | 2 +- client/scripts/size-baseline.json | 2 +- .../Budget/CostsPanel.solo.test.tsx | 84 ++++ client/src/components/Budget/CostsPanel.tsx | 153 ++---- client/src/components/Budget/CostsTable.tsx | 14 +- .../components/Budget/CostsToolbar.test.tsx | 16 +- client/src/components/Budget/CostsToolbar.tsx | 60 ++- .../src/components/Budget/SettlementModal.tsx | 178 +++++++ .../src/components/Budget/costsModel.test.ts | 30 +- client/src/components/Budget/costsModel.ts | 42 +- .../components/Budget/useCostsLedger.test.ts | 25 +- .../src/components/Budget/useCostsLedger.ts | 38 +- .../components/Budget/useExpenseForm.test.ts | 22 +- .../src/components/Budget/useExpenseForm.ts | 13 +- .../mobile/screens/trip/sheets/MCostSheet.tsx | 450 +++++++++--------- .../mobile/screens/trip/tabs/MCostsTab.tsx | 27 +- .../unit/mobile/trip/MCostSheet.test.tsx | 15 +- .../tests/unit/mobile/trip/MCostsTab.test.tsx | 16 +- wiki/Budget-Tracking.md | 6 + 19 files changed, 804 insertions(+), 389 deletions(-) create mode 100644 client/src/components/Budget/CostsPanel.solo.test.tsx create mode 100644 client/src/components/Budget/SettlementModal.tsx diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index 2dba8df97..1cac200af 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -290,7 +290,7 @@ { "feature": "Costs/budget settle-up payment: useSettlementForm", "hooks": ["src/components/Budget/useSettlementForm.ts"], - "desktop": ["src/components/Budget/CostsPanel.tsx"], + "desktop": ["src/components/Budget/SettlementModal.tsx"], "mobile": ["src/mobile/screens/trip/tabs/MCostsPayment.tsx"] }, { diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index 540e2735f..a0273ec96 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -4,7 +4,7 @@ "src/components/Admin/AdminPluginsPanel.test.tsx": 2704, "src/components/Admin/AdminPluginsPanel.tsx": 1266, "src/components/Budget/CostsPanel.test.tsx": 2730, - "src/components/Budget/CostsPanel.tsx": 1740, + "src/components/Budget/CostsPanel.tsx": 1668, "src/components/Map/MapView.tsx": 1200, "src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.tsx": 2126, diff --git a/client/src/components/Budget/CostsPanel.solo.test.tsx b/client/src/components/Budget/CostsPanel.solo.test.tsx new file mode 100644 index 000000000..ced96af7c --- /dev/null +++ b/client/src/components/Budget/CostsPanel.solo.test.tsx @@ -0,0 +1,84 @@ +// FE-COSTS-SOLO-001 to FE-COSTS-SOLO-003: a trip of one has nothing to split (#2689) +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { render, screen } from '../../../tests/helpers/render'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { useAuthStore } from '../../store/authStore'; +import { useSettingsStore } from '../../store/settingsStore'; +import { useTripStore } from '../../store/tripStore'; +import type { BudgetItem } from '../../types'; +import CostsPanel from './CostsPanel'; + +const alice = { id: 1, username: 'alice', avatar_url: null }; + +type Flow = { from: { user_id: number; username: string }; to: { user_id: number; username: string }; amount: number }; + +const museum = (over: Partial = {}): BudgetItem => + ({ + ...buildBudgetItem({ trip_id: 1 }), + id: 701, + name: 'Museum', + category: 'activities', + total_price: 40, + expense_date: '2025-06-15', + payers: [{ user_id: 1, amount: 40 }], + members: [{ user_id: 1, username: 'alice' }], + ...over, + }) as unknown as BudgetItem; + +function mount(items: BudgetItem[], flows: Flow[] = []) { + server.use( + http.get('/api/trips/1/budget', () => HttpResponse.json({ items })), + http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows, settlements: [] })) + ); + return render(); +} + +beforeEach(() => { + resetAllStores(); + seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'EUR' }) }); + seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'alice' }), isAuthenticated: true }); + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } }); +}); + +describe('CostsPanel on a trip of one (#2689)', () => { + it('FE-COSTS-SOLO-001: the total stands alone, without owing, settling or balances', async () => { + mount([museum()]); + await screen.findByText('Museum'); + expect(screen.getByRole('region', { name: 'Total trip spend' })).toHaveTextContent('1 expense'); + for (const name of ['You owe', "You're owed", 'Outstanding amount', 'Settle up', 'Balances', 'Final budget']) { + expect(screen.queryByRole('region', { name })).toBeNull(); + } + expect(screen.getByRole('region', { name: 'By category' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Settle up' })).toBeNull(); + expect(screen.queryByText('Split')).toBeNull(); + }); + + it('FE-COSTS-SOLO-002: an expense nobody paid is not flagged unfinished, and the editor asks for no payer or split', async () => { + const user = userEvent.setup(); + mount([museum({ payers: [] })]); + await screen.findByText('Museum'); + expect(screen.queryByText('Unfinished')).toBeNull(); + + await user.click(screen.getByRole('button', { name: 'Add expense' })); + expect(await screen.findByRole('dialog')).toBeInTheDocument(); + expect(screen.queryByText('Who paid?')).toBeNull(); + expect(screen.queryByRole('button', { name: 'Equally' })).toBeNull(); + }); + + it('FE-COSTS-SOLO-003: money still open with someone who left keeps the splitting side', async () => { + const shared = museum({ + members: [ + { user_id: 1, username: 'alice' }, + { user_id: 9, username: 'zoe' }, + ], + } as never); + mount([shared], [{ from: { user_id: 9, username: 'zoe' }, to: { user_id: 1, username: 'alice' }, amount: 20 }]); + expect(await screen.findByRole('region', { name: 'Settle up' })).toBeInTheDocument(); + expect(screen.getByRole('region', { name: 'You owe' })).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsx index 8d93dce5b..cffd543f4 100644 --- a/client/src/components/Budget/CostsPanel.tsx +++ b/client/src/components/Budget/CostsPanel.tsx @@ -12,17 +12,17 @@ import CustomSelect from '../shared/CustomSelect' import { CustomDatePicker } from '../shared/CustomDateTimePicker' import { useReceiptScan } from './useReceiptScan' import { ReceiptScanModal } from './ReceiptScanModal' -import { SYMBOLS, SPLIT_COLORS } from './BudgetPanel.constants' +import { SPLIT_COLORS } from './BudgetPanel.constants' import { finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote, settlementDate } from './CostsPanel.helpers' import { COST_CAT_META, COST_CATEGORY_LIST, catMeta } from './costsCategories' import { - baseTotal as baseTotalOf, booked as bookedAmount, currencyOptions, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf, + baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf, myPaidOf as myPaidOfModel, paymentAmount, paymentLineOf, settledShareOf, type CostsSettlement as Settlement, type CostsSettlementResponse, } from './costsModel' import { useCostsLedger } from './useCostsLedger' import { useExpenseLinks } from './useExpenseLinks' -import { useSettlementForm } from './useSettlementForm' +import { SettlementModal } from './SettlementModal' import type { CustomSplitUnit } from './usePercentSplit' import { useExpenseForm } from './useExpenseForm' import { ReceiptPreviewModal } from './ReceiptPreviewModal' @@ -37,7 +37,7 @@ import { NumericInput } from '../shared/NumericInput' import EmptyState from '../shared/EmptyState' import { Tooltip } from '../shared/Tooltip' import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell' -import { AddRowButton, EditorField, GRID_2, INPUT, PillSelect, Segmented, TEXTAREA } from '../shared/dialogParts' +import { AddRowButton, EditorField, INPUT, PillSelect, Segmented, TEXTAREA } from '../shared/dialogParts' import { CountPill, EYEBROW } from '../Planner/bookings/bookingParts' import CostsToolbar, { type CostsView } from './CostsToolbar' import CostsTable, { CostsTableSummary } from './CostsTable' @@ -73,12 +73,12 @@ 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, + me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, knownNames, splitting, search, setSearch, segment: filter, setSegment: setFilter, catFilter, setCatFilter, dayFilter, setDayFilter, totals, filtered, filteredSettlements, catBreakdown, exportCsv: handleExportCsv, deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll, } = useCostsLedger({ - tripId, trip, budgetItems, actions: { loadBudgetItems, deleteBudgetItem }, canEdit, t, toast, + tripId, trip, budgetItems, memberCount: tripMembers.length, actions: { loadBudgetItems, deleteBudgetItem }, canEdit, t, toast, settlementOnTripChange: true, skipUnfinishedShares: true, csvCurrencyAsStored: true, }) const curOf = useCallback((e: BudgetItem) => (e.currency || tripCurrency), [tripCurrency]) @@ -234,6 +234,16 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps return {parts.map((p, i) => {p.value})} } + // Who owes and who paid mean nothing with nothing to split (#2689); the count does. + const totalCard = ( + } tone="total" + foot={splitting ? <> + {t('costs.yourShare')}{fmt0(totals.myShare)} + {t('costs.youPaid')}{fmt0(totals.myPaid)} + : {t('costs.expensesCount', { count: budgetItems.length })}} /> + ) + // ── category + day filter controls (shared by both layouts) ────────────── // A prominent summary shown when a single day is selected: the day + its total. const dayFilterTotal = dayFilter ? filtered.reduce((a, e) => a + baseTotal(e), 0) : 0 @@ -254,7 +264,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{isMobile ? MobileBody() : (
- 0} onSettleAll={settleAll} onAddExpense={() => { setEditing(null); setModalOpen(true) }} onScanReceipt={receiptScan.offered ? receiptScan.open : undefined} @@ -268,7 +278,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps onExport: handleExportCsv, canExport: budgetItems.length > 0, }} /> - {/* ── Summary cards ── */} + {/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */} + {!splitting ?
{totalCard}
: (
} tone="owe" @@ -285,13 +296,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps foot={totals.outstandingCount > 0 ? {totals.outstandingCount} {t('costs.outstandingItems', { count: totals.outstandingCount })} : !settlement?.flows?.length && {t('costs.allSettled')}} /> - } tone="total" - foot={<> - {t('costs.yourShare')}{fmt0(totals.myShare)} - {t('costs.youPaid')}{fmt0(totals.myPaid)} - } /> -
+ {totalCard} +
)} {/* ── Main grid ── */} {/* The same four columns as the cards above: the ledger takes three, the @@ -342,6 +348,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps {/* sidebar */}
{/* settle up */} + {splitting && <>
{sideHead(t('costs.settleUp'), {(settlement?.flows || []).length}, canEdit && (
+ } {/* by category; the table view sums up four ways instead */} {view === 'table' ? ( - fmt(v)} personName={personName} /> + fmt(v)} personName={personName} splitting={splitting} /> ) : (
{sideHead(t('costs.byCategory'))} @@ -481,10 +489,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{t('costs.totalSpend')}
{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}
-
+ {splitting &&
{t('costs.yourShare')} {fmt0(totals.myShare)} {t('costs.youPaid')} {fmt0(totals.myPaid)} -
+
} {canEdit && (
- {/* Owe / Owed */} + {/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */} + {splitting && <>
@@ -537,6 +546,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{SettleFlows()}
+ } {/* Expenses */}
@@ -554,11 +564,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps setSearch(e.target.value)} placeholder={t('costs.searchPlaceholder')} className="text-content" style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(14px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }} />
-
+ {splitting &&
{(['all', 'mine', 'owed'] as const).map(f => ( ))} -
+
}
setCatFilter(String(v))} options={categoryOptions} size="sm" style={{ flex: 1, minWidth: 0 }} /> setDayFilter(String(v))} options={dayOptions} size="sm" searchable style={{ flex: 1, minWidth: 0 }} /> @@ -579,7 +589,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps })}
- {/* Balances */} + {/* Balances and the final budget */} + {splitting && <>
{t('costs.balances')}
{BalancesList({ balances: settlement?.balances || [] })} @@ -590,6 +601,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{t('costs.finalBudget')}
{FinalBudgetList()}
+ } {/* By category */}
@@ -633,9 +645,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps const c = catMeta(e.category) const Icon = c.Icon const line = lineOf(e.total_price || 0, e, baseTotal(e)) - const payers = (e.payers || []).filter(p => p.amount !== 0) - const net = round2(myPaidOf(e) - myShareOf(e)) - const unfinished = isUnfinished(e) + // Payers, the split and what is still open say nothing with nothing to split (#2689). + const payers = splitting ? (e.payers || []).filter(p => p.amount !== 0) : [] + const net = splitting ? round2(myPaidOf(e) - myShareOf(e)) : 0 + const unfinished = splitting && isUnfinished(e) const note = readUserNote(e) // Fixed columns, identical on every row, so the eye can run down the list @@ -725,7 +738,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps ))}
)} - {SplitChips({ e })} + {splitting && SplitChips({ e })}
{/* The note, marked by a rule in the category colour instead of a box, so @@ -1025,87 +1038,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps } } -// ── pure subcomponents ───────────────────────────────────────────────────── -// Add or edit a settle-up payment (from / to / amount / currency). Reachable inline -// from the ledger row and from a manual "Add payment" button, so recording "I sent -// money to X" works the same whether or not there's an outstanding expense behind it. -// A transfer can be made in any currency — paying a rouble debt in euros is normal — -// so it carries its own, defaulting to the display currency. The server freezes its -// FX rate on write, the same way an expense's is frozen. -function SettlementModal({ tripId, people, me, editing, currency, tripCurrency, onClose, onSaved }: { - tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; tripCurrency: string; onClose: () => void; onSaved: () => void -}) { - const { t } = useTranslation() - const toast = useToast() - const { fromId, setFromId, toId, setToId, amount, setAmount, currency: cur, setCurrency: setCur, day, setDay, note, setNote, saving, valid, save } = - useSettlementForm({ tripId, tripCurrency, base: currency, people, me, editing, t, toast, onSaved }) - const opts = people.map(p => ({ value: String(p.id), label: p.id === me ? t('costs.you') : p.username })) - - const labelId = useId() - const nameOf = (id: number) => { - const p = people.find(x => x.id === id) - if (!p) return '' - return p.id === me ? t('costs.you') : p.username - } - - return ( - } - tint={NEUTRAL_TINT} - labelId={labelId} - onClose={onClose} - title={editing ? t('costs.editPayment') : t('costs.addPayment')} - sub={fromId !== toId ? `${nameOf(fromId)} → ${nameOf(toId)}` : undefined} - /> - )} - footer={( - - - {t('common.cancel')} - {editing ? t('common.save') : t('costs.addPayment')} - - )} - > -
- - setFromId(Number(v))} options={opts} style={{ width: '100%' }} /> - - - setToId(Number(v))} options={opts} style={{ width: '100%' }} /> - -
-
- -
- {SYMBOLS[cur] || (cur + ' ')} - {/* Typed and shown the way the expense total is, in the reader's own decimal mark. */} - setAmount(v.replace(',', '.'))} - className="w-full flex-1 border-0 bg-transparent ps-1.5 font-semibold text-content outline-none dark:bg-transparent" style={fs(14, 'body')} /> -
-
- - setCur(String(v))} searchable - options={currencyOptions(cur)} - style={{ width: '100%' }} /> - -
- - - - -