Files
reco/server/routes/stats.js
T
fukunee 2c8473e9e0 Rework LLM classification around user categories
Move category CRUD into the config route so renames sync historical deals, feed per-user categories into the LLM prompt, cache clients per user, and drop the separate classify route.
2026-11-15 11:32:26 +08:00

211 lines
6.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const express = require("express");
const { getDB } = require("../db");
const router = express.Router();
// GET /api/stats/overview — 总览统计(基于 deals)
router.get("/overview", (req, res) => {
const db = getDB();
const { year, month, start_date, end_date } = req.query;
// 日期条件:支持任意区间(财年),也保留旧的 year/month
const dateConds = [];
const dateParams = [];
if (start_date) {
dateConds.push("d.deal_date >= ?");
dateParams.push(start_date);
}
if (end_date) {
dateConds.push("d.deal_date <= ?");
dateParams.push(end_date);
}
if (year) {
dateConds.push("strftime('%Y', d.deal_date) = ?");
dateParams.push(String(year));
if (month) {
dateConds.push("strftime('%m', d.deal_date) = ?");
dateParams.push(String(month).padStart(2, "0"));
}
}
let where = "WHERE d.user_id = ?";
const params = [req.userId, ...dateParams];
if (dateConds.length) where += " AND " + dateConds.join(" AND ");
const stats = db
.prepare(
`
SELECT
COUNT(*) as total_count,
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 catWhere =
where +
" AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
const categoryStats = db
.prepare(
`
SELECT
d.category as category,
COUNT(*) as count,
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);
const catBreakWhere =
where +
" AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
const categoryBreakdown = db
.prepare(
`
SELECT
d.category,
COUNT(*) as deal_count,
SUM(CASE WHEN d.direction='income' THEN d.amount ELSE 0 END) as total_income,
SUM(CASE WHEN d.direction='expense' THEN ABS(d.amount) ELSE 0 END) as total_expense
FROM deals d
${catBreakWhere}
GROUP BY d.category
ORDER BY (total_income + total_expense) DESC
`,
)
.all(...params);
const dateCondSql = dateConds.length ? " AND " + dateConds.join(" AND ") : "";
const maxIncomeStmt = db.prepare(
`SELECT id, amount, counterparty, deal_date, ai_description
FROM deals d WHERE d.category=? AND d.direction='income' AND d.user_id=?${dateCondSql}
ORDER BY d.amount DESC LIMIT 1`,
);
const maxExpenseStmt = db.prepare(
`SELECT id, amount, counterparty, deal_date, ai_description
FROM deals d WHERE d.category=? AND d.direction='expense' AND d.user_id=?${dateCondSql}
ORDER BY ABS(d.amount) DESC LIMIT 1`,
);
for (const cat of categoryBreakdown) {
cat.max_income =
maxIncomeStmt.get(cat.category, req.userId, ...dateParams) || null;
cat.max_expense =
maxExpenseStmt.get(cat.category, req.userId, ...dateParams) || null;
}
// 全量日期范围(不受筛选影响),供前端枚举财年
const dateRange = db
.prepare(
"SELECT MIN(deal_date) as min_date, MAX(deal_date) as max_date FROM deals WHERE user_id = ?",
)
.get(req.userId);
res.json({ overview: stats, categoryStats, categoryBreakdown, dateRange });
});
// 解析 categories 查询参数
function parseCategories(query) {
if (!query) return null;
return query
.split(",")
.map((c) => c.trim())
.filter(Boolean);
}
// GET /api/stats/monthly — 月度趋势(支持 ?categories=餐饮,购物 筛选)
router.get("/monthly", (req, res) => {
const db = getDB();
const { start_date, end_date } = req.query;
const cats = parseCategories(req.query.categories);
const conds = ["d.user_id = ?"];
const params = [req.userId];
if (start_date) {
conds.push("d.deal_date >= ?");
params.push(start_date);
}
if (end_date) {
conds.push("d.deal_date <= ?");
params.push(end_date);
}
// 只有显式传了 months 才限制为「最近 N 个月」;
// 不传任何时间参数 = 不限制(全部时间)
if (!start_date && !end_date && req.query.months != null) {
const months = Math.abs(parseInt(req.query.months) || 12);
conds.push("d.deal_date >= DATE('now', ? || ' months')");
params.push("-" + months);
}
if (cats && cats.length > 0) {
conds.push("d.category IN (" + cats.map(() => "?").join(",") + ")");
params.push(...cats);
}
const monthlyData = db
.prepare(
`
SELECT
strftime('%Y-%m', d.deal_date) as month,
COUNT(*) as count,
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 ${conds.join(" AND ")}
GROUP BY strftime('%Y-%m', d.deal_date)
ORDER BY month ASC
`,
)
.all(...params);
res.json(monthlyData);
});
// GET /api/stats/daily — 每日统计(支持 ?categories 筛选)
router.get("/daily", (req, res) => {
const db = getDB();
const days = Math.abs(parseInt(req.query.days) || 30);
const cats = parseCategories(req.query.categories);
let catFilter = "";
const params = ["-" + days, req.userId];
if (cats && cats.length > 0) {
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
params.push(...cats);
}
const dailyData = db
.prepare(
`
SELECT
d.deal_date as date,
COUNT(*) as count,
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') AND d.user_id = ?${catFilter}
GROUP BY d.deal_date
ORDER BY date ASC
`,
)
.all(...params);
res.json(dailyData);
});
module.exports = router;