version 0.3
This commit is contained in:
+151
-94
@@ -1,12 +1,12 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { runAutoReconciliation } = require('../services/matcher');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyTransactions } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/transactions - 获取交易列表(支持筛选和分页)
|
||||
router.get('/', (req, res) => {
|
||||
router.get("/", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const {
|
||||
@@ -21,8 +21,8 @@ router.get('/', (req, res) => {
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
sort_by = 'transaction_date',
|
||||
sort_order = 'DESC'
|
||||
sort_by = "transaction_date",
|
||||
sort_order = "DESC",
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
@@ -30,171 +30,220 @@ router.get('/', (req, res) => {
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push('t.transaction_date >= ?');
|
||||
conditions.push("t.transaction_date >= ?");
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push('t.transaction_date <= ?');
|
||||
conditions.push("t.transaction_date <= ?");
|
||||
params.push(end_date);
|
||||
}
|
||||
if (source_type) {
|
||||
conditions.push('t.source_type = ?');
|
||||
conditions.push("t.source_type = ?");
|
||||
params.push(source_type);
|
||||
}
|
||||
if (direction) {
|
||||
conditions.push('t.direction = ?');
|
||||
conditions.push("t.direction = ?");
|
||||
params.push(direction);
|
||||
}
|
||||
if (category) {
|
||||
conditions.push('t.category = ?');
|
||||
conditions.push("t.category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
conditions.push('t.reviewed = ?');
|
||||
conditions.push("t.reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
}
|
||||
if (min_amount) {
|
||||
conditions.push('ABS(t.amount) >= ?');
|
||||
conditions.push("ABS(t.amount) >= ?");
|
||||
params.push(parseFloat(min_amount));
|
||||
}
|
||||
if (max_amount) {
|
||||
conditions.push('ABS(t.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 ?)');
|
||||
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 whereClause =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = ['transaction_date', 'amount', 'created_at', 'counterparty', 'category', 'reviewed'];
|
||||
const safeSortBy = allowedSortFields.includes(sort_by) ? sort_by : 'transaction_date';
|
||||
const safeSortOrder = sort_order === 'ASC' ? 'ASC' : 'DESC';
|
||||
const allowedSortFields = [
|
||||
"transaction_time",
|
||||
"transaction_date",
|
||||
"amount",
|
||||
"created_at",
|
||||
"counterparty",
|
||||
"category",
|
||||
"reviewed",
|
||||
];
|
||||
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 countResult = db
|
||||
.prepare(`SELECT COUNT(*) as total FROM transactions t ${whereClause}`)
|
||||
.get(...params);
|
||||
|
||||
const transactions = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(...params, parseInt(limit), offset);
|
||||
|
||||
res.json({
|
||||
transactions,
|
||||
total: countResult.total,
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit))
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit)),
|
||||
});
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get('/:id', (req, res) => {
|
||||
router.get("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({ transaction: tx, matchedTransaction: matchedTx, relatedTransactions: relatedTxs });
|
||||
res.json({
|
||||
transaction: tx,
|
||||
matchedTransaction: matchedTx,
|
||||
relatedTransactions: relatedTxs,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put('/:id', (req, res) => {
|
||||
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);
|
||||
const tx = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push('category = ?');
|
||||
updates.push("category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push('ai_description = ?');
|
||||
updates.push("ai_description = ?");
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push('reviewed = ?');
|
||||
updates.push("reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push('reviewed_at = CURRENT_TIMESTAMP');
|
||||
updates.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push('review_notes = ?');
|
||||
updates.push("review_notes = ?");
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push('tags = ?');
|
||||
updates.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: '没有提供要更新的字段' });
|
||||
return res.status(400).json({ error: "没有提供要更新的字段" });
|
||||
}
|
||||
|
||||
updates.push('updated_at = CURRENT_TIMESTAMP');
|
||||
updates.push("updated_at = CURRENT_TIMESTAMP");
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(", ")} WHERE id = ?`).run(
|
||||
...params,
|
||||
);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
const updated = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
res.json({ success: true, transaction: updated });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 运行自动对账
|
||||
router.post('/reconcile', (req, res) => {
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const result = runAutoReconciliation();
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post('/classify', async (req, res) => {
|
||||
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列表' });
|
||||
return res.status(400).json({ error: "请提供要分类的交易ID列表" });
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -205,37 +254,28 @@ router.post('/classify', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all - 对所有未分类的交易进行分类
|
||||
router.post('/classify-all', async (req, res) => {
|
||||
// GET /api/transactions/needs-classify
|
||||
// POST /api/transactions/classify-all — 重分类过期分类的交易
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
const db = getDB();
|
||||
const unclassified = db.prepare(
|
||||
"SELECT id FROM transactions WHERE ai_category IS NULL OR ai_category = ''"
|
||||
).all();
|
||||
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: '无分类配置' });
|
||||
|
||||
if (unclassified.length === 0) {
|
||||
return res.json({ success: true, classified: 0, message: '所有交易已分类' });
|
||||
}
|
||||
|
||||
const ids = unclassified.map(r => r.id);
|
||||
try {
|
||||
// 分批处理,每批50条
|
||||
const batchSize = 50;
|
||||
let totalClassified = 0;
|
||||
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const batch = ids.slice(i, i + batchSize);
|
||||
const result = await classifyTransactions(batch);
|
||||
totalClassified += result.classified;
|
||||
}
|
||||
|
||||
res.json({ success: true, classified: totalClassified, total: ids.length });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.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;
|
||||
}
|
||||
res.json({ success: true, classified, total: ids.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
router.get('/stats/summary', (req, res) => {
|
||||
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();
|
||||
|
||||
@@ -243,33 +283,50 @@ router.get('/stats/summary', (req, res) => {
|
||||
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); }
|
||||
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 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 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 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 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 unreviewedCount = db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const categoryBreakdown = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
res.json({
|
||||
totalIncome: incomeResult.total,
|
||||
@@ -277,7 +334,7 @@ router.get('/stats/summary', (req, res) => {
|
||||
netAmount: incomeResult.total - expenseResult.total,
|
||||
totalCount: countResult.total,
|
||||
unreviewedCount: unreviewedCount.total,
|
||||
categoryBreakdown
|
||||
categoryBreakdown,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user