Migrate stats API to deals-based queries and add refresh button

This commit is contained in:
2026-05-05 23:51:03 +08:00
parent 075177cb3a
commit fa33128506
2 changed files with 195 additions and 85 deletions
+112 -27
View File
@@ -1,9 +1,39 @@
import React, { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, AlertCircle, FileText, RefreshCcw } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { getOverview, getMonthly, formatAmount } from '../hooks/useApi';
import React, { useState, useEffect } from "react";
import {
TrendingUp,
TrendingDown,
AlertCircle,
FileText,
RefreshCcw,
} from "lucide-react";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell,
} from "recharts";
import { getOverview, getMonthly, formatAmount } from "../hooks/useApi";
const COLORS = ['#4f46e5', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#f97316', '#84cc16', '#14b8a6', '#6366f1', '#e11d48'];
const COLORS = [
"#4f46e5",
"#10b981",
"#f59e0b",
"#ef4444",
"#8b5cf6",
"#ec4899",
"#06b6d4",
"#f97316",
"#84cc16",
"#14b8a6",
"#6366f1",
"#e11d48",
];
export default function Dashboard() {
const [overview, setOverview] = useState(null);
@@ -19,12 +49,12 @@ export default function Dashboard() {
try {
const [overviewData, monthlyData] = await Promise.all([
getOverview(),
getMonthly(12)
getMonthly(12),
]);
setOverview(overviewData);
setMonthly(monthlyData);
} catch (err) {
console.error('加载数据失败:', err);
console.error("加载数据失败:", err);
}
setLoading(false);
}
@@ -42,26 +72,48 @@ export default function Dashboard() {
return (
<div>
<div className="page-header">
<h2>📊 财务仪表盘</h2>
<p>全面掌握你的收支情况</p>
<div
className="page-header"
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "flex-start",
}}
>
<div>
<h2>📊 财务仪表盘</h2>
<p>全面掌握你的收支情况</p>
</div>
<button
className="btn btn-secondary"
onClick={loadData}
style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
>
<RefreshCcw size={14} /> 刷新
</button>
</div>
{/* Stats Cards */}
<div className="stats-grid">
<div className="stat-card">
<div className="stat-label">💰 总收入</div>
<div className="stat-value income">{formatAmount(ov.total_income)}</div>
<div className="stat-value income">
{formatAmount(ov.total_income)}
</div>
<div className="stat-sub">所有来源收入合计</div>
</div>
<div className="stat-card">
<div className="stat-label">💸 总支出</div>
<div className="stat-value expense">{formatAmount(ov.total_expense)}</div>
<div className="stat-value expense">
{formatAmount(ov.total_expense)}
</div>
<div className="stat-sub">所有支出合计</div>
</div>
<div className="stat-card">
<div className="stat-label">📈 净收支</div>
<div className={`stat-value ${(ov.total_income - ov.total_expense) >= 0 ? 'income' : 'expense'}`}>
<div
className={`stat-value ${ov.total_income - ov.total_expense >= 0 ? "income" : "expense"}`}
>
{formatAmount(ov.total_income - ov.total_expense)}
</div>
<div className="stat-sub">收入 - 支出</div>
@@ -69,7 +121,9 @@ export default function Dashboard() {
<div className="stat-card">
<div className="stat-label">📝 交易总数</div>
<div className="stat-value primary">{ov.total_count || 0}</div>
<div className="stat-sub">已导入 {ov.matched_count || 0} 笔已对账</div>
<div className="stat-sub">
共 {ov.matched_count || 0} 笔交易被记录
</div>
</div>
<div className="stat-card">
<div className="stat-label">⚠️ 待确认</div>
@@ -79,7 +133,14 @@ export default function Dashboard() {
</div>
{/* Charts Row */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: 20,
marginBottom: 24,
}}
>
{/* Monthly Trend */}
<div className="card">
<div className="card-header">
@@ -95,8 +156,18 @@ export default function Dashboard() {
formatter={(value) => formatAmount(value)}
labelStyle={{ fontWeight: 600 }}
/>
<Bar dataKey="income" name="收入" fill="#10b981" radius={[4,4,0,0]} />
<Bar dataKey="expense" name="支出" fill="#ef4444" radius={[4,4,0,0]} />
<Bar
dataKey="income"
name="收入"
fill="#10b981"
radius={[4, 4, 0, 0]}
/>
<Bar
dataKey="expense"
name="支出"
fill="#ef4444"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
) : (
@@ -122,7 +193,9 @@ export default function Dashboard() {
outerRadius={100}
dataKey="total_amount"
nameKey="category"
label={({ category, percent }) => `${category} ${(percent * 100).toFixed(0)}%`}
label={({ category, percent }) =>
`${category} ${(percent * 100).toFixed(0)}%`
}
labelLine={false}
>
{overview.categoryStats.slice(0, 8).map((_, idx) => (
@@ -162,18 +235,30 @@ export default function Dashboard() {
{overview.sourceStats.map((s, i) => (
<tr key={i}>
<td>
<span className={`source-type-label source-${s.source_type}`}>
{s.source_type === 'alipay' && '支付宝'}
{s.source_type === 'wechat' && '微信支付'}
{s.source_type === 'bank_debit' && '银行借记卡'}
{s.source_type === 'bank_credit' && '银行贷记卡'}
{s.source_type === 'abc' && '农业银行'}
<span
className={`source-type-label source-${s.source_type}`}
>
{s.source_type === "alipay" && "支付宝"}
{s.source_type === "wechat" && "微信支付"}
{s.source_type === "bank_debit" && "银行借记卡"}
{s.source_type === "bank_credit" && "银行贷记卡"}
{s.source_type === "abc" && "农业银行"}
</span>
</td>
<td>{s.count}</td>
<td style={{ color: 'var(--success)' }}>{formatAmount(s.total_income)}</td>
<td style={{ color: 'var(--danger)' }}>{formatAmount(s.total_expense)}</td>
<td className={s.total_income - s.total_expense >= 0 ? 'stat-value income' : 'stat-value expense'}>
<td style={{ color: "var(--success)" }}>
{formatAmount(s.total_income)}
</td>
<td style={{ color: "var(--danger)" }}>
{formatAmount(s.total_expense)}
</td>
<td
className={
s.total_income - s.total_expense >= 0
? "stat-value income"
: "stat-value expense"
}
>
{formatAmount(s.total_income - s.total_expense)}
</td>
</tr>
+83 -58
View File
@@ -1,108 +1,133 @@
const express = require('express');
const { getDB } = require('../db');
const express = require("express");
const { getDB } = require("../db");
const router = express.Router();
// GET /api/stats/overview - 总览统计
router.get('/overview', (req, res) => {
// GET /api/stats/overview — 总览统计(基于 deals)
router.get("/overview", (req, res) => {
const db = getDB();
const { year, month } = req.query;
let dateCondition = '';
let where = "";
const params = [];
if (year) {
dateCondition = 'WHERE strftime(\'%Y\', transaction_date) = ?';
where = "WHERE strftime('%Y', d.deal_date) = ?";
params.push(String(year));
if (month) {
dateCondition += ' AND strftime(\'%m\', transaction_date) = ?';
params.push(String(month).padStart(2, '0'));
where += " AND strftime('%m', d.deal_date) = ?";
params.push(String(month).padStart(2, "0"));
}
}
const stats = db.prepare(`
const stats = db
.prepare(
`
SELECT
COUNT(*) as total_count,
COALESCE(SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END), 0) as total_income,
COALESCE(SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END), 0) as total_expense,
COUNT(CASE WHEN reviewed = 0 AND ABS(amount) >= 100 THEN 1 END) as pending_review,
COUNT(CASE WHEN reviewed = 1 THEN 1 END) as reviewed_count,
COUNT(CASE WHEN matched_transaction_id IS NOT NULL THEN 1 END) as matched_count
FROM transactions
${dateCondition}
`).get(...params);
COALESCE(SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END), 0) as total_income,
COALESCE(SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END), 0) as total_expense,
COUNT(CASE WHEN d.reviewed = 0 AND ABS(d.amount) >= 100 THEN 1 END) as pending_review,
COUNT(CASE WHEN d.reviewed = 1 THEN 1 END) as reviewed_count,
COALESCE(SUM(d.match_count), 0) as matched_count
FROM deals d
${where}
`,
)
.get(...params);
// 按分类统计支出
const categoryStats = db.prepare(`
// 按分类统计支出(from deals)
const catWhere = where
? 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(
`
SELECT
category,
d.category as category,
COUNT(*) as count,
SUM(ABS(amount)) as total_amount,
AVG(ABS(amount)) as avg_amount
FROM transactions
${dateCondition}${dateCondition ? ' AND' : 'WHERE'} direction = 'expense' AND category IS NOT NULL
GROUP BY category
SUM(ABS(d.amount)) as total_amount,
AVG(ABS(d.amount)) as avg_amount
FROM deals d
${catWhere}
GROUP BY d.category
ORDER BY total_amount DESC
`).all(...params);
`,
)
.all(...params);
// 按来源统计
const sourceStats = db.prepare(`
// 按来源统计(通过 deal_transactions 关联 transactions)
const srcWhere = where ? where + "" : "";
const sourceStats = db
.prepare(
`
SELECT
t.source_type,
s.source_name,
COUNT(DISTINCT dt.deal_id) as deal_count,
COUNT(*) as count,
SUM(CASE WHEN t.direction = 'income' THEN t.amount ELSE 0 END) as total_income,
SUM(CASE WHEN t.direction = 'expense' THEN ABS(t.amount) ELSE 0 END) as total_expense
FROM transactions t
FROM deal_transactions dt
JOIN deals d ON d.id = dt.deal_id
JOIN transactions t ON t.id = dt.transaction_id
LEFT JOIN sources s ON s.id = t.source_id
${dateCondition}
${srcWhere}
GROUP BY t.source_type
ORDER BY total_expense DESC
`).all(...params);
`,
)
.all(...params);
res.json({
overview: stats,
categoryStats,
sourceStats
});
res.json({ overview: stats, categoryStats, sourceStats });
});
// GET /api/stats/monthly - 月度趋势
router.get('/monthly', (req, res) => {
// GET /api/stats/monthly — 月度趋势(基于 deals)
router.get("/monthly", (req, res) => {
const db = getDB();
const { months = 12 } = req.query;
const months = Math.abs(parseInt(req.query.months) || 12);
const monthlyData = db.prepare(`
const monthlyData = db
.prepare(
`
SELECT
strftime('%Y-%m', transaction_date) as month,
strftime('%Y-%m', d.deal_date) as month,
COUNT(*) as count,
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
FROM transactions
WHERE transaction_date >= DATE('now', '-${parseInt(months)} months')
GROUP BY strftime('%Y-%m', transaction_date)
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
FROM deals d
WHERE d.deal_date >= DATE('now', ? || ' months')
GROUP BY strftime('%Y-%m', d.deal_date)
ORDER BY month ASC
`).all();
`,
)
.all("-" + months);
res.json(monthlyData);
});
// GET /api/stats/daily - 每日统计
router.get('/daily', (req, res) => {
// GET /api/stats/daily — 每日统计(基于 deals)
router.get("/daily", (req, res) => {
const db = getDB();
const { days = 30 } = req.query;
const days = Math.abs(parseInt(req.query.days) || 30);
const dailyData = db.prepare(`
const dailyData = db
.prepare(
`
SELECT
transaction_date as date,
d.deal_date as date,
COUNT(*) as count,
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
FROM transactions
WHERE transaction_date >= DATE('now', '-${parseInt(days)} days')
GROUP BY transaction_date
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
FROM deals d
WHERE d.deal_date >= DATE('now', ? || ' days')
GROUP BY d.deal_date
ORDER BY date ASC
`).all();
`,
)
.all("-" + days);
res.json(dailyData);
});