import { useEffect, useState, type FormEvent } from 'react' import { finance } from '@/api/client' import type { Account } from '@/types/api' import { PageHeader } from '@/components/PageHeader' import { Loading } from '@/components/Loading' import { ErrorBox } from '@/components/ErrorBox' import { DataTable, type Column } from '@/components/DataTable' const ACCOUNT_TYPES = ['ASSET', 'LIABILITY', 'EQUITY', 'REVENUE', 'EXPENSE'] as const export function AccountsPage() { const [rows, setRows] = useState([]) const [error, setError] = useState(null) const [loading, setLoading] = useState(true) const [showCreate, setShowCreate] = useState(false) const [code, setCode] = useState('') const [name, setName] = useState('') const [accountType, setAccountType] = useState('ASSET') const [creating, setCreating] = useState(false) const load = () => { finance .listAccounts() .then((rs) => setRows([...rs].sort((a, b) => a.code.localeCompare(b.code)))) .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e)))) .finally(() => setLoading(false)) } useEffect(() => { load() }, []) // eslint-disable-line react-hooks/exhaustive-deps const onCreate = async (e: FormEvent) => { e.preventDefault() setCreating(true) setError(null) try { await finance.createAccount({ code, name, accountType }) setCode('') setName('') setShowCreate(false) load() } catch (err: unknown) { setError(err instanceof Error ? err : new Error(String(err))) } finally { setCreating(false) } } const columns: Column[] = [ { header: 'Code', key: 'code', render: (r) => {r.code} }, { header: 'Name', key: 'name' }, { header: 'Type', key: 'accountType' }, { header: 'Description', key: 'description', render: (r) => r.description ?? '—' }, ] return (
setShowCreate(!showCreate)}> {showCreate ? 'Cancel' : '+ New Account'} } /> {showCreate && (
setCode(e.target.value)} placeholder="1300" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
setName(e.target.value)} placeholder="Prepaid expenses" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
)} {loading && } {error && } {!loading && !error && }
) }