diff --git a/client/src/pages/Transactions.js b/client/src/pages/Transactions.js
index db2b71f..dd52593 100644
--- a/client/src/pages/Transactions.js
+++ b/client/src/pages/Transactions.js
@@ -20,6 +20,7 @@ export default function Transactions() {
const [reconciling, setReconciling] = useState(false);
const [classifying, setClassifying] = useState(false);
const [classifyProgress, setClassifyProgress] = useState(0);
+ const [deals, setDeals] = useState(null);
// 恢复分类进度(刷新后轮询)
useEffect(() => {
@@ -86,9 +87,15 @@ export default function Transactions() {
);
}
+ async function loadDeals() {
+ try { const res = await fetch("/api/deals"); const d = await res.json(); setDeals(d.deals); } catch (e) {}
+ }
+
+ useEffect(() => { loadDeals(); }, []);
+
async function handleReconcile() {
setReconciling(true);
- try { const r = await runReconciliation(); alert(`对账完成!成功匹配 ${r.matched} 对`); loadTransactions(); } catch (err) {}
+ try { const r = await runReconciliation(); loadDeals(); alert(`对账完成!成功匹配 ${r.matched} 对`); loadTransactions(); } catch (err) {}
setReconciling(false);
}
@@ -225,7 +232,34 @@ export default function Transactions() {
)}
- {editingTx && (
+
+ {/* 关联交易 */}
+ {deals && deals.length > 0 && (
+
setEditingTx(null)}>
e.stopPropagation()}>
编辑交易
diff --git a/server/db.js b/server/db.js
index 76e7e33..a0d61df 100644
--- a/server/db.js
+++ b/server/db.js
@@ -1,11 +1,11 @@
-const Database = require('better-sqlite3');
-const path = require('path');
+const Database = require("better-sqlite3");
+const path = require("path");
-const DB_PATH = path.join(__dirname, '..', 'data', 'reco.db');
+const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
// Ensure data directory exists
-const fs = require('fs');
-const dataDir = path.join(__dirname, '..', 'data');
+const fs = require("fs");
+const dataDir = path.join(__dirname, "..", "data");
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
@@ -15,8 +15,8 @@ let db;
function getDB() {
if (!db) {
db = new Database(DB_PATH);
- db.pragma('journal_mode = WAL');
- db.pragma('foreign_keys = ON');
+ db.pragma("journal_mode = WAL");
+ db.pragma("foreign_keys = ON");
}
return db;
}
@@ -105,16 +105,47 @@ function initDB() {
CREATE INDEX IF NOT EXISTS idx_tx_reviewed ON transactions(reviewed);
CREATE INDEX IF NOT EXISTS idx_tx_matched ON transactions(matched_transaction_id);
CREATE INDEX IF NOT EXISTS idx_tx_category ON transactions(category);
+ CREATE TABLE IF NOT EXISTS deals (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ deal_date DATE NOT NULL,
+ amount REAL NOT NULL,
+ counterparty TEXT,
+ description TEXT,
+ match_count INTEGER DEFAULT 2,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS deal_transactions (
+ deal_id INTEGER NOT NULL,
+ transaction_id INTEGER NOT NULL,
+ PRIMARY KEY (deal_id, transaction_id),
+ FOREIGN KEY (deal_id) REFERENCES deals(id) ON DELETE CASCADE,
+ FOREIGN KEY (transaction_id) REFERENCES transactions(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_deal_date ON deals(deal_date);
+ CREATE INDEX IF NOT EXISTS idx_dt_deal ON deal_transactions(deal_id);
+
`);
// 仅首次初始化时插入默认分类(不再用固定ID)
- const catCount = database.prepare("SELECT COUNT(*) as c FROM categories").get().c;
+ const catCount = database
+ .prepare("SELECT COUNT(*) as c FROM categories")
+ .get().c;
if (catCount === 0) {
- const insertCategory = database.prepare("INSERT INTO categories (name, keywords) VALUES (?, ?)");
+ const insertCategory = database.prepare(
+ "INSERT INTO categories (name, keywords) VALUES (?, ?)",
+ );
const defaults = [
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
- ["交通出行", '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
- ["购物消费", '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
+ [
+ "交通出行",
+ '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
+ ],
+ [
+ "购物消费",
+ '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
+ ],
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
["通讯网络", '["话费","宽带","流量"]'],
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
@@ -124,13 +155,15 @@ function initDB() {
["教育学习", '["学费","培训","书本","课程","考试"]'],
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
- ["其他杂项", "[]"]
+ ["其他杂项", "[]"],
];
- database.transaction(() => { defaults.forEach(c => insertCategory.run(c[0], c[1])); })();
+ database.transaction(() => {
+ defaults.forEach((c) => insertCategory.run(c[0], c[1]));
+ })();
console.log("[Reco] 已初始化默认分类");
}
- console.log('[Reco] 数据库初始化完成');
+ console.log("[Reco] 数据库初始化完成");
}
module.exports = { getDB, initDB };
diff --git a/server/index.js b/server/index.js
index 5675c02..7b0c67d 100644
--- a/server/index.js
+++ b/server/index.js
@@ -11,6 +11,7 @@ const transactionRoutes = require("./routes/transactions");
const classifyRoutes = require("./routes/classify");
const statsRoutes = require("./routes/stats");
const configRoutes = require("./routes/config");
+const dealsRoutes = require("./routes/deals");
const app = express();
const PORT = process.env.PORT || 3001;
@@ -25,6 +26,7 @@ app.use("/api/transactions", transactionRoutes);
app.use("/api/classify", classifyRoutes);
app.use("/api/stats", statsRoutes);
app.use("/api/config", configRoutes);
+app.use("/api/deals", dealsRoutes);
// Serve React static files in production
const clientBuildPath = path.join(__dirname, "..", "client", "build");
diff --git a/server/routes/deals.js b/server/routes/deals.js
new file mode 100644
index 0000000..2856441
--- /dev/null
+++ b/server/routes/deals.js
@@ -0,0 +1,112 @@
+const express = require('express');
+const { getDB } = require('../db');
+const router = express.Router();
+
+// GET /api/deals — 获取所有对账关联
+router.get('/', (req, res) => {
+ const db = getDB();
+ const { page = 1, limit = 50 } = req.query;
+ const offset = (page - 1) * limit;
+
+ const deals = db.prepare(`
+ SELECT d.*, GROUP_CONCAT(t.transaction_code) as codes
+ FROM deals d
+ LEFT JOIN deal_transactions dt ON dt.deal_id = d.id
+ LEFT JOIN transactions t ON t.id = dt.transaction_id
+ GROUP BY d.id
+ ORDER BY d.deal_date DESC, ABS(d.amount) DESC
+ LIMIT ? OFFSET ?
+ `).all(limit, offset);
+
+ const total = db.prepare('SELECT COUNT(*) as c FROM deals').get().c;
+
+ // 加载每笔 deal 的关联交易
+ for (const deal of deals) {
+ deal.transactions = db.prepare(`
+ SELECT t.*, s.source_name
+ FROM deal_transactions dt
+ JOIN transactions t ON t.id = dt.transaction_id
+ LEFT JOIN sources s ON s.id = t.source_id
+ WHERE dt.deal_id = ?
+ ORDER BY t.transaction_date
+ `).all(deal.id);
+ }
+
+ res.json({ deals, total, page: Number(page), totalPages: Math.ceil(total / limit) });
+});
+
+// POST /api/deals/generate — 根据现有 matched 关系生成 deals
+router.post('/generate', (req, res) => {
+ const db = getDB();
+
+ // 清除旧数据
+ db.prepare('DELETE FROM deal_transactions').run();
+ db.prepare('DELETE FROM deals').run();
+
+ // 查找所有已匹配的交易对(只取一方避免重复)
+ const pairs = db.prepare(`
+ SELECT DISTINCT
+ MIN(t1.id, t2.id) as id1,
+ MAX(t1.id, t2.id) as id2,
+ t1.transaction_date as d1, t2.transaction_date as d2,
+ t1.amount as a1, t2.amount as a2,
+ t1.counterparty as cp1, t2.counterparty as cp2,
+ t1.description as desc1, t2.description as desc2,
+ t1.match_score
+ FROM transactions t1
+ JOIN transactions t2 ON t2.id = t1.matched_transaction_id
+ WHERE t1.matched_transaction_id IS NOT NULL
+ AND t1.id < t1.matched_transaction_id
+ ORDER BY ABS(t1.amount) DESC
+ `).all();
+
+ const insertDeal = db.prepare('INSERT INTO deals (deal_date, amount, counterparty, description) VALUES (?,?,?,?)');
+ const insertDt = db.prepare('INSERT OR IGNORE INTO deal_transactions (deal_id, transaction_id) VALUES (?,?)');
+
+ let count = 0;
+ for (const p of pairs) {
+ const dealDate = p.d1 || p.d2;
+ const amount = p.a1 || p.a2;
+ const cp = [p.cp1, p.cp2].filter(Boolean).join(' / ');
+ const desc = [p.desc1, p.desc2].filter(Boolean).join(' / ');
+ const r = insertDeal.run(dealDate, amount, cp, desc);
+ insertDt.run(r.lastInsertRowid, p.id1);
+ insertDt.run(r.lastInsertRowid, p.id2);
+ count++;
+ }
+
+ res.json({ success: true, generated: count, total: pairs.length });
+});
+
+// POST /api/deals/refresh — 刷新 deals(增量更新)
+router.post('/refresh', (req, res) => {
+ const db = getDB();
+
+ // 找到有 matched 但不在 deals 中的交易
+ const matched = db.prepare(`
+ SELECT t1.id as id1, t2.id as id2, t1.transaction_date, t1.amount,
+ t1.counterparty as cp1, t2.counterparty as cp2,
+ t1.description as desc1, t2.description as desc2
+ FROM transactions t1
+ JOIN transactions t2 ON t2.id = t1.matched_transaction_id
+ WHERE t1.id < t1.matched_transaction_id
+ AND t1.id NOT IN (SELECT transaction_id FROM deal_transactions)
+ `).all();
+
+ if (matched.length === 0) return res.json({ success: true, added: 0 });
+
+ const insertDeal = db.prepare('INSERT INTO deals (deal_date, amount, counterparty, description) VALUES (?,?,?,?)');
+ const insertDt = db.prepare('INSERT OR IGNORE INTO deal_transactions (deal_id, transaction_id) VALUES (?,?)');
+
+ for (const p of matched) {
+ const r = insertDeal.run(p.transaction_date, p.amount,
+ [p.cp1, p.cp2].filter(Boolean).join(' / '),
+ [p.desc1, p.desc2].filter(Boolean).join(' / '));
+ insertDt.run(r.lastInsertRowid, p.id1);
+ insertDt.run(r.lastInsertRowid, p.id2);
+ }
+
+ res.json({ success: true, added: matched.length });
+});
+
+module.exports = router;
diff --git a/server/routes/transactions.js b/server/routes/transactions.js
index 18268f3..5024001 100644
--- a/server/routes/transactions.js
+++ b/server/routes/transactions.js
@@ -115,14 +115,20 @@ router.get("/", (req, res) => {
router.get("/needs-classify", (req, res) => {
const db = getDB();
- const validCats = db.prepare('SELECT name FROM categories').all().map(r => r.name);
+ const validCats = db
+ .prepare("SELECT name FROM categories")
+ .all()
+ .map((r) => r.name);
if (validCats.length === 0) return res.json({ ids: [], total: 0 });
- const ph = validCats.map(() => '?').join(',');
- const stale = db.prepare(`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`).all(...validCats);
- res.json({ ids: stale.map(r => r.id), total: stale.length });
+ const ph = validCats.map(() => "?").join(",");
+ const stale = db
+ .prepare(
+ `SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
+ )
+ .all(...validCats);
+ res.json({ ids: stale.map((r) => r.id), total: stale.length });
});
-
// GET /api/transactions/:id - 获取单笔交易详情
router.get("/:id", (req, res) => {
const db = getDB();
@@ -232,10 +238,40 @@ router.put("/:id", (req, res) => {
res.json({ success: true, transaction: updated });
});
-// POST /api/transactions/reconcile - 运行自动对账
+// POST /api/transactions/reconcile - 全量清除后重新对账,每笔交易生成deal
router.post("/reconcile", (req, res) => {
+ const db = getDB();
+ // 清除旧数据
+ db.prepare("DELETE FROM deal_transactions").run();
+ db.prepare("DELETE FROM deals").run();
+ db.prepare("UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL").run();
+ // 运行自动匹配
const result = runAutoReconciliation();
- res.json({ success: true, ...result });
+ // 收集所有交易,按 matched 关系分组
+ const allTxs = db.prepare("SELECT id,transaction_date,transaction_time,amount,counterparty,description,matched_transaction_id FROM transactions ORDER BY transaction_date,transaction_time").all();
+ const visited = new Set(); const groups = [];
+ for (const tx of allTxs) {
+ if (visited.has(tx.id)) continue; visited.add(tx.id);
+ const group = [tx];
+ for (const other of allTxs) {
+ if (visited.has(other.id)) continue;
+ if (other.matched_transaction_id===tx.id||tx.matched_transaction_id===other.id||(tx.matched_transaction_id&&tx.matched_transaction_id===other.matched_transaction_id)) {
+ group.push(other); visited.add(other.id);
+ }
+ }
+ groups.push(group);
+ }
+ // 为每组生成 deal(取最早一笔填充信息)
+ const insD=db.prepare("INSERT INTO deals(deal_date,amount,counterparty,description,match_count)VALUES(?,?,?,?,?)");
+ const insT=db.prepare("INSERT INTO deal_transactions(deal_id,transaction_id)VALUES(?,?)");
+ let dc=0;
+ for(const group of groups){
+ const e=group.reduce((a,b)=>(a.transaction_time||a.transaction_date)<(b.transaction_time||b.transaction_date)?a:b); const dealTime = e.transaction_time || e.transaction_date;
+ const r=insD.run(dealTime,e.amount,e.counterparty,e.description,group.length);
+ for(const tx of group)insT.run(r.lastInsertRowid,tx.id);
+ dc++;
+ }
+ res.json({success:true,matched:result.matched,total:result.total,deals:dc});
});
// POST /api/transactions/classify - 对选中的交易重新分类
@@ -258,14 +294,29 @@ router.post("/classify", async (req, res) => {
// POST /api/transactions/classify-all — 重分类过期分类的交易
router.post("/classify-all", async (req, res) => {
const db = getDB();
- const validCats = db.prepare('SELECT name FROM categories').all().map(r => r.name);
- if (validCats.length === 0) return res.json({ success: true, classified: 0, message: '无分类配置' });
+ const validCats = db
+ .prepare("SELECT name FROM categories")
+ .all()
+ .map((r) => r.name);
+ if (validCats.length === 0)
+ return res.json({ success: true, classified: 0, message: "无分类配置" });
- const ph = validCats.map(() => '?').join(',');
- const stale = db.prepare(`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`).all(...validCats);
- if (stale.length === 0) return res.json({ success: true, classified: 0, total: 0, message: '所有交易分类均有效' });
+ const ph = validCats.map(() => "?").join(",");
+ const stale = db
+ .prepare(
+ `SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`,
+ )
+ .all(...validCats);
+ if (stale.length === 0)
+ return res.json({
+ success: true,
+ classified: 0,
+ total: 0,
+ message: "所有交易分类均有效",
+ });
- const ids = stale.map(r => r.id), batchSize = 50;
+ const ids = stale.map((r) => r.id),
+ batchSize = 50;
let classified = 0;
for (let i = 0; i < ids.length; i += batchSize) {
const r = await classifyTransactions(ids.slice(i, i + batchSize));