Add user authentication with JWT login and registration
This commit is contained in:
@@ -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 });
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user