initial code commit

This commit is contained in:
Deven Thiel 2026-03-04 21:21:59 -05:00
commit 27bb45f7df
56 changed files with 15106 additions and 0 deletions

View file

@ -0,0 +1,171 @@
/**
* Login / Register screen gates the whole app.
* Local auth (password encryption key) + optional cloud auth.
*/
import { useState } from 'react';
import { useAppStore } from '@/store/appStore';
export function LoginScreen() {
const login = useAppStore((s) => s.login);
const register = useAppStore((s) => s.register);
const setCloudAuth = useAppStore((s) => s.setCloudAuth);
const [mode, setMode] = useState<'login' | 'register'>('login');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Cloud auth sub-panel
const [showCloud, setShowCloud] = useState(false);
const [cloudUrl, setCloudUrl] = useState('');
const [cloudEmail, setCloudEmail] = useState('');
const [cloudPass, setCloudPass] = useState('');
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (mode === 'register' && password !== confirm) {
setError('Passwords do not match');
return;
}
if (password.length < 8) {
setError('Password must be at least 8 characters');
return;
}
setBusy(true);
try {
if (mode === 'register') await register(username, password);
else await login(username, password);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
const cloudEmailLogin = async (isSignup: boolean) => {
if (!cloudUrl || !cloudEmail || !cloudPass) return;
setBusy(true);
setError(null);
try {
const res = await fetch(`${cloudUrl}/api/auth/${isSignup ? 'signup' : 'login'}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: cloudEmail, password: cloudPass }),
});
if (!res.ok) throw new Error((await res.json()).error ?? 'Cloud auth failed');
const { token } = await res.json();
setCloudAuth(token, cloudEmail, 'email');
alert('Cloud authenticated. Now enter a local encryption password above.');
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
const cloudGoogleLogin = () => {
if (!cloudUrl) {
setError('Enter cloud API URL first');
return;
}
// Open OAuth popup — server redirects back with token in query
const w = window.open(`${cloudUrl}/api/auth/google`, 'oauth', 'width=500,height=600');
const handler = (e: MessageEvent) => {
if (e.data?.type === 't99-oauth' && e.data.token) {
setCloudAuth(e.data.token, e.data.email, 'google');
window.removeEventListener('message', handler);
w?.close();
}
};
window.addEventListener('message', handler);
};
return (
<div className="flex items-center" style={{ justifyContent: 'center', minHeight: '100vh', padding: 20 }}>
<div className="card" style={{ width: '100%', maxWidth: 420 }}>
<h1 style={{ fontSize: 24, marginBottom: 4, fontFamily: 'var(--font-display)', color: 'var(--accent)' }}>
ten99timecard
</h1>
<p className="text-muted text-sm mb-4">
Income tracking & quarterly tax planning for 1099 workers
</p>
<div className="btn-group mb-4" style={{ width: '100%' }}>
<button className={`btn ${mode === 'login' ? 'active' : ''}`} style={{ flex: 1 }} onClick={() => setMode('login')}>
Unlock
</button>
<button className={`btn ${mode === 'register' ? 'active' : ''}`} style={{ flex: 1 }} onClick={() => setMode('register')}>
Create Vault
</button>
</div>
<form onSubmit={submit} className="flex-col gap-3">
<div className="field">
<label>Username</label>
<input className="input" value={username} onChange={(e) => setUsername(e.target.value)} required autoComplete="username" />
</div>
<div className="field">
<label>
{mode === 'register' ? 'Encryption password' : 'Password'}
</label>
<input type="password" className="input" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete={mode === 'register' ? 'new-password' : 'current-password'} />
</div>
{mode === 'register' && (
<>
<div className="field">
<label>Confirm password</label>
<input type="password" className="input" value={confirm} onChange={(e) => setConfirm(e.target.value)} required />
</div>
<p className="text-sm text-muted">
This password encrypts your data. <strong>It cannot be recovered.</strong>
</p>
</>
)}
{error && <div className="text-danger text-sm">{error}</div>}
<button type="submit" className="btn btn-primary" disabled={busy}>
{busy ? 'Working…' : mode === 'register' ? 'Create & Unlock' : 'Unlock'}
</button>
</form>
{/* Cloud auth collapsible */}
<div className="mt-4">
<button className="btn btn-sm btn-ghost" onClick={() => setShowCloud(!showCloud)}>
{showCloud ? '▾' : '▸'} Optional: connect to cloud storage
</button>
{showCloud && (
<div className="flex-col gap-2 mt-2" style={{ padding: 12, background: 'var(--bg-elev-2)', borderRadius: 6 }}>
<div className="field">
<label>Server URL</label>
<input className="input" value={cloudUrl} onChange={(e) => setCloudUrl(e.target.value)} placeholder="https://your-server.example.com" />
</div>
<div className="field-row">
<div className="field">
<label>Email</label>
<input type="email" className="input" value={cloudEmail} onChange={(e) => setCloudEmail(e.target.value)} />
</div>
<div className="field">
<label>Cloud password</label>
<input type="password" className="input" value={cloudPass} onChange={(e) => setCloudPass(e.target.value)} />
</div>
</div>
<div className="flex gap-2">
<button className="btn btn-sm" onClick={() => cloudEmailLogin(false)} disabled={busy}>Sign in</button>
<button className="btn btn-sm" onClick={() => cloudEmailLogin(true)} disabled={busy}>Sign up</button>
<button className="btn btn-sm" onClick={cloudGoogleLogin} disabled={busy}>Sign in with Google</button>
</div>
<p className="text-sm text-muted">
Cloud auth identifies WHICH blob to load. Your encryption password above is still what protects the data.
</p>
</div>
)}
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,300 @@
/**
* Configurable chart panel. Renders one ChartConfig as a Recharts chart,
* with inline controls for type, metrics, granularity, and axis ranges.
*/
import { useMemo, useState } from 'react';
import {
ResponsiveContainer,
LineChart, Line,
BarChart, Bar,
AreaChart, Area,
PieChart, Pie, Cell,
XAxis, YAxis, Tooltip, Legend, CartesianGrid,
} from 'recharts';
import type { ChartConfig, ChartMetric, ChartType, ChartGranularity } from '@/types';
import { buildChartSeries } from '@/lib/stats/aggregate';
import { useAppStore } from '@/store/appStore';
import { fmtMoneyShort } from '@/lib/format';
const METRIC_LABELS: Record<ChartMetric, string> = {
workValue: 'Work Value',
payments: 'Payments',
expenses: 'Expenses',
netIncome: 'Net Income',
cumulativePayments: 'Cumulative Payments',
cumulativeNet: 'Cumulative Net',
};
const CHART_COLORS = [
'var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)',
'var(--chart-4)', 'var(--chart-5)',
];
interface Props {
config: ChartConfig;
onChange: (patch: Partial<ChartConfig>) => void;
onRemove?: () => void;
}
export function ChartPanel({ config, onChange, onRemove }: Props) {
const work = useAppStore((s) => s.data.workEntries);
const payments = useAppStore((s) => s.data.payments);
const expenses = useAppStore((s) => s.data.expenses);
const [showControls, setShowControls] = useState(false);
const data = useMemo(
() =>
buildChartSeries(
work,
payments,
expenses,
config.metrics,
config.granularity,
config.rangeStart,
config.rangeEnd,
),
[work, payments, expenses, config],
);
const yDomain: [number | 'auto', number | 'auto'] = [
config.yMin ?? 'auto',
config.yMax ?? 'auto',
];
const toggleMetric = (m: ChartMetric) => {
const has = config.metrics.includes(m);
const next = has
? config.metrics.filter((x) => x !== m)
: [...config.metrics, m];
if (next.length > 0) onChange({ metrics: next });
};
return (
<div className="card" style={{ flex: 1, minHeight: 300, display: 'flex', flexDirection: 'column' }}>
<div className="card-header">
<input
className="input input-inline"
style={{ border: 'none', fontWeight: 600, fontSize: 14, background: 'transparent', width: '60%' }}
value={config.title ?? ''}
placeholder="Chart title"
onChange={(e) => onChange({ title: e.target.value })}
/>
<div className="flex gap-1">
<button className="btn btn-sm btn-ghost" onClick={() => setShowControls(!showControls)} title="Configure">
</button>
{onRemove && (
<button className="btn btn-sm btn-ghost text-danger" onClick={onRemove} title="Remove chart">
</button>
)}
</div>
</div>
{showControls && (
<div className="flex-col gap-2 mb-4" style={{ padding: 12, background: 'var(--bg-elev-2)', borderRadius: 'var(--radius-sm)' }}>
{/* Chart type */}
<div className="flex items-center gap-2">
<span className="text-sm text-muted" style={{ width: 80 }}>Type</span>
<div className="btn-group">
{(['line', 'bar', 'area', 'pie'] as ChartType[]).map((t) => (
<button
key={t}
className={`btn btn-sm ${config.type === t ? 'active' : ''}`}
onClick={() => onChange({ type: t })}
>
{t}
</button>
))}
</div>
</div>
{/* Granularity */}
<div className="flex items-center gap-2">
<span className="text-sm text-muted" style={{ width: 80 }}>Grain</span>
<div className="btn-group">
{(['day', 'week', 'month', 'year'] as ChartGranularity[]).map((g) => (
<button
key={g}
className={`btn btn-sm ${config.granularity === g ? 'active' : ''}`}
onClick={() => onChange({ granularity: g })}
>
{g}
</button>
))}
</div>
</div>
{/* Metrics */}
<div className="flex items-center gap-2" style={{ flexWrap: 'wrap' }}>
<span className="text-sm text-muted" style={{ width: 80 }}>Data</span>
{(Object.keys(METRIC_LABELS) as ChartMetric[]).map((m) => (
<label key={m} className="checkbox text-sm">
<input
type="checkbox"
checked={config.metrics.includes(m)}
onChange={() => toggleMetric(m)}
/>
{METRIC_LABELS[m]}
</label>
))}
</div>
{/* X range */}
<div className="flex items-center gap-2">
<span className="text-sm text-muted" style={{ width: 80 }}>X range</span>
<input
type="date"
className="input input-inline"
style={{ width: 140 }}
value={config.rangeStart ?? ''}
onChange={(e) => onChange({ rangeStart: e.target.value || null })}
/>
<span className="text-muted">to</span>
<input
type="date"
className="input input-inline"
style={{ width: 140 }}
value={config.rangeEnd ?? ''}
onChange={(e) => onChange({ rangeEnd: e.target.value || null })}
/>
</div>
{/* Y range */}
<div className="flex items-center gap-2">
<span className="text-sm text-muted" style={{ width: 80 }}>Y range</span>
<input
type="number"
className="input input-inline"
style={{ width: 100 }}
placeholder="auto"
value={config.yMin ?? ''}
onChange={(e) => onChange({ yMin: e.target.value ? Number(e.target.value) : null })}
/>
<span className="text-muted">to</span>
<input
type="number"
className="input input-inline"
style={{ width: 100 }}
placeholder="auto"
value={config.yMax ?? ''}
onChange={(e) => onChange({ yMax: e.target.value ? Number(e.target.value) : null })}
/>
</div>
</div>
)}
{/* Chart render */}
<div style={{ flex: 1, minHeight: 200 }}>
{data.length === 0 ? (
<div className="flex items-center justify-between full-height text-muted" style={{ justifyContent: 'center' }}>
No data to display
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
{renderChart(config, data, yDomain)}
</ResponsiveContainer>
)}
</div>
</div>
);
}
function renderChart(
config: ChartConfig,
data: ReturnType<typeof buildChartSeries>,
yDomain: [number | 'auto', number | 'auto'],
) {
const common = {
data,
margin: { top: 5, right: 10, bottom: 5, left: 0 },
};
const axes = (
<>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
<XAxis dataKey="label" stroke="var(--fg-muted)" fontSize={11} />
<YAxis
stroke="var(--fg-muted)"
fontSize={11}
domain={yDomain}
tickFormatter={(v) => fmtMoneyShort(v)}
/>
<Tooltip
contentStyle={{
background: 'var(--bg-elev)',
border: '1px solid var(--border)',
borderRadius: 'var(--radius-sm)',
}}
formatter={(v: number) => fmtMoneyShort(v)}
/>
<Legend wrapperStyle={{ fontSize: 12 }} />
</>
);
switch (config.type) {
case 'line':
return (
<LineChart {...common}>
{axes}
{config.metrics.map((m, i) => (
<Line
key={m}
type="monotone"
dataKey={m}
name={METRIC_LABELS[m]}
stroke={CHART_COLORS[i % CHART_COLORS.length]}
strokeWidth={2}
dot={false}
/>
))}
</LineChart>
);
case 'bar':
return (
<BarChart {...common}>
{axes}
{config.metrics.map((m, i) => (
<Bar key={m} dataKey={m} name={METRIC_LABELS[m]} fill={CHART_COLORS[i % CHART_COLORS.length]} />
))}
</BarChart>
);
case 'area':
return (
<AreaChart {...common}>
{axes}
{config.metrics.map((m, i) => (
<Area
key={m}
type="monotone"
dataKey={m}
name={METRIC_LABELS[m]}
stroke={CHART_COLORS[i % CHART_COLORS.length]}
fill={CHART_COLORS[i % CHART_COLORS.length]}
fillOpacity={0.3}
/>
))}
</AreaChart>
);
case 'pie': {
// Pie: sum each metric over the range
const totals = config.metrics.map((m) => ({
name: METRIC_LABELS[m],
value: data.reduce((s, d) => s + (Number(d[m]) || 0), 0),
}));
return (
<PieChart>
<Pie data={totals} dataKey="value" nameKey="name" outerRadius="80%" label>
{totals.map((_, i) => (
<Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />
))}
</Pie>
<Tooltip formatter={(v: number) => fmtMoneyShort(v)} />
<Legend wrapperStyle={{ fontSize: 12 }} />
</PieChart>
);
}
}
}

View file

@ -0,0 +1,30 @@
/**
* Right-side chart column used on data pages.
* Shows the user's configured charts + an "Add chart" button.
*/
import { useAppStore } from '@/store/appStore';
import { ChartPanel } from './ChartPanel';
export function ChartSidebar() {
const charts = useAppStore((s) => s.data.dashboard.charts);
const addChart = useAppStore((s) => s.addChart);
const updateChart = useAppStore((s) => s.updateChart);
const removeChart = useAppStore((s) => s.removeChart);
return (
<>
{charts.map((c) => (
<ChartPanel
key={c.id}
config={c}
onChange={(patch) => updateChart(c.id, patch)}
onRemove={charts.length > 1 ? () => removeChart(c.id) : undefined}
/>
))}
<button className="btn" onClick={() => addChart()}>
+ Add chart
</button>
</>
);
}

View file

@ -0,0 +1,72 @@
import { useEffect } from 'react';
interface Props {
open: boolean;
title: string;
onClose: () => void;
children: React.ReactNode;
footer?: React.ReactNode;
}
export function Modal({ open, title, onClose, children, footer }: Props) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open, onClose]);
if (!open) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal" onClick={(e) => e.stopPropagation()}>
<h3 className="modal-title">{title}</h3>
{children}
{footer && <div className="modal-footer">{footer}</div>}
</div>
</div>
);
}
/** Confirmation dialog with safe cancel default */
export function ConfirmDialog({
open,
title,
message,
confirmLabel = 'Confirm',
danger = false,
onConfirm,
onCancel,
}: {
open: boolean;
title: string;
message: string;
confirmLabel?: string;
danger?: boolean;
onConfirm: () => void;
onCancel: () => void;
}) {
return (
<Modal
open={open}
title={title}
onClose={onCancel}
footer={
<>
<button className="btn" onClick={onCancel}>
Cancel
</button>
<button
className={danger ? 'btn btn-danger' : 'btn btn-primary'}
onClick={onConfirm}
>
{confirmLabel}
</button>
</>
}
>
<p>{message}</p>
</Modal>
);
}

View file

@ -0,0 +1,234 @@
/**
* Reusable add/edit entry form. Supports flat-amount OR hours×rate input.
*/
import { useState } from 'react';
import type { WorkEntry, Payment, Expense } from '@/types';
import { todayISO } from '@/lib/format';
// ─── Work Entry ──────────────────────────────────────────────────────────────
type WorkDraft = Omit<WorkEntry, 'id' | 'createdAt' | 'updatedAt'>;
export function WorkEntryForm({
initial,
defaultRate,
onSubmit,
onCancel,
}: {
initial?: Partial<WorkDraft>;
defaultRate: number;
onSubmit: (d: WorkDraft) => void;
onCancel: () => void;
}) {
const [mode, setMode] = useState<'amount' | 'time'>(
initial?.hours != null ? 'time' : 'amount',
);
const [date, setDate] = useState(initial?.date ?? todayISO());
const [desc, setDesc] = useState(initial?.description ?? '');
const [amount, setAmount] = useState(initial?.amount?.toString() ?? '');
const [hours, setHours] = useState(initial?.hours?.toString() ?? '');
const [rate, setRate] = useState(initial?.rate?.toString() ?? String(defaultRate));
const [client, setClient] = useState(initial?.client ?? '');
const computedValue =
mode === 'amount'
? parseFloat(amount) || 0
: (parseFloat(hours) || 0) * (parseFloat(rate) || 0);
const submit = (e: React.FormEvent) => {
e.preventDefault();
const base: WorkDraft = { date, description: desc, client: client || undefined };
if (mode === 'amount') base.amount = parseFloat(amount) || 0;
else {
base.hours = parseFloat(hours) || 0;
base.rate = parseFloat(rate) || 0;
}
onSubmit(base);
};
return (
<form onSubmit={submit} className="flex-col gap-3">
<div className="field-row">
<div className="field">
<label>Date</label>
<input type="date" className="input" value={date} onChange={(e) => setDate(e.target.value)} required />
</div>
<div className="field">
<label>Client</label>
<input className="input" value={client} onChange={(e) => setClient(e.target.value)} placeholder="optional" />
</div>
</div>
<div className="field">
<label>Description</label>
<input className="input" value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="What did you work on?" required />
</div>
<div className="btn-group">
<button type="button" className={`btn btn-sm ${mode === 'amount' ? 'active' : ''}`} onClick={() => setMode('amount')}>
$ Flat amount
</button>
<button type="button" className={`btn btn-sm ${mode === 'time' ? 'active' : ''}`} onClick={() => setMode('time')}>
Time × rate
</button>
</div>
{mode === 'amount' ? (
<div className="field">
<label>Amount ($)</label>
<input type="number" step="0.01" className="input" value={amount} onChange={(e) => setAmount(e.target.value)} required />
</div>
) : (
<div className="field-row">
<div className="field">
<label>Hours</label>
<input type="number" step="0.01" className="input" value={hours} onChange={(e) => setHours(e.target.value)} required />
</div>
<div className="field">
<label>Rate ($/hr)</label>
<input type="number" step="0.01" className="input" value={rate} onChange={(e) => setRate(e.target.value)} required />
</div>
</div>
)}
<div className="text-muted text-sm">Value: <span className="mono">${computedValue.toFixed(2)}</span></div>
<div className="modal-footer">
<button type="button" className="btn" onClick={onCancel}>Cancel</button>
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
);
}
// ─── Payment ─────────────────────────────────────────────────────────────────
type PaymentDraft = Omit<Payment, 'id' | 'createdAt' | 'updatedAt'>;
export function PaymentForm({
initial,
onSubmit,
onCancel,
}: {
initial?: Partial<PaymentDraft>;
onSubmit: (d: PaymentDraft) => void;
onCancel: () => void;
}) {
const [date, setDate] = useState(initial?.date ?? todayISO());
const [amount, setAmount] = useState(initial?.amount?.toString() ?? '');
const [payer, setPayer] = useState(initial?.payer ?? '');
const [form, setForm] = useState<Payment['form']>(initial?.form ?? '1099-NEC');
const [notes, setNotes] = useState(initial?.notes ?? '');
const submit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit({ date, amount: parseFloat(amount) || 0, payer, form, notes: notes || undefined });
};
return (
<form onSubmit={submit} className="flex-col gap-3">
<div className="field-row">
<div className="field">
<label>Date received</label>
<input type="date" className="input" value={date} onChange={(e) => setDate(e.target.value)} required />
</div>
<div className="field">
<label>Amount ($)</label>
<input type="number" step="0.01" className="input" value={amount} onChange={(e) => setAmount(e.target.value)} required />
</div>
</div>
<div className="field-row">
<div className="field">
<label>Payer</label>
<input className="input" value={payer} onChange={(e) => setPayer(e.target.value)} required />
</div>
<div className="field">
<label>Form</label>
<select className="select" value={form} onChange={(e) => setForm(e.target.value as Payment['form'])}>
<option value="1099-NEC">1099-NEC</option>
<option value="1099-K">1099-K</option>
<option value="1099-MISC">1099-MISC</option>
<option value="direct">Direct / no form</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div className="field">
<label>Notes</label>
<input className="input" value={notes} onChange={(e) => setNotes(e.target.value)} />
</div>
<div className="modal-footer">
<button type="button" className="btn" onClick={onCancel}>Cancel</button>
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
);
}
// ─── Expense ─────────────────────────────────────────────────────────────────
type ExpenseDraft = Omit<Expense, 'id' | 'createdAt' | 'updatedAt'>;
export function ExpenseForm({
initial,
onSubmit,
onCancel,
}: {
initial?: Partial<ExpenseDraft>;
onSubmit: (d: ExpenseDraft) => void;
onCancel: () => void;
}) {
const [date, setDate] = useState(initial?.date ?? todayISO());
const [amount, setAmount] = useState(initial?.amount?.toString() ?? '');
const [desc, setDesc] = useState(initial?.description ?? '');
const [deductible, setDeductible] = useState(initial?.deductible ?? true);
const [category, setCategory] = useState(initial?.category ?? '');
const submit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit({
date,
amount: parseFloat(amount) || 0,
description: desc,
deductible,
category: category || undefined,
});
};
return (
<form onSubmit={submit} className="flex-col gap-3">
<div className="field-row">
<div className="field">
<label>Date</label>
<input type="date" className="input" value={date} onChange={(e) => setDate(e.target.value)} required />
</div>
<div className="field">
<label>Amount ($)</label>
<input type="number" step="0.01" className="input" value={amount} onChange={(e) => setAmount(e.target.value)} required />
</div>
</div>
<div className="field">
<label>Description</label>
<input className="input" value={desc} onChange={(e) => setDesc(e.target.value)} required />
</div>
<div className="field-row">
<div className="field">
<label>Category</label>
<input className="input" value={category} onChange={(e) => setCategory(e.target.value)} placeholder="optional" />
</div>
<div className="field">
<label>&nbsp;</label>
<label className="checkbox">
<input type="checkbox" checked={deductible} onChange={(e) => setDeductible(e.target.checked)} />
Tax deductible
</label>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn" onClick={onCancel}>Cancel</button>
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
);
}

View file

@ -0,0 +1,179 @@
/**
* Hierarchical expandable spreadsheet.
* Year Month Day Item, with per-row toggles AND global
* "expand to level" buttons.
*/
import { useState, useMemo, useCallback } from 'react';
import clsx from 'clsx';
import type { HierNode } from '@/types';
import { fmtMoney } from '@/lib/format';
export type ExpandLevel = 'year' | 'month' | 'day' | 'item';
interface Props {
nodes: HierNode[];
/** Called when user clicks an item-level row's edit/delete */
onEdit?: (node: HierNode) => void;
onDelete?: (node: HierNode) => void;
/** Label for the value column (e.g. "Earned", "Paid", "Spent") */
valueLabel: string;
}
const LEVEL_ORDER: Record<ExpandLevel, number> = {
year: 0,
month: 1,
day: 2,
item: 3,
};
export function HierSpreadsheet({ nodes, onEdit, onDelete, valueLabel }: Props) {
// Expanded keys set. We use a Set so individual rows can be toggled
// independently of the global expand-level buttons.
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const toggle = useCallback((key: string) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, []);
/** Expand all nodes up to and including the given level */
const expandToLevel = useCallback(
(level: ExpandLevel) => {
const depth = LEVEL_ORDER[level];
const keys = new Set<string>();
const walk = (ns: HierNode[], d: number) => {
for (const n of ns) {
if (d < depth) keys.add(n.key);
walk(n.children, d + 1);
}
};
walk(nodes, 0);
setExpanded(keys);
},
[nodes],
);
const collapseAll = useCallback(() => setExpanded(new Set()), []);
// Flatten to visible rows
const rows = useMemo(() => {
const out: Array<{ node: HierNode; depth: number }> = [];
const walk = (ns: HierNode[], depth: number) => {
for (const n of ns) {
out.push({ node: n, depth });
if (expanded.has(n.key)) walk(n.children, depth + 1);
}
};
walk(nodes, 0);
return out;
}, [nodes, expanded]);
const grandTotal = useMemo(
() => nodes.reduce((s, n) => s + n.value, 0),
[nodes],
);
return (
<div className="flex-col gap-2 full-height">
{/* Expand level controls */}
<div className="flex items-center justify-between">
<div className="btn-group">
<button className="btn btn-sm" onClick={collapseAll} title="Collapse all">
Year
</button>
<button className="btn btn-sm" onClick={() => expandToLevel('month')}>
Month
</button>
<button className="btn btn-sm" onClick={() => expandToLevel('day')}>
Day
</button>
<button className="btn btn-sm" onClick={() => expandToLevel('item')}>
Item
</button>
</div>
<span className="text-muted text-sm">{rows.length} rows</span>
</div>
{/* Table */}
<div className="scroll-y" style={{ flex: 1, minHeight: 0 }}>
<table className="data-table">
<thead>
<tr>
<th>Period / Item</th>
<th className="num">{valueLabel}</th>
<th style={{ width: 80 }}></th>
</tr>
</thead>
<tbody>
{rows.length === 0 && (
<tr>
<td colSpan={3} className="text-muted" style={{ textAlign: 'center', padding: 24 }}>
No entries yet
</td>
</tr>
)}
{rows.map(({ node, depth }) => {
const isExpanded = expanded.has(node.key);
const hasChildren = node.children.length > 0;
const isItem = node.level === 'item';
return (
<tr
key={node.key}
className={clsx('hier-row', `level-${node.level}`)}
onClick={hasChildren ? () => toggle(node.key) : undefined}
>
<td className={`indent-${depth}`}>
{hasChildren && (
<span className={clsx('hier-toggle', isExpanded && 'expanded')}>
</span>
)}
{!hasChildren && <span className="hier-toggle" />}
{node.label}
</td>
<td className="num">{fmtMoney(node.value)}</td>
<td className="num">
{isItem && (
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{onEdit && (
<button
className="btn btn-sm btn-ghost"
onClick={() => onEdit(node)}
title="Edit"
>
</button>
)}
{onDelete && (
<button
className="btn btn-sm btn-ghost text-danger"
onClick={() => onDelete(node)}
title="Delete"
>
</button>
)}
</div>
)}
</td>
</tr>
);
})}
</tbody>
<tfoot>
<tr>
<td>Grand Total</td>
<td className="num">{fmtMoney(grandTotal)}</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</div>
);
}