feat(costs): leave a category out of the totals for a look (#2819)

Seeing what a trip cost without, say, food meant adding it up by hand. A
click (or tap) on a category in the breakdown now leaves it out of the
total, your share and what you paid, dimmed in place with a line naming it
and Count all to undo. View only: nothing is saved, and what is owed, open
or settled stays whole. The desktop breakdown moves into its own component.
This commit is contained in:
Maurice
2026-11-13 10:04:57 +01:00
parent a70eea5bf2
commit 72fc61a016
40 changed files with 480 additions and 63 deletions
@@ -0,0 +1,62 @@
// FE-COSTS-CATBARS-001 to FE-COSTS-CATBARS-003
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import { CostsCategoryBreakdown } from './CostsCategoryBreakdown';
import type { CostsCategoryBar } from './costsModel';
const fmt = (v: number) => `${v} €`;
const rows: CostsCategoryBar[] = [
{ key: 'accommodation', amount: 300, widthPct: 100, leftOut: false },
{ key: 'food', amount: 120, widthPct: 40, leftOut: false },
];
function setup(over: Partial<Parameters<typeof CostsCategoryBreakdown>[0]> = {}) {
const onToggle = vi.fn();
const onCountAll = vi.fn();
render(
<CostsCategoryBreakdown
rows={rows}
leftOutLabel=""
fmt={fmt}
onToggle={onToggle}
onCountAll={onCountAll}
{...over}
/>
);
return { onToggle, onCountAll };
}
describe('CostsCategoryBreakdown (#2819)', () => {
it('FE-COSTS-CATBARS-001: a category is clicked out of the totals, with a hint on how', async () => {
const user = userEvent.setup();
const { onToggle } = setup();
expect(screen.getByText('Select a category to leave it out of the totals.')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Leave Food & drink out of the totals' }));
expect(onToggle).toHaveBeenCalledWith('food');
});
it('FE-COSTS-CATBARS-002: a category left out stays dimmed in place and says what is left out', async () => {
const user = userEvent.setup();
const { onToggle, onCountAll } = setup({
rows: [rows[0], { ...rows[1], leftOut: true, widthPct: 0 }],
leftOutLabel: 'Left out of the totals: Food & drink',
});
const food = screen.getByRole('button', { name: 'Count Food & drink in the totals again' });
expect(food.className).toContain('opacity-45');
expect(screen.getByText('120 €').className).toContain('line-through');
expect(screen.getByText('Left out of the totals: Food & drink')).toBeInTheDocument();
expect(screen.queryByText('Select a category to leave it out of the totals.')).toBeNull();
await user.click(food);
expect(onToggle).toHaveBeenCalledWith('food');
await user.click(screen.getByRole('button', { name: 'Count all' }));
expect(onCountAll).toHaveBeenCalledTimes(1);
});
it('FE-COSTS-CATBARS-003: without spend there is nothing to break down', () => {
setup({ rows: [] });
expect(screen.getByText('No expenses yet.')).toBeInTheDocument();
expect(screen.queryByRole('button')).toBeNull();
});
});
@@ -0,0 +1,101 @@
import type { CostCategory } from '@trek/shared';
import { RotateCcw } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { fs } from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { COST_CAT_META } from './costsCategories';
import type { CostsCategoryBar } from './costsModel';
/**
* What each category cost, as a ranked list of bars (spec §3.5), on the
* desktop Costs panel. Categories net refunds against spend (#2176): a category
* that nets negative keeps its row without a bar. Bars are scaled against the
* most expensive category counted, not the trip total, so the ranking reads.
*
* A row is a switch that leaves its category out of the totals for a look
* without it (#2819). It stays in place, dimmed and struck through, and the
* line on top says what is left out, with a way to count everything again.
*/
export function CostsCategoryBreakdown({
rows,
leftOutLabel,
fmt,
onToggle,
onCountAll,
}: {
rows: CostsCategoryBar[];
/** What the totals leave out, as the line on top says it; empty while everything counts. */
leftOutLabel: string;
fmt: (amount: number) => string;
onToggle: (key: CostCategory) => void;
onCountAll: () => void;
}) {
const { t } = useTranslation();
if (rows.length === 0) {
return (
<div className="text-content-faint" style={fs(12.5, 'body')}>
{t('costs.noCategories')}
</div>
);
}
return (
<div className="flex flex-col gap-3">
{leftOutLabel ? (
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="min-w-0 text-content-muted" style={fs(12, 'body')}>
{leftOutLabel}
</span>
<button
type="button"
onClick={onCountAll}
className="inline-flex flex-none items-center gap-1 rounded-full bg-surface-card px-2.5 py-1 font-semibold text-content-muted shadow-sm hover:text-content"
style={fs(11.5)}
>
<RotateCcw size={12} /> {t('costs.breakdown.countAll')}
</button>
</div>
) : (
rows.length > 1 && (
<p className="m-0 text-content-faint" style={fs(11.5)}>
{t('costs.breakdown.hint')}
</p>
)
)}
{rows.map((row) => {
const c = COST_CAT_META[row.key];
const name = t(c.labelKey);
const action = row.leftOut
? t('costs.breakdown.countIn', { category: name })
: t('costs.breakdown.leaveOut', { category: name });
return (
<Tooltip key={row.key} label={action}>
<button
type="button"
aria-label={action}
onClick={() => onToggle(row.key)}
className={`grid w-full grid-cols-[auto_1fr_auto] items-center gap-x-2.5 gap-y-1 rounded-lg text-start transition-opacity ${row.leftOut ? 'opacity-45' : ''}`}
>
<span className="h-2.5 w-2.5 rounded-[3px]" style={{ background: c.color }} />
<span className="text-content" style={fs(13, 'body')}>
{name}
</span>
<span
className={`font-semibold text-content-muted ${row.leftOut ? 'line-through' : ''}`}
style={fs(13, 'body')}
>
{fmt(row.amount)}
</span>
<span className="col-span-full h-[5px] overflow-hidden rounded-[3px] bg-surface-secondary">
<span
className="block h-full rounded-[3px]"
style={{ width: `${row.widthPct}%`, background: c.color }}
/>
</span>
</button>
</Tooltip>
);
})}
</div>
);
}
+12 -33
View File
@@ -14,7 +14,7 @@ import { useReceiptScan } from './useReceiptScan'
import { ReceiptScanModal } from './ReceiptScanModal'
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 { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import {
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
myPaidOf as myPaidOfModel, paymentAmount, paymentLineOf, settledShareOf,
@@ -31,6 +31,7 @@ import { useExpenseDeleteConfirm } from './useExpenseDeleteConfirm'
import { FlowPills } from './FlowPills'
import { CostsSplitChips } from './CostsSplitChips'
import { CostsModeCard } from './CostsModeCard'
import { CostsCategoryBreakdown } from './CostsCategoryBreakdown'
import type { BudgetParticipantFinal, ReceiptLine } from '@trek/shared'
import type { BudgetItem, BudgetItemReceipt } from '../../types'
import type { TripMember } from './BudgetPanelMemberChips'
@@ -74,7 +75,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const {
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,
totals, filtered, filteredSettlements, catBreakdown, leftOutLabel, toggleLeftOutCat, countAllCats, exportCsv: handleExportCsv,
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll,
} = useCostsLedger({
tripId, trip, budgetItems, memberCount: tripMembers.length, actions: { loadBudgetItems, deleteBudgetItem }, canEdit, t, toast,
@@ -237,12 +238,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
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 ? <>
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>} />
</> : <span className={CHIP}>{t('costs.expensesCount', { count: budgetItems.length })}</span>}
{leftOutLabel && <span className={`${CHIP} text-warning`}>{leftOutLabel}</span>}</>} />
)
// Spend by category; a click leaves one out of the totals for a look without it (#2819).
const categoryBars = <CostsCategoryBreakdown rows={catBreakdown} leftOutLabel={leftOutLabel} fmt={v => fmt0(v)}
onToggle={toggleLeftOutCat} onCountAll={countAllCats} />
// ── 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
@@ -377,7 +383,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
) : (
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
{sideHead(t('costs.byCategory'))}
<div className="px-4 py-4">{CategoryBreakdown()}</div>
<div className="px-4 py-4">{categoryBars}</div>
</section>
)}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
@@ -606,7 +612,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{/* By category */}
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
{CategoryBreakdown()}
{categoryBars}
</div>
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
</div>
@@ -978,33 +984,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div>
)
}
function CategoryBreakdown() {
// Categories net refunds against spend (#2176): a negative entry lowers its
// category's sum, and a category that nets negative keeps its own row,
// just without a bar, since the bars rank positive spend. Bars are scaled
// relative to the most expensive category (the top row fills the bar), not
// to the trip grand total, which makes the relative ranking readable.
if (catBreakdown.length === 0) return <div className="text-content-faint" style={{ fontSize: 'calc(12.5px * var(--fs-scale-body, 1))' }}>{t('costs.noCategories')}</div>
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{catBreakdown.map(row => {
const c = COST_CAT_META[row.key]
const v = row.amount; const pct = row.widthPct
return (
<div key={row.key} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 10, alignItems: 'center' }}>
<span style={{ width: 10, height: 10, borderRadius: 3, background: c.color }} />
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>{t(c.labelKey)}</span>
<span className="text-content-muted" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{fmt0(v)}</span>
<div className="bg-surface-secondary" style={{ gridColumn: '1 / -1', height: 5, borderRadius: 3, overflow: 'hidden', marginTop: -2 }}>
<span style={{ display: 'block', height: '100%', width: pct + '%', background: c.color, borderRadius: 3 }} />
</div>
</div>
)
})}
</div>
)
}
}
// ── Add / edit expense modal ───────────────────────────────────────────────
@@ -1,9 +1,11 @@
import type { CostCategory } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { buildBudgetItem } from '../../../tests/helpers/factories';
import type { BudgetItem } from '../../types';
import {
buildCostsCsv,
categoryBreakdown,
computeTotals,
currencyOptions,
filterBudgetItems,
@@ -18,7 +20,7 @@ import {
type CostsSettlement,
} from './costsModel';
// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-014
// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-015
// 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.
@@ -180,3 +182,25 @@ describe('costsModel: when Costs shows who paid and the shares (#2689, #1714)',
expect(showsSplitting('split', 3, [shared], { flows: [flow], balances: [] }, 1)).toBe(true);
});
});
describe('costsModel: categories left out of the totals (#2819)', () => {
it('FE-BUDGET-COSTSMODEL-015: they leave what was spent, paid and shared, not what is owed or open, and keep their row', () => {
const food = expense({
category: 'food',
total_price: 40,
payers: [payer(1, 40)],
members: [member(1), member(2)],
});
const hotel = expense({ category: 'accommodation', total_price: 100, payers: [], members: [member(1)] });
const flow = { from: { user_id: 2, username: 'u2' }, to: { user_id: 1, username: 'u1' }, amount: 20 };
const without = computeTotals([food, hotel], [flow], ctx, myShareOf, new Set<CostCategory>(['food']));
expect(without).toMatchObject({ totalSpend: 100, myPaid: 0, myShare: 100, owed: 20, outstanding: 100 });
expect(computeTotals([food, hotel], [flow], ctx).totalSpend).toBe(140);
const bars = categoryBreakdown([food, hotel], ctx, new Set<CostCategory>(['accommodation']));
expect(bars.map((b) => [b.key, b.leftOut, b.widthPct])).toEqual([
['accommodation', true, 0],
['food', false, 100],
]);
});
});
+35 -9
View File
@@ -225,15 +225,30 @@ export interface CostsTotals {
outstandingCount: number;
}
/** No category left out of the totals. */
const ALL_COUNTED: ReadonlySet<CostCategory> = new Set();
/** Whether an expense counts in the totals while `leftOut` categories are set aside. */
function counts(e: BudgetItem, leftOut: ReadonlySet<CostCategory>): boolean {
return leftOut.size === 0 || !leftOut.has(catMeta(e.category).key);
}
/**
* The hero and tile figures. Categories left out for a look without them
* (#2819) leave what was spent, paid and shared; what is owed and still open
* stays whole, since leaving a category out of the view settles nothing.
*/
export function computeTotals(
items: BudgetItem[],
flows: CostsSettlementFlow[],
ctx: CostsCtx,
shareOf: ShareOf = myShareOf
shareOf: ShareOf = myShareOf,
leftOut: ReadonlySet<CostCategory> = ALL_COUNTED
): CostsTotals {
const totalSpend = items.reduce((a, e) => a + baseTotal(e, ctx), 0);
const myPaid = items.reduce((a, e) => a + myPaidOf(e, ctx), 0);
const myShare = items.reduce((a, e) => a + shareOf(e, ctx), 0);
const counted = items.filter((e) => counts(e, leftOut));
const totalSpend = counted.reduce((a, e) => a + baseTotal(e, ctx), 0);
const myPaid = counted.reduce((a, e) => a + myPaidOf(e, ctx), 0);
const myShare = counted.reduce((a, e) => a + shareOf(e, ctx), 0);
const owe = flows.filter((f) => f.from.user_id === ctx.me).reduce((a, f) => a + f.amount, 0);
const owed = flows.filter((f) => f.to.user_id === ctx.me).reduce((a, f) => a + f.amount, 0);
const outstandingItems = items.filter((e) => isUnfinished(e, ctx));
@@ -366,11 +381,17 @@ export function dayFilterKeys(items: BudgetItem[]): string[] {
export interface CostsCategoryBar {
key: CostCategory;
amount: number;
/** 0-100, relative to the largest category (not the grand total) — spec §3.5. */
/** 0-100, relative to the largest category counted (not the grand total) — spec §3.5. */
widthPct: number;
/** Left out of the totals for now (#2819): the row stays, without a bar. */
leftOut: boolean;
}
export function categoryBreakdown(items: BudgetItem[], ctx: CostsCtx): CostsCategoryBar[] {
export function categoryBreakdown(
items: BudgetItem[],
ctx: CostsCtx,
leftOut: ReadonlySet<CostCategory> = ALL_COUNTED
): CostsCategoryBar[] {
// Categories net refunds against spend (#2176): a negative entry lowers its
// category's sum. A category that nets negative keeps its own row at the
// bottom, with widthPct 0 — the bars rank positive spend, and a negative
@@ -380,11 +401,16 @@ export function categoryBreakdown(items: BudgetItem[], ctx: CostsCtx): CostsCate
const key = catMeta(e.category).key;
totals.set(key, (totals.get(key) || 0) + baseTotal(e, ctx));
}
const rows = COST_CATEGORY_LIST.map((c) => ({ key: c.key, amount: totals.get(c.key) || 0 }))
// A row left out keeps its place, so it does not jump while it is toggled.
const rows = COST_CATEGORY_LIST.map((c) => ({
key: c.key,
amount: totals.get(c.key) || 0,
leftOut: leftOut.has(c.key),
}))
.filter((r) => r.amount !== 0)
.sort((a, b) => b.amount - a.amount);
const max = Math.max(0, ...rows.map((r) => r.amount));
return rows.map((r) => ({ ...r, widthPct: max > 0 && r.amount > 0 ? (r.amount / max) * 100 : 0 }));
const max = Math.max(0, ...rows.filter((r) => !r.leftOut).map((r) => r.amount));
return rows.map((r) => ({ ...r, widthPct: !r.leftOut && max > 0 && r.amount > 0 ? (r.amount / max) * 100 : 0 }));
}
// ── presentation helpers ─────────────────────────────────────────────────
@@ -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-015
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-016
const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -273,6 +273,24 @@ describe('useCostsLedger: a trip that keeps totals only (#1714)', () => {
});
});
describe('useCostsLedger: categories left out (#2819)', () => {
it('FE-BUDGET-LEDGER-016: a category left out leaves the total and is named, and counting all brings it back', async () => {
const { result } = setup();
await waitFor(() => expect(result.current.settlement).toEqual(SETTLEMENT));
const whole = result.current.totals.totalSpend;
const [first] = result.current.catBreakdown;
act(() => result.current.toggleLeftOutCat(first.key));
expect(result.current.totals.totalSpend).toBeCloseTo(whole - first.amount, 6);
expect(result.current.catBreakdown.find((r) => r.key === first.key)?.leftOut).toBe(true);
expect(result.current.leftOutLabel).toBe('costs.breakdown.leftOut');
// What is owed stays whole: the flows are the server's.
expect(result.current.totals.owe).toBe(15);
act(() => result.current.countAllCats());
expect(result.current.totals.totalSpend).toBe(whole);
expect(result.current.leftOutLabel).toBe('');
});
});
describe('useCostsLedger: writes', () => {
it('FE-BUDGET-LEDGER-009: deleting an expense reads the settlement again, a failure toasts', async () => {
const { result } = setup();
+27 -2
View File
@@ -1,3 +1,4 @@
import type { CostCategory } from '@trek/shared';
import { liveQuery } from 'dexie';
import { useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
@@ -12,6 +13,7 @@ import { useServerPing } from '../../sync/useServerPing';
import type { BudgetItem, Trip } from '../../types';
import { downloadBlob } from '../../utils/fileDownload';
import { localToday } from '../Planner/today';
import { COST_CAT_META } from './costsCategories';
import {
buildCostsCsv,
categoryBreakdown,
@@ -184,6 +186,18 @@ export function useCostsLedger({
const [segment, setSegment] = useState<CostsSegment>('all');
const [catFilter, setCatFilter] = useState(''); // '' = all categories
const [dayFilter, setDayFilter] = useState(''); // '' = all days, else YYYY-MM-DD
// Categories left out of the totals for a look without them (#2819): only this
// view, nothing is saved and nothing owed changes.
const [leftOutCats, setLeftOutCats] = useState<ReadonlySet<CostCategory>>(() => new Set());
const toggleLeftOutCat = useCallback((key: CostCategory) => {
setLeftOutCats((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, []);
const countAllCats = useCallback(() => setLeftOutCats(new Set()), []);
const shareOf = skipUnfinishedShares ? settledShareOf : myShareOf;
const flows = useMemo(() => settlement?.flows || [], [settlement]);
@@ -197,7 +211,10 @@ export function useCostsLedger({
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 totals = useMemo(
() => computeTotals(budgetItems, flows, ctx, shareOf, leftOutCats),
[budgetItems, flows, ctx, shareOf, leftOutCats]
);
const filtered = useMemo(
() =>
filterBudgetItems(
@@ -219,7 +236,12 @@ export function useCostsLedger({
: [],
[splitting, settlement, search, activeSegment, catFilter, dayFilter, me]
);
const catBreakdown = useMemo(() => categoryBreakdown(budgetItems, ctx), [budgetItems, ctx]);
const catBreakdown = useMemo(() => categoryBreakdown(budgetItems, ctx, leftOutCats), [budgetItems, ctx, leftOutCats]);
// What the totals leave out, named in the breakdown's order, for the line that says so.
const leftOutLabel = useMemo(() => {
const names = catBreakdown.filter((r) => r.leftOut).map((r) => t(COST_CAT_META[r.key].labelKey));
return names.length > 0 ? t('costs.breakdown.leftOut', { categories: names.join(', ') }) : '';
}, [catBreakdown, t]);
// CSV export of all expenses, the wiki-documented export that got lost in the
// Costs rework (#1500). One row per expense, oldest first.
@@ -324,6 +346,9 @@ export function useCostsLedger({
filtered,
filteredSettlements,
catBreakdown,
leftOutLabel,
toggleLeftOutCat,
countAllCats,
exportCsv,
deleteExpense,
undoSettlement,