version 0.3
This commit is contained in:
+22
-28
@@ -107,34 +107,28 @@ function initDB() {
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_category ON transactions(category);
|
||||
`);
|
||||
|
||||
// 插入默认分类
|
||||
const insertCategory = database.prepare(
|
||||
'INSERT OR IGNORE INTO categories (id, name, keywords) VALUES (?, ?, ?)'
|
||||
);
|
||||
|
||||
const defaultCategories = [
|
||||
[1, '餐饮美食', '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[2, '交通出行', '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
|
||||
[3, '购物消费', '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
|
||||
[4, '住房相关', '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
[5, '通讯网络', '["话费","宽带","流量"]'],
|
||||
[6, '投资理财', '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
[7, '工资收入', '["工资","薪资","奖金","报销","劳务"]'],
|
||||
[8, '转账红包', '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
[9, '医疗健康', '["医院","药店","挂号","体检","保险"]'],
|
||||
[10, '教育学习', '["学费","培训","书本","课程","考试"]'],
|
||||
[11, '娱乐休闲', '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
[12, '信用卡还款', '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
[13, '其他杂项', '[]']
|
||||
];
|
||||
|
||||
const insertMany = database.transaction((cats) => {
|
||||
for (const cat of cats) {
|
||||
insertCategory.run(cat[0], cat[1], cat[2]);
|
||||
}
|
||||
});
|
||||
|
||||
insertMany(defaultCategories);
|
||||
// 仅首次初始化时插入默认分类(不再用固定ID)
|
||||
const catCount = database.prepare("SELECT COUNT(*) as c FROM categories").get().c;
|
||||
if (catCount === 0) {
|
||||
const insertCategory = database.prepare("INSERT INTO categories (name, keywords) VALUES (?, ?)");
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
["交通出行", '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
|
||||
["购物消费", '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"]
|
||||
];
|
||||
database.transaction(() => { defaults.forEach(c => insertCategory.run(c[0], c[1])); })();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
}
|
||||
|
||||
console.log('[Reco] 数据库初始化完成');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
const XLSX = require('xlsx');
|
||||
const dayjs = require('dayjs');
|
||||
|
||||
/**
|
||||
* 农业银行 XLSX 流水解析
|
||||
*
|
||||
* 多 Sheet,每个 Sheet 结构:
|
||||
* R0-R2: 元数据 (户名、币种、起止日期)
|
||||
* R3: 表头 (交易日期,交易时间,交易摘要,交易金额,,本次余额,对手信息,日志号,交易渠道,交易附言)
|
||||
* R4+: 数据(部分交易跨2行)
|
||||
*/
|
||||
|
||||
function parseABC(filePath) {
|
||||
const wb = XLSX.readFile(filePath);
|
||||
const transactions = [];
|
||||
|
||||
for (const name of wb.SheetNames) {
|
||||
const ws = wb.Sheets[name];
|
||||
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '', raw: true });
|
||||
if (!rows || rows.length < 5) continue;
|
||||
|
||||
// 收集有效数据行(跳过空行、元数据、页脚)
|
||||
const dataRows = [];
|
||||
for (let i = 4; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length === 0) continue;
|
||||
const hasContent = row.some(c => c !== '');
|
||||
const isFooter = String(row[0] || '').includes('该交易明细') || String(row[0] || '').includes('第') && String(row[0] || '').includes('页');
|
||||
if (hasContent && !isFooter) dataRows.push(row);
|
||||
}
|
||||
|
||||
// 合并多行:如果 row[0] 为空,附加到上一行
|
||||
const merged = [];
|
||||
for (const row of dataRows) {
|
||||
if (!row[0] && merged.length > 0) {
|
||||
// 合并: 时间取 row[1],对手信息拼接 row[6]
|
||||
const prev = merged[merged.length - 1];
|
||||
if (row[1] && !prev[1]) prev[1] = row[1];
|
||||
if (row[6]) prev[6] = (prev[6] || '') + row[6];
|
||||
if (row[3] && !prev[3]) prev[3] = row[3];
|
||||
} else if (row[0]) {
|
||||
merged.push([...row]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of merged) {
|
||||
const dateRaw = row[0]; // 20250507
|
||||
const timeRaw = row[1]; // 080222 或空
|
||||
const summary = String(row[2] || '').trim(); // 转支/南网电费/转存...
|
||||
const amountRaw = row[3]; // -2.85 / 832
|
||||
const balanceRaw = row[5]; // 本次余额
|
||||
const counterpartyRaw = String(row[6] || '').trim(); // 对手信息
|
||||
const channel = String(row[8] || '').trim(); // 交易渠道
|
||||
const notes = String(row[9] || '').trim(); // 交易附言
|
||||
|
||||
if (!dateRaw) continue;
|
||||
|
||||
const amount = parseFloat(amountRaw);
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
// 日期
|
||||
const ds = String(dateRaw);
|
||||
let dateStr;
|
||||
if (ds.length === 8) dateStr = `${ds.substring(0, 4)}-${ds.substring(4, 6)}-${ds.substring(6, 8)}`;
|
||||
else dateStr = dayjs(ds).format('YYYY-MM-DD');
|
||||
|
||||
// 时间
|
||||
let timeStr = '';
|
||||
const ts = String(timeRaw || '').trim();
|
||||
if (ts.length === 6) timeStr = `${ts.substring(0, 2)}:${ts.substring(2, 4)}:${ts.substring(4, 6)}`;
|
||||
const txTime = timeStr ? `${dateStr} ${timeStr}` : dateStr;
|
||||
|
||||
const direction = amount >= 0 ? 'income' : 'expense';
|
||||
const balance = balanceRaw ? parseFloat(balanceRaw) : null;
|
||||
|
||||
// 支付方式
|
||||
let method = '';
|
||||
if (channel === '电子商务') method = '电子商务';
|
||||
else if (summary.includes('转支')) method = '转账支出';
|
||||
else if (summary.includes('转存')) method = '转账存入';
|
||||
else if (summary.includes('还房贷')) method = '房贷还款';
|
||||
else if (summary.includes('电费')) method = '电费扣款';
|
||||
else if (summary.includes('还款')) method = '信用卡还款';
|
||||
else method = summary;
|
||||
|
||||
transactions.push({
|
||||
transaction_date: dateStr,
|
||||
transaction_time: txTime,
|
||||
counterparty: counterpartyRaw || '--',
|
||||
description: summary,
|
||||
notes,
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method,
|
||||
raw_data: JSON.stringify({ dateRaw, timeRaw, summary, amountRaw, balanceRaw, counterpartyRaw, channel, notes })
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseABC };
|
||||
+103
-190
@@ -1,208 +1,121 @@
|
||||
const dayjs = require("dayjs");
|
||||
const XLSX = require('xlsx');
|
||||
const iconv = require('iconv-lite');
|
||||
const fs = require('fs');
|
||||
const dayjs = require('dayjs');
|
||||
|
||||
/**
|
||||
* 支付宝账单CSV解析器
|
||||
*
|
||||
* 支付宝导出的CSV通常有两种格式:
|
||||
* 1. 标准版:交易时间,交易对方,商品说明,收/支,金额,交易状态,交易订单号,收/付款方式...
|
||||
* 2. 新版:可能列名略有不同
|
||||
*
|
||||
* 此解析器尝试自动识别列名
|
||||
*/
|
||||
function parseAlipayCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
// 跳过空行和标题行
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
// 尝试多种可能的列名映射
|
||||
const dateStr =
|
||||
record["交易时间"] ||
|
||||
record["交易日期"] ||
|
||||
record["time"] ||
|
||||
record["date"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["交易对象"] ||
|
||||
record["counterparty"] ||
|
||||
record["merchant"] ||
|
||||
"";
|
||||
const description =
|
||||
record["商品说明"] ||
|
||||
record["商品"] ||
|
||||
record["商品名称"] ||
|
||||
record["description"] ||
|
||||
record["product"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || "";
|
||||
const directionStr =
|
||||
record["收/支"] ||
|
||||
record["收支"] ||
|
||||
record["direction"] ||
|
||||
record["type"] ||
|
||||
"";
|
||||
const amountStr =
|
||||
record["金额"] || record["amount"] || record["money"] || "0";
|
||||
const status =
|
||||
record["交易状态"] || record["status"] || record["交易状态"] || "";
|
||||
const method =
|
||||
record["收/付款方式"] ||
|
||||
record["支付方式"] ||
|
||||
record["method"] ||
|
||||
record["payment"] ||
|
||||
"";
|
||||
const orderNo =
|
||||
record["交易订单号"] ||
|
||||
record["订单号"] ||
|
||||
record["order_no"] ||
|
||||
record["trade_no"] ||
|
||||
"";
|
||||
const dateStr = record['交易时间'] || record['交易创建时间'] || record['交易日期'] || record['付款时间'] || '';
|
||||
const counterparty = record['交易对方'] || record['交易对象'] || record['counterparty'] || '';
|
||||
const description = record['商品说明'] || record['商品名称'] || record['商品'] || record['description'] || '';
|
||||
const notes = record['备注'] || record['memo'] || '';
|
||||
const directionStr = record['收/支'] || record['收支'] || record['direction'] || '';
|
||||
const amountStr = record['金额'] || record['金额(元)'] || record['amount'] || '0';
|
||||
const status = record['交易状态'] || record['status'] || '';
|
||||
const method = record['收/付款方式'] || record['支付方式'] || record['method'] || '支付宝';
|
||||
const orderNo = record['交易号'] || record['交易订单号'] || record['订单号'] || '';
|
||||
|
||||
if (!dateStr && !amountStr) continue;
|
||||
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ''));
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
// 确定收支方向
|
||||
let direction = "expense";
|
||||
if (
|
||||
directionStr.includes("收入") ||
|
||||
directionStr.includes("收") ||
|
||||
directionStr === "收入"
|
||||
) {
|
||||
direction = "income";
|
||||
} else if (directionStr.includes("支") || directionStr.includes("支出")) {
|
||||
direction = "expense";
|
||||
} else if (amount > 0) {
|
||||
direction = "income";
|
||||
} else {
|
||||
amount = -Math.abs(amount);
|
||||
direction = "expense";
|
||||
}
|
||||
let direction = 'expense';
|
||||
if (directionStr.includes('收入') || directionStr === '收入') direction = 'income';
|
||||
else if (directionStr.includes('支')) direction = 'expense';
|
||||
|
||||
// 统一金额符号:支出为负
|
||||
if (direction === "expense") {
|
||||
amount = -Math.abs(amount);
|
||||
} else {
|
||||
amount = Math.abs(amount);
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
status: status.trim(),
|
||||
method: method.trim(),
|
||||
order_no: orderNo.trim(),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
function parseDate(dateStr) {
|
||||
if (!dateStr) return dayjs().format("YYYY-MM-DD");
|
||||
|
||||
// 尝试多种日期格式
|
||||
const formats = [
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm",
|
||||
"YYYY-MM-DD",
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY/MM/DD HH:mm",
|
||||
"YYYY/MM/DD",
|
||||
"MM/DD/YYYY HH:mm:ss",
|
||||
"MM/DD/YYYY",
|
||||
"YYYY年MM月DD日 HH:mm:ss",
|
||||
"YYYY年MM月DD日 HH:mm",
|
||||
"YYYY年MM月DD日",
|
||||
];
|
||||
|
||||
for (const fmt of formats) {
|
||||
const d = dayjs(dateStr, fmt);
|
||||
if (d.isValid()) return d.format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
// 最后尝试直接解析
|
||||
const d = dayjs(dateStr);
|
||||
if (d.isValid()) return d.format("YYYY-MM-DD");
|
||||
|
||||
return dayjs().format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseAlipayFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
|
||||
// 假设第一行是表头
|
||||
const headers = rows[0];
|
||||
const headerMap = {};
|
||||
headers.forEach((h, i) => {
|
||||
headerMap[h] = i;
|
||||
});
|
||||
|
||||
const transactions = [];
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length === 0) continue;
|
||||
|
||||
const dateStr = String(
|
||||
row[headerMap["交易时间"] || headerMap["交易日期"]] || row[0] || "",
|
||||
);
|
||||
const counterparty = String(
|
||||
row[headerMap["交易对方"]] || row[2] || "",
|
||||
).trim();
|
||||
const description = String(
|
||||
row[headerMap["商品说明"] || headerMap["商品"]] || row[3] || "",
|
||||
).trim();
|
||||
const directionStr = String(row[headerMap["收/支"]] || row[4] || "").trim();
|
||||
const amountRaw = row[headerMap["金额"]] || row[5] || 0;
|
||||
|
||||
let amount = parseFloat(amountRaw);
|
||||
if (isNaN(amount)) amount = 0;
|
||||
let direction = "expense";
|
||||
if (directionStr.includes("收入") || directionStr.includes("收"))
|
||||
direction = "income";
|
||||
else if (directionStr.includes("支出") || directionStr.includes("支"))
|
||||
direction = "expense";
|
||||
|
||||
if (direction === "expense") amount = -Math.abs(amount);
|
||||
if (direction === 'expense') amount = -Math.abs(amount);
|
||||
else amount = Math.abs(amount);
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty,
|
||||
description,
|
||||
notes: "",
|
||||
amount,
|
||||
direction,
|
||||
status: "",
|
||||
method: "",
|
||||
order_no: "",
|
||||
raw_data: JSON.stringify(row),
|
||||
transaction_date: parseDate(dateStr),
|
||||
transaction_time: dateStr.includes(':') ? dateStr.trim() : parseDate(dateStr),
|
||||
counterparty: counterparty.trim(), description: description.trim(), notes: notes.trim(),
|
||||
amount, direction, status: status.trim(), method, order_no: orderNo.trim(),
|
||||
raw_data: JSON.stringify(record)
|
||||
});
|
||||
}
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseAlipayCSV, parseAlipayFromXLSX, parseDate };
|
||||
function parseDate(s) {
|
||||
if (!s) return dayjs().format('YYYY-MM-DD');
|
||||
const fmts = ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm', 'YYYY-MM-DD', 'YYYY/MM/DD HH:mm:ss', 'YYYY/MM/DD'];
|
||||
for (const f of fmts) { const d = dayjs(s, f); if (d.isValid()) return d.format('YYYY-MM-DD'); }
|
||||
const d = dayjs(s); return d.isValid() ? d.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD');
|
||||
}
|
||||
|
||||
// ── 新版支付宝 GBK CSV(Tab+逗号混合分隔) ──
|
||||
|
||||
function parseAlipayFile(filePath) {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
let content;
|
||||
try { content = iconv.decode(buf, 'gbk'); } catch (e) { content = buf.toString('utf-8'); }
|
||||
|
||||
const lines = content.split('\n').filter(l => l.trim());
|
||||
if (lines.length < 5) return [];
|
||||
|
||||
const skip = ['支付宝', '账号', '起始日期', '---', '导出时间', '待收入', '已支出', '待支出', '交易号'];
|
||||
|
||||
const transactions = [];
|
||||
for (const line of lines) {
|
||||
if (skip.some(p => line.startsWith(p))) continue;
|
||||
|
||||
// 逗号分割 + 清理前导 tab 和空白
|
||||
const cols = line.split(',').map(c => c.replace(/^\t/, '').trim());
|
||||
if (cols.length < 12) continue;
|
||||
|
||||
const tradeNo = cols[0];
|
||||
const createTime = cols[2]; // 交易创建时间
|
||||
const payTime = cols[3]; // 付款时间
|
||||
const source = cols[5]; // 交易来源地
|
||||
const type = cols[6]; // 类型
|
||||
const counterparty = cols[7]; // 交易对方
|
||||
const product = cols[8]; // 商品名称
|
||||
const amountStr = cols[9]; // 金额
|
||||
const directionStr = cols[10]; // 收/支
|
||||
const status = cols[11]; // 交易状态
|
||||
const refundStr = cols[13]; // 成功退款(元)
|
||||
const notes = cols[14] || ''; // 备注
|
||||
|
||||
// 跳过:不计收支 / 已成功退款的交易
|
||||
if (directionStr.includes('不计收支')) continue;
|
||||
if (refundStr && parseFloat(refundStr) > 0) continue;
|
||||
|
||||
// 优先付款时间,退款时可能为空
|
||||
const dateStr = payTime || createTime;
|
||||
if (!dateStr || !amountStr) continue;
|
||||
|
||||
let amount = parseFloat(amountStr);
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
let direction = 'expense';
|
||||
if (directionStr.includes('收入')) direction = 'income';
|
||||
else if (directionStr.includes('不计收支')) direction = 'income';
|
||||
else if (directionStr.includes('支出')) direction = 'expense';
|
||||
|
||||
if (direction === 'expense') amount = -Math.abs(amount);
|
||||
else amount = Math.abs(amount);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parseDate(dateStr),
|
||||
transaction_time: dateStr.includes(':') ? dateStr : parseDate(dateStr),
|
||||
counterparty, description: product || type, notes, amount, direction, status,
|
||||
method: source.includes('淘宝') ? '淘宝' : '支付宝', order_no: tradeNo,
|
||||
raw_data: JSON.stringify({ cols })
|
||||
});
|
||||
}
|
||||
return transactions;
|
||||
}
|
||||
|
||||
function parseAlipayFromXLSX(filePath) {
|
||||
const wb = XLSX.readFile(filePath);
|
||||
const ws = wb.Sheets[wb.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '', raw: true });
|
||||
if (!rows || rows.length < 2) return [];
|
||||
const headers = rows[0];
|
||||
return parseAlipayCSV(rows.slice(1).map(row => { const o = {}; headers.forEach((h, i) => { o[h] = row[i]; }); return o; }));
|
||||
}
|
||||
|
||||
module.exports = { parseAlipayCSV, parseAlipayFromXLSX, parseAlipayFile };
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
const { parseDate } = require("./alipay");
|
||||
|
||||
/**
|
||||
* 银行卡流水CSV解析器
|
||||
*
|
||||
* 银行导出的CSV格式因银行而异,常见格式:
|
||||
* 交易日期,摘要,交易金额,余额,交易对方,备注
|
||||
* 交易日期,收入金额,支出金额,余额,摘要
|
||||
* 日期,类型,金额,余额,说明
|
||||
*
|
||||
* 此解析器尝试自动识别列名
|
||||
*/
|
||||
function parseBankCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
const dateStr =
|
||||
record["交易日期"] ||
|
||||
record["日期"] ||
|
||||
record["交易时间"] ||
|
||||
record["date"] ||
|
||||
record["time"] ||
|
||||
"";
|
||||
const description =
|
||||
record["摘要"] ||
|
||||
record["说明"] ||
|
||||
record["description"] ||
|
||||
record["summary"] ||
|
||||
record["用途"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["对方"] ||
|
||||
record["counterparty"] ||
|
||||
record["对方户名"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || record["附言"] || "";
|
||||
const balanceStr = record["余额"] || record["balance"] || "";
|
||||
const method =
|
||||
record["交易方式"] || record["渠道"] || record["method"] || "";
|
||||
|
||||
// 银行通常有两种格式:单列金额(正负表示方向) 或 分列收入/支出
|
||||
let amount = 0;
|
||||
let direction = "expense";
|
||||
|
||||
const amountStr =
|
||||
record["交易金额"] || record["金额"] || record["amount"] || "";
|
||||
const incomeStr =
|
||||
record["收入金额"] ||
|
||||
record["收入"] ||
|
||||
record["credit"] ||
|
||||
record["贷方金额"] ||
|
||||
"";
|
||||
const expenseStr =
|
||||
record["支出金额"] ||
|
||||
record["支出"] ||
|
||||
record["debit"] ||
|
||||
record["借方金额"] ||
|
||||
"";
|
||||
|
||||
if (
|
||||
incomeStr &&
|
||||
parseFloat(String(incomeStr).replace(/[,,¥¥\s]/g, "")) !== 0
|
||||
) {
|
||||
amount = parseFloat(String(incomeStr).replace(/[,,¥¥\s]/g, ""));
|
||||
direction = "income";
|
||||
} else if (
|
||||
expenseStr &&
|
||||
parseFloat(String(expenseStr).replace(/[,,¥¥\s]/g, "")) !== 0
|
||||
) {
|
||||
amount = -parseFloat(String(expenseStr).replace(/[,,¥¥\s]/g, ""));
|
||||
direction = "expense";
|
||||
} else if (amountStr) {
|
||||
amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (amount < 0) {
|
||||
direction = "expense";
|
||||
} else {
|
||||
direction = "income";
|
||||
}
|
||||
}
|
||||
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
let balance = null;
|
||||
if (balanceStr) {
|
||||
balance = parseFloat(String(balanceStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (isNaN(balance)) balance = null;
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method: method.trim(),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseBankFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
// Fallback: use CSV parser on the rows treated as records
|
||||
const headerRow = rows[0];
|
||||
const dataRows = rows.slice(1).map((row) => {
|
||||
const obj = {};
|
||||
headerRow.forEach((h, i) => {
|
||||
obj[h] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
return parseBankCSV(dataRows);
|
||||
}
|
||||
|
||||
module.exports = { parseBankCSV, parseBankFromXLSX };
|
||||
@@ -1,100 +0,0 @@
|
||||
const { parseDate } = require("./alipay");
|
||||
|
||||
/**
|
||||
* 信用卡账单CSV解析器
|
||||
*
|
||||
* 信用卡账单通常格式:
|
||||
* 交易日期,入账日期,交易说明,交易金额,入账金额
|
||||
* 交易日期,交易描述,人民币金额,交易类型
|
||||
*/
|
||||
function parseCreditCardCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
const dateStr =
|
||||
record["交易日期"] ||
|
||||
record["交易日"] ||
|
||||
record["date"] ||
|
||||
record["transaction_date"] ||
|
||||
"";
|
||||
const postDateStr =
|
||||
record["入账日期"] || record["记账日"] || record["post_date"] || dateStr;
|
||||
const description =
|
||||
record["交易说明"] ||
|
||||
record["交易描述"] ||
|
||||
record["description"] ||
|
||||
record["商品"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["商户名称"] ||
|
||||
record["merchant"] ||
|
||||
record["counterparty"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || "";
|
||||
|
||||
// 信用卡金额通常是正数表示消费(支出),负数表示还款(收入)
|
||||
const amountStr =
|
||||
record["交易金额"] ||
|
||||
record["人民币金额"] ||
|
||||
record["金额"] ||
|
||||
record["amount"] ||
|
||||
"0";
|
||||
const postAmountStr = record["入账金额"] || record["记账金额"] || "";
|
||||
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
// 信用卡:正数=消费(欠款增加,对用户来说是支出)
|
||||
let direction = "expense";
|
||||
if (amount < 0) {
|
||||
direction = "income"; // 负数=还款/退款
|
||||
amount = Math.abs(amount); // 存储为正值收入
|
||||
} else {
|
||||
amount = -Math.abs(amount); // 存储为负值支出
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
post_date: parseDate(postDateStr),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseCreditFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
const headerRow = rows[0];
|
||||
const dataRows = rows.slice(1).map((row) => {
|
||||
const obj = {};
|
||||
headerRow.forEach((h, i) => {
|
||||
obj[h] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
return parseCreditCardCSV(dataRows);
|
||||
}
|
||||
|
||||
module.exports = { parseCreditCardCSV, parseCreditFromXLSX };
|
||||
@@ -59,11 +59,13 @@ function parseSPDBXLS(filePath) {
|
||||
const balance = balanceStr ? parseFloat(balanceStr) : null;
|
||||
|
||||
// 日期/时间解析
|
||||
const parsed = dayjs(dateStr, [
|
||||
let parsed = dayjs(dateStr, [
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY/MM/DD",
|
||||
]);
|
||||
// UTC → CST (+8h)
|
||||
parsed = parsed.add(8, "hour");
|
||||
const txDate = parsed.format("YYYY-MM-DD");
|
||||
const txTime = parsed.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
|
||||
+41
-220
@@ -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
@@ -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
@@ -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 });
|
||||
});
|
||||
|
||||
|
||||
+58
-149
@@ -1,63 +1,54 @@
|
||||
const { getDB } = require("../db");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json');
|
||||
|
||||
/**
|
||||
* LLM 服务:调用大模型对交易进行分类和描述
|
||||
*
|
||||
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
|
||||
* 如果未配置 API Key,使用本地规则进行降级分类
|
||||
*/
|
||||
let openaiClient = null;
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
|
||||
} catch (e) {}
|
||||
return {};
|
||||
}
|
||||
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
}
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
|
||||
const db = getDB();
|
||||
const apiKey = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
|
||||
.get();
|
||||
const baseURL = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
|
||||
.get();
|
||||
const model = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
|
||||
.get();
|
||||
const cfg = loadConfig();
|
||||
const apiKey = cfg.llm_api_key;
|
||||
const baseURL = cfg.llm_base_url || 'https://api.openai.com/v1';
|
||||
const model = cfg.llm_model || 'gpt-4o-mini';
|
||||
|
||||
if (!apiKey || !apiKey.value) return null;
|
||||
|
||||
const { OpenAI } = require("openai");
|
||||
|
||||
openaiClient = new OpenAI({
|
||||
apiKey: apiKey.value,
|
||||
baseURL: (baseURL && baseURL.value) || "https://api.openai.com/v1",
|
||||
});
|
||||
|
||||
openaiClient._model = (model && model.value) || "gpt-4o-mini";
|
||||
if (!apiKey) return null;
|
||||
|
||||
const { OpenAI } = require('openai');
|
||||
openaiClient = new OpenAI({ apiKey, baseURL });
|
||||
openaiClient._model = model;
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分类 Prompt
|
||||
*/
|
||||
function buildClassificationPrompt(transactions) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
const categories = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const categoryList = categories
|
||||
.map(
|
||||
(c) =>
|
||||
`${c.name}(关键词:${JSON.parse(c.keywords || "[]").join("、")})`,
|
||||
)
|
||||
.join("\n");
|
||||
.map(c => `${c.name}(关键词:${JSON.parse(c.keywords || '[]').join('、')})`)
|
||||
.join('\n');
|
||||
|
||||
const txList = transactions
|
||||
.map(
|
||||
(tx, i) =>
|
||||
`[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || "未知"} | 描述:${tx.description || "无"} | 来源:${tx.source_type}`,
|
||||
)
|
||||
.join("\n");
|
||||
const txList = transactions.map((tx, i) =>
|
||||
`[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || '未知'} | 描述:${tx.description || '无'} | 来源:${tx.source_type}`
|
||||
).join('\n');
|
||||
|
||||
return `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
@@ -77,148 +68,66 @@ ${txList}
|
||||
仅返回JSON数组,不要包含其他内容。`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分类交易
|
||||
*/
|
||||
async function classifyTransactions(transactionIds) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
|
||||
const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds];
|
||||
|
||||
const transactions = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM transactions WHERE id IN (${ids.map(() => "?").join(",")})
|
||||
`,
|
||||
)
|
||||
.all(...ids);
|
||||
|
||||
const transactions = db.prepare(`SELECT * FROM transactions WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
if (transactions.length === 0) return { classified: 0 };
|
||||
|
||||
// 尝试使用LLM
|
||||
const client = getOpenAIClient();
|
||||
|
||||
if (client) {
|
||||
try {
|
||||
const prompt = buildClassificationPrompt(transactions);
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
{ role: 'system', content: '你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 2000,
|
||||
temperature: 0.3, max_tokens: 2000,
|
||||
});
|
||||
|
||||
const content = response.choices[0].message.content;
|
||||
const jsonMatch = content.match(/\[[\s\S]*\]/);
|
||||
if (jsonMatch) {
|
||||
const results = JSON.parse(jsonMatch[0]);
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`);
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const tx = transactions[item.index - 1];
|
||||
if (tx) {
|
||||
updateStmt.run(
|
||||
item.category,
|
||||
item.description,
|
||||
item.confidence,
|
||||
item.category,
|
||||
tx.id,
|
||||
);
|
||||
}
|
||||
if (tx) updateStmt.run(item.category, item.description, item.confidence, item.category, tx.id);
|
||||
}
|
||||
})();
|
||||
|
||||
return { classified: results.length, source: "llm" };
|
||||
return { classified: results.length, source: 'llm' };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
|
||||
console.error('[Reco] LLM分类失败,降级规则匹配:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:使用本地关键词规则分类
|
||||
return classifyByRules(transactions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地关键词规则分类(无需LLM)
|
||||
*/
|
||||
function classifyByRules(transactions) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
const categories = db.prepare('SELECT id, name, keywords FROM categories').all();
|
||||
const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`);
|
||||
let classified = 0;
|
||||
let needsReview = 0;
|
||||
|
||||
for (const tx of transactions) {
|
||||
const text =
|
||||
`${tx.description || ""} ${tx.counterparty || ""} ${tx.notes || ""}`.toLowerCase();
|
||||
|
||||
// 金额超过100元标记为需要人工确认
|
||||
const largeAmount = Math.abs(tx.amount) >= 100;
|
||||
|
||||
// 关键词匹配
|
||||
let bestCategory = "其他杂项";
|
||||
let bestScore = 0;
|
||||
|
||||
const text = `${tx.description || ''} ${tx.counterparty || ''} ${tx.notes || ''}`.toLowerCase();
|
||||
let bestCategory = '其他杂项', bestScore = 0;
|
||||
for (const cat of categories) {
|
||||
const keywords = JSON.parse(cat.keywords || "[]");
|
||||
let score = 0;
|
||||
for (const kw of keywords) {
|
||||
if (text.includes(kw.toLowerCase())) {
|
||||
score++;
|
||||
}
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestCategory = cat.name;
|
||||
}
|
||||
for (const kw of JSON.parse(cat.keywords || '[]')) { if (text.includes(kw.toLowerCase())) score++; }
|
||||
if (score > bestScore) { bestScore = score; bestCategory = cat.name; }
|
||||
}
|
||||
|
||||
// 生成简单描述
|
||||
let aiDescription = "";
|
||||
if (tx.direction === "income") {
|
||||
aiDescription = `收到${tx.counterparty || "对方"} ${Math.abs(tx.amount).toFixed(2)}元`;
|
||||
} else {
|
||||
aiDescription = `向${tx.counterparty || "对方"}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? "(" + tx.description + ")" : ""}`;
|
||||
}
|
||||
|
||||
updateStmt.run(
|
||||
bestCategory,
|
||||
aiDescription.substring(0, 100),
|
||||
bestScore > 0 ? 0.7 : 0.3,
|
||||
bestCategory,
|
||||
tx.id,
|
||||
);
|
||||
|
||||
const desc = tx.direction === 'income'
|
||||
? `收到${tx.counterparty || '对方'} ${Math.abs(tx.amount).toFixed(2)}元`
|
||||
: `向${tx.counterparty || '对方'}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? '(' + tx.description + ')' : ''}`;
|
||||
updateStmt.run(bestCategory, desc.substring(0, 100), bestScore > 0 ? 0.7 : 0.3, bestCategory, tx.id);
|
||||
classified++;
|
||||
if (largeAmount) needsReview++;
|
||||
}
|
||||
|
||||
return { classified, needsReview, source: "rules" };
|
||||
return { classified, source: 'rules' };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient };
|
||||
module.exports = { classifyTransactions, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
|
||||
Reference in New Issue
Block a user