feat(账单导入): 预览确认导入流程,去除账单名称输入框
- 上传先解析预览,弹框显示记录数+前5条样本,确认后入库 - 取消时删临时文件,不写入数据库 - 去掉账单名称手动输入,用来源类型自动命名 - 修复中文文件名 Latin-1 编码乱码 - 所有 alert/confirm 替换为 Toast 通知和 Modal 确认弹框 - 去除导入时自动分类逻辑
This commit is contained in:
+190
-72
@@ -1,117 +1,235 @@
|
||||
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 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 router = express.Router();
|
||||
const uploadDir = path.join(__dirname, '..', '..', 'data', 'uploads');
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
|
||||
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
|
||||
const tempDir = path.join(__dirname, "..", "..", "data", "temp");
|
||||
[uploadDir, tempDir].forEach((d) => {
|
||||
if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
|
||||
});
|
||||
|
||||
const ALLOWED_EXTS = ['.csv', '.txt', '.xlsx', '.xls'];
|
||||
const VALID_TYPES = ['alipay', 'wechat', 'bank_debit', 'abc'];
|
||||
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) => {
|
||||
function parseFile(filePath, sourceType, originalname) {
|
||||
const fileExt = path.extname(originalname).toLowerCase();
|
||||
const isExcel = [".xlsx", ".xls"].includes(fileExt);
|
||||
if (isExcel) {
|
||||
switch (sourceType) {
|
||||
case "alipay":
|
||||
return parseAlipayFromXLSX(filePath);
|
||||
case "wechat":
|
||||
return parseWechatXLSX(filePath);
|
||||
case "bank_debit":
|
||||
return parseSPDBXLS(filePath);
|
||||
case "abc":
|
||||
return parseABC(filePath);
|
||||
}
|
||||
} else {
|
||||
if (sourceType === "alipay") return parseAlipayFile(filePath);
|
||||
const content = fs.readFileSync(filePath, "utf-8");
|
||||
const records = parse(content, {
|
||||
columns: true,
|
||||
skip_empty_lines: true,
|
||||
bom: true,
|
||||
relax_column_count: true,
|
||||
trim: true,
|
||||
});
|
||||
if (!records?.length) return [];
|
||||
return parseWechatCSV(records);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// POST /api/upload — 解析 + 暂存,返回预览
|
||||
router.post("/", upload.single("file"), async (req, res) => {
|
||||
try {
|
||||
const { source_type, source_name } = req.body;
|
||||
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);
|
||||
if (!VALID_TYPES.includes(source_type))
|
||||
return res.status(400).json({ error: "无效的账单类型" });
|
||||
if (!req.file) return res.status(400).json({ error: "请选择文件" });
|
||||
|
||||
const originalname = Buffer.from(req.file.originalname, "latin1").toString(
|
||||
"utf8",
|
||||
);
|
||||
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();
|
||||
|
||||
if (db.prepare('SELECT id FROM sources WHERE file_hash = ?').get(fileHash)) {
|
||||
if (
|
||||
db.prepare("SELECT id FROM sources WHERE file_hash = ?").get(fileHash)
|
||||
) {
|
||||
fs.unlinkSync(req.file.path);
|
||||
return res.status(409).json({ error: '该文件已导入过' });
|
||||
return res.status(409).json({ error: "该文件已导入过" });
|
||||
}
|
||||
|
||||
let parsedTransactions;
|
||||
|
||||
if (isExcel) {
|
||||
switch (source_type) {
|
||||
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 {
|
||||
// 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);
|
||||
}
|
||||
const parsed = parseFile(req.file.path, source_type, originalname);
|
||||
if (!parsed?.length) {
|
||||
fs.unlinkSync(req.file.path);
|
||||
return res.status(400).json({ error: "未能解析出交易记录" });
|
||||
}
|
||||
|
||||
if (!parsedTransactions?.length) return res.status(400).json({ error: '未能解析出交易记录' });
|
||||
console.log(`[Reco] ${source_type}: ${parsedTransactions.length}条`);
|
||||
// 暂存到临时文件
|
||||
const tempId = crypto.randomBytes(8).toString("hex");
|
||||
const tempPath = path.join(tempDir, tempId + ".json");
|
||||
fs.writeFileSync(
|
||||
tempPath,
|
||||
JSON.stringify({
|
||||
parsed,
|
||||
sourceType: source_type,
|
||||
sourceName: source_name || source_type,
|
||||
originalname,
|
||||
fileHash,
|
||||
uploadPath: req.file.path,
|
||||
}),
|
||||
);
|
||||
|
||||
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);
|
||||
res.json({
|
||||
success: true,
|
||||
preview: true,
|
||||
tempId,
|
||||
record_count: parsed.length,
|
||||
sample: parsed.slice(0, 5),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 解析失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/upload/confirm — 确认导入
|
||||
router.post("/confirm", (req, res) => {
|
||||
try {
|
||||
const { tempId } = req.body;
|
||||
if (!tempId) return res.status(400).json({ error: "缺少 tempId" });
|
||||
const tempPath = path.join(tempDir, tempId + ".json");
|
||||
if (!fs.existsSync(tempPath))
|
||||
return res.status(400).json({ error: "预览已过期,请重新上传" });
|
||||
const temp = JSON.parse(fs.readFileSync(tempPath, "utf-8"));
|
||||
const {
|
||||
parsed,
|
||||
sourceType,
|
||||
sourceName,
|
||||
originalname,
|
||||
fileHash,
|
||||
uploadPath,
|
||||
} = temp;
|
||||
const db = getDB();
|
||||
|
||||
const src = db
|
||||
.prepare(
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?,?,?,?,?)",
|
||||
)
|
||||
.run(sourceType, sourceName, originalname, fileHash, parsed.length);
|
||||
|
||||
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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
|
||||
const ids = []; let skip = 0;
|
||||
for (const tx of parsedTransactions) {
|
||||
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++;
|
||||
let inserted = 0,
|
||||
skip = 0;
|
||||
for (const tx of parsed) {
|
||||
const code = generateTransactionCode(
|
||||
tx.transaction_date,
|
||||
tx.amount,
|
||||
tx.counterparty,
|
||||
tx.description,
|
||||
);
|
||||
const r = ins.run(
|
||||
code,
|
||||
src.lastInsertRowid,
|
||||
sourceType,
|
||||
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) inserted++;
|
||||
else skip++;
|
||||
}
|
||||
|
||||
let classifyResult = { classified: 0, source: 'none' };
|
||||
if (ids.length) try { classifyResult = await classifyTransactions(ids); } catch (e) {}
|
||||
fs.unlinkSync(tempPath);
|
||||
if (uploadPath && fs.existsSync(uploadPath)) fs.unlinkSync(uploadPath);
|
||||
|
||||
res.json({
|
||||
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)
|
||||
success: true,
|
||||
inserted,
|
||||
skipped: skip,
|
||||
source_id: src.lastInsertRowid,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[Reco] 上传失败:', err);
|
||||
console.error("[Reco] 确认导入失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
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());
|
||||
// POST /api/upload/cancel — 取消导入
|
||||
router.post("/cancel", (req, res) => {
|
||||
const { tempId } = req.body;
|
||||
if (tempId) {
|
||||
const tempPath = path.join(tempDir, tempId + ".json");
|
||||
if (fs.existsSync(tempPath)) {
|
||||
try {
|
||||
const temp = JSON.parse(fs.readFileSync(tempPath, "utf-8"));
|
||||
if (temp.uploadPath && fs.existsSync(temp.uploadPath))
|
||||
fs.unlinkSync(temp.uploadPath);
|
||||
} catch (e) {}
|
||||
fs.unlinkSync(tempPath);
|
||||
}
|
||||
}
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.delete('/sources/:id', (req, res) => {
|
||||
getDB().prepare('DELETE FROM sources WHERE id = ?').run(req.params.id);
|
||||
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);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user