diff --git a/client/src/pages/Transactions.js b/client/src/pages/Transactions.js index 8becd17..63f8a73 100644 --- a/client/src/pages/Transactions.js +++ b/client/src/pages/Transactions.js @@ -1,268 +1,909 @@ -import 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'; +import 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) { - if (!dt) return ''; - return String(dt).replace(/:00$/, '').substring(0, 16); + if (!dt) return ""; + return String(dt).replace(/:00$/, "").substring(0, 16); } +const DEAL_FILTER_DEFAULT = { + page: 1, + limit: 20, + start_date: "", + end_date: "", + direction: "", + category: "", + keyword: "", + sort_by: "deal_date", + sort_order: "DESC", +}; + export default function Transactions() { - const [data, setData] = useState({ transactions: [], total: 0, page: 1, totalPages: 0 }); + const [data, setData] = useState({ + transactions: [], + total: 0, + page: 1, + totalPages: 0, + }); const [filters, setFilters] = useState({ - page: 1, limit: 20, start_date: '', end_date: '', - source_type: '', direction: '', keyword: '', - sort_by: 'transaction_time', sort_order: 'DESC' + page: 1, + limit: 20, + start_date: "", + end_date: "", + source_type: "", + direction: "", + keyword: "", + sort_by: "transaction_time", + sort_order: "DESC", }); const [loading, setLoading] = useState(true); + const [dealLoading, setDealLoading] = useState(false); const [categories, setCategories] = useState([]); const [reconciling, setReconciling] = useState(false); const [classifying, setClassifying] = useState(false); const [classifyProgress, setClassifyProgress] = useState(0); const [toast, setToast] = useState(null); - const [deals, setDeals] = useState({ deals: [], total: 0, page: 1, totalPages: 0 }); + const [deals, setDeals] = useState({ + deals: [], + total: 0, + page: 1, + totalPages: 0, + }); const [clearConfirm, setClearConfirm] = useState(false); const [editingDeal, setEditingDeal] = useState(null); - const [dealFilters, setDealFilters] = useState({ page: 1, limit: 20, keyword: "", sort_by: "deal_date", sort_order: "DESC" }); + const [dealFilters, setDealFilters] = useState({ ...DEAL_FILTER_DEFAULT }); - 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 ; return dealFilters.sort_order === "ASC" ? : ; } - function DealTh({ field, children, style }) { return dealToggleSort(field)} style={{ cursor: "pointer", userSelect: "none", ...style }}>{children}; } + /* ── sort helpers ── */ + 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 ; + return dealFilters.sort_order === "ASC" ? ( + + ) : ( + + ); + } + function DealTh({ field, children, style }) { + return ( + dealToggleSort(field)} + style={{ cursor: "pointer", userSelect: "none", ...style }} + > + + {children} + + + + ); + } - function showToast(msg, type) { setToast({ message: msg, type, key: Date.now() }); } + function SortIcon({ field }) { + if (filters.sort_by !== field) + return ; + return filters.sort_order === "ASC" ? ( + + ) : ( + + ); + } + function Th({ field, children, style }) { + return ( + toggleSort(field)} + style={{ cursor: "pointer", userSelect: "none", ...style }} + > + + {children} + + + + ); + } - // 恢复分类进度 + function showToast(msg, type) { + setToast({ message: msg, type, key: Date.now() }); + } + + /* ── restore classify progress ── */ useEffect(() => { - const saved = sessionStorage.getItem('classifyTask'); + const saved = sessionStorage.getItem("classifyTask"); if (!saved) return; const task = JSON.parse(saved); - if (Date.now() - task.ts > 300000) { sessionStorage.removeItem('classifyTask'); return; } - setClassifying(true); setClassifyProgress(task.progress || 0); + if (Date.now() - task.ts > 300000) { + sessionStorage.removeItem("classifyTask"); + return; + } + setClassifying(true); + setClassifyProgress(task.progress || 0); const poll = setInterval(async () => { try { - const res = await fetch('/api/transactions/needs-classify'); + const res = await fetch("/api/transactions/needs-classify"); const { total } = await res.json(); - const p = task.total > 0 ? Math.round((task.total - total) / task.total * 100) : 100; + 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); sessionStorage.removeItem('classifyTask'); loadTransactions(); } - } catch (e) { clearInterval(poll); setClassifying(false); sessionStorage.removeItem('classifyTask'); } + 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(); loadDeals(dealFilters); }, []); - useEffect(() => { loadDeals(dealFilters); }, [dealFilters]); - useEffect(() => { loadTransactions(); }, [filters]); + useEffect(() => { + loadCategories(); + loadDeals(DEAL_FILTER_DEFAULT); + }, []); + useEffect(() => { + loadDeals(dealFilters); + }, [dealFilters]); + useEffect(() => { + loadTransactions(); + }, [filters]); - async function loadCategories() { try { setCategories(await getCategories()); } 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 loadCategories() { + try { + setCategories(await getCategories()); + } catch (e) {} + } + + async function loadDeals(f) { + setDealLoading(true); + try { + const p = new URLSearchParams(); + Object.entries(f).forEach(([k, v]) => { + if (v !== "" && v !== undefined) p.set(k, v); + }); + const r = await fetch("/api/deals?" + p); + setDeals(await r.json()); + } catch (e) {} + setDealLoading(false); + } async function loadTransactions() { setLoading(true); try { - const p = {}; for (const [k, v] of Object.entries(filters)) if (v !== '' && v !== undefined) p[k] = v; + 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(k, v) { setFilters(prev => ({ ...prev, [k]: v, page: k === 'page' ? v : 1 })); } + function updateFilter(k, v) { + setFilters((prev) => ({ ...prev, [k]: v, page: k === "page" ? v : 1 })); + } + function updateDealFilter(k, v) { + setDealFilters((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 })); - } - - function SortIcon({ field }) { - if (filters.sort_by !== field) return ; - return filters.sort_order === 'ASC' ? : ; - } - function Th({ field, children, style }) { - return toggleSort(field)} style={{ cursor: 'pointer', userSelect: 'none', ...style }}>{children}; + setFilters((prev) => ({ + ...prev, + sort_by: field, + sort_order: + prev.sort_by === field && prev.sort_order === "DESC" ? "ASC" : "DESC", + page: 1, + })); } + /* ── deal edit / clear ── */ async function handleUpdateDeal() { if (!editingDeal) return; try { - var r=await fetch("/api/deals/"+editingDeal.id,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:editingDeal.category,ai_description:editingDeal.ai_description})}); - setEditingDeal(null);loadDeals(dealFilters);showToast("已更新","success"); - }catch(e){showToast("更新失败","error");} + await fetch("/api/deals/" + editingDeal.id, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + category: editingDeal.category, + ai_description: editingDeal.ai_description, + }), + }); + setEditingDeal(null); + loadDeals(dealFilters); + showToast("已更新", "success"); + } catch (e) { + showToast("更新失败", "error"); + } } async function handleClearDeals() { - try { await fetch("/api/deals/clear", { method: "POST" }); setDeals({ deals: [], total: 0, page: 1, totalPages: 0 }); setClearConfirm(false); } catch (e) {} + 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(); showToast('匹配 ' + (r.matched || 0) + ' 对,生成 ' + (r.deals || 0) + ' 条关联', 'success'); loadTransactions(); loadDeals(dealFilters); } catch (e) {} + try { + const r = await runReconciliation(); + showToast( + "匹配 " + (r.matched || 0) + " 对,生成 " + (r.deals || 0) + " 条关联", + "success", + ); + loadTransactions(); + loadDeals(dealFilters); + } catch (e) {} setReconciling(false); } async function handleClassifyAll() { - setClassifying(true); setClassifyProgress(0); - sessionStorage.setItem('classifyTask', JSON.stringify({ total: 0, progress: 0, ts: Date.now() })); + setClassifying(true); + setClassifyProgress(0); + sessionStorage.setItem( + "classifyTask", + JSON.stringify({ total: 0, progress: 0, ts: Date.now() }), + ); try { - const res = await fetch('/api/transactions/needs-classify'); + const res = await fetch("/api/transactions/needs-classify"); const { ids, total } = await res.json(); - 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; + 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) { await classifyTransactions(ids.slice(i, i + B)); done += Math.min(B, ids.length - i); - const pct = Math.round(done / total * 100); + const pct = Math.round((done / total) * 100); setClassifyProgress(pct); - sessionStorage.setItem('classifyTask', JSON.stringify({ total, progress: pct, ts: Date.now() })); + sessionStorage.setItem( + "classifyTask", + JSON.stringify({ total, progress: pct, ts: Date.now() }), + ); } - sessionStorage.removeItem('classifyTask'); - showToast('分类完成!共重分类 ' + total + ' 笔', 'success'); + sessionStorage.removeItem("classifyTask"); + showToast("分类完成!共重分类 " + total + " 笔", "success"); loadTransactions(); - } catch (e) { sessionStorage.removeItem('classifyTask'); showToast('分类失败: ' + (e.response?.data?.error || e.message), 'error'); } + } catch (e) { + sessionStorage.removeItem("classifyTask"); + showToast("分类失败: " + (e.response?.data?.error || e.message), "error"); + } setClassifying(false); } + /* ════════════════════════════════ RENDER ════════════════════════════════ */ return (
-

