Add deal management API and replace transactions with deals in Review

page
This commit is contained in:
2026-05-06 01:07:10 +08:00
parent 82412287a4
commit 4c4e740753
3 changed files with 401 additions and 95 deletions
+16
View File
@@ -60,6 +60,22 @@ export async function deleteSource(id) {
return res.data; return res.data;
} }
// Deals
export async function getDeals(params = {}) {
const res = await api.get("/deals", { params });
return res.data;
}
export async function updateDeal(id, data) {
const res = await api.put(`/deals/${id}`, data);
return res.data;
}
export async function batchConfirmDeals(ids) {
const res = await api.post("/deals/batch-confirm", { ids });
return res.data;
}
// Transactions // Transactions
export async function getTransactions(params = {}) { export async function getTransactions(params = {}) {
const res = await api.get("/transactions", { params }); const res = await api.get("/transactions", { params });
+356 -95
View File
@@ -1,19 +1,31 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useCallback } from "react";
import { CheckCircle, X, Edit3, Brain, Search, Filter } from 'lucide-react'; import { CheckCircle, X, Edit3, ChevronDown, ChevronRight } from "lucide-react";
import { getTransactions, updateTransaction, formatAmount, formatDate, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi'; import {
getDeals,
updateDeal,
batchConfirmDeals,
formatAmount,
formatDate,
SOURCE_TYPE_MAP,
getCategories,
} from "../hooks/useApi";
export default function Review() { export default function Review() {
const [transactions, setTransactions] = useState([]); const [deals, setDeals] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [categories, setCategories] = useState([]); const [categories, setCategories] = useState([]);
const [editingTx, setEditingTx] = useState(null); const [editingDeal, setEditingDeal] = useState(null);
const [showReviewed, setShowReviewed] = useState(false); const [showReviewed, setShowReviewed] = useState(false);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState("");
const [expandedDeals, setExpandedDeals] = useState(new Set());
useEffect(() => { useEffect(() => {
loadCategories(); loadCategories();
loadReviewTransactions(); }, []);
useEffect(() => {
loadReviewDeals();
}, [showReviewed, keyword]); }, [showReviewed, keyword]);
async function loadCategories() { async function loadCategories() {
@@ -23,177 +35,399 @@ export default function Review() {
} catch (err) {} } catch (err) {}
} }
async function loadReviewTransactions() { async function loadReviewDeals() {
setLoading(true); setLoading(true);
try { try {
const params = { const params = {
min_amount: 100, // Only >= 100 RMB min_amount: 100,
limit: 200, limit: 200,
sort_by: 'amount', sort_by: "amount",
sort_order: 'DESC' sort_order: "DESC",
}; };
if (!showReviewed) params.reviewed = 0; if (!showReviewed) params.reviewed = 0;
if (keyword) params.keyword = keyword; if (keyword) params.keyword = keyword;
const result = await getTransactions(params); const result = await getDeals(params);
setTransactions(result.transactions); setDeals(result.deals);
setTotal(result.total); setTotal(result.total);
// Update badge count in sidebar // Update badge count in sidebar
try { try {
const badge = document.getElementById('review-badge'); const badge = document.getElementById("review-badge");
if (badge) { if (badge) {
// Get fresh unreviewed count if (!showReviewed) {
const { getOverview } = require('../hooks/useApi'); badge.textContent = result.total;
// Just use local count } else {
if (!showReviewed) badge.textContent = result.total; // When showing reviewed, fetch unreviewed count for badge
const unreviewed = await getDeals({
min_amount: 100,
reviewed: 0,
limit: 1,
});
badge.textContent = unreviewed.total;
}
} }
} catch (e) {} } catch (e) {}
} catch (err) {} } catch (err) {}
setLoading(false); setLoading(false);
} }
async function handleConfirm(tx) { async function handleConfirm(deal) {
try { try {
await updateTransaction(tx.id, { reviewed: 1 }); await updateDeal(deal.id, { reviewed: 1 });
loadReviewTransactions(); loadReviewDeals();
} catch (err) {} } catch (err) {}
} }
async function handleUpdateTx(id, updates) { async function handleUpdateDeal(id, updates) {
try { try {
await updateTransaction(id, updates); await updateDeal(id, updates);
setEditingTx(null); setEditingDeal(null);
loadReviewTransactions(); loadReviewDeals();
} catch (err) {} } catch (err) {}
} }
async function handleConfirmAll() { async function handleConfirmAll() {
if (!window.confirm(`确定要批量确认当前显示的 ${transactions.length} 笔交易吗?`)) return; const unreviewed = deals.filter((d) => !d.reviewed);
for (const tx of transactions) { if (unreviewed.length === 0) return;
if (!tx.reviewed) { if (
try { await updateTransaction(tx.id, { reviewed: 1 }); } catch (err) {} !window.confirm(
} `确定要批量确认当前显示的 ${unreviewed.length} 笔交易吗?`,
} )
loadReviewTransactions(); )
return;
try {
await batchConfirmDeals(unreviewed.map((d) => d.id));
loadReviewDeals();
} catch (err) {}
}
function toggleExpand(dealId) {
setExpandedDeals((prev) => {
const next = new Set(prev);
if (next.has(dealId)) next.delete(dealId);
else next.add(dealId);
return next;
});
} }
return ( return (
<div> <div>
<div className="page-header"> <div className="page-header">
<h2>🔍 大额交易确认</h2> <h2>🔍 大额交易确认</h2>
<p>逐笔确认 ≥100 元的交易,核对AI分类和描述是否正确</p> <p>逐笔确认 ≥100 元的 Deal(关联交易组),核对AI分类和描述是否正确</p>
</div> </div>
{/* Toolbar */} {/* Toolbar */}
<div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap', alignItems: 'center' }}> <div
style={{
display: "flex",
gap: 10,
marginBottom: 20,
flexWrap: "wrap",
alignItems: "center",
}}
>
<div className="form-group" style={{ marginBottom: 0, minWidth: 200 }}> <div className="form-group" style={{ marginBottom: 0, minWidth: 200 }}>
<input <input
type="text" type="text"
className="form-input" className="form-input"
placeholder="🔍 搜索对方/描述..." placeholder="🔍 搜索对方/描述..."
value={keyword} value={keyword}
onChange={e => setKeyword(e.target.value)} onChange={(e) => setKeyword(e.target.value)}
/> />
</div> </div>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 14 }}> <label
<input type="checkbox" checked={showReviewed} onChange={e => setShowReviewed(e.target.checked)} /> style={{
display: "flex",
alignItems: "center",
gap: 6,
cursor: "pointer",
fontSize: 14,
}}
>
<input
type="checkbox"
checked={showReviewed}
onChange={(e) => setShowReviewed(e.target.checked)}
/>
显示已确认 显示已确认
</label> </label>
<div style={{ flex: 1 }} /> <div style={{ flex: 1 }} />
<span style={{ fontSize: 14, color: 'var(--text-secondary)' }}> <span style={{ fontSize: 14, color: "var(--text-secondary)" }}>
共 <strong>{total}</strong> 笔大额交易 共 <strong>{total}</strong> 笔大额 Deal
{!showReviewed && <span style={{ color: 'var(--warning)' }}>(待确认)</span>} {!showReviewed && (
<span style={{ color: "var(--warning)" }}>(待确认)</span>
)}
</span> </span>
<button className="btn btn-success btn-sm" onClick={handleConfirmAll}> {!showReviewed && (
<CheckCircle size={14} /> 全部确认 <button className="btn btn-success btn-sm" onClick={handleConfirmAll}>
</button> <CheckCircle size={14} /> 全部确认
</button>
)}
</div> </div>
{/* Review List */} {/* Review List */}
<div className="card"> <div className="card">
{loading ? ( {loading ? (
<div className="loading"><div className="spinner"></div>加载中...</div> <div className="loading">
) : transactions.length > 0 ? ( <div className="spinner"></div>加载中...
</div>
) : deals.length > 0 ? (
<div> <div>
{transactions.map(tx => ( {deals.map((deal) => (
<div key={tx.id} className={`review-item ${tx.reviewed ? 'reviewed' : ''}`}> <div
<div className={`amount-col ${tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}`}> key={deal.id}
{formatAmount(tx.amount)} className={`review-item ${deal.reviewed ? "reviewed" : ""}`}
>
<div
className={`amount-col ${deal.direction === "income" ? "stat-value income" : "stat-value expense"}`}
>
{formatAmount(deal.amount)}
</div> </div>
<div className="info-col"> <div className="info-col">
<div className="title"> <div className="title">
{tx.ai_description || tx.description || '无描述'} {deal.ai_description || deal.description || "无描述"}
</div> </div>
<div className="meta"> <div className="meta">
{formatDate(tx.transaction_date)} · {formatDate(deal.deal_date)} ·
<span className={`source-type-label source-${tx.source_type}`} style={{ marginLeft: 4 }}> {deal.counterparty && <span> {deal.counterparty} ·</span>}
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type} {deal.category && (
</span> <span
{tx.counterparty && <span> · {tx.counterparty}</span>} className="tag tag-matched"
{tx.category && ( style={{ marginLeft: 4 }}
<span className="tag tag-matched" style={{ marginLeft: 6 }}>{tx.category}</span> >
{deal.category}
</span>
)} )}
{tx.reviewed && <span style={{ marginLeft: 6, color: 'var(--success)' }}>✓ 已确认</span>} {deal.reviewed && (
{tx.matched_transaction_id && ( <span style={{ marginLeft: 6, color: "var(--success)" }}>
<span className="tag tag-matched" style={{ marginLeft: 6 }}>已对账</span> ✓ 已确认
</span>
)}
{deal.match_count > 1 && (
<span
className="tag tag-transfer"
style={{ marginLeft: 6 }}
>
关联×{deal.match_count}
</span>
)} )}
</div> </div>
</div> </div>
<div className="action-col"> <div className="action-col">
<button className="btn btn-secondary btn-sm" onClick={() => setEditingTx({ ...tx })}> {deal.transactions && deal.transactions.length > 0 && (
<button
className="btn btn-secondary btn-sm"
onClick={() => toggleExpand(deal.id)}
title="查看关联明细"
>
{expandedDeals.has(deal.id) ? (
<ChevronDown size={12} />
) : (
<ChevronRight size={12} />
)}{" "}
{deal.transactions.length}笔
</button>
)}
<button
className="btn btn-secondary btn-sm"
onClick={() => setEditingDeal({ ...deal })}
>
<Edit3 size={12} /> 编辑 <Edit3 size={12} /> 编辑
</button> </button>
{!tx.reviewed && ( {!deal.reviewed && (
<button className="btn btn-success btn-sm" onClick={() => handleConfirm(tx)}> <button
className="btn btn-success btn-sm"
onClick={() => handleConfirm(deal)}
>
<CheckCircle size={12} /> 确认 <CheckCircle size={12} /> 确认
</button> </button>
)} )}
</div> </div>
{/* Expanded transactions detail */}
{expandedDeals.has(deal.id) && deal.transactions && (
<div
style={{
width: "100%",
marginTop: 8,
padding: "10px 0 0",
borderTop: "1px dashed var(--border)",
}}
>
{deal.transactions.map((tx, i) => (
<div
key={i}
style={{
display: "flex",
gap: 12,
alignItems: "center",
padding: "6px 0",
fontSize: 12,
color: "var(--text-secondary)",
}}
>
<span
className={`source-type-label source-${tx.source_type}`}
style={{ minWidth: 64, textAlign: "center" }}
>
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}
</span>
<span style={{ flex: 1 }}>
{tx.description || "无描述"}
</span>
<span
style={{
fontWeight: 600,
color:
tx.direction === "income"
? "var(--success)"
: "var(--danger)",
}}
>
{formatAmount(tx.amount)}
</span>
<span style={{ fontSize: 11 }}>
{formatDate(tx.transaction_date)}
</span>
</div>
))}
</div>
)}
</div> </div>
))} ))}
</div> </div>
) : ( ) : (
<div className="empty-state"> <div className="empty-state">
<div className="icon">✅</div> <div className="icon">✅</div>
<p>{showReviewed ? '没有已确认的大额交易' : '所有大额交易已确认!'}</p> <p>
{showReviewed
? "没有已确认的大额 Deal"
: "所有大额 Deal 已确认!"}
</p>
<p style={{ fontSize: 13, marginTop: 8 }}> <p style={{ fontSize: 13, marginTop: 8 }}>
{showReviewed ? '尝试切换显示模式' : '可以去交易明细页面查看所有记录'} {showReviewed
? "尝试切换显示模式"
: "可以去交易明细页面查看所有记录"}
</p> </p>
</div> </div>
)} )}
</div> </div>
{/* Edit Modal */} {/* Edit Modal */}
{editingTx && ( {editingDeal && (
<div className="modal-overlay" onClick={() => setEditingTx(null)}> <div className="modal-overlay" onClick={() => setEditingDeal(null)}>
<div className="modal" onClick={e => e.stopPropagation()}> <div className="modal" onClick={(e) => e.stopPropagation()}>
<h3>编辑交易分类与描述</h3> <h3>编辑 Deal 分类与描述</h3>
<div style={{ <div
marginBottom: 16, padding: 12, background: 'var(--bg)', style={{
borderRadius: 8, fontSize: 13 marginBottom: 16,
}}> padding: 12,
background: "var(--bg)",
borderRadius: 8,
fontSize: 13,
}}
>
<div style={{ fontWeight: 600, marginBottom: 4 }}> <div style={{ fontWeight: 600, marginBottom: 4 }}>
{formatAmount(editingTx.amount)} · {formatDate(editingTx.transaction_date)} {formatAmount(editingDeal.amount)} ·{" "}
{formatDate(editingDeal.deal_date)}
</div> </div>
<div style={{ color: 'var(--text-secondary)' }}> <div style={{ color: "var(--text-secondary)" }}>
{editingTx.counterparty} · {editingTx.description} {editingDeal.counterparty} ·{" "}
</div> {editingDeal.description || "无描述"}
<div style={{ fontFamily: 'monospace', fontSize: 11, color: 'var(--text-secondary)', marginTop: 4 }}>
编码: {editingTx.transaction_code}
</div> </div>
{editingDeal.match_count > 1 && (
<div
style={{
fontSize: 11,
color: "var(--primary)",
marginTop: 2,
}}
>
关联 {editingDeal.match_count} 笔原始交易
</div>
)}
</div> </div>
{/* Show associated transactions in modal */}
{editingDeal.transactions &&
editingDeal.transactions.length > 0 && (
<div
style={{
marginBottom: 16,
padding: 10,
background: "var(--bg)",
borderRadius: 6,
fontSize: 12,
maxHeight: 120,
overflowY: "auto",
}}
>
<div
style={{
fontWeight: 600,
marginBottom: 6,
color: "var(--text-secondary)",
fontSize: 11,
}}
>
关联原始交易明细:
</div>
{editingDeal.transactions.map((tx, i) => (
<div
key={i}
style={{
display: "flex",
gap: 8,
alignItems: "center",
padding: "3px 0",
fontSize: 11,
color: "var(--text-secondary)",
}}
>
<span
className={`source-type-label source-${tx.source_type}`}
>
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}
</span>
<span style={{ flex: 1 }}>
{tx.description || "无描述"} ·{" "}
{tx.counterparty || "未知"}
</span>
<span
style={{
fontWeight: 500,
color:
tx.direction === "income"
? "var(--success)"
: "var(--danger)",
}}
>
{formatAmount(tx.amount)}
</span>
</div>
))}
</div>
)}
<div className="form-group"> <div className="form-group">
<label>分类</label> <label>分类</label>
<select className="form-select" value={editingTx.category || ''} <select
onChange={e => setEditingTx({ ...editingTx, category: e.target.value })}> className="form-select"
value={editingDeal.category || ""}
onChange={(e) =>
setEditingDeal({ ...editingDeal, category: e.target.value })
}
>
<option value="">选择分类</option> <option value="">选择分类</option>
{categories.map(c => ( {categories.map((c) => (
<option key={c.id} value={c.name}>{c.name}</option> <option key={c.id} value={c.name}>
{c.name}
</option>
))} ))}
</select> </select>
</div> </div>
@@ -203,8 +437,13 @@ export default function Review() {
<input <input
type="text" type="text"
className="form-input" className="form-input"
value={editingTx.ai_description || ''} value={editingDeal.ai_description || ""}
onChange={e => setEditingTx({ ...editingTx, ai_description: e.target.value })} onChange={(e) =>
setEditingDeal({
...editingDeal,
ai_description: e.target.value,
})
}
placeholder="简要描述这笔交易..." placeholder="简要描述这笔交易..."
/> />
</div> </div>
@@ -214,20 +453,42 @@ export default function Review() {
<input <input
type="text" type="text"
className="form-input" className="form-input"
value={editingTx.review_notes || ''} value={editingDeal.review_notes || ""}
onChange={e => setEditingTx({ ...editingTx, review_notes: e.target.value })} onChange={(e) =>
setEditingDeal({
...editingDeal,
review_notes: e.target.value,
})
}
placeholder="人工备注(可选)" placeholder="人工备注(可选)"
/> />
</div> </div>
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}> <div
<button className="btn btn-secondary" onClick={() => setEditingTx(null)}>取消</button> style={{
<button className="btn btn-primary" onClick={() => handleUpdateTx(editingTx.id, { display: "flex",
category: editingTx.category, gap: 10,
ai_description: editingTx.ai_description, justifyContent: "flex-end",
review_notes: editingTx.review_notes, marginTop: 20,
reviewed: 1 }}
})}> >
<button
className="btn btn-secondary"
onClick={() => setEditingDeal(null)}
>
取消
</button>
<button
className="btn btn-primary"
onClick={() =>
handleUpdateDeal(editingDeal.id, {
category: editingDeal.category,
ai_description: editingDeal.ai_description,
review_notes: editingDeal.review_notes,
reviewed: 1,
})
}
>
保存并确认 保存并确认
</button> </button>
</div> </div>
+29
View File
@@ -13,6 +13,9 @@ router.get("/", (req, res) => {
category, category,
direction, direction,
keyword, keyword,
min_amount,
max_amount,
reviewed,
sort_by = "deal_date", sort_by = "deal_date",
sort_order = "DESC", sort_order = "DESC",
} = req.query; } = req.query;
@@ -42,6 +45,18 @@ router.get("/", (req, res) => {
); );
params.push("%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%"); params.push("%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%");
} }
if (min_amount) {
conditions.push("ABS(d.amount) >= ?");
params.push(parseFloat(min_amount));
}
if (max_amount) {
conditions.push("ABS(d.amount) <= ?");
params.push(parseFloat(max_amount));
}
if (reviewed !== undefined) {
conditions.push("d.reviewed = ?");
params.push(parseInt(reviewed));
}
const where = conditions.length ? "WHERE " + conditions.join(" AND ") : ""; const where = conditions.length ? "WHERE " + conditions.join(" AND ") : "";
const allowedSort = [ const allowedSort = [
@@ -141,6 +156,20 @@ router.put("/:id", (req, res) => {
res.json({ success: true }); res.json({ success: true });
}); });
// POST /api/deals/batch-confirm — 批量确认大额交易
router.post("/batch-confirm", (req, res) => {
const db = getDB();
const { ids } = req.body;
if (!ids || !Array.isArray(ids) || ids.length === 0) {
return res.status(400).json({ error: "请提供交易ID列表" });
}
const ph = ids.map(() => "?").join(",");
db.prepare(
`UPDATE deals SET reviewed=1, reviewed_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id IN (${ph})`,
).run(...ids);
res.json({ success: true, confirmed: ids.length });
});
// POST /api/deals/clear // POST /api/deals/clear
router.post("/clear", (req, res) => { router.post("/clear", (req, res) => {
const db = getDB(); const db = getDB();