import React, { useState, useEffect, useCallback, useRef } from 'react';
import { toast } from 'sonner';
import { ChevronLeft, ChevronRight, ChevronDown, Tag, ReceiptText, TrendingDown, Pencil, Check, X, Trash2, BookmarkPlus, Settings2, Copy, DollarSign } from 'lucide-react';
import { api } from '@/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
const MONTH_NAMES = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function fmt(n) {
return Number(n || 0).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
function pctBar(amount, budget) {
if (!budget) return null;
const pct = Math.min(100, Math.round((amount / budget) * 100));
const over = amount > budget;
return { pct, over };
}
// ── Category picker dropdown ─────────────────────────────────────────────────
function CategoryPicker({ categories, current, onSelect }) {
const [open, setOpen] = useState(false);
const ref = useRef(null);
useEffect(() => {
if (!open) return;
const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
document.addEventListener('mousedown', close);
return () => document.removeEventListener('mousedown', close);
}, [open]);
const currentCat = categories.find(c => c.id === current);
return (
{open && (
{categories.length === 0 ? (
No spending categories. Enable some in Categories.
) : categories.map(cat => (
))}
)}
);
}
// ── Transaction row ──────────────────────────────────────────────────────────
function TxRow({ tx, categories, onCategorize }) {
const [saving, setSaving] = useState(false);
const [rememberPrompt, setRememberPrompt] = useState(null); // { categoryId, categoryName }
const dismissTimer = useRef(null);
// Auto-dismiss the "remember" prompt after 7 seconds
useEffect(() => {
if (!rememberPrompt) return;
dismissTimer.current = setTimeout(() => setRememberPrompt(null), 7000);
return () => clearTimeout(dismissTimer.current);
}, [rememberPrompt]);
const handleSelect = async (categoryId) => {
setSaving(true);
setRememberPrompt(null);
try {
await api.categorizeTransaction(tx.id, { category_id: categoryId, save_rule: false });
const catName = categories.find(c => c.id === categoryId)?.name ?? null;
onCategorize(tx.id, categoryId, catName);
// Offer to remember the merchant rule (only when assigning a real category)
if (categoryId) setRememberPrompt({ categoryId, categoryName: catName });
} catch (err) {
toast.error(err.message || 'Failed to categorize');
} finally {
setSaving(false);
}
};
const saveRule = async () => {
if (!rememberPrompt) return;
clearTimeout(dismissTimer.current);
setRememberPrompt(null);
try {
await api.categorizeTransaction(tx.id, { category_id: rememberPrompt.categoryId, save_rule: true });
toast.success(`Rule saved — future ${tx.payee} transactions will be auto-categorized.`);
} catch (err) {
toast.error(err.message || 'Failed to save rule');
}
};
return (
-{fmt(tx.amount)}
{saving
?
Saving…
:
}
{rememberPrompt && (
Always categorize {tx.payee} as{' '}
{rememberPrompt.categoryName}?
)}
);
}
// ── Budget edit inline ───────────────────────────────────────────────────────
function BudgetEditor({ categoryId, year, month, initial, onSaved }) {
const [editing, setEditing] = useState(false);
const [val, setVal] = useState(initial ?? '');
const save = async () => {
const amount = val === '' ? null : parseFloat(val);
if (val !== '' && (isNaN(amount) || amount < 0)) { toast.error('Enter a valid amount'); return; }
try {
await api.setSpendingBudget({ category_id: categoryId, year, month, amount });
onSaved(categoryId, amount);
setEditing(false);
} catch { toast.error('Failed to save budget'); }
};
if (!editing) return (
);
return (
setVal(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') save(); if (e.key === 'Escape') setEditing(false); }}
placeholder="0.00"
autoFocus
className="w-20 rounded border border-border/60 bg-background px-1.5 py-0.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-ring"
/>
);
}
// ── Income section ───────────────────────────────────────────────────────────
function IncomeSection({ year, month, totalIncome }) {
const [open, setOpen] = useState(false);
const [rows, setRows] = useState([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [pages, setPages] = useState(1);
const [loading, setLoading] = useState(false);
const load = useCallback(async (p = 1) => {
setLoading(true);
try {
const d = await api.spendingIncome({ year, month, page: p });
setRows(d.transactions || []);
setTotal(d.total || 0);
setPages(d.pages || 1);
setPage(p);
} catch (err) {
toast.error(err.message || 'Failed to load income transactions');
} finally {
setLoading(false);
}
}, [year, month]);
useEffect(() => { if (open) load(1); }, [open, load]);
if (!totalIncome) return null;
return (
{open && (
{loading ? (
Loading…
) : rows.length === 0 ? (
No income transactions found.
) : (
<>
{pages > 1 && (
{page} / {pages}
)}
>
)}
Positive unmatched transactions — deposits, refunds, transfers in. Bill-matched payments are excluded.
)}
);
}
// ── Rules manager ────────────────────────────────────────────────────────────
function RulesManager({ categories }) {
const [open, setOpen] = useState(false);
const [rules, setRules] = useState([]);
const [loading, setLoading] = useState(false);
const [newMerchant, setNewMerchant] = useState('');
const [newCategory, setNewCategory] = useState('');
const [adding, setAdding] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try { setRules((await api.spendingCategoryRules()).rules || []); }
catch { toast.error('Failed to load rules'); }
finally { setLoading(false); }
}, []);
useEffect(() => { if (open) load(); }, [open, load]);
const deleteRule = async (id) => {
try {
await api.deleteSpendingRule(id);
setRules(prev => prev.filter(r => r.id !== id));
} catch { toast.error('Failed to delete rule'); }
};
const addRule = async (e) => {
e.preventDefault();
if (!newMerchant.trim() || !newCategory) return;
setAdding(true);
try {
await api.addSpendingRule({ merchant: newMerchant.trim(), category_id: parseInt(newCategory, 10) });
setNewMerchant(''); setNewCategory('');
await load();
toast.success('Rule saved.');
} catch (err) {
toast.error(err.message || 'Failed to save rule');
} finally { setAdding(false); }
};
return (
{open && (
{/* Add new rule */}
{/* Existing rules */}
{loading ? (
Loading…
) : rules.length === 0 ? (
No rules saved yet. Categorize a transaction and click "Save rule" to create one.
) : (
{rules.map(r => (
{r.merchant}
→
{r.category_name}
))}
)}
)}
);
}
// ── Main page ────────────────────────────────────────────────────────────────
export default function SpendingPage() {
const now = new Date();
const [year, setYear] = useState(now.getFullYear());
const [month, setMonth] = useState(now.getMonth() + 1);
const [summary, setSummary] = useState(null);
const [transactions, setTransactions] = useState([]);
const [txTotal, setTxTotal] = useState(0);
const [txPage, setTxPage] = useState(1);
const [txPages, setTxPages] = useState(1);
const [categories, setCategories] = useState([]);
const [activeCat, setActiveCat] = useState(undefined); // undefined = all
const [loading, setLoading] = useState(true);
const [txLoading, setTxLoading] = useState(false);
const [budgets, setBudgets] = useState({}); // categoryId → amount
const [copying, setCopying] = useState(false);
// loadCategories is stable — categories don't vary by month
const loadCategories = useCallback(async () => {
try {
const d = await api.categories();
// Only show spending-enabled categories in the spending UI
setCategories((d.categories || d || []).filter(c => !c.deleted_at && c.spending_enabled));
} catch (err) {
toast.error(err.message || 'Failed to load categories');
}
}, []);
// loadTransactions is exposed so pagination buttons can call it with a page arg
const loadTransactions = useCallback(async (page = 1) => {
setTxLoading(true);
try {
const params = { year, month, page, limit: 50 };
if (activeCat === null) params.category_id = 'null';
else if (activeCat !== undefined) params.category_id = activeCat;
const d = await api.spendingTransactions(params);
setTransactions(d.transactions || []);
setTxTotal(d.total || 0);
setTxPages(d.pages || 1);
setTxPage(page);
} catch (err) {
toast.error(err.message || 'Failed to load transactions');
} finally {
setTxLoading(false);
}
}, [year, month, activeCat]);
// Load categories once on mount
useEffect(() => { loadCategories(); }, [loadCategories]);
// Load summary and transactions whenever month/category filter changes.
// Depends on primitive values directly — avoids the double-fetch that
// happened when useCallback references were used as deps (both effects
// would fire whenever year/month changed).
useEffect(() => {
let cancelled = false;
const run = async () => {
setLoading(true);
try {
const d = await api.spendingSummary({ year, month });
if (cancelled) return;
setSummary(d);
const bmap = {};
(d.by_category || []).forEach(c => { if (c.category_id && c.budget != null) bmap[c.category_id] = c.budget; });
setBudgets(bmap);
} catch (err) {
if (!cancelled) toast.error(err.message || 'Failed to load spending summary');
} finally {
if (!cancelled) setLoading(false);
}
};
run();
loadTransactions(1);
return () => { cancelled = true; };
}, [year, month, activeCat]); // eslint-disable-line react-hooks/exhaustive-deps
const handleCopyBudgets = async () => {
setCopying(true);
try {
const d = await api.copySpendingBudgets({ year, month });
if (d.copied === 0) {
toast.info('No budgets found in the previous month to copy.');
} else {
// Update local budget state from server response
const bmap = {};
(d.budgets || []).forEach(b => { bmap[b.category_id] = b.amount; });
setBudgets(bmap);
setSummary(prev => prev ? {
...prev,
by_category: prev.by_category.map(c =>
c.category_id && bmap[c.category_id] != null
? { ...c, budget: bmap[c.category_id] }
: c
),
} : prev);
toast.success(`${d.copied} budget${d.copied !== 1 ? 's' : ''} copied from last month.`);
}
} catch (err) {
toast.error(err.message || 'Failed to copy budgets');
} finally {
setCopying(false);
}
};
const navMonth = (dir) => {
let m = month + dir, y = year;
if (m > 12) { m = 1; y++; }
if (m < 1) { m = 12; y--; }
setMonth(m); setYear(y); setActiveCat(undefined); setTxPage(1);
};
const handleCategorize = (txId, categoryId, categoryName) => {
setTransactions(prev => prev.map(t =>
t.id === txId ? { ...t, spending_category_id: categoryId, spending_category_name: categoryName } : t
));
loadSummary();
};
const handleBudgetSaved = (categoryId, amount) => {
setBudgets(prev => ({ ...prev, [categoryId]: amount }));
setSummary(prev => {
if (!prev) return prev;
return {
...prev,
by_category: prev.by_category.map(c =>
c.category_id === categoryId ? { ...c, budget: amount } : c
),
};
});
};
const selectCat = (catId) => {
setActiveCat(prev => prev === catId ? undefined : catId);
setTxPage(1);
};
if (loading) {
return (
Loading spending…
);
}
const uncatEntry = summary?.by_category?.find(c => !c.category_id);
const catEntries = summary?.by_category?.filter(c => !!c.category_id) || [];
return (
{/* Header */}
Spending
Unmatched bank transactions by category
{MONTH_NAMES[month - 1]} {year}
{/* Overview strip */}
Total Spending
{fmt(summary?.total_spending)}
Uncategorized
{fmt(summary?.uncategorized_amount)}
{summary?.uncategorized_count > 0 && (
{summary.uncategorized_count} transaction{summary.uncategorized_count !== 1 ? 's' : ''}
)}
Income Received
{fmt(summary?.income)}
{/* No spending categories notice */}
{categories.length === 0 && (
No spending categories are enabled yet. Go to{' '}
Categories
{' '}and enable "Spending" on the categories you want to use here.
)}
{/* Category breakdown */}
By Category
{activeCat !== undefined && (
)}
{catEntries.length === 0 && !uncatEntry ? (
No spending transactions found for this month.
) : (
{catEntries.map(cat => {
const bar = pctBar(cat.amount, cat.budget ?? budgets[cat.category_id]);
const isActive = activeCat === cat.category_id;
return (
);
})}
{/* Uncategorized row */}
{uncatEntry && (
)}
)}
{/* Transaction list */}
Transactions
{activeCat !== undefined && (
— {activeCat === null ? 'Uncategorized' : catEntries.find(c => c.category_id === activeCat)?.category_name}
)}
{txTotal}
{txLoading ? (
Loading…
) : transactions.length === 0 ? (
No transactions found.
) : (
<>
{transactions.map(tx => (
))}
{txPages > 1 && (
Page {txPage} of {txPages}
)}
>
)}
{/* Income & deposits */}
{/* Merchant rules manager */}
);
}