📋 交易明细

查看、筛选、排序、对账和分类

- -
- - - - +
+

📋 交易明细

+

查看、筛选、排序、对账和分类

- {/* 筛选+表格 合体卡片 */} + {/* 操作按钮行 */} +
+ + + + +
+ + {/* ── 交易记录 ── */}

交易记录

- 共 {data.total} 笔,第 {data.page}/{data.totalPages} 页 + + 共 {data.total} 笔,第 {data.page}/{data.totalPages} 页 +
+ + {/* 筛选栏 */}
-
updateFilter("start_date", e.target.value)} />
-
updateFilter("end_date", e.target.value)} />
-
-
-
updateFilter("keyword", e.target.value)} />
+
+ + updateFilter("start_date", e.target.value)} + /> +
+
+ + updateFilter("end_date", e.target.value)} + /> +
+
+ + +
+
+ + +
+
+ + updateFilter("keyword", e.target.value)} + /> +
{loading ? ( -
加载中...
+
+
加载中... +
) : data.transactions.length > 0 ? ( <> -
- - - - - - - - - - {data.transactions.map(tx => ( - - - - - - - +
+
日期时间来源对方描述金额方向
{fmtDatetime(tx.transaction_time) || fmtDatetime(tx.transaction_date)}{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}{tx.counterparty || '--'}{tx.description || '--'}{formatAmount(tx.amount)}{tx.direction === 'income' ? '收入' : '支出'}
+ + + + + + + + - ))} - -
方向ID日期 + 金额 + 对方来源
+ + + {data.transactions.map((tx) => ( + + + + {tx.direction === "income" ? "收入" : "支出"} + + + + {tx.id} + + + {fmtDatetime(tx.transaction_time) || + fmtDatetime(tx.transaction_date)} + + + {formatAmount(tx.amount)} + + {tx.counterparty || "--"} + + + {SOURCE_TYPE_MAP[tx.source_type] || tx.source_type} + + + + ))} + + +
{data.totalPages > 1 && (
- - {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 ; })} - + + {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 ( + + ); + }, + )} +
)} ) : ( -
📭

没有找到交易记录

+
+
📭
+

没有找到交易记录

+
)}
- {/* 关联交易 */} - {deals.deals && deals.deals.length > 0 && ( -
-
-

关联交易

- 共 {deals.total} 条,第 {deals.page}/{deals.totalPages} 页 -
-
-
setDealFilters(p => ({ ...p, keyword: e.target.value, page: 1 }))} />
-
-
-
- - - - - - - - - {deals.deals.map(d => ( - - - - - - - - ))} - -
dealToggleSort("deal_date")} style={{ cursor: "pointer", userSelect: "none" }}>日期{dealFilters.sort_by === "deal_date" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} dealToggleSort("amount")} style={{ cursor: "pointer", userSelect: "none", textAlign: "right" }}>金额{dealFilters.sort_by === "amount" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} dealToggleSort("category")} style={{ cursor: "pointer", userSelect: "none" }}>分类{dealFilters.sort_by === "category" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""} dealToggleSort("counterparty")} style={{ cursor: "pointer", userSelect: "none" }}>对方{dealFilters.sort_by === "counterparty" ? (dealFilters.sort_order === "ASC" ? " ▲" : " ▼") : ""}关联明细
{d.deal_date}= 0 ? "stat-value income" : "stat-value expense"}>{formatAmount(d.amount)}{d.category || 未分类}{d.counterparty || "--"} - {d.transactions?.map((t, i) => ( - - {SOURCE_TYPE_MAP[t.source_type]} - {" "}{t.description?.substring(0, 20)} - - ))} -
- {deals.totalPages > 1 && ( -
- - {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 ; })} - -
- )} + {/* ── 关联交易 ── */} +
+
+

