119 lines
5.4 KiB
JavaScript
119 lines
5.4 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 { 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 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 }
|
|
});
|
|
|
|
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);
|
|
|
|
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: '该文件已导入过' });
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
if (!parsedTransactions?.length) return res.status(400).json({ error: '未能解析出交易记录' });
|
|
console.log(`[Reco] ${source_type}: ${parsedTransactions.length}条`);
|
|
|
|
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);
|
|
|
|
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 classifyResult = { classified: 0, source: 'none' };
|
|
if (ids.length) try { classifyResult = await classifyTransactions(ids); } catch (e) {}
|
|
|
|
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)
|
|
});
|
|
} catch (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());
|
|
});
|
|
|
|
router.delete('/sources/:id', (req, res) => {
|
|
getDB().prepare('DELETE FROM sources WHERE id = ?').run(req.params.id);
|
|
res.json({ success: true });
|
|
});
|
|
|
|
module.exports = router;
|