refactor(数据模型): 分类/确认字段从transactions迁移到deals
- deals表新增direction/category/ai_category/ai_description/ai_confidence/reviewed/review_notes/reviewed_at/tags - transactions表不再写入这些字段(旧数据保留) - classifyDeals替代classifyTransactions, AI分类改到deal级别 - needs-classify/classify-all查询deals - deals路由新增PUT :id编辑接口 - 前端交易明细去掉分类列和编辑弹框分类字段
This commit is contained in:
+18
-206
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyTransactions } = require("../services/llm");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -79,8 +79,6 @@ router.get("/", (req, res) => {
|
||||
"amount",
|
||||
"created_at",
|
||||
"counterparty",
|
||||
"category",
|
||||
"reviewed",
|
||||
];
|
||||
const safeSortBy = allowedSortFields.includes(sort_by)
|
||||
? sort_by
|
||||
@@ -115,214 +113,28 @@ router.get("/", (req, res) => {
|
||||
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const validCats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (validCats.length === 0) return res.json({ ids: [], total: 0 });
|
||||
const ph = validCats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...validCats);
|
||||
res.json({ ids: stale.map((r) => r.id), total: stale.length });
|
||||
const cats = db.prepare("SELECT name FROM categories").all().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})`).all(...cats);
|
||||
res.json({ ids: stale.map(r => r.id), total: stale.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`,
|
||||
)
|
||||
.get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`,
|
||||
)
|
||||
.get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.transaction_code = ? AND t.id != ?
|
||||
`,
|
||||
)
|
||||
.all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({
|
||||
transaction: tx,
|
||||
matchedTransaction: matchedTx,
|
||||
relatedTransactions: relatedTxs,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
|
||||
const tx = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push("category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push("ai_description = ?");
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push("reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push("review_notes = ?");
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: "没有提供要更新的字段" });
|
||||
}
|
||||
|
||||
updates.push("updated_at = CURRENT_TIMESTAMP");
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(", ")} WHERE id = ?`).run(
|
||||
...params,
|
||||
);
|
||||
|
||||
const updated = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
res.json({ success: true, transaction: updated });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 全量清除后重新对账,每笔交易生成deal
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const db = getDB();
|
||||
// 清除旧数据
|
||||
db.prepare("DELETE FROM deal_transactions").run();
|
||||
db.prepare("DELETE FROM deals").run();
|
||||
db.prepare("UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL").run();
|
||||
// 运行自动匹配
|
||||
const result = runAutoReconciliation();
|
||||
// 收集所有交易,按 matched 关系分组
|
||||
const allTxs = db.prepare("SELECT id,transaction_date,transaction_time,amount,counterparty,description,matched_transaction_id FROM transactions ORDER BY transaction_date,transaction_time").all();
|
||||
const visited = new Set(); const groups = [];
|
||||
for (const tx of allTxs) {
|
||||
if (visited.has(tx.id)) continue; visited.add(tx.id);
|
||||
const group = [tx];
|
||||
for (const other of allTxs) {
|
||||
if (visited.has(other.id)) continue;
|
||||
if (other.matched_transaction_id===tx.id||tx.matched_transaction_id===other.id||(tx.matched_transaction_id&&tx.matched_transaction_id===other.matched_transaction_id)) {
|
||||
group.push(other); visited.add(other.id);
|
||||
}
|
||||
}
|
||||
groups.push(group);
|
||||
}
|
||||
// 为每组生成 deal(取最早一笔填充信息)
|
||||
const insD=db.prepare("INSERT INTO deals(deal_date,amount,counterparty,description,match_count)VALUES(?,?,?,?,?)");
|
||||
const insT=db.prepare("INSERT INTO deal_transactions(deal_id,transaction_id)VALUES(?,?)");
|
||||
let dc=0;
|
||||
for(const group of groups){
|
||||
const e=group.reduce((a,b)=>(a.transaction_time||a.transaction_date)<(b.transaction_time||b.transaction_date)?a:b); const dealTime = e.transaction_time || e.transaction_date;
|
||||
const r=insD.run(dealTime,e.amount,e.counterparty,e.description,group.length);
|
||||
for(const tx of group)insT.run(r.lastInsertRowid,tx.id);
|
||||
dc++;
|
||||
}
|
||||
res.json({success:true,matched:result.matched,total:result.total,deals:dc});
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post("/classify", 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 classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/transactions/needs-classify
|
||||
// POST /api/transactions/classify-all — 重分类过期分类的交易
|
||||
// POST /api/transactions/classify-all — 重分类 deals
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
const db = getDB();
|
||||
const validCats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (validCats.length === 0)
|
||||
return res.json({ success: true, classified: 0, message: "无分类配置" });
|
||||
|
||||
const ph = validCats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...validCats);
|
||||
if (stale.length === 0)
|
||||
return res.json({
|
||||
success: true,
|
||||
classified: 0,
|
||||
total: 0,
|
||||
message: "所有交易分类均有效",
|
||||
});
|
||||
|
||||
const ids = stale.map((r) => r.id),
|
||||
batchSize = 50;
|
||||
let classified = 0;
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const r = await classifyTransactions(ids.slice(i, i + batchSize));
|
||||
classified += r.classified;
|
||||
const cats = db.prepare("SELECT name FROM categories").all().map(r => r.name);
|
||||
if (!cats.length) return res.json({ classified: 0 });
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db.prepare(`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`).all(...cats);
|
||||
if (!stale.length) return res.json({ classified: 0, total: 0 });
|
||||
const ids = stale.map(r => r.id), B = 50;
|
||||
let n = 0;
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
const r = await classifyDeals(ids.slice(i, i + B));
|
||||
n += r.classified;
|
||||
}
|
||||
res.json({ success: true, classified, total: ids.length });
|
||||
res.json({ success: true, classified: n, total: ids.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
|
||||
Reference in New Issue
Block a user