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:
+83
-3
@@ -1,7 +1,11 @@
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
|
||||
const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
|
||||
const DB_PATH =
|
||||
process.env.RECO_DB_PATH || path.join(__dirname, "..", "data", "reco.db");
|
||||
|
||||
// 系统兜底分类:所有用户都不允许修改/删除
|
||||
const SYSTEM_LOCKED_CATEGORIES = ["其他杂项"];
|
||||
|
||||
const fs = require("fs");
|
||||
const dataDir = path.join(__dirname, "..", "data");
|
||||
@@ -68,6 +72,7 @@ function initDB() {
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT,
|
||||
is_locked INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -186,6 +191,74 @@ function initDB() {
|
||||
console.error("[Reco] config 迁移失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:分类锁定标记。
|
||||
// 内置基础分类(最初的 1-10 号)和系统兜底分类(其他杂项)不允许修改/删除。
|
||||
try {
|
||||
const catCols = database
|
||||
.prepare("PRAGMA table_info(categories)")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!catCols.includes("is_locked")) {
|
||||
database.exec(
|
||||
"ALTER TABLE categories ADD COLUMN is_locked INTEGER DEFAULT 0",
|
||||
);
|
||||
}
|
||||
database.prepare("UPDATE categories SET is_locked = 1 WHERE id <= 10").run();
|
||||
if (SYSTEM_LOCKED_CATEGORIES.length) {
|
||||
const ph = SYSTEM_LOCKED_CATEGORIES.map(() => "?").join(",");
|
||||
database
|
||||
.prepare(`UPDATE categories SET is_locked = 1 WHERE name IN (${ph})`)
|
||||
.run(...SYSTEM_LOCKED_CATEGORIES);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类锁定初始化失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:合并同名重复分类。
|
||||
// 老用户的历史分类 user_id 为 NULL,之后初始化默认分类时按 user_id 计数为 0,
|
||||
// 于是又插入了一整套默认分类,导致同名分类出现两份。
|
||||
// 合并策略:保留 id 最小的一行(通常是用户手工维护过的),关键词取并集,删除其余行。
|
||||
try {
|
||||
const dupGroups = database
|
||||
.prepare(
|
||||
`SELECT user_id, name, COUNT(*) AS c FROM categories
|
||||
GROUP BY user_id, name HAVING c > 1`,
|
||||
)
|
||||
.all();
|
||||
if (dupGroups.length) {
|
||||
const rowsStmt = database.prepare(
|
||||
"SELECT id, keywords FROM categories WHERE name = ? AND user_id IS ? ORDER BY id",
|
||||
);
|
||||
const setKeywords = database.prepare(
|
||||
"UPDATE categories SET keywords = ? WHERE id = ?",
|
||||
);
|
||||
const delCategory = database.prepare("DELETE FROM categories WHERE id = ?");
|
||||
database.transaction(() => {
|
||||
for (const g of dupGroups) {
|
||||
const rows = rowsStmt.all(g.name, g.user_id);
|
||||
const merged = [];
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const arr = JSON.parse(r.keywords || "[]");
|
||||
if (Array.isArray(arr))
|
||||
for (const k of arr)
|
||||
if (k && !merged.includes(k)) merged.push(k);
|
||||
} catch (e) {}
|
||||
}
|
||||
setKeywords.run(JSON.stringify(merged), rows[0].id);
|
||||
for (const r of rows.slice(1)) delCategory.run(r.id);
|
||||
}
|
||||
})();
|
||||
console.log(`[Reco] 已合并 ${dupGroups.length} 组重复分类`);
|
||||
}
|
||||
// 唯一索引:同一用户下不允许同名分类
|
||||
database.exec(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_categories_user_name ON categories(user_id, name)",
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类去重失败:", e.message);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
@@ -198,7 +271,7 @@ function initDefaultCategories(userId) {
|
||||
if (existing > 0) return;
|
||||
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||
"INSERT OR IGNORE INTO categories (name, keywords, user_id, is_locked) VALUES (?, ?, ?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
@@ -222,7 +295,14 @@ function initDefaultCategories(userId) {
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1], userId));
|
||||
defaults.forEach((c) =>
|
||||
ins.run(
|
||||
c[0],
|
||||
c[1],
|
||||
userId,
|
||||
SYSTEM_LOCKED_CATEGORIES.includes(c[0]) ? 1 : 0,
|
||||
),
|
||||
);
|
||||
})();
|
||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ process.noDeprecation = true;
|
||||
|
||||
const uploadRoutes = require("./routes/upload");
|
||||
const transactionRoutes = require("./routes/transactions");
|
||||
const classifyRoutes = require("./routes/classify");
|
||||
const statsRoutes = require("./routes/stats");
|
||||
const configRoutes = require("./routes/config");
|
||||
const dealsRoutes = require("./routes/deals");
|
||||
@@ -31,7 +30,6 @@ app.use(authMiddleware);
|
||||
// 业务 API routes(受认证保护)
|
||||
app.use("/api/upload", uploadRoutes);
|
||||
app.use("/api/transactions", transactionRoutes);
|
||||
app.use("/api/classify", classifyRoutes);
|
||||
app.use("/api/stats", statsRoutes);
|
||||
app.use("/api/config", configRoutes);
|
||||
app.use("/api/deals", dealsRoutes);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+331
-126
@@ -1,5 +1,9 @@
|
||||
const BATCH_SIZE = 30;
|
||||
const CONCURRENCY = 5;
|
||||
const CONCURRENCY = 8;
|
||||
// 单次 LLM 响应的 token 上限。
|
||||
// 注意:reasoning 模型(如 deepseek-flash/reasoner)会先消耗 reasoning tokens,
|
||||
// 该预算如果太小,content 会被截断为空,导致分类静默退回规则匹配。
|
||||
const MAX_TOKENS = Number(process.env.LLM_MAX_TOKENS) || 16000;
|
||||
|
||||
/* ============================== 配置管理 ============================== */
|
||||
function loadUserLLMConfig(userId) {
|
||||
@@ -11,48 +15,82 @@ function loadUserLLMConfig(userId) {
|
||||
return row ? JSON.parse(row.value) : {};
|
||||
}
|
||||
|
||||
const clientCache = new Map(); // userId -> { sig, client }
|
||||
|
||||
function getOpenAIClient(userId) {
|
||||
const cfg = loadUserLLMConfig(userId);
|
||||
if (!cfg.llm_api_key) {
|
||||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||||
return null;
|
||||
}
|
||||
// 配置未变时复用 client,避免每批都重新创建连接池
|
||||
const sig = [
|
||||
cfg.llm_api_key,
|
||||
cfg.llm_base_url || "",
|
||||
cfg.llm_model || "",
|
||||
].join("|");
|
||||
const cached = clientCache.get(userId);
|
||||
if (cached && cached.sig === sig) return cached.client;
|
||||
|
||||
const { OpenAI } = require("openai");
|
||||
const client = new OpenAI({
|
||||
apiKey: cfg.llm_api_key,
|
||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||
});
|
||||
client._model = cfg.llm_model || "gpt-4o-mini";
|
||||
clientCache.set(userId, { sig, client });
|
||||
return client;
|
||||
}
|
||||
|
||||
/* ============================== 分类加载 ============================== */
|
||||
function loadCategories(userId) {
|
||||
const { getDB } = require("../db");
|
||||
return getDB()
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((c) => {
|
||||
let keywords = [];
|
||||
try {
|
||||
keywords = JSON.parse(c.keywords || "[]");
|
||||
} catch (e) {}
|
||||
return { id: c.id, name: c.name, keywords };
|
||||
});
|
||||
}
|
||||
|
||||
/* ============================== Prompt 构建 ============================== */
|
||||
function buildPrompt(deals, userId) {
|
||||
function buildPrompt(deals, userId, cats) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
if (!cats) cats = loadCategories(userId);
|
||||
|
||||
const cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const catList = cats
|
||||
.map(
|
||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
||||
)
|
||||
.map((c) => c.name + "(" + c.keywords.join("、") + ")")
|
||||
.join("\n");
|
||||
|
||||
// 一次查出整批 deal 的关联交易,避免逐条查询(N+1)
|
||||
const dealIds = deals.map((d) => d.id);
|
||||
const txByDeal = new Map();
|
||||
if (dealIds.length) {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT dt.deal_id, t.description, t.counterparty, t.source_type, t.notes
|
||||
FROM deal_transactions dt
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
WHERE dt.deal_id IN (${dealIds.map(() => "?").join(",")})
|
||||
`,
|
||||
)
|
||||
.all(...dealIds);
|
||||
for (const r of rows) {
|
||||
if (!txByDeal.has(r.deal_id)) txByDeal.set(r.deal_id, []);
|
||||
txByDeal.get(r.deal_id).push(r);
|
||||
}
|
||||
}
|
||||
|
||||
let txTotal = 0;
|
||||
const dealList = deals
|
||||
.map((d, i) => {
|
||||
const txs = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.description, t.counterparty, t.source_type, t.notes
|
||||
FROM deal_transactions dt
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
WHERE dt.deal_id = ?
|
||||
`,
|
||||
)
|
||||
.all(d.id);
|
||||
const txs = txByDeal.get(d.id) || [];
|
||||
|
||||
let extra = "";
|
||||
if (txs.length > 0) {
|
||||
@@ -79,7 +117,7 @@ function buildPrompt(deals, userId) {
|
||||
}
|
||||
|
||||
return (
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${Number(d.amount).toFixed(2)}元` +
|
||||
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
||||
);
|
||||
})
|
||||
@@ -123,8 +161,89 @@ function extractJsonArray(text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ============================== 单次 LLM 请求 ============================== */
|
||||
// 返回 { pairs, finish, contentLen, reasoning },pairs 为 [{ deal, item }]
|
||||
async function requestLLMClassification(deals, client, userId, cats, maxTokens) {
|
||||
const prompt = buildPrompt(deals, userId, cats);
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: "你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: maxTokens,
|
||||
});
|
||||
|
||||
const choice = response.choices?.[0];
|
||||
const content = choice?.message?.content || "";
|
||||
const results = extractJsonArray(content);
|
||||
const pairs = [];
|
||||
if (results && results.length) {
|
||||
for (const item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) pairs.push({ deal: d, item });
|
||||
}
|
||||
}
|
||||
return {
|
||||
pairs,
|
||||
finish: choice?.finish_reason,
|
||||
contentLen: content.length,
|
||||
reasoning: response.usage?.completion_tokens_details?.reasoning_tokens,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求 LLM 分类,并对 reasoning 模型“思考吃光 max_tokens → content 被截断为空”
|
||||
* 的情况自愈:把批量对半拆分、顺序重试(深度上限 6,最细拆到单条)。
|
||||
* 返回 [{ deal, item }]。
|
||||
*/
|
||||
async function classifyViaLLM(deals, client, userId, cats, depth) {
|
||||
const r = await requestLLMClassification(
|
||||
deals,
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
MAX_TOKENS,
|
||||
);
|
||||
if (r.pairs.length) return r.pairs;
|
||||
|
||||
if (r.finish === "length" && deals.length > 1 && depth < 6) {
|
||||
const mid = Math.ceil(deals.length / 2);
|
||||
console.warn(
|
||||
`[Reco] classifyDeals — LLM 输出被截断 (reasoning=${r.reasoning ?? "-"}, ` +
|
||||
`max_tokens=${MAX_TOKENS}),拆分为 ${mid}+${deals.length - mid} 重试`,
|
||||
);
|
||||
const a = await classifyViaLLM(
|
||||
deals.slice(0, mid),
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
depth + 1,
|
||||
);
|
||||
const b = await classifyViaLLM(
|
||||
deals.slice(mid),
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
depth + 1,
|
||||
);
|
||||
return [...a, ...b];
|
||||
}
|
||||
|
||||
console.warn(
|
||||
`[Reco] classifyDeals — LLM 返回不可解析,退回规则 (finish=${r.finish}, ` +
|
||||
`content=${r.contentLen}字, reasoning=${r.reasoning ?? "-"}, ` +
|
||||
`max_tokens=${MAX_TOKENS})`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds, userId) {
|
||||
async function classifyDeals(dealIds, userId, opts = {}) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
@@ -141,157 +260,243 @@ async function classifyDeals(dealIds, userId) {
|
||||
.all(...ids, userId);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const cats = opts.cats || loadCategories(userId);
|
||||
const client = getOpenAIClient(userId);
|
||||
if (client) {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const prompt = buildPrompt(deals, userId);
|
||||
const t0 = Date.now();
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 4000,
|
||||
});
|
||||
|
||||
const rawContent = response.choices[0]?.message?.content || "";
|
||||
const results = extractJsonArray(rawContent);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const pairs = await classifyViaLLM(deals, client, userId, cats, 0);
|
||||
if (pairs.length) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
d.id,
|
||||
);
|
||||
}
|
||||
for (const { deal, item } of pairs) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
deal.id,
|
||||
);
|
||||
}
|
||||
})();
|
||||
// 截断到单条仍失败的个别 deal,用规则补齐
|
||||
const covered = new Set(pairs.map((p) => p.deal.id));
|
||||
const missing = deals.filter((d) => !covered.has(d.id));
|
||||
let filled = 0;
|
||||
if (missing.length) {
|
||||
const r = classifyDealsByRules(missing, userId, cats);
|
||||
filled = r.classified;
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
`[Reco] classifyDeals — 完成 ${pairs.length + filled} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
);
|
||||
return { classified: results.length, source: "llm" };
|
||||
return { classified: pairs.length + filled, source: "llm" };
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||
}
|
||||
}
|
||||
return classifyDealsByRules(deals, userId);
|
||||
return classifyDealsByRules(deals, userId, cats);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals, userId) {
|
||||
// 关键词打分;category=null/score=0 表示没命中任何关键词
|
||||
function bestRuleCategory(deal, cats) {
|
||||
const text = (
|
||||
(deal.description || "") +
|
||||
" " +
|
||||
(deal.counterparty || "")
|
||||
).toLowerCase();
|
||||
let category = null;
|
||||
let score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of c.keywords) {
|
||||
if (kw && text.includes(kw.toLowerCase())) s++;
|
||||
}
|
||||
if (s > score) {
|
||||
score = s;
|
||||
category = c.name;
|
||||
}
|
||||
}
|
||||
return { category, score };
|
||||
}
|
||||
|
||||
function buildRuleDescription(deal) {
|
||||
const income = parseFloat(deal.amount) >= 0;
|
||||
const desc =
|
||||
(income ? "收到" : "向") +
|
||||
(deal.counterparty || "对方") +
|
||||
(income ? "" : "支付") +
|
||||
Math.abs(Number(deal.amount) || 0).toFixed(2) +
|
||||
"元";
|
||||
return desc.substring(0, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则分类并写库。
|
||||
* onlyMatched=false:全部写入,未命中归入「其他杂项」(纯规则兑底)。
|
||||
* onlyMatched=true :只写命中关键词的,未命中的返回给 LLM 处理。
|
||||
*/
|
||||
function applyRules(deals, cats, { onlyMatched = false } = {}) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
let matched = 0;
|
||||
let unclassified = 0;
|
||||
const unmatched = [];
|
||||
// 兜底分类:优先「其他杂项」;用户删掉该分类后就不再强行归类
|
||||
const hasFallback = cats.some((c) => c.name === "其他杂项");
|
||||
db.transaction(() => {
|
||||
for (const d of deals) {
|
||||
const text = (d.description + " " + d.counterparty).toLowerCase();
|
||||
let best = "其他杂项",
|
||||
score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of JSON.parse(c.keywords || "[]")) {
|
||||
if (kw && text.includes(kw.toLowerCase())) s++;
|
||||
}
|
||||
if (s > score) {
|
||||
score = s;
|
||||
best = c.name;
|
||||
}
|
||||
const { category, score } = bestRuleCategory(d, cats);
|
||||
if (!category && onlyMatched) {
|
||||
unmatched.push(d);
|
||||
continue;
|
||||
}
|
||||
const directionText = parseFloat(d.amount) >= 0 ? "收到" : "向";
|
||||
const actionText = parseFloat(d.amount) >= 0 ? "" : "支付";
|
||||
const desc =
|
||||
directionText +
|
||||
(d.counterparty || "对方") +
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
"元";
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
const finalCategory = category || (hasFallback ? "其他杂项" : null);
|
||||
if (!finalCategory) {
|
||||
unclassified++;
|
||||
continue;
|
||||
}
|
||||
upd.run(
|
||||
finalCategory,
|
||||
buildRuleDescription(d),
|
||||
score > 0 ? 0.7 : 0.3,
|
||||
finalCategory,
|
||||
d.id,
|
||||
);
|
||||
if (score > 0) matched++;
|
||||
}
|
||||
})();
|
||||
return { matched, unmatched, unclassified };
|
||||
}
|
||||
|
||||
function classifyDealsByRules(deals, userId, cats) {
|
||||
if (!cats) cats = loadCategories(userId);
|
||||
const t0 = Date.now();
|
||||
const { matched, unclassified } = applyRules(deals, cats, {
|
||||
onlyMatched: false,
|
||||
});
|
||||
const classified = deals.length - unclassified;
|
||||
if (unclassified > 0) {
|
||||
console.warn(
|
||||
`[Reco] classifyDealsByRules — ${unclassified} 条无关键词命中且无「其他杂项」兜底,保持待分类`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
||||
`[Reco] classifyDealsByRules — ${classified}/${deals.length} 条(命中 ${matched}), ${Date.now() - t0}ms, 来源: rules`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
return { classified, source: "rules" };
|
||||
}
|
||||
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
async function classifyAllDeals(userId, cats, stale, job) {
|
||||
const t0 = Date.now();
|
||||
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((r) => r.name);
|
||||
// 1) 规则优先:命中关键词的直接定,只有没命中的才交给 LLM
|
||||
const { matched, unmatched } = applyRules(stale, cats, { onlyMatched: true });
|
||||
job.done = matched;
|
||||
if (matched > 0) job.source = "rules";
|
||||
console.log(
|
||||
`[Reco] classifyAll — 规则命中 ${matched}/${stale.length},剩余 ${unmatched.length} 交 LLM`,
|
||||
);
|
||||
|
||||
if (!cats.length) {
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
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, userId);
|
||||
|
||||
if (!stale.length) {
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
|
||||
let totalClassified = 0;
|
||||
let source = "rules";
|
||||
const tStart = Date.now();
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
chunk.map((b) => classifyDeals(b, userId)),
|
||||
);
|
||||
for (const r of results) {
|
||||
totalClassified += r.classified;
|
||||
if (r.source === "llm") source = "llm";
|
||||
// 2) LLM 处理未命中的(分批 + 并发)
|
||||
if (unmatched.length) {
|
||||
const batches = [];
|
||||
for (let i = 0; i < unmatched.length; i += BATCH_SIZE) {
|
||||
batches.push(unmatched.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const group = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
group.map((b) => classifyDeals(b.map((d) => d.id), userId, { cats })),
|
||||
);
|
||||
for (const r of results) {
|
||||
job.done += r.classified || 0;
|
||||
if (r.source === "llm") job.source = "llm";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
||||
`[Reco] classifyAll — 完成 ${job.done}/${stale.length} 条, 来源: ${job.source}, ${Date.now() - t0}ms`,
|
||||
);
|
||||
}
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
const runningJobs = new Map(); // userId -> { total, done, source, startedAt }
|
||||
|
||||
function getStaleDeals(userId, cats) {
|
||||
const { getDB } = require("../db");
|
||||
const names = cats.map((c) => c.name);
|
||||
if (!names.length) return [];
|
||||
const ph = names.map(() => "?").join(",");
|
||||
return getDB()
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...names, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动全量分类:后台执行、立即返回,前端轮询 classify-status 拿进度。
|
||||
* 同一用户已在跑时重复点击直接返回当前任务状态。
|
||||
*/
|
||||
function startClassifyAll(userId) {
|
||||
const running = runningJobs.get(userId);
|
||||
if (running) {
|
||||
return {
|
||||
started: false,
|
||||
running: true,
|
||||
total: running.total,
|
||||
done: running.done,
|
||||
};
|
||||
}
|
||||
|
||||
const cats = loadCategories(userId);
|
||||
if (!cats.length) return { started: false, running: false, total: 0, done: 0 };
|
||||
|
||||
const stale = getStaleDeals(userId, cats);
|
||||
if (!stale.length) return { started: false, running: false, total: 0, done: 0 };
|
||||
|
||||
const job = {
|
||||
total: stale.length,
|
||||
done: 0,
|
||||
source: "rules",
|
||||
startedAt: Date.now(),
|
||||
};
|
||||
runningJobs.set(userId, job);
|
||||
classifyAllDeals(userId, cats, stale, job)
|
||||
.catch((e) => console.error("[Reco] classifyAll 后台任务失败:", e))
|
||||
.finally(() => runningJobs.delete(userId));
|
||||
|
||||
return { started: true, running: true, total: job.total, done: 0 };
|
||||
}
|
||||
|
||||
function getClassifyStatus(userId) {
|
||||
const job = runningJobs.get(userId);
|
||||
if (!job) return { running: false, total: 0, done: 0, source: null };
|
||||
return {
|
||||
running: true,
|
||||
total: job.total,
|
||||
done: job.done,
|
||||
source: job.source,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
classifyDeals,
|
||||
classifyAllDeals,
|
||||
startClassifyAll,
|
||||
getClassifyStatus,
|
||||
getOpenAIClient,
|
||||
buildPrompt,
|
||||
loadCategories,
|
||||
BATCH_SIZE,
|
||||
CONCURRENCY,
|
||||
MAX_TOKENS,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user