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.
186 lines
5.2 KiB
JavaScript
186 lines
5.2 KiB
JavaScript
const express = require("express");
|
|
const { getDB } = require("../db");
|
|
const router = express.Router();
|
|
|
|
// GET /api/deals — 支持筛选和分页
|
|
router.get("/", (req, res) => {
|
|
const db = getDB();
|
|
const {
|
|
page = 1,
|
|
limit = 10,
|
|
start_date,
|
|
end_date,
|
|
category,
|
|
direction,
|
|
keyword,
|
|
min_amount,
|
|
max_amount,
|
|
reviewed,
|
|
sort_by = "deal_date",
|
|
sort_order = "DESC",
|
|
} = req.query;
|
|
const offset = (page - 1) * limit;
|
|
|
|
const conditions = ["d.user_id = ?"];
|
|
const params = [req.userId];
|
|
if (start_date) {
|
|
conditions.push("d.deal_date >= ?");
|
|
params.push(start_date);
|
|
}
|
|
if (end_date) {
|
|
conditions.push("d.deal_date <= ?");
|
|
params.push(end_date);
|
|
}
|
|
if (category) {
|
|
conditions.push("d.category = ?");
|
|
params.push(category);
|
|
}
|
|
if (direction) {
|
|
conditions.push("d.direction = ?");
|
|
params.push(direction);
|
|
}
|
|
if (keyword) {
|
|
conditions.push(
|
|
"(d.counterparty LIKE ? OR d.description LIKE ? OR d.ai_description LIKE ?)",
|
|
);
|
|
params.push("%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%");
|
|
}
|
|
if (min_amount) {
|
|
conditions.push("ABS(d.amount) >= ?");
|
|
params.push(parseFloat(min_amount));
|
|
}
|
|
if (max_amount) {
|
|
conditions.push("ABS(d.amount) <= ?");
|
|
params.push(parseFloat(max_amount));
|
|
}
|
|
if (reviewed !== undefined) {
|
|
conditions.push("d.reviewed = ?");
|
|
params.push(parseInt(reviewed));
|
|
}
|
|
const where = conditions.length ? "WHERE " + conditions.join(" AND ") : "";
|
|
|
|
const allowedSort = [
|
|
"id",
|
|
"deal_date",
|
|
"amount",
|
|
"direction",
|
|
"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}`)
|
|
.get(...params).c;
|
|
|
|
const totalsResult = db
|
|
.prepare(
|
|
`SELECT COALESCE(SUM(CASE WHEN d.direction='income' THEN d.amount ELSE 0 END),0) as totalIncome, COALESCE(SUM(CASE WHEN d.direction='expense' THEN ABS(d.amount) ELSE 0 END),0) as totalExpense FROM deals d ${where}`,
|
|
)
|
|
.get(...params);
|
|
|
|
const deals = db
|
|
.prepare(
|
|
`
|
|
SELECT d.*, GROUP_CONCAT(t.transaction_code) as codes
|
|
FROM deals d
|
|
LEFT JOIN deal_transactions dt ON dt.deal_id = d.id
|
|
LEFT JOIN transactions t ON t.id = dt.transaction_id
|
|
${where}
|
|
GROUP BY d.id
|
|
ORDER BY ${sortExpr} ${safeOrder}${tieBreaker}
|
|
LIMIT ? OFFSET ?
|
|
`,
|
|
)
|
|
.all(...params, limit, offset);
|
|
|
|
for (const deal of deals) {
|
|
deal.transactions = db
|
|
.prepare(
|
|
`
|
|
SELECT t.*, s.source_name
|
|
FROM deal_transactions dt
|
|
JOIN transactions t ON t.id = dt.transaction_id
|
|
LEFT JOIN sources s ON s.id = t.source_id
|
|
WHERE dt.deal_id = ?
|
|
`,
|
|
)
|
|
.all(deal.id);
|
|
}
|
|
|
|
res.json({
|
|
deals,
|
|
total,
|
|
totalIncome: totalsResult.totalIncome,
|
|
totalExpense: totalsResult.totalExpense,
|
|
page: Number(page),
|
|
totalPages: Math.ceil(total / limit),
|
|
});
|
|
});
|
|
|
|
// PUT /api/deals/:id — 编辑分类/确认
|
|
router.put("/:id", (req, res) => {
|
|
const db = getDB();
|
|
const { category, ai_description, reviewed, tags } = req.body;
|
|
const sets = [];
|
|
const params = [];
|
|
if (category !== undefined) {
|
|
sets.push("category = ?");
|
|
params.push(category);
|
|
}
|
|
if (ai_description !== undefined) {
|
|
sets.push("ai_description = ?");
|
|
params.push(ai_description);
|
|
}
|
|
if (reviewed !== undefined) {
|
|
sets.push("reviewed = ?");
|
|
params.push(reviewed);
|
|
if (reviewed) sets.push("reviewed_at = CURRENT_TIMESTAMP");
|
|
}
|
|
if (tags !== undefined) {
|
|
sets.push("tags = ?");
|
|
params.push(JSON.stringify(tags));
|
|
}
|
|
if (!sets.length) return res.status(400).json({ error: "无更新字段" });
|
|
sets.push("updated_at = CURRENT_TIMESTAMP");
|
|
params.push(req.params.id);
|
|
params.push(req.userId);
|
|
db.prepare(
|
|
"UPDATE deals SET " + sets.join(", ") + " WHERE id = ? AND user_id = ?",
|
|
).run(...params);
|
|
res.json({ success: true });
|
|
});
|
|
|
|
// POST /api/deals/batch-confirm — 批量确认大额交易
|
|
router.post("/batch-confirm", (req, res) => {
|
|
const db = getDB();
|
|
const { ids } = req.body;
|
|
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
|
return res.status(400).json({ error: "请提供交易ID列表" });
|
|
}
|
|
const ph = ids.map(() => "?").join(",");
|
|
db.prepare(
|
|
`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 — 清除当前用户所有 deals
|
|
router.post("/clear", (req, res) => {
|
|
const db = getDB();
|
|
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 });
|
|
});
|
|
|
|
module.exports = router;
|