230 lines
6.9 KiB
JavaScript
230 lines
6.9 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 { 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;
|