feat(账单导入): 预览确认导入流程,去除账单名称输入框
- 上传先解析预览,弹框显示记录数+前5条样本,确认后入库 - 取消时删临时文件,不写入数据库 - 去掉账单名称手动输入,用来源类型自动命名 - 修复中文文件名 Latin-1 编码乱码 - 所有 alert/confirm 替换为 Toast 通知和 Modal 确认弹框 - 去除导入时自动分类逻辑
This commit is contained in:
+307
-136
@@ -6,36 +6,119 @@ import {
|
||||
AlertCircle,
|
||||
Trash2,
|
||||
RefreshCw,
|
||||
X,
|
||||
Info,
|
||||
} from "lucide-react";
|
||||
import { uploadFile, getSources, deleteSource } from "../hooks/useApi";
|
||||
import { getSources, deleteSource } from "../hooks/useApi";
|
||||
|
||||
const SOURCE_TYPES = [
|
||||
{ value: "alipay", label: "支付宝", icon: "🔵", desc: "支付宝账单 CSV 文件" },
|
||||
{ value: "wechat", label: "微信支付", icon: "🟢", desc: "微信支付账单 XLSX 文件" },
|
||||
{ value: "bank_debit", label: "浦发银行", icon: "🏦", desc: "浦发银行流水 XLS 文件" },
|
||||
{ value: "abc", label: "农业银行", icon: "🏦", desc: "农业银行流水 XLSX 文件" },
|
||||
{
|
||||
value: "alipay",
|
||||
label: "支付宝",
|
||||
icon: "\uD83D\uDD35",
|
||||
desc: "支付宝账单 CSV 文件",
|
||||
},
|
||||
{
|
||||
value: "wechat",
|
||||
label: "微信支付",
|
||||
icon: "\uD83D\uDFE2",
|
||||
desc: "微信支付账单 XLSX 文件",
|
||||
},
|
||||
{
|
||||
value: "bank_debit",
|
||||
label: "浦发银行",
|
||||
icon: "\uD83C\uDFE6",
|
||||
desc: "浦发银行流水 XLS 文件",
|
||||
},
|
||||
{
|
||||
value: "abc",
|
||||
label: "农业银行",
|
||||
icon: "\uD83C\uDFE6",
|
||||
desc: "农业银行流水 XLSX 文件",
|
||||
},
|
||||
];
|
||||
|
||||
const ALLOWED_EXTS = ["csv", "txt", "xlsx", "xls"];
|
||||
|
||||
// Toast 组件
|
||||
function Toast({ message, type, onClose }) {
|
||||
useEffect(() => {
|
||||
const t = setTimeout(onClose, 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [onClose]);
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: 24,
|
||||
right: 24,
|
||||
zIndex: 3000,
|
||||
padding: "14px 20px",
|
||||
borderRadius: 10,
|
||||
background:
|
||||
type === "success"
|
||||
? "#10b981"
|
||||
: type === "error"
|
||||
? "#ef4444"
|
||||
: "#4f46e5",
|
||||
color: "#fff",
|
||||
fontSize: 14,
|
||||
fontWeight: 500,
|
||||
boxShadow: "0 4px 12px rgba(0,0,0,0.2)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 10,
|
||||
maxWidth: 400,
|
||||
animation: "slideIn 0.3s ease",
|
||||
}}
|
||||
>
|
||||
{type === "success" ? (
|
||||
<CheckCircle size={18} />
|
||||
) : type === "error" ? (
|
||||
<AlertCircle size={18} />
|
||||
) : (
|
||||
<Info size={18} />
|
||||
)}
|
||||
<span style={{ flex: 1 }}>{message}</span>
|
||||
<button
|
||||
onClick={onClose}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "#fff",
|
||||
cursor: "pointer",
|
||||
opacity: 0.7,
|
||||
}}
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Import() {
|
||||
const [sourceType, setSourceType] = useState("alipay");
|
||||
const [sourceName, setSourceName] = useState("");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadResult, setUploadResult] = useState(null);
|
||||
const [sources, setSources] = useState([]);
|
||||
const [error, setError] = useState("");
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [preview, setPreview] = useState(null);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [toast, setToast] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadSources();
|
||||
}, []);
|
||||
|
||||
function showToast(message, type) {
|
||||
setToast({ message, type, key: Date.now() });
|
||||
}
|
||||
|
||||
async function loadSources() {
|
||||
try {
|
||||
const data = await getSources();
|
||||
setSources(data);
|
||||
setSources(await getSources());
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
@@ -48,58 +131,105 @@ export default function Import() {
|
||||
}
|
||||
setError("");
|
||||
setUploading(true);
|
||||
setUploadResult(null);
|
||||
setPreview(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("source_type", sourceType);
|
||||
formData.append(
|
||||
"source_name",
|
||||
sourceName ||
|
||||
`${SOURCE_TYPES.find((s) => s.value === sourceType)?.label}_${new Date().toLocaleDateString()}`,
|
||||
);
|
||||
const result = await uploadFile(formData);
|
||||
setUploadResult(result);
|
||||
await loadSources();
|
||||
formData.append("source_name", sourceType);
|
||||
const res = await fetch("/api/upload", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "解析失败");
|
||||
setPreview(data);
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.error || err.message || "上传失败");
|
||||
setError(err.message || "上传失败");
|
||||
}
|
||||
setUploading(false);
|
||||
}
|
||||
|
||||
async function handleDeleteSource(id) {
|
||||
if (!window.confirm("确定要删除这个导入来源及其所有交易记录吗?")) return;
|
||||
async function handleConfirm() {
|
||||
if (!preview?.tempId) return;
|
||||
setConfirming(true);
|
||||
try {
|
||||
await deleteSource(id);
|
||||
await loadSources();
|
||||
} catch (err) {}
|
||||
const res = await fetch("/api/upload/confirm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tempId: preview.tempId }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "导入失败");
|
||||
setPreview(null);
|
||||
showToast(
|
||||
`导入成功!写入 ${data.inserted} 条${data.skipped > 0 ? ",跳过 " + data.skipped + " 条重复" : ""}`,
|
||||
"success",
|
||||
);
|
||||
loadSources();
|
||||
} catch (err) {
|
||||
showToast("导入失败: " + err.message, "error");
|
||||
}
|
||||
setConfirming(false);
|
||||
}
|
||||
|
||||
async function handleCancel() {
|
||||
if (preview?.tempId) {
|
||||
await fetch("/api/upload/cancel", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tempId: preview.tempId }),
|
||||
});
|
||||
}
|
||||
setPreview(null);
|
||||
}
|
||||
|
||||
async function handleDeleteSource(id) {
|
||||
setDeleteTarget(id);
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!deleteTarget) return;
|
||||
try {
|
||||
await deleteSource(deleteTarget);
|
||||
showToast("已删除", "success");
|
||||
loadSources();
|
||||
} catch (err) {
|
||||
showToast("删除失败", "error");
|
||||
}
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
|
||||
function handleDrop(e) {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
handleFile(file);
|
||||
handleFile(e.dataTransfer.files[0]);
|
||||
}
|
||||
|
||||
const SOURCE_LABEL_MAP = {
|
||||
alipay: "支付宝",
|
||||
wechat: "微信支付",
|
||||
bank_debit: "银行借记卡",
|
||||
bank_credit: "银行贷记卡",
|
||||
credit_card: "信用卡",
|
||||
bank_debit: "浦发银行",
|
||||
abc: "农业银行",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Toast */}
|
||||
{toast && (
|
||||
<Toast
|
||||
key={toast.key}
|
||||
message={toast.message}
|
||||
type={toast.type}
|
||||
onClose={() => setToast(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="page-header">
|
||||
<h2>📥 导入账单</h2>
|
||||
<p>
|
||||
上传支付宝、微信、银行卡等账单文件(CSV/TXT/XLSX/XLS),系统自动解析并分类
|
||||
</p>
|
||||
<p>上传账单文件,确认后导入数据库</p>
|
||||
</div>
|
||||
|
||||
{/* 类型选择 */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>选择账单类型</h3>
|
||||
@@ -117,10 +247,10 @@ export default function Import() {
|
||||
key={st.value}
|
||||
onClick={() => setSourceType(st.value)}
|
||||
style={{
|
||||
padding: "16px",
|
||||
padding: 16,
|
||||
cursor: "pointer",
|
||||
textAlign: "center",
|
||||
borderRadius: "12px",
|
||||
borderRadius: 12,
|
||||
border: `2px solid ${sourceType === st.value ? "var(--primary)" : "var(--border)"}`,
|
||||
background:
|
||||
sourceType === st.value ? "var(--primary-bg)" : "white",
|
||||
@@ -142,18 +272,6 @@ export default function Import() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>账单名称(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="如:工商银行工资卡、招商银行信用卡..."
|
||||
value={sourceName}
|
||||
onChange={(e) => setSourceName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 上传区域 */}
|
||||
<div
|
||||
className={`upload-zone ${dragOver ? "drag-over" : ""}`}
|
||||
onDragOver={(e) => {
|
||||
@@ -207,97 +325,8 @@ export default function Import() {
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{uploadResult && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
padding: "16px",
|
||||
background: "#f0fdf4",
|
||||
borderRadius: 8,
|
||||
border: "1px solid #bbf7d0",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
<CheckCircle size={20} color="var(--success)" />
|
||||
<span style={{ fontWeight: 600, color: "var(--success)" }}>
|
||||
导入成功!
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
共导入 <strong>{uploadResult.record_count}</strong> 笔, 写入{" "}
|
||||
<strong>
|
||||
{uploadResult.inserted ?? uploadResult.record_count}
|
||||
</strong>{" "}
|
||||
笔
|
||||
{uploadResult.skipped > 0 && (
|
||||
<span>(跳过 {uploadResult.skipped} 笔重复)</span>
|
||||
)}
|
||||
, 分类 <strong>{uploadResult.classified || 0}</strong> 笔 (
|
||||
{uploadResult.classify_source === "llm"
|
||||
? "大模型"
|
||||
: uploadResult.classify_source === "rules"
|
||||
? "规则匹配"
|
||||
: "待分类"}
|
||||
)
|
||||
</div>
|
||||
{uploadResult.sample?.length > 0 && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>
|
||||
示例数据:
|
||||
</div>
|
||||
<div className="table-container">
|
||||
<table style={{ fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>日期</th>
|
||||
<th>对方</th>
|
||||
<th>描述</th>
|
||||
<th>金额</th>
|
||||
<th>方向</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{uploadResult.sample.map((s, i) => (
|
||||
<tr key={i}>
|
||||
<td>{s.transaction_date}</td>
|
||||
<td>{s.counterparty}</td>
|
||||
<td>{s.description}</td>
|
||||
<td
|
||||
className={
|
||||
s.direction === "income"
|
||||
? "stat-value income"
|
||||
: "stat-value expense"
|
||||
}
|
||||
>
|
||||
{s.amount.toFixed(2)}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={`tag ${s.direction === "income" ? "tag-income" : "tag-expense"}`}
|
||||
>
|
||||
{s.direction === "income" ? "收入" : "支出"}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 已导入列表 */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📋 已导入的账单</h3>
|
||||
@@ -359,6 +388,148 @@ export default function Import() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 确认导入弹框 */}
|
||||
{preview && (
|
||||
<div className="modal-overlay">
|
||||
<div className="modal" style={{ maxWidth: 480 }}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
<h3>确认导入</h3>
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16, lineHeight: 1.8 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 24,
|
||||
fontWeight: 700,
|
||||
color: "var(--primary)",
|
||||
textAlign: "center",
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
{preview.record_count} 条记录
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
textAlign: "center",
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
已成功解析,确认后导入数据库
|
||||
</div>
|
||||
</div>
|
||||
{preview.sample?.length > 0 && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>
|
||||
预览:
|
||||
</div>
|
||||
<div className="table-container">
|
||||
<table style={{ fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>日期</th>
|
||||
<th>对方</th>
|
||||
<th>描述</th>
|
||||
<th>金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.sample.map((s, i) => (
|
||||
<tr key={i}>
|
||||
<td>{s.transaction_date}</td>
|
||||
<td>{s.counterparty}</td>
|
||||
<td
|
||||
style={{
|
||||
maxWidth: 120,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{s.description}
|
||||
</td>
|
||||
<td
|
||||
className={
|
||||
s.direction === "income"
|
||||
? "stat-value income"
|
||||
: "stat-value expense"
|
||||
}
|
||||
>
|
||||
{s.amount.toFixed(2)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}
|
||||
>
|
||||
<button className="btn btn-secondary" onClick={handleCancel}>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleConfirm}
|
||||
disabled={confirming}
|
||||
>
|
||||
<CheckCircle size={16} />{" "}
|
||||
{confirming ? "导入中..." : "确认导入"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 删除确认弹框 */}
|
||||
{deleteTarget && (
|
||||
<div className="modal-overlay">
|
||||
<div className="modal" style={{ maxWidth: 400 }}>
|
||||
<h3 style={{ marginBottom: 12 }}>确认删除</h3>
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
marginBottom: 20,
|
||||
fontSize: 14,
|
||||
}}
|
||||
>
|
||||
确定要删除此账单来源及其所有交易记录吗?此操作不可撤销。
|
||||
</p>
|
||||
<div
|
||||
style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}
|
||||
>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setDeleteTarget(null)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button className="btn btn-danger" onClick={confirmDelete}>
|
||||
确认删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,4 +6,6 @@ Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
|
||||
1.先把数据导入的功能做清楚
|
||||
2.把交易合并功能做清楚
|
||||
2.把调用大模型做分类的功能做清楚
|
||||
3.最后调报表
|
||||
为“AI分类全部”专门写一个服务,这个方法不需要传参,过程与原有方法类似,不过它的逻辑是取出当前全部订单,写成并行的。
|
||||
取消在导入账单时调用大模型分类的逻辑
|
||||
3.最后调报表
|
||||
|
||||
+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