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:
@@ -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>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><sqlb_project><db path="C:/Code/Reco/data/reco.db" readonly="0" foreign_keys="1" case_sensitive_like="0" temp_store="0" wal_autocheckpoint="1000" synchronous="2"/><attached/><window><main_tabs open="query browser structure" current="0"/></window><tab_structure><column_width id="0" width="300"/><column_width id="1" width="0"/><column_width id="2" width="100"/><column_width id="3" width="8287"/><column_width id="4" width="0"/><expanded_item id="0" parent="1"/><expanded_item id="1" parent="1"/><expanded_item id="2" parent="1"/><expanded_item id="3" parent="1"/></tab_structure><tab_browse><table title="categories" custom_title="0" dock_id="2" table="4,10:maincategories"/><dock_state state="000000ff00000000fd00000001000000020000066500000449fc0100000002fb000000160064006f0063006b00420072006f00770073006500310100000000ffffffff0000000000000000fb000000160064006f0063006b00420072006f00770073006500320100000000000006650000012600ffffff000002b30000000000000004000000040000000800000008fc00000000"/><default_encoding codec=""/><browse_table_settings><table schema="main" name="categories" show_row_id="0" encoding="" plot_x_axis="" unlock_view_pk="_rowid_" freeze_columns="0"><sort/><column_widths><column index="1" value="32"/><column index="2" value="59"/><column index="3" value="300"/><column index="4" value="74"/><column index="5" value="156"/></column_widths><filter_values/><conditional_formats/><row_id_formats/><display_formats/><hidden_columns/><plot_y_axes/><global_filter/></table></browse_table_settings></tab_browse><tab_sql><sql name="SQL 1*">select * from deals␍
|
||||
select * from transactions␍
|
||||
␍
|
||||
␍
|
||||
</sql><current_tab id="0"/></tab_sql></sqlb_project>
|
||||
+31
-6
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user