version 0.3

This commit is contained in:
2026-05-05 16:36:57 +08:00
parent 9a963623a8
commit fa5637b5ca
25 changed files with 3090 additions and 2975 deletions
+104
View File
@@ -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
View File
@@ -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 };
-135
View File
@@ -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 };
-100
View File
@@ -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 };
+3 -1
View File
@@ -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");