const express = require("express"); const { getDB } = require("../db"); const { runAutoReconciliation } = require("../services/matcher"); const { classifyDeals, classifyAllDeals } = require("../services/llm"); const router = express.Router(); // GET /api/transactions - 获取交易列表(支持筛选和分页) router.get("/", (req, res) => { const db = getDB(); const { page = 1, limit = 10, start_date, end_date, source_type, direction, min_amount, max_amount, keyword, sort_by = "transaction_date", sort_order = "DESC", } = req.query; const offset = (parseInt(page) - 1) * parseInt(limit); const conditions = ["t.user_id = ?"]; const params = [req.userId]; if (start_date) { conditions.push("t.transaction_date >= ?"); params.push(start_date); } if (end_date) { conditions.push("t.transaction_date <= ?"); params.push(end_date); } if (source_type) { conditions.push("t.source_type = ?"); params.push(source_type); } if (direction) { conditions.push("t.direction = ?"); params.push(direction); } if (min_amount) { conditions.push("ABS(t.amount) >= ?"); params.push(parseFloat(min_amount)); } if (max_amount) { conditions.push("ABS(t.amount) <= ?"); params.push(parseFloat(max_amount)); } if (keyword) { conditions.push( "(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ?)", ); const kw = `%${keyword}%`; params.push(kw, kw, kw); } const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : ""; const allowedSortFields = [ "id", "transaction_time", "transaction_date", "amount", "created_at", "counterparty", "direction", "source_type", ]; const safeSortBy = allowedSortFields.includes(sort_by) ? sort_by : "transaction_date"; const safeSortOrder = sort_order === "ASC" ? "ASC" : "DESC"; const countResult = db .prepare(`SELECT COUNT(*) as total FROM transactions t ${whereClause}`) .get(...params); const totalsResult = db .prepare( `SELECT COALESCE(SUM(CASE WHEN t.direction='income' THEN t.amount ELSE 0 END),0) as totalIncome, COALESCE(SUM(CASE WHEN t.direction='expense' THEN ABS(t.amount) ELSE 0 END),0) as totalExpense FROM transactions t ${whereClause}`, ) .get(...params); const transactions = db .prepare( ` SELECT t.*, s.source_name FROM transactions t LEFT JOIN sources s ON s.id = t.source_id ${whereClause} ORDER BY t.${safeSortBy} ${safeSortOrder} LIMIT ? OFFSET ? `, ) .all(...params, parseInt(limit), offset); res.json({ transactions, total: countResult.total, totalIncome: totalsResult.totalIncome, totalExpense: totalsResult.totalExpense, page: parseInt(page), limit: parseInt(limit), totalPages: Math.ceil(countResult.total / parseInt(limit)), }); }); router.get("/needs-classify", (req, res) => { const db = getDB(); const cats = db .prepare("SELECT name FROM categories WHERE user_id = ?") .all(req.userId) .map((r) => r.name); if (!cats.length) return res.json({ ids: [], total: 0 }); const ph = cats.map(() => "?").join(","); const stale = db .prepare( `SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`, ) .all(...cats, req.userId); console.log( `[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`, ); res.json({ ids: stale.map((r) => r.id), total: stale.length }); }); // POST /api/transactions/reconcile - 全量清除后重新对账 router.post("/reconcile", (req, res) => { const db = getDB(); const userId = req.userId; // 仅清除当前用户的数据 db.prepare( "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 WHERE user_id = ? ORDER BY transaction_date,transaction_time", ) .all(userId); 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); } const insD = db.prepare( "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(?,?)", ); 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 r = insD.run( e.transaction_time || e.transaction_date, e.amount, e.direction, e.counterparty, e.description, group.length, userId, ); 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 — 对指定 deal 批量分类 router.post("/classify", async (req, res) => { const { ids } = req.body; console.log( `[Reco] POST /transactions/classify — 收到 ${ids ? ids.length : 0} 个ID`, ); if (!ids || !Array.isArray(ids) || ids.length === 0) { return res.status(400).json({ error: "请提供交易ID列表" }); } try { const result = await classifyDeals(ids, req.userId); console.log( `[Reco] POST /transactions/classify — 完成, classified: ${result.classified}, source: ${result.source}`, ); res.json({ success: true, ...result }); } catch (err) { console.error("[Reco] 分类失败:", err); res.status(500).json({ error: err.message }); } }); // POST /api/transactions/classify-all — AI分类全部(并行) router.post("/classify-all", async (req, res) => { console.log(`[Reco] POST /transactions/classify-all — 开始`); try { const result = await classifyAllDeals(req.userId); console.log( `[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`, ); res.json({ success: true, ...result }); } catch (err) { console.error("[Reco] 分类全部失败:", err); res.status(500).json({ error: err.message }); } }); module.exports = router;