diff --git a/client/src/pages/Transactions.js b/client/src/pages/Transactions.js
index 5f9c1fa..3dadb5c 100644
--- a/client/src/pages/Transactions.js
+++ b/client/src/pages/Transactions.js
@@ -1,5 +1,5 @@
-import React, { useState, useEffect } from 'react';
-import { RotateCcw, Link2, Brain, ChevronLeft, ChevronRight, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
+mport React, { useState, useEffect } from 'react';
+import { RotateCcw, Link2, Brain, ChevronLeft, ChevronRight, ArrowUpDown, ArrowUp, ArrowDown, CheckCircle, AlertCircle, X } from 'lucide-react';
import { getTransactions, runReconciliation, classifyTransactions, formatAmount, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
function fmtDatetime(dt) {
@@ -10,7 +10,7 @@ function fmtDatetime(dt) {
export default function Transactions() {
const [data, setData] = useState({ transactions: [], total: 0, page: 1, totalPages: 0 });
const [filters, setFilters] = useState({
- page: 1, limit: 50, start_date: '', end_date: '',
+ page: 1, limit: 20, start_date: '', end_date: '',
source_type: '', direction: '', keyword: '',
sort_by: 'transaction_time', sort_order: 'DESC'
});
@@ -19,7 +19,16 @@ export default function Transactions() {
const [reconciling, setReconciling] = useState(false);
const [classifying, setClassifying] = useState(false);
const [classifyProgress, setClassifyProgress] = useState(0);
- const [deals, setDeals] = useState(null);
+ const [toast, setToast] = useState(null);
+ const [deals, setDeals] = useState({ deals: [], total: 0, page: 1, totalPages: 0 });
+ const [clearConfirm, setClearConfirm] = useState(false);
+ const [dealFilters, setDealFilters] = useState({ page: 1, limit: 20, keyword: "", sort_by: "deal_date", sort_order: "DESC" });
+
+ function dealToggleSort(field) { setDealFilters(p => ({ ...p, sort_by: field, sort_order: p.sort_by === field && p.sort_order === "DESC" ? "ASC" : "DESC", page: 1 })); }
+ function DealSortIcon({ field }) { if (dealFilters.sort_by !== field) return ; return dealFilters.sort_order === "ASC" ? : ; }
+ function DealTh({ field, children, style }) { return
dealToggleSort(field)} style={{ cursor: "pointer", userSelect: "none", ...style }}>{children} | ; }
+
+ function showToast(msg, type) { setToast({ message: msg, type, key: Date.now() }); }
// 恢复分类进度
useEffect(() => {
@@ -40,11 +49,12 @@ export default function Transactions() {
return () => clearInterval(poll);
}, []);
- useEffect(() => { loadCategories(); loadDeals(); }, []);
+ useEffect(() => { loadCategories(); loadDeals(dealFilters); }, []);
+ useEffect(() => { loadDeals(dealFilters); }, [dealFilters]);
useEffect(() => { loadTransactions(); }, [filters]);
async function loadCategories() { try { setCategories(await getCategories()); } catch (e) {} }
- async function loadDeals() { try { const r = await fetch('/api/deals'); setDeals((await r.json()).deals); } catch (e) {} }
+ async function loadDeals(filters) { try { const p = new URLSearchParams(filters); const r = await fetch('/api/deals?' + p); const d = await r.json(); setDeals(d); } catch (e) {} }
async function loadTransactions() {
setLoading(true);
@@ -69,9 +79,13 @@ export default function Transactions() {
return toggleSort(field)} style={{ cursor: 'pointer', userSelect: 'none', ...style }}>{children} | ;
}
+ async function handleClearDeals() {
+ try { await fetch("/api/deals/clear", { method: "POST" }); setDeals({ deals: [], total: 0, page: 1, totalPages: 0 }); setClearConfirm(false); } catch (e) {}
+ }
+
async function handleReconcile() {
setReconciling(true);
- try { const r = await runReconciliation(); alert('匹配 ' + (r.matched || 0) + ' 对,生成 ' + (r.deals || 0) + ' 条关联'); loadTransactions(); loadDeals(); } catch (e) {}
+ try { const r = await runReconciliation(); showToast('匹配 ' + (r.matched || 0) + ' 对,生成 ' + (r.deals || 0) + ' 条关联', 'success'); loadTransactions(); loadDeals(dealFilters); } catch (e) {}
setReconciling(false);
}
@@ -81,7 +95,7 @@ export default function Transactions() {
try {
const res = await fetch('/api/transactions/needs-classify');
const { ids, total } = await res.json();
- if (!ids.length) { alert('所有交易分类均有效!'); setClassifying(false); sessionStorage.removeItem('classifyTask'); return; }
+ if (!ids.length) { showToast('所有交易分类均有效!', 'info'); setClassifying(false); sessionStorage.removeItem('classifyTask'); return; }
sessionStorage.setItem('classifyTask', JSON.stringify({ total, progress: 0, ts: Date.now() }));
const B = 50; let done = 0;
for (let i = 0; i < ids.length; i += B) {
@@ -92,9 +106,9 @@ export default function Transactions() {
sessionStorage.setItem('classifyTask', JSON.stringify({ total, progress: pct, ts: Date.now() }));
}
sessionStorage.removeItem('classifyTask');
- alert('分类完成!共重分类 ' + total + ' 笔');
+ showToast('分类完成!共重分类 ' + total + ' 笔', 'success');
loadTransactions();
- } catch (e) { sessionStorage.removeItem('classifyTask'); alert('分类失败: ' + (e.response?.data?.error || e.message)); }
+ } catch (e) { sessionStorage.removeItem('classifyTask'); showToast('分类失败: ' + (e.response?.data?.error || e.message), 'error'); }
setClassifying(false);
}
@@ -105,22 +119,22 @@ export default function Transactions() {
-
+
+
{/* 筛选+表格 合体卡片 */}
-
-
updateFilter('start_date', e.target.value)} />
-
updateFilter('end_date', e.target.value)} />
-
-
-
updateFilter('keyword', e.target.value)} />
+
+
交易记录
+ 共 {data.total} 笔,第 {data.page}/{data.totalPages} 页
-
-
-
共 {data.total} 笔交易
-
第 {data.page}/{data.totalPages} 页 · 点击列头排序
+
+
updateFilter("start_date", e.target.value)} />
+
updateFilter("end_date", e.target.value)} />
+
+
+
updateFilter("keyword", e.target.value)} />
{loading ? (
@@ -163,23 +177,36 @@ export default function Transactions() {
{/* 关联交易 */}
- {deals && deals.length > 0 && (
+ {deals.deals && deals.deals.length > 0 && (
-
🔗 关联交易(Deal)
共 {deals.length} 条
+
+
关联交易
+ 共 {deals.total} 条,第 {deals.page}/{deals.totalPages} 页
+
+
+
setDealFilters(p => ({ ...p, keyword: e.target.value, page: 1 }))} />
+
+
- | 日期 | 金额 | 分类 | 对方 | 关联明细 |
+
+ | dealToggleSort("deal_date")} style={{ cursor: "pointer", userSelect: "none" }}>日期{dealFilters.sort_by === "deal_date" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} |
+ dealToggleSort("amount")} style={{ cursor: "pointer", userSelect: "none", textAlign: "right" }}>金额{dealFilters.sort_by === "amount" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} |
+ dealToggleSort("category")} style={{ cursor: "pointer", userSelect: "none" }}>分类{dealFilters.sort_by === "category" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} |
+ dealToggleSort("counterparty")} style={{ cursor: "pointer", userSelect: "none" }}>对方{dealFilters.sort_by === "counterparty" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} |
+ 关联明细 |
+
- {deals.map(d => (
+ {deals.deals.map(d => (
- | {d.deal_date} |
- = 0 ? 'stat-value income' : 'stat-value expense'}>{formatAmount(d.amount)} |
- {d.category || 未分类} |
- {d.counterparty || '--'} |
-
+ | {d.deal_date} |
+ = 0 ? "stat-value income" : "stat-value expense"}>{formatAmount(d.amount)} |
+ {d.category || 未分类} |
+ {d.counterparty || "--"} |
+
{d.transactions?.map((t, i) => (
- {SOURCE_TYPE_MAP[t.source_type]}
- {' '}{t.description?.substring(0, 20)}
+ {SOURCE_TYPE_MAP[t.source_type]}
+ {" "}{t.description?.substring(0, 20)}
))}
|
@@ -187,6 +214,35 @@ export default function Transactions() {
))}
+ {deals.totalPages > 1 && (
+
+
+ {Array.from({ length: Math.min(deals.totalPages, 7) }, (_, i) => { const pg = i + Math.max(1, deals.page - 3); if (pg > deals.totalPages) return null; return ; })}
+
+
+ )}
+
+ )}
+
+
+ {clearConfirm && (
+
+
+
清空关联交易
+
确定要清空所有 Deal 关联记录吗?此操作不可撤销。
+
+
+
+
+
+
+ )}
+
+ {toast && (
+
+ {toast.type === "success" ?
: toast.type === "error" ?
:
}
+
{toast.message}
+
)}
diff --git a/data/scripts/reco.sqbpro b/data/scripts/reco.sqbpro
new file mode 100644
index 0000000..1de3641
--- /dev/null
+++ b/data/scripts/reco.sqbpro
@@ -0,0 +1,5 @@
+
select * from deals
+select * from transactions
+
+
+
diff --git a/server/routes/deals.js b/server/routes/deals.js
index a1ba5e0..17e4e98 100644
--- a/server/routes/deals.js
+++ b/server/routes/deals.js
@@ -2,23 +2,40 @@ const express = require('express');
const { getDB } = require('../db');
const router = express.Router();
-// GET /api/deals
+// GET /api/deals — 支持筛选和分页
router.get('/', (req, res) => {
const db = getDB();
- const { page = 1, limit = 50 } = req.query;
+ const { page = 1, limit = 20, start_date, end_date, category, direction, keyword, sort_by = 'deal_date', sort_order = 'DESC' } = req.query;
const offset = (page - 1) * limit;
+ const conditions = [];
+ const params = [];
+ if (start_date) { conditions.push('d.deal_date >= ?'); params.push(start_date); }
+ if (end_date) { conditions.push('d.deal_date <= ?'); params.push(end_date); }
+ if (category) { conditions.push('d.category = ?'); params.push(category); }
+ if (direction) { conditions.push('d.direction = ?'); params.push(direction); }
+ if (keyword) {
+ conditions.push('(d.counterparty LIKE ? OR d.description LIKE ? OR d.ai_description LIKE ?)');
+ params.push('%' + keyword + '%', '%' + keyword + '%', '%' + keyword + '%');
+ }
+ const where = conditions.length ? 'WHERE ' + conditions.join(' AND ') : '';
+
+ const allowedSort = ['id', 'deal_date', 'amount', 'counterparty', 'category', 'match_count'];
+ const safeSort = allowedSort.includes(sort_by) ? sort_by : 'deal_date';
+ const safeOrder = sort_order === 'ASC' ? 'ASC' : 'DESC';
+
+ const total = db.prepare(`SELECT COUNT(*) as c FROM deals d ${where}`).get(...params).c;
+
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
+ ${where}
GROUP BY d.id
- ORDER BY d.deal_date DESC, ABS(d.amount) DESC
+ ORDER BY d.${safeSort} ${safeOrder}
LIMIT ? OFFSET ?
- `).all(limit, offset);
-
- const total = db.prepare('SELECT COUNT(*) as c FROM deals').get().c;
+ `).all(...params, limit, offset);
for (const deal of deals) {
deal.transactions = db.prepare(`
@@ -50,4 +67,12 @@ router.put('/:id', (req, res) => {
res.json({ success: true });
});
+// POST /api/deals/clear
+router.post("/clear", (req, res) => {
+ const db = getDB();
+ db.prepare("DELETE FROM deal_transactions").run();
+ db.prepare("DELETE FROM deals").run();
+ res.json({ success: true });
+});
+
module.exports = router;
diff --git a/server/routes/transactions.js b/server/routes/transactions.js
index 4e5b8d3..0669b0f 100644
--- a/server/routes/transactions.js
+++ b/server/routes/transactions.js
@@ -11,7 +11,7 @@ router.get("/", (req, res) => {
const {
page = 1,
- limit = 50,
+ limit = 20,
start_date,
end_date,
source_type,
@@ -74,6 +74,7 @@ router.get("/", (req, res) => {
// 安全的白名单排序
const allowedSortFields = [
+ "id",
"transaction_time",
"transaction_date",
"amount",
@@ -120,6 +121,38 @@ router.get("/needs-classify", (req, res) => {
res.json({ ids: stale.map(r => r.id), total: stale.length });
});
+// POST /api/transactions/reconcile - 全量清除后重新对账
+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();
+ const allTxs = db.prepare('SELECT id,transaction_date,transaction_time,amount,direction,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);
+ }
+ const insD=db.prepare('INSERT INTO deals(deal_date,amount,direction,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 r=insD.run(e.transaction_time||e.transaction_date,e.amount,e.direction,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-all — 重分类 deals
router.post("/classify-all", async (req, res) => {
const db = getDB();