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.

feat(costs): leave out owing and settling on a trip of one (#2689)

Mauricec9c419b4ad88
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> = {}): 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(<CostsPanel tripId={1} tripMembers={[alice]} />);
+}
+
+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 <span dir="ltr" className="inline-flex items-baseline">{parts.map((p, i) => <span key={i} style={isBig(p) ? undefined : { fontSize: smallSize, fontWeight: 500, color: mutedColor }}>{p.value}</span>)}</span>
}
+ // Who owes and who paid mean nothing with nothing to split (#2689); the count does.
+ const totalCard = (
+ <SummaryCard label={t('costs.totalSpend')} sub={t('costs.totalSpendSub')} amount={totals.totalSpend} currency={base} locale={locale}
+ icon={<BarChart3 size={18} />} tone="total"
+ foot={splitting ? <>
+ <span className={CHIP}>{t('costs.yourShare')}<b className="text-content">{fmt0(totals.myShare)}</b></span>
+ <span className={CHIP}>{t('costs.youPaid')}<b className="text-content">{fmt0(totals.myPaid)}</b></span>
+ </> : <span className={CHIP}>{t('costs.expensesCount', { count: budgetItems.length })}</span>} />
+ )
+
// ── 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
<div className="costs-root" style={{ minHeight: '100%', background: 'var(--c-bg)', padding: isMobile ? '6px 14px 28px' : '24px 28px 48px' }}>
{isMobile ? MobileBody() : (
<div style={{ maxWidth: '100%', margin: '0 auto' }}>
- <CostsToolbar dateMeta={dateMeta} people={people} me={me} colorFor={colorFor}
+ <CostsToolbar dateMeta={dateMeta} people={people} me={me} colorFor={colorFor} splitting={splitting}
canEdit={canEdit} canSettle={(settlement?.flows || []).length > 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 ? <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}
icon={<ArrowDown size={18} />} tone="owe"
@@ -285,13 +296,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
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>} />
- <SummaryCard label={t('costs.totalSpend')} sub={t('costs.totalSpendSub')} amount={totals.totalSpend} currency={base} locale={locale}
- icon={<BarChart3 size={18} />} tone="total"
- foot={<>
- <span className={CHIP}>{t('costs.yourShare')}<b className="text-content">{fmt0(totals.myShare)}</b></span>
- <span className={CHIP}>{t('costs.youPaid')}<b className="text-content">{fmt0(totals.myPaid)}</b></span>
- </>} />
- </div>
+ {totalCard}
+ </div>)}
{/* ── 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 */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* settle up */}
+ {splitting && <>
<section aria-label={t('costs.settleUp')} className={SIDE_CARD}>
{sideHead(t('costs.settleUp'), <CountPill>{(settlement?.flows || []).length}</CountPill>, canEdit && (
<button type="button" onClick={() => setAddingPayment(true)}
@@ -363,10 +370,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{sideHead(t('costs.finalBudget'))}
<div className="px-4 py-4">{FinalBudgetList()}</div>
</section>
+ </>}
{/* by category; the table view sums up four ways instead */}
{view === 'table' ? (
- <CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} />
+ <CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
) : (
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
{sideHead(t('costs.byCategory'))}
@@ -481,10 +489,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
- <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
+ {splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
<span>{t('costs.yourShare')} <b style={{ color: '#fff', fontWeight: 600, marginInlineStart: 4 }}>{fmt0(totals.myShare)}</b></span>
<span>{t('costs.youPaid')} <b style={{ color: '#fff', fontWeight: 600, marginInlineStart: 4 }}>{fmt0(totals.myPaid)}</b></span>
- </div>
+ </div>}
{canEdit && (
<button type="button" onClick={() => { setEditing(null); setModalOpen(true) }} style={{ marginTop: 16, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.16)', color: '#fff', padding: 13, borderRadius: 14, fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
<Plus size={17} /> {t('costs.addExpense')}
@@ -499,7 +507,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
)}
</section>
- {/* Owe / Owed */}
+ {/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */}
+ {splitting && <>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div style={{ width: 34, height: 34, borderRadius: 10, display: 'grid', placeItems: 'center', marginBottom: 10, background: '#dc262622', color: '#dc2626' }}><ArrowDown size={17} /></div>
@@ -537,6 +546,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div>
{SettleFlows()}
</div>
+ </>}
{/* Expenses */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
@@ -554,11 +564,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<Search size={16} className="text-content-faint" />
<input value={search} onChange={e => 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' }} />
</div>
- <div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 11, padding: 3, gap: 2 }}>
+ {splitting && <div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 11, padding: 3, gap: 2 }}>
{(['all', 'mine', 'owed'] as const).map(f => (
<button type="button" key={f} onClick={() => setFilter(f)} className={filter === f ? 'bg-surface-card text-content' : 'text-content-muted'} style={{ flex: 1, padding: '8px 6px', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, borderRadius: 8, border: 0, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>{t('costs.filter.' + f)}</button>
))}
- </div>
+ </div>}
<div style={{ display: 'flex', gap: 8 }}>
<CustomSelect value={catFilter} onChange={v => setCatFilter(String(v))} options={categoryOptions} size="sm" style={{ flex: 1, minWidth: 0 }} />
<CustomSelect value={dayFilter} onChange={v => setDayFilter(String(v))} options={dayOptions} size="sm" searchable style={{ flex: 1, minWidth: 0 }} />
@@ -579,7 +589,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
})}
</div>
- {/* Balances */}
+ {/* Balances and the final budget */}
+ {splitting && <>
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.balances')}</div>
{BalancesList({ balances: settlement?.balances || [] })}
@@ -590,6 +601,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.finalBudget')}</div>
{FinalBudgetList()}
</div>
+ </>}
{/* By category */}
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
@@ -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
))}
</div>
)}
- {SplitChips({ e })}
+ {splitting && SplitChips({ e })}
</div>
{/* 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 (
- <DialogShell
- onClose={onClose}
- labelledBy={labelId}
- width="narrow"
- header={(
- <DialogHeader
- tile={<DialogTile><ArrowLeftRight size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
- tint={NEUTRAL_TINT}
- labelId={labelId}
- onClose={onClose}
- title={editing ? t('costs.editPayment') : t('costs.addPayment')}
- sub={fromId !== toId ? `${nameOf(fromId)} → ${nameOf(toId)}` : undefined}
- />
- )}
- footer={(
- <DialogFooter>
- <FooterSpacer />
- <DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
- <DialogButton variant="primary" onClick={save} disabled={!valid || saving}>{editing ? t('common.save') : t('costs.addPayment')}</DialogButton>
- </DialogFooter>
- )}
- >
- <div className={GRID_2}>
- <EditorField label={t('costs.from')}>
- <CustomSelect value={String(fromId)} onChange={v => setFromId(Number(v))} options={opts} style={{ width: '100%' }} />
- </EditorField>
- <EditorField label={t('costs.to')}>
- <CustomSelect value={String(toId)} onChange={v => setToId(Number(v))} options={opts} style={{ width: '100%' }} />
- </EditorField>
- </div>
- <div className={GRID_2}>
- <EditorField label={t('costs.amount')}>
- <div className="flex items-center rounded-[10px] border border-edge bg-surface-input px-3" style={{ height: FIELD_H }}>
- <span className="text-content-faint" style={fs(14, 'body')}>{SYMBOLS[cur] || (cur + ' ')}</span>
- {/* Typed and shown the way the expense total is, in the reader's own decimal mark. */}
- <NumericInput mode="decimal" placeholder={zeroAmountInput(cur)} value={localizeAmountInput(amount, cur)}
- onValueChange={v => 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')} />
- </div>
- </EditorField>
- <EditorField label={t('costs.currency')}>
- <CustomSelect value={cur} onChange={v => setCur(String(v))} searchable
- options={currencyOptions(cur)}
- style={{ width: '100%' }} />
- </EditorField>
- </div>
- <EditorField label={t('costs.day')}>
- <CustomDatePicker value={day} onChange={setDay} style={{ width: '100%' }} />
- </EditorField>
- <EditorField label={t('costs.note')} htmlFor="payment-note">
- <textarea id="payment-note" value={note} onChange={e => setNote(e.target.value)} rows={2}
- placeholder={t('costs.paymentNotePlaceholder')} maxLength={NOTE_MAX} className={`${TEXTAREA} resize-y`} />
- </EditorField>
- </DialogShell>
- )
-}
-
// ── Add / edit expense modal ───────────────────────────────────────────────
export interface ExpensePrefill {
name?: string
@@ -1134,7 +1066,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
handleRemoveReceipt, handleToggleItemParticipant, handleUpdateItemName, handleUpdateItemPrice, isTicketMode,
multiPayer, name, nameOf, note, onPayerAmountChange, onTotalChange, participants, payerAmounts, payerId, payerIds,
payersOk, pendingReceiptFiles, placeholderShares, previewReceipts: modalPreviewReceipts, receipts, save, saving,
- currencyChoices, setCat, setCurrency, setDay, setName, setNote, setPayerId, splitUnits: units,
+ currencyChoices, setCat, setCurrency, setDay, setName, setNote, setPayerId, showSplit, splitUnits: units,
setPreviewReceipts: setModalPreviewReceipts, setSplitMode, splitMode, splitShortfall, splitSum, sym, ticketInfo,
ticketItems, toggleParticipant, togglePayer, total, totalNum, tripCur, uploadingReceipt, valid,
} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved })
@@ -1482,8 +1414,9 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
)}
</div>
- {payerSection}
- {splitSection}
+ {/* Nothing to split on a trip of one (#2689). */}
+ {showSplit && payerSection}
+ {showSplit && splitSection}
{/* Side by side the two panels share one height. */}
<div className={isMobile ? 'flex flex-col gap-5' : 'grid grid-cols-2 gap-3'}>
diff --git a/client/src/components/Budget/CostsTable.tsx b/client/src/components/Budget/CostsTable.tsx
index 324a88d76..574d01275 100644
--- a/client/src/components/Budget/CostsTable.tsx
+++ b/client/src/components/Budget/CostsTable.tsx
@@ -316,9 +316,13 @@ function TextInput({ value, onSave, onCancel, label, numeric = false }: {
export type CostsSummaryTab = 'category' | 'date' | 'payer' | 'status'
/** The four ways the old budget summed the table up: by category, by day, by payer, paid against open. */
-export function CostsTableSummary({ items, baseTotal, toBase, fmt, personName }: Pick<CostsTableProps, 'items' | 'baseTotal' | 'toBase' | 'fmt' | 'personName'>) {
+export function CostsTableSummary({ items, baseTotal, toBase, fmt, personName, splitting = true }: Pick<CostsTableProps, 'items' | 'baseTotal' | 'toBase' | 'fmt' | 'personName'> & {
+ /** False with nothing to split (#2689): who paid and paid or open are no question then. */
+ splitting?: boolean
+}) {
const { t, locale } = useTranslation()
- const [tab, setTab] = useState<CostsSummaryTab>('category')
+ const [picked, setTab] = useState<CostsSummaryTab>('category')
+ const tab = splitting || picked === 'category' || picked === 'date' ? picked : 'category'
const rows = useMemo((): { key: string; label: string; amount: number; color?: string }[] => {
const sum = new Map<string, { label: string; amount: number; color?: string }>()
@@ -361,8 +365,10 @@ export function CostsTableSummary({ items, baseTotal, toBase, fmt, personName }:
<Segmented<CostsSummaryTab> value={tab} onChange={setTab} label={t('costs.table.summary')} fill options={[
{ value: 'category', label: t('costs.table.byCategory') },
{ value: 'date', label: t('costs.table.byDate') },
- { value: 'payer', label: t('costs.table.byPayer') },
- { value: 'status', label: t('costs.table.byStatus') },
+ ...(splitting ? [
+ { value: 'payer' as const, label: t('costs.table.byPayer') },
+ { value: 'status' as const, label: t('costs.table.byStatus') },
+ ] : []),
]} />
</div>
<ul className="m-0 flex list-none flex-col gap-3 p-4">
diff --git a/client/src/components/Budget/CostsToolbar.test.tsx b/client/src/components/Budget/CostsToolbar.test.tsx
index 250fe4b3a..93fe97833 100644
--- a/client/src/components/Budget/CostsToolbar.test.tsx
+++ b/client/src/components/Budget/CostsToolbar.test.tsx
@@ -1,4 +1,4 @@
-// FE-COSTSBAR-001 to FE-COSTSBAR-013
+// FE-COSTSBAR-001 to FE-COSTSBAR-014
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
@@ -160,5 +160,19 @@ describe('CostsToolbar', () => {
await user.click(buttons[1])
expect(onView).toHaveBeenCalledWith('table')
})
+
+ it('FE-COSTSBAR-014: with nothing to split the travelers, Settle up and the owner filter stay away (#2689)', async () => {
+ const user = userEvent.setup()
+ // An owner filter left on from before neither counts nor shows.
+ setup({ splitting: false, filters: filters({ owner: 'owed' }) })
+ expect(screen.queryByText('2 travelers')).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Settle up' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Add expense' })).toBeInTheDocument()
+ const button = screen.getByRole('button', { name: 'Filter' })
+ expect(within(button).queryByText('1')).toBeNull()
+ await user.click(button)
+ expect(within(screen.getByRole('menu')).queryByRole('button', { name: 'Paid by me' })).toBeNull()
+ expect(within(screen.getByRole('menu')).getByRole('button', { name: 'Food' })).toBeInTheDocument()
+ })
})
})
diff --git a/client/src/components/Budget/CostsToolbar.tsx b/client/src/components/Budget/CostsToolbar.tsx
index d829ca8f1..80a7c5f01 100644
--- a/client/src/components/Budget/CostsToolbar.tsx
+++ b/client/src/components/Budget/CostsToolbar.tsx
@@ -37,6 +37,11 @@ interface CostsToolbarProps {
canEdit: boolean
/** Whether there is any suggested transfer left to settle. */
canSettle: boolean
+ /**
+ * False when there is nothing to split (#2689): the travelers, Settle up and
+ * the owner filter go, since each one is about who owes whom.
+ */
+ splitting?: boolean
onSettleAll: () => void
onAddExpense: () => void
/** Opens the receipt scan; left out when the AI model reads no images. */
@@ -57,7 +62,7 @@ const BAR_BTN = 'relative grid h-9 w-9 flex-none place-items-center rounded-[10p
* Bookings, Lists and Files open with: the tab's name and what the numbers
* cover, then how to narrow the ledger and the actions on the right.
*/
-export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, onSettleAll, onAddExpense, onScanReceipt, filters, view, onView }: CostsToolbarProps) {
+export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, splitting = true, onSettleAll, onAddExpense, onScanReceipt, filters, view, onView }: CostsToolbarProps) {
const { t } = useTranslation()
const searchRef = useRef<HTMLInputElement>(null)
const chip = 'inline-flex items-center whitespace-nowrap rounded-full bg-surface-card px-3 py-1.5 font-medium text-content-muted shadow-sm'
@@ -76,22 +81,24 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
<b className="text-content">{t('costs.daysCount', { count: dateMeta.days })}</b>
</span>
)}
- <span className={`${chip} gap-2 ps-1.5`}>
- <span className="inline-flex">
- {people.slice(0, 4).map((p, i) => {
- const ring = { width: 22, height: 22, marginInlineStart: i ? -8 : 0 }
- return p.avatar_url
- ? <img key={p.id} src={p.avatar_url} alt="" className="block shrink-0 rounded-full border-2 border-surface-card object-cover" style={ring} />
- : (
- <span key={p.id} className="grid shrink-0 place-items-center rounded-full border-2 border-surface-card font-bold" style={{
- ...ring, background: colorFor(p.id), fontSize: 'calc(9px * var(--fs-scale-caption, 1))',
- color: '#fff', // theme-lint-disable: an initial on the member's own colour
- }}>{(p.id === me ? t('costs.youShort') : p.username.charAt(0)).toUpperCase()}</span>
- )
- })}
+ {splitting && (
+ <span className={`${chip} gap-2 ps-1.5`}>
+ <span className="inline-flex">
+ {people.slice(0, 4).map((p, i) => {
+ const ring = { width: 22, height: 22, marginInlineStart: i ? -8 : 0 }
+ return p.avatar_url
+ ? <img key={p.id} src={p.avatar_url} alt="" className="block shrink-0 rounded-full border-2 border-surface-card object-cover" style={ring} />
+ : (
+ <span key={p.id} className="grid shrink-0 place-items-center rounded-full border-2 border-surface-card font-bold" style={{
+ ...ring, background: colorFor(p.id), fontSize: 'calc(9px * var(--fs-scale-caption, 1))',
+ color: '#fff', // theme-lint-disable: an initial on the member's own colour
+ }}>{(p.id === me ? t('costs.youShort') : p.username.charAt(0)).toUpperCase()}</span>
+ )
+ })}
+ </span>
+ <b className="text-content">{t('costs.travelers', { count: people.length })}</b>
</span>
- <b className="text-content">{t('costs.travelers', { count: people.length })}</b>
- </span>
+ )}
</div>
{filters && (
@@ -114,7 +121,7 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
</Tooltip>
)}
</label>
- <FilterMenu {...filters} />
+ <FilterMenu {...filters} splitting={splitting} />
<Tooltip label={t('budget.exportCsv')}>
<button type="button" onClick={filters.onExport} disabled={!filters.canExport} aria-label={t('budget.exportCsv')} className={BAR_BTN}>
<Download size={15} strokeWidth={2} />
@@ -141,11 +148,13 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
<>
{filters && <span className="mx-0.5 h-[22px] w-px flex-none bg-edge-faint" />}
<div className="flex shrink-0 flex-wrap gap-1.5" style={{ fontSize: BODY_SIZE }}>
- <button type="button" onClick={onSettleAll} disabled={!canSettle}
- className={`${button} bg-surface-card text-content disabled:cursor-default disabled:opacity-40`}>
- <Check size={14} strokeWidth={2.5} />
- {t('costs.settleUp')}
- </button>
+ {splitting && (
+ <button type="button" onClick={onSettleAll} disabled={!canSettle}
+ className={`${button} bg-surface-card text-content disabled:cursor-default disabled:opacity-40`}>
+ <Check size={14} strokeWidth={2.5} />
+ {t('costs.settleUp')}
+ </button>
+ )}
{onScanReceipt && (
<button type="button" onClick={onScanReceipt} className={`${button} bg-surface-card text-content`}>
<ScanLine size={14} strokeWidth={2.5} />
@@ -164,13 +173,14 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
}
/** Whose expenses, which category and which day, in one place; the button counts what is switched on. */
-function FilterMenu(f: CostsFilterProps) {
+function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
const close = useCallback(() => setOpen(false), [])
useDismissOnOutside(ref, open, close)
- const active = (f.owner !== 'all' ? 1 : 0) + (f.category ? 1 : 0) + (f.day ? 1 : 0)
+ // Whose expenses is only a question while something is split.
+ const active = (f.splitting && f.owner !== 'all' ? 1 : 0) + (f.category ? 1 : 0) + (f.day ? 1 : 0)
const owners: [OwnerFilter, string][] = [['all', t('costs.filter.all')], ['mine', t('costs.filter.mine')], ['owed', t('costs.filter.owed')]]
return (
@@ -183,6 +193,7 @@ function FilterMenu(f: CostsFilterProps) {
</Tooltip>
{open && (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
+ {f.splitting && <>
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
{owners.map(([o, label]) => (
<button key={o} type="button" onClick={() => f.onOwner(o)} aria-pressed={f.owner === o}
@@ -194,6 +205,7 @@ function FilterMenu(f: CostsFilterProps) {
</div>
<div style={POPOVER_DIVIDER} />
+ </>}
<div style={POPOVER_CAPTION}>{t('costs.category')}</div>
<div className="max-h-[220px] overflow-y-auto">
{f.categoryOptions.map(o => (
diff --git a/client/src/components/Budget/SettlementModal.tsx b/client/src/components/Budget/SettlementModal.tsx
new file mode 100644
index 000000000..85ff8ae6c
--- /dev/null
+++ b/client/src/components/Budget/SettlementModal.tsx
@@ -0,0 +1,178 @@
+import { ArrowLeftRight } from 'lucide-react';
+import { useId } from 'react';
+
+import { useTranslation } from '../../i18n';
+import { localizeAmountInput, zeroAmountInput } from '../../utils/formatters';
+import { CustomDatePicker } from '../shared/CustomDateTimePicker';
+import CustomSelect from '../shared/CustomSelect';
+import {
+ DialogButton,
+ DialogFooter,
+ DialogHeader,
+ DialogShell,
+ DialogTile,
+ FooterSpacer,
+ NEUTRAL_TINT,
+ fs,
+} from '../shared/DialogShell';
+import { NumericInput } from '../shared/NumericInput';
+import { useToast } from '../shared/Toast';
+import { EditorField, GRID_2, TEXTAREA } from '../shared/dialogParts';
+import { SYMBOLS } from './BudgetPanel.constants';
+import type { TripMember } from './BudgetPanelMemberChips';
+import { NOTE_MAX } from './CostsPanel.helpers';
+import { currencyOptions, type CostsSettlement } from './costsModel';
+import { useSettlementForm } from './useSettlementForm';
+
+/** The amount field's height, the same as the amount row of the expense dialog. */
+const FIELD_H = 40;
+
+/**
+ * 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.
+ */
+export function SettlementModal({
+ tripId,
+ people,
+ me,
+ editing,
+ currency,
+ tripCurrency,
+ onClose,
+ onSaved,
+}: {
+ tripId: number;
+ people: TripMember[];
+ me: number;
+ editing: CostsSettlement | 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 (
+ <DialogShell
+ onClose={onClose}
+ labelledBy={labelId}
+ width="narrow"
+ header={
+ <DialogHeader
+ tile={
+ <DialogTile>
+ <ArrowLeftRight size={20} strokeWidth={1.9} className="text-content-muted" />
+ </DialogTile>
+ }
+ tint={NEUTRAL_TINT}
+ labelId={labelId}
+ onClose={onClose}
+ title={editing ? t('costs.editPayment') : t('costs.addPayment')}
+ sub={fromId !== toId ? `${nameOf(fromId)} → ${nameOf(toId)}` : undefined}
+ />
+ }
+ footer={
+ <DialogFooter>
+ <FooterSpacer />
+ <DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
+ <DialogButton variant="primary" onClick={save} disabled={!valid || saving}>
+ {editing ? t('common.save') : t('costs.addPayment')}
+ </DialogButton>
+ </DialogFooter>
+ }
+ >
+ <div className={GRID_2}>
+ <EditorField label={t('costs.from')}>
+ <CustomSelect
+ value={String(fromId)}
+ onChange={(v) => setFromId(Number(v))}
+ options={opts}
+ style={{ width: '100%' }}
+ />
+ </EditorField>
+ <EditorField label={t('costs.to')}>
+ <CustomSelect
+ value={String(toId)}
+ onChange={(v) => setToId(Number(v))}
+ options={opts}
+ style={{ width: '100%' }}
+ />
+ </EditorField>
+ </div>
+ <div className={GRID_2}>
+ <EditorField label={t('costs.amount')}>
+ <div
+ className="flex items-center rounded-[10px] border border-edge bg-surface-input px-3"
+ style={{ height: FIELD_H }}
+ >
+ <span className="text-content-faint" style={fs(14, 'body')}>
+ {SYMBOLS[cur] || cur + ' '}
+ </span>
+ {/* Typed and shown the way the expense total is, in the reader's own decimal mark. */}
+ <NumericInput
+ mode="decimal"
+ placeholder={zeroAmountInput(cur)}
+ value={localizeAmountInput(amount, cur)}
+ onValueChange={(v) => 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')}
+ />
+ </div>
+ </EditorField>
+ <EditorField label={t('costs.currency')}>
+ <CustomSelect
+ value={cur}
+ onChange={(v) => setCur(String(v))}
+ searchable
+ options={currencyOptions(cur)}
+ style={{ width: '100%' }}
+ />
+ </EditorField>
+ </div>
+ <EditorField label={t('costs.day')}>
+ <CustomDatePicker value={day} onChange={setDay} style={{ width: '100%' }} />
+ </EditorField>
+ <EditorField label={t('costs.note')} htmlFor="payment-note">
+ <textarea
+ id="payment-note"
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ rows={2}
+ placeholder={t('costs.paymentNotePlaceholder')}
+ maxLength={NOTE_MAX}
+ className={`${TEXTAREA} resize-y`}
+ />
+ </EditorField>
+ </DialogShell>
+ );
+}
diff --git a/client/src/components/Budget/costsModel.test.ts b/client/src/components/Budget/costsModel.test.ts
index 8fa2d6eb2..2d9f3851a 100644
--- a/client/src/components/Budget/costsModel.test.ts
+++ b/client/src/components/Budget/costsModel.test.ts
@@ -7,16 +7,18 @@ import {
computeTotals,
currencyOptions,
filterBudgetItems,
+ isPlainSplit,
myShareOf,
paymentAmount,
paymentLineOf,
settledShareOf,
+ showsSplitting,
type CostsCtx,
type CostsFilterState,
type CostsSettlement,
} from './costsModel';
-// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-011
+// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-013
// The pieces both ledgers share since the desktop panel runs on this model too;
// the rest of the model is pinned in tests/unit/mobile/trip/costsModel.test.ts.
@@ -145,3 +147,29 @@ describe('costsModel: the currency picker options', () => {
expect(currencyOptions(null, ['ZZZ']).some((o) => o.value === 'ZZZ')).toBe(false);
});
});
+
+describe('costsModel: when Costs shows who paid and the shares (#2689)', () => {
+ const settled = { flows: [], balances: [] };
+
+ it('FE-BUDGET-COSTSMODEL-012: a trip of one has nothing to split, unless the ledger still names someone else', () => {
+ const mine = expense({ payers: [payer(1, 20)], members: [member(1)] });
+ expect(showsSplitting(2, [], null, 1)).toBe(true);
+ expect(showsSplitting(1, [mine], settled, 1)).toBe(false);
+ expect(showsSplitting(0, [], null, 1)).toBe(false);
+ // Someone who left: named on an expense, owed money, or still in a transfer.
+ expect(showsSplitting(1, [expense({ members: [member(1), member(9)] })], settled, 1)).toBe(true);
+ const owed = { flows: [], balances: [{ user_id: 9, username: 'u9', avatar_url: null, balance: 5 }] };
+ expect(showsSplitting(1, [mine], owed, 1)).toBe(true);
+ const flow = { from: { user_id: 9, username: 'u9' }, to: { user_id: 1, username: 'u1' }, amount: 5 };
+ expect(showsSplitting(1, [mine], { flows: [flow], balances: [] }, 1)).toBe(true);
+ });
+
+ it('FE-BUDGET-COSTSMODEL-013: a split is plain with one payer, equal shares, no receipt lines and only current members', () => {
+ expect(isPlainSplit(null, [1])).toBe(true);
+ expect(isPlainSplit(expense({ payers: [payer(1, 20)], members: [member(1)] }), [1])).toBe(true);
+ expect(isPlainSplit(expense({ payers: [payer(1, 10), payer(2, 10)], members: [] }), [1, 2])).toBe(false);
+ expect(isPlainSplit(expense({ members: [{ ...member(1), amount: 15 }] }), [1])).toBe(false);
+ expect(isPlainSplit(expense({ ticket_json: '{"items":[]}', members: [member(1)] }), [1])).toBe(false);
+ expect(isPlainSplit(expense({ payers: [payer(9, 20)], members: [] }), [1])).toBe(false);
+ });
+});
diff --git a/client/src/components/Budget/costsModel.ts b/client/src/components/Budget/costsModel.ts
index e732214a1..5fc4a875f 100644
--- a/client/src/components/Budget/costsModel.ts
+++ b/client/src/components/Budget/costsModel.ts
@@ -5,7 +5,7 @@ import type { BudgetItem } from '../../types';
import { formatDisplayDate } from '../../utils/dateFormat';
import { currencyDecimals } from '../../utils/formatters';
import { currenciesWith, SYMBOLS } from './BudgetPanel.constants';
-import { paidByUser, readUserNote, settlementDate, splitEqualShares } from './CostsPanel.helpers';
+import { hasTicketSplit, paidByUser, readUserNote, settlementDate, splitEqualShares } from './CostsPanel.helpers';
import { catMeta, COST_CATEGORY_LIST } from './costsCategories';
/**
@@ -170,6 +170,46 @@ export interface CostsSettlementResponse {
unconverted?: BudgetUnconverted;
}
+// ── who paid and the shares: when Costs shows them ─────────────────────────
+
+/**
+ * Whether Costs shows the splitting side: who paid, the shares, the balances
+ * and settling up. A trip of one has nothing to split, since every share is the
+ * whole amount and nobody can owe anybody (#2689), so it is left out there,
+ * unless the ledger still names someone else: a traveller who left the trip
+ * with money open, or members that have not loaded yet.
+ */
+export function showsSplitting(
+ memberCount: number,
+ items: BudgetItem[],
+ settlement: Pick<CostsSettlementResponse, 'flows' | 'balances'> | null,
+ me: number
+): boolean {
+ if (memberCount > 1) return true;
+ const namesOthers = items.some((e) => [...(e.payers || []), ...(e.members || [])].some((p) => p.user_id !== me));
+ const moneyOpen = (settlement?.balances || []).some((b) => Math.abs(b.balance) >= 0.005);
+ return namesOthers || moneyOpen || (settlement?.flows || []).length > 0;
+}
+
+/**
+ * Whether an expense's payers and split hold nothing beyond the obvious, so an
+ * editor that leaves them out of sight loses nothing by it: at most one payer,
+ * an equal split, no receipt lines, and only people still on the trip. A new
+ * expense (null) has nothing yet.
+ */
+export function isPlainSplit(e: BudgetItem | null, memberIds: number[]): boolean {
+ if (!e) return true;
+ const payers = (e.payers || []).filter((p) => p.amount !== 0);
+ const members = e.members || [];
+ const people = [...payers, ...members].map((p) => p.user_id);
+ return (
+ payers.length <= 1 &&
+ !hasTicketSplit(e) &&
+ members.every((m) => m.amount === null || m.amount === undefined) &&
+ people.every((id) => memberIds.includes(id))
+ );
+}
+
// ── hero / tile totals (spec §3.1-§3.3) ────────────────────────────────────
export interface CostsTotals {
diff --git a/client/src/components/Budget/useCostsLedger.test.ts b/client/src/components/Budget/useCostsLedger.test.ts
index da054e71c..3bfa07b2b 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-013
+// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-014
const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -82,6 +82,7 @@ let toastInfo: Mock<(message: string) => void>;
interface Options {
trip?: Trip;
items?: BudgetItem[];
+ memberCount?: number;
settlementOnTripChange?: boolean;
skipUnfinishedShares?: boolean;
csvCurrencyAsStored?: boolean;
@@ -95,6 +96,7 @@ function setup(options: Options = {}) {
tripId,
trip: options.trip ?? buildTrip({ id: 7, currency: 'EUR', title: 'Rome' }),
budgetItems: items,
+ memberCount: options.memberCount ?? 3,
actions: { loadBudgetItems, deleteBudgetItem },
canEdit: true,
t: (key: string) => key,
@@ -240,6 +242,27 @@ describe('useCostsLedger: totals and filters', () => {
});
});
+describe('useCostsLedger: a trip of one (#2689)', () => {
+ it('FE-BUDGET-LEDGER-014: nothing to split leaves out the payments and the owner filter', async () => {
+ const mine = buildBudgetItem({
+ id: 8,
+ name: 'Museum',
+ total_price: 20,
+ members: [member(1)],
+ payers: [payer(1, 20)],
+ });
+ settlementMock().mockResolvedValue({ ...SETTLEMENT, flows: [], balances: [] });
+ const { result } = setup({ items: [mine], memberCount: 1 });
+ await waitFor(() => expect(settlementMock()).toHaveBeenCalled());
+ await waitFor(() => expect(result.current.settlement?.flows).toEqual([]));
+ expect(result.current.splitting).toBe(false);
+ expect(result.current.filteredSettlements).toEqual([]);
+ // A filter left on "I'm owed" from before cannot hide the expenses either.
+ act(() => result.current.setSegment('owed'));
+ expect(result.current.filtered.map((e) => e.id)).toEqual([8]);
+ });
+});
+
describe('useCostsLedger: writes', () => {
it('FE-BUDGET-LEDGER-009: deleting an expense reads the settlement again, a failure toasts', async () => {
const { result } = setup();
diff --git a/client/src/components/Budget/useCostsLedger.ts b/client/src/components/Budget/useCostsLedger.ts
index c5c0dd639..7bf453029 100644
--- a/client/src/components/Budget/useCostsLedger.ts
+++ b/client/src/components/Budget/useCostsLedger.ts
@@ -20,6 +20,7 @@ import {
filterSettlements,
myShareOf,
settledShareOf,
+ showsSplitting,
type CostsCtx,
type CostsSegment,
type CostsSettlementResponse,
@@ -52,6 +53,9 @@ interface Toaster {
* breakdown, the CSV export and the ledger writes. Each surface lays it out
* and keeps its own dialogs or sheets.
*
+ * `splitting` says whether the ledger has anything to split at all (#2689);
+ * without it the owner filter and the recorded payments are left out too.
+ *
* Where the two differ today, the surface says which way: the desktop also
* reads the settlement when the trip changes (`settlementOnTripChange`), leaves
* an expense nobody paid out of my share (`skipUnfinishedShares`, #2225) and
@@ -61,6 +65,7 @@ export function useCostsLedger({
tripId,
trip,
budgetItems,
+ memberCount,
actions,
canEdit,
t,
@@ -72,6 +77,8 @@ export function useCostsLedger({
tripId: number;
trip: Trip | null | undefined;
budgetItems: BudgetItem[];
+ /** The trip's current members; with one, there is nothing to split. */
+ memberCount: number;
actions: Pick<TripStoreState, 'loadBudgetItems' | 'deleteBudgetItem'>;
canEdit: boolean;
t: Translate;
@@ -179,23 +186,37 @@ export function useCostsLedger({
const shareOf = skipUnfinishedShares ? settledShareOf : myShareOf;
const flows = useMemo(() => settlement?.flows || [], [settlement]);
+ const splitting = useMemo(
+ () => showsSplitting(memberCount, budgetItems, settlement, me),
+ [memberCount, budgetItems, settlement, me]
+ );
+ // The owner filter is hidden while nothing is split, so it cannot hold the list back.
+ 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]);
// `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.
const totals = useMemo(() => computeTotals(budgetItems, flows, ctx, shareOf), [budgetItems, flows, ctx, shareOf]);
const filtered = useMemo(
- () => filterBudgetItems(budgetItems, { search, segment, categoryKey: catFilter, dayKey: dayFilter }, ctx, shareOf),
- [budgetItems, search, segment, catFilter, dayFilter, ctx, shareOf]
+ () =>
+ filterBudgetItems(
+ budgetItems,
+ { search, segment: activeSegment, categoryKey: catFilter, dayKey: dayFilter },
+ ctx,
+ shareOf
+ ),
+ [budgetItems, search, activeSegment, catFilter, dayFilter, ctx, shareOf]
);
const filteredSettlements = useMemo(
() =>
- filterSettlements(
- settlement?.settlements || [],
- { search, segment, categoryKey: catFilter, dayKey: dayFilter },
- me
- ),
- [settlement, search, segment, catFilter, dayFilter, me]
+ splitting
+ ? filterSettlements(
+ settlement?.settlements || [],
+ { search, segment: activeSegment, categoryKey: catFilter, dayKey: dayFilter },
+ me
+ )
+ : [],
+ [splitting, settlement, search, activeSegment, catFilter, dayFilter, me]
);
const catBreakdown = useMemo(() => categoryBreakdown(budgetItems, ctx), [budgetItems, ctx]);
@@ -288,6 +309,7 @@ export function useCostsLedger({
settlementError,
loadSettlement,
flows,
+ splitting,
knownNames,
search,
setSearch,
diff --git a/client/src/components/Budget/useExpenseForm.test.ts b/client/src/components/Budget/useExpenseForm.test.ts
index 780f32e55..a2b595fc3 100644
--- a/client/src/components/Budget/useExpenseForm.test.ts
+++ b/client/src/components/Budget/useExpenseForm.test.ts
@@ -21,7 +21,7 @@ vi.mock('./receiptUploads', () => ({
),
}));
-// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-026
+// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-027
const PEOPLE: TripMember[] = [
{ id: 1, username: 'alice', avatar_url: null },
@@ -163,6 +163,26 @@ describe('useExpenseForm: where it starts', () => {
expect(setup({ editing }).result.current.currency).toBe('EUR');
});
+ it('FE-BUDGET-EXPFORM-027: a trip of one hides who paid and the split, unless the expense holds more (#2689)', () => {
+ expect(setup().result.current.showSplit).toBe(true);
+ const solo = (editing: BudgetItem | null) =>
+ renderHook(() =>
+ useExpenseForm({ tripId: 7, base: 'EUR', people: [PEOPLE[0]], me: 1, editing, onSaved: vi.fn() })
+ ).result.current;
+ expect(solo(null).showSplit).toBe(false);
+ expect(solo(buildBudgetItem({ payers: [{ user_id: 1, amount: 20 }], members: [] })).showSplit).toBe(false);
+ // Someone who left the trip, or an uneven split, stays in reach.
+ const withBob = buildBudgetItem({
+ payers: [{ user_id: 1, amount: 20 }],
+ members: [{ user_id: 2, paid: 0, username: 'bob', amount: null }],
+ } as Partial<BudgetItem>);
+ expect(solo(withBob).showSplit).toBe(true);
+ const custom = buildBudgetItem({
+ members: [{ user_id: 1, paid: 0, username: 'alice', amount: 15 }],
+ } as Partial<BudgetItem>);
+ expect(solo(custom).showSplit).toBe(true);
+ });
+
it('FE-BUDGET-EXPFORM-003: an edited expense reopens with its payer, its custom split, its note and receipts', () => {
const receipt = { id: 3, filename: 'r.jpg', original_name: 'r.jpg', url: '/uploads/r.jpg' };
const editing = buildBudgetItem({
diff --git a/client/src/components/Budget/useExpenseForm.ts b/client/src/components/Budget/useExpenseForm.ts
index d9385eeb9..f8490e631 100644
--- a/client/src/components/Budget/useExpenseForm.ts
+++ b/client/src/components/Budget/useExpenseForm.ts
@@ -26,7 +26,7 @@ import {
type TicketItem,
} from './CostsPanel.helpers';
import { catMeta } from './costsCategories';
-import { currencyOptions } from './costsModel';
+import { currencyOptions, isPlainSplit } from './costsModel';
import { useExpenseFx } from './expenseFx';
import { linkableReceiptFiles, receiptOfFile } from './receiptLinks';
import { saveWithReceipts } from './receiptUploads';
@@ -132,6 +132,16 @@ export function useExpenseForm({
// the others absorb the remainder.
const [pinnedPayers, setPinnedPayers] = useState<Set<number>>(() => new Set(initialPayers.map((p) => p.user_id)));
+ // A trip of one has nothing to split (#2689): who paid and the split stay out of
+ // sight, unless the expense being edited carries more than that one person.
+ const [plainSplit] = useState(() =>
+ isPlainSplit(
+ editing,
+ people.map((p) => p.id)
+ )
+ );
+ const showSplit = people.length > 1 || !plainSplit;
+
const [splitMode, setSplitMode] = useState<ExpenseSplitMode>(() => {
if (hasTicketSplit(editing)) return 'ticket';
if (editing && editing.members && editing.members.length > 0) {
@@ -472,6 +482,7 @@ export function useExpenseForm({
togglePayer,
onPayerAmountChange,
payersOk,
+ showSplit,
splitMode,
setSplitMode,
isTicketMode,
diff --git a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
index 6ea25cf13..c32748a67 100644
--- a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
@@ -62,7 +62,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
const {
sym, nameOf, tripCur, name, setName, cat, setCat, currency, setCurrency, currencyChoices, day, setDay, note, setNote, total, onTotalChange,
totalNum, fx, participants, toggleParticipant, payerId, setPayerId, multiPayer, enableMultiPayer, disableMultiPayer,
- payerIds, payerAmounts, togglePayer, onPayerAmountChange, payersOk, splitMode, setSplitMode, isTicketMode, ticketItems,
+ payerIds, payerAmounts, togglePayer, onPayerAmountChange, payersOk, showSplit, splitMode, setSplitMode, isTicketMode, ticketItems,
ticketInfo, handleAddEmptyItem, handleUpdateItemName, handleUpdateItemPrice, handleRemoveItem, handleToggleItemParticipant,
customAmounts, handleCustomAmountChange, splitUnits, splitSum, customBalanced, each, equalShares, placeholderShares,
receipts, pendingReceiptFiles, uploadingReceipt, handleReceiptFileSelect, handleRemoveReceipt, handleRemovePendingReceipt,
@@ -246,252 +246,256 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
</div>
)}
- {/* WHO PAID */}
- <div className="mb-[6px] mt-3 flex items-center justify-between">
- <Eyebrow className="uppercase">{t('costs.whoPaid')}</Eyebrow>
- <button
- type="button"
- onClick={() => (multiPayer ? disableMultiPayer() : enableMultiPayer())}
- className="font-geist text-[0.625rem] font-semibold text-m-muted underline"
- >
- {multiPayer ? t('costs.singlePayer') : t('costs.multiplePayers')}
- </button>
- </div>
- {!multiPayer ? (
- <CustomSelect
- value={String(payerId)}
- onChange={v => setPayerId(Number(v))}
- size="sm"
- options={[
- { value: '0', label: t('costs.noOnePaid') },
- ...people.map(p => ({ value: String(p.id), label: nameOf(p) })),
- ]}
- style={{ width: '100%' }}
- />
- ) : (
+ {/* WHO PAID and SPLIT: nothing to split on a trip of one (#2689). */}
+ {showSplit && (
<>
- <div className="flex flex-col gap-[6px]">
- {people.map((p, idx) => {
- const on = payerIds.has(p.id)
- return (
- <div key={p.id} className={`${ROW_CLS} ${on ? '' : 'opacity-60'}`}>
- <button
- type="button"
- onClick={() => togglePayer(p.id)}
- className="flex min-w-0 flex-1 items-center gap-[8px] text-start"
- >
- <Avatar p={p} idx={idx} dim={!on} />
- <span className="truncate text-[0.8125rem] font-medium text-m-ink">{nameOf(p)}</span>
- </button>
- {on ? (
- <div className={`${MINI_INPUT_WRAP} w-[120px] flex-none`}>
- <span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>
- <NumericInput
- mode="signed-decimal"
- signToggleLabel={t('costs.toggleSign')}
- placeholder={zeroAmountInput(currency)}
- value={localizeAmountInput(payerAmounts[p.id] || '', currency)}
- onValueChange={v => onPayerAmountChange(p.id, v)}
- className="w-full border-0 bg-transparent py-[7px] text-end text-[0.8125rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
- />
+ <div className="mb-[6px] mt-3 flex items-center justify-between">
+ <Eyebrow className="uppercase">{t('costs.whoPaid')}</Eyebrow>
+ <button
+ type="button"
+ onClick={() => (multiPayer ? disableMultiPayer() : enableMultiPayer())}
+ className="font-geist text-[0.625rem] font-semibold text-m-muted underline"
+ >
+ {multiPayer ? t('costs.singlePayer') : t('costs.multiplePayers')}
+ </button>
+ </div>
+ {!multiPayer ? (
+ <CustomSelect
+ value={String(payerId)}
+ onChange={v => setPayerId(Number(v))}
+ size="sm"
+ options={[
+ { value: '0', label: t('costs.noOnePaid') },
+ ...people.map(p => ({ value: String(p.id), label: nameOf(p) })),
+ ]}
+ style={{ width: '100%' }}
+ />
+ ) : (
+ <>
+ <div className="flex flex-col gap-[6px]">
+ {people.map((p, idx) => {
+ const on = payerIds.has(p.id)
+ return (
+ <div key={p.id} className={`${ROW_CLS} ${on ? '' : 'opacity-60'}`}>
+ <button
+ type="button"
+ onClick={() => togglePayer(p.id)}
+ className="flex min-w-0 flex-1 items-center gap-[8px] text-start"
+ >
+ <Avatar p={p} idx={idx} dim={!on} />
+ <span className="truncate text-[0.8125rem] font-medium text-m-ink">{nameOf(p)}</span>
+ </button>
+ {on ? (
+ <div className={`${MINI_INPUT_WRAP} w-[120px] flex-none`}>
+ <span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>
+ <NumericInput
+ mode="signed-decimal"
+ signToggleLabel={t('costs.toggleSign')}
+ placeholder={zeroAmountInput(currency)}
+ value={localizeAmountInput(payerAmounts[p.id] || '', currency)}
+ onValueChange={v => onPayerAmountChange(p.id, v)}
+ className="w-full border-0 bg-transparent py-[7px] text-end text-[0.8125rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
+ />
+ </div>
+ ) : (
+ <button type="button" onClick={() => togglePayer(p.id)} className="flex-none text-[0.6875rem] text-m-faint">
+ {t('costs.tapToInclude')}
+ </button>
+ )}
</div>
- ) : (
- <button type="button" onClick={() => togglePayer(p.id)} className="flex-none text-[0.6875rem] text-m-faint">
- {t('costs.tapToInclude')}
- </button>
- )}
+ )
+ })}
+ </div>
+ {!payersOk && (
+ <div className="mt-2 text-[0.6875rem] text-[color:var(--m-st-danger)]">
+ {t('costs.payersUnbalanced', { amount: formatMoney(totalNum, currency, locale) })}
</div>
- )
- })}
- </div>
- {!payersOk && (
- <div className="mt-2 text-[0.6875rem] text-[color:var(--m-st-danger)]">
- {t('costs.payersUnbalanced', { amount: formatMoney(totalNum, currency, locale) })}
- </div>
+ )}
+ </>
)}
- </>
- )}
- {/* SPLIT */}
- <Eyebrow className="mb-[6px] mt-3 uppercase">{t('costs.split')}</Eyebrow>
- <div className="flex rounded-full bg-[color:var(--m-ic)] p-[3px]">
- {SPLIT_MODES.map(m => (
- <button
- key={m.id}
- type="button"
- onClick={() => setSplitMode(m.id)}
- className={`flex-1 rounded-full py-[7px] text-[0.71875rem] font-semibold ${splitMode === m.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
- >
- {t(m.labelKey)}
- </button>
- ))}
- </div>
-
- {splitMode === 'custom' && (
- <>
- <div role="radiogroup" aria-label={t('costs.splitUnit')} className="mt-2 flex rounded-full bg-[color:var(--m-ic)] p-[3px]">
- {unitOptions.map(u => (
+ {/* SPLIT */}
+ <Eyebrow className="mb-[6px] mt-3 uppercase">{t('costs.split')}</Eyebrow>
+ <div className="flex rounded-full bg-[color:var(--m-ic)] p-[3px]">
+ {SPLIT_MODES.map(m => (
<button
- key={u.id}
+ key={m.id}
type="button"
- role="radio"
- aria-checked={splitUnits.unit === u.id}
- onClick={() => splitUnits.setUnit(u.id)}
- className={`min-w-0 flex-1 truncate rounded-full px-2 py-[6px] text-caption font-semibold ${splitUnits.unit === u.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
+ onClick={() => setSplitMode(m.id)}
+ className={`flex-1 rounded-full py-[7px] text-[0.71875rem] font-semibold ${splitMode === m.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
>
- {u.label}
+ {t(m.labelKey)}
</button>
))}
</div>
- <p className="mt-[6px] text-caption text-m-faint">
- {t(inPercent ? 'costs.splitHint.percent' : inUnits ? 'costs.splitHint.shares' : 'costs.splitHint.custom')}
- </p>
- </>
- )}
- {isTicketMode ? (
- <div className="mt-2 flex flex-col gap-2">
- {ticketItems.map(item => (
- <div key={item.id} className="flex flex-col gap-2 rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-[10px]">
- <div className="flex items-center gap-2">
- <input
- type="text"
- placeholder={t('costs.whatFor')}
- value={item.name}
- onChange={e => handleUpdateItemName(item.id, e.target.value)}
- className="min-w-0 flex-[2] rounded-[9px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[10px] py-[7px] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
- />
- <div className={`${MINI_INPUT_WRAP} min-w-0 flex-1`}>
- <span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>
- <NumericInput
- mode="decimal"
- placeholder={zeroAmountInput(currency)}
- value={localizeAmountInput(item.price, currency)}
- onValueChange={v => handleUpdateItemPrice(item.id, v)}
- className="w-full border-0 bg-transparent py-[7px] text-end text-[0.8125rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
- />
- </div>
- <button type="button" onClick={() => handleRemoveItem(item.id)} className="flex-none text-m-muted" aria-label={t('common.delete')}>
- <Trash2 size={15} strokeWidth={2} />
- </button>
- </div>
- <div className="flex flex-wrap gap-[5px]">
- {people.map((p, idx) => (
+ {splitMode === 'custom' && (
+ <>
+ <div role="radiogroup" aria-label={t('costs.splitUnit')} className="mt-2 flex rounded-full bg-[color:var(--m-ic)] p-[3px]">
+ {unitOptions.map(u => (
<button
- key={p.id}
+ key={u.id}
type="button"
- onClick={() => handleToggleItemParticipant(item.id, p.id)}
- className={`flex items-center gap-[4px] rounded-full px-[8px] py-[3px] text-[0.6875rem] font-medium ${
- item.participants.has(p.id) ? 'bg-m-act text-m-actfg' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] text-m-muted'
- }`}
+ role="radio"
+ aria-checked={splitUnits.unit === u.id}
+ onClick={() => splitUnits.setUnit(u.id)}
+ className={`min-w-0 flex-1 truncate rounded-full px-2 py-[6px] text-caption font-semibold ${splitUnits.unit === u.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
>
- <Avatar p={p} idx={idx} size={14} dim={!item.participants.has(p.id)} />
- <span>{nameOf(p)}</span>
+ {u.label}
</button>
))}
</div>
- </div>
- ))}
- <button
- type="button"
- onClick={handleAddEmptyItem}
- className="flex items-center justify-center gap-[6px] rounded-[12px] border border-dashed border-[color:var(--m-rowbr)] py-[10px] text-[0.78125rem] font-semibold text-m-muted"
- >
- <Plus size={14} strokeWidth={2.2} /> {t('common.add')}
- </button>
- {ticketItems.length > 0 && (
- <div className="rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
- <Eyebrow className="mb-[8px] uppercase">{t('costs.split')}</Eyebrow>
- <div className="flex flex-col gap-1">
- {people.map(p => (
- <div key={p.id} className="flex justify-between text-[0.8125rem]">
- <span className="text-m-muted">{nameOf(p)}</span>
- <span className="font-semibold text-m-ink [font-variant-numeric:tabular-nums]">{formatMoney(ticketInfo.shares[p.id] || 0, currency, locale)}</span>
- </div>
- ))}
- </div>
- </div>
+ <p className="mt-[6px] text-caption text-m-faint">
+ {t(inPercent ? 'costs.splitHint.percent' : inUnits ? 'costs.splitHint.shares' : 'costs.splitHint.custom')}
+ </p>
+ </>
)}
- </div>
- ) : (
- <>
- <div className="mt-2 flex flex-col gap-[6px]">
- {people.map((p, idx) => {
- const on = participants.has(p.id)
- return (
- <div key={p.id} className={`${ROW_CLS} ${on ? '' : 'opacity-60'}`}>
- <button
- type="button"
- onClick={() => toggleParticipant(p.id)}
- className="flex min-w-0 flex-1 items-center gap-[8px] text-start"
- >
- <Avatar p={p} idx={idx} dim={!on} />
- <span className="truncate text-[0.8125rem] font-medium text-m-ink">{nameOf(p)}</span>
- {p.is_guest && <GuestBadge size="xs" />}
- </button>
- {splitMode === 'equally' ? (
- on ? (
- <span className="flex-none pe-1 text-[0.8125rem] font-semibold text-m-ink [font-variant-numeric:tabular-nums]">
- {formatMoney(equalShares[p.id] || 0, currency, locale)}
- </span>
- ) : (
- <span className="flex-none pe-1 text-[0.6875rem] text-m-faint">{t('costs.tapToInclude')}</span>
- )
- ) : on && inUnits ? (
- <div className="flex w-[120px] flex-none flex-col items-end gap-[2px]">
- <div className={`${MINI_INPUT_WRAP} w-full`}>
- <input
- type="text"
- inputMode="decimal"
- aria-label={inPercent ? `${nameOf(p)} %` : t('costs.splitSharesOf', { name: nameOf(p) })}
- placeholder={splitUnits.placeholder}
- value={splitUnits.entries[p.id] ?? ''}
- onChange={e => splitUnits.onEntryChange(p.id, e.target.value)}
- className="w-full border-0 bg-transparent py-[7px] text-end text-body font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
- />
- {inPercent && <span className="text-caption text-m-faint">%</span>}
- </div>
- {customAmounts[p.id] && (
- <span className="text-caption text-m-faint [font-variant-numeric:tabular-nums]">
- {formatMoney(Number.parseFloat(customAmounts[p.id]) || 0, currency, locale)}
- </span>
- )}
- </div>
- ) : on ? (
- <div className={`${MINI_INPUT_WRAP} w-[120px] flex-none`}>
+
+ {isTicketMode ? (
+ <div className="mt-2 flex flex-col gap-2">
+ {ticketItems.map(item => (
+ <div key={item.id} className="flex flex-col gap-2 rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-[10px]">
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ placeholder={t('costs.whatFor')}
+ value={item.name}
+ onChange={e => handleUpdateItemName(item.id, e.target.value)}
+ className="min-w-0 flex-[2] rounded-[9px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[10px] py-[7px] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
+ />
+ <div className={`${MINI_INPUT_WRAP} min-w-0 flex-1`}>
<span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>
- <input
- type="text"
- inputMode="decimal"
- placeholder={localizeAmountInput(amountToInputString(placeholderShares[p.id] || 0, currency), currency)}
- value={localizeAmountInput(customAmounts[p.id] || '', currency)}
- onChange={e => handleCustomAmountChange(p.id, e.target.value)}
+ <NumericInput
+ mode="decimal"
+ placeholder={zeroAmountInput(currency)}
+ value={localizeAmountInput(item.price, currency)}
+ onValueChange={v => handleUpdateItemPrice(item.id, v)}
className="w-full border-0 bg-transparent py-[7px] text-end text-[0.8125rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
/>
</div>
- ) : (
- <button type="button" onClick={() => toggleParticipant(p.id)} className="flex-none text-[0.6875rem] text-m-faint">
- {t('costs.tapToInclude')}
+ <button type="button" onClick={() => handleRemoveItem(item.id)} className="flex-none text-m-muted" aria-label={t('common.delete')}>
+ <Trash2 size={15} strokeWidth={2} />
</button>
- )}
+ </div>
+ <div className="flex flex-wrap gap-[5px]">
+ {people.map((p, idx) => (
+ <button
+ key={p.id}
+ type="button"
+ onClick={() => handleToggleItemParticipant(item.id, p.id)}
+ className={`flex items-center gap-[4px] rounded-full px-[8px] py-[3px] text-[0.6875rem] font-medium ${
+ item.participants.has(p.id) ? 'bg-m-act text-m-actfg' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] text-m-muted'
+ }`}
+ >
+ <Avatar p={p} idx={idx} size={14} dim={!item.participants.has(p.id)} />
+ <span>{nameOf(p)}</span>
+ </button>
+ ))}
+ </div>
</div>
- )
- })}
- </div>
- <div className="mt-2 text-[0.71875rem]">
- {splitMode === 'equally' ? (
- <span className="text-m-faint">
- {participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, locale) })}
- </span>
- ) : (
- <span className={`font-semibold ${customBalanced ? 'text-[color:var(--m-st-confirmed)]' : 'text-[color:var(--m-st-danger)]'}`}>
- {/* An uneven split has no one share to print "each" with. */}
- {customBalanced
- ? t('costs.splitBalanced')
- : `${formatMoney(splitSum, currency, locale)} / ${formatMoney(totalNum, currency, locale)}`}
- </span>
- )}
- </div>
+ ))}
+ <button
+ type="button"
+ onClick={handleAddEmptyItem}
+ className="flex items-center justify-center gap-[6px] rounded-[12px] border border-dashed border-[color:var(--m-rowbr)] py-[10px] text-[0.78125rem] font-semibold text-m-muted"
+ >
+ <Plus size={14} strokeWidth={2.2} /> {t('common.add')}
+ </button>
+ {ticketItems.length > 0 && (
+ <div className="rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
+ <Eyebrow className="mb-[8px] uppercase">{t('costs.split')}</Eyebrow>
+ <div className="flex flex-col gap-1">
+ {people.map(p => (
+ <div key={p.id} className="flex justify-between text-[0.8125rem]">
+ <span className="text-m-muted">{nameOf(p)}</span>
+ <span className="font-semibold text-m-ink [font-variant-numeric:tabular-nums]">{formatMoney(ticketInfo.shares[p.id] || 0, currency, locale)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <>
+ <div className="mt-2 flex flex-col gap-[6px]">
+ {people.map((p, idx) => {
+ const on = participants.has(p.id)
+ return (
+ <div key={p.id} className={`${ROW_CLS} ${on ? '' : 'opacity-60'}`}>
+ <button
+ type="button"
+ onClick={() => toggleParticipant(p.id)}
+ className="flex min-w-0 flex-1 items-center gap-[8px] text-start"
+ >
+ <Avatar p={p} idx={idx} dim={!on} />
+ <span className="truncate text-[0.8125rem] font-medium text-m-ink">{nameOf(p)}</span>
+ {p.is_guest && <GuestBadge size="xs" />}
+ </button>
+ {splitMode === 'equally' ? (
+ on ? (
+ <span className="flex-none pe-1 text-[0.8125rem] font-semibold text-m-ink [font-variant-numeric:tabular-nums]">
+ {formatMoney(equalShares[p.id] || 0, currency, locale)}
+ </span>
+ ) : (
+ <span className="flex-none pe-1 text-[0.6875rem] text-m-faint">{t('costs.tapToInclude')}</span>
+ )
+ ) : on && inUnits ? (
+ <div className="flex w-[120px] flex-none flex-col items-end gap-[2px]">
+ <div className={`${MINI_INPUT_WRAP} w-full`}>
+ <input
+ type="text"
+ inputMode="decimal"
+ aria-label={inPercent ? `${nameOf(p)} %` : t('costs.splitSharesOf', { name: nameOf(p) })}
+ placeholder={splitUnits.placeholder}
+ value={splitUnits.entries[p.id] ?? ''}
+ onChange={e => splitUnits.onEntryChange(p.id, e.target.value)}
+ className="w-full border-0 bg-transparent py-[7px] text-end text-body font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
+ />
+ {inPercent && <span className="text-caption text-m-faint">%</span>}
+ </div>
+ {customAmounts[p.id] && (
+ <span className="text-caption text-m-faint [font-variant-numeric:tabular-nums]">
+ {formatMoney(Number.parseFloat(customAmounts[p.id]) || 0, currency, locale)}
+ </span>
+ )}
+ </div>
+ ) : on ? (
+ <div className={`${MINI_INPUT_WRAP} w-[120px] flex-none`}>
+ <span className="text-[0.75rem] text-m-faint">{sym(currency)}</span>
+ <input
+ type="text"
+ inputMode="decimal"
+ placeholder={localizeAmountInput(amountToInputString(placeholderShares[p.id] || 0, currency), currency)}
+ value={localizeAmountInput(customAmounts[p.id] || '', currency)}
+ onChange={e => handleCustomAmountChange(p.id, e.target.value)}
+ className="w-full border-0 bg-transparent py-[7px] text-end text-[0.8125rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
+ />
+ </div>
+ ) : (
+ <button type="button" onClick={() => toggleParticipant(p.id)} className="flex-none text-[0.6875rem] text-m-faint">
+ {t('costs.tapToInclude')}
+ </button>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ <div className="mt-2 text-[0.71875rem]">
+ {splitMode === 'equally' ? (
+ <span className="text-m-faint">
+ {participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, locale) })}
+ </span>
+ ) : (
+ <span className={`font-semibold ${customBalanced ? 'text-[color:var(--m-st-confirmed)]' : 'text-[color:var(--m-st-danger)]'}`}>
+ {/* An uneven split has no one share to print "each" with. */}
+ {customBalanced
+ ? t('costs.splitBalanced')
+ : `${formatMoney(splitSum, currency, locale)} / ${formatMoney(totalNum, currency, locale)}`}
+ </span>
+ )}
+ </div>
+ </>
+ )}
</>
)}
diff --git a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
index 9eba7d1cd..16d6956c4 100644
--- a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
@@ -45,11 +45,11 @@ 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, knownNames,
+ me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, flows, splitting, knownNames,
search, setSearch, segment, setSegment, catFilter, setCatFilter, dayFilter, setDayFilter,
totals, filtered, filteredSettlements, catBreakdown, exportCsv: handleExportCsv,
deleteExpense, undoSettlement: handleUndoSettlement,
- } = useCostsLedger({ tripId, trip, budgetItems, actions: planner.tripActions, canEdit, t, toast })
+ } = useCostsLedger({ tripId, trip, budgetItems, memberCount: tripMembers.length, actions: planner.tripActions, canEdit, t, toast })
const [catOpen, setCatOpen] = useState(false)
const [dayOpen, setDayOpen] = useState(false)
@@ -137,8 +137,9 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
<div className="mt-1 font-geist text-[1.875rem] font-extrabold tabular-nums tracking-[-0.02em]">
{formatMoney(totals.totalSpend, base, locale)}
</div>
- {/* Each figure under its own label, so the two pairs never read as one run. */}
- <div className="mt-[8px] flex flex-wrap gap-x-[22px] gap-y-[6px] text-[0.6875rem]" style={{ color: 'rgba(245,245,247,.7)' }}>
+ {/* Each figure under its own label, so the two pairs never read as one run.
+ Only with something to split (#2689), like everything owed below. */}
+ {splitting && <div className="mt-[8px] flex flex-wrap gap-x-[22px] gap-y-[6px] text-[0.6875rem]" style={{ color: 'rgba(245,245,247,.7)' }}>
<span className="flex flex-col">
{t('costs.yourShare')}
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>{formatMoney(totals.myShare, base, locale)}</b>
@@ -147,9 +148,10 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
{t('costs.youPaid')}
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>{formatMoney(totals.myPaid, base, locale)}</b>
</span>
- </div>
+ </div>}
</div>
+ {splitting && <>
{/* You owe / You're owed (spec §3.2). The two tiles stand level and each
amount sits at the foot of its tile, so a label that wraps in one of
them (German "Dir wird geschuldet") leaves both amounts on one line. */}
@@ -300,6 +302,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
})}
</div>
+ </>}
+
{/* By category (spec §3.5) */}
<div className="mt-2 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
<div className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint">{t('costs.byCategory')}</div>
@@ -342,7 +346,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
aria-label={t('costs.searchPlaceholder')}
className="mt-2 block w-full rounded-full border border-[color:var(--m-rowbr)] bg-m-card px-[13px] py-[10px] font-[inherit] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
/>
- <div className="mt-2 flex rounded-full bg-m-card p-[3px]">
+ {splitting && <div className="mt-2 flex rounded-full bg-m-card p-[3px]">
{(['all', 'mine', 'owed'] as const).map(seg => (
<button
key={seg}
@@ -354,7 +358,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
{t('costs.filter.' + seg)}
</button>
))}
- </div>
+ </div>}
<div className="mt-2 flex gap-2">
<button
@@ -469,6 +473,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
locale={locale}
t={t}
canEdit={canEdit}
+ splitting={splitting}
onEdit={() => {
setEditingExpense(en.item)
setExpenseModalOpen(true)
@@ -573,13 +578,15 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
}
/** One expense card (spec 03 §3.7): category ribbon, optional unfinished ribbon, member chips, total pill, edit/delete stack. */
-function ExpenseRow({ item, ctx, base, locale, t, canEdit, onEdit, onDelete, onTogglePaid, onPreviewReceipts }: {
+function ExpenseRow({ item, ctx, base, locale, t, canEdit, splitting, onEdit, onDelete, onTogglePaid, onPreviewReceipts }: {
item: BudgetItem
ctx: CostsCtx
base: string
locale: string
t: TFn
canEdit: boolean
+ /** False with nothing to split (#2689): no unfinished ribbon, no shares to tick paid. */
+ splitting: boolean
onEdit: () => void
onDelete: () => void
onTogglePaid: (userId: number, paid: boolean) => void
@@ -589,9 +596,9 @@ function ExpenseRow({ item, ctx, base, locale, t, canEdit, onEdit, onDelete, onT
const Icon = meta.Icon
const total = baseTotal(item, ctx)
const line = lineOf(item.total_price || 0, item, ctx, total)
- const unfinished = isUnfinished(item, ctx)
+ const unfinished = splitting && isUnfinished(item, ctx)
const borderColor = tint(meta.color, 0.55)
- const members = item.members || []
+ const members = splitting ? item.members || [] : []
const note = readUserNote(item)
// No swipe here: edit and delete stand beside the card already, and a swipe
diff --git a/client/tests/unit/mobile/trip/MCostSheet.test.tsx b/client/tests/unit/mobile/trip/MCostSheet.test.tsx
index 6f2596113..6c48055b3 100644
--- a/client/tests/unit/mobile/trip/MCostSheet.test.tsx
+++ b/client/tests/unit/mobile/trip/MCostSheet.test.tsx
@@ -10,7 +10,7 @@ import { localToday } from '../../../../src/components/Planner/today'
import { resetAllStores } from '../../../helpers/store'
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
-// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-041
+// FE-MOB-COSTSH-001 to FE-MOB-COSTSH-042
// The sheet reads its copy from useTranslation(), so assertions are English.
// EUR formats de-DE style: displayed amounts and inputs use a comma.
@@ -790,4 +790,17 @@ describe('MCostSheet', () => {
await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1))
expect(addBudgetItem.mock.calls[0][1]).toMatchObject({ receipt_file_ids: [51] })
})
+
+ it('FE-MOB-COSTSH-042: on a trip of one the sheet asks for no payer or split, and saves the expense as mine (#2689)', async () => {
+ renderSheet({ people: [PEOPLE[0]] })
+ expect(screen.queryByText(/Who paid/i)).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Equally' })).not.toBeInTheDocument()
+ fillBasics('Museum', '12')
+ fireEvent.click(submit())
+ await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1))
+ expect(addBudgetItem.mock.calls[0][1]).toMatchObject({
+ payers: [{ user_id: 1, amount: 12 }],
+ members: [{ user_id: 1, amount: null }],
+ })
+ })
})
diff --git a/client/tests/unit/mobile/trip/MCostsTab.test.tsx b/client/tests/unit/mobile/trip/MCostsTab.test.tsx
index 22dd074bc..7cd664e40 100644
--- a/client/tests/unit/mobile/trip/MCostsTab.test.tsx
+++ b/client/tests/unit/mobile/trip/MCostsTab.test.tsx
@@ -18,7 +18,7 @@ import { server } from '../../../helpers/msw/server'
import { fireEvent, render, screen, waitFor, within } from '../../../helpers/render'
import { setSizeClass } from '../../../helpers/sizeClass'
-// FE-MOB-COSTT-001 to FE-MOB-COSTT-053
+// FE-MOB-COSTT-001 to FE-MOB-COSTT-056
// The add/edit expense sheet is the shared desktop-sized form; the panel only
// owns when it opens and what happens on save, so it is stubbed here.
@@ -968,4 +968,18 @@ describe('MCostsTab', () => {
delete (document.documentElement as { dir?: string }).dir
}
})
+
+ it('FE-MOB-COSTT-056: a trip of one shows the total and the categories, nothing owed or to settle (#2689)', async () => {
+ serveSettlement({ balances: [], flows: [], settlements: [] })
+ const solo = planner({ tripMembers: [MEMBERS[0]] as unknown as TripPlanner['tripMembers'], budgetItems: [TAXI, SOUVENIR] })
+ render(<MCostsTab planner={solo} shell={buildShell()} />)
+ await waitFor(() => expect(settlementBases).toEqual(['USD']))
+ expect(screen.getByText('costs.totalSpend')).toBeInTheDocument()
+ expect(screen.getByText('costs.byCategory')).toBeInTheDocument()
+ for (const key of ['costs.yourShare', 'costs.youOwe', 'costs.outstanding', 'costs.settleUp', 'costs.finalBudget', 'costs.filter.mine', 'costs.unfinished']) {
+ expect(screen.queryByText(key)).not.toBeInTheDocument()
+ }
+ // The souvenirs nobody paid for are an expense like any other here.
+ expect(screen.getByText('Souvenirs')).toBeInTheDocument()
+ })
})
diff --git a/wiki/Budget-Tracking.md b/wiki/Budget-Tracking.md
index 3a893f28a..26858c901 100644
--- a/wiki/Budget-Tracking.md
+++ b/wiki/Budget-Tracking.md
@@ -161,6 +161,12 @@ The **Add payment** dialog has **From** and **To** (the head band reads *You →
Balances are always netted in the **trip currency** and converted to your display currency once, at the end, so they stay stable even when the trip mixes currencies. An expense or payment in a foreign currency for which no exchange rate is known yet is left out of the balances and totals rather than counted 1:1; see [Currencies](Currencies#expense-currency).
+## A trip of one
+
+With only you on the trip there is nothing to split: every share is the whole amount, and nobody can owe anybody. Costs then leaves that side out. The summary is the **Total trip spend** card on its own, with the number of expenses under it, and the right-hand column keeps **By category**. **You owe**, **You're owed**, **Outstanding amount**, **Settle up**, **Balances** and **Final budget** are gone, and so are the travelers in the bar, the **Settle up** button and the **All / Paid by me / I'm owed** switch. Rows show no payers, no split and no **Unfinished** chip, and the expense dialog asks for neither **Who paid?** nor **Split**; a new expense is saved as paid by you. The phone does the same.
+
+Everything comes back as soon as a second member joins. It also stays while the ledger still names someone else: a traveler who left with money open, or an expense split with them. An expense whose payers or split hold more than you alone (several payers, an uneven split, a ticket) keeps both sections in its dialog, so nothing on it is hidden from you.
+
## Members who left and deleted guests
Someone who has left the trip is still named in the lists and keeps their balance, so the settlement stays correct. Deleting a guest keeps the costs adding up: their payments are not dropped from the totals.