version 0.3

This commit is contained in:
2026-05-05 16:36:57 +08:00
parent 9a963623a8
commit fa5637b5ca
25 changed files with 3090 additions and 2975 deletions
+41 -220
View File
@@ -1,249 +1,70 @@
const express = require("express");
const { getDB } = require("../db");
const express = require('express');
const { getDB } = require('../db');
const { loadConfig, saveConfig, getOpenAIClient, resetClient } = require('../services/llm');
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);
// GET /api/config
router.get('/', (req, res) => {
res.json(loadConfig());
});
// 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));
}
})();
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
router.put('/', (req, res) => {
const cfg = { ...loadConfig(), ...req.body };
saveConfig(cfg);
resetClient();
res.json({ success: true });
});
// POST /api/config/test-llm - 测试LLM连接(详细调试版)
router.post("/test-llm", async (req, res) => {
const { getOpenAIClient } = require("../services/llm");
// POST /api/config/test-llm
router.post('/test-llm', async (req, res) => {
console.log('[Reco] === LLM 连接测试 ===');
const cfg = loadConfig();
console.log(' API Key:', cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + '...' : '(无)');
console.log(' Base URL:', cfg.llm_base_url || '默认');
console.log(' Model:', cfg.llm_model || '默认');
console.log("[Reco] ========== LLM 连接测试开始 ==========");
const client = getOpenAIClient();
if (!client) return res.status(400).json({ error: '请先配置 LLM API Key' });
// 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;
const t0 = Date.now();
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({
const resp = 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,
messages: [{ role: 'user', content: '回复"连接成功"' }],
max_tokens: 10, timeout: 15000,
});
const reply = resp.choices?.[0]?.message?.content || '(空)';
console.log(` 成功 ${Date.now() - t0}ms: ${reply}`);
res.json({ success: true, reply, model: client._model, elapsed_ms: Date.now() - t0 });
} 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.error(` 失败 ${Date.now() - t0}ms:`, err.message);
res.status(500).json({ error: `连接失败: ${err.message}` });
}
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);
// Categories
router.get('/categories', (req, res) => {
res.json(getDB().prepare('SELECT * FROM categories ORDER BY id').all());
});
// PUT /api/config/categories/:id - 更新分类
router.put("/categories/:id", (req, res) => {
const db = getDB();
router.put('/categories/:id', (req, res) => {
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);
getDB().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();
router.post('/categories', (req, res) => {
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 (?, ?, ?)",
)
if (!name) return res.status(400).json({ error: '分类名称不能为空' });
const r = getDB().prepare('INSERT INTO categories (name,keywords,parent_id) VALUES (?,?,?)')
.run(name, JSON.stringify(keywords || []), parent_id || null);
res.json({ success: true, id: result.lastInsertRowid });
res.json({ success: true, id: r.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);
router.delete('/categories/:id', (req, res) => {
getDB().prepare('DELETE FROM categories WHERE id=?').run(req.params.id);
res.json({ success: true });
});
+151 -94
View File
@@ -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,
});
});
+63 -174
View File
@@ -1,228 +1,117 @@
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 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 { parseAlipayFile, parseAlipayFromXLSX } = require('../parsers/alipay');
const { parseWechatCSV, parseWechatXLSX } = require('../parsers/wechat');
const { parseSPDBXLS } = require('../parsers/spdb');
const { parseABC } = require('../parsers/abc');
const { generateTransactionCode } = require('../utils/transactionCode');
const { classifyTransactions } = require('../services/llm');
const router = express.Router();
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
const uploadDir = path.join(__dirname, '..', '..', 'data', 'uploads');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
const ALLOWED_EXTS = [".csv", ".txt", ".xlsx", ".xls"];
const ALLOWED_EXTS = ['.csv', '.txt', '.xlsx', '.xls'];
const VALID_TYPES = ['alipay', 'wechat', 'bank_debit', 'abc'];
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),
),
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 文件格式"));
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 },
limits: { fileSize: 20 * 1024 * 1024 }
});
router.post("/", upload.single("file"), async (req, res) => {
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: "请选择要上传的文件" });
if (!VALID_TYPES.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 isExcel = ['.xlsx', '.xls'].includes(fileExt);
const fileBuffer = fs.readFileSync(req.file.path);
const fileHash = crypto.createHash("md5").update(fileBuffer).digest("hex");
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) {
if (db.prepare('SELECT id FROM sources WHERE file_hash = ?').get(fileHash)) {
fs.unlinkSync(req.file.path);
return res
.status(409)
.json({ error: "该文件已导入过", source_id: existing.id });
return res.status(409).json({ error: '该文件已导入过' });
}
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;
case 'alipay': parsedTransactions = parseAlipayFromXLSX(req.file.path); break;
case 'wechat': parsedTransactions = parseWechatXLSX(req.file.path); break;
case 'bank_debit': parsedTransactions = parseSPDBXLS(req.file.path); break;
case 'abc': parsedTransactions = parseABC(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;
// CSV: alipay uses GBK parser, wechat/bank use csv-parse
if (source_type === 'alipay') {
parsedTransactions = parseAlipayFile(req.file.path);
} 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: `解析失败: ${e.message}` }); }
if (!records?.length) return res.status(400).json({ error: '无有效记录' });
parsedTransactions = parseWechatCSV(records);
}
}
if (!parsedTransactions?.length)
return res.status(400).json({ error: "未能解析出交易记录" });
console.log(`[Reco] 解析完成: ${parsedTransactions.length}条`);
if (!parsedTransactions?.length) return res.status(400).json({ error: '未能解析出交易记录' });
console.log(`[Reco] ${source_type}: ${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 src = db.prepare('INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?,?,?,?,?)')
.run(source_type, source_name || source_type, req.file.originalname, fileHash, parsedTransactions.length);
const insertTx = db.prepare(`INSERT OR IGNORE INTO transactions (
const ins = 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
const ids = [];
let skip = 0;
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++;
const code = generateTransactionCode(tx.transaction_date, tx.amount, tx.counterparty, tx.description);
const r = ins.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) {}
}
let classifyResult = { classified: 0, source: 'none' };
if (ids.length) 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),
success: true, source_id: src.lastInsertRowid, source_name: source_name || source_type, source_type,
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);
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.get('/sources', (req, res) => {
res.json(getDB().prepare('SELECT s.*, COUNT(t.id) 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);
router.delete('/sources/:id', (req, res) => {
getDB().prepare('DELETE FROM sources WHERE id = ?').run(req.params.id);
res.json({ success: true });
});