const express = require("express"); const { getDB } = require("../db"); const { runAutoReconciliation } = require("../services/matcher"); const { classifyDeals } = require("../services/llm"); const router = express.Router(); // GET /api/transactions - 获取交易列表(支持筛选和分页) router.get("/", (req, res) => { const db = getDB(); const { page = 1, limit = 50, start_date, end_date, source_type, direction, category, reviewed, min_amount, max_amount, keyword, sort_by = "transaction_date", sort_order = "DESC", } = req.query; const offset = (parseInt(page) - 1) * parseInt(limit); const conditions = []; const params = []; 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 (category) { conditions.push("t.category = ?"); params.push(category); } if (reviewed !== undefined) { conditions.push("t.reviewed = ?"); params.push(parseInt(reviewed)); } 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 ? OR t.ai_description LIKE ?)", ); const kw = `%${keyword}%`; params.push(kw, kw, kw, kw); } const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : ""; // 安全的白名单排序 const allowedSortFields = [ "transaction_time", "transaction_date", "amount", "created_at", "counterparty", ]; 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 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, 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").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 }); }); // POST /api/transactions/classify-all — 重分类 deals router.post("/classify-all", async (req, res) => { const db = getDB(); 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: n, total: ids.length }); }); // GET /api/transactions/stats/summary - 获取汇总统计 router.get("/stats/summary", (req, res) => { // This is handled by the stats route, but let's keep a simple version here too const db = getDB(); const { start_date, end_date } = req.query; const conditions = []; const params = []; if (start_date) { conditions.push("transaction_date >= ?"); params.push(start_date); } if (end_date) { conditions.push("transaction_date <= ?"); params.push(end_date); } const where = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : ""; const incomeResult = db .prepare( `SELECT COALESCE(SUM(amount), 0) as total FROM transactions ${where} AND direction = 'income'`, ) .get(...params); const expenseResult = db .prepare( `SELECT COALESCE(SUM(ABS(amount)), 0) as total FROM transactions ${where} AND direction = 'expense'`, ) .get(...params); const countResult = db .prepare(`SELECT COUNT(*) as total FROM transactions ${where}`) .get(...params); const unreviewedCount = db .prepare( `SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`, ) .get(...params); const categoryBreakdown = db .prepare( ` SELECT category, COUNT(*) as count, SUM(ABS(amount)) as total_amount FROM transactions ${where} AND direction = 'expense' GROUP BY category ORDER BY total_amount DESC `, ) .all(...params); res.json({ totalIncome: incomeResult.total, totalExpense: expenseResult.total, netAmount: incomeResult.total - expenseResult.total, totalCount: countResult.total, unreviewedCount: unreviewedCount.total, categoryBreakdown, }); }); module.exports = router;