init project by zed@deepseek-V4PRO
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "reco",
|
||||
"version": "1.0.0",
|
||||
"description": "银行流水对账分析系统 - Bank Transaction Reconciliation & Analysis",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"install:all": "cd client && npm install",
|
||||
"dev:server": "node server/index.js",
|
||||
"dev:client": "cd client && npx react-scripts start",
|
||||
"dev": "npx concurrently \"npm run dev:server\" \"npm run dev:client\"",
|
||||
"build:client": "cd client && npx react-scripts build",
|
||||
"start": "node server/index.js",
|
||||
"setup": "npm install && npm run install:all"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.7.0",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.21.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"csv-parse": "^5.6.0",
|
||||
"uuid": "^10.0.0",
|
||||
"openai": "^4.73.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"crypto-js": "^4.2.0"
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
|
||||
const DB_PATH = path.join(__dirname, '..', 'data', 'reco.db');
|
||||
|
||||
// Ensure data directory exists
|
||||
const fs = require('fs');
|
||||
const dataDir = path.join(__dirname, '..', 'data');
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
let db;
|
||||
|
||||
function getDB() {
|
||||
if (!db) {
|
||||
db = new Database(DB_PATH);
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
function initDB() {
|
||||
const database = getDB();
|
||||
|
||||
database.exec(`
|
||||
-- 交易来源表:记录每一次导入的账单文件
|
||||
CREATE TABLE IF NOT EXISTS sources (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_type TEXT NOT NULL, -- 'alipay', 'wechat', 'bank_debit', 'bank_credit', 'credit_card'
|
||||
source_name TEXT NOT NULL, -- 用户自定义名称,如 "工商银行工资卡"
|
||||
file_name TEXT NOT NULL,
|
||||
file_hash TEXT,
|
||||
imported_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
record_count INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
-- 交易记录表:每一笔原始交易
|
||||
CREATE TABLE IF NOT EXISTS transactions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
transaction_code TEXT UNIQUE NOT NULL, -- 统一交易编码
|
||||
source_id INTEGER NOT NULL,
|
||||
source_type TEXT NOT NULL,
|
||||
|
||||
-- 时间相关
|
||||
transaction_date DATE NOT NULL,
|
||||
transaction_time DATETIME,
|
||||
|
||||
-- 交易方信息
|
||||
counterparty TEXT, -- 交易对方
|
||||
description TEXT, -- 原始描述/商品说明
|
||||
notes TEXT, -- 备注
|
||||
|
||||
-- 金额
|
||||
amount REAL NOT NULL, -- 交易金额(正=收入,负=支出)
|
||||
currency TEXT DEFAULT 'CNY',
|
||||
balance REAL, -- 余额(如有)
|
||||
|
||||
-- 交易属性
|
||||
direction TEXT, -- 'income' | 'expense' | 'transfer'
|
||||
status TEXT, -- 交易状态
|
||||
method TEXT, -- 支付方式
|
||||
category TEXT, -- 分类(大模型生成或手动指定)
|
||||
ai_category TEXT, -- 大模型原始分类
|
||||
ai_description TEXT, -- 大模型生成的描述
|
||||
ai_confidence REAL, -- 大模型置信度
|
||||
|
||||
-- 对账相关
|
||||
matched_transaction_id INTEGER, -- 匹配到的另一笔交易ID(银行扣款↔支付宝支出)
|
||||
match_score REAL, -- 匹配置信度 0-1
|
||||
reviewed INTEGER DEFAULT 0, -- 是否已人工确认 0=未确认 1=已确认
|
||||
review_notes TEXT, -- 人工备注
|
||||
reviewed_at DATETIME,
|
||||
|
||||
-- 标签
|
||||
tags TEXT, -- JSON数组字符串
|
||||
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (matched_transaction_id) REFERENCES transactions(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
-- 分类配置表:保存大模型分类类别
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT, -- JSON数组:关联关键词
|
||||
parent_id INTEGER,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 配置表
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
|
||||
-- 索引
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_date ON transactions(transaction_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_code ON transactions(transaction_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_amount ON transactions(amount);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_source ON transactions(source_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_reviewed ON transactions(reviewed);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_matched ON transactions(matched_transaction_id);
|
||||
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);
|
||||
|
||||
console.log('[Reco] 数据库初始化完成');
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB };
|
||||
@@ -0,0 +1,40 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const { initDB } = require('./db');
|
||||
|
||||
const uploadRoutes = require('./routes/upload');
|
||||
const transactionRoutes = require('./routes/transactions');
|
||||
const classifyRoutes = require('./routes/classify');
|
||||
const statsRoutes = require('./routes/stats');
|
||||
const configRoutes = require('./routes/config');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
|
||||
// API routes
|
||||
app.use('/api/upload', uploadRoutes);
|
||||
app.use('/api/transactions', transactionRoutes);
|
||||
app.use('/api/classify', classifyRoutes);
|
||||
app.use('/api/stats', statsRoutes);
|
||||
app.use('/api/config', configRoutes);
|
||||
|
||||
// Serve React static files in production
|
||||
const clientBuildPath = path.join(__dirname, '..', 'client', 'build');
|
||||
app.use(express.static(clientBuildPath));
|
||||
app.get('*', (req, res) => {
|
||||
if (!req.path.startsWith('/api')) {
|
||||
res.sendFile(path.join(clientBuildPath, 'index.html'));
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize database and start server
|
||||
initDB();
|
||||
app.listen(PORT, () => {
|
||||
console.log(`[Reco] 服务器已启动: http://localhost:${PORT}`);
|
||||
console.log(`[Reco] API 地址: http://localhost:${PORT}/api`);
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
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'] || '';
|
||||
|
||||
if (!dateStr && !amountStr) continue;
|
||||
|
||||
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';
|
||||
}
|
||||
|
||||
// 统一金额符号:支出为负
|
||||
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');
|
||||
}
|
||||
|
||||
module.exports = { parseAlipayCSV, parseDate };
|
||||
@@ -0,0 +1,76 @@
|
||||
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;
|
||||
}
|
||||
|
||||
module.exports = { parseBankCSV };
|
||||
@@ -0,0 +1,56 @@
|
||||
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;
|
||||
}
|
||||
|
||||
module.exports = { parseCreditCardCSV };
|
||||
@@ -0,0 +1,70 @@
|
||||
const { parseDate } = require('./alipay');
|
||||
|
||||
/**
|
||||
* 微信账单CSV解析器
|
||||
*
|
||||
* 微信导出的CSV格式:
|
||||
* 交易时间,交易类型,交易对方,商品,收/支,金额(元),支付方式,当前状态,交易单号,商户单号,备注
|
||||
*/
|
||||
function parseWechatCSV(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 type = record['交易类型'] || record['类型'] || record['transaction_type'] || '';
|
||||
const counterparty = record['交易对方'] || record['对方'] || record['counterparty'] || '';
|
||||
const description = record['商品'] || record['商品名称'] || record['product'] || record['description'] || '';
|
||||
const directionStr = record['收/支'] || record['收支'] || record['direction'] || '';
|
||||
const amountStr = record['金额(元)'] || record['金额'] || record['amount'] || '0';
|
||||
const method = record['支付方式'] || record['method'] || record['payment'] || '';
|
||||
const status = record['当前状态'] || record['状态'] || record['status'] || '';
|
||||
const orderNo = record['交易单号'] || record['订单号'] || record['order_no'] || '';
|
||||
const notes = record['备注'] || record['memo'] || '';
|
||||
|
||||
if (!dateStr && !amountStr) continue;
|
||||
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ''));
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
let direction = 'expense';
|
||||
if (directionStr.includes('收入') || directionStr.includes('收')) {
|
||||
direction = 'income';
|
||||
} else if (directionStr.includes('支出') || directionStr.includes('支')) {
|
||||
direction = 'expense';
|
||||
} else if (amount > 0) {
|
||||
direction = 'income';
|
||||
} else {
|
||||
amount = -Math.abs(amount);
|
||||
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() || type.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
status: status.trim(),
|
||||
method: method.trim(),
|
||||
order_no: orderNo.trim(),
|
||||
transaction_type: type.trim(),
|
||||
raw_data: JSON.stringify(record)
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseWechatCSV };
|
||||
@@ -0,0 +1,47 @@
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* 生成统一交易编码
|
||||
* 规则:基于日期+金额+交易对方的MD5哈希前12位
|
||||
* 相同日期、相同金额、相同对方的交易会被合并到同一个编码
|
||||
*/
|
||||
function generateTransactionCode(dateStr, amount, counterparty, description) {
|
||||
// 金额保留2位小数
|
||||
const amountFixed = parseFloat(amount).toFixed(2);
|
||||
// 截取日期到天
|
||||
const dateDay = String(dateStr).substring(0, 10);
|
||||
|
||||
const raw = `${dateDay}|${amountFixed}|${(counterparty || '').trim()}|${(description || '').trim()}`;
|
||||
return 'TX' + crypto.createHash('md5').update(raw).digest('hex').substring(0, 12).toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合交易:将相同交易编码的交易合并
|
||||
* 保留最详细的信息
|
||||
*/
|
||||
function mergeTransactions(txs) {
|
||||
if (txs.length === 0) return null;
|
||||
if (txs.length === 1) return txs[0];
|
||||
|
||||
// 按 info 优先级:优先保留有更多字段的交易
|
||||
const merged = { ...txs[0] };
|
||||
const fieldsToPickBest = ['counterparty', 'description', 'notes', 'method', 'status'];
|
||||
|
||||
for (const field of fieldsToPickBest) {
|
||||
for (const tx of txs) {
|
||||
if (tx[field] && !merged[field]) {
|
||||
merged[field] = tx[field];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 合并 source_type(记录多个来源)
|
||||
const sourceTypes = [...new Set(txs.map(t => t.source_type))];
|
||||
merged.source_type = sourceTypes.join(',');
|
||||
merged._merged_from = txs.length;
|
||||
merged._source_ids = txs.map(t => t.source_id);
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
module.exports = { generateTransactionCode, mergeTransactions };
|
||||
Reference in New Issue
Block a user