Add filtering, sorting and pagination to deals page

Add filtering, sorting, and pagination to deals page

Replace alert calls with toast notifications and add a clear deals
button with confirmation dialog
This commit is contained in:
2026-05-05 21:59:45 +08:00
parent 9bb4f1ca87
commit e23598e2e4
4 changed files with 158 additions and 39 deletions
+88 -32
View File
@@ -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 <ArrowUpDown size={12} style={{ opacity: 0.3 }} />; return dealFilters.sort_order === "ASC" ? <ArrowUp size={12} /> : <ArrowDown size={12} />; }
function DealTh({ field, children, style }) { return <th onClick={() => dealToggleSort(field)} style={{ cursor: "pointer", userSelect: "none", ...style }}><span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>{children}<DealSortIcon field={field} /></span></th>; }
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 <th onClick={() => toggleSort(field)} style={{ cursor: 'pointer', userSelect: 'none', ...style }}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>{children}<SortIcon field={field} /></span></th>;
}
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() {
<div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' }}>
<button className="btn btn-primary" onClick={handleReconcile} disabled={reconciling}><Link2 size={16} /> {reconciling ? '对账中...' : '自动对账'}</button>
<button className="btn btn-secondary" onClick={handleClassifyAll} disabled={classifying}><Brain size={16} /> {classifying ? `分类中 ${classifyProgress}%` : 'AI 分类全部'}</button>
<button className="btn btn-secondary" onClick={() => setFilters({ page: 1, limit: 50, start_date: '', end_date: '', source_type: '', direction: '', keyword: '', sort_by: 'transaction_time', sort_order: 'DESC' })}><RotateCcw size={16} /> 重置</button>
<button className="btn btn-danger" onClick={() => setClearConfirm(true)} style={{ marginLeft: "auto" }}>清空关联</button>
<button className="btn btn-secondary" onClick={() => setFilters({ page: 1, limit: 20, start_date: '', end_date: '', source_type: '', direction: '', keyword: '', sort_by: 'transaction_time', sort_order: 'DESC' })}><RotateCcw size={16} /> 重置</button>
</div>
{/* 筛选+表格 合体卡片 */}
<div className="card">
<div className="filter-bar" style={{ padding: '0 20px', marginBottom: 12 }}>
<div className="form-group"><label>开始</label><input type="date" className="form-input" value={filters.start_date} onChange={e => updateFilter('start_date', e.target.value)} /></div>
<div className="form-group"><label>结束</label><input type="date" className="form-input" value={filters.end_date} onChange={e => updateFilter('end_date', e.target.value)} /></div>
<div className="form-group"><label>来源</label><select className="form-select" value={filters.source_type} onChange={e => updateFilter('source_type', e.target.value)}><option value="">全部</option>{Object.entries(SOURCE_TYPE_MAP).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></div>
<div className="form-group"><label>方向</label><select className="form-select" value={filters.direction} onChange={e => updateFilter('direction', e.target.value)}><option value="">全部</option><option value="income">收入</option><option value="expense">支出</option></select></div>
<div className="form-group"><label>搜索</label><input type="text" className="form-input" placeholder="对方/描述..." value={filters.keyword} onChange={e => updateFilter('keyword', e.target.value)} /></div>
<div className="card-header">
<h3>交易记录</h3>
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}>共 {data.total} 笔,第 {data.page}/{data.totalPages} 页</span>
</div>
<div className="card-header" style={{ paddingTop: 0 }}>
<h3>共 {data.total} 笔交易</h3>
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>第 {data.page}/{data.totalPages} 页 · 点击列头排序</span>
<div className="filter-bar" style={{ padding: "0 20px 12px" }}>
<div className="form-group"><label>开始</label><input type="date" className="form-input" value={filters.start_date} onChange={e => updateFilter("start_date", e.target.value)} /></div>
<div className="form-group"><label>结束</label><input type="date" className="form-input" value={filters.end_date} onChange={e => updateFilter("end_date", e.target.value)} /></div>
<div className="form-group"><label>来源</label><select className="form-select" value={filters.source_type} onChange={e => updateFilter("source_type", e.target.value)}><option value="">全部</option>{Object.entries(SOURCE_TYPE_MAP).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></div>
<div className="form-group"><label>方向</label><select className="form-select" value={filters.direction} onChange={e => updateFilter("direction", e.target.value)}><option value="">全部</option><option value="income">收入</option><option value="expense">支出</option></select></div>
<div className="form-group"><label>搜索</label><input type="text" className="form-input" placeholder="对方/描述..." value={filters.keyword} onChange={e => updateFilter("keyword", e.target.value)} /></div>
</div>
{loading ? (
@@ -163,23 +177,36 @@ export default function Transactions() {
</div>
{/* 关联交易 */}
{deals && deals.length > 0 && (
{deals.deals && deals.deals.length > 0 && (
<div className="card" style={{ marginTop: 20 }}>
<div className="card-header"><h3>🔗 关联交易(Deal)</h3><span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>共 {deals.length} 条</span></div>
<div className="card-header">
<h3>关联交易</h3>
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}>共 {deals.total} 条,第 {deals.page}/{deals.totalPages} 页</span>
</div>
<div className="filter-bar" style={{ padding: "0 20px 12px" }}>
<div className="form-group"><label>搜索</label><input type="text" className="form-input" placeholder="对方/描述..." value={dealFilters.keyword} onChange={e => setDealFilters(p => ({ ...p, keyword: e.target.value, page: 1 }))} /></div>
<div className="form-group"><label>分类</label><select className="form-select" value={dealFilters.category || ""} onChange={e => setDealFilters(p => ({ ...p, category: e.target.value, page: 1 }))}><option value="">全部</option>{categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}</select></div>
</div>
<div className="table-container"><table>
<thead><tr><th>日期</th><th>金额</th><th>分类</th><th>对方</th><th>关联明细</th></tr></thead>
<thead><tr>
<th onClick={() => dealToggleSort("deal_date")} style={{ cursor: "pointer", userSelect: "none" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>日期{dealFilters.sort_by === "deal_date" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""}</span></th>
<th onClick={() => dealToggleSort("amount")} style={{ cursor: "pointer", userSelect: "none", textAlign: "right" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>金额{dealFilters.sort_by === "amount" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""}</span></th>
<th onClick={() => dealToggleSort("category")} style={{ cursor: "pointer", userSelect: "none" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>分类{dealFilters.sort_by === "category" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""}</span></th>
<th onClick={() => dealToggleSort("counterparty")} style={{ cursor: "pointer", userSelect: "none" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>对方{dealFilters.sort_by === "counterparty" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""}</span></th>
<th>关联明细</th>
</tr></thead>
<tbody>
{deals.map(d => (
{deals.deals.map(d => (
<tr key={d.id}>
<td style={{ whiteSpace: 'nowrap', fontSize: 13 }}>{d.deal_date}</td>
<td style={{ fontWeight: 600, whiteSpace: 'nowrap' }} className={parseFloat(d.amount) >= 0 ? 'stat-value income' : 'stat-value expense'}>{formatAmount(d.amount)}</td>
<td>{d.category || <span style={{ color: 'var(--text-secondary)', fontSize: 11 }}>未分类</span>}</td>
<td>{d.counterparty || '--'}</td>
<td style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
<td style={{ whiteSpace: "nowrap", fontSize: 13 }}>{d.deal_date}</td>
<td style={{ fontWeight: 600, whiteSpace: "nowrap", textAlign: "right" }} className={parseFloat(d.amount) >= 0 ? "stat-value income" : "stat-value expense"}>{formatAmount(d.amount)}</td>
<td>{d.category || <span style={{ color: "var(--text-secondary)", fontSize: 11 }}>未分类</span>}</td>
<td>{d.counterparty || "--"}</td>
<td style={{ fontSize: 12, color: "var(--text-secondary)" }}>
{d.transactions?.map((t, i) => (
<span key={i} style={{ marginRight: 8 }}>
<span className={'source-type-label source-' + t.source_type}>{SOURCE_TYPE_MAP[t.source_type]}</span>
{' '}{t.description?.substring(0, 20)}
<span className={"source-type-label source-" + t.source_type}>{SOURCE_TYPE_MAP[t.source_type]}</span>
{" "}{t.description?.substring(0, 20)}
</span>
))}
</td>
@@ -187,6 +214,35 @@ export default function Transactions() {
))}
</tbody>
</table></div>
{deals.totalPages > 1 && (
<div className="pagination">
<button disabled={deals.page <= 1} onClick={() => setDealFilters(p => ({ ...p, page: p.page - 1 }))}><ChevronLeft size={14} /> 上一页</button>
{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 <button key={pg} className={deals.page === pg ? "active" : ""} onClick={() => setDealFilters(p => ({ ...p, page: pg }))}>{pg}</button>; })}
<button disabled={deals.page >= deals.totalPages} onClick={() => setDealFilters(p => ({ ...p, page: p.page + 1 }))}>下一页 <ChevronRight size={14} /></button>
</div>
)}
</div>
)}
{clearConfirm && (
<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 }}>确定要清空所有 Deal 关联记录吗?此操作不可撤销。</p>
<div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
<button className="btn btn-secondary" onClick={() => setClearConfirm(false)}>取消</button>
<button className="btn btn-danger" onClick={handleClearDeals}>确认清空</button>
</div>
</div>
</div>
)}
{toast && (
<div style={{ position: "fixed", top: 24, right: 24, zIndex: 3000, padding: "14px 20px", borderRadius: 10, background: toast.type === "success" ? "#10b981" : toast.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 }}>
{toast.type === "success" ? <CheckCircle size={18} /> : toast.type === "error" ? <AlertCircle size={18} /> : <CheckCircle size={18} />}
<span style={{ flex: 1 }}>{toast.message}</span>
<button onClick={() => setToast(null)} style={{ background: "none", border: "none", color: "#fff", cursor: "pointer", opacity: 0.7 }}><X size={16} /></button>
</div>
)}
</div>