关联交易

+ + 共 {deals.total} 条,第 {deals.page}/{deals.totalPages} 页 +
- )} + {/* 筛选栏 */} +
+
+ + updateDealFilter("start_date", e.target.value)} + /> +
+
+ + updateDealFilter("end_date", e.target.value)} + /> +
+
+ + +
+
+ + +
+
+ + updateDealFilter("keyword", e.target.value)} + /> +
+
+ +
+
+ {dealLoading ? ( +
+
加载中... +
+ ) : deals.deals.length > 0 ? ( + <> +
+ + + + 方向 + ID + 日期 + + 金额 + + 对方 + + 分类 + + + + + {deals.deals.map((d) => ( + + + + + + + + + + + ))} + +
关联明细编辑
+ = 0 ? "tag-income" : "tag-expense"}`} + > + {d.direction === "income" || parseFloat(d.amount) >= 0 + ? "收入" + : "支出"} + + + {d.id} + + {fmtDatetime(d.deal_date) || d.deal_date} + = 0 + ? "stat-value income" + : "stat-value expense" + } + > + {formatAmount(d.amount)} + {d.counterparty || "--"} + {d.transactions?.map((t, i) => ( + + + {SOURCE_TYPE_MAP[t.source_type]} + {" "} + {t.description?.substring(0, 20)} + + ))} + + {d.category || ( + + 未分类 + + )} + + +
+
+ {deals.totalPages > 1 && ( +
+ + {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 ( + + ); + }, + )} + +
+ )} + + ) : ( +
+
🔗
+

没有找到关联交易

+
+ )} +
+ + {/* ── 清空确认弹窗 ── */} {clearConfirm && (

清空关联交易

-

确定要清空所有 Deal 关联记录吗?此操作不可撤销。

-
- - +

+ 确定要清空所有 Deal 关联记录吗?此操作不可撤销。 +

+
+ +
)} + {/* ── Toast ── */} {toast && ( -
- {toast.type === "success" ? : toast.type === "error" ? : } +
+ {toast.type === "success" ? ( + + ) : toast.type === "error" ? ( + + ) : ( + + )} {toast.message} - +
)} + {/* ── 编辑 Deal 弹窗 ── */} {editingDeal && (
-
-

编辑 Deal #{editingDeal.id}

-
{editingDeal.deal_date} | {editingDeal.counterparty} | {formatAmount(editingDeal.amount)}
-
-
-
+
e.stopPropagation()} + > +

编辑 Deal #{editingDeal.id}

+
+ {editingDeal.deal_date} | {editingDeal.counterparty} |{" "} + {formatAmount(editingDeal.amount)} +
+
+ + +
+
+ + + setEditingDeal({ + ...editingDeal, + ai_description: e.target.value, + }) + } + placeholder="交易描述..." + /> +
+
+ + +
)} diff --git a/server/routes/deals.js b/server/routes/deals.js index 17e4e98..89315ae 100644 --- a/server/routes/deals.js +++ b/server/routes/deals.js @@ -1,32 +1,68 @@ -const express = require('express'); -const { getDB } = require('../db'); +const express = require("express"); +const { getDB } = require("../db"); const router = express.Router(); // GET /api/deals — 支持筛选和分页 -router.get('/', (req, res) => { +router.get("/", (req, res) => { const db = getDB(); - const { page = 1, limit = 20, start_date, end_date, category, direction, keyword, sort_by = 'deal_date', sort_order = 'DESC' } = 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 + '%'); + if (start_date) { + conditions.push("d.deal_date >= ?"); + params.push(start_date); } - const where = conditions.length ? 'WHERE ' + conditions.join(' AND ') : ''; + 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 allowedSort = [ + "id", + "deal_date", + "amount", + "direction", + "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 total = db + .prepare(`SELECT COUNT(*) as c FROM deals d ${where}`) + .get(...params).c; - const deals = db.prepare(` + 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 @@ -35,35 +71,65 @@ router.get('/', (req, res) => { GROUP BY d.id ORDER BY d.${safeSort} ${safeOrder} LIMIT ? OFFSET ? - `).all(...params, limit, offset); + `, + ) + .all(...params, limit, offset); for (const deal of deals) { - deal.transactions = db.prepare(` + deal.transactions = db + .prepare( + ` SELECT t.*, s.source_name FROM deal_transactions dt JOIN transactions t ON t.id = dt.transaction_id LEFT JOIN sources s ON s.id = t.source_id WHERE dt.deal_id = ? - `).all(deal.id); + `, + ) + .all(deal.id); } - res.json({ deals, total, page: Number(page), totalPages: Math.ceil(total / limit) }); + res.json({ + deals, + total, + page: Number(page), + totalPages: Math.ceil(total / limit), + }); }); // PUT /api/deals/:id — 编辑分类/确认 -router.put('/:id', (req, res) => { +router.put("/:id", (req, res) => { const db = getDB(); const { category, ai_description, reviewed, review_notes, tags } = req.body; - const sets = []; const params = []; - if (category !== undefined) { sets.push('category = ?'); params.push(category); } - if (ai_description !== undefined) { sets.push('ai_description = ?'); params.push(ai_description); } - if (reviewed !== undefined) { sets.push('reviewed = ?'); params.push(reviewed); if (reviewed) sets.push('reviewed_at = CURRENT_TIMESTAMP'); } - if (review_notes !== undefined) { sets.push('review_notes = ?'); params.push(review_notes); } - if (tags !== undefined) { sets.push('tags = ?'); params.push(JSON.stringify(tags)); } - if (!sets.length) return res.status(400).json({ error: '无更新字段' }); - sets.push('updated_at = CURRENT_TIMESTAMP'); + const sets = []; + const params = []; + if (category !== undefined) { + sets.push("category = ?"); + params.push(category); + } + if (ai_description !== undefined) { + sets.push("ai_description = ?"); + params.push(ai_description); + } + if (reviewed !== undefined) { + sets.push("reviewed = ?"); + params.push(reviewed); + if (reviewed) sets.push("reviewed_at = CURRENT_TIMESTAMP"); + } + if (review_notes !== undefined) { + sets.push("review_notes = ?"); + params.push(review_notes); + } + if (tags !== undefined) { + sets.push("tags = ?"); + params.push(JSON.stringify(tags)); + } + if (!sets.length) return res.status(400).json({ error: "无更新字段" }); + sets.push("updated_at = CURRENT_TIMESTAMP"); params.push(req.params.id); - db.prepare('UPDATE deals SET ' + sets.join(', ') + ' WHERE id = ?').run(...params); + db.prepare("UPDATE deals SET " + sets.join(", ") + " WHERE id = ?").run( + ...params, + ); res.json({ success: true }); }); diff --git a/server/routes/transactions.js b/server/routes/transactions.js index 0669b0f..3d67ca3 100644 --- a/server/routes/transactions.js +++ b/server/routes/transactions.js @@ -80,6 +80,8 @@ router.get("/", (req, res) => { "amount", "created_at", "counterparty", + "direction", + "source_type", ]; const safeSortBy = allowedSortFields.includes(sort_by) ? sort_by @@ -114,54 +116,104 @@ router.get("/", (req, res) => { router.get("/needs-classify", (req, res) => { const db = getDB(); - const cats = db.prepare("SELECT name FROM categories").all().map(r => r.name); + const cats = db + .prepare("SELECT name FROM categories") + .all() + .map((r) => r.name); if (!cats.length) return res.json({ ids: [], total: 0 }); const ph = cats.map(() => "?").join(","); - const stale = db.prepare(`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`).all(...cats); - res.json({ ids: stale.map(r => r.id), total: stale.length }); + const stale = db + .prepare( + `SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`, + ) + .all(...cats); + res.json({ ids: stale.map((r) => r.id), total: stale.length }); }); // POST /api/transactions/reconcile - 全量清除后重新对账 -router.post('/reconcile', (req, res) => { +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(); + 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 = []; + 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); + 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); + 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); + 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}); + 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(); - const cats = db.prepare("SELECT name FROM categories").all().map(r => r.name); + const cats = db + .prepare("SELECT name FROM categories") + .all() + .map((r) => r.name); if (!cats.length) return res.json({ classified: 0 }); const ph = cats.map(() => "?").join(","); - const stale = db.prepare(`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`).all(...cats); + const stale = db + .prepare( + `SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`, + ) + .all(...cats); if (!stale.length) return res.json({ classified: 0, total: 0 }); - const ids = stale.map(r => r.id), B = 50; + const ids = stale.map((r) => r.id), + B = 50; let n = 0; for (let i = 0; i < ids.length; i += B) { const r = await classifyDeals(ids.slice(i, i + B));