diff --git a/client/src/pages/Import.js b/client/src/pages/Import.js
index baa48ec..724c8dd 100644
--- a/client/src/pages/Import.js
+++ b/client/src/pages/Import.js
@@ -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 (
+
+ {type === "success" ? (
+
+ ) : type === "error" ? (
+
+ ) : (
+
+ )}
+
{message}
+
+
+ );
+}
+
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 (
+ {/* Toast */}
+ {toast && (
+
setToast(null)}
+ />
+ )}
+
📥 导入账单
-
- 上传支付宝、微信、银行卡等账单文件(CSV/TXT/XLSX/XLS),系统自动解析并分类
-
+
上传账单文件,确认后导入数据库
- {/* 类型选择 */}
选择账单类型
@@ -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() {
))}
-
-
- setSourceName(e.target.value)}
- />
-
-
- {/* 上传区域 */}
{
@@ -207,97 +325,8 @@ export default function Import() {
{error}
)}
-
- {uploadResult && (
-
-
-
-
- 导入成功!
-
-
-
- 共导入 {uploadResult.record_count} 笔, 写入{" "}
-
- {uploadResult.inserted ?? uploadResult.record_count}
- {" "}
- 笔
- {uploadResult.skipped > 0 && (
- (跳过 {uploadResult.skipped} 笔重复)
- )}
- , 分类 {uploadResult.classified || 0} 笔 (
- {uploadResult.classify_source === "llm"
- ? "大模型"
- : uploadResult.classify_source === "rules"
- ? "规则匹配"
- : "待分类"}
- )
-
- {uploadResult.sample?.length > 0 && (
-
-
- 示例数据:
-
-
-
-
-
- | 日期 |
- 对方 |
- 描述 |
- 金额 |
- 方向 |
-
-
-
- {uploadResult.sample.map((s, i) => (
-
- | {s.transaction_date} |
- {s.counterparty} |
- {s.description} |
-
- {s.amount.toFixed(2)}
- |
-
-
- {s.direction === "income" ? "收入" : "支出"}
-
- |
-
- ))}
-
-
-
-
- )}
-
- )}
- {/* 已导入列表 */}
📋 已导入的账单
@@ -359,6 +388,148 @@ export default function Import() {
)}
+
+ {/* 确认导入弹框 */}
+ {preview && (
+
+
+
+
确认导入
+
+
+
+
+ {preview.record_count} 条记录
+
+
+ 已成功解析,确认后导入数据库
+
+
+ {preview.sample?.length > 0 && (
+
+
+ 预览:
+
+
+
+
+
+ | 日期 |
+ 对方 |
+ 描述 |
+ 金额 |
+
+
+
+ {preview.sample.map((s, i) => (
+
+ | {s.transaction_date} |
+ {s.counterparty} |
+
+ {s.description}
+ |
+
+ {s.amount.toFixed(2)}
+ |
+
+ ))}
+
+
+
+
+ )}
+
+
+
+
+
+
+ )}
+
+ {/* 删除确认弹框 */}
+ {deleteTarget && (
+
+
+
确认删除
+
+ 确定要删除此账单来源及其所有交易记录吗?此操作不可撤销。
+
+
+
+
+
+
+
+ )}
);
}
diff --git a/readme.md b/readme.md
index 2063dc7..451c82a 100644
--- a/readme.md
+++ b/readme.md
@@ -6,4 +6,6 @@ Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
1.先把数据导入的功能做清楚
2.把交易合并功能做清楚
2.把调用大模型做分类的功能做清楚
-3.最后调报表
\ No newline at end of file
+为“AI分类全部”专门写一个服务,这个方法不需要传参,过程与原有方法类似,不过它的逻辑是取出当前全部订单,写成并行的。
+取消在导入账单时调用大模型分类的逻辑
+3.最后调报表
diff --git a/server/routes/upload.js b/server/routes/upload.js
index b9004ee..ad0d1e3 100644
--- a/server/routes/upload.js
+++ b/server/routes/upload.js
@@ -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 });
});