Files

247 lines
7.1 KiB
JavaScript

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");
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 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 },
});
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 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 db = getDB();
if (
db.prepare("SELECT id FROM sources WHERE file_hash = ?").get(fileHash)
) {
fs.unlinkSync(req.file.path);
return res.status(409).json({ error: "该文件已导入过" });
}
const parsed = parseFile(req.file.path, source_type, originalname);
if (!parsed?.length) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: "未能解析出交易记录" });
}
// 暂存到临时文件
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,
}),
);
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 userId = req.userId;
const src = db
.prepare(
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count, user_id) VALUES (?,?,?,?,?,?)",
)
.run(
sourceType,
sourceName,
originalname,
fileHash,
parsed.length,
userId,
);
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, user_id
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
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,
userId,
);
if (r.changes > 0) inserted++;
else skip++;
}
fs.unlinkSync(tempPath);
if (uploadPath && fs.existsSync(uploadPath)) fs.unlinkSync(uploadPath);
res.json({
success: true,
inserted,
skipped: skip,
source_id: src.lastInsertRowid,
});
} catch (err) {
console.error("[Reco] 确认导入失败:", err);
res.status(500).json({ error: err.message });
}
});
// 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.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 WHERE s.user_id = ? GROUP BY s.id ORDER BY s.imported_at DESC",
)
.all(req.userId),
);
});
router.delete("/sources/:id", (req, res) => {
getDB()
.prepare("DELETE FROM sources WHERE id = ? AND user_id = ?")
.run(req.params.id, req.userId);
res.json({ success: true });
});
module.exports = router;