import { useEffect, useMemo, useState } from 'react' import { listAccounts, listAllTransactions, type Account, type Transaction, } from '../db' import { formatCents, initialsOf, signedAmount } from '../format' import { navigate } from '../router' import { Header, Screen } from '../components/Screen' export function HomePage(props: { user: string onLogout: () => void reloadKey: number }) { const [accounts, setAccounts] = useState(null) const [txns, setTxns] = useState([]) useEffect(() => { let alive = true Promise.all([listAccounts(), listAllTransactions()]).then(([a, t]) => { if (!alive) return setAccounts(a) setTxns(t) }) return () => { alive = false } }, [props.reloadKey]) const balanceByAccount = useMemo(() => { const m = new Map() for (const t of txns) { m.set(t.accountId, (m.get(t.accountId) ?? 0) + signedAmount(t)) } return m }, [txns]) const totalBalance = useMemo(() => { let sum = 0 for (const v of balanceByAccount.values()) sum += v return sum }, [balanceByAccount]) return ( } /> } footer={ <>
Total balance 0 ? ' credit' : totalBalance < 0 ? ' debit' : '') } > {formatCents(totalBalance)}
{accounts?.length ?? 0} account {(accounts?.length ?? 0) === 1 ? '' : 's'}
} > {accounts === null ? (
Loading…
) : accounts.length === 0 ? (
No accounts yet
Create your first account to start tracking transactions.
) : (
{accounts.map((a) => { const bal = balanceByAccount.get(a.id) ?? 0 return ( ) })}
)}
) } function countTxns(all: Transaction[], accountId: string): number { let n = 0 for (const t of all) if (t.accountId === accountId) n++ return n }