Add deals feature for reconciled transactions
- Create deals schema and routes to group matched transactions - Display deals in a new card on the Transactions page - Generate deals during reconciliation and refresh them on demand
This commit is contained in:
+47
-14
@@ -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 };
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
@@ -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));
|
||||
|
||||
Reference in New Issue
Block a user