mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
refactor(budget): share the costs ledger and settlement form between desktop and phone
costsModel moves from the phone tabs to components/Budget. useCostsLedger holds the settlement, the totals, the filters, the CSV export and the payments, and useSettlementForm holds the payment form. CostsPanel and MCostsTab both run on them. The old differences stay behind flags. The desktop also loads the settlement on a trip change, leaves expenses nobody paid out of my share (#2225) and writes each currency as stored in the CSV. The phone sheet starts blank, refills when it opens and ignores a second save while one is running.
This commit is contained in:
@@ -11,7 +11,8 @@ import { useTripStore } from '../../../../store/tripStore'
|
||||
import { formatMoney, localizeAmountInput } from '../../../../utils/formatters'
|
||||
import { openFile } from '../../../../utils/fileDownload'
|
||||
import { splitShareLabel } from '../../../../components/Budget/expenseFx'
|
||||
import { SYMBOLS, SPLIT_COLORS, currenciesWith } from '../../../../components/Budget/BudgetPanel.constants'
|
||||
import { SPLIT_COLORS } from '../../../../components/Budget/BudgetPanel.constants'
|
||||
import { currencyOptions } from '../../../../components/Budget/costsModel'
|
||||
import { COST_CATEGORY_LIST, catMeta } from '../../../../components/Budget/costsCategories'
|
||||
import { NOTE_MAX } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'
|
||||
@@ -166,7 +167,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
|
||||
onChange={v => setCurrency(String(v))}
|
||||
searchable
|
||||
size="sm"
|
||||
options={currenciesWith(currency).map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
|
||||
options={currencyOptions(currency)}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
import { convertBooked, convertedLine } from '../../../../hooks/useExchangeRates'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
AlertCircle, ArrowDown, ArrowLeftRight, ArrowRight, ArrowUp, Check, ChevronDown, ChevronUp,
|
||||
Layers, Pencil, Plus, RotateCcw, StickyNote, Trash2, Receipt,
|
||||
} from 'lucide-react'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useExchangeRates, withFallbackFx } from '../../../../hooks/useExchangeRates'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { amountToInputString, formatMoney } from '../../../../utils/formatters'
|
||||
import { downloadBlob, openFile } from '../../../../utils/fileDownload'
|
||||
import { budgetApi } from '../../../../api/client'
|
||||
import { formatMoney } from '../../../../utils/formatters'
|
||||
import { openFile } from '../../../../utils/fileDownload'
|
||||
import MCostSheet from '../sheets/MCostSheet'
|
||||
import { ReceiptPreviewModal } from '../../../../components/Budget/ReceiptPreviewModal'
|
||||
import { useFreezeMissingRates } from '../../../../components/Budget/useFreezeMissingRates'
|
||||
import { finalBudgetFor, finalBudgetSources, NOTE_MAX, paidByUser, readUserNote, settlementDate } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import { useCostsLedger } from '../../../../components/Budget/useCostsLedger'
|
||||
import { useSettlementForm } from '../../../../components/Budget/useSettlementForm'
|
||||
import { finalBudgetFor, finalBudgetSources, NOTE_MAX, paidByUser, readUserNote } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import { catMeta, COST_CAT_META } from '../../../../components/Budget/costsCategories'
|
||||
import CustomSelect from '../../../../components/shared/CustomSelect'
|
||||
import { CustomDatePicker } from '../../../../components/shared/CustomDateTimePicker'
|
||||
import { SYMBOLS, currenciesWith } from '../../../../components/Budget/BudgetPanel.constants'
|
||||
import { localToday } from '../../../../components/Planner/today'
|
||||
import MConfirmSheet from '../../settings/MConfirmSheet'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MChip from '../../../components/MChip'
|
||||
@@ -28,10 +22,9 @@ import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetFooter, FormSheetHeader }
|
||||
import { CountPill, TabScroller } from './tabChrome'
|
||||
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
|
||||
import {
|
||||
baseTotal, buildCostsCsv, categoryBreakdown, categoryFilterKeys, computeTotals,
|
||||
dayFilterKeys, filterBudgetItems, filterSettlements, groupLedgerByDay, isUnfinished, lineOf, memberShareOf, tint,
|
||||
type CostsCtx, type CostsSegment, type CostsSettlement, type CostsSettlementResponse,
|
||||
} from './costsModel'
|
||||
baseTotal, categoryFilterKeys, currencyOptions, dayFilterKeys, groupLedgerByDay, isUnfinished, lineOf, memberShareOf,
|
||||
paymentAmount, paymentLineOf, tint, type CostsCtx, type CostsSettlement,
|
||||
} from '../../../../components/Budget/costsModel'
|
||||
import type { BudgetParticipantFinal } from '@trek/shared'
|
||||
import type { BudgetItem, BudgetItemReceipt, TripMember } from '../../../../types'
|
||||
|
||||
@@ -51,44 +44,16 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
const { t, tripId, trip, tripMembers, budgetItems, days, toast } = planner
|
||||
const { locale } = useTranslation()
|
||||
const canEdit = planner.can('budget_edit', trip)
|
||||
const me = useAuthStore(s => s.user?.id ?? -1)
|
||||
|
||||
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
|
||||
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
|
||||
const tripCurrency = (trip?.currency || base).toUpperCase()
|
||||
// Anchored on the trip currency's quote, the one the server books with (#2525).
|
||||
const { convert, displayPerTrip } = useExchangeRates(base, tripCurrency)
|
||||
const ctx: CostsCtx = useMemo(() => ({ me, tripCurrency, displayCurrency: base, convert }), [me, tripCurrency, base, convert])
|
||||
// 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,
|
||||
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 })
|
||||
|
||||
const [settlement, setSettlement] = useState<CostsSettlementResponse | null>(null)
|
||||
// A failed settlement read leaves `settlement` null, and the final budget would
|
||||
// read that as "the trip cost nobody anything", a claim we cannot make.
|
||||
const [settlementError, setSettlementError] = useState(false)
|
||||
// Sends the browser's own figure for the display currency, as CostsPanel.tsx does.
|
||||
const loadSettlement = useCallback(() => {
|
||||
budgetApi.settlement(tripId, base, base !== tripCurrency ? displayPerTrip : null)
|
||||
.then(s => { setSettlement(s); setSettlementError(false) })
|
||||
.catch(() => setSettlementError(true))
|
||||
}, [tripId, base, tripCurrency, displayPerTrip])
|
||||
|
||||
// Mirrors CostsPanel.tsx: items reload on trip change, settlement reloads on
|
||||
// trip/base change and when the number of expenses changes; further refreshes
|
||||
// are explicit after each mutation below (add/edit/delete expense, add
|
||||
// payment), so an unrelated re-render doesn't refetch the settlement. The count
|
||||
// is for an expense saved outside this tab: a scanned receipt is reviewed in
|
||||
// the trip sheets, which reload the items but cannot reach this settlement.
|
||||
useEffect(() => {
|
||||
planner.tripActions.loadBudgetItems(tripId)
|
||||
}, [tripId, planner.tripActions])
|
||||
useEffect(() => {
|
||||
loadSettlement()
|
||||
}, [budgetItems.length, loadSettlement])
|
||||
useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted: settlement?.unconverted, onHealed: loadSettlement })
|
||||
|
||||
const [search, setSearch] = useState('')
|
||||
const [segment, setSegment] = useState<CostsSegment>('all')
|
||||
const [catFilter, setCatFilter] = useState('')
|
||||
const [dayFilter, setDayFilter] = useState('')
|
||||
const [catOpen, setCatOpen] = useState(false)
|
||||
const [dayOpen, setDayOpen] = useState(false)
|
||||
const [settleOpen, setSettleOpen] = useState(true)
|
||||
@@ -101,18 +66,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
const [confirmDelete, setConfirmDelete] = useState<BudgetItem | null>(null)
|
||||
const [previewReceipts, setPreviewReceipts] = useState<{ receipts: BudgetItemReceipt[]; initialIndex: number } | null>(null)
|
||||
|
||||
const flows = useMemo(() => settlement?.flows || [], [settlement])
|
||||
const totals = useMemo(() => computeTotals(budgetItems, flows, ctx), [budgetItems, flows, ctx])
|
||||
const filtered = useMemo(
|
||||
() => filterBudgetItems(budgetItems, { search, segment, categoryKey: catFilter, dayKey: dayFilter }, ctx),
|
||||
[budgetItems, search, segment, catFilter, dayFilter, ctx],
|
||||
)
|
||||
const filteredSettlements = useMemo(
|
||||
() => filterSettlements(settlement?.settlements || [], { search, segment, categoryKey: catFilter, dayKey: dayFilter }, me),
|
||||
[settlement, search, segment, catFilter, dayFilter, me],
|
||||
)
|
||||
const groups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements), [filtered, filteredSettlements])
|
||||
const catBreakdown = useMemo(() => categoryBreakdown(budgetItems, ctx), [budgetItems, ctx])
|
||||
const catKeys = useMemo(() => categoryFilterKeys(budgetItems), [budgetItems])
|
||||
const dayKeys = useMemo(() => dayFilterKeys(budgetItems), [budgetItems])
|
||||
|
||||
@@ -138,12 +92,6 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleExportCsv = useCallback(() => {
|
||||
const { filename, content } = buildCostsCsv(budgetItems, { base, ctx, locale, tripTitle: trip?.title, t })
|
||||
const blob = new Blob(['' + content], { type: 'text/csv;charset=utf-8;' })
|
||||
downloadBlob(blob, filename)
|
||||
}, [budgetItems, base, ctx, locale, trip?.title, t])
|
||||
|
||||
// Header intent signals (spec 03 §3.8 addExpense/csvGo) — increment-only
|
||||
// counters the shell owns; pattern mirrors useTodoList.ts's addItemSignal.
|
||||
const lastAddSignal = useRef(shell.addExpenseSignal)
|
||||
@@ -163,25 +111,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
lastCsvSignal.current = shell.exportCostsCsvSignal
|
||||
}, [shell.exportCostsCsvSignal, handleExportCsv])
|
||||
|
||||
const handleDeleteExpense = async (item: BudgetItem) => {
|
||||
try {
|
||||
await planner.tripActions.deleteBudgetItem(tripId, item.id)
|
||||
loadSettlement()
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'))
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors CostsPanel.tsx's undoSettlement: deleting the recorded transfer
|
||||
// brings the suggested flow back, so it reads as "undo" rather than delete.
|
||||
const handleUndoSettlement = async (id: number) => {
|
||||
try {
|
||||
await budgetApi.deleteSettlement(tripId, id)
|
||||
loadSettlement()
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'))
|
||||
}
|
||||
}
|
||||
const handleDeleteExpense = (item: BudgetItem) => deleteExpense(item.id)
|
||||
|
||||
const handleTogglePaid = async (itemId: number, userId: number, paid: boolean) => {
|
||||
try {
|
||||
@@ -767,11 +697,10 @@ function PaymentRow({ settlement, ctx, base, locale, t, personName, canEdit, onE
|
||||
onEdit: () => void
|
||||
onUndo: () => void
|
||||
}) {
|
||||
const cur = (settlement.currency || base).toUpperCase()
|
||||
// At the rate it was settled at, not today's (#1445), matching the desktop ledger.
|
||||
// At the rate it was settled at, not today's (#1445), as on the desktop ledger.
|
||||
// A transfer without a currency was entered in the display currency, not the trip's.
|
||||
const amount = convertBooked(settlement.amount, cur, settlement.exchange_rate, ctx.tripCurrency, ctx.convert)
|
||||
const line = convertedLine(settlement.amount, cur, settlement.exchange_rate, ctx.tripCurrency, base, amount)
|
||||
const amount = paymentAmount(settlement, ctx)
|
||||
const line = paymentLineOf(settlement, ctx, amount)
|
||||
return (
|
||||
<div className="mt-2 flex items-center gap-[6px]">
|
||||
<div className="relative min-w-0 flex-1 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card px-3 py-[12px]">
|
||||
@@ -883,8 +812,8 @@ function MemberAvatar({ name, avatarUrl, isMe, variant, size, t }: {
|
||||
}
|
||||
|
||||
/**
|
||||
* "Add/edit payment" — records or updates a manual settle-up transfer
|
||||
* (`budgetApi.createSettlement`/`updateSettlement`). No pixel spec exists for
|
||||
* "Add/edit payment": records or updates a manual settle-up transfer through
|
||||
* the same `useSettlementForm` as the desktop dialog. No pixel spec exists for
|
||||
* this form (the demo only toasts "Demo: add payment", 03-trip-tabs.md §3.8)
|
||||
* and no mobile/exported-desktop sheet covers it, so this is a small local
|
||||
* sheet built from the trip form-sheet chrome, kept to the fields the
|
||||
@@ -907,43 +836,8 @@ function AddPaymentSheet({ open, editing, onClose, tripId, base, tripCurrency, p
|
||||
t: TFn
|
||||
onSaved: () => void
|
||||
}) {
|
||||
const [fromId, setFromId] = useState(me)
|
||||
const [toId, setToId] = useState(() => people.find(p => p.id !== me)?.id ?? me)
|
||||
const [amount, setAmount] = useState('')
|
||||
const [currency, setCurrency] = useState(base)
|
||||
const [day, setDay] = useState(localToday())
|
||||
const [note, setNote] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const cur = (editing?.currency || base).toUpperCase()
|
||||
setFromId(editing?.from_user_id ?? me)
|
||||
setToId(editing?.to_user_id ?? people.find(p => p.id !== me)?.id ?? me)
|
||||
setAmount(editing ? amountToInputString(editing.amount, cur) : '')
|
||||
setCurrency(cur)
|
||||
setDay(editing ? settlementDate(editing) : localToday())
|
||||
setNote(editing?.note || '')
|
||||
setSaving(false)
|
||||
}, [open, editing, me, base, people])
|
||||
|
||||
const amt = Number.parseFloat(amount.replace(',', '.')) || 0
|
||||
const valid = amt > 0 && fromId !== toId && !!day
|
||||
|
||||
const save = async () => {
|
||||
if (!valid || saving) return
|
||||
setSaving(true)
|
||||
const data = withFallbackFx({ from_user_id: fromId, to_user_id: toId, amount: amt, currency, settled_at: day, note: note.trim() || null }, tripCurrency)
|
||||
try {
|
||||
if (editing) await budgetApi.updateSettlement(tripId, editing.id, data)
|
||||
else await budgetApi.createSettlement(tripId, data)
|
||||
onSaved()
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
const { fromId, setFromId, toId, setToId, amount, setAmount, currency, setCurrency, day, setDay, note, setNote, saving, valid, save } =
|
||||
useSettlementForm({ tripId, tripCurrency, base, people, me, editing, open, t, toast, onSaved, oneSaveAtATime: true })
|
||||
|
||||
const title = editing ? t('costs.editPayment') : t('costs.addPayment')
|
||||
|
||||
@@ -985,7 +879,7 @@ function AddPaymentSheet({ open, editing, onClose, tripId, base, tripCurrency, p
|
||||
onChange={v => setCurrency(String(v))}
|
||||
searchable
|
||||
size="sm"
|
||||
options={currenciesWith(currency).map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
|
||||
options={currencyOptions(currency)}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,362 +0,0 @@
|
||||
import type { BudgetParticipantFinal, BudgetUnconverted, CostCategory } from '@trek/shared'
|
||||
import { paidByUser, readUserNote, settlementDate, splitEqualShares } from '../../../../components/Budget/CostsPanel.helpers'
|
||||
import { catMeta, COST_CATEGORY_LIST } from '../../../../components/Budget/costsCategories'
|
||||
import { convertBooked, convertedLine, tripAmountOf } from '../../../../hooks/useExchangeRates'
|
||||
import { currencyDecimals } from '../../../../utils/formatters'
|
||||
import type { BudgetItem } from '../../../../types'
|
||||
|
||||
/**
|
||||
* Costs view-model — the real-data counterpart to the demo's `EXPS`/`CATS`
|
||||
* (spec 03 §3.10). Every function here mirrors the desktop `CostsPanel.tsx`
|
||||
* maths 1:1 (baseTotal/myPaidOf/myShareOf/isUnfinished/totals/filters/CSV) so
|
||||
* the two surfaces never disagree, decoupled from React so it stays testable.
|
||||
* Money is converted to the display/base currency via an injected `convert`
|
||||
* (from `useExchangeRates`), never computed here.
|
||||
*/
|
||||
|
||||
/** Per-render context every money computation needs — cheap to build, memoize in the caller. */
|
||||
export interface CostsCtx {
|
||||
me: number
|
||||
/** The trip's own currency — what a NULL `budget_items.currency` means. */
|
||||
tripCurrency: string
|
||||
/** The currency everything is shown in, the base `convert` converts to. */
|
||||
displayCurrency: string
|
||||
convert: (amount: number, currency: string | null | undefined) => number
|
||||
}
|
||||
|
||||
/** An expense's own currency, defaulting to the trip currency (NULL column = trip currency). */
|
||||
export function currencyOf(e: BudgetItem, ctx: CostsCtx): string {
|
||||
return (e.currency || ctx.tripCurrency).toUpperCase()
|
||||
}
|
||||
|
||||
/** An amount of this expense in the display currency, at the rate the expense was booked at. */
|
||||
export function booked(amount: number, e: BudgetItem, ctx: CostsCtx): number {
|
||||
return convertBooked(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.convert)
|
||||
}
|
||||
|
||||
/**
|
||||
* The line under an amount of this expense the list shows converted, what was entered and
|
||||
* where it went (#2525); null when there is nothing to explain. `shown` is the display
|
||||
* value printed beside it.
|
||||
*/
|
||||
export function lineOf(amount: number, e: BudgetItem, ctx: CostsCtx, shown: number) {
|
||||
return convertedLine(amount, e.currency, e.exchange_rate, ctx.tripCurrency, ctx.displayCurrency, shown)
|
||||
}
|
||||
|
||||
/** Expense total converted to the display/base currency, at its booked rate. */
|
||||
export function baseTotal(e: BudgetItem, ctx: CostsCtx): number {
|
||||
return booked(e.total_price || 0, e, ctx)
|
||||
}
|
||||
|
||||
/** How much `ctx.me` personally fronted for this expense, in the base currency. */
|
||||
export function myPaidOf(e: BudgetItem, ctx: CostsCtx): number {
|
||||
return booked(paidByUser(e, ctx.me), e, ctx)
|
||||
}
|
||||
|
||||
/** A given member's share of this expense (explicit custom amount, else equal split), base currency. */
|
||||
export function memberShareOf(e: BudgetItem, userId: number, ctx: CostsCtx): number {
|
||||
const member = (e.members || []).find(m => m.user_id === userId)
|
||||
if (!member) return 0
|
||||
if (member.amount !== null && member.amount !== undefined) {
|
||||
return booked(member.amount, e, ctx)
|
||||
}
|
||||
const shares = splitEqualShares(e.total_price || 0, e.members || [], e.id)
|
||||
return booked(shares[userId] || 0, e, ctx)
|
||||
}
|
||||
|
||||
/** `ctx.me`'s own share — the common case of {@link memberShareOf}. */
|
||||
export function myShareOf(e: BudgetItem, ctx: CostsCtx): number {
|
||||
return memberShareOf(e, ctx.me, ctx)
|
||||
}
|
||||
|
||||
/**
|
||||
* A recorded total nobody has actually paid yet — counts toward the trip total
|
||||
* but stays out of settlement. A negative total (a refund, #2176) is just as
|
||||
* unfinished until its recipient is recorded as the (negative) payer.
|
||||
*/
|
||||
export function isUnfinished(e: BudgetItem, ctx: CostsCtx): boolean {
|
||||
return baseTotal(e, ctx) !== 0 && (e.payers || []).filter(p => p.amount !== 0).length === 0
|
||||
}
|
||||
|
||||
// ── settlement (server-computed; these types describe what MCostsTab reads from it) ──
|
||||
|
||||
export interface CostsSettlementFlow {
|
||||
from: { user_id: number; username: string; avatar_url?: string | null }
|
||||
to: { user_id: number; username: string; avatar_url?: string | null }
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface CostsBalance {
|
||||
user_id: number
|
||||
username: string
|
||||
avatar_url: string | null
|
||||
balance: number
|
||||
}
|
||||
|
||||
/** A recorded settle-up transfer ("Ajouter un paiement") — history, not a suggestion like {@link CostsSettlementFlow}. */
|
||||
export interface CostsSettlement {
|
||||
id: number
|
||||
from_user_id: number
|
||||
to_user_id: number
|
||||
amount: number
|
||||
// Legacy rows predate this column (null) and are read as the display currency.
|
||||
currency?: string | null
|
||||
// The rate frozen when the transfer was settled, units of `currency` per 1 trip
|
||||
// currency (#1445). Absent, or exactly 1, on rows written before the freeze existed.
|
||||
exchange_rate?: number
|
||||
created_at?: string
|
||||
// The day the transfer actually happened; editable, unlike created_at (when it
|
||||
// was recorded). Null/absent on rows predating this field.
|
||||
settled_at?: string | null
|
||||
/** A free-text note on the payment (#2340). */
|
||||
note?: string | null
|
||||
}
|
||||
|
||||
export interface CostsSettlementResponse {
|
||||
balances: CostsBalance[]
|
||||
flows: CostsSettlementFlow[]
|
||||
settlements: CostsSettlement[]
|
||||
/** What the trip ends up costing each participant — netted server-side off the same ledger as `balances`. */
|
||||
finalBudgets: BudgetParticipantFinal[]
|
||||
/** The currency the figures are in: the display currency, or the trip's own without a quote for it. */
|
||||
currency?: string
|
||||
/** Rows no rate could convert, left out of every figure above. */
|
||||
unconverted?: BudgetUnconverted
|
||||
}
|
||||
|
||||
// ── hero / tile totals (spec §3.1-§3.3) ────────────────────────────────────
|
||||
|
||||
export interface CostsTotals {
|
||||
totalSpend: number
|
||||
myPaid: number
|
||||
myShare: number
|
||||
owe: number
|
||||
owed: number
|
||||
outstanding: number
|
||||
outstandingCount: number
|
||||
}
|
||||
|
||||
export function computeTotals(items: BudgetItem[], flows: CostsSettlementFlow[], ctx: CostsCtx): 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 + myShareOf(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))
|
||||
const outstanding = outstandingItems.reduce((a, e) => a + baseTotal(e, ctx), 0)
|
||||
return { totalSpend, myPaid, myShare, owe, owed, outstanding, outstandingCount: outstandingItems.length }
|
||||
}
|
||||
|
||||
// ── expenses list: filter + group (spec §3.6-§3.7) ─────────────────────────
|
||||
|
||||
export type CostsSegment = 'all' | 'mine' | 'owed'
|
||||
|
||||
export interface CostsFilterState {
|
||||
search: string
|
||||
segment: CostsSegment
|
||||
/** '' = all categories */
|
||||
categoryKey: string
|
||||
/** '' = all days, else the expense's own YYYY-MM-DD */
|
||||
dayKey: string
|
||||
}
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100
|
||||
|
||||
/**
|
||||
* `mine`/`owed` use the real balance, not the demo's `payer==='you'` shortcut
|
||||
* (spec 03 §3.6): `mine` = I fronted money on it, `owed` = I'm net owed on it.
|
||||
*/
|
||||
export function filterBudgetItems(items: BudgetItem[], f: CostsFilterState, ctx: CostsCtx): BudgetItem[] {
|
||||
let list = items.slice()
|
||||
if (f.segment === 'mine') list = list.filter(e => myPaidOf(e, ctx) > 0)
|
||||
if (f.segment === 'owed') list = list.filter(e => round2(myPaidOf(e, ctx) - myShareOf(e, ctx)) > 0)
|
||||
if (f.categoryKey) list = list.filter(e => catMeta(e.category).key === f.categoryKey)
|
||||
if (f.dayKey) list = list.filter(e => (e.expense_date || '') === f.dayKey)
|
||||
const q = f.search.trim().toLowerCase()
|
||||
if (q) list = list.filter(e => e.name.toLowerCase().includes(q))
|
||||
return list
|
||||
}
|
||||
|
||||
export interface CostsDayGroup {
|
||||
/** '' = no date (spec's "NO DATE" group) */
|
||||
dateKey: string
|
||||
items: BudgetItem[]
|
||||
}
|
||||
|
||||
/** Groups by `expense_date`, newest first, the no-date bucket sinking to the end (spec §3.7). */
|
||||
export function groupByDay(items: BudgetItem[]): CostsDayGroup[] {
|
||||
const byDate = new Map<string, BudgetItem[]>()
|
||||
for (const e of items) {
|
||||
const key = e.expense_date || ''
|
||||
const bucket = byDate.get(key)
|
||||
if (bucket) bucket.push(e)
|
||||
else byDate.set(key, [e])
|
||||
}
|
||||
const keys = Array.from(byDate.keys()).sort((a, b) => {
|
||||
if (a === b) return 0
|
||||
if (a === '') return 1
|
||||
if (b === '') return -1
|
||||
return b.localeCompare(a)
|
||||
})
|
||||
return keys.map(dateKey => ({ dateKey, items: byDate.get(dateKey) as BudgetItem[] }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Settlements ("payments") shown inline in the ledger, mirroring the desktop
|
||||
* `CostsPanel.tsx`'s `filteredSettlements`: they have no name/category, so a
|
||||
* text or category filter hides them; "owed" excludes them; "mine" keeps only
|
||||
* transfers the current user is part of.
|
||||
*/
|
||||
export function filterSettlements(settlements: CostsSettlement[], f: CostsFilterState, me: number): CostsSettlement[] {
|
||||
if (f.search.trim() || f.categoryKey) return []
|
||||
if (f.segment === 'owed') return []
|
||||
let list = settlements.slice()
|
||||
if (f.segment === 'mine') list = list.filter(s => s.from_user_id === me || s.to_user_id === me)
|
||||
if (f.dayKey) list = list.filter(s => settlementDate(s) === f.dayKey)
|
||||
return list
|
||||
}
|
||||
|
||||
export type CostsLedgerEntry =
|
||||
| { kind: 'expense'; date: string; item: BudgetItem }
|
||||
| { kind: 'payment'; date: string; settlement: CostsSettlement }
|
||||
|
||||
export interface CostsLedgerDayGroup {
|
||||
/** '' = no date (spec's "NO DATE" group) */
|
||||
dateKey: string
|
||||
entries: CostsLedgerEntry[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link groupByDay}, but also folds in settlement payments (see
|
||||
* {@link filterSettlements}) as their own ledger entries, keyed by
|
||||
* {@link settlementDate} — the mobile counterpart to desktop's unified
|
||||
* `LedgerEntry` grouping, so a payment shows up even on a day with no expense.
|
||||
*/
|
||||
export function groupLedgerByDay(items: BudgetItem[], settlements: CostsSettlement[]): CostsLedgerDayGroup[] {
|
||||
const entries: CostsLedgerEntry[] = [
|
||||
...items.map(item => ({ kind: 'expense' as const, date: item.expense_date || '', item })),
|
||||
...settlements.map(settlement => ({ kind: 'payment' as const, date: settlementDate(settlement), settlement })),
|
||||
]
|
||||
const byDate = new Map<string, CostsLedgerEntry[]>()
|
||||
for (const en of entries) {
|
||||
const bucket = byDate.get(en.date)
|
||||
if (bucket) bucket.push(en)
|
||||
else byDate.set(en.date, [en])
|
||||
}
|
||||
const keys = Array.from(byDate.keys()).sort((a, b) => {
|
||||
if (a === b) return 0
|
||||
if (a === '') return 1
|
||||
if (b === '') return -1
|
||||
return b.localeCompare(a)
|
||||
})
|
||||
return keys.map(dateKey => ({ dateKey, entries: byDate.get(dateKey) as CostsLedgerEntry[] }))
|
||||
}
|
||||
|
||||
/** Categories present among `items`, canonical order — the dropdown only lists categories in use (spec §3.6). */
|
||||
export function categoryFilterKeys(items: BudgetItem[]): CostCategory[] {
|
||||
const present = new Set(items.map(e => catMeta(e.category).key))
|
||||
return COST_CATEGORY_LIST.map(c => c.key).filter(k => present.has(k))
|
||||
}
|
||||
|
||||
/** Distinct expense dates, ascending (spec §3.6: "Tage mit Ausgaben aufsteigend"). */
|
||||
export function dayFilterKeys(items: BudgetItem[]): string[] {
|
||||
const dates = new Set(items.map(e => e.expense_date).filter((d): d is string => Boolean(d)))
|
||||
return Array.from(dates).sort((a, b) => a.localeCompare(b))
|
||||
}
|
||||
|
||||
// ── by-category breakdown (spec §3.5) ───────────────────────────────────────
|
||||
|
||||
export interface CostsCategoryBar {
|
||||
key: CostCategory
|
||||
amount: number
|
||||
/** 0-100, relative to the largest category (not the grand total) — spec §3.5. */
|
||||
widthPct: number
|
||||
}
|
||||
|
||||
export function categoryBreakdown(items: BudgetItem[], ctx: CostsCtx): 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
|
||||
// CSS width would be dropped and render as a full bar.
|
||||
const totals = new Map<CostCategory, number>()
|
||||
for (const e of items) {
|
||||
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 }))
|
||||
.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 }))
|
||||
}
|
||||
|
||||
// ── presentation helpers ─────────────────────────────────────────────────
|
||||
|
||||
/** Category colour at a fixed alpha — the expense card's border tint (spec §3.10: "brC"). */
|
||||
export function tint(hex: string, alpha: number): string {
|
||||
const clean = hex.replace('#', '')
|
||||
const r = Number.parseInt(clean.slice(0, 2), 16)
|
||||
const g = Number.parseInt(clean.slice(2, 4), 16)
|
||||
const b = Number.parseInt(clean.slice(4, 6), 16)
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`
|
||||
}
|
||||
|
||||
// ── CSV export (spec §3.8 `csvGo`; string-building only — the caller turns this into a download) ──
|
||||
|
||||
export interface CsvBuildOptions {
|
||||
base: string
|
||||
ctx: CostsCtx
|
||||
locale: string
|
||||
tripTitle?: string | null
|
||||
t: (key: string) => string
|
||||
}
|
||||
|
||||
/** Ports `CostsPanel.tsx`'s `handleExportCsv` row-building 1:1; the Blob/download is a DOM concern left to the caller. */
|
||||
export function buildCostsCsv(items: BudgetItem[], opts: CsvBuildOptions): { filename: string; content: string } {
|
||||
const sep = ';'
|
||||
// A cell starting with =, +, -, @, TAB or CR is evaluated as a formula by Excel
|
||||
// and Sheets, and the name/note columns are free text any trip member can write.
|
||||
// Mirrors the same guard in `CostsPanel.tsx`'s exporter.
|
||||
const esc = (v: unknown) => {
|
||||
let s = String(v ?? '')
|
||||
if (/^[=+\-@\t\r]/.test(s)) s = "'" + s
|
||||
return s.includes(sep) || s.includes('"') || s.includes('\n') ? '"' + s.replace(/"/g, '""') + '"' : s
|
||||
}
|
||||
const fmtDate = (iso: string) => {
|
||||
if (!iso) return ''
|
||||
try {
|
||||
return new Date(iso + 'T00:00:00Z').toLocaleDateString(opts.locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' })
|
||||
} catch {
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
// Read in another currency than the trip's, what each row counts as in the trip currency
|
||||
// too, the figure every sum is built from (#2525). Same columns as the desktop export.
|
||||
const trip = opts.ctx.tripCurrency.toUpperCase()
|
||||
const tripCol = trip !== opts.base.toUpperCase()
|
||||
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', ...(tripCol ? [`Amount (${trip})`] : []), `Amount (${opts.base})`, 'Note']
|
||||
const rows = [header.join(sep)]
|
||||
const sorted = items.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || ''))
|
||||
for (const e of sorted) {
|
||||
const cur = currencyOf(e, opts.ctx)
|
||||
const note = readUserNote(e)
|
||||
const inTrip = tripAmountOf(e.total_price || 0, e.currency, e.exchange_rate, trip, opts.ctx.convert)
|
||||
rows.push(
|
||||
[
|
||||
esc(fmtDate(e.expense_date || '')),
|
||||
esc(e.name),
|
||||
esc(opts.t(catMeta(e.category).labelKey)),
|
||||
(e.total_price || 0).toFixed(currencyDecimals(cur)),
|
||||
cur,
|
||||
...(tripCol ? [inTrip.toFixed(currencyDecimals(trip))] : []),
|
||||
baseTotal(e, opts.ctx).toFixed(currencyDecimals(opts.base)),
|
||||
esc(note),
|
||||
].join(sep),
|
||||
)
|
||||
}
|
||||
|
||||
const safeName = (opts.tripTitle || 'trip').replace(/[^a-zA-Z0-9À-ɏ _-]/g, '').trim()
|
||||
return { filename: `costs-${safeName}.csv`, content: rows.join('\r\n') }
|
||||
}
|
||||
Reference in New Issue
Block a user