version 0.1

This commit is contained in:
2026-05-05 14:53:38 +08:00
parent 1da3bf9dd9
commit 6402a03026
27 changed files with 24704 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
const express = require('express');
const { classifyTransactions } = require('../services/llm');
const router = express.Router();
// POST /api/classify - 对指定交易进行分类
router.post('/', 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) {
console.error('[Reco] 分类失败:', err);
res.status(500).json({ error: err.message });
}
});
module.exports = router;
+250
View File
@@ -0,0 +1,250 @@
const express = require("express");
const { getDB } = require("../db");
const router = express.Router();
// GET /api/config - 获取所有配置
router.get("/", (req, res) => {
const db = getDB();
const configs = db.prepare("SELECT key, value FROM config").all();
const configMap = {};
for (const c of configs) {
configMap[c.key] = c.value;
}
res.json(configMap);
});
// PUT /api/config - 更新配置
router.put("/", (req, res) => {
const db = getDB();
const updates = req.body;
if (!updates || Object.keys(updates).length === 0) {
return res.status(400).json({ error: "请提供要更新的配置" });
}
const upsert = db.prepare(
"INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?",
);
db.transaction(() => {
for (const [key, value] of Object.entries(updates)) {
upsert.run(key, String(value), String(value));
}
})();
res.json({ success: true });
});
// POST /api/config/test-llm - 测试LLM连接(详细调试版)
router.post("/test-llm", async (req, res) => {
const { getOpenAIClient } = require("../services/llm");
console.log("[Reco] ========== LLM 连接测试开始 ==========");
// 1. 检查数据库配置
const db = getDB();
const apiKeyRow = db
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
.get();
const baseUrlRow = db
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
.get();
const modelRow = db
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
.get();
console.log("[Reco] [调试] 数据库配置检查:");
console.log(" API Key 存在:", !!apiKeyRow?.value);
console.log(" API Key 长度:", apiKeyRow?.value?.length || 0);
console.log(
" Base URL:",
baseUrlRow?.value || "(使用默认 https://api.openai.com/v1)",
);
console.log(" Model:", modelRow?.value || "(使用默认 gpt-4o-mini)");
// 2. 尝试创建客户端
let client;
try {
client = getOpenAIClient();
} catch (clientErr) {
console.error("[Reco] [调试] 创建LLM客户端异常:", clientErr.message);
return res.status(500).json({
error: `创建LLM客户端失败: ${clientErr.message}`,
debug: { errorType: "client_init_error", errorDetail: clientErr.message },
});
}
if (!client) {
console.log("[Reco] [调试] LLM客户端为空 - 请检查API Key配置");
return res.status(400).json({
error: "请先在系统设置中配置 LLM API Key",
debug: {
hasApiKey: !!apiKeyRow?.value,
hasBaseUrl: !!baseUrlRow?.value,
hasModel: !!modelRow?.value,
hint: "前往 系统设置 → 大模型配置 填入API Key",
},
});
}
console.log("[Reco] [调试] LLM客户端创建成功");
console.log(" Model:", client._model);
console.log(" BaseURL:", client.baseURL || "(未暴露)");
// 3. 发送测试请求
const startTime = Date.now();
try {
console.log("[Reco] [调试] 正在发送测试请求 (timeout: 15s)...");
const response = await client.chat.completions.create({
model: client._model,
messages: [{ role: "user", content: '请回复"连接成功"两个字' }],
max_tokens: 10,
timeout: 15000,
});
const elapsed = Date.now() - startTime;
const reply = response.choices?.[0]?.message?.content || "(空)";
console.log(`[Reco] [调试] ✅ LLM测试成功!`);
console.log(` 耗时: ${elapsed}ms`);
console.log(` 回复: "${reply}"`);
console.log(
` Token用量:`,
response.usage ? JSON.stringify(response.usage) : "未返回",
);
res.json({
success: true,
reply,
model: client._model,
elapsed_ms: elapsed,
usage: response.usage || null,
});
} catch (err) {
const elapsed = Date.now() - startTime;
console.error(`[Reco] [调试] ❌ LLM测试失败! 耗时: ${elapsed}ms`);
console.error(" 错误类型:", err.constructor?.name || typeof err);
console.error(" 错误消息:", err.message);
console.error(" 错误代码:", err.code || "(无)");
console.error(" HTTP状态码:", err.status || err.statusCode || "(无)");
// OpenAI SDK v4 的错误详情
if (err.error) {
console.error(" API错误详情:", JSON.stringify(err.error));
}
if (err.response) {
console.error(" 响应状态:", err.response.status);
console.error(
" 响应头:",
JSON.stringify(err.response.headers || {}).substring(0, 300),
);
try {
console.error(
" 响应体:",
JSON.stringify(
err.response.data || err.response.body || {},
).substring(0, 800),
);
} catch (e) {}
}
if (err.stack) {
console.error(" 堆栈(首500):", err.stack.substring(0, 500));
}
res.status(500).json({
error: `LLM 连接失败: ${err.message}`,
debug: {
errorType: err.constructor?.name || typeof err,
errorCode: err.code || null,
httpStatus: err.status || err.statusCode || null,
elapsed_ms: elapsed,
apiBaseUrl: baseUrlRow?.value || "https://api.openai.com/v1",
model: client._model,
hint: getHint(err),
},
});
}
console.log("[Reco] ========== LLM 连接测试结束 ==========");
});
function getHint(err) {
const msg = (err.message || "").toLowerCase();
if (
msg.includes("401") ||
msg.includes("unauthorized") ||
msg.includes("invalid api key")
) {
return "API Key 无效或未授权,请检查 Key 是否正确";
}
if (msg.includes("404") || msg.includes("not found")) {
return "模型名称或API端点不存在,请检查 Base URL 和模型名";
}
if (
msg.includes("timeout") ||
msg.includes("etimedout") ||
msg.includes("enotfound")
) {
return "网络连接超时或DNS解析失败,请检查 Base URL 和网络";
}
if (msg.includes("429") || msg.includes("rate")) {
return "请求频率过高或被限流,请稍后重试";
}
if (
msg.includes("connect") ||
msg.includes("refused") ||
msg.includes("econnrefused")
) {
return "无法连接到API服务器,请确认 Base URL 正确且服务正在运行";
}
return "请检查 API Key、Base URL 和 Model 配置是否正确";
}
// GET /api/config/categories - 获取分类列表
router.get("/categories", (req, res) => {
const db = getDB();
const categories = db.prepare("SELECT * FROM categories ORDER BY id").all();
res.json(categories);
});
// PUT /api/config/categories/:id - 更新分类
router.put("/categories/:id", (req, res) => {
const db = getDB();
const { name, keywords } = req.body;
db.prepare(
"UPDATE categories SET name = COALESCE(?, name), keywords = COALESCE(?, keywords) WHERE id = ?",
).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
res.json({ success: true });
});
// POST /api/config/categories - 新增分类
router.post("/categories", (req, res) => {
const db = getDB();
const { name, keywords, parent_id } = req.body;
if (!name) {
return res.status(400).json({ error: "分类名称不能为空" });
}
const result = db
.prepare(
"INSERT INTO categories (name, keywords, parent_id) VALUES (?, ?, ?)",
)
.run(name, JSON.stringify(keywords || []), parent_id || null);
res.json({ success: true, id: result.lastInsertRowid });
});
// DELETE /api/config/categories/:id - 删除分类
router.delete("/categories/:id", (req, res) => {
const db = getDB();
db.prepare("DELETE FROM categories WHERE id = ?").run(req.params.id);
res.json({ success: true });
});
module.exports = router;
+110
View File
@@ -0,0 +1,110 @@
const express = require('express');
const { getDB } = require('../db');
const router = express.Router();
// GET /api/stats/overview - 总览统计
router.get('/overview', (req, res) => {
const db = getDB();
const { year, month } = req.query;
let dateCondition = '';
const params = [];
if (year) {
dateCondition = 'WHERE strftime(\'%Y\', transaction_date) = ?';
params.push(String(year));
if (month) {
dateCondition += ' AND strftime(\'%m\', transaction_date) = ?';
params.push(String(month).padStart(2, '0'));
}
}
const stats = db.prepare(`
SELECT
COUNT(*) as total_count,
COALESCE(SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END), 0) as total_income,
COALESCE(SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END), 0) as total_expense,
COUNT(CASE WHEN reviewed = 0 AND ABS(amount) >= 100 THEN 1 END) as pending_review,
COUNT(CASE WHEN reviewed = 1 THEN 1 END) as reviewed_count,
COUNT(CASE WHEN matched_transaction_id IS NOT NULL THEN 1 END) as matched_count
FROM transactions
${dateCondition}
`).get(...params);
// 按分类统计支出
const categoryStats = db.prepare(`
SELECT
category,
COUNT(*) as count,
SUM(ABS(amount)) as total_amount,
AVG(ABS(amount)) as avg_amount
FROM transactions
${dateCondition}${dateCondition ? ' AND' : 'WHERE'} direction = 'expense' AND category IS NOT NULL
GROUP BY category
ORDER BY total_amount DESC
`).all(...params);
// 按来源统计
const sourceStats = db.prepare(`
SELECT
t.source_type,
s.source_name,
COUNT(*) as count,
SUM(CASE WHEN t.direction = 'income' THEN t.amount ELSE 0 END) as total_income,
SUM(CASE WHEN t.direction = 'expense' THEN ABS(t.amount) ELSE 0 END) as total_expense
FROM transactions t
LEFT JOIN sources s ON s.id = t.source_id
${dateCondition}
GROUP BY t.source_type
ORDER BY total_expense DESC
`).all(...params);
res.json({
overview: stats,
categoryStats,
sourceStats
});
});
// GET /api/stats/monthly - 月度趋势
router.get('/monthly', (req, res) => {
const db = getDB();
const { months = 12 } = req.query;
const monthlyData = db.prepare(`
SELECT
strftime('%Y-%m', transaction_date) as month,
COUNT(*) as count,
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
FROM transactions
WHERE transaction_date >= DATE('now', '-${parseInt(months)} months')
GROUP BY strftime('%Y-%m', transaction_date)
ORDER BY month ASC
`).all();
res.json(monthlyData);
});
// GET /api/stats/daily - 每日统计
router.get('/daily', (req, res) => {
const db = getDB();
const { days = 30 } = req.query;
const dailyData = db.prepare(`
SELECT
transaction_date as date,
COUNT(*) as count,
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
FROM transactions
WHERE transaction_date >= DATE('now', '-${parseInt(days)} days')
GROUP BY transaction_date
ORDER BY date ASC
`).all();
res.json(dailyData);
});
module.exports = router;
+284
View File
@@ -0,0 +1,284 @@
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) => {
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_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 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))
});
});
// 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 - 运行自动对账
router.post('/reconcile', (req, res) => {
const result = runAutoReconciliation();
res.json({ success: true, ...result });
});
// 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 });
}
});
// 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();
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 });
}
});
// 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;
+229
View File
@@ -0,0 +1,229 @@
const express = require("express");
const multer = require("multer");
const { parse } = require("csv-parse/sync");
const crypto = require("crypto");
const path = require("path");
const fs = require("fs");
const { getDB } = require("../db");
const { parseAlipayCSV, parseAlipayFromXLSX } = require("../parsers/alipay");
const { parseWechatCSV, parseWechatXLSX } = require("../parsers/wechat");
const { parseBankCSV, parseBankFromXLSX } = require("../parsers/bank");
const {
parseCreditCardCSV,
parseCreditFromXLSX,
} = require("../parsers/credit");
const { parseSPDBXLS } = require("../parsers/spdb");
const { generateTransactionCode } = require("../utils/transactionCode");
const { classifyTransactions } = require("../services/llm");
const router = express.Router();
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
const ALLOWED_EXTS = [".csv", ".txt", ".xlsx", ".xls"];
const upload = multer({
storage: multer.diskStorage({
destination: uploadDir,
filename: (req, file, cb) =>
cb(
null,
Date.now() +
"-" +
Math.round(Math.random() * 1e9) +
path.extname(file.originalname),
),
}),
fileFilter: (req, file, cb) => {
if (ALLOWED_EXTS.includes(path.extname(file.originalname).toLowerCase()))
cb(null, true);
else cb(new Error("仅支持 CSV / TXT / XLSX / XLS 文件格式"));
},
limits: { fileSize: 20 * 1024 * 1024 },
});
router.post("/", upload.single("file"), async (req, res) => {
try {
const { source_type, source_name } = req.body;
if (
!source_type ||
![
"alipay",
"wechat",
"bank_debit",
"bank_credit",
"credit_card",
].includes(source_type)
) {
return res.status(400).json({ error: "无效的账单类型" });
}
if (!req.file) return res.status(400).json({ error: "请选择要上传的文件" });
const fileExt = path.extname(req.file.originalname).toLowerCase();
const isExcel = [".xlsx", ".xls"].includes(fileExt);
console.log(
`[Reco] 上传: ${req.file.originalname} type=${source_type} ext=${fileExt}`,
);
const fileBuffer = fs.readFileSync(req.file.path);
const fileHash = crypto.createHash("md5").update(fileBuffer).digest("hex");
const db = getDB();
const existing = db
.prepare("SELECT id FROM sources WHERE file_hash = ?")
.get(fileHash);
if (existing) {
fs.unlinkSync(req.file.path);
return res
.status(409)
.json({ error: "该文件已导入过", source_id: existing.id });
}
let parsedTransactions;
if (isExcel) {
console.log(`[Reco] XLSX解析: ${source_type}`);
switch (source_type) {
case "alipay":
parsedTransactions = parseAlipayFromXLSX(req.file.path);
break;
case "wechat":
parsedTransactions = parseWechatXLSX(req.file.path);
break;
case "bank_debit":
case "bank_credit":
parsedTransactions = parseSPDBXLS(req.file.path);
break;
case "credit_card":
parsedTransactions = parseCreditFromXLSX(req.file.path);
break;
}
} else {
const content = fileBuffer.toString("utf-8");
let records;
try {
records = parse(content, {
columns: true,
skip_empty_lines: true,
bom: true,
relax_column_count: true,
trim: true,
});
} catch (e) {
return res.status(400).json({ error: `CSV解析失败: ${e.message}` });
}
if (!records?.length)
return res.status(400).json({ error: "文件中无有效记录" });
switch (source_type) {
case "alipay":
parsedTransactions = parseAlipayCSV(records);
break;
case "wechat":
parsedTransactions = parseWechatCSV(records);
break;
case "bank_debit":
case "bank_credit":
parsedTransactions = parseBankCSV(records);
break;
case "credit_card":
parsedTransactions = parseCreditCardCSV(records);
break;
}
}
if (!parsedTransactions?.length)
return res.status(400).json({ error: "未能解析出交易记录" });
console.log(`[Reco] 解析完成: ${parsedTransactions.length}条`);
const sourceName =
source_name || `${source_type}_${new Date().toISOString().slice(0, 10)}`;
const src = db
.prepare(
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?, ?, ?, ?, ?)",
)
.run(
source_type,
sourceName,
req.file.originalname,
fileHash,
parsedTransactions.length,
);
const insertTx = db.prepare(`INSERT OR IGNORE INTO transactions (
transaction_code, source_id, source_type, transaction_date, transaction_time,
counterparty, description, notes, amount, direction, status, method, balance, tags
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
const ids = [];
let skip = 0;
for (const tx of parsedTransactions) {
const code = generateTransactionCode(
tx.transaction_date,
tx.amount,
tx.counterparty,
tx.description,
);
const r = insertTx.run(
code,
src.lastInsertRowid,
source_type,
tx.transaction_date,
tx.transaction_time,
tx.counterparty,
tx.description,
tx.notes || "",
tx.amount,
tx.direction,
tx.status || "",
tx.method || "",
tx.balance || null,
null,
);
if (r.changes > 0) ids.push(r.lastInsertRowid);
else skip++;
}
console.log(`[Reco] 写入: ${ids.length}条, 跳过: ${skip}条`);
let classifyResult = { classified: 0, source: "none" };
if (ids.length > 0) {
try {
classifyResult = await classifyTransactions(ids);
} catch (e) {}
}
res.json({
success: true,
source_id: src.lastInsertRowid,
source_name: sourceName,
source_type,
file_name: req.file.originalname,
record_count: parsedTransactions.length,
inserted: ids.length,
skipped: skip,
classified: classifyResult.classified,
classify_source: classifyResult.source,
sample: parsedTransactions.slice(0, 5),
});
} catch (err) {
console.error("[Reco] 上传失败:", err);
res.status(500).json({ error: err.message });
}
});
router.get("/sources", (req, res) => {
const db = getDB();
res.json(
db
.prepare(
`SELECT s.*, COUNT(t.id) as tx_count FROM sources s LEFT JOIN transactions t ON t.source_id = s.id GROUP BY s.id ORDER BY s.imported_at DESC`,
)
.all(),
);
});
router.delete("/sources/:id", (req, res) => {
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
res.json({ success: true });
});
module.exports = router;