import { focusRevealedEditor } from '../shared/dialogFocus' import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react' import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react' import { useTranslation } from '../../i18n' import type { BudgetItem } from '../../types' import { NEUTRAL_TINT, fs } from '../shared/DialogShell' import { Segmented } from '../shared/dialogParts' import { Tooltip } from '../shared/Tooltip' import { CustomDatePicker } from '../shared/CustomDateTimePicker' import { MoreButton, tintOf } from '../Planner/planParts' import { COST_CATEGORY_LIST, catMeta } from './costsCategories' import { calcPD, calcPP, calcPPD, hasCustomMemberSplit, normalizePastedAmount } from './BudgetPanel.helpers' /** * The Costs tab as a categorized table: the planning view the old budget had, * built on the same expenses the list shows. Name, date, total, persons and days * edit in place; everything a split or a payer needs stays in the expense * dialog, which each row opens. */ type EditableField = 'name' | 'total_price' | 'persons' | 'days' export interface CostsTableProps { /** The expenses left after the bar's search and filters. */ items: BudgetItem[] /** The display currency everything is shown in. */ base: string canEdit: boolean /** An expense's total in the display currency, booked at its frozen rate. */ baseTotal: (e: BudgetItem) => number /** Any amount of an expense in the display currency. */ toBase: (amount: number, e: BudgetItem) => number /** The currency an expense was entered in. */ currencyOf: (e: BudgetItem) => string fmt: (amount: number) => string personName: (userId: number) => string onUpdate: (id: number, patch: Partial) => Promise /** Creates an empty expense in a category and resolves with it. */ onAdd: (category: string, expenseDate: string | null) => Promise onOpen: (e: BudgetItem) => void onDelete: (id: number) => void } // Every column is centred on its title except the name, which reads from the left. const HEAD_BASE = 'px-3 py-2.5 font-geist font-bold uppercase tracking-[.08em] text-content-faint' const HEAD = `${HEAD_BASE} text-center` const CELL = 'px-3 py-2 text-center tabular-nums text-content' /** The three worked-out columns sit on their own quiet ground, apart from what is typed in. */ const CALC = 'bg-surface-secondary' /** A value you can change, shown the way the rest of the app shows a fact: a white badge. */ const BADGE = 'inline-flex h-6 min-w-[40px] items-center justify-center rounded-full bg-surface-card px-2.5 font-geist tabular-nums text-content shadow-sm ring-1 ring-edge-faint' /** The same place with nothing in it yet: a dashed outline and a plus that says it takes a value. */ const BADGE_EMPTY = 'inline-flex h-6 min-w-[40px] items-center justify-center rounded-full border border-dashed border-edge text-content-faint transition-colors group-hover:border-content-faint' /** Shown and edited, a cell keeps one height, so a row never grows while you type in it. */ const CELL_H = 'h-7' const INPUT = `${CELL_H} w-full min-w-0 rounded-[8px] border border-edge bg-surface-input px-1.5 py-0 leading-none text-content outline-none focus:ring-2 focus:ring-[color:var(--text-primary)]` const hasPayers = (e: BudgetItem) => (e.payers || []).some(p => p.amount !== 0) export default function CostsTable(p: CostsTableProps) { const { t, locale } = useTranslation() const [collapsed, setCollapsed] = useState>(new Set()) const [editing, setEditing] = useState<{ id: number; field: EditableField } | null>(null) const groups = useMemo(() => { const byKey = new Map() for (const e of p.items) { const key = catMeta(e.category).key if (!byKey.has(key)) byKey.set(key, []) byKey.get(key)!.push(e) } // The category order of the dialog, each group oldest first like a ledger on paper. return COST_CATEGORY_LIST .filter(c => byKey.has(c.key)) .map(c => ({ meta: c, items: byKey.get(c.key)!.slice().sort((a, b) => (a.expense_date || '￿').localeCompare(b.expense_date || '￿') || a.id - b.id) })) }, [p.items]) const grandTotal = p.items.reduce((sum, e) => sum + p.baseTotal(e), 0) const numFmt = (v: number | null) => v == null ? '' : new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(v) const toggle = (key: string) => setCollapsed(prev => { const next = new Set(prev) if (next.has(key)) next.delete(key); else next.add(key) return next }) // A new row takes the latest date of its category, so back-filling a day goes quickly. const add = async (category: string) => { const dates = p.items.filter(e => catMeta(e.category).key === category && e.expense_date).map(e => e.expense_date as string).sort((a, b) => a.localeCompare(b)) const created = await p.onAdd(category, dates.length ? dates[dates.length - 1] : null) if (created) setEditing({ id: created.id, field: 'name' }) } return (
{groups.map(({ meta, items }) => { const open = !collapsed.has(meta.key) const subtotal = items.reduce((sum, e) => sum + p.baseTotal(e), 0) return ( {open && items.map(e => ( ))} {open && p.canEdit && ( )} ) })}
{t('budget.table.name')} {t('budget.table.date')} {t('budget.table.total')} {t('budget.table.persons')} {t('budget.table.days')} {t('budget.table.perPerson')} {t('budget.table.perDay')} {t('budget.table.perPersonDay')} {t('files.menu')}
{p.fmt(subtotal)}
{t('budget.total')} {p.items.length} {p.fmt(grandTotal)}
) } /** One expense as a table row, its own cells editable in place. */ function Row({ e, p, editing, setEditing, numFmt }: { e: BudgetItem p: CostsTableProps editing: { id: number; field: EditableField } | null setEditing: (v: { id: number; field: EditableField } | null) => void numFmt: (v: number | null) => string }) { const { t, locale } = useTranslation() const total = p.baseTotal(e) const custom = hasCustomMemberSplit(e) const persons = e.persons ?? null const days = e.days ?? null const foreign = p.currencyOf(e) !== p.base // A total someone paid is the sum of what they paid, and a foreign one is shown // converted: both change in the expense itself, where the split and the rate live. const totalLock = hasPayers(e) ? t('costs.table.lockedPayer') : foreign ? t('costs.table.lockedCurrency', { currency: p.currencyOf(e) }) : null const isEditing = (field: EditableField) => editing?.id === e.id && editing.field === field const save = (patch: Partial) => { setEditing(null); void p.onUpdate(e.id, patch) } const dateText = e.expense_date ? (() => { try { return new Date(e.expense_date + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return e.expense_date } })() : '' return ( setEditing({ id: e.id, field: 'name' })} display={{e.name}} input={ { if (v.trim()) save({ name: v.trim() }); else setEditing(null) }} onCancel={() => setEditing(null)} label={t('budget.table.name')} />} /> {p.canEdit ? ( // The app's own calendar, the way the old table picked a day.
void p.onUpdate(e.id, { expense_date: v || null })} placeholder={t('costs.noDate')} compact borderless />
) : ( {dateText || t('costs.noDate')} )} {totalLock ? ( ) : ( setEditing({ id: e.id, field: 'total_price' })} align="center" display={{p.fmt(total)}} input={ { const n = Number(normalizePastedAmount(v)) if (v.trim() && Number.isFinite(n)) save({ total_price: n }); else setEditing(null) }} onCancel={() => setEditing(null)} label={t('budget.table.total')} />} /> )} {(['persons', 'days'] as const).map(field => { const value = field === 'persons' ? persons : days return ( setEditing({ id: e.id, field })} align="center" display={value == null ? {p.canEdit ? : null} : {value}} input={ { const n = Number.parseInt(v, 10) save({ [field]: v.trim() === '' ? null : Number.isFinite(n) && n > 0 ? n : null } as Partial) }} onCancel={() => setEditing(null)} label={t(`budget.table.${field}`)} />} /> ) })} {/* An uneven split has no single share per person, so those columns stay empty (#1458). */} {custom ? '' : numFmt(calcPP(total, persons))} {numFmt(calcPD(total, days))} {custom ? '' : numFmt(calcPPD(total, persons, days))} p.onOpen(e) }, p.canEdit && { divider: true }, p.canEdit && { label: t('common.delete'), icon: Trash2, danger: true, onClick: () => p.onDelete(e.id) }, ]} size={26} /> ) } /** A value that turns into a field on a click (or Enter), when the viewer may edit. */ function EditCell({ label, text, canEdit, editing, onEdit, display, input, align = 'left' }: { label: string /** The value as words, for the button's name: "Total: 45.00". */ text: string canEdit: boolean editing: boolean onEdit: () => void display: ReactNode input: ReactNode align?: 'left' | 'right' | 'center' }) { const justify = align === 'right' ? 'justify-end' : align === 'center' ? 'justify-center' : 'justify-start' if (editing) return <>{input} if (!canEdit) return {display} return ( ) } /** The field a cell becomes: Enter or Tab keeps it, Escape leaves it as it was. */ function TextInput({ value, onSave, onCancel, label, numeric = false }: { value: string onSave: (v: string) => void onCancel: () => void label: string numeric?: boolean }) { const [draft, setDraft] = useState(value) const done = useRef(false) const finish = (fn: () => void) => { if (done.current) return; done.current = true; fn() } const onKey = (ev: KeyboardEvent) => { if (ev.key === 'Enter') { ev.preventDefault(); finish(() => onSave(draft)) } // Spent here: the field lets go, the page around it stays. if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) } } return ( setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))} className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} /> ) } 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, splitting = true }: Pick & { /** False with nothing to split (#2689): who paid and paid or open are no question then. */ splitting?: boolean }) { const { t, locale } = useTranslation() const [picked, setTab] = useState('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() const addTo = (key: string, label: string, amount: number, color?: string) => { const prev = sum.get(key) sum.set(key, { label, amount: (prev?.amount ?? 0) + amount, color }) } for (const e of items) { const total = baseTotal(e) if (tab === 'category') { const m = catMeta(e.category) addTo(m.key, t(m.labelKey), total, m.color) } else if (tab === 'date') { const d = e.expense_date || '' const label = d ? (() => { try { return new Date(d + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return d } })() : t('costs.noDate') addTo(d || '￿', label, total) } else if (tab === 'payer') { const paid = (e.payers || []).filter(x => x.amount !== 0) if (paid.length === 0) addTo('none', t('costs.table.noPayer'), total) for (const x of paid) addTo(String(x.user_id), personName(x.user_id), toBase(x.amount, e)) } else if (hasPayers(e)) { addTo('paid', t('costs.table.paid'), total, 'var(--success)') } else { addTo('open', t('costs.table.open'), total, 'var(--warning)') } } const list = Array.from(sum.entries()).map(([key, v]) => ({ key, ...v })) if (tab === 'date') return list.sort((a, b) => a.key.localeCompare(b.key)) return list.sort((a, b) => b.amount - a.amount) }, [items, tab, baseTotal, toBase, personName, locale, t]) const max = Math.max(1, ...rows.map(r => Math.abs(r.amount))) return (
{t('costs.table.summary')} 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') }, ...(splitting ? [ { value: 'payer' as const, label: t('costs.table.byPayer') }, { value: 'status' as const, label: t('costs.table.byStatus') }, ] : []), ]} />
    {rows.length === 0 &&
  • {t('costs.emptyText')}
  • } {rows.map(r => (
  • {r.color && } {r.label} {fmt(r.amount)}
  • ))}
) }