Compare commits
10
Commits
ef7fef2254
...
2c8473e9e0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c8473e9e0 | ||
|
|
cb5915e2ce | ||
|
|
99837bea9a | ||
|
|
27a170ec0c | ||
|
|
4ec7b67ed0 | ||
|
|
fc1614a998 | ||
|
|
890bb1e579 | ||
|
|
bf0c6ce9b1 | ||
|
|
08fbde8a39 | ||
|
|
965ef2058d |
+132
-35
@@ -20,7 +20,9 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
|
||||
"Microsoft YaHei", sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
@@ -185,10 +187,18 @@ body {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.stat-value.income { color: var(--success); }
|
||||
.stat-value.expense { color: var(--danger); }
|
||||
.stat-value.warning { color: var(--warning); }
|
||||
.stat-value.primary { color: var(--primary); }
|
||||
.stat-value.income {
|
||||
color: var(--success);
|
||||
}
|
||||
.stat-value.expense {
|
||||
color: var(--danger);
|
||||
}
|
||||
.stat-value.warning {
|
||||
color: var(--warning);
|
||||
}
|
||||
.stat-value.primary {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
@@ -209,7 +219,9 @@ body {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover { background: #4338ca; }
|
||||
.btn-primary:hover {
|
||||
background: #4338ca;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg);
|
||||
@@ -217,7 +229,9 @@ body {
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.btn-secondary:hover { background: var(--border); }
|
||||
.btn-secondary:hover {
|
||||
background: var(--border);
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: var(--success);
|
||||
@@ -234,6 +248,17 @@ body {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
filter: grayscale(0.6);
|
||||
}
|
||||
|
||||
.btn:disabled:hover {
|
||||
opacity: 0.4;
|
||||
filter: grayscale(0.6);
|
||||
}
|
||||
|
||||
/* Form elements */
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
@@ -247,7 +272,8 @@ body {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.form-input, .form-select {
|
||||
.form-input,
|
||||
.form-select {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--border);
|
||||
@@ -257,7 +283,8 @@ body {
|
||||
background: white;
|
||||
}
|
||||
|
||||
.form-input:focus, .form-select:focus {
|
||||
.form-input:focus,
|
||||
.form-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-light);
|
||||
box-shadow: 0 0 0 3px var(--primary-bg);
|
||||
@@ -289,7 +316,9 @@ td {
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
tr:hover { background: var(--bg); }
|
||||
tr:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* Tags */
|
||||
.tag {
|
||||
@@ -300,11 +329,26 @@ tr:hover { background: var(--bg); }
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tag-income { background: #d1fae5; color: #065f46; }
|
||||
.tag-expense { background: #fee2e2; color: #991b1b; }
|
||||
.tag-transfer { background: #dbeafe; color: #1e40af; }
|
||||
.tag-matched { background: #e0e7ff; color: #3730a3; }
|
||||
.tag-unreviewed { background: #fef3c7; color: #92400e; }
|
||||
.tag-income {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
.tag-expense {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
.tag-transfer {
|
||||
background: #dbeafe;
|
||||
color: #1e40af;
|
||||
}
|
||||
.tag-matched {
|
||||
background: #e0e7ff;
|
||||
color: #3730a3;
|
||||
}
|
||||
.tag-unreviewed {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
/* Review items */
|
||||
.review-item {
|
||||
@@ -324,10 +368,17 @@ tr:hover { background: var(--bg); }
|
||||
}
|
||||
|
||||
.review-item.reviewed {
|
||||
opacity: 0.7;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.review-item.income-border {
|
||||
border-left: 3px solid var(--success);
|
||||
}
|
||||
|
||||
.review-item.expense-border {
|
||||
border-left: 3px solid var(--danger);
|
||||
}
|
||||
|
||||
.review-item .amount-col {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
@@ -366,7 +417,8 @@ tr:hover { background: var(--bg); }
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.upload-zone:hover, .upload-zone.drag-over {
|
||||
.upload-zone:hover,
|
||||
.upload-zone.drag-over {
|
||||
border-color: var(--primary-light);
|
||||
background: var(--primary-bg);
|
||||
}
|
||||
@@ -476,7 +528,9 @@ tr:hover { background: var(--bg); }
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tab:hover { color: var(--text); }
|
||||
.tab:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
.tab.active {
|
||||
color: var(--primary);
|
||||
border-bottom-color: var(--primary);
|
||||
@@ -493,12 +547,30 @@ tr:hover { background: var(--bg); }
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.source-alipay { background: #dbeafe; color: #1e40af; }
|
||||
.source-wechat { background: #d1fae5; color: #065f46; }
|
||||
.source-bank_debit { background: #fef3c7; color: #92400e; }
|
||||
.source-bank_credit { background: #fef3c7; color: #92400e; }
|
||||
.source-abc { background: #e0e7ff; color: #3730a3; }
|
||||
.source-credit_card { background: #fee2e2; color: #991b1b; }
|
||||
.source-alipay {
|
||||
background: #dbeafe;
|
||||
color: #1e40af;
|
||||
}
|
||||
.source-wechat {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
.source-bank_debit {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
.source-bank_credit {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
.source-abc {
|
||||
background: #e0e7ff;
|
||||
color: #3730a3;
|
||||
}
|
||||
.source-credit_card {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
/* Loading */
|
||||
.loading {
|
||||
@@ -520,7 +592,9 @@ tr:hover { background: var(--bg); }
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* Toast */
|
||||
@@ -536,20 +610,43 @@ tr:hover { background: var(--bg); }
|
||||
animation: slideIn 0.3s ease;
|
||||
}
|
||||
|
||||
.toast-success { background: var(--success); }
|
||||
.toast-error { background: var(--danger); }
|
||||
.toast-success {
|
||||
background: var(--success);
|
||||
}
|
||||
.toast-error {
|
||||
background: var(--danger);
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateX(100%); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
from {
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 768px) {
|
||||
.sidebar { width: 60px; }
|
||||
.sidebar .nav-link span:not(.badge) { display: none; }
|
||||
.sidebar .logo-sub { display: none; }
|
||||
.main-content { margin-left: 60px; padding: 16px; }
|
||||
.stats-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.filter-bar { flex-direction: column; }
|
||||
.sidebar {
|
||||
width: 60px;
|
||||
}
|
||||
.sidebar .nav-link span:not(.badge) {
|
||||
display: none;
|
||||
}
|
||||
.sidebar .logo-sub {
|
||||
display: none;
|
||||
}
|
||||
.main-content {
|
||||
margin-left: 60px;
|
||||
padding: 16px;
|
||||
}
|
||||
.stats-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
.filter-bar {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
+129
-20
@@ -1,18 +1,41 @@
|
||||
import React from 'react';
|
||||
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom';
|
||||
import React from "react";
|
||||
import {
|
||||
LayoutDashboard, Upload, ListFilter, ClipboardCheck, Settings
|
||||
} from 'lucide-react';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import Import from './pages/Import';
|
||||
import Transactions from './pages/Transactions';
|
||||
import Review from './pages/Review';
|
||||
import SettingsPage from './pages/Settings';
|
||||
import './App.css';
|
||||
BrowserRouter,
|
||||
Routes,
|
||||
Route,
|
||||
NavLink,
|
||||
Navigate,
|
||||
Outlet,
|
||||
useNavigate,
|
||||
} from "react-router-dom";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Upload,
|
||||
ListFilter,
|
||||
ClipboardCheck,
|
||||
Settings,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { AuthProvider, useAuth } from "./context/AuthContext";
|
||||
import ProtectedRoute from "./components/ProtectedRoute";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
import Import from "./pages/Import";
|
||||
import Transactions from "./pages/Transactions";
|
||||
import Review from "./pages/Review";
|
||||
import SettingsPage from "./pages/Settings";
|
||||
import Login from "./pages/Login";
|
||||
import "./App.css";
|
||||
|
||||
function MainLayout() {
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
function handleLogout() {
|
||||
logout();
|
||||
navigate("/login", { replace: true });
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div className="app">
|
||||
<nav className="sidebar">
|
||||
<div className="sidebar-header">
|
||||
@@ -20,42 +43,128 @@ function App() {
|
||||
<span className="logo-sub">银行流水对账分析</span>
|
||||
</div>
|
||||
<div className="nav-links">
|
||||
<NavLink to="/" end className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<NavLink
|
||||
to="/"
|
||||
end
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<LayoutDashboard size={20} />
|
||||
<span>仪表盘</span>
|
||||
</NavLink>
|
||||
<NavLink to="/import" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<NavLink
|
||||
to="/import"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<Upload size={20} />
|
||||
<span>导入账单</span>
|
||||
</NavLink>
|
||||
<NavLink to="/transactions" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<NavLink
|
||||
to="/transactions"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<ListFilter size={20} />
|
||||
<span>交易明细</span>
|
||||
</NavLink>
|
||||
<NavLink to="/review" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<NavLink
|
||||
to="/review"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<ClipboardCheck size={20} />
|
||||
<span>大额确认</span>
|
||||
<span className="badge" id="review-badge">0</span>
|
||||
<span className="badge" id="review-badge">
|
||||
0
|
||||
</span>
|
||||
</NavLink>
|
||||
<NavLink to="/settings" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<NavLink
|
||||
to="/settings"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<Settings size={20} />
|
||||
<span>系统设置</span>
|
||||
</NavLink>
|
||||
</div>
|
||||
<div className="sidebar-footer">
|
||||
<div
|
||||
style={{
|
||||
fontSize: 12,
|
||||
color: "rgba(255,255,255,0.5)",
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
👤 {user?.nickname || user?.username}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span className="version">v1.0.0</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "rgba(255,255,255,0.5)",
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 4,
|
||||
fontSize: 11,
|
||||
padding: "2px 6px",
|
||||
borderRadius: 4,
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.target.style.color = "white";
|
||||
e.target.style.background = "rgba(255,255,255,0.1)";
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.target.style.color = "rgba(255,255,255,0.5)";
|
||||
e.target.style.background = "none";
|
||||
}}
|
||||
>
|
||||
<LogOut size={12} /> 登出
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<main className="main-content">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
{/* 公开路由 */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* 受保护路由 */}
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/import" element={<Import />} />
|
||||
<Route path="/transactions" element={<Transactions />} />
|
||||
<Route path="/review" element={<Review />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
{/* 未匹配路由重定向到首页 */}
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import React from 'react';
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function ProtectedRoute() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
const api = axios.create({ baseURL: '/api', timeout: 15000 });
|
||||
|
||||
const TOKEN_KEY = 'reco_token';
|
||||
const USER_KEY = 'reco_user';
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(USER_KEY);
|
||||
return stored ? JSON.parse(stored) : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
const [token, setTokenRaw] = useState(() => localStorage.getItem(TOKEN_KEY));
|
||||
|
||||
const setToken = useCallback((t) => {
|
||||
if (t) {
|
||||
localStorage.setItem(TOKEN_KEY, t);
|
||||
} else {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
setTokenRaw(t);
|
||||
}, []);
|
||||
|
||||
// 同步 user 到 localStorage
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
} else {
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const isAuthenticated = !!token;
|
||||
|
||||
async function login(username, password) {
|
||||
const res = await api.post('/auth/login', { username, password });
|
||||
setToken(res.data.token);
|
||||
setUser(res.data.user);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
async function register(username, password, nickname) {
|
||||
const res = await api.post('/auth/register', { username, password, nickname });
|
||||
setToken(res.data.token);
|
||||
setUser(res.data.user);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
function logout() {
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, token, isAuthenticated, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth 必须在 AuthProvider 内使用');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export default AuthContext;
|
||||
@@ -6,6 +6,28 @@ const api = axios.create({
|
||||
timeout: 60000,
|
||||
});
|
||||
|
||||
// 请求拦截器:自动携带 Token
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem("reco_token");
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// 响应拦截器:401 自动跳转登录
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem("reco_token");
|
||||
localStorage.removeItem("reco_user");
|
||||
window.location.href = "/login";
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
// Global toast handler
|
||||
let toastHandler = null;
|
||||
export function setToastHandler(handler) {
|
||||
@@ -60,6 +82,16 @@ export async function deleteSource(id) {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function confirmUpload(tempId) {
|
||||
const res = await api.post("/upload/confirm", { tempId });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function cancelUpload(tempId) {
|
||||
const res = await api.post("/upload/cancel", { tempId });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Deals
|
||||
export async function getDeals(params = {}) {
|
||||
const res = await api.get("/deals", { params });
|
||||
@@ -76,6 +108,11 @@ export async function batchConfirmDeals(ids) {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function clearDeals() {
|
||||
const res = await api.post("/deals/clear");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Transactions
|
||||
export async function getTransactions(params = {}) {
|
||||
const res = await api.get("/transactions", { params });
|
||||
@@ -107,9 +144,12 @@ export async function classifyTransactions(ids) {
|
||||
}
|
||||
|
||||
export async function classifyAll() {
|
||||
const res = await api.post("/transactions/classify-all", null, {
|
||||
timeout: 600000,
|
||||
});
|
||||
const res = await api.post("/transactions/classify-all");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getClassifyStatus() {
|
||||
const res = await api.get("/transactions/classify-status");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -119,8 +159,8 @@ export async function getOverview(params = {}) {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getMonthly(months = 12) {
|
||||
const res = await api.get("/stats/monthly", { params: { months } });
|
||||
export async function getMonthly(params = {}) {
|
||||
const res = await api.get("/stats/monthly", { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -162,7 +202,6 @@ export async function updateCategory(id, data) {
|
||||
const res = await api.put(`/config/categories/${id}`, data);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export function formatAmount(amount) {
|
||||
if (amount === null || amount === undefined) return "--";
|
||||
const n = Number(amount);
|
||||
|
||||
+283
-151
@@ -1,5 +1,4 @@
|
||||
import React, { useState, useEffect, useMemo } from "react";
|
||||
import { RefreshCcw } from "lucide-react";
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
@@ -11,14 +10,8 @@ import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
Legend,
|
||||
} from "recharts";
|
||||
import {
|
||||
getOverview,
|
||||
getMonthly,
|
||||
formatAmount,
|
||||
formatDate,
|
||||
} from "../hooks/useApi";
|
||||
import { getOverview, getMonthly, formatAmount } from "../hooks/useApi";
|
||||
|
||||
const COLORS = [
|
||||
"#4f46e5",
|
||||
@@ -35,68 +28,52 @@ const COLORS = [
|
||||
"#e11d48",
|
||||
];
|
||||
|
||||
// 不参与支出饼图的分类(投资/转账/赠与类)
|
||||
const EXCLUDED_PATTERNS = ["投资", "转账", "赠与", "红包"];
|
||||
const DEFAULT_UNCHECKED = ["投资理财", "转账红包", "投资赠与"];
|
||||
// 单独成卡片的分类(默认不勾选,仍可在明细表里手动勾选)
|
||||
const GIFT_CATEGORY = "投资赠与";
|
||||
|
||||
function isExcluded(category) {
|
||||
if (!category) return true;
|
||||
const s = category.trim().toLowerCase();
|
||||
return EXCLUDED_PATTERNS.some(p => s.includes(p.toLowerCase()));
|
||||
// 财年:以每年 2 月 1 日 00:00:00 为结算点
|
||||
// 财年 Y = [Y-02-01 00:00:00, (Y+1)-01-31 23:59:59]
|
||||
const FY_START_MONTH = 2;
|
||||
|
||||
function fiscalYearOf(value) {
|
||||
if (!value) return null;
|
||||
const d =
|
||||
value instanceof Date ? value : new Date(String(value).replace(" ", "T"));
|
||||
if (Number.isNaN(d.getTime())) return null;
|
||||
return d.getMonth() + 1 >= FY_START_MONTH
|
||||
? d.getFullYear()
|
||||
: d.getFullYear() - 1;
|
||||
}
|
||||
|
||||
/** 将小切片合并为"其他",最多保留 topN-1 个分类 + 1 个"其他" */
|
||||
function buildPieData(categoryStats, topN = 8) {
|
||||
const filtered = (categoryStats || []).filter(
|
||||
(c) => !isExcluded(c.category),
|
||||
);
|
||||
if (filtered.length === 0) return { slices: [], totalAmount: 0 };
|
||||
|
||||
const totalAmount = filtered.reduce((s, c) => s + c.total_amount, 0);
|
||||
if (filtered.length <= topN) return { slices: filtered, totalAmount };
|
||||
|
||||
const top = filtered.slice(0, topN - 1);
|
||||
const rest = filtered.slice(topN - 1);
|
||||
const otherAmount = rest.reduce((s, c) => s + c.total_amount, 0);
|
||||
|
||||
function fiscalRange(fy) {
|
||||
const y = Number(fy);
|
||||
return {
|
||||
slices: [
|
||||
...top,
|
||||
{
|
||||
category: "其他",
|
||||
count: rest.reduce((s, c) => s + c.count, 0),
|
||||
total_amount: otherAmount,
|
||||
},
|
||||
],
|
||||
totalAmount,
|
||||
start_date: `${y}-02-01 00:00:00`,
|
||||
end_date: `${y + 1}-01-31 23:59:59`,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFiscalYears(range) {
|
||||
if (!range?.min_date || !range?.max_date) return [];
|
||||
const lo = fiscalYearOf(range.min_date);
|
||||
const hi = fiscalYearOf(range.max_date);
|
||||
if (lo === null || hi === null) return [];
|
||||
const years = [];
|
||||
for (let y = hi; y >= lo; y--) years.push(y);
|
||||
return years;
|
||||
}
|
||||
|
||||
const RADIAN = Math.PI / 180;
|
||||
|
||||
/** 自定义 label:拉出引导线 + 百分比 */
|
||||
function renderPieLabel({
|
||||
cx,
|
||||
cy,
|
||||
midAngle,
|
||||
innerRadius,
|
||||
outerRadius,
|
||||
percent,
|
||||
category,
|
||||
}) {
|
||||
const radius = outerRadius + 30;
|
||||
const x = cx + radius * Math.cos(-midAngle * RADIAN);
|
||||
const y = cy + radius * Math.sin(-midAngle * RADIAN);
|
||||
|
||||
// 引导线起点
|
||||
function renderPieLabel({ cx, cy, midAngle, outerRadius, percent, category }) {
|
||||
const r = outerRadius + 30;
|
||||
const x = cx + r * Math.cos(-midAngle * RADIAN);
|
||||
const y = cy + r * Math.sin(-midAngle * RADIAN);
|
||||
const mx = cx + (outerRadius + 8) * Math.cos(-midAngle * RADIAN);
|
||||
const my = cy + (outerRadius + 8) * Math.sin(-midAngle * RADIAN);
|
||||
// 饼内点
|
||||
const ex = cx + (outerRadius + 2) * Math.cos(-midAngle * RADIAN);
|
||||
const ey = cy + (outerRadius + 2) * Math.sin(-midAngle * RADIAN);
|
||||
|
||||
const pct = (percent * 100).toFixed(0);
|
||||
const textAnchor = x > cx ? "start" : "end";
|
||||
|
||||
const anchor = x > cx ? "start" : "end";
|
||||
return (
|
||||
<>
|
||||
<polyline
|
||||
@@ -108,119 +85,239 @@ function renderPieLabel({
|
||||
<text
|
||||
x={x + (x > cx ? 4 : -4)}
|
||||
y={y}
|
||||
textAnchor={textAnchor}
|
||||
textAnchor={anchor}
|
||||
dominantBaseline="central"
|
||||
fontSize={11}
|
||||
fill="#475569"
|
||||
>
|
||||
<tspan fontWeight={600}>{category}</tspan>
|
||||
<tspan fill="#94a3b8"> {pct}%</tspan>
|
||||
<tspan fill="#94a3b8"> {(percent * 100).toFixed(0)}%</tspan>
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function buildPieData(stats, topN = 7) {
|
||||
const list = stats || [];
|
||||
if (!list.length) return { slices: [], total: 0 };
|
||||
const total = list.reduce((s, c) => s + c.total_amount, 0);
|
||||
if (list.length <= topN) return { slices: list, total };
|
||||
const top = list.slice(0, topN - 1);
|
||||
const rest = list.slice(topN - 1);
|
||||
const other = {
|
||||
category: "其他",
|
||||
count: rest.reduce((s, c) => s + c.count, 0),
|
||||
total_amount: rest.reduce((s, c) => s + c.total_amount, 0),
|
||||
};
|
||||
return { slices: [...top, other], total };
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [overview, setOverview] = useState(null);
|
||||
const [raw, setRaw] = useState(null);
|
||||
const [monthly, setMonthly] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [checked, setChecked] = useState(() => new Set());
|
||||
const [fy, setFy] = useState(null); // number=财年 | "all" | null=未初始化
|
||||
const [fyOptions, setFyOptions] = useState([]);
|
||||
|
||||
// 初始化:先取全量日期范围,枚举可选财年并默认选最新一个
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
(async () => {
|
||||
try {
|
||||
const ov = await getOverview();
|
||||
const years = buildFiscalYears(ov?.dateRange);
|
||||
setFyOptions(years);
|
||||
setFy(years.length ? years[0] : "all");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
async function loadData() {
|
||||
// 财年变化 -> 重新拉取总览
|
||||
useEffect(() => {
|
||||
if (fy === null) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [overviewData, monthlyData] = await Promise.all([
|
||||
getOverview(),
|
||||
getMonthly(12),
|
||||
]);
|
||||
setOverview(overviewData);
|
||||
setMonthly(monthlyData);
|
||||
} catch (err) {
|
||||
console.error("加载数据失败:", err);
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
const ov = overview?.overview || {};
|
||||
const { slices: pieData, totalAmount: pieTotal } = useMemo(
|
||||
() => buildPieData(overview?.categoryStats),
|
||||
[overview],
|
||||
const params = fy === "all" ? {} : fiscalRange(fy);
|
||||
const ov = await getOverview(params);
|
||||
if (cancelled) return;
|
||||
setRaw(ov);
|
||||
const allCats = new Set(
|
||||
(ov?.categoryBreakdown || []).map((c) => c.category),
|
||||
);
|
||||
for (const c of DEFAULT_UNCHECKED) allCats.delete(c);
|
||||
setChecked(allCats);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
if (!cancelled) setLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [fy]);
|
||||
|
||||
if (loading) {
|
||||
// 勾选分类 / 财年变化 -> 重新拉取月度趋势
|
||||
useEffect(() => {
|
||||
if (!raw) return;
|
||||
const cats = [...checked];
|
||||
if (cats.length === 0) {
|
||||
setMonthly([]);
|
||||
return;
|
||||
}
|
||||
const params = { categories: cats.join(",") };
|
||||
if (fy !== "all" && fy != null) Object.assign(params, fiscalRange(fy));
|
||||
getMonthly(params).then(setMonthly).catch(console.error);
|
||||
}, [checked, raw, fy]);
|
||||
|
||||
function toggleCat(cat) {
|
||||
setChecked((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(cat) ? next.delete(cat) : next.add(cat);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
const allCats = (raw?.categoryBreakdown || []).map((c) => c.category);
|
||||
const allChecked = checked.size === allCats.length && allCats.length > 0;
|
||||
const noneChecked = checked.size === 0;
|
||||
|
||||
function toggleAll() {
|
||||
if (allChecked) {
|
||||
setChecked(new Set());
|
||||
} else {
|
||||
setChecked(new Set(allCats));
|
||||
}
|
||||
}
|
||||
|
||||
const derived = useMemo(() => {
|
||||
if (!raw) return null;
|
||||
const cb = raw.categoryBreakdown || [];
|
||||
const cs = raw.categoryStats || [];
|
||||
// 勾选分类参与统计(投资赠与默认不勾选,用户想算进去可手动勾)
|
||||
const sel = cb.filter((c) => checked.has(c.category));
|
||||
const totalIncome = sel.reduce((s, c) => s + c.total_income, 0);
|
||||
const totalExpense = sel.reduce((s, c) => s + c.total_expense, 0);
|
||||
const dealCount = sel.reduce((s, c) => s + c.deal_count, 0);
|
||||
const pieStats = cs.filter((c) => checked.has(c.category));
|
||||
|
||||
// 投资赠与单独一张卡片:净额 = 收入 - 支出
|
||||
const gift = cb.find((c) => c.category === GIFT_CATEGORY) || null;
|
||||
const giftNet = gift ? gift.total_income - gift.total_expense : 0;
|
||||
|
||||
return {
|
||||
sel,
|
||||
totalIncome,
|
||||
totalExpense,
|
||||
dealCount,
|
||||
pieStats,
|
||||
gift,
|
||||
giftNet,
|
||||
};
|
||||
}, [raw, checked]);
|
||||
|
||||
const ov = raw?.overview || {};
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<div className="loading">
|
||||
<div className="spinner"></div>加载中...
|
||||
<div className="spinner" />
|
||||
加载中...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
className="page-header"
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "flex-start",
|
||||
}}
|
||||
style={{ display: "flex", justifyContent: "space-between" }}
|
||||
>
|
||||
<div>
|
||||
<h2>📊 财务仪表盘</h2>
|
||||
<p>全面掌握你的收支情况</p>
|
||||
<p>
|
||||
勾选分类后,所有统计基于选中项计算
|
||||
{fy && fy !== "all"
|
||||
? ` · 财年 ${fy}(${fy}-02-01 ~ ${Number(fy) + 1}-01-31)`
|
||||
: " · 全部时间"}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={loadData}
|
||||
style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
财年
|
||||
</span>
|
||||
<select
|
||||
className="form-select"
|
||||
style={{ width: 130 }}
|
||||
value={fy ?? ""}
|
||||
onChange={(e) =>
|
||||
setFy(e.target.value === "all" ? "all" : Number(e.target.value))
|
||||
}
|
||||
disabled={fy === null}
|
||||
title={
|
||||
fy && fy !== "all"
|
||||
? `${fy}-02-01 ~ ${Number(fy) + 1}-01-31`
|
||||
: "全部时间"
|
||||
}
|
||||
>
|
||||
<RefreshCcw size={14} /> 刷新
|
||||
</button>
|
||||
{fyOptions.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y} 财年
|
||||
</option>
|
||||
))}
|
||||
<option value="all">全部</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="stats-grid">
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">💰 总收入</div>
|
||||
<div className="stat-value income">
|
||||
{formatAmount(ov.total_income)}
|
||||
{formatAmount(derived?.totalIncome ?? 0)}
|
||||
</div>
|
||||
<div className="stat-sub">所有来源收入合计</div>
|
||||
<div className="stat-sub">{checked.size} 个分类合计</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">💸 总支出</div>
|
||||
<div className="stat-value expense">
|
||||
{formatAmount(ov.total_expense)}
|
||||
{formatAmount(-(derived?.totalExpense ?? 0))}
|
||||
</div>
|
||||
<div className="stat-sub">所有支出合计</div>
|
||||
<div className="stat-sub">{checked.size} 个分类合计</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">🎁 投资赠与</div>
|
||||
<div
|
||||
className={`stat-value ${(derived?.giftNet ?? 0) >= 0 ? "income" : "expense"}`}
|
||||
>
|
||||
{formatAmount(derived?.giftNet ?? 0)}
|
||||
</div>
|
||||
<div className="stat-sub">净额,默认不勾选</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">📈 净收支</div>
|
||||
<div
|
||||
className={`stat-value ${ov.total_income - ov.total_expense >= 0 ? "income" : "expense"}`}
|
||||
className={`stat-value ${(derived?.totalIncome ?? 0) - (derived?.totalExpense ?? 0) >= 0 ? "income" : "expense"}`}
|
||||
>
|
||||
{formatAmount(ov.total_income - ov.total_expense)}
|
||||
{formatAmount(
|
||||
(derived?.totalIncome ?? 0) - (derived?.totalExpense ?? 0),
|
||||
)}
|
||||
</div>
|
||||
<div className="stat-sub">收入 - 支出</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">📝 交易总数</div>
|
||||
<div className="stat-value primary">{ov.total_count || 0}</div>
|
||||
<div className="stat-sub">
|
||||
共 {ov.matched_count || 0} 笔交易被记录
|
||||
</div>
|
||||
<div className="stat-label">📝 交易笔数</div>
|
||||
<div className="stat-value primary">{derived?.dealCount ?? 0}</div>
|
||||
<div className="stat-sub">共 {ov.matched_count || 0} 条原始记录</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">⚠️ 待确认</div>
|
||||
<div className="stat-value warning">{ov.pending_review || 0}</div>
|
||||
<div className="stat-sub">≥100元 未确认交易</div>
|
||||
<div className="stat-sub">≥100元 未确认</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Charts Row */}
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
@@ -229,7 +326,6 @@ export default function Dashboard() {
|
||||
marginBottom: 24,
|
||||
}}
|
||||
>
|
||||
{/* Monthly Trend */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📅 月度收支趋势</h3>
|
||||
@@ -240,10 +336,7 @@ export default function Dashboard() {
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis dataKey="month" tick={{ fontSize: 11 }} />
|
||||
<YAxis tick={{ fontSize: 11 }} />
|
||||
<Tooltip
|
||||
formatter={(value) => formatAmount(value)}
|
||||
labelStyle={{ fontWeight: 600 }}
|
||||
/>
|
||||
<Tooltip formatter={(v) => formatAmount(v)} />
|
||||
<Bar
|
||||
dataKey="income"
|
||||
name="收入"
|
||||
@@ -261,26 +354,30 @@ export default function Dashboard() {
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无数据,请先导入账单</p>
|
||||
<p>暂无数据</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Category Pie */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 支出分类占比</h3>
|
||||
{pieData.length > 0 && (
|
||||
{(() => {
|
||||
const pd = buildPieData(derived?.pieStats);
|
||||
return pd.total > 0 ? (
|
||||
<span style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
合计 {formatAmount(-pieTotal)}
|
||||
合计 {formatAmount(-pd.total)}
|
||||
</span>
|
||||
)}
|
||||
) : null;
|
||||
})()}
|
||||
</div>
|
||||
{pieData.length > 0 ? (
|
||||
{(() => {
|
||||
const pd = buildPieData(derived?.pieStats);
|
||||
return pd.slices.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={pieData}
|
||||
data={pd.slices}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={50}
|
||||
@@ -290,44 +387,57 @@ export default function Dashboard() {
|
||||
nameKey="category"
|
||||
label={renderPieLabel}
|
||||
labelLine={false}
|
||||
isAnimationActive={true}
|
||||
isAnimationActive
|
||||
>
|
||||
{pieData.map((_, idx) => (
|
||||
<Cell key={idx} fill={COLORS[idx % COLORS.length]} />
|
||||
{pd.slices.map((_, i) => (
|
||||
<Cell key={i} fill={COLORS[i % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value) => formatAmount(-value)}
|
||||
labelFormatter={(name) => `分类: ${name}`}
|
||||
formatter={(v) => formatAmount(-v)}
|
||||
labelFormatter={(n) => `分类: ${n}`}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : overview?.categoryStats?.length > 0 ? (
|
||||
<div className="empty-state" style={{ padding: "40px 0" }}>
|
||||
<div className="icon">📊</div>
|
||||
<p style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
投资/转账类不参与支出占比统计
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: "40px 0" }}>
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无分类数据,请先对账并 AI 分类</p>
|
||||
<p>请勾选至少一个分类</p>
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Breakdown Table */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📋 分类收支明细</h3>
|
||||
<span style={{ fontSize: 12, color: "var(--text-secondary)" }}>
|
||||
勾选的行参与上方统计
|
||||
</span>
|
||||
</div>
|
||||
{overview?.categoryBreakdown?.length > 0 ? (
|
||||
{(raw?.categoryBreakdown || []).length > 0 ? (
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 40 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
ref={(el) => {
|
||||
if (el) el.indeterminate = !allChecked && !noneChecked;
|
||||
}}
|
||||
checked={allChecked}
|
||||
onChange={toggleAll}
|
||||
title={allChecked ? "全部取消" : "全部勾选"}
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
cursor: "pointer",
|
||||
accentColor: "var(--primary)",
|
||||
}}
|
||||
/>
|
||||
</th>
|
||||
<th>分类</th>
|
||||
<th style={{ textAlign: "right" }}>笔数</th>
|
||||
<th style={{ textAlign: "right" }}>收入</th>
|
||||
@@ -338,18 +448,37 @@ export default function Dashboard() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{overview.categoryBreakdown.map((cat, i) => (
|
||||
<tr key={i}>
|
||||
{raw.categoryBreakdown.map((cat, i) => {
|
||||
const on = checked.has(cat.category);
|
||||
return (
|
||||
<tr key={i} style={{ opacity: on ? 1 : 0.45 }}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={on}
|
||||
onChange={() => toggleCat(cat.category)}
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
cursor: "pointer",
|
||||
accentColor: "var(--primary)",
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<span className="tag tag-matched">{cat.category}</span>
|
||||
</td>
|
||||
<td style={{ textAlign: "right" }}>{cat.deal_count}</td>
|
||||
<td style={{ textAlign: "right", color: "var(--success)" }}>
|
||||
<td
|
||||
style={{ textAlign: "right", color: "var(--success)" }}
|
||||
>
|
||||
{cat.total_income > 0
|
||||
? formatAmount(cat.total_income)
|
||||
: "--"}
|
||||
</td>
|
||||
<td style={{ textAlign: "right", color: "var(--danger)" }}>
|
||||
<td
|
||||
style={{ textAlign: "right", color: "var(--danger)" }}
|
||||
>
|
||||
{cat.total_expense > 0
|
||||
? formatAmount(-cat.total_expense)
|
||||
: "--"}
|
||||
@@ -368,11 +497,12 @@ export default function Dashboard() {
|
||||
</td>
|
||||
<td style={{ fontSize: 12, maxWidth: 180 }}>
|
||||
{cat.max_income ? (
|
||||
<span>
|
||||
<span
|
||||
title={`${cat.max_income.counterparty || ""} ${cat.max_income.ai_description || ""}`}
|
||||
>
|
||||
<span
|
||||
style={{ color: "var(--success)", fontWeight: 500 }}
|
||||
style={{
|
||||
color: "var(--success)",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{formatAmount(cat.max_income.amount)}
|
||||
</span>
|
||||
@@ -393,11 +523,12 @@ export default function Dashboard() {
|
||||
</td>
|
||||
<td style={{ fontSize: 12, maxWidth: 180 }}>
|
||||
{cat.max_expense ? (
|
||||
<span>
|
||||
<span
|
||||
title={`${cat.max_expense.counterparty || ""} ${cat.max_expense.ai_description || ""}`}
|
||||
>
|
||||
<span
|
||||
style={{ color: "var(--danger)", fontWeight: 500 }}
|
||||
style={{
|
||||
color: "var(--danger)",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{formatAmount(cat.max_expense.amount)}
|
||||
</span>
|
||||
@@ -417,14 +548,15 @@ export default function Dashboard() {
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无数据,请先导入账单</p>
|
||||
<p>暂无数据</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+17
-25
@@ -9,7 +9,13 @@ import {
|
||||
X,
|
||||
Info,
|
||||
} from "lucide-react";
|
||||
import { getSources, deleteSource } from "../hooks/useApi";
|
||||
import {
|
||||
getSources,
|
||||
deleteSource,
|
||||
uploadFile,
|
||||
confirmUpload,
|
||||
cancelUpload,
|
||||
} from "../hooks/useApi";
|
||||
|
||||
const SOURCE_TYPES = [
|
||||
{
|
||||
@@ -40,7 +46,6 @@ const SOURCE_TYPES = [
|
||||
|
||||
const ALLOWED_EXTS = ["csv", "txt", "xlsx", "xls"];
|
||||
|
||||
// Toast 组件
|
||||
function Toast({ message, type, onClose }) {
|
||||
useEffect(() => {
|
||||
const t = setTimeout(onClose, 3000);
|
||||
@@ -137,15 +142,10 @@ export default function Import() {
|
||||
formData.append("file", file);
|
||||
formData.append("source_type", sourceType);
|
||||
formData.append("source_name", sourceType);
|
||||
const res = await fetch("/api/upload", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "解析失败");
|
||||
const data = await uploadFile(formData);
|
||||
setPreview(data);
|
||||
} catch (err) {
|
||||
setError(err.message || "上传失败");
|
||||
setError(err.response?.data?.error || err.message || "上传失败");
|
||||
}
|
||||
setUploading(false);
|
||||
}
|
||||
@@ -154,13 +154,7 @@ export default function Import() {
|
||||
if (!preview?.tempId) return;
|
||||
setConfirming(true);
|
||||
try {
|
||||
const res = await fetch("/api/upload/confirm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tempId: preview.tempId }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "导入失败");
|
||||
const data = await confirmUpload(preview.tempId);
|
||||
setPreview(null);
|
||||
showToast(
|
||||
`导入成功!写入 ${data.inserted} 条${data.skipped > 0 ? ",跳过 " + data.skipped + " 条重复" : ""}`,
|
||||
@@ -168,18 +162,19 @@ export default function Import() {
|
||||
);
|
||||
loadSources();
|
||||
} catch (err) {
|
||||
showToast("导入失败: " + err.message, "error");
|
||||
showToast(
|
||||
"导入失败: " + (err.response?.data?.error || err.message),
|
||||
"error",
|
||||
);
|
||||
}
|
||||
setConfirming(false);
|
||||
}
|
||||
|
||||
async function handleCancel() {
|
||||
if (preview?.tempId) {
|
||||
await fetch("/api/upload/cancel", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tempId: preview.tempId }),
|
||||
});
|
||||
try {
|
||||
await cancelUpload(preview.tempId);
|
||||
} catch (e) {}
|
||||
}
|
||||
setPreview(null);
|
||||
}
|
||||
@@ -215,7 +210,6 @@ export default function Import() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Toast */}
|
||||
{toast && (
|
||||
<Toast
|
||||
key={toast.key}
|
||||
@@ -389,7 +383,6 @@ export default function Import() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 确认导入弹框 */}
|
||||
{preview && (
|
||||
<div className="modal-overlay">
|
||||
<div className="modal" style={{ maxWidth: 480 }}>
|
||||
@@ -500,7 +493,6 @@ export default function Import() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 删除确认弹框 */}
|
||||
{deleteTarget && (
|
||||
<div className="modal-overlay">
|
||||
<div className="modal" style={{ maxWidth: 400 }}>
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { LogIn, UserPlus, AlertCircle } from 'lucide-react';
|
||||
|
||||
export default function Login() {
|
||||
const { login, register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [mode, setMode] = useState('login'); // 'login' | 'register'
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [nickname, setNickname] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
function switchMode() {
|
||||
setMode(mode === 'login' ? 'register' : 'login');
|
||||
setError('');
|
||||
}
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!username.trim() || !password.trim()) {
|
||||
setError('请填写用户名和密码');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
await login(username.trim(), password);
|
||||
} else {
|
||||
await register(username.trim(), password, nickname.trim() || username.trim());
|
||||
}
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
const msg = err.response?.data?.error || err.message || '操作失败';
|
||||
setError(msg);
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
|
||||
padding: 20,
|
||||
}}>
|
||||
<div style={{
|
||||
background: 'white',
|
||||
borderRadius: 16,
|
||||
padding: 40,
|
||||
width: '100%',
|
||||
maxWidth: 400,
|
||||
boxShadow: '0 20px 60px rgba(0,0,0,0.15)',
|
||||
}}>
|
||||
{/* Logo */}
|
||||
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
||||
<div style={{ fontSize: 48, marginBottom: 8 }}>💰</div>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>Reco</h1>
|
||||
<p style={{ fontSize: 13, color: '#64748b', marginTop: 4 }}>
|
||||
银行流水对账分析系统
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div style={{
|
||||
marginBottom: 16,
|
||||
padding: '10px 14px',
|
||||
background: '#fef2f2',
|
||||
borderRadius: 8,
|
||||
color: '#ef4444',
|
||||
fontSize: 13,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
}}>
|
||||
<AlertCircle size={16} />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>
|
||||
用户名
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="请输入用户名(3-32位)"
|
||||
autoFocus
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 14px',
|
||||
border: '1px solid #e2e8f0',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
onFocus={(e) => { e.target.style.borderColor = '#818cf8'; e.target.style.boxShadow = '0 0 0 3px #eef2ff'; }}
|
||||
onBlur={(e) => { e.target.style.borderColor = '#e2e8f0'; e.target.style.boxShadow = 'none'; }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>
|
||||
密码
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={mode === 'register' ? '至少6个字符' : '请输入密码'}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 14px',
|
||||
border: '1px solid #e2e8f0',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
onFocus={(e) => { e.target.style.borderColor = '#818cf8'; e.target.style.boxShadow = '0 0 0 3px #eef2ff'; }}
|
||||
onBlur={(e) => { e.target.style.borderColor = '#e2e8f0'; e.target.style.boxShadow = 'none'; }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mode === 'register' && (
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>
|
||||
昵称 <span style={{ color: '#94a3b8', fontWeight: 400 }}>(可选)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={nickname}
|
||||
onChange={(e) => setNickname(e.target.value)}
|
||||
placeholder="显示名称,默认为用户名"
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 14px',
|
||||
border: '1px solid #e2e8f0',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
onFocus={(e) => { e.target.style.borderColor = '#818cf8'; e.target.style.boxShadow = '0 0 0 3px #eef2ff'; }}
|
||||
onBlur={(e) => { e.target.style.borderColor = '#e2e8f0'; e.target.style.boxShadow = 'none'; }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '12px',
|
||||
background: loading ? '#a5b4fc' : '#4f46e5',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
fontSize: 15,
|
||||
fontWeight: 600,
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
marginTop: 6,
|
||||
}}
|
||||
>
|
||||
{mode === 'login' ? <LogIn size={18} /> : <UserPlus size={18} />}
|
||||
{loading ? '处理中...' : mode === 'login' ? '登录' : '注册'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Switch mode */}
|
||||
<div style={{ textAlign: 'center', marginTop: 20, fontSize: 13, color: '#64748b' }}>
|
||||
{mode === 'login' ? '还没有账号?' : '已有账号?'}
|
||||
<button
|
||||
onClick={switchMode}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
color: '#4f46e5',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
marginLeft: 4,
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
{mode === 'login' ? '注册新账号' : '去登录'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+115
-35
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Edit3, Loader2 } from "lucide-react";
|
||||
import React, { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { Edit3, Loader2, Check, X } from "lucide-react";
|
||||
import {
|
||||
getDeals,
|
||||
updateDeal,
|
||||
@@ -22,14 +22,25 @@ export default function Review() {
|
||||
const [editingDeal, setEditingDeal] = useState(null);
|
||||
const [showReviewed, setShowReviewed] = useState(true);
|
||||
const [keyword, setKeyword] = useState("");
|
||||
const [debouncedKeyword, setDebouncedKeyword] = useState("");
|
||||
const [confirmingId, setConfirmingId] = useState(null);
|
||||
const sentinelRef = useRef(null);
|
||||
const debounceRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
}, []);
|
||||
|
||||
// 搜索防抖 300ms
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => setDebouncedKeyword(keyword), 300);
|
||||
return () => clearTimeout(debounceRef.current);
|
||||
}, [keyword]);
|
||||
|
||||
useEffect(() => {
|
||||
loadReviewDeals(1, false);
|
||||
}, [showReviewed, keyword]);
|
||||
}, [showReviewed, debouncedKeyword]);
|
||||
|
||||
async function loadCategories() {
|
||||
try {
|
||||
@@ -52,11 +63,12 @@ export default function Review() {
|
||||
min_amount: 100,
|
||||
limit: PAGE_SIZE,
|
||||
page: p || 1,
|
||||
sort_by: "amount",
|
||||
// 按金额绝对值从大到小排序(收/支混排)
|
||||
sort_by: "abs_amount",
|
||||
sort_order: "DESC",
|
||||
};
|
||||
if (!showReviewed) params.reviewed = 0;
|
||||
if (keyword) params.keyword = keyword;
|
||||
if (debouncedKeyword) params.keyword = debouncedKeyword;
|
||||
|
||||
const result = await getDeals(params);
|
||||
if (append) {
|
||||
@@ -90,10 +102,24 @@ export default function Review() {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function handleLoadMore() {
|
||||
const handleLoadMore = useCallback(() => {
|
||||
if (loadingMore || page >= totalPages) return;
|
||||
loadReviewDeals(page + 1, true);
|
||||
}
|
||||
}, [loadingMore, page, totalPages, showReviewed, debouncedKeyword]);
|
||||
|
||||
// 自动滚动加载:哨兵元素进入视口时触发
|
||||
useEffect(() => {
|
||||
const sentinel = sentinelRef.current;
|
||||
if (!sentinel) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0].isIntersecting) handleLoadMore();
|
||||
},
|
||||
{ rootMargin: "200px" },
|
||||
);
|
||||
observer.observe(sentinel);
|
||||
return () => observer.disconnect();
|
||||
}, [handleLoadMore]);
|
||||
|
||||
async function handleUpdateDeal(id, updates) {
|
||||
try {
|
||||
@@ -103,6 +129,16 @@ export default function Review() {
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
// 行内快速确认:信任当前AI分类,一键标记已确认
|
||||
async function handleQuickConfirm(deal) {
|
||||
setConfirmingId(deal.id);
|
||||
try {
|
||||
await updateDeal(deal.id, { reviewed: 1 });
|
||||
loadReviewDeals(1, false);
|
||||
} catch (err) {}
|
||||
setConfirmingId(null);
|
||||
}
|
||||
|
||||
const hasMore = page < totalPages;
|
||||
|
||||
return (
|
||||
@@ -169,7 +205,7 @@ export default function Review() {
|
||||
{deals.map((deal) => (
|
||||
<div
|
||||
key={deal.id}
|
||||
className={`review-item ${deal.reviewed ? "reviewed" : ""}`}
|
||||
className={`review-item${deal.reviewed ? " reviewed" : ""}${deal.direction === "income" ? " income-border" : " expense-border"}`}
|
||||
>
|
||||
<div
|
||||
className={`amount-col ${deal.direction === "income" ? "stat-value income" : "stat-value expense"}`}
|
||||
@@ -184,17 +220,22 @@ export default function Review() {
|
||||
{formatDate(deal.deal_date)} ·
|
||||
{deal.counterparty && <span> {deal.counterparty} ·</span>}
|
||||
{deal.category && (
|
||||
<span
|
||||
className="tag tag-matched"
|
||||
style={{ marginLeft: 4 }}
|
||||
>
|
||||
{deal.category}
|
||||
</span>
|
||||
<span className="tag tag-matched">{deal.category}</span>
|
||||
)}
|
||||
{deal.reviewed && (
|
||||
<span style={{ marginLeft: 6, color: "var(--success)" }}>
|
||||
{deal.reviewed === 1 ? (
|
||||
<span
|
||||
className="tag tag-income"
|
||||
style={{ marginLeft: 6 }}
|
||||
>
|
||||
✓ 已确认
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className="tag tag-unreviewed"
|
||||
style={{ marginLeft: 6 }}
|
||||
>
|
||||
待确认
|
||||
</span>
|
||||
)}
|
||||
{deal.match_count > 1 && (
|
||||
<span
|
||||
@@ -215,6 +256,23 @@ export default function Review() {
|
||||
{deal.transactions.length}笔
|
||||
</span>
|
||||
)}
|
||||
{deal.reviewed !== 1 && (
|
||||
<button
|
||||
className="btn btn-success btn-sm"
|
||||
onClick={() => handleQuickConfirm(deal)}
|
||||
disabled={confirmingId === deal.id}
|
||||
>
|
||||
{confirmingId === deal.id ? (
|
||||
<Loader2
|
||||
size={12}
|
||||
style={{ animation: "spin 0.8s linear infinite" }}
|
||||
/>
|
||||
) : (
|
||||
<Check size={12} />
|
||||
)}
|
||||
确认
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => setEditingDeal({ ...deal })}
|
||||
@@ -225,29 +283,40 @@ export default function Review() {
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Load More */}
|
||||
{/* 自动加载哨兵 */}
|
||||
{hasMore && (
|
||||
<div style={{ textAlign: "center", padding: "16px 0 4px" }}>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
style={{ minWidth: 160 }}
|
||||
<div
|
||||
ref={sentinelRef}
|
||||
style={{ textAlign: "center", padding: "24px 0 4px" }}
|
||||
>
|
||||
{loadingMore && (
|
||||
<span
|
||||
style={{ fontSize: 13, color: "var(--text-secondary)" }}
|
||||
>
|
||||
{loadingMore ? (
|
||||
<>
|
||||
<Loader2
|
||||
size={14}
|
||||
style={{ animation: "spin 0.8s linear infinite" }}
|
||||
/>{" "}
|
||||
加载中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
加载更多({deals.length} / {total})
|
||||
</>
|
||||
style={{
|
||||
animation: "spin 0.8s linear infinite",
|
||||
marginRight: 6,
|
||||
verticalAlign: "middle",
|
||||
}}
|
||||
/>
|
||||
加载中...({deals.length} / {total})
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* 全部加载完成 */}
|
||||
{!hasMore && deals.length > 0 && (
|
||||
<div
|
||||
style={{
|
||||
textAlign: "center",
|
||||
padding: "24px 0 4px",
|
||||
fontSize: 13,
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
已全部加载 · 共 {total} 笔
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -426,6 +495,17 @@ export default function Review() {
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={() =>
|
||||
handleUpdateDeal(editingDeal.id, {
|
||||
category: editingDeal.category,
|
||||
ai_description: editingDeal.ai_description,
|
||||
})
|
||||
}
|
||||
>
|
||||
仅保存
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={() =>
|
||||
@@ -436,7 +516,7 @@ export default function Review() {
|
||||
})
|
||||
}
|
||||
>
|
||||
保存并确认
|
||||
<Check size={14} /> 保存并确认
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+409
-51
@@ -1,64 +1,223 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw, X } from 'lucide-react';
|
||||
import { getConfig, updateConfig, testLLM, getCategories, updateCategory, createCategory, deleteCategory } from '../hooks/useApi';
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw, X } from "lucide-react";
|
||||
import {
|
||||
getConfig,
|
||||
updateConfig,
|
||||
testLLM,
|
||||
getCategories,
|
||||
updateCategory,
|
||||
createCategory,
|
||||
deleteCategory,
|
||||
classifyTransactions,
|
||||
} from "../hooks/useApi";
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [config, setConfig] = useState({ llm_api_key: '', llm_base_url: 'https://api.openai.com/v1', llm_model: 'gpt-4o-mini' });
|
||||
const [config, setConfig] = useState({
|
||||
llm_api_key: "",
|
||||
llm_base_url: "https://api.openai.com/v1",
|
||||
llm_model: "gpt-4o-mini",
|
||||
});
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [llmStatus, setLLMStatus] = useState(null);
|
||||
const [testingLlm, setTestingLlm] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editingCat, setEditingCat] = useState(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [newCat, setNewCat] = useState({ name: '', keywords: '' });
|
||||
const [newCat, setNewCat] = useState({ name: "", keywords: "" });
|
||||
const [reclassifying, setReclassifying] = useState(false);
|
||||
const [reclassifyMsg, setReclassifyMsg] = useState(null);
|
||||
|
||||
useEffect(() => { loadAll(); }, []);
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
|
||||
async function loadAll() {
|
||||
try { const [cfg, cats] = await Promise.all([getConfig(), getCategories()]); setConfig(prev => ({ ...prev, ...cfg })); setCategories(cats); } catch (err) {}
|
||||
try {
|
||||
const [cfg, cats] = await Promise.all([getConfig(), getCategories()]);
|
||||
setConfig((prev) => ({ ...prev, ...cfg }));
|
||||
setCategories(cats);
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleSaveConfig() { setSaving(true); try { await updateConfig(config); alert('保存成功!'); } catch (err) {} setSaving(false); }
|
||||
async function handleSaveConfig() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateConfig(config);
|
||||
alert("保存成功!");
|
||||
} catch (err) {}
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
async function handleTestLLM() {
|
||||
setTestingLlm(true); setLLMStatus(null);
|
||||
setTestingLlm(true);
|
||||
setLLMStatus(null);
|
||||
await updateConfig(config);
|
||||
try { const r = await testLLM(); setLLMStatus({ success: true, message: `连接成功!模型: ${r.model}, 回复: ${r.reply}` }); }
|
||||
catch (err) { setLLMStatus({ success: false, message: err.response?.data?.error || err.message }); }
|
||||
try {
|
||||
const r = await testLLM();
|
||||
setLLMStatus({
|
||||
success: true,
|
||||
message: `连接成功!模型: ${r.model}, 回复: ${r.reply}`,
|
||||
});
|
||||
} catch (err) {
|
||||
setLLMStatus({
|
||||
success: false,
|
||||
message: err.response?.data?.error || err.message,
|
||||
});
|
||||
}
|
||||
setTestingLlm(false);
|
||||
}
|
||||
|
||||
async function handleUpdateCategory(id, field, value) { try { await updateCategory(id, { [field]: value }); loadAll(); } catch (err) {} }
|
||||
async function handleUpdateCategory(id, field, value) {
|
||||
try {
|
||||
const result = await updateCategory(id, { [field]: value });
|
||||
loadAll();
|
||||
if (result.affectedDeals > 0) {
|
||||
setReclassifyMsg({
|
||||
type: "info",
|
||||
text: `分类名称已更新,${result.affectedDeals} 条历史交易记录已自动同步新名称。`,
|
||||
});
|
||||
setTimeout(() => setReclassifyMsg(null), 6000);
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleAddCategory() {
|
||||
if (!newCat.name.trim()) return;
|
||||
try {
|
||||
await createCategory({ name: newCat.name.trim(), keywords: newCat.keywords.split(',').map(k => k.trim()).filter(Boolean) });
|
||||
setNewCat({ name: '', keywords: '' }); setAdding(false); loadAll();
|
||||
await createCategory({
|
||||
name: newCat.name.trim(),
|
||||
keywords: newCat.keywords
|
||||
.split(",")
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
setNewCat({ name: "", keywords: "" });
|
||||
setAdding(false);
|
||||
loadAll();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleDeleteCategory(id, name) {
|
||||
if (!window.confirm(`确定删除分类「${name}」吗?`)) return;
|
||||
try { await deleteCategory(id); loadAll(); } catch (err) {}
|
||||
if (
|
||||
!window.confirm(
|
||||
`确定删除分类「${name}」吗?\n\n删除后,使用该分类的历史交易将标记为"待分类",可重新进行AI分类。`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
const result = await deleteCategory(id);
|
||||
loadAll();
|
||||
if (result.affectedDeals > 0) {
|
||||
const ids = result.affectedIds || [];
|
||||
setReclassifyMsg({
|
||||
type: "warning",
|
||||
text: `已删除「${name}」,${result.affectedDeals} 条历史交易(${ids.length} 笔deal)已重置为待分类状态。`,
|
||||
ids,
|
||||
});
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleReclassify(ids) {
|
||||
setReclassifying(true);
|
||||
setReclassifyMsg(null);
|
||||
try {
|
||||
const result = await classifyTransactions(ids);
|
||||
setReclassifyMsg({
|
||||
type: "success",
|
||||
text: `重分类完成!${result.classified} 条交易已重新分类(来源: ${result.source === "llm" ? "AI" : "规则匹配"})。`,
|
||||
});
|
||||
loadAll();
|
||||
} catch (err) {
|
||||
setReclassifyMsg({
|
||||
type: "error",
|
||||
text: "重分类失败: " + (err.response?.data?.error || err.message),
|
||||
});
|
||||
}
|
||||
setReclassifying(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header"><h2>⚙️ 系统设置</h2><p>配置大模型API及管理交易分类</p></div>
|
||||
<div className="page-header">
|
||||
<h2>⚙️ 系统设置</h2>
|
||||
<p>配置大模型API及管理交易分类</p>
|
||||
</div>
|
||||
|
||||
{/* LLM Config */}
|
||||
<div className="card">
|
||||
<div className="card-header"><h3>🤖 大模型配置</h3><span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>支持 OpenAI 兼容API</span></div>
|
||||
<div className="form-group"><label>API Key</label><input type="password" className="form-input" placeholder="sk-..." value={config.llm_api_key || ''} onChange={e => setConfig({ ...config, llm_api_key: e.target.value })} /></div>
|
||||
<div className="form-group"><label>API Base URL</label><input type="text" className="form-input" placeholder="https://api.openai.com/v1" value={config.llm_base_url || ''} onChange={e => setConfig({ ...config, llm_base_url: e.target.value })} /></div>
|
||||
<div className="form-group"><label>模型名称</label><input type="text" className="form-input" placeholder="gpt-4o-mini" value={config.llm_model || ''} onChange={e => setConfig({ ...config, llm_model: e.target.value })} /></div>
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<button className="btn btn-primary" onClick={handleSaveConfig} disabled={saving}><Save size={16} /> {saving ? '保存中...' : '保存配置'}</button>
|
||||
<button className="btn btn-secondary" onClick={handleTestLLM} disabled={testingLlm}><Zap size={16} /> {testingLlm ? '测试中...' : '测试连接'}</button>
|
||||
<div className="card-header">
|
||||
<h3>🤖 大模型配置</h3>
|
||||
<span style={{ fontSize: 12, color: "var(--text-secondary)" }}>
|
||||
支持 OpenAI 兼容API
|
||||
</span>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>API Key</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
placeholder="sk-..."
|
||||
value={config.llm_api_key || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_api_key: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>API Base URL</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
value={config.llm_base_url || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_base_url: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>模型名称</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="gpt-4o-mini"
|
||||
value={config.llm_model || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_model: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 10 }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleSaveConfig}
|
||||
disabled={saving}
|
||||
>
|
||||
<Save size={16} /> {saving ? "保存中..." : "保存配置"}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={handleTestLLM}
|
||||
disabled={testingLlm}
|
||||
>
|
||||
<Zap size={16} /> {testingLlm ? "测试中..." : "测试连接"}
|
||||
</button>
|
||||
</div>
|
||||
{llmStatus && (
|
||||
<div style={{ marginTop: 16, padding: '12px 16px', borderRadius: 8, fontSize: 14, background: llmStatus.success ? '#f0fdf4' : '#fef2f2', color: llmStatus.success ? 'var(--success)' : 'var(--danger)', border: `1px solid ${llmStatus.success ? '#bbf7d0' : '#fecaca'}` }}>{llmStatus.message}</div>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
padding: "12px 16px",
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
background: llmStatus.success ? "#f0fdf4" : "#fef2f2",
|
||||
color: llmStatus.success ? "var(--success)" : "var(--danger)",
|
||||
border: `1px solid ${llmStatus.success ? "#bbf7d0" : "#fecaca"}`,
|
||||
}}
|
||||
>
|
||||
{llmStatus.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -66,53 +225,252 @@ export default function SettingsPage() {
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 分类管理</h3>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => setAdding(true)}><Plus size={14} /> 新增</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}><RefreshCw size={14} /> 刷新</button>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => setAdding(true)}
|
||||
>
|
||||
<Plus size={14} /> 新增
|
||||
</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}>
|
||||
<RefreshCw size={14} /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>管理交易分类及关键词,AI 根据关键词自动分类</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 13,
|
||||
color: "var(--text-secondary)",
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
管理交易分类及关键词,AI 根据关键词自动分类。
|
||||
<br />
|
||||
重命名分类会自动同步历史数据;删除分类后历史交易将标记为待分类。
|
||||
</div>
|
||||
|
||||
{/* Reclassify notification */}
|
||||
{reclassifyMsg && (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: "12px 16px",
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
background:
|
||||
reclassifyMsg.type === "success"
|
||||
? "#f0fdf4"
|
||||
: reclassifyMsg.type === "warning"
|
||||
? "#fffbeb"
|
||||
: reclassifyMsg.type === "error"
|
||||
? "#fef2f2"
|
||||
: "#eff6ff",
|
||||
color:
|
||||
reclassifyMsg.type === "success"
|
||||
? "var(--success)"
|
||||
: reclassifyMsg.type === "warning"
|
||||
? "#92400e"
|
||||
: reclassifyMsg.type === "error"
|
||||
? "var(--danger)"
|
||||
: "var(--text-primary)",
|
||||
border: `1px solid ${reclassifyMsg.type === "success" ? "#bbf7d0" : reclassifyMsg.type === "warning" ? "#fde68a" : reclassifyMsg.type === "error" ? "#fecaca" : "#bfdbfe"}`,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<span>{reclassifyMsg.text}</span>
|
||||
{reclassifyMsg.ids && reclassifyMsg.ids.length > 0 && (
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => handleReclassify(reclassifyMsg.ids)}
|
||||
disabled={reclassifying}
|
||||
style={{ whiteSpace: "nowrap" }}
|
||||
>
|
||||
<Zap size={12} /> {reclassifying ? "重分类中..." : "立即重分类"}
|
||||
</button>
|
||||
)}
|
||||
{!reclassifyMsg.ids && (
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => setReclassifyMsg(null)}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New category inline form */}
|
||||
{adding && (
|
||||
<div style={{ display: 'flex', gap: 10, marginBottom: 12, padding: '10px 12px', background: 'var(--primary-bg)', borderRadius: 8, alignItems: 'center' }}>
|
||||
<input type="text" className="form-input" style={{ width: 130 }} placeholder="分类名称" value={newCat.name} onChange={e => setNewCat({ ...newCat, name: e.target.value })} />
|
||||
<input type="text" className="form-input" style={{ flex: 1 }} placeholder="关键词,逗号,分隔" value={newCat.keywords} onChange={e => setNewCat({ ...newCat, keywords: e.target.value })} />
|
||||
<button className="btn btn-primary btn-sm" onClick={handleAddCategory}><Plus size={12} /> 添加</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => { setAdding(false); setNewCat({ name: '', keywords: '' }); }}><X size={12} /></button>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: 10,
|
||||
marginBottom: 12,
|
||||
padding: "10px 12px",
|
||||
background: "var(--primary-bg)",
|
||||
borderRadius: 8,
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: 130 }}
|
||||
placeholder="分类名称"
|
||||
value={newCat.name}
|
||||
onChange={(e) => setNewCat({ ...newCat, name: e.target.value })}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ flex: 1 }}
|
||||
placeholder="关键词,逗号,分隔"
|
||||
value={newCat.keywords}
|
||||
onChange={(e) =>
|
||||
setNewCat({ ...newCat, keywords: e.target.value })
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={handleAddCategory}
|
||||
>
|
||||
<Plus size={12} /> 添加
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => {
|
||||
setAdding(false);
|
||||
setNewCat({ name: "", keywords: "" });
|
||||
}}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead><tr><th style={{ width: 50 }}>ID</th><th>分类名称</th><th>关键词</th><th style={{ width: 160 }}>操作</th></tr></thead>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 50 }}>ID</th>
|
||||
<th>分类名称</th>
|
||||
<th>关键词</th>
|
||||
<th style={{ width: 160 }}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categories.map(cat => (
|
||||
{categories.map((cat) => (
|
||||
<tr key={cat.id}>
|
||||
<td>{cat.id}</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: 120 }} value={editingCat.name} onChange={e => setEditingCat({ ...editingCat, name: e.target.value })} />
|
||||
: <strong>{cat.name}</strong>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: '100%' }} value={editingCat.keywords} onChange={e => setEditingCat({ ...editingCat, keywords: e.target.value })} />
|
||||
: <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{JSON.parse(cat.keywords || '[]').join(', ') || '(无)'}</span>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: 120 }}
|
||||
value={editingCat.name}
|
||||
onChange={(e) =>
|
||||
setEditingCat({ ...editingCat, name: e.target.value })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<strong>{cat.name}</strong>
|
||||
{cat.is_locked ? (
|
||||
<span
|
||||
className="tag tag-matched"
|
||||
style={{ marginLeft: 6, fontSize: 11 }}
|
||||
title="内置分类,不可修改/删除"
|
||||
>
|
||||
🔒 内置
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={async () => { await handleUpdateCategory(cat.id, 'name', editingCat.name); await handleUpdateCategory(cat.id, 'keywords', editingCat.keywords.split(',').map(k => k.trim()).filter(Boolean)); setEditingCat(null); }}><Save size={12} /> 保存</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat(null)}>取消</button>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: "100%" }}
|
||||
value={editingCat.keywords}
|
||||
onChange={(e) =>
|
||||
setEditingCat({
|
||||
...editingCat,
|
||||
keywords: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
style={{ fontSize: 12, color: "var(--text-secondary)" }}
|
||||
>
|
||||
{JSON.parse(cat.keywords || "[]").join(", ") ||
|
||||
"(无)"}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={async () => {
|
||||
await handleUpdateCategory(
|
||||
cat.id,
|
||||
"name",
|
||||
editingCat.name,
|
||||
);
|
||||
await handleUpdateCategory(
|
||||
cat.id,
|
||||
"keywords",
|
||||
editingCat.keywords
|
||||
.split(",")
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
setEditingCat(null);
|
||||
}}
|
||||
>
|
||||
<Save size={12} /> 保存
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => setEditingCat(null)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat({ ...cat, keywords: JSON.parse(cat.keywords || '[]').join(', ') })}>编辑</button>
|
||||
<button className="btn btn-danger btn-sm" onClick={() => handleDeleteCategory(cat.id, cat.name)}><Trash2 size={12} /></button>
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
disabled={!!cat.is_locked}
|
||||
title={cat.is_locked ? "内置分类不可修改" : "编辑"}
|
||||
onClick={() =>
|
||||
setEditingCat({
|
||||
...cat,
|
||||
keywords: JSON.parse(cat.keywords || "[]").join(
|
||||
", ",
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
disabled={!!cat.is_locked}
|
||||
title={cat.is_locked ? "内置分类不可删除" : "删除"}
|
||||
onClick={() => handleDeleteCategory(cat.id, cat.name)}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
RotateCcw,
|
||||
Link2,
|
||||
@@ -14,8 +14,12 @@ import {
|
||||
} from "lucide-react";
|
||||
import {
|
||||
getTransactions,
|
||||
getDeals,
|
||||
updateDeal,
|
||||
clearDeals,
|
||||
runReconciliation,
|
||||
classifyTransactions,
|
||||
classifyAll,
|
||||
getClassifyStatus,
|
||||
formatAmount,
|
||||
SOURCE_TYPE_MAP,
|
||||
getCategories,
|
||||
@@ -76,6 +80,8 @@ export default function Transactions() {
|
||||
const [clearConfirm, setClearConfirm] = useState(false);
|
||||
const [editingDeal, setEditingDeal] = useState(null);
|
||||
const [dealFilters, setDealFilters] = useState({ ...DEAL_FILTER_DEFAULT });
|
||||
const classifyPollRef = useRef(null);
|
||||
const reloadRef = useRef(null);
|
||||
|
||||
/* sort helpers */
|
||||
function dealToggleSort(field) {
|
||||
@@ -137,39 +143,66 @@ export default function Transactions() {
|
||||
setToast({ message: msg, type, key: Date.now() });
|
||||
}
|
||||
|
||||
/* restore classify progress */
|
||||
useEffect(() => {
|
||||
const saved = sessionStorage.getItem("classifyTask");
|
||||
if (!saved) return;
|
||||
const task = JSON.parse(saved);
|
||||
if (Date.now() - task.ts > 300000) {
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
return;
|
||||
function stopClassifyPoll() {
|
||||
if (classifyPollRef.current) {
|
||||
clearInterval(classifyPollRef.current);
|
||||
classifyPollRef.current = null;
|
||||
}
|
||||
setClassifying(true);
|
||||
setClassifyProgress(task.progress || 0);
|
||||
const poll = setInterval(async () => {
|
||||
}
|
||||
|
||||
// 轮询服务端全量分类进度
|
||||
function pollClassifyStatus() {
|
||||
const tick = async () => {
|
||||
try {
|
||||
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;
|
||||
setClassifyProgress(Math.min(Math.max(p, 0), 100));
|
||||
if (total <= 0 || p >= 100) {
|
||||
clearInterval(poll);
|
||||
const s = await getClassifyStatus();
|
||||
if (s.running) {
|
||||
setClassifying(true);
|
||||
setClassifyProgress(
|
||||
s.total ? Math.min(100, Math.round((s.done / s.total) * 100)) : 0,
|
||||
);
|
||||
} else {
|
||||
stopClassifyPoll();
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
loadTransactions();
|
||||
setClassifyProgress(100);
|
||||
showToast("分类完成!", "success");
|
||||
if (reloadRef.current) reloadRef.current();
|
||||
}
|
||||
} catch (e) {
|
||||
clearInterval(poll);
|
||||
stopClassifyPoll();
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
}
|
||||
}, 10000);
|
||||
return () => clearInterval(poll);
|
||||
};
|
||||
stopClassifyPoll();
|
||||
classifyPollRef.current = setInterval(tick, 2000);
|
||||
tick();
|
||||
}
|
||||
|
||||
/* 保持 reload 回调最新,避免轮询里拿到旧 filters */
|
||||
useEffect(() => {
|
||||
reloadRef.current = () => {
|
||||
loadTransactions();
|
||||
loadDeals(dealFilters);
|
||||
};
|
||||
});
|
||||
|
||||
/* 恢复全量分类进度:任务在服务端后台执行,刷新页面后继续显示 */
|
||||
useEffect(() => {
|
||||
let stopped = false;
|
||||
(async () => {
|
||||
try {
|
||||
const s = await getClassifyStatus();
|
||||
if (stopped || !s.running) return;
|
||||
setClassifying(true);
|
||||
setClassifyProgress(
|
||||
s.total ? Math.min(100, Math.round((s.done / s.total) * 100)) : 0,
|
||||
);
|
||||
pollClassifyStatus();
|
||||
} catch (e) {}
|
||||
})();
|
||||
return () => {
|
||||
stopped = true;
|
||||
stopClassifyPoll();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -192,12 +225,10 @@ export default function Transactions() {
|
||||
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());
|
||||
const params = {};
|
||||
for (const [k, v] of Object.entries(f))
|
||||
if (v !== "" && v !== undefined) params[k] = v;
|
||||
setDeals(await getDeals(params));
|
||||
} catch (e) {}
|
||||
setDealLoading(false);
|
||||
}
|
||||
@@ -234,13 +265,9 @@ export default function Transactions() {
|
||||
async function handleUpdateDeal() {
|
||||
if (!editingDeal) return;
|
||||
try {
|
||||
await fetch("/api/deals/" + editingDeal.id, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
await updateDeal(editingDeal.id, {
|
||||
category: editingDeal.category,
|
||||
ai_description: editingDeal.ai_description,
|
||||
}),
|
||||
});
|
||||
setEditingDeal(null);
|
||||
loadDeals(dealFilters);
|
||||
@@ -252,8 +279,15 @@ export default function Transactions() {
|
||||
|
||||
async function handleClearDeals() {
|
||||
try {
|
||||
await fetch("/api/deals/clear", { method: "POST" });
|
||||
setDeals({ deals: [], total: 0, page: 1, totalPages: 0 });
|
||||
await clearDeals();
|
||||
setDeals({
|
||||
deals: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
totalPages: 0,
|
||||
totalIncome: 0,
|
||||
totalExpense: 0,
|
||||
});
|
||||
setClearConfirm(false);
|
||||
} catch (e) {}
|
||||
}
|
||||
@@ -273,67 +307,21 @@ export default function Transactions() {
|
||||
}
|
||||
|
||||
async function handleClassifyAll() {
|
||||
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 { ids, total } = await res.json();
|
||||
if (!ids.length) {
|
||||
const { total } = await classifyAll();
|
||||
if (!total) {
|
||||
showToast("所有交易分类均有效!", "info");
|
||||
setClassifying(false);
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
return;
|
||||
}
|
||||
sessionStorage.setItem(
|
||||
"classifyTask",
|
||||
JSON.stringify({ total, progress: 0, ts: Date.now() }),
|
||||
);
|
||||
// 分批并行处理(每批30条,最多2批同时进行)
|
||||
const B = 30;
|
||||
const CONCURRENCY = 4;
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
batches.push(ids.slice(i, i + B));
|
||||
}
|
||||
|
||||
let done = 0;
|
||||
let llmCount = 0;
|
||||
let rulesCount = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
chunk.map((batch) => classifyTransactions(batch)),
|
||||
);
|
||||
for (const r of results) {
|
||||
done += r.classified || 0;
|
||||
if (r.source === "llm") llmCount += r.classified || 0;
|
||||
else rulesCount += r.classified || 0;
|
||||
}
|
||||
const pct = Math.round((done / total) * 100);
|
||||
setClassifyProgress(pct);
|
||||
sessionStorage.setItem(
|
||||
"classifyTask",
|
||||
JSON.stringify({ total, progress: pct, ts: Date.now() }),
|
||||
);
|
||||
}
|
||||
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
const detail =
|
||||
llmCount > 0
|
||||
? `(LLM: ${llmCount},规则: ${rulesCount})`
|
||||
: `(规则匹配: ${rulesCount})`;
|
||||
showToast(`分类完成!共处理 ${total} 笔 ${detail}`, "success");
|
||||
loadTransactions();
|
||||
setClassifying(true);
|
||||
setClassifyProgress(0);
|
||||
pollClassifyStatus();
|
||||
} catch (e) {
|
||||
sessionStorage.removeItem("classifyTask");
|
||||
showToast("分类失败: " + (e.response?.data?.error || e.message), "error");
|
||||
showToast(
|
||||
"分类启动失败: " + (e.response?.data?.error || e.message),
|
||||
"error",
|
||||
);
|
||||
}
|
||||
setClassifying(false);
|
||||
}
|
||||
|
||||
/* ============================== RENDER ============================== */
|
||||
|
||||
Generated
+117
@@ -8,6 +8,7 @@
|
||||
"name": "reco",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.2.0",
|
||||
@@ -15,6 +16,7 @@
|
||||
"dayjs": "^1.11.13",
|
||||
"express": "^4.21.0",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"openai": "^4.73.0",
|
||||
"uuid": "^10.0.0",
|
||||
@@ -124,6 +126,15 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bcryptjs": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
||||
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"bin": {
|
||||
"bcrypt": "bin/bcrypt"
|
||||
}
|
||||
},
|
||||
"node_modules/better-sqlite3": {
|
||||
"version": "11.10.0",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
|
||||
@@ -244,6 +255,12 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
@@ -527,6 +544,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/ee-first/-/ee-first-1.1.1.tgz",
|
||||
@@ -962,6 +988,97 @@
|
||||
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^4.0.1",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"setup": "npm install && npm run install:all"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^11.10.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.2.0",
|
||||
@@ -20,6 +21,7 @@
|
||||
"dayjs": "^1.11.13",
|
||||
"express": "^4.21.0",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"openai": "^4.73.0",
|
||||
"uuid": "^10.0.0",
|
||||
|
||||
+157
-17
@@ -1,7 +1,11 @@
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
|
||||
const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
|
||||
const DB_PATH =
|
||||
process.env.RECO_DB_PATH || path.join(__dirname, "..", "data", "reco.db");
|
||||
|
||||
// 系统兜底分类:所有用户都不允许修改/删除
|
||||
const SYSTEM_LOCKED_CATEGORIES = ["其他杂项"];
|
||||
|
||||
const fs = require("fs");
|
||||
const dataDir = path.join(__dirname, "..", "data");
|
||||
@@ -22,6 +26,15 @@ function initDB() {
|
||||
const database = getDB();
|
||||
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sources (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_type TEXT NOT NULL,
|
||||
@@ -59,7 +72,7 @@ function initDB() {
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT,
|
||||
parent_id INTEGER,
|
||||
is_locked INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -77,11 +90,9 @@ function initDB() {
|
||||
description TEXT,
|
||||
match_count INTEGER DEFAULT 1,
|
||||
category TEXT,
|
||||
ai_category TEXT,
|
||||
ai_description TEXT,
|
||||
ai_confidence REAL,
|
||||
reviewed INTEGER DEFAULT 0,
|
||||
review_notes TEXT,
|
||||
reviewed_at DATETIME,
|
||||
tags TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -98,13 +109,38 @@ function initDB() {
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_date ON transactions(transaction_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_code ON transactions(transaction_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_amount ON transactions(amount);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_amount ON transactions(ABS(amount));
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_source ON transactions(source_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_matched ON transactions(matched_transaction_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_deal_date ON deals(deal_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_dt_deal ON deal_transactions(deal_id);
|
||||
`);
|
||||
|
||||
// 兼容旧库:为所有业务表添加 user_id 字段
|
||||
const tables = ["sources", "transactions", "deals", "categories"];
|
||||
for (const table of tables) {
|
||||
try {
|
||||
const cols = database
|
||||
.prepare("PRAGMA table_info(" + table + ")")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!cols.includes("user_id")) {
|
||||
database.exec(
|
||||
"ALTER TABLE " +
|
||||
table +
|
||||
" ADD COLUMN user_id INTEGER REFERENCES users(id)",
|
||||
);
|
||||
database.exec(
|
||||
"CREATE INDEX IF NOT EXISTS idx_" +
|
||||
table +
|
||||
"_user ON " +
|
||||
table +
|
||||
"(user_id)",
|
||||
);
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// 兼容旧库:为 deals 表添加新字段
|
||||
try {
|
||||
const dealCols = database
|
||||
@@ -129,13 +165,113 @@ function initDB() {
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// 仅首次初始化默认分类
|
||||
const catCount = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories")
|
||||
.get().c;
|
||||
if (catCount === 0) {
|
||||
// 兼容旧库:config 表 key PRIMARY KEY -> id + UNIQUE(key,user_id)
|
||||
try {
|
||||
const cfgCols = database
|
||||
.prepare("PRAGMA table_info(config)")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!cfgCols.includes("id")) {
|
||||
database.exec(`
|
||||
CREATE TABLE IF NOT EXISTS config_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
user_id INTEGER REFERENCES users(id),
|
||||
UNIQUE(key, user_id)
|
||||
);
|
||||
INSERT OR IGNORE INTO config_new (key, value, user_id)
|
||||
SELECT key, value, NULL FROM config;
|
||||
DROP TABLE config;
|
||||
ALTER TABLE config_new RENAME TO config;
|
||||
`);
|
||||
console.log("[Reco] config 表已迁移为 id+UNIQUE(key,user_id)");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Reco] config 迁移失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:分类锁定标记。
|
||||
// 内置基础分类(最初的 1-10 号)和系统兜底分类(其他杂项)不允许修改/删除。
|
||||
try {
|
||||
const catCols = database
|
||||
.prepare("PRAGMA table_info(categories)")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!catCols.includes("is_locked")) {
|
||||
database.exec(
|
||||
"ALTER TABLE categories ADD COLUMN is_locked INTEGER DEFAULT 0",
|
||||
);
|
||||
}
|
||||
database.prepare("UPDATE categories SET is_locked = 1 WHERE id <= 10").run();
|
||||
if (SYSTEM_LOCKED_CATEGORIES.length) {
|
||||
const ph = SYSTEM_LOCKED_CATEGORIES.map(() => "?").join(",");
|
||||
database
|
||||
.prepare(`UPDATE categories SET is_locked = 1 WHERE name IN (${ph})`)
|
||||
.run(...SYSTEM_LOCKED_CATEGORIES);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类锁定初始化失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:合并同名重复分类。
|
||||
// 老用户的历史分类 user_id 为 NULL,之后初始化默认分类时按 user_id 计数为 0,
|
||||
// 于是又插入了一整套默认分类,导致同名分类出现两份。
|
||||
// 合并策略:保留 id 最小的一行(通常是用户手工维护过的),关键词取并集,删除其余行。
|
||||
try {
|
||||
const dupGroups = database
|
||||
.prepare(
|
||||
`SELECT user_id, name, COUNT(*) AS c FROM categories
|
||||
GROUP BY user_id, name HAVING c > 1`,
|
||||
)
|
||||
.all();
|
||||
if (dupGroups.length) {
|
||||
const rowsStmt = database.prepare(
|
||||
"SELECT id, keywords FROM categories WHERE name = ? AND user_id IS ? ORDER BY id",
|
||||
);
|
||||
const setKeywords = database.prepare(
|
||||
"UPDATE categories SET keywords = ? WHERE id = ?",
|
||||
);
|
||||
const delCategory = database.prepare("DELETE FROM categories WHERE id = ?");
|
||||
database.transaction(() => {
|
||||
for (const g of dupGroups) {
|
||||
const rows = rowsStmt.all(g.name, g.user_id);
|
||||
const merged = [];
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const arr = JSON.parse(r.keywords || "[]");
|
||||
if (Array.isArray(arr))
|
||||
for (const k of arr)
|
||||
if (k && !merged.includes(k)) merged.push(k);
|
||||
} catch (e) {}
|
||||
}
|
||||
setKeywords.run(JSON.stringify(merged), rows[0].id);
|
||||
for (const r of rows.slice(1)) delCategory.run(r.id);
|
||||
}
|
||||
})();
|
||||
console.log(`[Reco] 已合并 ${dupGroups.length} 组重复分类`);
|
||||
}
|
||||
// 唯一索引:同一用户下不允许同名分类
|
||||
database.exec(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_categories_user_name ON categories(user_id, name)",
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类去重失败:", e.message);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
// 为新用户创建默认分类
|
||||
function initDefaultCategories(userId) {
|
||||
const database = getDB();
|
||||
const existing = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories WHERE user_id = ?")
|
||||
.get(userId).c;
|
||||
if (existing > 0) return;
|
||||
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords) VALUES (?, ?)",
|
||||
"INSERT OR IGNORE INTO categories (name, keywords, user_id, is_locked) VALUES (?, ?, ?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
@@ -159,12 +295,16 @@ function initDB() {
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1]));
|
||||
defaults.forEach((c) =>
|
||||
ins.run(
|
||||
c[0],
|
||||
c[1],
|
||||
userId,
|
||||
SYSTEM_LOCKED_CATEGORIES.includes(c[0]) ? 1 : 0,
|
||||
),
|
||||
);
|
||||
})();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB };
|
||||
module.exports = { getDB, initDB, initDefaultCategories };
|
||||
|
||||
+9
-3
@@ -8,10 +8,11 @@ process.noDeprecation = true;
|
||||
|
||||
const uploadRoutes = require("./routes/upload");
|
||||
const transactionRoutes = require("./routes/transactions");
|
||||
const classifyRoutes = require("./routes/classify");
|
||||
const statsRoutes = require("./routes/stats");
|
||||
const configRoutes = require("./routes/config");
|
||||
const dealsRoutes = require("./routes/deals");
|
||||
const authRoutes = require("./routes/auth");
|
||||
const { authMiddleware } = require("./middleware/auth");
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
@@ -20,10 +21,15 @@ const PORT = process.env.PORT || 3001;
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: "50mb" }));
|
||||
|
||||
// API routes
|
||||
// Auth routes(不受认证中间件限制)
|
||||
app.use("/api/auth", authRoutes);
|
||||
|
||||
// 全局认证中间件(auth 路由已在白名单中放行)
|
||||
app.use(authMiddleware);
|
||||
|
||||
// 业务 API routes(受认证保护)
|
||||
app.use("/api/upload", uploadRoutes);
|
||||
app.use("/api/transactions", transactionRoutes);
|
||||
app.use("/api/classify", classifyRoutes);
|
||||
app.use("/api/stats", statsRoutes);
|
||||
app.use("/api/config", configRoutes);
|
||||
app.use("/api/deals", dealsRoutes);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const JWT_SECRET =
|
||||
process.env.JWT_SECRET || "reco-jwt-secret-change-in-production";
|
||||
const JWT_EXPIRES_IN = "7d";
|
||||
|
||||
// 无需认证的公开路由
|
||||
const PUBLIC_PATHS = [
|
||||
"/api/auth/login",
|
||||
"/api/auth/register",
|
||||
"/api/auth/health",
|
||||
];
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
// 白名单放行
|
||||
if (
|
||||
PUBLIC_PATHS.includes(req.path) ||
|
||||
req.path.startsWith("/api/auth/health")
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith("Bearer ")) {
|
||||
return res.status(401).json({ error: "请先登录" });
|
||||
}
|
||||
|
||||
try {
|
||||
const token = header.split(" ")[1];
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.userId = decoded.userId;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: "登录已过期,请重新登录" });
|
||||
}
|
||||
}
|
||||
|
||||
function signToken(userId) {
|
||||
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||
}
|
||||
|
||||
module.exports = { authMiddleware, signToken, JWT_SECRET };
|
||||
@@ -0,0 +1,112 @@
|
||||
const express = require("express");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const { getDB, initDefaultCategories } = require("../db");
|
||||
const { signToken } = require("../middleware/auth");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/auth/register — 开放注册
|
||||
router.post("/register", (req, res) => {
|
||||
try {
|
||||
const { username, password, nickname } = req.body;
|
||||
|
||||
// 校验
|
||||
if (!username || username.length < 3 || username.length > 32) {
|
||||
return res.status(400).json({ error: "用户名需 3-32 个字符" });
|
||||
}
|
||||
if (!password || password.length < 6) {
|
||||
return res.status(400).json({ error: "密码至少 6 个字符" });
|
||||
}
|
||||
|
||||
const db = getDB();
|
||||
|
||||
// 查重
|
||||
const exists = db
|
||||
.prepare("SELECT id FROM users WHERE username = ?")
|
||||
.get(username);
|
||||
if (exists) {
|
||||
return res.status(409).json({ error: "用户名已存在" });
|
||||
}
|
||||
|
||||
// 哈希密码 & 插入
|
||||
const hashed = bcrypt.hashSync(password, 10);
|
||||
const result = db
|
||||
.prepare(
|
||||
"INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(username, hashed, nickname || username);
|
||||
|
||||
const userId = result.lastInsertRowid;
|
||||
|
||||
// 为新用户初始化默认分类
|
||||
initDefaultCategories(userId);
|
||||
|
||||
// 签发 Token
|
||||
const token = signToken(userId);
|
||||
|
||||
console.log(`[Reco] 新用户注册: ${username} (id=${userId})`);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
user: { id: userId, username, nickname: nickname || username },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 注册失败:", err);
|
||||
res.status(500).json({ error: "注册失败,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/login — 登录
|
||||
router.post("/login", (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: "请输入用户名和密码" });
|
||||
}
|
||||
|
||||
const db = getDB();
|
||||
const user = db
|
||||
.prepare("SELECT * FROM users WHERE username = ?")
|
||||
.get(username);
|
||||
|
||||
if (!user || !bcrypt.compareSync(password, user.password)) {
|
||||
return res.status(401).json({ error: "用户名或密码错误" });
|
||||
}
|
||||
|
||||
const token = signToken(user.id);
|
||||
|
||||
console.log(`[Reco] 用户登录: ${username} (id=${user.id})`);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
nickname: user.nickname || user.username,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 登录失败:", err);
|
||||
res.status(500).json({ error: "登录失败,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/auth/me — 获取当前用户信息
|
||||
router.get("/me", (req, res) => {
|
||||
try {
|
||||
const db = getDB();
|
||||
// 注意:这个路由需要通过中间件手动验证,因为它不在白名单
|
||||
const user = db
|
||||
.prepare("SELECT id, username, nickname, created_at FROM users WHERE id = ?")
|
||||
.get(req.userId);
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: "用户不存在" });
|
||||
}
|
||||
res.json(user);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: "获取用户信息失败" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,23 +0,0 @@
|
||||
const express = require("express");
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/classify - 对指定交易进行分类
|
||||
router.post("/", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
+166
-36
@@ -1,42 +1,82 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { loadConfig, saveConfig, getOpenAIClient, resetClient } = require('../services/llm');
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const router = express.Router();
|
||||
|
||||
// 从 DB 读取当前用户的 LLM 配置
|
||||
function loadUserLLMConfig(userId) {
|
||||
const db = getDB();
|
||||
const row = db
|
||||
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", userId);
|
||||
return row ? JSON.parse(row.value) : {};
|
||||
}
|
||||
|
||||
// 为当前用户创建 LLM 客户端
|
||||
function getUserLLMClient(userId) {
|
||||
const cfg = loadUserLLMConfig(userId);
|
||||
if (!cfg.llm_api_key) return null;
|
||||
const { OpenAI } = require("openai");
|
||||
const client = new OpenAI({
|
||||
apiKey: cfg.llm_api_key,
|
||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||
});
|
||||
client._model = cfg.llm_model || "gpt-4o-mini";
|
||||
return client;
|
||||
}
|
||||
|
||||
// GET /api/config
|
||||
router.get('/', (req, res) => {
|
||||
res.json(loadConfig());
|
||||
router.get("/", (req, res) => {
|
||||
res.json(loadUserLLMConfig(req.userId));
|
||||
});
|
||||
|
||||
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
|
||||
router.put('/', (req, res) => {
|
||||
const cfg = { ...loadConfig(), ...req.body };
|
||||
saveConfig(cfg);
|
||||
resetClient();
|
||||
// PUT /api/config
|
||||
router.put("/", (req, res) => {
|
||||
const db = getDB();
|
||||
const value = JSON.stringify(req.body);
|
||||
|
||||
const row = db
|
||||
.prepare("SELECT id FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", req.userId);
|
||||
if (row) {
|
||||
db.prepare("UPDATE config SET value = ? WHERE id = ?").run(value, row.id);
|
||||
} else {
|
||||
db.prepare("INSERT INTO config (key, value, user_id) VALUES (?, ?, ?)").run(
|
||||
"llm_config",
|
||||
value,
|
||||
req.userId,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm
|
||||
router.post('/test-llm', async (req, res) => {
|
||||
console.log('[Reco] === LLM 连接测试 ===');
|
||||
const cfg = loadConfig();
|
||||
console.log(' API Key:', cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + '...' : '(无)');
|
||||
console.log(' Base URL:', cfg.llm_base_url || '默认');
|
||||
console.log(' Model:', cfg.llm_model || '默认');
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
console.log("[Reco] === LLM 连接测试 ===");
|
||||
const client = getUserLLMClient(req.userId);
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (!client) return res.status(400).json({ error: '请先配置 LLM API Key' });
|
||||
if (!client) {
|
||||
return res.status(400).json({ error: "请先配置 LLM API Key" });
|
||||
}
|
||||
|
||||
console.log(" Model:", client._model);
|
||||
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const resp = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [{ role: 'user', content: '回复"连接成功"' }],
|
||||
max_tokens: 10, timeout: 15000,
|
||||
messages: [{ role: "user", content: '回复"连接成功"' }],
|
||||
max_tokens: 10,
|
||||
timeout: 15000,
|
||||
});
|
||||
const reply = resp.choices?.[0]?.message?.content || '(空)';
|
||||
const reply = resp.choices?.[0]?.message?.content || "(空)";
|
||||
console.log(` 成功 ${Date.now() - t0}ms: ${reply}`);
|
||||
res.json({ success: true, reply, model: client._model, elapsed_ms: Date.now() - t0 });
|
||||
res.json({
|
||||
success: true,
|
||||
reply,
|
||||
model: client._model,
|
||||
elapsed_ms: Date.now() - t0,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(` 失败 ${Date.now() - t0}ms:`, err.message);
|
||||
res.status(500).json({ error: `连接失败: ${err.message}` });
|
||||
@@ -44,28 +84,118 @@ router.post('/test-llm', async (req, res) => {
|
||||
});
|
||||
|
||||
// Categories
|
||||
router.get('/categories', (req, res) => {
|
||||
res.json(getDB().prepare('SELECT * FROM categories ORDER BY id').all());
|
||||
router.get("/categories", (req, res) => {
|
||||
res.json(
|
||||
getDB()
|
||||
.prepare("SELECT * FROM categories WHERE user_id = ? ORDER BY id")
|
||||
.all(req.userId),
|
||||
);
|
||||
});
|
||||
|
||||
router.put('/categories/:id', (req, res) => {
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
getDB().prepare('UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?')
|
||||
.run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
res.json({ success: true });
|
||||
const current = db
|
||||
.prepare("SELECT * FROM categories WHERE id = ? AND user_id = ?")
|
||||
.get(req.params.id, req.userId);
|
||||
if (!current) return res.status(404).json({ error: "分类不存在" });
|
||||
if (current.is_locked)
|
||||
return res.status(403).json({ error: "内置分类不可修改" });
|
||||
|
||||
const newName = name === undefined ? current.name : String(name).trim();
|
||||
if (!newName) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
|
||||
const affectedIds = [];
|
||||
try {
|
||||
db.transaction(() => {
|
||||
if (newName !== current.name) {
|
||||
const dup = db
|
||||
.prepare(
|
||||
"SELECT id FROM categories WHERE user_id = ? AND name = ? AND id <> ?",
|
||||
)
|
||||
.get(req.userId, newName, req.params.id);
|
||||
if (dup) {
|
||||
const err = new Error("已存在同名分类");
|
||||
err.status = 409;
|
||||
throw err;
|
||||
}
|
||||
// 重命名:同步历史 deal 的分类名
|
||||
for (const row of db
|
||||
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||
.all(req.userId, current.name))
|
||||
affectedIds.push(row.id);
|
||||
db.prepare(
|
||||
"UPDATE deals SET category = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||
).run(newName, req.userId, current.name);
|
||||
}
|
||||
const sets = [];
|
||||
const params = [];
|
||||
if (newName !== current.name) {
|
||||
sets.push("name = ?");
|
||||
params.push(newName);
|
||||
}
|
||||
if (keywords !== undefined) {
|
||||
sets.push("keywords = ?");
|
||||
params.push(JSON.stringify(Array.isArray(keywords) ? keywords : []));
|
||||
}
|
||||
if (sets.length) {
|
||||
db.prepare(
|
||||
`UPDATE categories SET ${sets.join(", ")} WHERE id = ? AND user_id = ?`,
|
||||
).run(...params, req.params.id, req.userId);
|
||||
}
|
||||
})();
|
||||
} catch (err) {
|
||||
return res
|
||||
.status(err.status || 500)
|
||||
.json({ error: err.message || "更新失败" });
|
||||
}
|
||||
|
||||
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||
});
|
||||
|
||||
router.post('/categories', (req, res) => {
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
if (!name) return res.status(400).json({ error: '分类名称不能为空' });
|
||||
const r = getDB().prepare('INSERT INTO categories (name,keywords,parent_id) VALUES (?,?,?)')
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null);
|
||||
router.post("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
const trimmed = typeof name === "string" ? name.trim() : "";
|
||||
if (!trimmed) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const dup = db
|
||||
.prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?")
|
||||
.get(req.userId, trimmed);
|
||||
if (dup) return res.status(409).json({ error: "已存在同名分类" });
|
||||
const r = db
|
||||
.prepare(
|
||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(trimmed, JSON.stringify(keywords || []), req.userId);
|
||||
res.json({ success: true, id: r.lastInsertRowid });
|
||||
});
|
||||
|
||||
router.delete('/categories/:id', (req, res) => {
|
||||
getDB().prepare('DELETE FROM categories WHERE id=?').run(req.params.id);
|
||||
res.json({ success: true });
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const cat = db
|
||||
.prepare("SELECT name, is_locked FROM categories WHERE id = ? AND user_id = ?")
|
||||
.get(req.params.id, req.userId);
|
||||
if (!cat) return res.status(404).json({ error: "分类不存在" });
|
||||
if (cat.is_locked)
|
||||
return res.status(403).json({ error: "内置分类不可删除" });
|
||||
|
||||
const affectedIds = db
|
||||
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
||||
.all(req.userId, cat.name)
|
||||
.map((r) => r.id);
|
||||
|
||||
db.transaction(() => {
|
||||
// 历史 deal 重置为待分类
|
||||
db.prepare(
|
||||
"UPDATE deals SET category = NULL, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
||||
).run(req.userId, cat.name);
|
||||
db.prepare("DELETE FROM categories WHERE id = ? AND user_id = ?").run(
|
||||
req.params.id,
|
||||
req.userId,
|
||||
);
|
||||
})();
|
||||
|
||||
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+19
-12
@@ -21,8 +21,8 @@ router.get("/", (req, res) => {
|
||||
} = req.query;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
const conditions = ["d.user_id = ?"];
|
||||
const params = [req.userId];
|
||||
if (start_date) {
|
||||
conditions.push("d.deal_date >= ?");
|
||||
params.push(start_date);
|
||||
@@ -67,9 +67,14 @@ router.get("/", (req, res) => {
|
||||
"counterparty",
|
||||
"category",
|
||||
"match_count",
|
||||
"abs_amount",
|
||||
];
|
||||
const safeSort = allowedSort.includes(sort_by) ? sort_by : "deal_date";
|
||||
const safeOrder = sort_order === "ASC" ? "ASC" : "DESC";
|
||||
// abs_amount:按金额绝对值排序(大额确认用,收/支混排时按体量从大到小)
|
||||
const sortExpr =
|
||||
safeSort === "abs_amount" ? "ABS(d.amount)" : `d.${safeSort}`;
|
||||
const tieBreaker = safeSort === "abs_amount" ? ", d.id DESC" : "";
|
||||
|
||||
const total = db
|
||||
.prepare(`SELECT COUNT(*) as c FROM deals d ${where}`)
|
||||
@@ -90,7 +95,7 @@ router.get("/", (req, res) => {
|
||||
LEFT JOIN transactions t ON t.id = dt.transaction_id
|
||||
${where}
|
||||
GROUP BY d.id
|
||||
ORDER BY d.${safeSort} ${safeOrder}
|
||||
ORDER BY ${sortExpr} ${safeOrder}${tieBreaker}
|
||||
LIMIT ? OFFSET ?
|
||||
`,
|
||||
)
|
||||
@@ -139,7 +144,6 @@ router.put("/:id", (req, res) => {
|
||||
params.push(reviewed);
|
||||
if (reviewed) sets.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
|
||||
if (tags !== undefined) {
|
||||
sets.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
@@ -147,9 +151,10 @@ router.put("/:id", (req, res) => {
|
||||
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,
|
||||
);
|
||||
params.push(req.userId);
|
||||
db.prepare(
|
||||
"UPDATE deals SET " + sets.join(", ") + " WHERE id = ? AND user_id = ?",
|
||||
).run(...params);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
@@ -162,16 +167,18 @@ router.post("/batch-confirm", (req, res) => {
|
||||
}
|
||||
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);
|
||||
`UPDATE deals SET reviewed=1, reviewed_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id IN (${ph}) AND user_id = ?`,
|
||||
).run(...ids, req.userId);
|
||||
res.json({ success: true, confirmed: ids.length });
|
||||
});
|
||||
|
||||
// POST /api/deals/clear
|
||||
// POST /api/deals/clear — 清除当前用户所有 deals
|
||||
router.post("/clear", (req, res) => {
|
||||
const db = getDB();
|
||||
db.prepare("DELETE FROM deal_transactions").run();
|
||||
db.prepare("DELETE FROM deals").run();
|
||||
db.prepare(
|
||||
"DELETE FROM deal_transactions WHERE deal_id IN (SELECT id FROM deals WHERE user_id = ?)",
|
||||
).run(req.userId);
|
||||
db.prepare("DELETE FROM deals WHERE user_id = ?").run(req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+91
-30
@@ -6,20 +6,32 @@ const router = express.Router();
|
||||
// GET /api/stats/overview — 总览统计(基于 deals)
|
||||
router.get("/overview", (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let where = "";
|
||||
const params = [];
|
||||
const { year, month, start_date, end_date } = req.query;
|
||||
|
||||
// 日期条件:支持任意区间(财年),也保留旧的 year/month
|
||||
const dateConds = [];
|
||||
const dateParams = [];
|
||||
if (start_date) {
|
||||
dateConds.push("d.deal_date >= ?");
|
||||
dateParams.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
dateConds.push("d.deal_date <= ?");
|
||||
dateParams.push(end_date);
|
||||
}
|
||||
if (year) {
|
||||
where = "WHERE strftime('%Y', d.deal_date) = ?";
|
||||
params.push(String(year));
|
||||
dateConds.push("strftime('%Y', d.deal_date) = ?");
|
||||
dateParams.push(String(year));
|
||||
if (month) {
|
||||
where += " AND strftime('%m', d.deal_date) = ?";
|
||||
params.push(String(month).padStart(2, "0"));
|
||||
dateConds.push("strftime('%m', d.deal_date) = ?");
|
||||
dateParams.push(String(month).padStart(2, "0"));
|
||||
}
|
||||
}
|
||||
|
||||
let where = "WHERE d.user_id = ?";
|
||||
const params = [req.userId, ...dateParams];
|
||||
if (dateConds.length) where += " AND " + dateConds.join(" AND ");
|
||||
|
||||
const stats = db
|
||||
.prepare(
|
||||
`
|
||||
@@ -36,10 +48,9 @@ router.get("/overview", (req, res) => {
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
// 按分类统计支出(用于饼图)
|
||||
const catWhere = where
|
||||
? where + " AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"
|
||||
: "WHERE d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
const catWhere =
|
||||
where +
|
||||
" AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryStats = db
|
||||
.prepare(
|
||||
@@ -57,10 +68,9 @@ router.get("/overview", (req, res) => {
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
// 按分类汇总(收入+支出),排除投资理财、转账红包
|
||||
const catBreakWhere = where
|
||||
? where + " AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')"
|
||||
: "WHERE d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
const catBreakWhere =
|
||||
where +
|
||||
" AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryBreakdown = db
|
||||
.prepare(
|
||||
@@ -78,30 +88,72 @@ router.get("/overview", (req, res) => {
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
// 为每个分类查最大收入/支出 Deal
|
||||
const dateCondSql = dateConds.length ? " AND " + dateConds.join(" AND ") : "";
|
||||
const maxIncomeStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='income'
|
||||
ORDER BY amount DESC LIMIT 1`,
|
||||
FROM deals d WHERE d.category=? AND d.direction='income' AND d.user_id=?${dateCondSql}
|
||||
ORDER BY d.amount DESC LIMIT 1`,
|
||||
);
|
||||
const maxExpenseStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='expense'
|
||||
ORDER BY ABS(amount) DESC LIMIT 1`,
|
||||
FROM deals d WHERE d.category=? AND d.direction='expense' AND d.user_id=?${dateCondSql}
|
||||
ORDER BY ABS(d.amount) DESC LIMIT 1`,
|
||||
);
|
||||
|
||||
for (const cat of categoryBreakdown) {
|
||||
cat.max_income = maxIncomeStmt.get(cat.category) || null;
|
||||
cat.max_expense = maxExpenseStmt.get(cat.category) || null;
|
||||
cat.max_income =
|
||||
maxIncomeStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||
cat.max_expense =
|
||||
maxExpenseStmt.get(cat.category, req.userId, ...dateParams) || null;
|
||||
}
|
||||
|
||||
res.json({ overview: stats, categoryStats, categoryBreakdown });
|
||||
// 全量日期范围(不受筛选影响),供前端枚举财年
|
||||
const dateRange = db
|
||||
.prepare(
|
||||
"SELECT MIN(deal_date) as min_date, MAX(deal_date) as max_date FROM deals WHERE user_id = ?",
|
||||
)
|
||||
.get(req.userId);
|
||||
|
||||
res.json({ overview: stats, categoryStats, categoryBreakdown, dateRange });
|
||||
});
|
||||
|
||||
// GET /api/stats/monthly — 月度趋势(基于 deals)
|
||||
// 解析 categories 查询参数
|
||||
function parseCategories(query) {
|
||||
if (!query) return null;
|
||||
return query
|
||||
.split(",")
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
// GET /api/stats/monthly — 月度趋势(支持 ?categories=餐饮,购物 筛选)
|
||||
router.get("/monthly", (req, res) => {
|
||||
const db = getDB();
|
||||
const { start_date, end_date } = req.query;
|
||||
const cats = parseCategories(req.query.categories);
|
||||
|
||||
const conds = ["d.user_id = ?"];
|
||||
const params = [req.userId];
|
||||
|
||||
if (start_date) {
|
||||
conds.push("d.deal_date >= ?");
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conds.push("d.deal_date <= ?");
|
||||
params.push(end_date);
|
||||
}
|
||||
// 只有显式传了 months 才限制为「最近 N 个月」;
|
||||
// 不传任何时间参数 = 不限制(全部时间)
|
||||
if (!start_date && !end_date && req.query.months != null) {
|
||||
const months = Math.abs(parseInt(req.query.months) || 12);
|
||||
conds.push("d.deal_date >= DATE('now', ? || ' months')");
|
||||
params.push("-" + months);
|
||||
}
|
||||
if (cats && cats.length > 0) {
|
||||
conds.push("d.category IN (" + cats.map(() => "?").join(",") + ")");
|
||||
params.push(...cats);
|
||||
}
|
||||
|
||||
const monthlyData = db
|
||||
.prepare(
|
||||
@@ -112,20 +164,29 @@ router.get("/monthly", (req, res) => {
|
||||
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
|
||||
FROM deals d
|
||||
WHERE d.deal_date >= DATE('now', ? || ' months')
|
||||
WHERE ${conds.join(" AND ")}
|
||||
GROUP BY strftime('%Y-%m', d.deal_date)
|
||||
ORDER BY month ASC
|
||||
`,
|
||||
)
|
||||
.all("-" + months);
|
||||
.all(...params);
|
||||
|
||||
res.json(monthlyData);
|
||||
});
|
||||
|
||||
// GET /api/stats/daily — 每日统计(基于 deals)
|
||||
// GET /api/stats/daily — 每日统计(支持 ?categories 筛选)
|
||||
router.get("/daily", (req, res) => {
|
||||
const db = getDB();
|
||||
const days = Math.abs(parseInt(req.query.days) || 30);
|
||||
const cats = parseCategories(req.query.categories);
|
||||
|
||||
let catFilter = "";
|
||||
const params = ["-" + days, req.userId];
|
||||
|
||||
if (cats && cats.length > 0) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
params.push(...cats);
|
||||
}
|
||||
|
||||
const dailyData = db
|
||||
.prepare(
|
||||
@@ -136,12 +197,12 @@ router.get("/daily", (req, res) => {
|
||||
SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END) as expense
|
||||
FROM deals d
|
||||
WHERE d.deal_date >= DATE('now', ? || ' days')
|
||||
WHERE d.deal_date >= DATE('now', ? || ' days') AND d.user_id = ?${catFilter}
|
||||
GROUP BY d.deal_date
|
||||
ORDER BY date ASC
|
||||
`,
|
||||
)
|
||||
.all("-" + days);
|
||||
.all(...params);
|
||||
|
||||
res.json(dailyData);
|
||||
});
|
||||
|
||||
+28
-116
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const { runAutoReconciliation } = require("../services/matcher");
|
||||
const { classifyDeals, classifyAllDeals } = require("../services/llm");
|
||||
const { classifyDeals, startClassifyAll, getClassifyStatus } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -16,8 +16,6 @@ router.get("/", (req, res) => {
|
||||
end_date,
|
||||
source_type,
|
||||
direction,
|
||||
category,
|
||||
reviewed,
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
@@ -26,8 +24,8 @@ router.get("/", (req, res) => {
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
const conditions = ["t.user_id = ?"];
|
||||
const params = [req.userId];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push("t.transaction_date >= ?");
|
||||
@@ -45,14 +43,6 @@ router.get("/", (req, res) => {
|
||||
conditions.push("t.direction = ?");
|
||||
params.push(direction);
|
||||
}
|
||||
if (category) {
|
||||
conditions.push("t.category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
conditions.push("t.reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
}
|
||||
if (min_amount) {
|
||||
conditions.push("ABS(t.amount) >= ?");
|
||||
params.push(parseFloat(min_amount));
|
||||
@@ -63,16 +53,15 @@ router.get("/", (req, res) => {
|
||||
}
|
||||
if (keyword) {
|
||||
conditions.push(
|
||||
"(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ? OR t.ai_description LIKE ?)",
|
||||
"(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ?)",
|
||||
);
|
||||
const kw = `%${keyword}%`;
|
||||
params.push(kw, kw, kw, kw);
|
||||
params.push(kw, kw, kw);
|
||||
}
|
||||
|
||||
const whereClause =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = [
|
||||
"id",
|
||||
"transaction_time",
|
||||
@@ -122,39 +111,26 @@ 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);
|
||||
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);
|
||||
console.log(
|
||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
||||
);
|
||||
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();
|
||||
const userId = req.userId;
|
||||
|
||||
// 仅清除当前用户的数据
|
||||
db.prepare(
|
||||
"UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL",
|
||||
).run();
|
||||
const result = runAutoReconciliation();
|
||||
"DELETE FROM deal_transactions WHERE deal_id IN (SELECT id FROM deals WHERE user_id = ?)",
|
||||
).run(userId);
|
||||
db.prepare("DELETE FROM deals WHERE user_id = ?").run(userId);
|
||||
db.prepare(
|
||||
"UPDATE transactions SET matched_transaction_id=NULL, match_score=NULL WHERE user_id = ?",
|
||||
).run(userId);
|
||||
|
||||
const result = runAutoReconciliation(userId);
|
||||
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",
|
||||
"SELECT id,transaction_date,transaction_time,amount,direction,counterparty,description,matched_transaction_id FROM transactions WHERE user_id = ? ORDER BY transaction_date,transaction_time",
|
||||
)
|
||||
.all();
|
||||
.all(userId);
|
||||
const visited = new Set();
|
||||
const groups = [];
|
||||
for (const tx of allTxs) {
|
||||
@@ -176,7 +152,7 @@ router.post("/reconcile", (req, res) => {
|
||||
groups.push(group);
|
||||
}
|
||||
const insD = db.prepare(
|
||||
"INSERT INTO deals(deal_date,amount,direction,counterparty,description,match_count)VALUES(?,?,?,?,?,?)",
|
||||
"INSERT INTO deals(deal_date,amount,direction,counterparty,description,match_count,user_id)VALUES(?,?,?,?,?,?,?)",
|
||||
);
|
||||
const insT = db.prepare(
|
||||
"INSERT INTO deal_transactions(deal_id,transaction_id)VALUES(?,?)",
|
||||
@@ -196,6 +172,7 @@ router.post("/reconcile", (req, res) => {
|
||||
e.counterparty,
|
||||
e.description,
|
||||
group.length,
|
||||
userId,
|
||||
);
|
||||
for (const tx of group) insT.run(r.lastInsertRowid, tx.id);
|
||||
dc++;
|
||||
@@ -218,7 +195,7 @@ router.post("/classify", async (req, res) => {
|
||||
return res.status(400).json({ error: "请提供交易ID列表" });
|
||||
}
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
const result = await classifyDeals(ids, req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify — 完成, classified: ${result.classified}, source: ${result.source}`,
|
||||
);
|
||||
@@ -229,83 +206,18 @@ router.post("/classify", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all — AI分类全部(并行)
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
||||
try {
|
||||
const result = await classifyAllDeals();
|
||||
// POST /api/transactions/classify-all — 启动全量分类(后台执行,前端轮询状态)
|
||||
router.post("/classify-all", (req, res) => {
|
||||
const result = startClassifyAll(req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
||||
`[Reco] POST /transactions/classify-all — started=${result.started}, total=${result.total}`,
|
||||
);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类全部失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
router.get("/stats/summary", (req, res) => {
|
||||
// This is handled by the stats route, but let's keep a simple version here too
|
||||
const db = getDB();
|
||||
|
||||
const { start_date, end_date } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push("transaction_date >= ?");
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push("transaction_date <= ?");
|
||||
params.push(end_date);
|
||||
}
|
||||
|
||||
const where =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
const incomeResult = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(amount), 0) as total FROM transactions ${where} AND direction = 'income'`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const expenseResult = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(ABS(amount)), 0) as total FROM transactions ${where} AND direction = 'expense'`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const countResult = db
|
||||
.prepare(`SELECT COUNT(*) as total FROM transactions ${where}`)
|
||||
.get(...params);
|
||||
|
||||
const unreviewedCount = db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const categoryBreakdown = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT category, COUNT(*) as count, SUM(ABS(amount)) as total_amount
|
||||
FROM transactions ${where} AND direction = 'expense'
|
||||
GROUP BY category
|
||||
ORDER BY total_amount DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
res.json({
|
||||
totalIncome: incomeResult.total,
|
||||
totalExpense: expenseResult.total,
|
||||
netAmount: incomeResult.total - expenseResult.total,
|
||||
totalCount: countResult.total,
|
||||
unreviewedCount: unreviewedCount.total,
|
||||
categoryBreakdown,
|
||||
});
|
||||
// GET /api/transactions/classify-status — 全量分类进度
|
||||
router.get("/classify-status", (req, res) => {
|
||||
res.json(getClassifyStatus(req.userId));
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+18
-7
@@ -145,17 +145,25 @@ router.post("/confirm", (req, res) => {
|
||||
uploadPath,
|
||||
} = temp;
|
||||
const db = getDB();
|
||||
const userId = req.userId;
|
||||
|
||||
const src = db
|
||||
.prepare(
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?,?,?,?,?)",
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count, user_id) VALUES (?,?,?,?,?,?)",
|
||||
)
|
||||
.run(sourceType, sourceName, originalname, fileHash, parsed.length);
|
||||
.run(
|
||||
sourceType,
|
||||
sourceName,
|
||||
originalname,
|
||||
fileHash,
|
||||
parsed.length,
|
||||
userId,
|
||||
);
|
||||
|
||||
const ins = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
transaction_code, source_id, source_type, transaction_date, transaction_time,
|
||||
counterparty, description, notes, amount, direction, status, method, balance
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
counterparty, description, notes, amount, direction, status, method, balance, user_id
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
|
||||
let inserted = 0,
|
||||
skip = 0;
|
||||
@@ -180,6 +188,7 @@ router.post("/confirm", (req, res) => {
|
||||
tx.status || "",
|
||||
tx.method || "",
|
||||
tx.balance || null,
|
||||
userId,
|
||||
);
|
||||
if (r.changes > 0) inserted++;
|
||||
else skip++;
|
||||
@@ -221,14 +230,16 @@ router.get("/sources", (req, res) => {
|
||||
res.json(
|
||||
getDB()
|
||||
.prepare(
|
||||
"SELECT s.*, COUNT(t.id) tx_count FROM sources s LEFT JOIN transactions t ON t.source_id=s.id GROUP BY s.id ORDER BY s.imported_at DESC",
|
||||
"SELECT s.*, COUNT(t.id) tx_count FROM sources s LEFT JOIN transactions t ON t.source_id=s.id WHERE s.user_id = ? GROUP BY s.id ORDER BY s.imported_at DESC",
|
||||
)
|
||||
.all(),
|
||||
.all(req.userId),
|
||||
);
|
||||
});
|
||||
|
||||
router.delete("/sources/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
|
||||
getDB()
|
||||
.prepare("DELETE FROM sources WHERE id = ? AND user_id = ?")
|
||||
.run(req.params.id, req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+339
-203
@@ -1,74 +1,96 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, "..", "..", "data", "llm_config.json");
|
||||
const BATCH_SIZE = 30; // 每批发送给 LLM 的 deal 数量
|
||||
const CONCURRENCY = 5; // 并行调用 LLM 的最大并发数
|
||||
|
||||
let openaiClient = null;
|
||||
const BATCH_SIZE = 30;
|
||||
const CONCURRENCY = 8;
|
||||
// 单次 LLM 响应的 token 上限。
|
||||
// 注意:reasoning 模型(如 deepseek-flash/reasoner)会先消耗 reasoning tokens,
|
||||
// 该预算如果太小,content 会被截断为空,导致分类静默退回规则匹配。
|
||||
const MAX_TOKENS = Number(process.env.LLM_MAX_TOKENS) || 16000;
|
||||
|
||||
/* ============================== 配置管理 ============================== */
|
||||
function loadConfig() {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH))
|
||||
return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
|
||||
} catch (e) {}
|
||||
return {};
|
||||
}
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), "utf-8");
|
||||
}
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
function loadUserLLMConfig(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const row = db
|
||||
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
||||
.get("llm_config", userId);
|
||||
return row ? JSON.parse(row.value) : {};
|
||||
}
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
const cfg = loadConfig();
|
||||
const clientCache = new Map(); // userId -> { sig, client }
|
||||
|
||||
function getOpenAIClient(userId) {
|
||||
const cfg = loadUserLLMConfig(userId);
|
||||
if (!cfg.llm_api_key) {
|
||||
console.log("[Reco] LLM 未配置 API Key");
|
||||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||||
return null;
|
||||
}
|
||||
// 配置未变时复用 client,避免每批都重新创建连接池
|
||||
const sig = [
|
||||
cfg.llm_api_key,
|
||||
cfg.llm_base_url || "",
|
||||
cfg.llm_model || "",
|
||||
].join("|");
|
||||
const cached = clientCache.get(userId);
|
||||
if (cached && cached.sig === sig) return cached.client;
|
||||
|
||||
const { OpenAI } = require("openai");
|
||||
openaiClient = new OpenAI({
|
||||
const client = new OpenAI({
|
||||
apiKey: cfg.llm_api_key,
|
||||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||||
});
|
||||
openaiClient._model = cfg.llm_model || "gpt-4o-mini";
|
||||
console.log(
|
||||
`[Reco] LLM 客户端已初始化 — 模型: ${openaiClient._model}, BaseURL: ${cfg.llm_base_url || "默认"}`,
|
||||
);
|
||||
return openaiClient;
|
||||
client._model = cfg.llm_model || "gpt-4o-mini";
|
||||
clientCache.set(userId, { sig, client });
|
||||
return client;
|
||||
}
|
||||
|
||||
/* ============================== 分类加载 ============================== */
|
||||
function loadCategories(userId) {
|
||||
const { getDB } = require("../db");
|
||||
return getDB()
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((c) => {
|
||||
let keywords = [];
|
||||
try {
|
||||
keywords = JSON.parse(c.keywords || "[]");
|
||||
} catch (e) {}
|
||||
return { id: c.id, name: c.name, keywords };
|
||||
});
|
||||
}
|
||||
|
||||
/* ============================== Prompt 构建 ============================== */
|
||||
function buildPrompt(deals) {
|
||||
function buildPrompt(deals, userId, cats) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
if (!cats) cats = loadCategories(userId);
|
||||
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
const catList = cats
|
||||
.map(
|
||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
||||
)
|
||||
.map((c) => c.name + "(" + c.keywords.join("、") + ")")
|
||||
.join("\n");
|
||||
|
||||
// 一次查出整批 deal 的关联交易,避免逐条查询(N+1)
|
||||
const dealIds = deals.map((d) => d.id);
|
||||
const txByDeal = new Map();
|
||||
if (dealIds.length) {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT dt.deal_id, t.description, t.counterparty, t.source_type, t.notes
|
||||
FROM deal_transactions dt
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
WHERE dt.deal_id IN (${dealIds.map(() => "?").join(",")})
|
||||
`,
|
||||
)
|
||||
.all(...dealIds);
|
||||
for (const r of rows) {
|
||||
if (!txByDeal.has(r.deal_id)) txByDeal.set(r.deal_id, []);
|
||||
txByDeal.get(r.deal_id).push(r);
|
||||
}
|
||||
}
|
||||
|
||||
let txTotal = 0;
|
||||
const dealList = deals
|
||||
.map((d, i) => {
|
||||
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
|
||||
const txs = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT t.description, t.counterparty, t.source_type, t.notes
|
||||
FROM deal_transactions dt
|
||||
JOIN transactions t ON t.id = dt.transaction_id
|
||||
WHERE dt.deal_id = ?
|
||||
`,
|
||||
)
|
||||
.all(d.id);
|
||||
const txs = txByDeal.get(d.id) || [];
|
||||
|
||||
let extra = "";
|
||||
if (txs.length > 0) {
|
||||
@@ -95,7 +117,7 @@ function buildPrompt(deals) {
|
||||
}
|
||||
|
||||
return (
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${Number(d.amount).toFixed(2)}元` +
|
||||
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
||||
);
|
||||
})
|
||||
@@ -126,12 +148,10 @@ ${dealList}
|
||||
/* ============================== JSON 提取 ============================== */
|
||||
function extractJsonArray(text) {
|
||||
if (!text) return null;
|
||||
// 先尝试直接解析
|
||||
try {
|
||||
const r = JSON.parse(text);
|
||||
if (Array.isArray(r)) return r;
|
||||
} catch (e) {}
|
||||
// 找到第一个 [ 和最后一个 ]
|
||||
const start = text.indexOf("[");
|
||||
const end = text.lastIndexOf("]");
|
||||
if (start === -1 || end === -1 || start >= end) return null;
|
||||
@@ -141,226 +161,342 @@ function extractJsonArray(text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
if (ids.length === 0) return { classified: 0 };
|
||||
|
||||
console.log(`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID`);
|
||||
|
||||
const deals = db
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
|
||||
)
|
||||
.all(...ids);
|
||||
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const client = getOpenAIClient();
|
||||
if (client) {
|
||||
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
|
||||
try {
|
||||
const prompt = buildPrompt(deals);
|
||||
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
|
||||
const t0 = Date.now();
|
||||
/* ============================== 单次 LLM 请求 ============================== */
|
||||
// 返回 { pairs, finish, contentLen, reasoning },pairs 为 [{ deal, item }]
|
||||
async function requestLLMClassification(deals, client, userId, cats, maxTokens) {
|
||||
const prompt = buildPrompt(deals, userId, cats);
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||
content: "你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 4000,
|
||||
max_tokens: maxTokens,
|
||||
});
|
||||
const elapsed = Date.now() - t0;
|
||||
|
||||
const choice = response.choices?.[0];
|
||||
const content = choice?.message?.content || "";
|
||||
const results = extractJsonArray(content);
|
||||
const pairs = [];
|
||||
if (results && results.length) {
|
||||
for (const item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) pairs.push({ deal: d, item });
|
||||
}
|
||||
}
|
||||
return {
|
||||
pairs,
|
||||
finish: choice?.finish_reason,
|
||||
contentLen: content.length,
|
||||
reasoning: response.usage?.completion_tokens_details?.reasoning_tokens,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求 LLM 分类,并对 reasoning 模型“思考吃光 max_tokens → content 被截断为空”
|
||||
* 的情况自愈:把批量对半拆分、顺序重试(深度上限 6,最细拆到单条)。
|
||||
* 返回 [{ deal, item }]。
|
||||
*/
|
||||
async function classifyViaLLM(deals, client, userId, cats, depth) {
|
||||
const r = await requestLLMClassification(
|
||||
deals,
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
MAX_TOKENS,
|
||||
);
|
||||
if (r.pairs.length) return r.pairs;
|
||||
|
||||
if (r.finish === "length" && deals.length > 1 && depth < 6) {
|
||||
const mid = Math.ceil(deals.length / 2);
|
||||
console.warn(
|
||||
`[Reco] classifyDeals — LLM 输出被截断 (reasoning=${r.reasoning ?? "-"}, ` +
|
||||
`max_tokens=${MAX_TOKENS}),拆分为 ${mid}+${deals.length - mid} 重试`,
|
||||
);
|
||||
const a = await classifyViaLLM(
|
||||
deals.slice(0, mid),
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
depth + 1,
|
||||
);
|
||||
const b = await classifyViaLLM(
|
||||
deals.slice(mid),
|
||||
client,
|
||||
userId,
|
||||
cats,
|
||||
depth + 1,
|
||||
);
|
||||
return [...a, ...b];
|
||||
}
|
||||
|
||||
console.warn(
|
||||
`[Reco] classifyDeals — LLM 返回不可解析,退回规则 (finish=${r.finish}, ` +
|
||||
`content=${r.contentLen}字, reasoning=${r.reasoning ?? "-"}, ` +
|
||||
`max_tokens=${MAX_TOKENS})`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds, userId, opts = {}) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
if (ids.length === 0) return { classified: 0 };
|
||||
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
|
||||
`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID (userId=${userId})`,
|
||||
);
|
||||
|
||||
const rawContent = response.choices[0]?.message?.content || "";
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
|
||||
);
|
||||
const deals = db
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")}) AND user_id = ?`,
|
||||
)
|
||||
.all(...ids, userId);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const results = extractJsonArray(rawContent);
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
|
||||
);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const cats = opts.cats || loadCategories(userId);
|
||||
const client = getOpenAIClient(userId);
|
||||
if (client) {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const pairs = await classifyViaLLM(deals, client, userId, cats, 0);
|
||||
if (pairs.length) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
const t1 = Date.now();
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) {
|
||||
for (const { deal, item } of pairs) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
d.id,
|
||||
deal.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
|
||||
);
|
||||
return { classified: results.length, source: "llm" };
|
||||
// 截断到单条仍失败的个别 deal,用规则补齐
|
||||
const covered = new Set(pairs.map((p) => p.deal.id));
|
||||
const missing = deals.filter((d) => !covered.has(d.id));
|
||||
let filled = 0;
|
||||
if (missing.length) {
|
||||
const r = classifyDealsByRules(missing, userId, cats);
|
||||
filled = r.classified;
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 完成 ${pairs.length + filled} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
);
|
||||
return { classified: pairs.length + filled, source: "llm" };
|
||||
}
|
||||
console.log(`[Reco] classifyDeals — JSON解析为空,降级到规则匹配 ⚠️`);
|
||||
} catch (e) {
|
||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||
}
|
||||
} else {
|
||||
console.log(`[Reco] classifyDeals — 未配置LLM,使用规则匹配`);
|
||||
}
|
||||
// LLM 不可用或失败 → 降级为规则匹配
|
||||
return classifyDealsByRules(deals);
|
||||
return classifyDealsByRules(deals, userId, cats);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals) {
|
||||
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
// 包裹在事务中批量更新
|
||||
db.transaction(() => {
|
||||
for (const d of deals) {
|
||||
const text = (d.description + " " + d.counterparty).toLowerCase();
|
||||
let best = "其他杂项",
|
||||
score = 0;
|
||||
// 关键词打分;category=null/score=0 表示没命中任何关键词
|
||||
function bestRuleCategory(deal, cats) {
|
||||
const text = (
|
||||
(deal.description || "") +
|
||||
" " +
|
||||
(deal.counterparty || "")
|
||||
).toLowerCase();
|
||||
let category = null;
|
||||
let score = 0;
|
||||
for (const c of cats) {
|
||||
let s = 0;
|
||||
for (const kw of JSON.parse(c.keywords || "[]")) {
|
||||
for (const kw of c.keywords) {
|
||||
if (kw && text.includes(kw.toLowerCase())) s++;
|
||||
}
|
||||
if (s > score) {
|
||||
score = s;
|
||||
best = c.name;
|
||||
category = c.name;
|
||||
}
|
||||
}
|
||||
const directionText = parseFloat(d.amount) >= 0 ? "收到" : "向";
|
||||
const actionText = parseFloat(d.amount) >= 0 ? "" : "支付";
|
||||
return { category, score };
|
||||
}
|
||||
|
||||
function buildRuleDescription(deal) {
|
||||
const income = parseFloat(deal.amount) >= 0;
|
||||
const desc =
|
||||
directionText +
|
||||
(d.counterparty || "对方") +
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
(income ? "收到" : "向") +
|
||||
(deal.counterparty || "对方") +
|
||||
(income ? "" : "支付") +
|
||||
Math.abs(Number(deal.amount) || 0).toFixed(2) +
|
||||
"元";
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
return desc.substring(0, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则分类并写库。
|
||||
* onlyMatched=false:全部写入,未命中归入「其他杂项」(纯规则兑底)。
|
||||
* onlyMatched=true :只写命中关键词的,未命中的返回给 LLM 处理。
|
||||
*/
|
||||
function applyRules(deals, cats, { onlyMatched = false } = {}) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
let matched = 0;
|
||||
let unclassified = 0;
|
||||
const unmatched = [];
|
||||
// 兜底分类:优先「其他杂项」;用户删掉该分类后就不再强行归类
|
||||
const hasFallback = cats.some((c) => c.name === "其他杂项");
|
||||
db.transaction(() => {
|
||||
for (const d of deals) {
|
||||
const { category, score } = bestRuleCategory(d, cats);
|
||||
if (!category && onlyMatched) {
|
||||
unmatched.push(d);
|
||||
continue;
|
||||
}
|
||||
const finalCategory = category || (hasFallback ? "其他杂项" : null);
|
||||
if (!finalCategory) {
|
||||
unclassified++;
|
||||
continue;
|
||||
}
|
||||
upd.run(
|
||||
finalCategory,
|
||||
buildRuleDescription(d),
|
||||
score > 0 ? 0.7 : 0.3,
|
||||
finalCategory,
|
||||
d.id,
|
||||
);
|
||||
if (score > 0) matched++;
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
|
||||
return { matched, unmatched, unclassified };
|
||||
}
|
||||
|
||||
function classifyDealsByRules(deals, userId, cats) {
|
||||
if (!cats) cats = loadCategories(userId);
|
||||
const t0 = Date.now();
|
||||
const { matched, unclassified } = applyRules(deals, cats, {
|
||||
onlyMatched: false,
|
||||
});
|
||||
const classified = deals.length - unclassified;
|
||||
if (unclassified > 0) {
|
||||
console.warn(
|
||||
`[Reco] classifyDealsByRules — ${unclassified} 条无关键词命中且无「其他杂项」兜底,保持待分类`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — ${classified}/${deals.length} 条(命中 ${matched}), ${Date.now() - t0}ms, 来源: rules`,
|
||||
);
|
||||
return { classified, source: "rules" };
|
||||
}
|
||||
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals() {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
async function classifyAllDeals(userId, cats, stale, job) {
|
||||
const t0 = Date.now();
|
||||
|
||||
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
|
||||
|
||||
// 1. 取出全部未分类或分类已过时的 deal
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
// 1) 规则优先:命中关键词的直接定,只有没命中的才交给 LLM
|
||||
const { matched, unmatched } = applyRules(stale, cats, { onlyMatched: true });
|
||||
job.done = matched;
|
||||
if (matched > 0) job.source = "rules";
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
|
||||
`[Reco] classifyAll — 规则命中 ${matched}/${stale.length},剩余 ${unmatched.length} 交 LLM`,
|
||||
);
|
||||
|
||||
if (!cats.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无分类,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ph = cats.map(() => "?").join(",");
|
||||
const stale = db
|
||||
.prepare(
|
||||
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
|
||||
)
|
||||
.all(...cats);
|
||||
|
||||
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
|
||||
|
||||
if (!stale.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
|
||||
// 2. 分批
|
||||
// 2) LLM 处理未命中的(分批 + 并发)
|
||||
if (unmatched.length) {
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
||||
for (let i = 0; i < unmatched.length; i += BATCH_SIZE) {
|
||||
batches.push(unmatched.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 共 ${batches.length} 批 (每批≤${BATCH_SIZE}条), 最大并发 ${CONCURRENCY}`,
|
||||
);
|
||||
|
||||
// 3. 并行处理(带并发限制)
|
||||
let totalClassified = 0;
|
||||
let source = "rules";
|
||||
const tStart = Date.now();
|
||||
let round = 0;
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
round++;
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const from = i + 1;
|
||||
const to = Math.min(i + CONCURRENCY, batches.length);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮: 并行处理第 ${from}-${to} 批 (共 ${chunk.length} 批)`,
|
||||
const group = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
group.map((b) => classifyDeals(b.map((d) => d.id), userId, { cats })),
|
||||
);
|
||||
|
||||
const tRound = Date.now();
|
||||
const results = await Promise.all(chunk.map((b) => classifyDeals(b)));
|
||||
const roundElapsed = Date.now() - tRound;
|
||||
|
||||
for (const r of results) {
|
||||
totalClassified += r.classified;
|
||||
if (r.source === "llm") source = "llm";
|
||||
job.done += r.classified || 0;
|
||||
if (r.source === "llm") job.source = "llm";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
|
||||
`[Reco] classifyAll — 完成 ${job.done}/${stale.length} 条, 来源: ${job.source}, ${Date.now() - t0}ms`,
|
||||
);
|
||||
}
|
||||
|
||||
const totalElapsed = Date.now() - tStart;
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
|
||||
);
|
||||
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
|
||||
const runningJobs = new Map(); // userId -> { total, done, source, startedAt }
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
function getStaleDeals(userId, cats) {
|
||||
const { getDB } = require("../db");
|
||||
const names = cats.map((c) => c.name);
|
||||
if (!names.length) return [];
|
||||
const ph = names.map(() => "?").join(",");
|
||||
return getDB()
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...names, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动全量分类:后台执行、立即返回,前端轮询 classify-status 拿进度。
|
||||
* 同一用户已在跑时重复点击直接返回当前任务状态。
|
||||
*/
|
||||
function startClassifyAll(userId) {
|
||||
const running = runningJobs.get(userId);
|
||||
if (running) {
|
||||
return {
|
||||
started: false,
|
||||
running: true,
|
||||
total: running.total,
|
||||
done: running.done,
|
||||
};
|
||||
}
|
||||
|
||||
const cats = loadCategories(userId);
|
||||
if (!cats.length) return { started: false, running: false, total: 0, done: 0 };
|
||||
|
||||
const stale = getStaleDeals(userId, cats);
|
||||
if (!stale.length) return { started: false, running: false, total: 0, done: 0 };
|
||||
|
||||
const job = {
|
||||
total: stale.length,
|
||||
done: 0,
|
||||
source: "rules",
|
||||
startedAt: Date.now(),
|
||||
};
|
||||
runningJobs.set(userId, job);
|
||||
classifyAllDeals(userId, cats, stale, job)
|
||||
.catch((e) => console.error("[Reco] classifyAll 后台任务失败:", e))
|
||||
.finally(() => runningJobs.delete(userId));
|
||||
|
||||
return { started: true, running: true, total: job.total, done: 0 };
|
||||
}
|
||||
|
||||
function getClassifyStatus(userId) {
|
||||
const job = runningJobs.get(userId);
|
||||
if (!job) return { running: false, total: 0, done: 0, source: null };
|
||||
return {
|
||||
running: true,
|
||||
total: job.total,
|
||||
done: job.done,
|
||||
source: job.source,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
classifyDeals,
|
||||
classifyAllDeals,
|
||||
startClassifyAll,
|
||||
getClassifyStatus,
|
||||
getOpenAIClient,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
resetClient,
|
||||
buildPrompt,
|
||||
loadCategories,
|
||||
BATCH_SIZE,
|
||||
CONCURRENCY,
|
||||
MAX_TOKENS,
|
||||
};
|
||||
|
||||
+46
-33
@@ -1,4 +1,4 @@
|
||||
const { getDB } = require('../db');
|
||||
const { getDB } = require("../db");
|
||||
|
||||
/**
|
||||
* 交易匹配服务
|
||||
@@ -13,7 +13,7 @@ const { getDB } = require('../db');
|
||||
* 2. 日期相近(±1天) + 相同金额 + 描述相似
|
||||
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
|
||||
*/
|
||||
function findMatches(newTransaction) {
|
||||
function findMatches(newTransaction, userId) {
|
||||
const db = getDB();
|
||||
|
||||
const absAmount = Math.abs(newTransaction.amount);
|
||||
@@ -21,24 +21,29 @@ function findMatches(newTransaction) {
|
||||
// 只匹配金额 > 0.01 的交易
|
||||
if (absAmount < 0.01) return [];
|
||||
|
||||
const candidates = db.prepare(`
|
||||
const candidates = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id, transaction_code, transaction_date, amount, counterparty,
|
||||
description, source_type, direction, category
|
||||
description, source_type, direction
|
||||
FROM transactions
|
||||
WHERE id != ?
|
||||
AND source_id != ?
|
||||
AND reviewed = 0
|
||||
AND user_id = ?
|
||||
AND ABS(ABS(amount) - ?) <= 1.0
|
||||
AND transaction_date BETWEEN DATE(?, '-2 days') AND DATE(?, '+2 days')
|
||||
ORDER BY ABS(julianday(transaction_date) - julianday(?)) ASC
|
||||
LIMIT 20
|
||||
`).all(
|
||||
`,
|
||||
)
|
||||
.all(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
userId,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date
|
||||
newTransaction.transaction_date,
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return [];
|
||||
@@ -53,66 +58,70 @@ function findMatches(newTransaction) {
|
||||
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
|
||||
if (amountDiff < 0.01) {
|
||||
score += 40;
|
||||
reasons.push('金额完全一致');
|
||||
reasons.push("金额完全一致");
|
||||
} else if (amountDiff < 0.1) {
|
||||
score += 35;
|
||||
reasons.push('金额基本一致');
|
||||
reasons.push("金额基本一致");
|
||||
} else if (amountDiff < 1.0) {
|
||||
score += 20;
|
||||
reasons.push('金额接近');
|
||||
reasons.push("金额接近");
|
||||
}
|
||||
|
||||
// 日期得分
|
||||
const dateDiff = Math.abs(
|
||||
new Date(candidate.transaction_date) - new Date(newTransaction.transaction_date)
|
||||
) / (1000 * 60 * 60 * 24);
|
||||
const dateDiff =
|
||||
Math.abs(
|
||||
new Date(candidate.transaction_date) -
|
||||
new Date(newTransaction.transaction_date),
|
||||
) /
|
||||
(1000 * 60 * 60 * 24);
|
||||
|
||||
if (dateDiff < 0.01) {
|
||||
score += 30;
|
||||
reasons.push('日期相同');
|
||||
reasons.push("日期相同");
|
||||
} else if (dateDiff <= 1) {
|
||||
score += 20;
|
||||
reasons.push('日期差1天');
|
||||
reasons.push("日期差1天");
|
||||
} else if (dateDiff <= 2) {
|
||||
score += 10;
|
||||
reasons.push('日期差2天');
|
||||
reasons.push("日期差2天");
|
||||
}
|
||||
|
||||
// 对方名称相似度
|
||||
const nameSim = stringSimilarity(
|
||||
(candidate.counterparty || '').toLowerCase(),
|
||||
(newTransaction.counterparty || '').toLowerCase()
|
||||
(candidate.counterparty || "").toLowerCase(),
|
||||
(newTransaction.counterparty || "").toLowerCase(),
|
||||
);
|
||||
if (nameSim > 0.8) {
|
||||
score += 20;
|
||||
reasons.push('对方名称高度相似');
|
||||
reasons.push("对方名称高度相似");
|
||||
} else if (nameSim > 0.5) {
|
||||
score += 10;
|
||||
reasons.push('对方名称部分相似');
|
||||
reasons.push("对方名称部分相似");
|
||||
}
|
||||
|
||||
// 描述相似度
|
||||
const descSim = stringSimilarity(
|
||||
(candidate.description || '').toLowerCase(),
|
||||
(newTransaction.description || '').toLowerCase()
|
||||
(candidate.description || "").toLowerCase(),
|
||||
(newTransaction.description || "").toLowerCase(),
|
||||
);
|
||||
if (descSim > 0.7) {
|
||||
score += 10;
|
||||
reasons.push('描述相似');
|
||||
reasons.push("描述相似");
|
||||
}
|
||||
|
||||
// 方向互补(一个支出一个收入,说明是转账匹配)
|
||||
if (candidate.direction !== newTransaction.direction) {
|
||||
score += 5;
|
||||
reasons.push('收支方向互补');
|
||||
reasons.push("收支方向互补");
|
||||
}
|
||||
|
||||
if (score >= 40) { // 最低匹配阈值
|
||||
if (score >= 40) {
|
||||
// 最低匹配阈值
|
||||
matches.push({
|
||||
transaction_id: candidate.id,
|
||||
match_score: Math.min(score, 100) / 100,
|
||||
reasons: reasons.join(';'),
|
||||
candidate
|
||||
reasons: reasons.join(";"),
|
||||
candidate,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -124,17 +133,21 @@ function findMatches(newTransaction) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行全局自动对账
|
||||
* 运行全局自动对账(限定当前用户)
|
||||
* 对所有未匹配的交易尝试匹配
|
||||
*/
|
||||
function runAutoReconciliation() {
|
||||
function runAutoReconciliation(userId) {
|
||||
const db = getDB();
|
||||
|
||||
const unmatched = db.prepare(`
|
||||
const unmatched = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM transactions
|
||||
WHERE matched_transaction_id IS NULL
|
||||
WHERE matched_transaction_id IS NULL AND user_id = ?
|
||||
ORDER BY transaction_date DESC
|
||||
`).all();
|
||||
`,
|
||||
)
|
||||
.all(userId);
|
||||
|
||||
let matchCount = 0;
|
||||
|
||||
@@ -149,7 +162,7 @@ function runAutoReconciliation() {
|
||||
for (const tx of unmatched) {
|
||||
if (processed.has(tx.id)) continue;
|
||||
|
||||
const matches = findMatches(tx);
|
||||
const matches = findMatches(tx, userId);
|
||||
if (matches.length > 0 && matches[0].match_score >= 0.7) {
|
||||
const bestMatch = matches[0];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user