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;
}
// 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
export async function getTransactions(params = {}) {
const res = await api.get("/transactions", { params });
+356 -95
View File
@@ -1,19 +1,31 @@
import React, { useState, useEffect } from 'react';
import { CheckCircle, X, Edit3, Brain, Search, Filter } from 'lucide-react';
import { getTransactions, updateTransaction, formatAmount, formatDate, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
import React, { useState, useEffect, useCallback } from "react";
import { CheckCircle, X, Edit3, ChevronDown, ChevronRight } from "lucide-react";
import {
getDeals,
updateDeal,
batchConfirmDeals,
formatAmount,
formatDate,
SOURCE_TYPE_MAP,
getCategories,
} from "../hooks/useApi";
export default function Review() {
const [transactions, setTransactions] = useState([]);
const [deals, setDeals] = useState([]);
const [loading, setLoading] = useState(true);
const [total, setTotal] = useState(0);
const [categories, setCategories] = useState([]);
const [editingTx, setEditingTx] = useState(null);
const [editingDeal, setEditingDeal] = useState(null);
const [showReviewed, setShowReviewed] = useState(false);
const [keyword, setKeyword] = useState('');
const [keyword, setKeyword] = useState("");
const [expandedDeals, setExpandedDeals] = useState(new Set());
useEffect(() => {
loadCategories();
loadReviewTransactions();
}, []);
useEffect(() => {
loadReviewDeals();
}, [showReviewed, keyword]);
async function loadCategories() {
@@ -23,177 +35,399 @@ export default function Review() {
} catch (err) {}
}
async function loadReviewTransactions() {
async function loadReviewDeals() {
setLoading(true);
try {
const params = {
min_amount: 100, // Only >= 100 RMB
min_amount: 100,
limit: 200,
sort_by: 'amount',
sort_order: 'DESC'
sort_by: "amount",
sort_order: "DESC",
};
if (!showReviewed) params.reviewed = 0;
if (keyword) params.keyword = keyword;
const result = await getTransactions(params);
setTransactions(result.transactions);
const result = await getDeals(params);
setDeals(result.deals);
setTotal(result.total);
// Update badge count in sidebar
try {
const badge = document.getElementById('review-badge');
const badge = document.getElementById("review-badge");
if (badge) {
// Get fresh unreviewed count
const { getOverview } = require('../hooks/useApi');
// Just use local count
if (!showReviewed) badge.textContent = result.total;
if (!showReviewed) {
badge.textContent = result.total;
} else {
// 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 (err) {}
setLoading(false);
}
async function handleConfirm(tx) {
async function handleConfirm(deal) {
try {
await updateTransaction(tx.id, { reviewed: 1 });
loadReviewTransactions();
await updateDeal(deal.id, { reviewed: 1 });
loadReviewDeals();
} catch (err) {}
}
async function handleUpdateTx(id, updates) {
async function handleUpdateDeal(id, updates) {
try {
await updateTransaction(id, updates);
setEditingTx(null);
loadReviewTransactions();
await updateDeal(id, updates);
setEditingDeal(null);
loadReviewDeals();
} catch (err) {}
}
async function handleConfirmAll() {
if (!window.confirm(`确定要批量确认当前显示的 ${transactions.length} 笔交易吗?`)) return;
for (const tx of transactions) {
if (!tx.reviewed) {
try { await updateTransaction(tx.id, { reviewed: 1 }); } catch (err) {}
}
}
loadReviewTransactions();
const unreviewed = deals.filter((d) => !d.reviewed);
if (unreviewed.length === 0) return;
if (
!window.confirm(
`确定要批量确认当前显示的 ${unreviewed.length} 笔交易吗?`,
)
)
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 (
<div>
<div className="page-header">
<h2>🔍 大额交易确认</h2>
<p>逐笔确认 ≥100 元的交易,核对AI分类和描述是否正确</p>
<p>逐笔确认 ≥100 元的 Deal(关联交易组),核对AI分类和描述是否正确</p>
</div>
{/* 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 }}>
<input
type="text"
className="form-input"
placeholder="🔍 搜索对方/描述..."
value={keyword}
onChange={e => setKeyword(e.target.value)}
onChange={(e) => setKeyword(e.target.value)}
/>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 14 }}>
<input type="checkbox" checked={showReviewed} onChange={e => setShowReviewed(e.target.checked)} />
<label
style={{
display: "flex",
alignItems: "center",
gap: 6,
cursor: "pointer",
fontSize: 14,
}}
>
<input
type="checkbox"
checked={showReviewed}
onChange={(e) => setShowReviewed(e.target.checked)}
/>
显示已确认
</label>
<div style={{ flex: 1 }} />
<span style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
共 <strong>{total}</strong> 笔大额交易
{!showReviewed && <span style={{ color: 'var(--warning)' }}>(待确认)</span>}
<span style={{ fontSize: 14, color: "var(--text-secondary)" }}>
共 <strong>{total}</strong> 笔大额 Deal
{!showReviewed && (
<span style={{ color: "var(--warning)" }}>(待确认)</span>
)}
</span>
<button className="btn btn-success btn-sm" onClick={handleConfirmAll}>
<CheckCircle size={14} /> 全部确认
</button>
{!showReviewed && (
<button className="btn btn-success btn-sm" onClick={handleConfirmAll}>
<CheckCircle size={14} /> 全部确认
</button>
)}
</div>
{/* Review List */}
<div className="card">
{loading ? (
<div className="loading"><div className="spinner"></div>加载中...</div>
) : transactions.length > 0 ? (
<div className="loading">
<div className="spinner"></div>加载中...
</div>
) : deals.length > 0 ? (
<div>
{transactions.map(tx => (
<div key={tx.id} className={`review-item ${tx.reviewed ? 'reviewed' : ''}`}>
<div className={`amount-col ${tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}`}>
{formatAmount(tx.amount)}
{deals.map((deal) => (
<div
key={deal.id}
className={`review-item ${deal.reviewed ? "reviewed" : ""}`}
>
<div
className={`amount-col ${deal.direction === "income" ? "stat-value income" : "stat-value expense"}`}
>
{formatAmount(deal.amount)}
</div>
<div className="info-col">
<div className="title">
{tx.ai_description || tx.description || '无描述'}
{deal.ai_description || deal.description || "无描述"}
</div>
<div className="meta">
{formatDate(tx.transaction_date)} ·
<span className={`source-type-label source-${tx.source_type}`} style={{ marginLeft: 4 }}>
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}
</span>
{tx.counterparty && <span> · {tx.counterparty}</span>}
{tx.category && (
<span className="tag tag-matched" style={{ marginLeft: 6 }}>{tx.category}</span>
{formatDate(deal.deal_date)} ·
{deal.counterparty && <span> {deal.counterparty} ·</span>}
{deal.category && (
<span
className="tag tag-matched"
style={{ marginLeft: 4 }}
>
{deal.category}
</span>
)}
{tx.reviewed && <span style={{ marginLeft: 6, color: 'var(--success)' }}>✓ 已确认</span>}
{tx.matched_transaction_id && (
<span className="tag tag-matched" style={{ marginLeft: 6 }}>已对账</span>
{deal.reviewed && (
<span style={{ marginLeft: 6, color: "var(--success)" }}>
✓ 已确认
</span>
)}
{deal.match_count > 1 && (
<span
className="tag tag-transfer"
style={{ marginLeft: 6 }}
>
关联×{deal.match_count}
</span>
)}
</div>
</div>
<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} /> 编辑
</button>
{!tx.reviewed && (
<button className="btn btn-success btn-sm" onClick={() => handleConfirm(tx)}>
{!deal.reviewed && (
<button
className="btn btn-success btn-sm"
onClick={() => handleConfirm(deal)}
>
<CheckCircle size={12} /> 确认
</button>
)}
</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 className="empty-state">
<div className="icon">✅</div>
<p>{showReviewed ? '没有已确认的大额交易' : '所有大额交易已确认!'}</p>
<p>
{showReviewed
? "没有已确认的大额 Deal"
: "所有大额 Deal 已确认!"}
</p>
<p style={{ fontSize: 13, marginTop: 8 }}>
{showReviewed ? '尝试切换显示模式' : '可以去交易明细页面查看所有记录'}
{showReviewed
? "尝试切换显示模式"
: "可以去交易明细页面查看所有记录"}
</p>
</div>
)}
</div>
{/* Edit Modal */}
{editingTx && (
<div className="modal-overlay" onClick={() => setEditingTx(null)}>
<div className="modal" onClick={e => e.stopPropagation()}>
<h3>编辑交易分类与描述</h3>
{editingDeal && (
<div className="modal-overlay" onClick={() => setEditingDeal(null)}>
<div className="modal" onClick={(e) => e.stopPropagation()}>
<h3>编辑 Deal 分类与描述</h3>
<div style={{
marginBottom: 16, padding: 12, background: 'var(--bg)',
borderRadius: 8, fontSize: 13
}}>
<div
style={{
marginBottom: 16,
padding: 12,
background: "var(--bg)",
borderRadius: 8,
fontSize: 13,
}}
>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{formatAmount(editingTx.amount)} · {formatDate(editingTx.transaction_date)}
{formatAmount(editingDeal.amount)} ·{" "}
{formatDate(editingDeal.deal_date)}
</div>
<div style={{ color: 'var(--text-secondary)' }}>
{editingTx.counterparty} · {editingTx.description}
</div>
<div style={{ fontFamily: 'monospace', fontSize: 11, color: 'var(--text-secondary)', marginTop: 4 }}>
编码: {editingTx.transaction_code}
<div style={{ color: "var(--text-secondary)" }}>
{editingDeal.counterparty} ·{" "}
{editingDeal.description || "无描述"}
</div>
{editingDeal.match_count > 1 && (
<div
style={{
fontSize: 11,
color: "var(--primary)",
marginTop: 2,
}}
>
关联 {editingDeal.match_count} 笔原始交易
</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">
<label>分类</label>
<select className="form-select" value={editingTx.category || ''}
onChange={e => setEditingTx({ ...editingTx, category: e.target.value })}>
<select
className="form-select"
value={editingDeal.category || ""}
onChange={(e) =>
setEditingDeal({ ...editingDeal, category: e.target.value })
}
>
<option value="">选择分类</option>
{categories.map(c => (
<option key={c.id} value={c.name}>{c.name}</option>
{categories.map((c) => (
<option key={c.id} value={c.name}>
{c.name}
</option>
))}
</select>
</div>
@@ -203,8 +437,13 @@ export default function Review() {
<input
type="text"
className="form-input"
value={editingTx.ai_description || ''}
onChange={e => setEditingTx({ ...editingTx, ai_description: e.target.value })}
value={editingDeal.ai_description || ""}
onChange={(e) =>
setEditingDeal({
...editingDeal,
ai_description: e.target.value,
})
}
placeholder="简要描述这笔交易..."
/>
</div>
@@ -214,20 +453,42 @@ export default function Review() {
<input
type="text"
className="form-input"
value={editingTx.review_notes || ''}
onChange={e => setEditingTx({ ...editingTx, review_notes: e.target.value })}
value={editingDeal.review_notes || ""}
onChange={(e) =>
setEditingDeal({
...editingDeal,
review_notes: e.target.value,
})
}
placeholder="人工备注(可选)"
/>
</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, {
category: editingTx.category,
ai_description: editingTx.ai_description,
review_notes: editingTx.review_notes,
reviewed: 1
})}>
<div
style={{
display: "flex",
gap: 10,
justifyContent: "flex-end",
marginTop: 20,
}}
>
<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>
</div>
+29
View File
@@ -13,6 +13,9 @@ router.get("/", (req, res) => {
category,
direction,
keyword,
min_amount,
max_amount,
reviewed,
sort_by = "deal_date",
sort_order = "DESC",
} = req.query;
@@ -42,6 +45,18 @@ router.get("/", (req, res) => {
);
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 allowedSort = [
@@ -141,6 +156,20 @@ router.put("/:id", (req, res) => {
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
router.post("/clear", (req, res) => {
const db = getDB();