Add user authentication with JWT login and registration
This commit is contained in:
+162
-53
@@ -1,61 +1,170 @@
|
||||
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 });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<nav className="sidebar">
|
||||
<div className="sidebar-header">
|
||||
<h1 className="logo">💰 Reco</h1>
|
||||
<span className="logo-sub">银行流水对账分析</span>
|
||||
</div>
|
||||
<div className="nav-links">
|
||||
<NavLink
|
||||
to="/"
|
||||
end
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<LayoutDashboard size={20} />
|
||||
<span>仪表盘</span>
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/import"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<Upload size={20} />
|
||||
<span>导入账单</span>
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/transactions"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<ListFilter size={20} />
|
||||
<span>交易明细</span>
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/review"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "active" : ""}`}
|
||||
>
|
||||
<ClipboardCheck size={20} />
|
||||
<span>大额确认</span>
|
||||
<span className="badge" id="review-badge">
|
||||
0
|
||||
</span>
|
||||
</NavLink>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div className="app">
|
||||
<nav className="sidebar">
|
||||
<div className="sidebar-header">
|
||||
<h1 className="logo">💰 Reco</h1>
|
||||
<span className="logo-sub">银行流水对账分析</span>
|
||||
</div>
|
||||
<div className="nav-links">
|
||||
<NavLink to="/" end className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<LayoutDashboard size={20} />
|
||||
<span>仪表盘</span>
|
||||
</NavLink>
|
||||
<NavLink to="/import" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<Upload size={20} />
|
||||
<span>导入账单</span>
|
||||
</NavLink>
|
||||
<NavLink to="/transactions" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<ListFilter size={20} />
|
||||
<span>交易明细</span>
|
||||
</NavLink>
|
||||
<NavLink to="/review" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<ClipboardCheck size={20} />
|
||||
<span>大额确认</span>
|
||||
<span className="badge" id="review-badge">0</span>
|
||||
</NavLink>
|
||||
<NavLink to="/settings" className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}>
|
||||
<Settings size={20} />
|
||||
<span>系统设置</span>
|
||||
</NavLink>
|
||||
</div>
|
||||
<div className="sidebar-footer">
|
||||
<span className="version">v1.0.0</span>
|
||||
</div>
|
||||
</nav>
|
||||
<main className="main-content">
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/import" element={<Import />} />
|
||||
<Route path="/transactions" element={<Transactions />} />
|
||||
<Route path="/review" element={<Review />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
<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,16 @@ export async function batchConfirmDeals(ids) {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function clearDeals() {
|
||||
const res = await api.post("/deals/clear");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getNeedsClassify() {
|
||||
const res = await api.get("/transactions/needs-classify");
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Transactions
|
||||
export async function getTransactions(params = {}) {
|
||||
const res = await api.get("/transactions", { params });
|
||||
|
||||
@@ -99,6 +99,10 @@ export default function Dashboard() {
|
||||
useEffect(() => {
|
||||
if (!raw) return;
|
||||
const cats = [...checked];
|
||||
if (cats.length === 0) {
|
||||
setMonthly([]);
|
||||
return;
|
||||
}
|
||||
getMonthly(12, cats).then(setMonthly).catch(console.error);
|
||||
}, [checked, raw]);
|
||||
|
||||
|
||||
+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>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
} from "lucide-react";
|
||||
import {
|
||||
getTransactions,
|
||||
getDeals,
|
||||
updateDeal,
|
||||
clearDeals,
|
||||
getNeedsClassify,
|
||||
runReconciliation,
|
||||
classifyTransactions,
|
||||
formatAmount,
|
||||
@@ -150,8 +154,7 @@ export default function Transactions() {
|
||||
setClassifyProgress(task.progress || 0);
|
||||
const poll = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/transactions/needs-classify");
|
||||
const { total } = await res.json();
|
||||
const { total } = await getNeedsClassify();
|
||||
const p =
|
||||
task.total > 0
|
||||
? Math.round(((task.total - total) / task.total) * 100)
|
||||
@@ -192,12 +195,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 +235,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({
|
||||
category: editingDeal.category,
|
||||
ai_description: editingDeal.ai_description,
|
||||
}),
|
||||
await updateDeal(editingDeal.id, {
|
||||
category: editingDeal.category,
|
||||
ai_description: editingDeal.ai_description,
|
||||
});
|
||||
setEditingDeal(null);
|
||||
loadDeals(dealFilters);
|
||||
@@ -252,8 +249,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) {}
|
||||
}
|
||||
@@ -280,8 +284,7 @@ export default function Transactions() {
|
||||
JSON.stringify({ total: 0, progress: 0, ts: Date.now() }),
|
||||
);
|
||||
try {
|
||||
const res = await fetch("/api/transactions/needs-classify");
|
||||
const { ids, total } = await res.json();
|
||||
const { ids, total } = await getNeedsClassify();
|
||||
if (!ids.length) {
|
||||
showToast("所有交易分类均有效!", "info");
|
||||
setClassifying(false);
|
||||
|
||||
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",
|
||||
|
||||
+99
-34
@@ -22,6 +22,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,
|
||||
@@ -102,6 +111,31 @@ function initDB() {
|
||||
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
|
||||
@@ -111,9 +145,11 @@ function initDB() {
|
||||
const newCols = [
|
||||
["direction", "TEXT"],
|
||||
["category", "TEXT"],
|
||||
["ai_category", "TEXT"],
|
||||
["ai_description", "TEXT"],
|
||||
["ai_confidence", "REAL"],
|
||||
["reviewed", "INTEGER DEFAULT 0"],
|
||||
["review_notes", "TEXT"],
|
||||
["reviewed_at", "DATETIME"],
|
||||
["tags", "TEXT"],
|
||||
["updated_at", "DATETIME"],
|
||||
@@ -124,42 +160,71 @@ function initDB() {
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// 仅首次初始化默认分类
|
||||
const catCount = database
|
||||
.prepare("SELECT COUNT(*) as c FROM categories")
|
||||
.get().c;
|
||||
if (catCount === 0) {
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords) VALUES (?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[
|
||||
"交通出行",
|
||||
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
|
||||
],
|
||||
[
|
||||
"购物消费",
|
||||
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
|
||||
],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1]));
|
||||
})();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
// 兼容旧库: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);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB };
|
||||
// 为新用户创建默认分类
|
||||
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, user_id) VALUES (?, ?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[
|
||||
"交通出行",
|
||||
'["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]',
|
||||
],
|
||||
[
|
||||
"购物消费",
|
||||
'["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]',
|
||||
],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1], userId));
|
||||
})();
|
||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||
}
|
||||
|
||||
module.exports = { getDB, initDB, initDefaultCategories };
|
||||
|
||||
+9
-1
@@ -12,6 +12,8 @@ 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,7 +22,13 @@ 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);
|
||||
|
||||
@@ -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;
|
||||
@@ -12,7 +12,7 @@ router.post("/", async (req, res) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await classifyDeals(ids);
|
||||
const result = await classifyDeals(ids, req.userId);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 分类失败:", err);
|
||||
|
||||
+70
-111
@@ -1,39 +1,65 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
const {
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
getOpenAIClient,
|
||||
resetClient,
|
||||
} = require("../services/llm");
|
||||
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());
|
||||
res.json(loadUserLLMConfig(req.userId));
|
||||
});
|
||||
|
||||
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
|
||||
// PUT /api/config
|
||||
router.put("/", (req, res) => {
|
||||
const cfg = { ...loadConfig(), ...req.body };
|
||||
saveConfig(cfg);
|
||||
resetClient();
|
||||
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 || "默认");
|
||||
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 {
|
||||
@@ -59,111 +85,44 @@ router.post("/test-llm", async (req, res) => {
|
||||
|
||||
// Categories
|
||||
router.get("/categories", (req, res) => {
|
||||
res.json(getDB().prepare("SELECT * FROM categories ORDER BY id").all());
|
||||
res.json(
|
||||
getDB()
|
||||
.prepare("SELECT * FROM categories WHERE user_id = ? ORDER BY id")
|
||||
.all(req.userId),
|
||||
);
|
||||
});
|
||||
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
const db = getDB();
|
||||
|
||||
// 获取旧名称,用于级联更新 deals
|
||||
const oldCat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const oldName = oldCat?.name;
|
||||
|
||||
db.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?",
|
||||
).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
|
||||
// 如果名称变更,级联更新 deals 中的分类名
|
||||
let affectedDeals = 0;
|
||||
if (name && oldName && name !== oldName) {
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=? WHERE category=?")
|
||||
.run(name, oldName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=? WHERE ai_category=?")
|
||||
.run(name, oldName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
console.log(
|
||||
`[Reco] 分类重命名: "${oldName}" -> "${name}", 影响 ${affectedDeals} 条 deal`,
|
||||
getDB()
|
||||
.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=? AND user_id=?",
|
||||
)
|
||||
.run(
|
||||
name,
|
||||
keywords ? JSON.stringify(keywords) : null,
|
||||
req.params.id,
|
||||
req.userId,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true, affectedDeals });
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.post("/categories", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "分类名称不能为空" });
|
||||
const r = getDB()
|
||||
.prepare("INSERT INTO categories (name,keywords) VALUES (?,?)")
|
||||
.run(name, JSON.stringify(keywords || []));
|
||||
.prepare(
|
||||
"INSERT INTO categories (name,keywords,parent_id,user_id) VALUES (?,?,?,?)",
|
||||
)
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null, req.userId);
|
||||
res.json({ success: true, id: r.lastInsertRowid });
|
||||
});
|
||||
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
// 获取分类名,用于清理 deals 引用
|
||||
const cat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const catName = cat?.name;
|
||||
|
||||
// 删除分类
|
||||
db.prepare("DELETE FROM categories WHERE id=?").run(req.params.id);
|
||||
|
||||
// 将使用该分类的 deals 置为待重分类状态
|
||||
let affectedDeals = 0;
|
||||
const affectedIds = [];
|
||||
if (catName) {
|
||||
const deals1 = db
|
||||
.prepare("SELECT id FROM deals WHERE category=?")
|
||||
.all(catName);
|
||||
const deals2 = db
|
||||
.prepare("SELECT id FROM deals WHERE ai_category=? AND category!=?")
|
||||
.all(catName, catName);
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=NULL WHERE category=?")
|
||||
.run(catName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=NULL WHERE ai_category=?")
|
||||
.run(catName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
// 收集受影响的 deal ID(去重)
|
||||
const idSet = new Set();
|
||||
for (const d of deals1) idSet.add(d.id);
|
||||
for (const d of deals2) idSet.add(d.id);
|
||||
for (const id of idSet) affectedIds.push(id);
|
||||
console.log(
|
||||
`[Reco] 删除分类: "${catName}", 影响 ${affectedDeals} 条 deal (${affectedIds.length} 条唯一 deal)`,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
affectedDeals,
|
||||
affectedIds,
|
||||
categoryName: catName,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/config/categories/reclassify-affected — 重分类受影响的 deals
|
||||
router.post("/categories/reclassify-affected", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供deal ID列表" });
|
||||
}
|
||||
try {
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
const result = await classifyDeals(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 重分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
getDB()
|
||||
.prepare("DELETE FROM categories WHERE id=? AND user_id=?")
|
||||
.run(req.params.id, req.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+13
-11
@@ -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);
|
||||
@@ -139,7 +139,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 +146,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 +162,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 });
|
||||
});
|
||||
|
||||
|
||||
+70
-44
@@ -8,11 +8,11 @@ router.get("/overview", (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let where = "";
|
||||
const params = [];
|
||||
let where = "WHERE d.user_id = ?";
|
||||
const params = [req.userId];
|
||||
|
||||
if (year) {
|
||||
where = "WHERE strftime('%Y', d.deal_date) = ?";
|
||||
where += " AND strftime('%Y', d.deal_date) = ?";
|
||||
params.push(String(year));
|
||||
if (month) {
|
||||
where += " AND strftime('%m', d.deal_date) = ?";
|
||||
@@ -22,124 +22,150 @@ router.get("/overview", (req, res) => {
|
||||
|
||||
const stats = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
SELECT
|
||||
COUNT(*) as total_count,
|
||||
COALESCE(SUM(CASE WHEN d.direction = 'income' THEN d.amount ELSE 0 END), 0) as total_income,
|
||||
COALESCE(SUM(CASE WHEN d.direction = 'expense' THEN ABS(d.amount) ELSE 0 END), 0) as total_expense,
|
||||
COUNT(CASE WHEN d.reviewed = 0 AND ABS(d.amount) >= 100 THEN 1 END) as pending_review,
|
||||
COUNT(CASE WHEN d.reviewed = 1 THEN 1 END) as reviewed_count,
|
||||
COALESCE(SUM(d.match_count), 0) as matched_count
|
||||
FROM deals d ${where}`,
|
||||
FROM deals d
|
||||
${where}
|
||||
`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const catWhere = where
|
||||
? where + " AND d.direction = 'expense' AND d.category IS NOT NULL"
|
||||
: "WHERE d.direction = 'expense' AND d.category IS NOT NULL";
|
||||
const catWhere =
|
||||
where +
|
||||
" AND d.direction = 'expense' AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryStats = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
SELECT
|
||||
d.category as category,
|
||||
COUNT(*) as count,
|
||||
SUM(ABS(d.amount)) as total_amount,
|
||||
AVG(ABS(d.amount)) as avg_amount
|
||||
FROM deals d ${catWhere}
|
||||
FROM deals d
|
||||
${catWhere}
|
||||
GROUP BY d.category
|
||||
ORDER BY total_amount DESC`,
|
||||
ORDER BY total_amount DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
const catBreakWhere = where
|
||||
? where + " AND d.category IS NOT NULL"
|
||||
: "WHERE d.category IS NOT NULL";
|
||||
const catBreakWhere =
|
||||
where +
|
||||
" AND d.category IS NOT NULL AND d.category NOT IN ('投资理财','转账红包')";
|
||||
|
||||
const categoryBreakdown = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
SELECT
|
||||
d.category,
|
||||
COUNT(*) as deal_count,
|
||||
SUM(CASE WHEN d.direction='income' THEN d.amount ELSE 0 END) as total_income,
|
||||
SUM(CASE WHEN d.direction='expense' THEN ABS(d.amount) ELSE 0 END) as total_expense
|
||||
FROM deals d ${catBreakWhere}
|
||||
FROM deals d
|
||||
${catBreakWhere}
|
||||
GROUP BY d.category
|
||||
ORDER BY (total_income + total_expense) DESC`,
|
||||
ORDER BY (total_income + total_expense) DESC
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
const maxIncomeStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='income'
|
||||
FROM deals WHERE category=? AND direction='income' AND user_id=?
|
||||
ORDER BY amount DESC LIMIT 1`,
|
||||
);
|
||||
const maxExpenseStmt = db.prepare(
|
||||
`SELECT id, amount, counterparty, deal_date, ai_description
|
||||
FROM deals WHERE category=? AND direction='expense'
|
||||
FROM deals WHERE category=? AND direction='expense' AND user_id=?
|
||||
ORDER BY ABS(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) || null;
|
||||
cat.max_expense = maxExpenseStmt.get(cat.category, req.userId) || null;
|
||||
}
|
||||
|
||||
res.json({ overview: stats, categoryStats, categoryBreakdown });
|
||||
});
|
||||
|
||||
// GET /api/stats/monthly — 月度趋势(可选 categories 过滤)
|
||||
// 解析 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 months = Math.abs(parseInt(req.query.months) || 12);
|
||||
const cats = parseCategories(req.query.categories);
|
||||
|
||||
let catFilter = "";
|
||||
const params = ["-" + months];
|
||||
const params = ["-" + months, req.userId];
|
||||
|
||||
if (req.query.categories) {
|
||||
const cats = req.query.categories
|
||||
.split(",")
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
if (cats.length > 0) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
params.push(...cats);
|
||||
}
|
||||
if (cats && cats.length > 0) {
|
||||
catFilter = " AND d.category IN (" + cats.map(() => "?").join(",") + ")";
|
||||
params.push(...cats);
|
||||
}
|
||||
|
||||
const monthlyData = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
`
|
||||
SELECT
|
||||
strftime('%Y-%m', d.deal_date) as month,
|
||||
COUNT(*) as count,
|
||||
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
|
||||
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')${catFilter}
|
||||
WHERE d.deal_date >= DATE('now', ? || ' months') AND d.user_id = ?${catFilter}
|
||||
GROUP BY strftime('%Y-%m', d.deal_date)
|
||||
ORDER BY month ASC`,
|
||||
ORDER BY month ASC
|
||||
`,
|
||||
)
|
||||
.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(
|
||||
`SELECT
|
||||
`
|
||||
SELECT
|
||||
d.deal_date as date,
|
||||
COUNT(*) as count,
|
||||
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
|
||||
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`,
|
||||
ORDER BY date ASC
|
||||
`,
|
||||
)
|
||||
.all("-" + days);
|
||||
.all(...params);
|
||||
|
||||
res.json(dailyData);
|
||||
});
|
||||
|
||||
@@ -24,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 >= ?");
|
||||
@@ -62,7 +62,6 @@ router.get("/", (req, res) => {
|
||||
const whereClause =
|
||||
conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = [
|
||||
"id",
|
||||
"transaction_time",
|
||||
@@ -115,16 +114,16 @@ router.get("/", (req, res) => {
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(req.userId)
|
||||
.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})`,
|
||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats);
|
||||
.all(...cats, req.userId);
|
||||
console.log(
|
||||
`[Reco] GET /transactions/needs-classify — 返回 ${stale.length} 个待分类 deal`,
|
||||
);
|
||||
@@ -134,17 +133,23 @@ router.get("/needs-classify", (req, res) => {
|
||||
// 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) {
|
||||
@@ -166,7 +171,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(?,?)",
|
||||
@@ -186,6 +191,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++;
|
||||
@@ -208,7 +214,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}`,
|
||||
);
|
||||
@@ -223,7 +229,7 @@ router.post("/classify", async (req, res) => {
|
||||
router.post("/classify-all", async (req, res) => {
|
||||
console.log(`[Reco] POST /transactions/classify-all — 开始`);
|
||||
try {
|
||||
const result = await classifyAllDeals();
|
||||
const result = await classifyAllDeals(req.userId);
|
||||
console.log(
|
||||
`[Reco] POST /transactions/classify-all — 完成, classified: ${result.classified}, total: ${result.total}, source: ${result.source}`,
|
||||
);
|
||||
|
||||
+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 });
|
||||
});
|
||||
|
||||
|
||||
+46
-114
@@ -1,54 +1,39 @@
|
||||
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 = 5;
|
||||
|
||||
/* ============================== 配置管理 ============================== */
|
||||
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();
|
||||
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;
|
||||
}
|
||||
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";
|
||||
return client;
|
||||
}
|
||||
|
||||
/* ============================== Prompt 构建 ============================== */
|
||||
function buildPrompt(deals) {
|
||||
function buildPrompt(deals, userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
|
||||
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
|
||||
const cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const catList = cats
|
||||
.map(
|
||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
||||
@@ -58,7 +43,6 @@ function buildPrompt(deals) {
|
||||
let txTotal = 0;
|
||||
const dealList = deals
|
||||
.map((d, i) => {
|
||||
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
|
||||
const txs = db
|
||||
.prepare(
|
||||
`
|
||||
@@ -126,12 +110,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;
|
||||
@@ -142,28 +124,27 @@ function extractJsonArray(text) {
|
||||
}
|
||||
|
||||
/* ============================== 单批 LLM 分类 ============================== */
|
||||
async function classifyDeals(dealIds) {
|
||||
async function classifyDeals(dealIds, userId) {
|
||||
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`);
|
||||
console.log(
|
||||
`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID (userId=${userId})`,
|
||||
);
|
||||
|
||||
const deals = db
|
||||
.prepare(
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
|
||||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")}) AND user_id = ?`,
|
||||
)
|
||||
.all(...ids);
|
||||
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
|
||||
.all(...ids, userId);
|
||||
if (!deals.length) return { classified: 0 };
|
||||
|
||||
const client = getOpenAIClient();
|
||||
const client = getOpenAIClient(userId);
|
||||
if (client) {
|
||||
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
|
||||
try {
|
||||
const prompt = buildPrompt(deals);
|
||||
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
|
||||
const prompt = buildPrompt(deals, userId);
|
||||
const t0 = Date.now();
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
@@ -178,31 +159,20 @@ async function classifyDeals(dealIds) {
|
||||
temperature: 0.3,
|
||||
max_tokens: 4000,
|
||||
});
|
||||
const elapsed = Date.now() - t0;
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
|
||||
);
|
||||
|
||||
const rawContent = response.choices[0]?.message?.content || "";
|
||||
console.log(
|
||||
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
|
||||
);
|
||||
|
||||
const results = extractJsonArray(rawContent);
|
||||
console.log(
|
||||
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
|
||||
);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"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) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
@@ -212,34 +182,29 @@ async function classifyDeals(dealIds) {
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
|
||||
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
);
|
||||
return { classified: results.length, 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);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals) {
|
||||
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
|
||||
function classifyDealsByRules(deals, userId) {
|
||||
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 cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
"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();
|
||||
@@ -263,94 +228,64 @@ function classifyDealsByRules(deals) {
|
||||
actionText +
|
||||
Math.abs(d.amount).toFixed(2) +
|
||||
"元";
|
||||
upd.run(desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
}
|
||||
})();
|
||||
console.log(
|
||||
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
|
||||
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
}
|
||||
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals() {
|
||||
async function classifyAllDeals(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
|
||||
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
|
||||
|
||||
// 1. 取出全部未分类或分类已过时的 deal
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories")
|
||||
.all()
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((r) => r.name);
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
|
||||
);
|
||||
|
||||
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})`,
|
||||
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats);
|
||||
|
||||
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
|
||||
.all(...cats, userId);
|
||||
|
||||
if (!stale.length) {
|
||||
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
|
||||
// 2. 分批
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.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 results = await Promise.all(
|
||||
chunk.map((b) => classifyDeals(b, userId)),
|
||||
);
|
||||
|
||||
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";
|
||||
}
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
const totalElapsed = Date.now() - tStart;
|
||||
console.log(
|
||||
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
|
||||
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
||||
);
|
||||
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
}
|
||||
@@ -359,7 +294,4 @@ module.exports = {
|
||||
classifyDeals,
|
||||
classifyAllDeals,
|
||||
getOpenAIClient,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
resetClient,
|
||||
};
|
||||
|
||||
+51
-37
@@ -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,25 +21,31 @@ 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
|
||||
FROM transactions
|
||||
WHERE id != ?
|
||||
AND source_id != ?
|
||||
AND user_id = ?
|
||||
AND reviewed = 0
|
||||
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(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date
|
||||
);
|
||||
`,
|
||||
)
|
||||
.all(
|
||||
newTransaction.id || -1,
|
||||
newTransaction.source_id || -1,
|
||||
userId,
|
||||
absAmount,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
newTransaction.transaction_date,
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
@@ -53,66 +59,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 +134,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 +163,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