Simplify Transactions page and remove edit functionality

This commit is contained in:
2026-05-05 21:03:09 +08:00
parent c9a4d4527d
commit 9bb4f1ca87
+61 -151
View File
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { RotateCcw, Link2, Brain, ChevronLeft, ChevronRight, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
import { getTransactions, updateTransaction, runReconciliation, classifyAll, classifyTransactions, formatAmount, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
import { getTransactions, runReconciliation, classifyTransactions, formatAmount, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
function fmtDatetime(dt) {
if (!dt) return '';
@@ -11,18 +11,17 @@ 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: '',
source_type: '', direction: '', category: '', reviewed: '', min_amount: '', keyword: '',
source_type: '', direction: '', keyword: '',
sort_by: 'transaction_time', sort_order: 'DESC'
});
const [loading, setLoading] = useState(true);
const [categories, setCategories] = useState([]);
const [editingTx, setEditingTx] = useState(null);
const [reconciling, setReconciling] = useState(false);
const [classifying, setClassifying] = useState(false);
const [classifyProgress, setClassifyProgress] = useState(0);
const [deals, setDeals] = useState(null);
// 恢复分类进度(刷新后轮询)
// 恢复分类进度
useEffect(() => {
const saved = sessionStorage.getItem('classifyTask');
if (!saved) return;
@@ -35,67 +34,44 @@ export default function Transactions() {
const { total } = await res.json();
const p = task.total > 0 ? Math.round((task.total - total) / task.total * 100) : 100;
setClassifyProgress(Math.min(Math.max(p, 0), 100));
if (total <= 0 || p >= 100) {
clearInterval(poll); setClassifying(false); setClassifyProgress(100);
sessionStorage.removeItem('classifyTask'); loadTransactions();
}
if (total <= 0 || p >= 100) { clearInterval(poll); setClassifying(false); sessionStorage.removeItem('classifyTask'); loadTransactions(); }
} catch (e) { clearInterval(poll); setClassifying(false); sessionStorage.removeItem('classifyTask'); }
}, 2000);
return () => clearInterval(poll);
}, []);
useEffect(() => { loadCategories(); }, []);
useEffect(() => { loadCategories(); loadDeals(); }, []);
useEffect(() => { loadTransactions(); }, [filters]);
async function loadCategories() {
try { setCategories(await getCategories()); } catch (err) {}
}
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 loadTransactions() {
setLoading(true);
try {
const params = {};
for (const [k, v] of Object.entries(filters)) if (v !== '' && v !== undefined) params[k] = v;
setData(await getTransactions(params));
} catch (err) {}
const p = {}; for (const [k, v] of Object.entries(filters)) if (v !== '' && v !== undefined) p[k] = v;
setData(await getTransactions(p));
} catch (e) {}
setLoading(false);
}
function updateFilter(key, value) {
setFilters(prev => ({ ...prev, [key]: value, page: key === 'page' ? value : 1 }));
}
function updateFilter(k, v) { setFilters(prev => ({ ...prev, [k]: v, page: k === 'page' ? v : 1 })); }
function toggleSort(field) {
setFilters(prev => ({
...prev, sort_by: field,
sort_order: prev.sort_by === field && prev.sort_order === 'DESC' ? 'ASC' : 'DESC', page: 1
}));
setFilters(prev => ({ ...prev, sort_by: field, sort_order: prev.sort_by === field && prev.sort_order === 'DESC' ? 'ASC' : 'DESC', page: 1 }));
}
function SortIcon({ field }) {
if (filters.sort_by !== field) return <ArrowUpDown size={12} style={{ opacity: 0.3 }} />;
return filters.sort_order === 'ASC' ? <ArrowUp size={12} /> : <ArrowDown size={12} />;
}
function Th({ field, children, style }) {
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>
);
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 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(); loadDeals(); alert(`对账完成!成功匹配 ${r.matched} 对`); loadTransactions(); } catch (err) {}
try { const r = await runReconciliation(); alert('匹配 ' + (r.matched || 0) + ' 对,生成 ' + (r.deals || 0) + ' 条关联'); loadTransactions(); loadDeals(); } catch (e) {}
setReconciling(false);
}
@@ -116,60 +92,33 @@ export default function Transactions() {
sessionStorage.setItem('classifyTask', JSON.stringify({ total, progress: pct, ts: Date.now() }));
}
sessionStorage.removeItem('classifyTask');
alert('分类完成!共重分类 ' + total + ' 笔交易');
alert('分类完成!共重分类 ' + total + ' 笔');
loadTransactions();
} catch (e) { sessionStorage.removeItem('classifyTask'); alert('分类失败: ' + (e.response?.data?.error || e.message)); }
setClassifying(false);
}
async function handleUpdateTx(id, updates) {
try { await updateTransaction(id, updates); setEditingTx(null); loadTransactions(); } catch (err) {}
}
return (
<div>
<div className="page-header">
<h2>📋 交易明细</h2>
<p>查看、筛选、排序、对账和分类所有交易记录</p>
</div>
<div className="page-header"><h2>📋 交易明细</h2><p>查看、筛选、排序、对账和分类</p></div>
<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: '', category: '',
reviewed: '', min_amount: '', keyword: '', sort_by: 'transaction_time', sort_order: 'DESC'
})}>
<RotateCcw size={16} /> 重置
</button>
</div>
<div className="card" style={{ padding: '16px 20px' }}>
<div className="filter-bar">
<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" style={{display:"none"}}><select className="form-select" value={filters.category} onChange={e => updateFilter('category', e.target.value)}>
<option value="">全部</option>{categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
</select></div>
<div className="form-group"><label>确认</label><select className="form-select" value={filters.reviewed} onChange={e => updateFilter('reviewed', e.target.value)}>
<option value="">全部</option><option value="0">未确认</option><option value="1">已确认</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>
<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>
</div>
{/* 筛选+表格 合体卡片 */}
<div className="card">
<div className="card-header">
<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>
<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>
@@ -178,50 +127,32 @@ export default function Transactions() {
<div className="loading"><div className="spinner"></div>加载中...</div>
) : data.transactions.length > 0 ? (
<>
<div className="table-container">
<table>
<thead>
<tr>
<Th field="transaction_time">日期时间</Th>
<Th field="source_type">来源</Th>
<Th field="counterparty">对方</Th>
<Th field="description">描述</Th>
<Th field="amount" style={{ textAlign: 'right' }}>金额</Th>
<Th field="direction">方向</Th>
<th>操作</th>
<div className="table-container"><table>
<thead><tr>
<Th field="transaction_time">日期时间</Th>
<Th field="source_type">来源</Th>
<Th field="counterparty">对方</Th>
<Th field="description">描述</Th>
<Th field="amount" style={{ textAlign: 'right' }}>金额</Th>
<Th field="direction">方向</Th>
</tr></thead>
<tbody>
{data.transactions.map(tx => (
<tr key={tx.id}>
<td style={{ whiteSpace: 'nowrap', fontSize: 13 }}>{fmtDatetime(tx.transaction_time) || fmtDatetime(tx.transaction_date)}</td>
<td><span className={`source-type-label source-${tx.source_type}`}>{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}</span></td>
<td>{tx.counterparty || '--'}</td>
<td style={{ maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={tx.description}>{tx.description || '--'}</td>
<td style={{ textAlign: 'right', fontWeight: 600, whiteSpace: 'nowrap' }} className={tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}>{formatAmount(tx.amount)}</td>
<td><span className={`tag ${tx.direction === 'income' ? 'tag-income' : 'tag-expense'}`}>{tx.direction === 'income' ? '收入' : '支出'}</span></td>
</tr>
</thead>
<tbody>
{data.transactions.map(tx => (
<tr key={tx.id}>
<td style={{ whiteSpace: 'nowrap', fontSize: 13 }}>
{fmtDatetime(tx.transaction_time) || fmtDatetime(tx.transaction_date)}
</td>
<td><span className={`source-type-label source-${tx.source_type}`}>{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}</span></td>
<td>{tx.counterparty || '--'}</td>
<td style={{ maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={tx.ai_description || tx.description}>
{tx.ai_description || tx.description || '--'}
</td>
<td>{tx.category ? <span className="tag tag-matched">{tx.category}</span> : <span style={{ color: 'var(--text-secondary)', fontSize: 11 }}>未分类</span>}</td>
<td style={{ textAlign: 'right', fontWeight: 600, whiteSpace: 'nowrap' }} className={tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}>
{formatAmount(tx.amount)}
</td>
<td><span className={`tag ${tx.direction === 'income' ? 'tag-income' : 'tag-expense'}`}>{tx.direction === 'income' ? '收入' : '支出'}</span></td>
<td><button className="btn btn-secondary btn-sm" onClick={() => setEditingTx({ ...tx })}>编辑</button></td>
</tr>
))}
</tbody>
</table>
</div>
))}
</tbody>
</table></div>
{data.totalPages > 1 && (
<div className="pagination">
<button disabled={data.page <= 1} onClick={() => updateFilter('page', data.page - 1)}><ChevronLeft size={14} /> 上一页</button>
{Array.from({ length: Math.min(data.totalPages, 7) }, (_, i) => {
const p = i + Math.max(1, data.page - 3);
if (p > data.totalPages) return null;
return <button key={p} className={data.page === p ? 'active' : ''} onClick={() => updateFilter('page', p)}>{p}</button>;
})}
{Array.from({ length: Math.min(data.totalPages, 7) }, (_, i) => { const p = i + Math.max(1, data.page - 3); if (p > data.totalPages) return null; return <button key={p} className={data.page === p ? 'active' : ''} onClick={() => updateFilter('page', p)}>{p}</button>; })}
<button disabled={data.page >= data.totalPages} onClick={() => updateFilter('page', data.page + 1)}>下一页 <ChevronRight size={14} /></button>
</div>
)}
@@ -231,24 +162,24 @@ export default function Transactions() {
)}
</div>
{/* 关联交易 */}
{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>🔗 关联交易(Deal)</h3><span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>共 {deals.length} 条</span></div>
<div className="table-container"><table>
<thead><tr><th>日期</th><th>金额</th><th>对方</th><th>关联明细</th></tr></thead>
<thead><tr><th>日期</th><th>金额</th><th>分类</th><th>对方</th><th>关联明细</th></tr></thead>
<tbody>
{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.counterparty || "--"}</td>
<td style={{ fontSize: 12, color: "var(--text-secondary)" }}>
{d.transactions?.map((t,i) => (
<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)' }}>
{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>
@@ -258,27 +189,6 @@ export default function Transactions() {
</table></div>
</div>
)}
{editingTx && (
<div className="modal-overlay" onClick={() => setEditingTx(null)}>
<div className="modal" onClick={e => e.stopPropagation()}>
<h3>编辑交易</h3>
<div style={{ marginBottom: 12, fontSize: 13, color: 'var(--text-secondary)' }}>
{editingTx.transaction_code} | {fmtDatetime(editingTx.transaction_time)}
</div>
<div className="form-group"><label>分类</label><select className="form-select" value={editingTx.category || ''} onChange={e => setEditingTx({ ...editingTx, category: e.target.value })}>
<option value="">选择分类</option>{categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
</select></div>
<div className="form-group"><label>描述</label><input type="text" className="form-input" value={editingTx.ai_description || ''} onChange={e => setEditingTx({ ...editingTx, ai_description: e.target.value })} /></div>
<div className="form-group"><label>确认状态</label><select className="form-select" value={editingTx.reviewed || 0} onChange={e => setEditingTx({ ...editingTx, reviewed: parseInt(e.target.value) })}>
<option value={0}>未确认</option><option value={1}>已确认</option>
</select></div>
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
<button className="btn btn-secondary" onClick={() => setEditingTx(null)}>取消</button>
<button className="btn btn-primary" onClick={() => handleUpdateTx(editingTx.id, { reviewed: editingTx.reviewed })}>保存</button>
</div>
</div>
</div>
)}
</div>
);
}