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.
This commit is contained in:
@@ -1,23 +0,0 @@
|
||||
const express = require("express");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/classify - 对指定交易进行分类
|
||||
router.post("/", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyDeals(ids, req.userId);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
+93
-20
@@ -93,36 +93,109 @@ router.get("/categories", (req, res) => {
|
||||
});
|
||||
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
getDB()
|
||||
.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=? AND user_id=?",
|
||||
)
|
||||
.run(
|
||||
name,
|
||||
keywords ? JSON.stringify(keywords) : null,
|
||||
req.params.id,
|
||||
req.userId,
|
||||
);
|
||||
res.json({ success: true });
|
||||
const current = db
|
||||
.prepare("SELECT * FROM categories WHERE id = ? AND user_id = ?")
|
||||
.get(req.params.id, req.userId);
|
||||
if (!current) return res.status(404).json({ error: "分类不存在" });
|
||||
if (current.is_locked)
|
||||
return res.status(403).json({ error: "内置分类不可修改" });
|
||||
|
||||
const newName = name === undefined ? current.name : String(name).trim();
|
||||
if (!newName) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
|
||||
const affectedIds = [];
|
||||
try {
|
||||
db.transaction(() => {
|
||||
if (newName !== current.name) {
|
||||
const dup = db
|
||||
.prepare(
|
||||
"SELECT id FROM categories WHERE user_id = ? AND name = ? AND id <> ?",
|
||||
)
|
||||
.get(req.userId, newName, req.params.id);
|
||||
if (dup) {
|
||||
const err = new Error("已存在同名分类");
|
||||
err.status = 409;
|
||||
throw err;
|
||||
}
|
||||
// 重命名:同步历史 deal 的分类名
|
||||
for (const row of db
|
||||
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||
.all(req.userId, current.name))
|
||||
affectedIds.push(row.id);
|
||||
db.prepare(
|
||||
"UPDATE deals SET category = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||
).run(newName, req.userId, current.name);
|
||||
}
|
||||
const sets = [];
|
||||
const params = [];
|
||||
if (newName !== current.name) {
|
||||
sets.push("name = ?");
|
||||
params.push(newName);
|
||||
}
|
||||
if (keywords !== undefined) {
|
||||
sets.push("keywords = ?");
|
||||
params.push(JSON.stringify(Array.isArray(keywords) ? keywords : []));
|
||||
}
|
||||
if (sets.length) {
|
||||
db.prepare(
|
||||
`UPDATE categories SET ${sets.join(", ")} WHERE id = ? AND user_id = ?`,
|
||||
).run(...params, req.params.id, req.userId);
|
||||
}
|
||||
})();
|
||||
} catch (err) {
|
||||
return res
|
||||
.status(err.status || 500)
|
||||
.json({ error: err.message || "更新失败" });
|
||||
}
|
||||
|
||||
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||
});
|
||||
|
||||
router.post("/categories", (req, res) => {
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const r = getDB()
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
const trimmed = typeof name === "string" ? name.trim() : "";
|
||||
if (!trimmed) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const dup = db
|
||||
.prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?")
|
||||
.get(req.userId, trimmed);
|
||||
if (dup) return res.status(409).json({ error: "已存在同名分类" });
|
||||
const r = db
|
||||
.prepare(
|
||||
"INSERT INTO categories (name,keywords,parent_id,user_id) VALUES (?,?,?,?)",
|
||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null, req.userId);
|
||||
.run(trimmed, JSON.stringify(keywords || []), req.userId);
|
||||
res.json({ success: true, id: r.lastInsertRowid });
|
||||
});
|
||||
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
getDB()
|
||||
.prepare("DELETE FROM categories WHERE id=? AND user_id=?")
|
||||
.run(req.params.id, req.userId);
|
||||
res.json({ success: true });
|
||||
const db = getDB();
|
||||
const cat = db
|
||||
.prepare("SELECT name, is_locked FROM categories WHERE id = ? AND user_id = ?")
|
||||
.get(req.params.id, req.userId);
|
||||
if (!cat) return res.status(404).json({ error: "分类不存在" });
|
||||
if (cat.is_locked)
|
||||
return res.status(403).json({ error: "内置分类不可删除" });
|
||||
|
||||
const affectedIds = db
|
||||
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||
.all(req.userId, cat.name)
|
||||
.map((r) => r.id);
|
||||
|
||||
db.transaction(() => {
|
||||
// 历史 deal 重置为待分类
|
||||
db.prepare(
|
||||
"UPDATE deals SET category = NULL, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||
).run(req.userId, cat.name);
|
||||
db.prepare("DELETE FROM categories WHERE id = ? AND user_id = ?").run(
|
||||
req.params.id,
|
||||
req.userId,
|
||||
);
|
||||
})();
|
||||
|
||||
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -67,9 +67,14 @@ router.get("/", (req, res) => {
|
||||
"counterparty",
|
||||
"category",
|
||||
"match_count",
|
||||
"abs_amount",
|
||||
];
|
||||
const safeSort = allowedSort.includes(sort_by) ? sort_by : "deal_date";
|
||||
const safeOrder = sort_order === "ASC" ? "ASC" : "DESC";
|
||||
// abs_amount:按金额绝对值排序(大额确认用,收/支混排时按体量从大到小)
|
||||
const sortExpr =
|
||||
safeSort === "abs_amount" ? "ABS(d.amount)" : `d.${safeSort}`;
|
||||
const tieBreaker = safeSort === "abs_amount" ? ", d.id DESC" : "";
|
||||
|
||||
const total = db
|
||||
.prepare(`SELECT COUNT(*) as c FROM deals d ${where}`)
|
||||
@@ -90,7 +95,7 @@ router.get("/", (req, res) => {
|
||||
LEFT JOIN transactions t ON t.id = dt.transaction_id
|
||||
${where}
|
||||
GROUP BY d.id
|
||||
ORDER BY d.${safeSort} ${safeOrder}
|
||||
ORDER BY ${sortExpr} ${safeOrder}${tieBreaker}
|
||||
LIMIT ? OFFSET ?
|
||||
`,
|
||||
)
|
||||
|
||||
+57
-20
@@ -6,20 +6,32 @@ const router = express.Router();
|
||||
// GET /api/stats/overview — 总览统计(基于 deals)
|
||||
router.get("/overview", (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let where = "WHERE d.user_id = ?";
|
||||
const params = [req.userId];
|
||||
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) {
|
||||
where += " AND strftime('%Y', d.deal_date) = ?";
|
||||
params.push(String(year));
|
||||
dateConds.push("strftime('%Y', d.deal_date) = ?");
|
||||
dateParams.push(String(year));
|
||||
if (month) {
|
||||
where += " AND strftime('%m', d.deal_date) = ?";
|
||||
params.push(String(month).padStart(2, "0"));
|
||||
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(
|
||||
`
|
||||
@@ -76,23 +88,33 @@ router.get("/overview", (req, res) => {
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
const dateCondSql = dateConds.length ? " AND " + dateConds.join(" AND ") : "";
|
||||
const maxIncomeStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='income' AND user_id=?
|
||||
ORDER BY amount DESC LIMIT 1`,
|
||||
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 WHERE category=? AND direction='expense' AND user_id=?
|
||||
ORDER BY ABS(amount) DESC LIMIT 1`,
|
||||
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) || null;
|
||||
cat.max_expense = maxExpenseStmt.get(cat.category, req.userId) || null;
|
||||
cat.max_income =
|
||||
maxIncomeStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||
cat.max_expense =
|
||||
maxExpenseStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||
}
|
||||
|
||||
res.json({ overview: stats, categoryStats, categoryBreakdown });
|
||||
// 全量日期范围(不受筛选影响),供前端枚举财年
|
||||
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 查询参数
|
||||
@@ -107,14 +129,29 @@ function parseCategories(query) {
|
||||
// GET /api/stats/monthly — 月度趋势(支持 ?categories=餐饮,购物 筛选)
|
||||
router.get("/monthly", (req, res) => {
|
||||
const db = getDB();
|
||||
const months = Math.abs(parseInt(req.query.months) || 12);
|
||||
const { start_date, end_date } = req.query;
|
||||
const cats = parseCategories(req.query.categories);
|
||||
|
||||
let catFilter = "";
|
||||
const params = ["-" + months, req.userId];
|
||||
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) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
conds.push("d.category IN (" + cats.map(() => "?").join(",") + ")");
|
||||
params.push(...cats);
|
||||
}
|
||||
|
||||
@@ -127,7 +164,7 @@ router.get("/monthly", (req, res) => {
|
||||
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') AND d.user_id = ?${catFilter}
|
||||
WHERE ${conds.join(" AND ")}
|
||||
GROUP BY strftime('%Y-%m', d.deal_date)
|
||||
ORDER BY month ASC
|
||||
`,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyDeals, classifyAllDeals } = require("../services/llm");
|
||||
const { classifyDeals, startClassifyAll, getClassifyStatus } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -111,25 +111,6 @@ router.get("/", (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(req.userId)
|
||||
.map((r) => r.name);
|
||||
if (!cats.length) return res.json({ ids: [], total: 0 });
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats, req.userId);
|
||||
console.log(
|
||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
||||
);
|
||||
res.json({ ids: stale.map((r) => r.id), total: stale.length });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 全量清除后重新对账
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const db = getDB();
|
||||
@@ -225,19 +206,18 @@ router.post("/classify", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all — AI分类全部(并行)
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
||||
try {
|
||||
const result = await classifyAllDeals(req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
||||
);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类全部失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
// POST /api/transactions/classify-all — 启动全量分类(后台执行,前端轮询状态)
|
||||
router.post("/classify-all", (req, res) => {
|
||||
const result = startClassifyAll(req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — started=${result.started}, total=${result.total}`,
|
||||
);
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// GET /api/transactions/classify-status — 全量分类进度
|
||||
router.get("/classify-status", (req, res) => {
|
||||
res.json(getClassifyStatus(req.userId));
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user