Move category filtering to frontend with checkable toggles

This commit is contained in:
2026-05-06 22:02:42 +08:00
parent ef7fef2254
commit 965ef2058d
2 changed files with 247 additions and 238 deletions
+152 -145
View File
@@ -11,14 +11,8 @@ import {
PieChart, PieChart,
Pie, Pie,
Cell, Cell,
Legend,
} from "recharts"; } from "recharts";
import { import { getOverview, getMonthly, formatAmount } from "../hooks/useApi";
getOverview,
getMonthly,
formatAmount,
formatDate,
} from "../hooks/useApi";
const COLORS = [ const COLORS = [
"#4f46e5", "#4f46e5",
@@ -35,68 +29,20 @@ const COLORS = [
"#e11d48", "#e11d48",
]; ];
// 不参与支出饼图的分类(投资/转账/赠与类) /* ============ 默认不勾的分类 ============ */
const EXCLUDED_PATTERNS = ["投资", "转账", "赠与", "红包"]; const DEFAULT_UNCHECKED = ["投资理财", "转账红包"];
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,
};
}
/* ============ 饼图 label ============ */
const RADIAN = Math.PI / 180; const RADIAN = Math.PI / 180;
function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) {
/** 自定义 label:拉出引导线 + 百分比 */ const r = outerRadius + 30;
function renderPieLabel({ const x = cx + r * Math.cos(-midAngle * RADIAN);
cx, const y = cy + r * Math.sin(-midAngle * RADIAN);
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);
// 引导线起点
const mx = cx + (outerRadius + 8) * Math.cos(-midAngle * RADIAN); const mx = cx + (outerRadius + 8) * Math.cos(-midAngle * RADIAN);
const my = cy + (outerRadius + 8) * Math.sin(-midAngle * RADIAN); const my = cy + (outerRadius + 8) * Math.sin(-midAngle * RADIAN);
// 饼内点
const ex = cx + (outerRadius + 2) * Math.cos(-midAngle * RADIAN); const ex = cx + (outerRadius + 2) * Math.cos(-midAngle * RADIAN);
const ey = cy + (outerRadius + 2) * Math.sin(-midAngle * RADIAN); const ey = cy + (outerRadius + 2) * Math.sin(-midAngle * RADIAN);
const anchor = x > cx ? "start" : "end";
const pct = (percent * 100).toFixed(0);
const textAnchor = x > cx ? "start" : "end";
return ( return (
<> <>
<polyline <polyline
@@ -108,23 +54,42 @@ function renderPieLabel({
<text <text
x={x + (x > cx ? 4 : -4)} x={x + (x > cx ? 4 : -4)}
y={y} y={y}
textAnchor={textAnchor} textAnchor={anchor}
dominantBaseline="central" dominantBaseline="central"
fontSize={11} fontSize={11}
fill="#475569" fill="#475569"
> >
<tspan fontWeight={600}>{category}</tspan> <tspan fontWeight={600}>{category}</tspan>
<tspan fill="#94a3b8"> {pct}%</tspan> <tspan fill="#94a3b8"> {(percent * 100).toFixed(0)}%</tspan>
</text> </text>
</> </>
); );
} }
/* ============ 饼图数据: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() { export default function Dashboard() {
const [overview, setOverview] = useState(null); const [raw, setRaw] = useState(null); // 后端全量
const [monthly, setMonthly] = useState([]); const [monthly, setMonthly] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
// 勾选状态:Set<categoryName>
const [checked, setChecked] = useState(() => new Set());
useEffect(() => { useEffect(() => {
loadData(); loadData();
}, []); }, []);
@@ -132,45 +97,66 @@ export default function Dashboard() {
async function loadData() { async function loadData() {
setLoading(true); setLoading(true);
try { try {
const [overviewData, monthlyData] = await Promise.all([ const [ov, mo] = await Promise.all([getOverview(), getMonthly(12)]);
getOverview(), setRaw(ov);
getMonthly(12), setMonthly(mo);
]); // 初始化勾选
setOverview(overviewData); const allCats = new Set(
setMonthly(monthlyData); (ov?.categoryBreakdown || []).map((c) => c.category),
} catch (err) { );
console.error("加载数据失败:", err); for (const c of DEFAULT_UNCHECKED) allCats.delete(c);
setChecked(allCats);
} catch (e) {
console.error(e);
} }
setLoading(false); setLoading(false);
} }
const ov = overview?.overview || {}; function toggleCat(cat) {
const { slices: pieData, totalAmount: pieTotal } = useMemo( setChecked((prev) => {
() => buildPieData(overview?.categoryStats), const next = new Set(prev);
[overview], 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 (
<div className="loading"> <div className="loading">
<div className="spinner"></div>加载中... <div className="spinner" />
加载中...
</div> </div>
); );
}
return ( return (
<div> <div>
<div <div
className="page-header" className="page-header"
style={{ style={{ display: "flex", justifyContent: "space-between" }}
display: "flex",
justifyContent: "space-between",
alignItems: "flex-start",
}}
> >
<div> <div>
<h2>📊 财务仪表盘</h2> <h2>📊 财务仪表盘</h2>
<p>全面掌握你的收支情况</p> <p>勾选分类后,所有统计基于选中项计算</p>
</div> </div>
<button <button
className="btn btn-secondary" className="btn btn-secondary"
@@ -181,46 +167,45 @@ export default function Dashboard() {
</button> </button>
</div> </div>
{/* Stats Cards */} {/* ========== Stats Cards ========== */}
<div className="stats-grid"> <div className="stats-grid">
<div className="stat-card"> <div className="stat-card">
<div className="stat-label">💰 总收入</div> <div className="stat-label">💰 总收入</div>
<div className="stat-value income"> <div className="stat-value income">
{formatAmount(ov.total_income)} {formatAmount(derived?.totalIncome ?? 0)}
</div> </div>
<div className="stat-sub">所有来源收入合计</div> <div className="stat-sub">{checked.size} 个分类合计</div>
</div> </div>
<div className="stat-card"> <div className="stat-card">
<div className="stat-label">💸 总支出</div> <div className="stat-label">💸 总支出</div>
<div className="stat-value expense"> <div className="stat-value expense">
{formatAmount(ov.total_expense)} {formatAmount(-(derived?.totalExpense ?? 0))}
</div> </div>
<div className="stat-sub">所有支出合计</div> <div className="stat-sub">{checked.size} 个分类合计</div>
</div> </div>
<div className="stat-card"> <div className="stat-card">
<div className="stat-label">📈 净收支</div> <div className="stat-label">📈 净收支</div>
<div <div
className={`stat-value ${ov.total_income - ov.total_expense >= 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),
)}
</div> </div>
<div className="stat-sub">收入 - 支出</div>
</div> </div>
<div className="stat-card"> <div className="stat-card">
<div className="stat-label">📝 交易总数</div> <div className="stat-label">📝 交易笔数</div>
<div className="stat-value primary">{ov.total_count || 0}</div> <div className="stat-value primary">{derived?.dealCount ?? 0}</div>
<div className="stat-sub"> <div className="stat-sub">共 {ov.matched_count || 0} 条原始记录</div>
共 {ov.matched_count || 0} 笔交易被记录
</div>
</div> </div>
<div className="stat-card"> <div className="stat-card">
<div className="stat-label">⚠️ 待确认</div> <div className="stat-label">⚠️ 待确认</div>
<div className="stat-value warning">{ov.pending_review || 0}</div> <div className="stat-value warning">{ov.pending_review || 0}</div>
<div className="stat-sub">≥100元 未确认交易</div> <div className="stat-sub">≥100元 未确认</div>
</div> </div>
</div> </div>
{/* Charts Row */} {/* ========== Charts Row ========== */}
<div <div
style={{ style={{
display: "grid", display: "grid",
@@ -229,7 +214,7 @@ export default function Dashboard() {
marginBottom: 24, marginBottom: 24,
}} }}
> >
{/* Monthly Trend */} {/* Monthly */}
<div className="card"> <div className="card">
<div className="card-header"> <div className="card-header">
<h3>📅 月度收支趋势</h3> <h3>📅 月度收支趋势</h3>
@@ -240,10 +225,7 @@ export default function Dashboard() {
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" /> <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
<XAxis dataKey="month" tick={{ fontSize: 11 }} /> <XAxis dataKey="month" tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} /> <YAxis tick={{ fontSize: 11 }} />
<Tooltip <Tooltip formatter={(v) => formatAmount(v)} />
formatter={(value) => formatAmount(value)}
labelStyle={{ fontWeight: 600 }}
/>
<Bar <Bar
dataKey="income" dataKey="income"
name="收入" name="收入"
@@ -261,26 +243,31 @@ export default function Dashboard() {
) : ( ) : (
<div className="empty-state"> <div className="empty-state">
<div className="icon">📭</div> <div className="icon">📭</div>
<p>暂无数据,请先导入账单</p> <p>暂无数据</p>
</div> </div>
)} )}
</div> </div>
{/* Category Pie */} {/* Pie */}
<div className="card"> <div className="card">
<div className="card-header"> <div className="card-header">
<h3>🏷️ 支出分类占比</h3> <h3>🏷️ 支出分类占比</h3>
{pieData.length > 0 && ( {(() => {
const pd = buildPieData(derived?.pieStats);
return pd.total > 0 ? (
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}> <span style={{ fontSize: 13, color: "var(--text-secondary)" }}>
合计 {formatAmount(-pieTotal)} 合计 {formatAmount(-pd.total)}
</span> </span>
)} ) : null;
})()}
</div> </div>
{pieData.length > 0 ? ( {(() => {
const pd = buildPieData(derived?.pieStats);
return pd.slices.length > 0 ? (
<ResponsiveContainer width="100%" height={300}> <ResponsiveContainer width="100%" height={300}>
<PieChart> <PieChart>
<Pie <Pie
data={pieData} data={pd.slices}
cx="50%" cx="50%"
cy="50%" cy="50%"
innerRadius={50} innerRadius={50}
@@ -290,44 +277,42 @@ export default function Dashboard() {
nameKey="category" nameKey="category"
label={renderPieLabel} label={renderPieLabel}
labelLine={false} labelLine={false}
isAnimationActive={true} isAnimationActive
> >
{pieData.map((_, idx) => ( {pd.slices.map((_, i) => (
<Cell key={idx} fill={COLORS[idx % COLORS.length]} /> <Cell key={i} fill={COLORS[i % COLORS.length]} />
))} ))}
</Pie> </Pie>
<Tooltip <Tooltip
formatter={(value) => formatAmount(-value)} formatter={(v) => formatAmount(-v)}
labelFormatter={(name) => `分类: ${name}`} labelFormatter={(n) => `分类: ${n}`}
/> />
</PieChart> </PieChart>
</ResponsiveContainer> </ResponsiveContainer>
) : overview?.categoryStats?.length > 0 ? (
<div className="empty-state" style={{ padding: "40px 0" }}>
<div className="icon">📊</div>
<p style={{ fontSize: 13, color: "var(--text-secondary)" }}>
投资/转账类不参与支出占比统计
</p>
</div>
) : ( ) : (
<div className="empty-state" style={{ padding: "40px 0" }}> <div className="empty-state" style={{ padding: "40px 0" }}>
<div className="icon">📭</div> <div className="icon">📭</div>
<p>暂无分类数据,请先对账并 AI 分类</p> <p>请勾选至少一个分类</p>
</div> </div>
)} );
})()}
</div> </div>
</div> </div>
{/* Category Breakdown Table */} {/* ========== Category Table ========== */}
<div className="card"> <div className="card">
<div className="card-header"> <div className="card-header">
<h3>📋 分类收支明细</h3> <h3>📋 分类收支明细</h3>
<span style={{ fontSize: 12, color: "var(--text-secondary)" }}>
勾选的行参与上方统计
</span>
</div> </div>
{overview?.categoryBreakdown?.length > 0 ? ( {(raw?.categoryBreakdown || []).length > 0 ? (
<div className="table-container"> <div className="table-container">
<table> <table>
<thead> <thead>
<tr> <tr>
<th style={{ width: 40 }}>勾选</th>
<th>分类</th> <th>分类</th>
<th style={{ textAlign: "right" }}>笔数</th> <th style={{ textAlign: "right" }}>笔数</th>
<th style={{ textAlign: "right" }}>收入</th> <th style={{ textAlign: "right" }}>收入</th>
@@ -338,18 +323,37 @@ export default function Dashboard() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{overview.categoryBreakdown.map((cat, i) => ( {raw.categoryBreakdown.map((cat, i) => {
<tr key={i}> const on = checked.has(cat.category);
return (
<tr key={i} style={{ opacity: on ? 1 : 0.45 }}>
<td>
<input
type="checkbox"
checked={on}
onChange={() => toggleCat(cat.category)}
style={{
width: 16,
height: 16,
cursor: "pointer",
accentColor: "var(--primary)",
}}
/>
</td>
<td> <td>
<span className="tag tag-matched">{cat.category}</span> <span className="tag tag-matched">{cat.category}</span>
</td> </td>
<td style={{ textAlign: "right" }}>{cat.deal_count}</td> <td style={{ textAlign: "right" }}>{cat.deal_count}</td>
<td style={{ textAlign: "right", color: "var(--success)" }}> <td
style={{ textAlign: "right", color: "var(--success)" }}
>
{cat.total_income > 0 {cat.total_income > 0
? formatAmount(cat.total_income) ? formatAmount(cat.total_income)
: "--"} : "--"}
</td> </td>
<td style={{ textAlign: "right", color: "var(--danger)" }}> <td
style={{ textAlign: "right", color: "var(--danger)" }}
>
{cat.total_expense > 0 {cat.total_expense > 0
? formatAmount(-cat.total_expense) ? formatAmount(-cat.total_expense)
: "--"} : "--"}
@@ -368,11 +372,12 @@ export default function Dashboard() {
</td> </td>
<td style={{ fontSize: 12, maxWidth: 180 }}> <td style={{ fontSize: 12, maxWidth: 180 }}>
{cat.max_income ? ( {cat.max_income ? (
<span>
<span <span
title={`${cat.max_income.counterparty || ""} ${cat.max_income.ai_description || ""}`} style={{
> color: "var(--success)",
<span fontWeight: 500,
style={{ color: "var(--success)", fontWeight: 500 }} }}
> >
{formatAmount(cat.max_income.amount)} {formatAmount(cat.max_income.amount)}
</span> </span>
@@ -393,11 +398,12 @@ export default function Dashboard() {
</td> </td>
<td style={{ fontSize: 12, maxWidth: 180 }}> <td style={{ fontSize: 12, maxWidth: 180 }}>
{cat.max_expense ? ( {cat.max_expense ? (
<span>
<span <span
title={`${cat.max_expense.counterparty || ""} ${cat.max_expense.ai_description || ""}`} style={{
> color: "var(--danger)",
<span fontWeight: 500,
style={{ color: "var(--danger)", fontWeight: 500 }} }}
> >
{formatAmount(cat.max_expense.amount)} {formatAmount(cat.max_expense.amount)}
</span> </span>
@@ -417,14 +423,15 @@ export default function Dashboard() {
)} )}
</td> </td>
</tr> </tr>
))} );
})}
</tbody> </tbody>
</table> </table>
</div> </div>
) : ( ) : (
<div className="empty-state"> <div className="empty-state">
<div className="icon">📭</div> <div className="icon">📭</div>
<p>暂无数据,请先导入账单</p> <p>暂无数据</p>
</div> </div>
)} )}
</div> </div>
+7 -5
View File
@@ -38,8 +38,9 @@ router.get("/overview", (req, res) => {
// 按分类统计支出(用于饼图) // 按分类统计支出(用于饼图)
const catWhere = where const catWhere = where
? where + " AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')" ? where +
: "WHERE d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"; " AND d.direction = 'expense' AND d.category IS NOT NULL"
: "WHERE d.direction = 'expense' AND d.category IS NOT NULL";
const categoryStats = db const categoryStats = db
.prepare( .prepare(
@@ -57,10 +58,11 @@ router.get("/overview", (req, res) => {
) )
.all(...params); .all(...params);
// 按分类汇总(收入+支出),排除投资理财、转账红包 // 按分类汇总(收入+支出)
const catBreakWhere = where const catBreakWhere = where
? where + " AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')" ? where +
: "WHERE d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"; " AND d.category IS NOT NULL"
: "WHERE d.category IS NOT NULL";
const categoryBreakdown = db const categoryBreakdown = db
.prepare( .prepare(