version 0.1
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
const XLSX = require("xlsx");
|
||||
const dayjs = require("dayjs");
|
||||
|
||||
/**
|
||||
* 浦发银行 XLS/XLSX 流水解析
|
||||
*
|
||||
* 格式:
|
||||
* Row 0: 元数据 (账号, 账户类型, 日期范围)
|
||||
* Row 1: 表头 (顺序号, 交易日期, 交易类型, 存入金额, 取出金额, 余额, 交易对手名称, 交易对手账号, 附言)
|
||||
* Row 2+: 数据
|
||||
*/
|
||||
|
||||
function parseSPDBXLS(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 3) return [];
|
||||
|
||||
// 提取账号
|
||||
const accountNo = String(rows[0][1] || "");
|
||||
|
||||
const transactions = [];
|
||||
|
||||
for (let i = 2; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length < 8) continue;
|
||||
|
||||
const dateStr = String(row[1] || "").trim(); // "2025/05/06 01:12:46"
|
||||
const typeRaw = String(row[2] || "").trim(); // "网上支付-财付通—来伊份"
|
||||
const depositStr = row[3]; // 存入金额
|
||||
const withdrawStr = row[4]; // 取出金额
|
||||
const balanceStr = row[5]; // 余额
|
||||
const counterparty = String(row[6] || "").trim(); // 对手名称
|
||||
const opponentAcct = String(row[7] || "").trim(); // 对手账号
|
||||
const appendix = String(row[8] || "").trim(); // 附言
|
||||
|
||||
if (!dateStr) continue;
|
||||
|
||||
// 金额:存入或取出
|
||||
let amount = 0;
|
||||
let direction = "expense";
|
||||
if (depositStr !== "" && depositStr !== undefined && depositStr !== null) {
|
||||
amount = parseFloat(depositStr);
|
||||
direction = "income";
|
||||
} else if (
|
||||
withdrawStr !== "" &&
|
||||
withdrawStr !== undefined &&
|
||||
withdrawStr !== null
|
||||
) {
|
||||
amount = -parseFloat(withdrawStr);
|
||||
direction = "expense";
|
||||
}
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
const balance = balanceStr ? parseFloat(balanceStr) : null;
|
||||
|
||||
// 日期/时间解析
|
||||
const parsed = dayjs(dateStr, [
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY/MM/DD",
|
||||
]);
|
||||
const txDate = parsed.format("YYYY-MM-DD");
|
||||
const txTime = parsed.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
// 交易类型拆解: "网上支付-财付通—来伊份" → type="网上支付-财付通", desc="网上支付-财付通—来伊份"
|
||||
let description = typeRaw;
|
||||
let txType = typeRaw;
|
||||
const dashIdx = typeRaw.indexOf("—");
|
||||
if (dashIdx > 0) {
|
||||
txType = typeRaw.substring(0, dashIdx);
|
||||
}
|
||||
|
||||
// 支付方式
|
||||
let method = "";
|
||||
if (typeRaw.includes("财付通")) method = "财付通";
|
||||
else if (typeRaw.includes("支付宝")) method = "支付宝";
|
||||
else if (typeRaw.includes("工资")) method = "代发工资";
|
||||
else if (typeRaw.includes("转账")) method = "银行转账";
|
||||
else if (typeRaw.includes("银联")) method = "银联";
|
||||
else method = txType;
|
||||
|
||||
transactions.push({
|
||||
transaction_date: txDate,
|
||||
transaction_time: txTime,
|
||||
counterparty,
|
||||
description,
|
||||
notes: appendix, // 附言
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method,
|
||||
account_no: accountNo,
|
||||
opponent_account: opponentAcct,
|
||||
raw_data: JSON.stringify({
|
||||
dateStr,
|
||||
typeRaw,
|
||||
depositStr,
|
||||
withdrawStr,
|
||||
balanceStr,
|
||||
counterparty,
|
||||
opponentAcct,
|
||||
appendix,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseSPDBXLS };
|
||||
@@ -0,0 +1,23 @@
|
||||
const express = require('express');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/classify - 对指定交易进行分类
|
||||
router.post('/', async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: '请提供交易ID列表' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error('[Reco] 分类失败:', err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,250 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/config - 获取所有配置
|
||||
router.get("/", (req, res) => {
|
||||
const db = getDB();
|
||||
const configs = db.prepare("SELECT key, value FROM config").all();
|
||||
const configMap = {};
|
||||
for (const c of configs) {
|
||||
configMap[c.key] = c.value;
|
||||
}
|
||||
res.json(configMap);
|
||||
});
|
||||
|
||||
// PUT /api/config - 更新配置
|
||||
router.put("/", (req, res) => {
|
||||
const db = getDB();
|
||||
const updates = req.body;
|
||||
|
||||
if (!updates || Object.keys(updates).length === 0) {
|
||||
return res.status(400).json({ error: "请提供要更新的配置" });
|
||||
}
|
||||
|
||||
const upsert = db.prepare(
|
||||
"INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?",
|
||||
);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const [key, value] of Object.entries(updates)) {
|
||||
upsert.run(key, String(value), String(value));
|
||||
}
|
||||
})();
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm - 测试LLM连接(详细调试版)
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
const { getOpenAIClient } = require("../services/llm");
|
||||
|
||||
console.log("[Reco] ========== LLM 连接测试开始 ==========");
|
||||
|
||||
// 1. 检查数据库配置
|
||||
const db = getDB();
|
||||
const apiKeyRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
|
||||
.get();
|
||||
const baseUrlRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
|
||||
.get();
|
||||
const modelRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
|
||||
.get();
|
||||
|
||||
console.log("[Reco] [调试] 数据库配置检查:");
|
||||
console.log(" API Key 存在:", !!apiKeyRow?.value);
|
||||
console.log(" API Key 长度:", apiKeyRow?.value?.length || 0);
|
||||
console.log(
|
||||
" Base URL:",
|
||||
baseUrlRow?.value || "(使用默认 https://api.openai.com/v1)",
|
||||
);
|
||||
console.log(" Model:", modelRow?.value || "(使用默认 gpt-4o-mini)");
|
||||
|
||||
// 2. 尝试创建客户端
|
||||
let client;
|
||||
try {
|
||||
client = getOpenAIClient();
|
||||
} catch (clientErr) {
|
||||
console.error("[Reco] [调试] 创建LLM客户端异常:", clientErr.message);
|
||||
return res.status(500).json({
|
||||
error: `创建LLM客户端失败: ${clientErr.message}`,
|
||||
debug: { errorType: "client_init_error", errorDetail: clientErr.message },
|
||||
});
|
||||
}
|
||||
|
||||
if (!client) {
|
||||
console.log("[Reco] [调试] LLM客户端为空 - 请检查API Key配置");
|
||||
return res.status(400).json({
|
||||
error: "请先在系统设置中配置 LLM API Key",
|
||||
debug: {
|
||||
hasApiKey: !!apiKeyRow?.value,
|
||||
hasBaseUrl: !!baseUrlRow?.value,
|
||||
hasModel: !!modelRow?.value,
|
||||
hint: "前往 系统设置 → 大模型配置 填入API Key",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[Reco] [调试] LLM客户端创建成功");
|
||||
console.log(" Model:", client._model);
|
||||
console.log(" BaseURL:", client.baseURL || "(未暴露)");
|
||||
|
||||
// 3. 发送测试请求
|
||||
const startTime = Date.now();
|
||||
try {
|
||||
console.log("[Reco] [调试] 正在发送测试请求 (timeout: 15s)...");
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [{ role: "user", content: '请回复"连接成功"两个字' }],
|
||||
max_tokens: 10,
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const reply = response.choices?.[0]?.message?.content || "(空)";
|
||||
|
||||
console.log(`[Reco] [调试] ✅ LLM测试成功!`);
|
||||
console.log(` 耗时: ${elapsed}ms`);
|
||||
console.log(` 回复: "${reply}"`);
|
||||
console.log(
|
||||
` Token用量:`,
|
||||
response.usage ? JSON.stringify(response.usage) : "未返回",
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
reply,
|
||||
model: client._model,
|
||||
elapsed_ms: elapsed,
|
||||
usage: response.usage || null,
|
||||
});
|
||||
} catch (err) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
|
||||
console.error(`[Reco] [调试] ❌ LLM测试失败! 耗时: ${elapsed}ms`);
|
||||
console.error(" 错误类型:", err.constructor?.name || typeof err);
|
||||
console.error(" 错误消息:", err.message);
|
||||
console.error(" 错误代码:", err.code || "(无)");
|
||||
console.error(" HTTP状态码:", err.status || err.statusCode || "(无)");
|
||||
|
||||
// OpenAI SDK v4 的错误详情
|
||||
if (err.error) {
|
||||
console.error(" API错误详情:", JSON.stringify(err.error));
|
||||
}
|
||||
if (err.response) {
|
||||
console.error(" 响应状态:", err.response.status);
|
||||
console.error(
|
||||
" 响应头:",
|
||||
JSON.stringify(err.response.headers || {}).substring(0, 300),
|
||||
);
|
||||
try {
|
||||
console.error(
|
||||
" 响应体:",
|
||||
JSON.stringify(
|
||||
err.response.data || err.response.body || {},
|
||||
).substring(0, 800),
|
||||
);
|
||||
} catch (e) {}
|
||||
}
|
||||
if (err.stack) {
|
||||
console.error(" 堆栈(首500):", err.stack.substring(0, 500));
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: `LLM 连接失败: ${err.message}`,
|
||||
debug: {
|
||||
errorType: err.constructor?.name || typeof err,
|
||||
errorCode: err.code || null,
|
||||
httpStatus: err.status || err.statusCode || null,
|
||||
elapsed_ms: elapsed,
|
||||
apiBaseUrl: baseUrlRow?.value || "https://api.openai.com/v1",
|
||||
model: client._model,
|
||||
hint: getHint(err),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[Reco] ========== LLM 连接测试结束 ==========");
|
||||
});
|
||||
|
||||
function getHint(err) {
|
||||
const msg = (err.message || "").toLowerCase();
|
||||
if (
|
||||
msg.includes("401") ||
|
||||
msg.includes("unauthorized") ||
|
||||
msg.includes("invalid api key")
|
||||
) {
|
||||
return "API Key 无效或未授权,请检查 Key 是否正确";
|
||||
}
|
||||
if (msg.includes("404") || msg.includes("not found")) {
|
||||
return "模型名称或API端点不存在,请检查 Base URL 和模型名";
|
||||
}
|
||||
if (
|
||||
msg.includes("timeout") ||
|
||||
msg.includes("etimedout") ||
|
||||
msg.includes("enotfound")
|
||||
) {
|
||||
return "网络连接超时或DNS解析失败,请检查 Base URL 和网络";
|
||||
}
|
||||
if (msg.includes("429") || msg.includes("rate")) {
|
||||
return "请求频率过高或被限流,请稍后重试";
|
||||
}
|
||||
if (
|
||||
msg.includes("connect") ||
|
||||
msg.includes("refused") ||
|
||||
msg.includes("econnrefused")
|
||||
) {
|
||||
return "无法连接到API服务器,请确认 Base URL 正确且服务正在运行";
|
||||
}
|
||||
return "请检查 API Key、Base URL 和 Model 配置是否正确";
|
||||
}
|
||||
|
||||
// GET /api/config/categories - 获取分类列表
|
||||
router.get("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
const categories = db.prepare("SELECT * FROM categories ORDER BY id").all();
|
||||
res.json(categories);
|
||||
});
|
||||
|
||||
// PUT /api/config/categories/:id - 更新分类
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
|
||||
db.prepare(
|
||||
"UPDATE categories SET name = COALESCE(?, name), keywords = COALESCE(?, keywords) WHERE id = ?",
|
||||
).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/categories - 新增分类
|
||||
router.post("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: "分类名称不能为空" });
|
||||
}
|
||||
|
||||
const result = db
|
||||
.prepare(
|
||||
"INSERT INTO categories (name, keywords, parent_id) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null);
|
||||
|
||||
res.json({ success: true, id: result.lastInsertRowid });
|
||||
});
|
||||
|
||||
// DELETE /api/config/categories/:id - 删除分类
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
db.prepare("DELETE FROM categories WHERE id = ?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,110 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/stats/overview - 总览统计
|
||||
router.get('/overview', (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let dateCondition = '';
|
||||
const params = [];
|
||||
|
||||
if (year) {
|
||||
dateCondition = 'WHERE strftime(\'%Y\', transaction_date) = ?';
|
||||
params.push(String(year));
|
||||
if (month) {
|
||||
dateCondition += ' AND strftime(\'%m\', transaction_date) = ?';
|
||||
params.push(String(month).padStart(2, '0'));
|
||||
}
|
||||
}
|
||||
|
||||
const stats = db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as total_count,
|
||||
COALESCE(SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END), 0) as total_income,
|
||||
COALESCE(SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END), 0) as total_expense,
|
||||
COUNT(CASE WHEN reviewed = 0 AND ABS(amount) >= 100 THEN 1 END) as pending_review,
|
||||
COUNT(CASE WHEN reviewed = 1 THEN 1 END) as reviewed_count,
|
||||
COUNT(CASE WHEN matched_transaction_id IS NOT NULL THEN 1 END) as matched_count
|
||||
FROM transactions
|
||||
${dateCondition}
|
||||
`).get(...params);
|
||||
|
||||
// 按分类统计支出
|
||||
const categoryStats = db.prepare(`
|
||||
SELECT
|
||||
category,
|
||||
COUNT(*) as count,
|
||||
SUM(ABS(amount)) as total_amount,
|
||||
AVG(ABS(amount)) as avg_amount
|
||||
FROM transactions
|
||||
${dateCondition}${dateCondition ? ' AND' : 'WHERE'} direction = 'expense' AND category IS NOT NULL
|
||||
GROUP BY category
|
||||
ORDER BY total_amount DESC
|
||||
`).all(...params);
|
||||
|
||||
// 按来源统计
|
||||
const sourceStats = db.prepare(`
|
||||
SELECT
|
||||
t.source_type,
|
||||
s.source_name,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN t.direction = 'income' THEN t.amount ELSE 0 END) as total_income,
|
||||
SUM(CASE WHEN t.direction = 'expense' THEN ABS(t.amount) ELSE 0 END) as total_expense
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
${dateCondition}
|
||||
GROUP BY t.source_type
|
||||
ORDER BY total_expense DESC
|
||||
`).all(...params);
|
||||
|
||||
res.json({
|
||||
overview: stats,
|
||||
categoryStats,
|
||||
sourceStats
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/stats/monthly - 月度趋势
|
||||
router.get('/monthly', (req, res) => {
|
||||
const db = getDB();
|
||||
const { months = 12 } = req.query;
|
||||
|
||||
const monthlyData = db.prepare(`
|
||||
SELECT
|
||||
strftime('%Y-%m', transaction_date) as month,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
|
||||
FROM transactions
|
||||
WHERE transaction_date >= DATE('now', '-${parseInt(months)} months')
|
||||
GROUP BY strftime('%Y-%m', transaction_date)
|
||||
ORDER BY month ASC
|
||||
`).all();
|
||||
|
||||
res.json(monthlyData);
|
||||
});
|
||||
|
||||
// GET /api/stats/daily - 每日统计
|
||||
router.get('/daily', (req, res) => {
|
||||
const db = getDB();
|
||||
const { days = 30 } = req.query;
|
||||
|
||||
const dailyData = db.prepare(`
|
||||
SELECT
|
||||
transaction_date as date,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
|
||||
FROM transactions
|
||||
WHERE transaction_date >= DATE('now', '-${parseInt(days)} days')
|
||||
GROUP BY transaction_date
|
||||
ORDER BY date ASC
|
||||
`).all();
|
||||
|
||||
res.json(dailyData);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,284 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { runAutoReconciliation } = require('../services/matcher');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/transactions - 获取交易列表(支持筛选和分页)
|
||||
router.get('/', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 50,
|
||||
start_date,
|
||||
end_date,
|
||||
source_type,
|
||||
direction,
|
||||
category,
|
||||
reviewed,
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
sort_by = 'transaction_date',
|
||||
sort_order = 'DESC'
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push('t.transaction_date >= ?');
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push('t.transaction_date <= ?');
|
||||
params.push(end_date);
|
||||
}
|
||||
if (source_type) {
|
||||
conditions.push('t.source_type = ?');
|
||||
params.push(source_type);
|
||||
}
|
||||
if (direction) {
|
||||
conditions.push('t.direction = ?');
|
||||
params.push(direction);
|
||||
}
|
||||
if (category) {
|
||||
conditions.push('t.category = ?');
|
||||
params.push(category);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
conditions.push('t.reviewed = ?');
|
||||
params.push(parseInt(reviewed));
|
||||
}
|
||||
if (min_amount) {
|
||||
conditions.push('ABS(t.amount) >= ?');
|
||||
params.push(parseFloat(min_amount));
|
||||
}
|
||||
if (max_amount) {
|
||||
conditions.push('ABS(t.amount) <= ?');
|
||||
params.push(parseFloat(max_amount));
|
||||
}
|
||||
if (keyword) {
|
||||
conditions.push('(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ? OR t.ai_description LIKE ?)');
|
||||
const kw = `%${keyword}%`;
|
||||
params.push(kw, kw, kw, kw);
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = ['transaction_date', 'amount', 'created_at', 'counterparty', 'category', 'reviewed'];
|
||||
const safeSortBy = allowedSortFields.includes(sort_by) ? sort_by : 'transaction_date';
|
||||
const safeSortOrder = sort_order === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
const countResult = db.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions t ${whereClause}`
|
||||
).get(...params);
|
||||
|
||||
const transactions = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
${whereClause}
|
||||
ORDER BY t.${safeSortBy} ${safeSortOrder}
|
||||
LIMIT ? OFFSET ?
|
||||
`).all(...params, parseInt(limit), offset);
|
||||
|
||||
res.json({
|
||||
transactions,
|
||||
total: countResult.total,
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit))
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get('/:id', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`).get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`).get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.transaction_code = ? AND t.id != ?
|
||||
`).all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({ transaction: tx, matchedTransaction: matchedTx, relatedTransactions: relatedTxs });
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put('/:id', (req, res) => {
|
||||
const db = getDB();
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
|
||||
const tx = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push('category = ?');
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push('ai_description = ?');
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push('reviewed = ?');
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push('reviewed_at = CURRENT_TIMESTAMP');
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push('review_notes = ?');
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push('tags = ?');
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: '没有提供要更新的字段' });
|
||||
}
|
||||
|
||||
updates.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
res.json({ success: true, transaction: updated });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 运行自动对账
|
||||
router.post('/reconcile', (req, res) => {
|
||||
const result = runAutoReconciliation();
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post('/classify', async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: '请提供要分类的交易ID列表' });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all - 对所有未分类的交易进行分类
|
||||
router.post('/classify-all', async (req, res) => {
|
||||
const db = getDB();
|
||||
const unclassified = db.prepare(
|
||||
"SELECT id FROM transactions WHERE ai_category IS NULL OR ai_category = ''"
|
||||
).all();
|
||||
|
||||
if (unclassified.length === 0) {
|
||||
return res.json({ success: true, classified: 0, message: '所有交易已分类' });
|
||||
}
|
||||
|
||||
const ids = unclassified.map(r => r.id);
|
||||
try {
|
||||
// 分批处理,每批50条
|
||||
const batchSize = 50;
|
||||
let totalClassified = 0;
|
||||
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const batch = ids.slice(i, i + batchSize);
|
||||
const result = await classifyTransactions(batch);
|
||||
totalClassified += result.classified;
|
||||
}
|
||||
|
||||
res.json({ success: true, classified: totalClassified, total: ids.length });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
router.get('/stats/summary', (req, res) => {
|
||||
// This is handled by the stats route, but let's keep a simple version here too
|
||||
const db = getDB();
|
||||
|
||||
const { start_date, end_date } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
|
||||
if (start_date) { conditions.push('transaction_date >= ?'); params.push(start_date); }
|
||||
if (end_date) { conditions.push('transaction_date <= ?'); params.push(end_date); }
|
||||
|
||||
const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
|
||||
|
||||
const incomeResult = db.prepare(
|
||||
`SELECT COALESCE(SUM(amount), 0) as total FROM transactions ${where} AND direction = 'income'`
|
||||
).get(...params);
|
||||
|
||||
const expenseResult = db.prepare(
|
||||
`SELECT COALESCE(SUM(ABS(amount)), 0) as total FROM transactions ${where} AND direction = 'expense'`
|
||||
).get(...params);
|
||||
|
||||
const countResult = db.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where}`
|
||||
).get(...params);
|
||||
|
||||
const unreviewedCount = db.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`
|
||||
).get(...params);
|
||||
|
||||
const categoryBreakdown = db.prepare(`
|
||||
SELECT category, COUNT(*) as count, SUM(ABS(amount)) as total_amount
|
||||
FROM transactions ${where} AND direction = 'expense'
|
||||
GROUP BY category
|
||||
ORDER BY total_amount DESC
|
||||
`).all(...params);
|
||||
|
||||
res.json({
|
||||
totalIncome: incomeResult.total,
|
||||
totalExpense: expenseResult.total,
|
||||
netAmount: incomeResult.total - expenseResult.total,
|
||||
totalCount: countResult.total,
|
||||
unreviewedCount: unreviewedCount.total,
|
||||
categoryBreakdown
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,229 @@
|
||||
const express = require("express");
|
||||
const multer = require("multer");
|
||||
const { parse } = require("csv-parse/sync");
|
||||
const crypto = require("crypto");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const { getDB } = require("../db");
|
||||
const { parseAlipayCSV, parseAlipayFromXLSX } = require("../parsers/alipay");
|
||||
const { parseWechatCSV, parseWechatXLSX } = require("../parsers/wechat");
|
||||
const { parseBankCSV, parseBankFromXLSX } = require("../parsers/bank");
|
||||
const {
|
||||
parseCreditCardCSV,
|
||||
parseCreditFromXLSX,
|
||||
} = require("../parsers/credit");
|
||||
const { parseSPDBXLS } = require("../parsers/spdb");
|
||||
const { generateTransactionCode } = require("../utils/transactionCode");
|
||||
const { classifyTransactions } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
|
||||
|
||||
const ALLOWED_EXTS = [".csv", ".txt", ".xlsx", ".xls"];
|
||||
|
||||
const upload = multer({
|
||||
storage: multer.diskStorage({
|
||||
destination: uploadDir,
|
||||
filename: (req, file, cb) =>
|
||||
cb(
|
||||
null,
|
||||
Date.now() +
|
||||
"-" +
|
||||
Math.round(Math.random() * 1e9) +
|
||||
path.extname(file.originalname),
|
||||
),
|
||||
}),
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (ALLOWED_EXTS.includes(path.extname(file.originalname).toLowerCase()))
|
||||
cb(null, true);
|
||||
else cb(new Error("仅支持 CSV / TXT / XLSX / XLS 文件格式"));
|
||||
},
|
||||
limits: { fileSize: 20 * 1024 * 1024 },
|
||||
});
|
||||
|
||||
router.post("/", upload.single("file"), async (req, res) => {
|
||||
try {
|
||||
const { source_type, source_name } = req.body;
|
||||
if (
|
||||
!source_type ||
|
||||
![
|
||||
"alipay",
|
||||
"wechat",
|
||||
"bank_debit",
|
||||
"bank_credit",
|
||||
"credit_card",
|
||||
].includes(source_type)
|
||||
) {
|
||||
return res.status(400).json({ error: "无效的账单类型" });
|
||||
}
|
||||
if (!req.file) return res.status(400).json({ error: "请选择要上传的文件" });
|
||||
|
||||
const fileExt = path.extname(req.file.originalname).toLowerCase();
|
||||
const isExcel = [".xlsx", ".xls"].includes(fileExt);
|
||||
console.log(
|
||||
`[Reco] 上传: ${req.file.originalname} type=${source_type} ext=${fileExt}`,
|
||||
);
|
||||
|
||||
const fileBuffer = fs.readFileSync(req.file.path);
|
||||
const fileHash = crypto.createHash("md5").update(fileBuffer).digest("hex");
|
||||
const db = getDB();
|
||||
|
||||
const existing = db
|
||||
.prepare("SELECT id FROM sources WHERE file_hash = ?")
|
||||
.get(fileHash);
|
||||
if (existing) {
|
||||
fs.unlinkSync(req.file.path);
|
||||
return res
|
||||
.status(409)
|
||||
.json({ error: "该文件已导入过", source_id: existing.id });
|
||||
}
|
||||
|
||||
let parsedTransactions;
|
||||
|
||||
if (isExcel) {
|
||||
console.log(`[Reco] XLSX解析: ${source_type}`);
|
||||
switch (source_type) {
|
||||
case "alipay":
|
||||
parsedTransactions = parseAlipayFromXLSX(req.file.path);
|
||||
break;
|
||||
case "wechat":
|
||||
parsedTransactions = parseWechatXLSX(req.file.path);
|
||||
break;
|
||||
case "bank_debit":
|
||||
case "bank_credit":
|
||||
parsedTransactions = parseSPDBXLS(req.file.path);
|
||||
break;
|
||||
case "credit_card":
|
||||
parsedTransactions = parseCreditFromXLSX(req.file.path);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
const content = fileBuffer.toString("utf-8");
|
||||
let records;
|
||||
try {
|
||||
records = parse(content, {
|
||||
columns: true,
|
||||
skip_empty_lines: true,
|
||||
bom: true,
|
||||
relax_column_count: true,
|
||||
trim: true,
|
||||
});
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: `CSV解析失败: ${e.message}` });
|
||||
}
|
||||
if (!records?.length)
|
||||
return res.status(400).json({ error: "文件中无有效记录" });
|
||||
switch (source_type) {
|
||||
case "alipay":
|
||||
parsedTransactions = parseAlipayCSV(records);
|
||||
break;
|
||||
case "wechat":
|
||||
parsedTransactions = parseWechatCSV(records);
|
||||
break;
|
||||
case "bank_debit":
|
||||
case "bank_credit":
|
||||
parsedTransactions = parseBankCSV(records);
|
||||
break;
|
||||
case "credit_card":
|
||||
parsedTransactions = parseCreditCardCSV(records);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedTransactions?.length)
|
||||
return res.status(400).json({ error: "未能解析出交易记录" });
|
||||
console.log(`[Reco] 解析完成: ${parsedTransactions.length}条`);
|
||||
|
||||
const sourceName =
|
||||
source_name || `${source_type}_${new Date().toISOString().slice(0, 10)}`;
|
||||
const src = db
|
||||
.prepare(
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(
|
||||
source_type,
|
||||
sourceName,
|
||||
req.file.originalname,
|
||||
fileHash,
|
||||
parsedTransactions.length,
|
||||
);
|
||||
|
||||
const insertTx = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
transaction_code, source_id, source_type, transaction_date, transaction_time,
|
||||
counterparty, description, notes, amount, direction, status, method, balance, tags
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
const ids = [];
|
||||
let skip = 0;
|
||||
for (const tx of parsedTransactions) {
|
||||
const code = generateTransactionCode(
|
||||
tx.transaction_date,
|
||||
tx.amount,
|
||||
tx.counterparty,
|
||||
tx.description,
|
||||
);
|
||||
const r = insertTx.run(
|
||||
code,
|
||||
src.lastInsertRowid,
|
||||
source_type,
|
||||
tx.transaction_date,
|
||||
tx.transaction_time,
|
||||
tx.counterparty,
|
||||
tx.description,
|
||||
tx.notes || "",
|
||||
tx.amount,
|
||||
tx.direction,
|
||||
tx.status || "",
|
||||
tx.method || "",
|
||||
tx.balance || null,
|
||||
null,
|
||||
);
|
||||
if (r.changes > 0) ids.push(r.lastInsertRowid);
|
||||
else skip++;
|
||||
}
|
||||
console.log(`[Reco] 写入: ${ids.length}条, 跳过: ${skip}条`);
|
||||
|
||||
let classifyResult = { classified: 0, source: "none" };
|
||||
if (ids.length > 0) {
|
||||
try {
|
||||
classifyResult = await classifyTransactions(ids);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
source_id: src.lastInsertRowid,
|
||||
source_name: sourceName,
|
||||
source_type,
|
||||
file_name: req.file.originalname,
|
||||
record_count: parsedTransactions.length,
|
||||
inserted: ids.length,
|
||||
skipped: skip,
|
||||
classified: classifyResult.classified,
|
||||
classify_source: classifyResult.source,
|
||||
sample: parsedTransactions.slice(0, 5),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 上传失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/sources", (req, res) => {
|
||||
const db = getDB();
|
||||
res.json(
|
||||
db
|
||||
.prepare(
|
||||
`SELECT s.*, COUNT(t.id) as tx_count FROM sources s LEFT JOIN transactions t ON t.source_id = s.id GROUP BY s.id ORDER BY s.imported_at DESC`,
|
||||
)
|
||||
.all(),
|
||||
);
|
||||
});
|
||||
|
||||
router.delete("/sources/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,224 @@
|
||||
const { getDB } = require("../db");
|
||||
|
||||
/**
|
||||
* LLM 服务:调用大模型对交易进行分类和描述
|
||||
*
|
||||
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
|
||||
* 如果未配置 API Key,使用本地规则进行降级分类
|
||||
*/
|
||||
let 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();
|
||||
|
||||
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";
|
||||
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分类 Prompt
|
||||
*/
|
||||
function buildClassificationPrompt(transactions) {
|
||||
const db = getDB();
|
||||
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");
|
||||
|
||||
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 `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
## 可用分类:
|
||||
${categoryList}
|
||||
|
||||
## 交易记录:
|
||||
${txList}
|
||||
|
||||
## 要求:
|
||||
请为每笔交易返回一个JSON数组,每项包含:
|
||||
- index: 交易序号(整数)
|
||||
- category: 最合适的分类名称(必须从上面的可用分类中选择)
|
||||
- description: 用简洁的中文描述这笔交易(10-30字),例如"在星巴克购买咖啡"、"缴纳本月房租"、"收到工资"
|
||||
- confidence: 你对分类的置信度(0-1之间的浮点数)
|
||||
|
||||
仅返回JSON数组,不要包含其他内容。`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分类交易
|
||||
*/
|
||||
async function classifyTransactions(transactionIds) {
|
||||
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);
|
||||
|
||||
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 },
|
||||
],
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return { classified: results.length, source: "llm" };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:使用本地关键词规则分类
|
||||
return classifyByRules(transactions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地关键词规则分类(无需LLM)
|
||||
*/
|
||||
function classifyByRules(transactions) {
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 生成简单描述
|
||||
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,
|
||||
);
|
||||
|
||||
classified++;
|
||||
if (largeAmount) needsReview++;
|
||||
}
|
||||
|
||||
return { classified, needsReview, source: "rules" };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient };
|
||||
@@ -0,0 +1,198 @@
|
||||
const { getDB } = require('../db');
|
||||
|
||||
/**
|
||||
* 交易匹配服务
|
||||
*
|
||||
* 自动匹配不同来源的相同交易,例如:
|
||||
* - 支付宝消费 → 银行卡扣款
|
||||
* - 微信支付 → 信用卡扣款
|
||||
* - 跨行转账 ↔ 对方账户入账
|
||||
*
|
||||
* 匹配规则(按优先级):
|
||||
* 1. 相同日期 + 相同金额(最可靠)
|
||||
* 2. 日期相近(±1天) + 相同金额 + 描述相似
|
||||
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
|
||||
*/
|
||||
function findMatches(newTransaction) {
|
||||
const db = getDB();
|
||||
|
||||
const absAmount = Math.abs(newTransaction.amount);
|
||||
|
||||
// 只匹配金额 > 0.01 的交易
|
||||
if (absAmount < 0.01) return [];
|
||||
|
||||
const candidates = db.prepare(`
|
||||
SELECT id, transaction_code, transaction_date, amount, counterparty,
|
||||
description, source_type, direction, category
|
||||
FROM transactions
|
||||
WHERE id != ?
|
||||
AND source_id != ?
|
||||
AND reviewed = 0
|
||||
AND ABS(ABS(amount) - ?) <= 1.0
|
||||
AND transaction_date BETWEEN DATE(?, '-2 days') AND DATE(?, '+2 days')
|
||||
ORDER BY ABS(julianday(transaction_date) - julianday(?)) ASC
|
||||
LIMIT 20
|
||||
`).all(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
const matches = [];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
let score = 0;
|
||||
const reasons = [];
|
||||
|
||||
// 金额得分
|
||||
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
|
||||
if (amountDiff < 0.01) {
|
||||
score += 40;
|
||||
reasons.push('金额完全一致');
|
||||
} else if (amountDiff < 0.1) {
|
||||
score += 35;
|
||||
reasons.push('金额基本一致');
|
||||
} else if (amountDiff < 1.0) {
|
||||
score += 20;
|
||||
reasons.push('金额接近');
|
||||
}
|
||||
|
||||
// 日期得分
|
||||
const dateDiff = Math.abs(
|
||||
new Date(candidate.transaction_date) - new Date(newTransaction.transaction_date)
|
||||
) / (1000 * 60 * 60 * 24);
|
||||
|
||||
if (dateDiff < 0.01) {
|
||||
score += 30;
|
||||
reasons.push('日期相同');
|
||||
} else if (dateDiff <= 1) {
|
||||
score += 20;
|
||||
reasons.push('日期差1天');
|
||||
} else if (dateDiff <= 2) {
|
||||
score += 10;
|
||||
reasons.push('日期差2天');
|
||||
}
|
||||
|
||||
// 对方名称相似度
|
||||
const nameSim = stringSimilarity(
|
||||
(candidate.counterparty || '').toLowerCase(),
|
||||
(newTransaction.counterparty || '').toLowerCase()
|
||||
);
|
||||
if (nameSim > 0.8) {
|
||||
score += 20;
|
||||
reasons.push('对方名称高度相似');
|
||||
} else if (nameSim > 0.5) {
|
||||
score += 10;
|
||||
reasons.push('对方名称部分相似');
|
||||
}
|
||||
|
||||
// 描述相似度
|
||||
const descSim = stringSimilarity(
|
||||
(candidate.description || '').toLowerCase(),
|
||||
(newTransaction.description || '').toLowerCase()
|
||||
);
|
||||
if (descSim > 0.7) {
|
||||
score += 10;
|
||||
reasons.push('描述相似');
|
||||
}
|
||||
|
||||
// 方向互补(一个支出一个收入,说明是转账匹配)
|
||||
if (candidate.direction !== newTransaction.direction) {
|
||||
score += 5;
|
||||
reasons.push('收支方向互补');
|
||||
}
|
||||
|
||||
if (score >= 40) { // 最低匹配阈值
|
||||
matches.push({
|
||||
transaction_id: candidate.id,
|
||||
match_score: Math.min(score, 100) / 100,
|
||||
reasons: reasons.join(';'),
|
||||
candidate
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 按得分排序
|
||||
matches.sort((a, b) => b.match_score - a.match_score);
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行全局自动对账
|
||||
* 对所有未匹配的交易尝试匹配
|
||||
*/
|
||||
function runAutoReconciliation() {
|
||||
const db = getDB();
|
||||
|
||||
const unmatched = db.prepare(`
|
||||
SELECT * FROM transactions
|
||||
WHERE matched_transaction_id IS NULL
|
||||
ORDER BY transaction_date DESC
|
||||
`).all();
|
||||
|
||||
let matchCount = 0;
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET matched_transaction_id = ?, match_score = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
const processed = new Set();
|
||||
|
||||
for (const tx of unmatched) {
|
||||
if (processed.has(tx.id)) continue;
|
||||
|
||||
const matches = findMatches(tx);
|
||||
if (matches.length > 0 && matches[0].match_score >= 0.7) {
|
||||
const bestMatch = matches[0];
|
||||
|
||||
// 双向匹配
|
||||
db.transaction(() => {
|
||||
updateStmt.run(bestMatch.transaction_id, bestMatch.match_score, tx.id);
|
||||
updateStmt.run(tx.id, bestMatch.match_score, bestMatch.transaction_id);
|
||||
})();
|
||||
|
||||
processed.add(tx.id);
|
||||
processed.add(bestMatch.transaction_id);
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return { matched: matchCount, total: unmatched.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单的字符串相似度算法(基于重叠字符)
|
||||
*/
|
||||
function stringSimilarity(a, b) {
|
||||
if (!a || !b) return 0;
|
||||
if (a === b) return 1;
|
||||
|
||||
const shorter = a.length < b.length ? a : b;
|
||||
const longer = a.length < b.length ? b : a;
|
||||
|
||||
if (shorter.length === 0) return 0;
|
||||
|
||||
// 使用滑动窗口匹配
|
||||
let matches = 0;
|
||||
for (let i = 0; i < shorter.length - 1; i++) {
|
||||
const bigram = shorter.substring(i, i + 2);
|
||||
if (longer.includes(bigram)) {
|
||||
matches++;
|
||||
}
|
||||
}
|
||||
|
||||
const possibleMatches = shorter.length - 1;
|
||||
if (possibleMatches === 0) return 0;
|
||||
|
||||
return matches / possibleMatches;
|
||||
}
|
||||
|
||||
module.exports = { findMatches, runAutoReconciliation };
|
||||
Reference in New Issue
Block a user