From 965ef2058d51f7770a6eb0c33ef9d17d8addfc37 Mon Sep 17 00:00:00 2001 From: fukunee Date: Wed, 6 May 2026 22:02:42 +0800 Subject: [PATCH] Move category filtering to frontend with checkable toggles --- client/src/pages/Dashboard.js | 473 +++++++++++++++++----------------- server/routes/stats.js | 12 +- 2 files changed, 247 insertions(+), 238 deletions(-) diff --git a/client/src/pages/Dashboard.js b/client/src/pages/Dashboard.js index 86b8196..f4a5921 100644 --- a/client/src/pages/Dashboard.js +++ b/client/src/pages/Dashboard.js @@ -11,14 +11,8 @@ import { PieChart, Pie, Cell, - Legend, } from "recharts"; -import { - getOverview, - getMonthly, - formatAmount, - formatDate, -} from "../hooks/useApi"; +import { getOverview, getMonthly, formatAmount } from "../hooks/useApi"; const COLORS = [ "#4f46e5", @@ -35,68 +29,20 @@ const COLORS = [ "#e11d48", ]; -// 不参与支出饼图的分类(投资/转账/赠与类) -const EXCLUDED_PATTERNS = ["投资", "转账", "赠与", "红包"]; - -function isExcluded(category) { - if (!category) return true; - const s = category.trim().toLowerCase(); - return EXCLUDED_PATTERNS.some(p => s.includes(p.toLowerCase())); -} - -/** 将小切片合并为"其他",最多保留 topN-1 个分类 + 1 个"其他" */ -function buildPieData(categoryStats, topN = 8) { - const filtered = (categoryStats || []).filter( - (c) => !isExcluded(c.category), - ); - if (filtered.length === 0) return { slices: [], totalAmount: 0 }; - - const totalAmount = filtered.reduce((s, c) => s + c.total_amount, 0); - if (filtered.length <= topN) return { slices: filtered, totalAmount }; - - const top = filtered.slice(0, topN - 1); - const rest = filtered.slice(topN - 1); - const otherAmount = rest.reduce((s, c) => s + c.total_amount, 0); - - return { - slices: [ - ...top, - { - category: "其他", - count: rest.reduce((s, c) => s + c.count, 0), - total_amount: otherAmount, - }, - ], - totalAmount, - }; -} +/* ============ 默认不勾的分类 ============ */ +const DEFAULT_UNCHECKED = ["投资理财", "转账红包"]; +/* ============ 饼图 label ============ */ const RADIAN = Math.PI / 180; - -/** 自定义 label:拉出引导线 + 百分比 */ -function renderPieLabel({ - cx, - cy, - midAngle, - innerRadius, - outerRadius, - percent, - category, -}) { - const radius = outerRadius + 30; - const x = cx + radius * Math.cos(-midAngle * RADIAN); - const y = cy + radius * Math.sin(-midAngle * RADIAN); - - // 引导线起点 +function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) { + const r = outerRadius + 30; + const x = cx + r * Math.cos(-midAngle * RADIAN); + const y = cy + r * Math.sin(-midAngle * RADIAN); const mx = cx + (outerRadius + 8) * Math.cos(-midAngle * RADIAN); const my = cy + (outerRadius + 8) * Math.sin(-midAngle * RADIAN); - // 饼内点 const ex = cx + (outerRadius + 2) * Math.cos(-midAngle * RADIAN); const ey = cy + (outerRadius + 2) * Math.sin(-midAngle * RADIAN); - - const pct = (percent * 100).toFixed(0); - const textAnchor = x > cx ? "start" : "end"; - + const anchor = x > cx ? "start" : "end"; return ( <> cx ? 4 : -4)} y={y} - textAnchor={textAnchor} + textAnchor={anchor} dominantBaseline="central" fontSize={11} fill="#475569" > {category} - {pct}% + {(percent * 100).toFixed(0)}% ); } +/* ============ 饼图数据:topN + 其他 ============ */ +function buildPieData(stats, topN = 7) { + const list = stats || []; + if (!list.length) return { slices: [], total: 0 }; + const total = list.reduce((s, c) => s + c.total_amount, 0); + if (list.length <= topN) return { slices: list, total }; + const top = list.slice(0, topN - 1); + const rest = list.slice(topN - 1); + const other = { + category: "其他", + count: rest.reduce((s, c) => s + c.count, 0), + total_amount: rest.reduce((s, c) => s + c.total_amount, 0), + }; + return { slices: [...top, other], total }; +} + export default function Dashboard() { - const [overview, setOverview] = useState(null); + const [raw, setRaw] = useState(null); // 后端全量 const [monthly, setMonthly] = useState([]); const [loading, setLoading] = useState(true); + // 勾选状态:Set + const [checked, setChecked] = useState(() => new Set()); + useEffect(() => { loadData(); }, []); @@ -132,45 +97,66 @@ export default function Dashboard() { async function loadData() { setLoading(true); try { - const [overviewData, monthlyData] = await Promise.all([ - getOverview(), - getMonthly(12), - ]); - setOverview(overviewData); - setMonthly(monthlyData); - } catch (err) { - console.error("加载数据失败:", err); + const [ov, mo] = await Promise.all([getOverview(), getMonthly(12)]); + setRaw(ov); + setMonthly(mo); + // 初始化勾选 + const allCats = new Set( + (ov?.categoryBreakdown || []).map((c) => c.category), + ); + for (const c of DEFAULT_UNCHECKED) allCats.delete(c); + setChecked(allCats); + } catch (e) { + console.error(e); } setLoading(false); } - const ov = overview?.overview || {}; - const { slices: pieData, totalAmount: pieTotal } = useMemo( - () => buildPieData(overview?.categoryStats), - [overview], - ); + function toggleCat(cat) { + setChecked((prev) => { + const next = new Set(prev); + next.has(cat) ? next.delete(cat) : next.add(cat); + return next; + }); + } - if (loading) { + /* ============ 基于勾选计算 ============ */ + const derived = useMemo(() => { + if (!raw) return null; + const cb = raw.categoryBreakdown || []; + const cs = raw.categoryStats || []; + + // 勾选的分类 + const sel = cb.filter((c) => checked.has(c.category)); + const totalIncome = sel.reduce((s, c) => s + c.total_income, 0); + const totalExpense = sel.reduce((s, c) => s + c.total_expense, 0); + const dealCount = sel.reduce((s, c) => s + c.deal_count, 0); + + // 饼图数据(只取勾选的支出) + const pieStats = cs.filter((c) => checked.has(c.category)); + + return { sel, totalIncome, totalExpense, dealCount, pieStats }; + }, [raw, checked]); + + const ov = raw?.overview || {}; + + if (loading) return (
-
加载中... +
+ 加载中...
); - } return (

📊 财务仪表盘

-

全面掌握你的收支情况

+

勾选分类后,所有统计基于选中项计算

- {/* Stats Cards */} + {/* ========== Stats Cards ========== */}
💰 总收入
- {formatAmount(ov.total_income)} + {formatAmount(derived?.totalIncome ?? 0)}
-
所有来源收入合计
+
{checked.size} 个分类合计
💸 总支出
- {formatAmount(ov.total_expense)} + {formatAmount(-(derived?.totalExpense ?? 0))}
-
所有支出合计
+
{checked.size} 个分类合计
📈 净收支
= 0 ? "income" : "expense"}`} + className={`stat-value ${(derived?.totalIncome ?? 0) - (derived?.totalExpense ?? 0) >= 0 ? "income" : "expense"}`} > - {formatAmount(ov.total_income - ov.total_expense)} + {formatAmount( + (derived?.totalIncome ?? 0) - (derived?.totalExpense ?? 0), + )}
-
收入 - 支出
-
📝 交易总数
-
{ov.total_count || 0}
-
- 共 {ov.matched_count || 0} 笔交易被记录 -
+
📝 交易笔数
+
{derived?.dealCount ?? 0}
+
共 {ov.matched_count || 0} 条原始记录
⚠️ 待确认
{ov.pending_review || 0}
-
≥100元 未确认交易
+
≥100元 未确认
- {/* Charts Row */} + {/* ========== Charts Row ========== */}
- {/* Monthly Trend */} + {/* Monthly */}

📅 月度收支趋势

@@ -240,10 +225,7 @@ export default function Dashboard() { - formatAmount(value)} - labelStyle={{ fontWeight: 600 }} - /> + formatAmount(v)} />
📭
-

暂无数据,请先导入账单

+

暂无数据

)}
- {/* Category Pie */} + {/* Pie */}

🏷️ 支出分类占比

- {pieData.length > 0 && ( - - 合计 {formatAmount(-pieTotal)} - - )} + {(() => { + const pd = buildPieData(derived?.pieStats); + return pd.total > 0 ? ( + + 合计 {formatAmount(-pd.total)} + + ) : null; + })()}
- {pieData.length > 0 ? ( - - - - {pieData.map((_, idx) => ( - - ))} - - formatAmount(-value)} - labelFormatter={(name) => `分类: ${name}`} - /> - - - ) : overview?.categoryStats?.length > 0 ? ( -
-
📊
-

- 投资/转账类不参与支出占比统计 -

-
- ) : ( -
-
📭
-

暂无分类数据,请先对账并 AI 分类

-
- )} + {(() => { + const pd = buildPieData(derived?.pieStats); + return pd.slices.length > 0 ? ( + + + + {pd.slices.map((_, i) => ( + + ))} + + formatAmount(-v)} + labelFormatter={(n) => `分类: ${n}`} + /> + + + ) : ( +
+
📭
+

请勾选至少一个分类

+
+ ); + })()}
- {/* Category Breakdown Table */} + {/* ========== Category Table ========== */}

📋 分类收支明细

+ + 勾选的行参与上方统计 +
- {overview?.categoryBreakdown?.length > 0 ? ( + {(raw?.categoryBreakdown || []).length > 0 ? (
+ @@ -338,93 +323,115 @@ export default function Dashboard() { - {overview.categoryBreakdown.map((cat, i) => ( - - - - - - - + + + + + + + - + - - ))} + )} + + + ); + })}
勾选 分类 笔数 收入
- {cat.category} - {cat.deal_count} - {cat.total_income > 0 - ? formatAmount(cat.total_income) - : "--"} - - {cat.total_expense > 0 - ? formatAmount(-cat.total_expense) - : "--"} - = 0 - ? "var(--success)" - : "var(--danger)", - }} - > - {formatAmount(cat.total_income - cat.total_expense)} - - {cat.max_income ? ( - - - {formatAmount(cat.max_income.amount)} + {raw.categoryBreakdown.map((cat, i) => { + const on = checked.has(cat.category); + return ( +
+ toggleCat(cat.category)} + style={{ + width: 16, + height: 16, + cursor: "pointer", + accentColor: "var(--primary)", + }} + /> + + {cat.category} + {cat.deal_count} + {cat.total_income > 0 + ? formatAmount(cat.total_income) + : "--"} + + {cat.total_expense > 0 + ? formatAmount(-cat.total_expense) + : "--"} + = 0 + ? "var(--success)" + : "var(--danger)", + }} + > + {formatAmount(cat.total_income - cat.total_expense)} + + {cat.max_income ? ( + + + {formatAmount(cat.max_income.amount)} + + + {cat.max_income.counterparty || ""} + - - {cat.max_income.counterparty || ""} + ) : ( + + -- - - ) : ( - - -- - - )} - - {cat.max_expense ? ( - - - {formatAmount(cat.max_expense.amount)} + )} + + {cat.max_expense ? ( + + + {formatAmount(cat.max_expense.amount)} + + + {cat.max_expense.counterparty || ""} + - - {cat.max_expense.counterparty || ""} + ) : ( + + -- - - ) : ( - - -- - - )} -
) : (
📭
-

暂无数据,请先导入账单

+

暂无数据

)}
diff --git a/server/routes/stats.js b/server/routes/stats.js index ea78c7d..1acf7f2 100644 --- a/server/routes/stats.js +++ b/server/routes/stats.js @@ -38,8 +38,9 @@ router.get("/overview", (req, res) => { // 按分类统计支出(用于饼图) const catWhere = where - ? where + " AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')" - : "WHERE d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"; + ? where + + " AND d.direction = 'expense' AND d.category IS NOT NULL" + : "WHERE d.direction = 'expense' AND d.category IS NOT NULL"; const categoryStats = db .prepare( @@ -57,10 +58,11 @@ router.get("/overview", (req, res) => { ) .all(...params); - // 按分类汇总(收入+支出),排除投资理财、转账红包 + // 按分类汇总(收入+支出) const catBreakWhere = where - ? where + " AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')" - : "WHERE d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"; + ? where + + " AND d.category IS NOT NULL" + : "WHERE d.category IS NOT NULL"; const categoryBreakdown = db .prepare(