Add user authentication with JWT login and registration
This commit is contained in:
+99
-34
@@ -22,6 +22,15 @@ function initDB() {
|
||||
const database = getDB();
|
||||
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sources (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_type TEXT NOT NULL,
|
||||
@@ -102,6 +111,31 @@ function initDB() {
|
||||
CREATE INDEX IF NOT EXISTS idx_dt_deal ON deal_transactions(deal_id);
|
||||
`);
|
||||
|
||||
// 兼容旧库:为所有业务表添加 user_id 字段
|
||||
const tables = ["sources", "transactions", "deals", "categories"];
|
||||
for (const table of tables) {
|
||||
try {
|
||||
const cols = database
|
||||
.prepare("PRAGMA table_info(" + table + ")")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!cols.includes("user_id")) {
|
||||
database.exec(
|
||||
"ALTER TABLE " +
|
||||
table +
|
||||
" ADD COLUMN user_id INTEGER REFERENCES users(id)",
|
||||
);
|
||||
database.exec(
|
||||
"CREATE INDEX IF NOT EXISTS idx_" +
|
||||
table +
|
||||
"_user ON " +
|
||||
table +
|
||||
"(user_id)",
|
||||
);
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// 兼容旧库:为 deals 表添加新字段
|
||||
try {
|
||||
const dealCols = database
|
||||
@@ -111,9 +145,11 @@ function initDB() {
|
||||
const newCols = [
|
||||
["direction", "TEXT"],
|
||||
["category", "TEXT"],
|
||||
["ai_category", "TEXT"],
|
||||
["ai_description", "TEXT"],
|
||||
["ai_confidence", "REAL"],
|
||||
["reviewed", "INTEGER DEFAULT 0"],
|
||||
["review_notes", "TEXT"],
|
||||
["reviewed_at", "DATETIME"],
|
||||
["tags", "TEXT"],
|
||||
["updated_at", "DATETIME"],
|
||||
@@ -124,42 +160,71 @@ function initDB() {
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// 仅首次初始化默认分类
|
||||
const catCount = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories")
|
||||
.get().c;
|
||||
if (catCount === 0) {
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords) VALUES (?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[
|
||||
"交通出行",
|
||||
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
|
||||
],
|
||||
[
|
||||
"购物消费",
|
||||
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
|
||||
],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1]));
|
||||
})();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
// 兼容旧库:config 表 key PRIMARY KEY -> id + UNIQUE(key,user_id)
|
||||
try {
|
||||
const cfgCols = database
|
||||
.prepare("PRAGMA table_info(config)")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!cfgCols.includes("id")) {
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS config_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
user_id INTEGER REFERENCES users(id),
|
||||
UNIQUE(key, user_id)
|
||||
);
|
||||
INSERT OR IGNORE INTO config_new (key, value, user_id)
|
||||
SELECT key, value, NULL FROM config;
|
||||
DROP TABLE config;
|
||||
ALTER TABLE config_new RENAME TO config;
|
||||
`);
|
||||
console.log("[Reco] config 表已迁移为 id+UNIQUE(key,user_id)");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Reco] config 迁移失败:", e.message);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB };
|
||||
// 为新用户创建默认分类
|
||||
function initDefaultCategories(userId) {
|
||||
const database = getDB();
|
||||
const existing = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories WHERE user_id = ?")
|
||||
.get(userId).c;
|
||||
if (existing > 0) return;
|
||||
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[
|
||||
"交通出行",
|
||||
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
|
||||
],
|
||||
[
|
||||
"购物消费",
|
||||
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
|
||||
],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1], userId));
|
||||
})();
|
||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB, initDefaultCategories };
|
||||
|
||||
+9
-1
@@ -12,6 +12,8 @@ const classifyRoutes = require("./routes/classify");
|
||||
const statsRoutes = require("./routes/stats");
|
||||
const configRoutes = require("./routes/config");
|
||||
const dealsRoutes = require("./routes/deals");
|
||||
const authRoutes = require("./routes/auth");
|
||||
const { authMiddleware } = require("./middleware/auth");
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
@@ -20,7 +22,13 @@ const PORT = process.env.PORT || 3001;
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: "50mb" }));
|
||||
|
||||
// API routes
|
||||
// Auth routes(不受认证中间件限制)
|
||||
app.use("/api/auth", authRoutes);
|
||||
|
||||
// 全局认证中间件(auth 路由已在白名单中放行)
|
||||
app.use(authMiddleware);
|
||||
|
||||
// 业务 API routes(受认证保护)
|
||||
app.use("/api/upload", uploadRoutes);
|
||||
app.use("/api/transactions", transactionRoutes);
|
||||
app.use("/api/classify", classifyRoutes);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const JWT_SECRET =
|
||||
process.env.JWT_SECRET || "reco-jwt-secret-change-in-production";
|
||||
const JWT_EXPIRES_IN = "7d";
|
||||
|
||||
// 无需认证的公开路由
|
||||
const PUBLIC_PATHS = [
|
||||
"/api/auth/login",
|
||||
"/api/auth/register",
|
||||
"/api/auth/health",
|
||||
];
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
// 白名单放行
|
||||
if (
|
||||
PUBLIC_PATHS.includes(req.path) ||
|
||||
req.path.startsWith("/api/auth/health")
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith("Bearer ")) {
|
||||
return res.status(401).json({ error: "请先登录" });
|
||||
}
|
||||
|
||||
try {
|
||||
const token = header.split(" ")[1];
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.userId = decoded.userId;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: "登录已过期,请重新登录" });
|
||||
}
|
||||
}
|
||||
|
||||
function signToken(userId) {
|
||||
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||
}
|
||||
|
||||
module.exports = { authMiddleware, signToken, JWT_SECRET };
|
||||
@@ -0,0 +1,112 @@
|
||||
const express = require("express");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const { getDB, initDefaultCategories } = require("../db");
|
||||
const { signToken } = require("../middleware/auth");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/auth/register — 开放注册
|
||||
router.post("/register", (req, res) => {
|
||||
try {
|
||||
const { username, password, nickname } = req.body;
|
||||
|
||||
// 校验
|
||||
if (!username || username.length < 3 || username.length > 32) {
|
||||
return res.status(400).json({ error: "用户名需 3-32 个字符" });
|
||||
}
|
||||
if (!password || password.length < 6) {
|
||||
return res.status(400).json({ error: "密码至少 6 个字符" });
|
||||
}
|
||||
|
||||
const db = getDB();
|
||||
|
||||
// 查重
|
||||
const exists = db
|
||||
.prepare("SELECT id FROM users WHERE username = ?")
|
||||
.get(username);
|
||||
if (exists) {
|
||||
return res.status(409).json({ error: "用户名已存在" });
|
||||
}
|
||||
|
||||
// 哈希密码 & 插入
|
||||
const hashed = bcrypt.hashSync(password, 10);
|
||||
const result = db
|
||||
.prepare(
|
||||
"INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(username, hashed, nickname || username);
|
||||
|
||||
const userId = result.lastInsertRowid;
|
||||
|
||||
// 为新用户初始化默认分类
|
||||
initDefaultCategories(userId);
|
||||
|
||||
// 签发 Token
|
||||
const token = signToken(userId);
|
||||
|
||||
console.log(`[Reco] 新用户注册: ${username} (id=${userId})`);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
user: { id: userId, username, nickname: nickname || username },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 注册失败:", err);
|
||||
res.status(500).json({ error: "注册失败,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/login — 登录
|
||||
router.post("/login", (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: "请输入用户名和密码" });
|
||||
}
|
||||
|
||||
const db = getDB();
|
||||
const user = db
|
||||
.prepare("SELECT * FROM users WHERE username = ?")
|
||||
.get(username);
|
||||
|
||||
if (!user || !bcrypt.compareSync(password, user.password)) {
|
||||
return res.status(401).json({ error: "用户名或密码错误" });
|
||||
}
|
||||
|
||||
const token = signToken(user.id);
|
||||
|
||||
console.log(`[Reco] 用户登录: ${username} (id=${user.id})`);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
nickname: user.nickname || user.username,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 登录失败:", err);
|
||||
res.status(500).json({ error: "登录失败,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/auth/me — 获取当前用户信息
|
||||
router.get("/me", (req, res) => {
|
||||
try {
|
||||
const db = getDB();
|
||||
// 注意:这个路由需要通过中间件手动验证,因为它不在白名单
|
||||
const user = db
|
||||
.prepare("SELECT id, username, nickname, created_at FROM users WHERE id = ?")
|
||||
.get(req.userId);
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: "用户不存在" });
|
||||
}
|
||||
res.json(user);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: "获取用户信息失败" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -12,7 +12,7 @@ router.post("/", async (req, res) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
const result = await classifyDeals(ids, req.userId);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
|
||||
+70
-111
@@ -1,39 +1,65 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const {
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
getOpenAIClient,
|
||||
resetClient,
|
||||
} = require("../services/llm");
|
||||
const router = express.Router();
|
||||
|
||||
// 从 DB 读取当前用户的 LLM 配置
|
||||
function loadUserLLMConfig(userId) {
|
||||
const db = getDB();
|
||||
const row = db
|
||||
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", userId);
|
||||
return row ? JSON.parse(row.value) : {};
|
||||
}
|
||||
|
||||
// 为当前用户创建 LLM 客户端
|
||||
function getUserLLMClient(userId) {
|
||||
const cfg = loadUserLLMConfig(userId);
|
||||
if (!cfg.llm_api_key) return null;
|
||||
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";
|
||||
return client;
|
||||
}
|
||||
|
||||
// GET /api/config
|
||||
router.get("/", (req, res) => {
|
||||
res.json(loadConfig());
|
||||
res.json(loadUserLLMConfig(req.userId));
|
||||
});
|
||||
|
||||
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
|
||||
// PUT /api/config
|
||||
router.put("/", (req, res) => {
|
||||
const cfg = { ...loadConfig(), ...req.body };
|
||||
saveConfig(cfg);
|
||||
resetClient();
|
||||
const db = getDB();
|
||||
const value = JSON.stringify(req.body);
|
||||
|
||||
const row = db
|
||||
.prepare("SELECT id FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", req.userId);
|
||||
if (row) {
|
||||
db.prepare("UPDATE config SET value = ? WHERE id = ?").run(value, row.id);
|
||||
} else {
|
||||
db.prepare("INSERT INTO config (key, value, user_id) VALUES (?, ?, ?)").run(
|
||||
"llm_config",
|
||||
value,
|
||||
req.userId,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
console.log("[Reco] === LLM 连接测试 ===");
|
||||
const cfg = loadConfig();
|
||||
console.log(
|
||||
" API Key:",
|
||||
cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + "..." : "(无)",
|
||||
);
|
||||
console.log(" Base URL:", cfg.llm_base_url || "默认");
|
||||
console.log(" Model:", cfg.llm_model || "默认");
|
||||
const client = getUserLLMClient(req.userId);
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (!client) return res.status(400).json({ error: "请先配置 LLM API Key" });
|
||||
if (!client) {
|
||||
return res.status(400).json({ error: "请先配置 LLM API Key" });
|
||||
}
|
||||
|
||||
console.log(" Model:", client._model);
|
||||
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
@@ -59,111 +85,44 @@ router.post("/test-llm", async (req, res) => {
|
||||
|
||||
// Categories
|
||||
router.get("/categories", (req, res) => {
|
||||
res.json(getDB().prepare("SELECT * FROM categories ORDER BY id").all());
|
||||
res.json(
|
||||
getDB()
|
||||
.prepare("SELECT * FROM categories WHERE user_id = ? ORDER BY id")
|
||||
.all(req.userId),
|
||||
);
|
||||
});
|
||||
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
const db = getDB();
|
||||
|
||||
// 获取旧名称,用于级联更新 deals
|
||||
const oldCat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const oldName = oldCat?.name;
|
||||
|
||||
db.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?",
|
||||
).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
|
||||
// 如果名称变更,级联更新 deals 中的分类名
|
||||
let affectedDeals = 0;
|
||||
if (name && oldName && name !== oldName) {
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=? WHERE category=?")
|
||||
.run(name, oldName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=? WHERE ai_category=?")
|
||||
.run(name, oldName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
console.log(
|
||||
`[Reco] 分类重命名: "${oldName}" -> "${name}", 影响 ${affectedDeals} 条 deal`,
|
||||
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, affectedDeals });
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.post("/categories", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const r = getDB()
|
||||
.prepare("INSERT INTO categories (name,keywords) VALUES (?,?)")
|
||||
.run(name, JSON.stringify(keywords || []));
|
||||
.prepare(
|
||||
"INSERT INTO categories (name,keywords,parent_id,user_id) VALUES (?,?,?,?)",
|
||||
)
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null, req.userId);
|
||||
res.json({ success: true, id: r.lastInsertRowid });
|
||||
});
|
||||
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
// 获取分类名,用于清理 deals 引用
|
||||
const cat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const catName = cat?.name;
|
||||
|
||||
// 删除分类
|
||||
db.prepare("DELETE FROM categories WHERE id=?").run(req.params.id);
|
||||
|
||||
// 将使用该分类的 deals 置为待重分类状态
|
||||
let affectedDeals = 0;
|
||||
const affectedIds = [];
|
||||
if (catName) {
|
||||
const deals1 = db
|
||||
.prepare("SELECT id FROM deals WHERE category=?")
|
||||
.all(catName);
|
||||
const deals2 = db
|
||||
.prepare("SELECT id FROM deals WHERE ai_category=? AND category!=?")
|
||||
.all(catName, catName);
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=NULL WHERE category=?")
|
||||
.run(catName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=NULL WHERE ai_category=?")
|
||||
.run(catName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
// 收集受影响的 deal ID(去重)
|
||||
const idSet = new Set();
|
||||
for (const d of deals1) idSet.add(d.id);
|
||||
for (const d of deals2) idSet.add(d.id);
|
||||
for (const id of idSet) affectedIds.push(id);
|
||||
console.log(
|
||||
`[Reco] 删除分类: "${catName}", 影响 ${affectedDeals} 条 deal (${affectedIds.length} 条唯一 deal)`,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
affectedDeals,
|
||||
affectedIds,
|
||||
categoryName: catName,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/config/categories/reclassify-affected — 重分类受影响的 deals
|
||||
router.post("/categories/reclassify-affected", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供deal ID列表" });
|
||||
}
|
||||
try {
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
const result = await classifyDeals(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 重分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
getDB()
|
||||
.prepare("DELETE FROM categories WHERE id=? AND user_id=?")
|
||||
.run(req.params.id, req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+13
-11
@@ -21,8 +21,8 @@ router.get("/", (req, res) => {
|
||||
} = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
const conditions = ["d.user_id = ?"];
|
||||
const params = [req.userId];
|
||||
if (start_date) {
|
||||
conditions.push("d.deal_date >= ?");
|
||||
params.push(start_date);
|
||||
@@ -139,7 +139,6 @@ router.put("/:id", (req, res) => {
|
||||
params.push(reviewed);
|
||||
if (reviewed) sets.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
|
||||
if (tags !== undefined) {
|
||||
sets.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
@@ -147,9 +146,10 @@ router.put("/:id", (req, res) => {
|
||||
if (!sets.length) return res.status(400).json({ error: "无更新字段" });
|
||||
sets.push("updated_at = CURRENT_TIMESTAMP");
|
||||
params.push(req.params.id);
|
||||
db.prepare("UPDATE deals SET " + sets.join(", ") + " WHERE id = ?").run(
|
||||
...params,
|
||||
);
|
||||
params.push(req.userId);
|
||||
db.prepare(
|
||||
"UPDATE deals SET " + sets.join(", ") + " WHERE id = ? AND user_id = ?",
|
||||
).run(...params);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
@@ -162,16 +162,18 @@ router.post("/batch-confirm", (req, res) => {
|
||||
}
|
||||
const ph = ids.map(() => "?").join(",");
|
||||
db.prepare(
|
||||
`UPDATE deals SET reviewed=1, reviewed_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id IN (${ph})`,
|
||||
).run(...ids);
|
||||
`UPDATE deals SET reviewed=1, reviewed_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id IN (${ph}) AND user_id = ?`,
|
||||
).run(...ids, req.userId);
|
||||
res.json({ success: true, confirmed: ids.length });
|
||||
});
|
||||
|
||||
// POST /api/deals/clear
|
||||
// POST /api/deals/clear — 清除当前用户所有 deals
|
||||
router.post("/clear", (req, res) => {
|
||||
const db = getDB();
|
||||
db.prepare("DELETE FROM deal_transactions").run();
|
||||
db.prepare("DELETE FROM deals").run();
|
||||
db.prepare(
|
||||
"DELETE FROM deal_transactions WHERE deal_id IN (SELECT id FROM deals WHERE user_id = ?)",
|
||||
).run(req.userId);
|
||||
db.prepare("DELETE FROM deals WHERE user_id = ?").run(req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+70
-44
@@ -8,11 +8,11 @@ router.get("/overview", (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let where = "";
|
||||
const params = [];
|
||||
let where = "WHERE d.user_id = ?";
|
||||
const params = [req.userId];
|
||||
|
||||
if (year) {
|
||||
where = "WHERE strftime('%Y', d.deal_date) = ?";
|
||||
where += " AND strftime('%Y', d.deal_date) = ?";
|
||||
params.push(String(year));
|
||||
if (month) {
|
||||
where += " AND strftime('%m', d.deal_date) = ?";
|
||||
@@ -22,124 +22,150 @@ router.get("/overview", (req, res) => {
|
||||
|
||||
const stats = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
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}`,
|
||||
FROM deals d
|
||||
${where}
|
||||
`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
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 catWhere =
|
||||
where +
|
||||
" AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryStats = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
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}
|
||||
FROM deals d
|
||||
${catWhere}
|
||||
GROUP BY d.category
|
||||
ORDER BY total_amount DESC`,
|
||||
ORDER BY total_amount DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
const catBreakWhere = where
|
||||
? where + " AND d.category IS NOT NULL"
|
||||
: "WHERE d.category IS NOT NULL";
|
||||
const catBreakWhere =
|
||||
where +
|
||||
" AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryBreakdown = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
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}
|
||||
FROM deals d
|
||||
${catBreakWhere}
|
||||
GROUP BY d.category
|
||||
ORDER BY (total_income + total_expense) DESC`,
|
||||
ORDER BY (total_income + total_expense) DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
const maxIncomeStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='income'
|
||||
FROM deals WHERE category=? AND direction='income' AND user_id=?
|
||||
ORDER BY amount DESC LIMIT 1`,
|
||||
);
|
||||
const maxExpenseStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='expense'
|
||||
FROM deals WHERE category=? AND direction='expense' AND user_id=?
|
||||
ORDER BY ABS(amount) DESC LIMIT 1`,
|
||||
);
|
||||
|
||||
for (const cat of categoryBreakdown) {
|
||||
cat.max_income = maxIncomeStmt.get(cat.category) || null;
|
||||
cat.max_expense = maxExpenseStmt.get(cat.category) || null;
|
||||
cat.max_income = maxIncomeStmt.get(cat.category, req.userId) || null;
|
||||
cat.max_expense = maxExpenseStmt.get(cat.category, req.userId) || null;
|
||||
}
|
||||
|
||||
res.json({ overview: stats, categoryStats, categoryBreakdown });
|
||||
});
|
||||
|
||||
// GET /api/stats/monthly — 月度趋势(可选 categories 过滤)
|
||||
// 解析 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 months = Math.abs(parseInt(req.query.months) || 12);
|
||||
const cats = parseCategories(req.query.categories);
|
||||
|
||||
let catFilter = "";
|
||||
const params = ["-" + months];
|
||||
const params = ["-" + months, req.userId];
|
||||
|
||||
if (req.query.categories) {
|
||||
const cats = req.query.categories
|
||||
.split(",")
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
if (cats.length > 0) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
params.push(...cats);
|
||||
}
|
||||
if (cats && cats.length > 0) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
params.push(...cats);
|
||||
}
|
||||
|
||||
const monthlyData = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
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
|
||||
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')${catFilter}
|
||||
WHERE d.deal_date >= DATE('now', ? || ' months') AND d.user_id = ?${catFilter}
|
||||
GROUP BY strftime('%Y-%m', d.deal_date)
|
||||
ORDER BY month ASC`,
|
||||
ORDER BY month ASC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
res.json(monthlyData);
|
||||
});
|
||||
|
||||
// GET /api/stats/daily — 每日统计(基于 deals)
|
||||
// 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
|
||||
`
|
||||
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
|
||||
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')
|
||||
WHERE d.deal_date >= DATE('now', ? || ' days') AND d.user_id = ?${catFilter}
|
||||
GROUP BY d.deal_date
|
||||
ORDER BY date ASC`,
|
||||
ORDER BY date ASC
|
||||
`,
|
||||
)
|
||||
.all("-" + days);
|
||||
.all(...params);
|
||||
|
||||
res.json(dailyData);
|
||||
});
|
||||
|
||||
@@ -24,8 +24,8 @@ router.get("/", (req, res) => {
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
const conditions = ["t.user_id = ?"];
|
||||
const params = [req.userId];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push("t.transaction_date >= ?");
|
||||
@@ -62,7 +62,6 @@ router.get("/", (req, res) => {
|
||||
const whereClause =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = [
|
||||
"id",
|
||||
"transaction_time",
|
||||
@@ -115,16 +114,16 @@ router.get("/", (req, res) => {
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.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})`,
|
||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats);
|
||||
.all(...cats, req.userId);
|
||||
console.log(
|
||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
||||
);
|
||||
@@ -134,17 +133,23 @@ router.get("/needs-classify", (req, res) => {
|
||||
// POST /api/transactions/reconcile - 全量清除后重新对账
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const db = getDB();
|
||||
db.prepare("DELETE FROM deal_transactions").run();
|
||||
db.prepare("DELETE FROM deals").run();
|
||||
const userId = req.userId;
|
||||
|
||||
// 仅清除当前用户的数据
|
||||
db.prepare(
|
||||
"UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL",
|
||||
).run();
|
||||
const result = runAutoReconciliation();
|
||||
"DELETE FROM deal_transactions WHERE deal_id IN (SELECT id FROM deals WHERE user_id = ?)",
|
||||
).run(userId);
|
||||
db.prepare("DELETE FROM deals WHERE user_id = ?").run(userId);
|
||||
db.prepare(
|
||||
"UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL WHERE user_id = ?",
|
||||
).run(userId);
|
||||
|
||||
const result = runAutoReconciliation(userId);
|
||||
const allTxs = db
|
||||
.prepare(
|
||||
"SELECT id,transaction_date,transaction_time,amount,direction,counterparty,description,matched_transaction_id FROM transactions ORDER BY transaction_date,transaction_time",
|
||||
"SELECT id,transaction_date,transaction_time,amount,direction,counterparty,description,matched_transaction_id FROM transactions WHERE user_id = ? ORDER BY transaction_date,transaction_time",
|
||||
)
|
||||
.all();
|
||||
.all(userId);
|
||||
const visited = new Set();
|
||||
const groups = [];
|
||||
for (const tx of allTxs) {
|
||||
@@ -166,7 +171,7 @@ router.post("/reconcile", (req, res) => {
|
||||
groups.push(group);
|
||||
}
|
||||
const insD = db.prepare(
|
||||
"INSERT INTO deals(deal_date,amount,direction,counterparty,description,match_count)VALUES(?,?,?,?,?,?)",
|
||||
"INSERT INTO deals(deal_date,amount,direction,counterparty,description,match_count,user_id)VALUES(?,?,?,?,?,?,?)",
|
||||
);
|
||||
const insT = db.prepare(
|
||||
"INSERT INTO deal_transactions(deal_id,transaction_id)VALUES(?,?)",
|
||||
@@ -186,6 +191,7 @@ router.post("/reconcile", (req, res) => {
|
||||
e.counterparty,
|
||||
e.description,
|
||||
group.length,
|
||||
userId,
|
||||
);
|
||||
for (const tx of group) insT.run(r.lastInsertRowid, tx.id);
|
||||
dc++;
|
||||
@@ -208,7 +214,7 @@ router.post("/classify", async (req, res) => {
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
const result = await classifyDeals(ids, req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify — 完成, classified: ${result.classified}, source: ${result.source}`,
|
||||
);
|
||||
@@ -223,7 +229,7 @@ router.post("/classify", async (req, res) => {
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
||||
try {
|
||||
const result = await classifyAllDeals();
|
||||
const result = await classifyAllDeals(req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
||||
);
|
||||
|
||||
+18
-7
@@ -145,17 +145,25 @@ router.post("/confirm", (req, res) => {
|
||||
uploadPath,
|
||||
} = temp;
|
||||
const db = getDB();
|
||||
const userId = req.userId;
|
||||
|
||||
const src = db
|
||||
.prepare(
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?,?,?,?,?)",
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count, user_id) VALUES (?,?,?,?,?,?)",
|
||||
)
|
||||
.run(sourceType, sourceName, originalname, fileHash, parsed.length);
|
||||
.run(
|
||||
sourceType,
|
||||
sourceName,
|
||||
originalname,
|
||||
fileHash,
|
||||
parsed.length,
|
||||
userId,
|
||||
);
|
||||
|
||||
const ins = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
transaction_code, source_id, source_type, transaction_date, transaction_time,
|
||||
counterparty, description, notes, amount, direction, status, method, balance
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
counterparty, description, notes, amount, direction, status, method, balance, user_id
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
|
||||
let inserted = 0,
|
||||
skip = 0;
|
||||
@@ -180,6 +188,7 @@ router.post("/confirm", (req, res) => {
|
||||
tx.status || "",
|
||||
tx.method || "",
|
||||
tx.balance || null,
|
||||
userId,
|
||||
);
|
||||
if (r.changes > 0) inserted++;
|
||||
else skip++;
|
||||
@@ -221,14 +230,16 @@ router.get("/sources", (req, res) => {
|
||||
res.json(
|
||||
getDB()
|
||||
.prepare(
|
||||
"SELECT s.*, COUNT(t.id) tx_count FROM sources s LEFT JOIN transactions t ON t.source_id=s.id GROUP BY s.id ORDER BY s.imported_at DESC",
|
||||
"SELECT s.*, COUNT(t.id) tx_count FROM sources s LEFT JOIN transactions t ON t.source_id=s.id WHERE s.user_id = ? GROUP BY s.id ORDER BY s.imported_at DESC",
|
||||
)
|
||||
.all(),
|
||||
.all(req.userId),
|
||||
);
|
||||
});
|
||||
|
||||
router.delete("/sources/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
|
||||
getDB()
|
||||
.prepare("DELETE FROM sources WHERE id = ? AND user_id = ?")
|
||||
.run(req.params.id, req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+46
-114
@@ -1,54 +1,39 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, "..", "..", "data", "llm_config.json");
|
||||
const BATCH_SIZE = 30; // 每批发送给 LLM 的 deal 数量
|
||||
const CONCURRENCY = 5; // 并行调用 LLM 的最大并发数
|
||||
|
||||
let openaiClient = null;
|
||||
const BATCH_SIZE = 30;
|
||||
const CONCURRENCY = 5;
|
||||
|
||||
/* ============================== 配置管理 ============================== */
|
||||
function loadConfig() {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH))
|
||||
return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
|
||||
} catch (e) {}
|
||||
return {};
|
||||
}
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), "utf-8");
|
||||
}
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
function loadUserLLMConfig(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const row = db
|
||||
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", userId);
|
||||
return row ? JSON.parse(row.value) : {};
|
||||
}
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
const cfg = loadConfig();
|
||||
function getOpenAIClient(userId) {
|
||||
const cfg = loadUserLLMConfig(userId);
|
||||
if (!cfg.llm_api_key) {
|
||||
console.log("[Reco] LLM 未配置 API Key");
|
||||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||||
return null;
|
||||
}
|
||||
const { OpenAI } = require("openai");
|
||||
openaiClient = new OpenAI({
|
||||
const client = new OpenAI({
|
||||
apiKey: cfg.llm_api_key,
|
||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||
});
|
||||
openaiClient._model = cfg.llm_model || "gpt-4o-mini";
|
||||
console.log(
|
||||
`[Reco] LLM 客户端已初始化 — 模型: ${openaiClient._model}, BaseURL: ${cfg.llm_base_url || "默认"}`,
|
||||
);
|
||||
return openaiClient;
|
||||
client._model = cfg.llm_model || "gpt-4o-mini";
|
||||
return client;
|
||||
}
|
||||
|
||||
/* ============================== Prompt 构建 ============================== */
|
||||
function buildPrompt(deals) {
|
||||
function buildPrompt(deals, userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
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("、") + ")",
|
||||
@@ -58,7 +43,6 @@ function buildPrompt(deals) {
|
||||
let txTotal = 0;
|
||||
const dealList = deals
|
||||
.map((d, i) => {
|
||||
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
|
||||
const txs = db
|
||||
.prepare(
|
||||
`
|
||||
@@ -126,12 +110,10 @@ ${dealList}
|
||||
/* ============================== JSON 提取 ============================== */
|
||||
function extractJsonArray(text) {
|
||||
if (!text) return null;
|
||||
// 先尝试直接解析
|
||||
try {
|
||||
const r = JSON.parse(text);
|
||||
if (Array.isArray(r)) return r;
|
||||
} catch (e) {}
|
||||
// 找到第一个 [ 和最后一个 ]
|
||||
const start = text.indexOf("[");
|
||||
const end = text.lastIndexOf("]");
|
||||
if (start === -1 || end === -1 || start >= end) return null;
|
||||
@@ -142,28 +124,27 @@ function extractJsonArray(text) {
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds) {
|
||||
async function classifyDeals(dealIds, userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
if (ids.length === 0) return { classified: 0 };
|
||||
|
||||
console.log(`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID`);
|
||||
console.log(
|
||||
`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID (userId=${userId})`,
|
||||
);
|
||||
|
||||
const deals = db
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")}) AND user_id = ?`,
|
||||
)
|
||||
.all(...ids);
|
||||
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
|
||||
.all(...ids, userId);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const client = getOpenAIClient();
|
||||
const client = getOpenAIClient(userId);
|
||||
if (client) {
|
||||
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
|
||||
try {
|
||||
const prompt = buildPrompt(deals);
|
||||
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
|
||||
const prompt = buildPrompt(deals, userId);
|
||||
const t0 = Date.now();
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
@@ -178,31 +159,20 @@ async function classifyDeals(dealIds) {
|
||||
temperature: 0.3,
|
||||
max_tokens: 4000,
|
||||
});
|
||||
const elapsed = Date.now() - t0;
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
|
||||
);
|
||||
|
||||
const rawContent = response.choices[0]?.message?.content || "";
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
|
||||
);
|
||||
|
||||
const results = extractJsonArray(rawContent);
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
|
||||
);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
const t1 = Date.now();
|
||||
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,
|
||||
@@ -212,34 +182,29 @@ async function classifyDeals(dealIds) {
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
|
||||
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
);
|
||||
return { classified: results.length, source: "llm" };
|
||||
}
|
||||
console.log(`[Reco] classifyDeals — JSON解析为空,降级到规则匹配 ⚠️`);
|
||||
} catch (e) {
|
||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||
}
|
||||
} else {
|
||||
console.log(`[Reco] classifyDeals — 未配置LLM,使用规则匹配`);
|
||||
}
|
||||
// LLM 不可用或失败 → 降级为规则匹配
|
||||
return classifyDealsByRules(deals);
|
||||
return classifyDealsByRules(deals, userId);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals) {
|
||||
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
|
||||
function classifyDealsByRules(deals, userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
|
||||
const cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
// 包裹在事务中批量更新
|
||||
db.transaction(() => {
|
||||
for (const d of deals) {
|
||||
const text = (d.description + " " + d.counterparty).toLowerCase();
|
||||
@@ -263,94 +228,64 @@ function classifyDealsByRules(deals) {
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
"元";
|
||||
upd.run(desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
|
||||
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
}
|
||||
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals() {
|
||||
async function classifyAllDeals(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
|
||||
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
|
||||
|
||||
// 1. 取出全部未分类或分类已过时的 deal
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((r) => r.name);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
|
||||
);
|
||||
|
||||
if (!cats.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无分类,退出`);
|
||||
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})`,
|
||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats);
|
||||
|
||||
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
|
||||
.all(...cats, userId);
|
||||
|
||||
if (!stale.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
|
||||
// 2. 分批
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 共 ${batches.length} 批 (每批≤${BATCH_SIZE}条), 最大并发 ${CONCURRENCY}`,
|
||||
);
|
||||
|
||||
// 3. 并行处理(带并发限制)
|
||||
let totalClassified = 0;
|
||||
let source = "rules";
|
||||
const tStart = Date.now();
|
||||
let round = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
round++;
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const from = i + 1;
|
||||
const to = Math.min(i + CONCURRENCY, batches.length);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮: 并行处理第 ${from}-${to} 批 (共 ${chunk.length} 批)`,
|
||||
const results = await Promise.all(
|
||||
chunk.map((b) => classifyDeals(b, userId)),
|
||||
);
|
||||
|
||||
const tRound = Date.now();
|
||||
const results = await Promise.all(chunk.map((b) => classifyDeals(b)));
|
||||
const roundElapsed = Date.now() - tRound;
|
||||
|
||||
for (const r of results) {
|
||||
totalClassified += r.classified;
|
||||
if (r.source === "llm") source = "llm";
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
const totalElapsed = Date.now() - tStart;
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
|
||||
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
||||
);
|
||||
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
}
|
||||
@@ -359,7 +294,4 @@ module.exports = {
|
||||
classifyDeals,
|
||||
classifyAllDeals,
|
||||
getOpenAIClient,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
resetClient,
|
||||
};
|
||||
|
||||
+51
-37
@@ -1,4 +1,4 @@
|
||||
const { getDB } = require('../db');
|
||||
const { getDB } = require("../db");
|
||||
|
||||
/**
|
||||
* 交易匹配服务
|
||||
@@ -13,7 +13,7 @@ const { getDB } = require('../db');
|
||||
* 2. 日期相近(±1天) + 相同金额 + 描述相似
|
||||
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
|
||||
*/
|
||||
function findMatches(newTransaction) {
|
||||
function findMatches(newTransaction, userId) {
|
||||
const db = getDB();
|
||||
|
||||
const absAmount = Math.abs(newTransaction.amount);
|
||||
@@ -21,25 +21,31 @@ function findMatches(newTransaction) {
|
||||
// 只匹配金额 > 0.01 的交易
|
||||
if (absAmount < 0.01) return [];
|
||||
|
||||
const candidates = db.prepare(`
|
||||
const candidates = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id, transaction_code, transaction_date, amount, counterparty,
|
||||
description, source_type, direction, category
|
||||
FROM transactions
|
||||
WHERE id != ?
|
||||
AND source_id != ?
|
||||
AND user_id = ?
|
||||
AND reviewed = 0
|
||||
AND ABS(ABS(amount) - ?) <= 1.0
|
||||
AND transaction_date BETWEEN DATE(?, '-2 days') AND DATE(?, '+2 days')
|
||||
ORDER BY ABS(julianday(transaction_date) - julianday(?)) ASC
|
||||
LIMIT 20
|
||||
`).all(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date
|
||||
);
|
||||
`,
|
||||
)
|
||||
.all(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
userId,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
@@ -53,66 +59,70 @@ function findMatches(newTransaction) {
|
||||
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
|
||||
if (amountDiff < 0.01) {
|
||||
score += 40;
|
||||
reasons.push('金额完全一致');
|
||||
reasons.push("金额完全一致");
|
||||
} else if (amountDiff < 0.1) {
|
||||
score += 35;
|
||||
reasons.push('金额基本一致');
|
||||
reasons.push("金额基本一致");
|
||||
} else if (amountDiff < 1.0) {
|
||||
score += 20;
|
||||
reasons.push('金额接近');
|
||||
reasons.push("金额接近");
|
||||
}
|
||||
|
||||
// 日期得分
|
||||
const dateDiff = Math.abs(
|
||||
new Date(candidate.transaction_date) - new Date(newTransaction.transaction_date)
|
||||
) / (1000 * 60 * 60 * 24);
|
||||
const dateDiff =
|
||||
Math.abs(
|
||||
new Date(candidate.transaction_date) -
|
||||
new Date(newTransaction.transaction_date),
|
||||
) /
|
||||
(1000 * 60 * 60 * 24);
|
||||
|
||||
if (dateDiff < 0.01) {
|
||||
score += 30;
|
||||
reasons.push('日期相同');
|
||||
reasons.push("日期相同");
|
||||
} else if (dateDiff <= 1) {
|
||||
score += 20;
|
||||
reasons.push('日期差1天');
|
||||
reasons.push("日期差1天");
|
||||
} else if (dateDiff <= 2) {
|
||||
score += 10;
|
||||
reasons.push('日期差2天');
|
||||
reasons.push("日期差2天");
|
||||
}
|
||||
|
||||
// 对方名称相似度
|
||||
const nameSim = stringSimilarity(
|
||||
(candidate.counterparty || '').toLowerCase(),
|
||||
(newTransaction.counterparty || '').toLowerCase()
|
||||
(candidate.counterparty || "").toLowerCase(),
|
||||
(newTransaction.counterparty || "").toLowerCase(),
|
||||
);
|
||||
if (nameSim > 0.8) {
|
||||
score += 20;
|
||||
reasons.push('对方名称高度相似');
|
||||
reasons.push("对方名称高度相似");
|
||||
} else if (nameSim > 0.5) {
|
||||
score += 10;
|
||||
reasons.push('对方名称部分相似');
|
||||
reasons.push("对方名称部分相似");
|
||||
}
|
||||
|
||||
// 描述相似度
|
||||
const descSim = stringSimilarity(
|
||||
(candidate.description || '').toLowerCase(),
|
||||
(newTransaction.description || '').toLowerCase()
|
||||
(candidate.description || "").toLowerCase(),
|
||||
(newTransaction.description || "").toLowerCase(),
|
||||
);
|
||||
if (descSim > 0.7) {
|
||||
score += 10;
|
||||
reasons.push('描述相似');
|
||||
reasons.push("描述相似");
|
||||
}
|
||||
|
||||
// 方向互补(一个支出一个收入,说明是转账匹配)
|
||||
if (candidate.direction !== newTransaction.direction) {
|
||||
score += 5;
|
||||
reasons.push('收支方向互补');
|
||||
reasons.push("收支方向互补");
|
||||
}
|
||||
|
||||
if (score >= 40) { // 最低匹配阈值
|
||||
if (score >= 40) {
|
||||
// 最低匹配阈值
|
||||
matches.push({
|
||||
transaction_id: candidate.id,
|
||||
match_score: Math.min(score, 100) / 100,
|
||||
reasons: reasons.join(';'),
|
||||
candidate
|
||||
reasons: reasons.join(";"),
|
||||
candidate,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -124,17 +134,21 @@ function findMatches(newTransaction) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行全局自动对账
|
||||
* 运行全局自动对账(限定当前用户)
|
||||
* 对所有未匹配的交易尝试匹配
|
||||
*/
|
||||
function runAutoReconciliation() {
|
||||
function runAutoReconciliation(userId) {
|
||||
const db = getDB();
|
||||
|
||||
const unmatched = db.prepare(`
|
||||
const unmatched = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM transactions
|
||||
WHERE matched_transaction_id IS NULL
|
||||
WHERE matched_transaction_id IS NULL AND user_id = ?
|
||||
ORDER BY transaction_date DESC
|
||||
`).all();
|
||||
`,
|
||||
)
|
||||
.all(userId);
|
||||
|
||||
let matchCount = 0;
|
||||
|
||||
@@ -149,7 +163,7 @@ function runAutoReconciliation() {
|
||||
for (const tx of unmatched) {
|
||||
if (processed.has(tx.id)) continue;
|
||||
|
||||
const matches = findMatches(tx);
|
||||
const matches = findMatches(tx, userId);
|
||||
if (matches.length > 0 && matches[0].match_score >= 0.7) {
|
||||
const bestMatch = matches[0];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user