version 0.1
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
node_modules/
|
||||
client/node_modules/
|
||||
client/build/
|
||||
data/reco.db
|
||||
data/reco.db-*
|
||||
data/uploads/
|
||||
.DS_Store
|
||||
*.log
|
||||
Generated
+17544
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "reco-client",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"react": "^18.3.0",
|
||||
"react-dom": "^18.3.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"react-router-dom": "^6.27.0",
|
||||
"axios": "^1.7.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"recharts": "^2.13.0",
|
||||
"lucide-react": "^0.451.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build"
|
||||
},
|
||||
"proxy": "http://localhost:3001",
|
||||
"browserslist": {
|
||||
"production": [">0.2%", "not dead", "not op_mini all"],
|
||||
"development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Reco - 银行流水对账分析系统</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,554 @@
|
||||
:root {
|
||||
--primary: #4f46e5;
|
||||
--primary-light: #818cf8;
|
||||
--primary-bg: #eef2ff;
|
||||
--success: #10b981;
|
||||
--warning: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
--bg: #f8fafc;
|
||||
--card-bg: #ffffff;
|
||||
--text: #1e293b;
|
||||
--text-secondary: #64748b;
|
||||
--border: #e2e8f0;
|
||||
--sidebar-width: 220px;
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.app {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Sidebar */
|
||||
.sidebar {
|
||||
width: var(--sidebar-width);
|
||||
background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
|
||||
color: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 24px 20px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.1);
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.logo-sub {
|
||||
font-size: 11px;
|
||||
color: rgba(255,255,255,0.5);
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
flex: 1;
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 20px;
|
||||
color: rgba(255,255,255,0.65);
|
||||
text-decoration: none;
|
||||
font-size: 14px;
|
||||
transition: all 0.2s;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
color: white;
|
||||
background: rgba(255,255,255,0.08);
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
color: white;
|
||||
background: rgba(255,255,255,0.12);
|
||||
border-right: 3px solid var(--primary-light);
|
||||
}
|
||||
|
||||
.nav-link .badge {
|
||||
margin-left: auto;
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
font-size: 11px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
padding: 16px 20px;
|
||||
border-top: 1px solid rgba(255,255,255,0.1);
|
||||
}
|
||||
|
||||
.version {
|
||||
font-size: 11px;
|
||||
color: rgba(255,255,255,0.3);
|
||||
}
|
||||
|
||||
/* Main Content */
|
||||
.main-content {
|
||||
margin-left: var(--sidebar-width);
|
||||
flex: 1;
|
||||
padding: 24px 32px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Page Header */
|
||||
.page-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-header h2 {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
color: var(--text-secondary);
|
||||
margin-top: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* Cards */
|
||||
.card {
|
||||
background: var(--card-bg);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border);
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.card-header h3 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Stats Grid */
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--card-bg);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.stat-card .stat-label {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.stat-card .stat-value {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.stat-card .stat-sub {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
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); }
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover { background: #4338ca; }
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.btn-secondary:hover { background: var(--border); }
|
||||
|
||||
.btn-success {
|
||||
background: var(--success);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Form elements */
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
margin-bottom: 6px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.form-input, .form-select {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
transition: border-color 0.2s;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.form-input:focus, .form-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-light);
|
||||
box-shadow: 0 0 0 3px var(--primary-bg);
|
||||
}
|
||||
|
||||
/* Table */
|
||||
.table-container {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: left;
|
||||
padding: 12px 12px;
|
||||
background: var(--bg);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 2px solid var(--border);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
tr:hover { background: var(--bg); }
|
||||
|
||||
/* Tags */
|
||||
.tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
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; }
|
||||
|
||||
/* Review items */
|
||||
.review-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
margin-bottom: 10px;
|
||||
gap: 14px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.review-item:hover {
|
||||
border-color: var(--primary-light);
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
|
||||
}
|
||||
|
||||
.review-item.reviewed {
|
||||
opacity: 0.7;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.review-item .amount-col {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
min-width: 110px;
|
||||
}
|
||||
|
||||
.review-item .info-col {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.review-item .info-col .title {
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.review-item .info-col .meta {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.review-item .action-col {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Upload zone */
|
||||
.upload-zone {
|
||||
border: 2px dashed var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.upload-zone:hover, .upload-zone.drag-over {
|
||||
border-color: var(--primary-light);
|
||||
background: var(--primary-bg);
|
||||
}
|
||||
|
||||
.upload-zone .upload-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
max-width: 500px;
|
||||
width: 90%;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal h3 {
|
||||
font-size: 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Filter bar */
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.filter-bar .form-group {
|
||||
margin-bottom: 0;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
/* Pagination */
|
||||
.pagination {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.pagination button {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.pagination button.active {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.pagination button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Empty state */
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.empty-state .icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Tabs */
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
border-bottom: 2px solid var(--border);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 10px 20px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -2px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tab:hover { color: var(--text); }
|
||||
.tab.active {
|
||||
color: var(--primary);
|
||||
border-bottom-color: var(--primary);
|
||||
}
|
||||
|
||||
/* Source type labels */
|
||||
.source-type-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
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-credit_card { background: #fee2e2; color: #991b1b; }
|
||||
|
||||
/* Loading */
|
||||
.loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Toast */
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 12px 20px;
|
||||
border-radius: 10px;
|
||||
color: white;
|
||||
font-size: 14px;
|
||||
z-index: 2000;
|
||||
animation: slideIn 0.3s ease;
|
||||
}
|
||||
|
||||
.toast-success { background: var(--success); }
|
||||
.toast-error { background: var(--danger); }
|
||||
|
||||
@keyframes slideIn {
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import React from 'react';
|
||||
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom';
|
||||
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';
|
||||
|
||||
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>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: '/api',
|
||||
timeout: 60000,
|
||||
});
|
||||
|
||||
// Global toast handler
|
||||
let toastHandler = null;
|
||||
export function setToastHandler(handler) { toastHandler = handler; }
|
||||
function toast(message, type = 'success') {
|
||||
if (toastHandler) toastHandler(message, type);
|
||||
}
|
||||
|
||||
export function useApi() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const call = useCallback(async (method, url, data = null, config = {}) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await api[method](url, data, config);
|
||||
return response.data;
|
||||
} catch (err) {
|
||||
const message = err.response?.data?.error || err.message || '请求失败';
|
||||
toast(message, 'error');
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { call, loading };
|
||||
}
|
||||
|
||||
// ---- API functions ----
|
||||
|
||||
// Upload
|
||||
export async function uploadFile(formData, onProgress) {
|
||||
const res = await api.post('/upload', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
onUploadProgress: (e) => {
|
||||
if (onProgress && e.total) {
|
||||
onProgress(Math.round((e.loaded / e.total) * 100));
|
||||
}
|
||||
}
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getSources() {
|
||||
const res = await api.get('/upload/sources');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function deleteSource(id) {
|
||||
const res = await api.delete(`/upload/sources/${id}`);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Transactions
|
||||
export async function getTransactions(params = {}) {
|
||||
const res = await api.get('/transactions', { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getTransaction(id) {
|
||||
const res = await api.get(`/transactions/${id}`);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function updateTransaction(id, data) {
|
||||
const res = await api.put(`/transactions/${id}`, data);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function runReconciliation() {
|
||||
const res = await api.post('/transactions/reconcile');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function classifyTransactions(ids) {
|
||||
const res = await api.post('/transactions/classify', { ids });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function classifyAll() {
|
||||
const res = await api.post('/transactions/classify-all');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Stats
|
||||
export async function getOverview(params = {}) {
|
||||
const res = await api.get('/stats/overview', { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getMonthly(months = 12) {
|
||||
const res = await api.get('/stats/monthly', { params: { months } });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getDaily(days = 30) {
|
||||
const res = await api.get('/stats/daily', { params: { days } });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// Config
|
||||
export async function getConfig() {
|
||||
const res = await api.get('/config');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function updateConfig(data) {
|
||||
const res = await api.put('/config', data);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function testLLM() {
|
||||
const res = await api.post('/config/test-llm');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function getCategories() {
|
||||
const res = await api.get('/config/categories');
|
||||
return res.data;
|
||||
}
|
||||
|
||||
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);
|
||||
const prefix = n >= 0 ? '+' : '';
|
||||
return `${prefix}${n.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export function formatDate(dateStr) {
|
||||
if (!dateStr) return '--';
|
||||
return dateStr.substring(0, 10);
|
||||
}
|
||||
|
||||
export const SOURCE_TYPE_MAP = {
|
||||
alipay: '支付宝',
|
||||
wechat: '微信支付',
|
||||
bank_debit: '银行借记卡',
|
||||
bank_credit: '银行贷记卡',
|
||||
credit_card: '信用卡'
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,193 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { TrendingUp, TrendingDown, AlertCircle, FileText, RefreshCcw } from 'lucide-react';
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
|
||||
import { getOverview, getMonthly, formatAmount } from '../hooks/useApi';
|
||||
|
||||
const COLORS = ['#4f46e5', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#f97316', '#84cc16', '#14b8a6', '#6366f1', '#e11d48'];
|
||||
|
||||
export default function Dashboard() {
|
||||
const [overview, setOverview] = useState(null);
|
||||
const [monthly, setMonthly] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
async function loadData() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [overviewData, monthlyData] = await Promise.all([
|
||||
getOverview(),
|
||||
getMonthly(12)
|
||||
]);
|
||||
setOverview(overviewData);
|
||||
setMonthly(monthlyData);
|
||||
} catch (err) {
|
||||
console.error('加载数据失败:', err);
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="loading">
|
||||
<div className="spinner"></div>
|
||||
加载中...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ov = overview?.overview || {};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>📊 财务仪表盘</h2>
|
||||
<p>全面掌握你的收支情况</p>
|
||||
</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)}</div>
|
||||
<div className="stat-sub">所有来源收入合计</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-label">💸 总支出</div>
|
||||
<div className="stat-value expense">{formatAmount(ov.total_expense)}</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'}`}>
|
||||
{formatAmount(ov.total_income - ov.total_expense)}
|
||||
</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>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
{/* Charts Row */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
|
||||
{/* Monthly Trend */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📅 月度收支趋势</h3>
|
||||
</div>
|
||||
{monthly.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<BarChart data={monthly}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis dataKey="month" tick={{ fontSize: 11 }} />
|
||||
<YAxis tick={{ fontSize: 11 }} />
|
||||
<Tooltip
|
||||
formatter={(value) => formatAmount(value)}
|
||||
labelStyle={{ fontWeight: 600 }}
|
||||
/>
|
||||
<Bar dataKey="income" name="收入" fill="#10b981" radius={[4,4,0,0]} />
|
||||
<Bar dataKey="expense" name="支出" fill="#ef4444" radius={[4,4,0,0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无数据,请先导入账单</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Category Pie */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 支出分类占比</h3>
|
||||
</div>
|
||||
{overview?.categoryStats?.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={overview.categoryStats.slice(0, 8)}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={100}
|
||||
dataKey="total_amount"
|
||||
nameKey="category"
|
||||
label={({ category, percent }) => `${category} ${(percent * 100).toFixed(0)}%`}
|
||||
labelLine={false}
|
||||
>
|
||||
{overview.categoryStats.slice(0, 8).map((_, idx) => (
|
||||
<Cell key={idx} fill={COLORS[idx % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip formatter={(value) => formatAmount(value)} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无分类数据</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Source Summary */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏦 各来源汇总</h3>
|
||||
</div>
|
||||
{overview?.sourceStats?.length > 0 ? (
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>来源</th>
|
||||
<th>交易笔数</th>
|
||||
<th>收入合计</th>
|
||||
<th>支出合计</th>
|
||||
<th>净额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{overview.sourceStats.map((s, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<span className={`source-type-label source-${s.source_type}`}>
|
||||
{s.source_type === 'alipay' && '支付宝'}
|
||||
{s.source_type === 'wechat' && '微信支付'}
|
||||
{s.source_type === 'bank_debit' && '银行借记卡'}
|
||||
{s.source_type === 'bank_credit' && '银行贷记卡'}
|
||||
{s.source_type === 'credit_card' && '信用卡'}
|
||||
</span>
|
||||
</td>
|
||||
<td>{s.count}</td>
|
||||
<td style={{ color: 'var(--success)' }}>{formatAmount(s.total_income)}</td>
|
||||
<td style={{ color: 'var(--danger)' }}>{formatAmount(s.total_expense)}</td>
|
||||
<td className={s.total_income - s.total_expense >= 0 ? 'stat-value income' : 'stat-value expense'}>
|
||||
{formatAmount(s.total_income - s.total_expense)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>暂无数据,请先导入账单</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import {
|
||||
Upload,
|
||||
FileText,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Trash2,
|
||||
RefreshCw,
|
||||
} from "lucide-react";
|
||||
import { uploadFile, getSources, deleteSource } from "../hooks/useApi";
|
||||
|
||||
const SOURCE_TYPES = [
|
||||
{
|
||||
value: "alipay",
|
||||
label: "支付宝",
|
||||
icon: "\uD83D\uDD35",
|
||||
desc: "支付宝账单 CSV/XLSX 文件",
|
||||
},
|
||||
{
|
||||
value: "wechat",
|
||||
label: "微信支付",
|
||||
icon: "\uD83D\uDFE2",
|
||||
desc: "微信支付账单 XLSX/CSV 文件",
|
||||
},
|
||||
{
|
||||
value: "bank_debit",
|
||||
label: "银行借记卡",
|
||||
icon: "\uD83C\uDFE6",
|
||||
desc: "工资卡/储蓄卡流水文件",
|
||||
},
|
||||
{
|
||||
value: "credit_card",
|
||||
label: "信用卡",
|
||||
icon: "\uD83D\uDCB3",
|
||||
desc: "信用卡账单文件",
|
||||
},
|
||||
];
|
||||
|
||||
const ALLOWED_EXTS = ["csv", "txt", "xlsx", "xls"];
|
||||
|
||||
export default function Import() {
|
||||
const [sourceType, setSourceType] = useState("alipay");
|
||||
const [sourceName, setSourceName] = useState("");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadResult, setUploadResult] = useState(null);
|
||||
const [sources, setSources] = useState([]);
|
||||
const [error, setError] = useState("");
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadSources();
|
||||
}, []);
|
||||
|
||||
async function loadSources() {
|
||||
try {
|
||||
const data = await getSources();
|
||||
setSources(data);
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleFile(file) {
|
||||
if (!file) return;
|
||||
const ext = file.name.split(".").pop().toLowerCase();
|
||||
if (!ALLOWED_EXTS.includes(ext)) {
|
||||
setError("仅支持 CSV / TXT / XLSX / XLS 文件格式");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setUploading(true);
|
||||
setUploadResult(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("source_type", sourceType);
|
||||
formData.append(
|
||||
"source_name",
|
||||
sourceName ||
|
||||
`${SOURCE_TYPES.find((s) => s.value === sourceType)?.label}_${new Date().toLocaleDateString()}`,
|
||||
);
|
||||
const result = await uploadFile(formData);
|
||||
setUploadResult(result);
|
||||
await loadSources();
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.error || err.message || "上传失败");
|
||||
}
|
||||
setUploading(false);
|
||||
}
|
||||
|
||||
async function handleDeleteSource(id) {
|
||||
if (!window.confirm("确定要删除这个导入来源及其所有交易记录吗?")) return;
|
||||
try {
|
||||
await deleteSource(id);
|
||||
await loadSources();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
function handleDrop(e) {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
handleFile(file);
|
||||
}
|
||||
|
||||
const SOURCE_LABEL_MAP = {
|
||||
alipay: "支付宝",
|
||||
wechat: "微信支付",
|
||||
bank_debit: "银行借记卡",
|
||||
bank_credit: "银行贷记卡",
|
||||
credit_card: "信用卡",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>📥 导入账单</h2>
|
||||
<p>
|
||||
上传支付宝、微信、银行卡等账单文件(CSV/TXT/XLSX/XLS),系统自动解析并分类
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 类型选择 */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>选择账单类型</h3>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
|
||||
gap: 12,
|
||||
marginBottom: 20,
|
||||
}}
|
||||
>
|
||||
{SOURCE_TYPES.map((st) => (
|
||||
<div
|
||||
key={st.value}
|
||||
onClick={() => setSourceType(st.value)}
|
||||
style={{
|
||||
padding: "16px",
|
||||
cursor: "pointer",
|
||||
textAlign: "center",
|
||||
borderRadius: "12px",
|
||||
border: `2px solid ${sourceType === st.value ? "var(--primary)" : "var(--border)"}`,
|
||||
background:
|
||||
sourceType === st.value ? "var(--primary-bg)" : "white",
|
||||
transition: "all 0.2s",
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 32, marginBottom: 8 }}>{st.icon}</div>
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>{st.label}</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
color: "var(--text-secondary)",
|
||||
marginTop: 4,
|
||||
}}
|
||||
>
|
||||
{st.desc}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>账单名称(可选)</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="如:工商银行工资卡、招商银行信用卡..."
|
||||
value={sourceName}
|
||||
onChange={(e) => setSourceName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 上传区域 */}
|
||||
<div
|
||||
className={`upload-zone ${dragOver ? "drag-over" : ""}`}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(true);
|
||||
}}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<div className="upload-icon">
|
||||
{uploading ? (
|
||||
<RefreshCw
|
||||
size={48}
|
||||
style={{ animation: "spin 1s linear infinite" }}
|
||||
/>
|
||||
) : (
|
||||
<Upload size={48} />
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: 16, fontWeight: 500, marginBottom: 8 }}>
|
||||
{uploading ? "正在解析..." : "拖拽文件到此处,或点击选择"}
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
支持 .csv / .txt / .xlsx / .xls 文件,最大 20MB
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".csv,.txt,.xlsx,.xls"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => handleFile(e.target.files[0])}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
padding: "12px 16px",
|
||||
background: "#fef2f2",
|
||||
borderRadius: 8,
|
||||
color: "var(--danger)",
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<AlertCircle size={18} />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{uploadResult && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
padding: "16px",
|
||||
background: "#f0fdf4",
|
||||
borderRadius: 8,
|
||||
border: "1px solid #bbf7d0",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
<CheckCircle size={20} color="var(--success)" />
|
||||
<span style={{ fontWeight: 600, color: "var(--success)" }}>
|
||||
导入成功!
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: "var(--text-secondary)" }}>
|
||||
共导入 <strong>{uploadResult.record_count}</strong> 笔, 写入{" "}
|
||||
<strong>
|
||||
{uploadResult.inserted ?? uploadResult.record_count}
|
||||
</strong>{" "}
|
||||
笔
|
||||
{uploadResult.skipped > 0 && (
|
||||
<span>(跳过 {uploadResult.skipped} 笔重复)</span>
|
||||
)}
|
||||
, 分类 <strong>{uploadResult.classified || 0}</strong> 笔 (
|
||||
{uploadResult.classify_source === "llm"
|
||||
? "大模型"
|
||||
: uploadResult.classify_source === "rules"
|
||||
? "规则匹配"
|
||||
: "待分类"}
|
||||
)
|
||||
</div>
|
||||
{uploadResult.sample?.length > 0 && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>
|
||||
示例数据:
|
||||
</div>
|
||||
<div className="table-container">
|
||||
<table style={{ fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>日期</th>
|
||||
<th>对方</th>
|
||||
<th>描述</th>
|
||||
<th>金额</th>
|
||||
<th>方向</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{uploadResult.sample.map((s, i) => (
|
||||
<tr key={i}>
|
||||
<td>{s.transaction_date}</td>
|
||||
<td>{s.counterparty}</td>
|
||||
<td>{s.description}</td>
|
||||
<td
|
||||
className={
|
||||
s.direction === "income"
|
||||
? "stat-value income"
|
||||
: "stat-value expense"
|
||||
}
|
||||
>
|
||||
{s.amount.toFixed(2)}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={`tag ${s.direction === "income" ? "tag-income" : "tag-expense"}`}
|
||||
>
|
||||
{s.direction === "income" ? "收入" : "支出"}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 已导入列表 */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📋 已导入的账单</h3>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadSources}>
|
||||
<RefreshCw size={14} /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
{sources.length > 0 ? (
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>账单名称</th>
|
||||
<th>类型</th>
|
||||
<th>文件名</th>
|
||||
<th>记录数</th>
|
||||
<th>导入时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sources.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>
|
||||
<FileText size={14} style={{ marginRight: 6 }} />
|
||||
{s.source_name}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={`source-type-label source-${s.source_type}`}
|
||||
>
|
||||
{SOURCE_LABEL_MAP[s.source_type] || s.source_type}
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
style={{ fontSize: 12, color: "var(--text-secondary)" }}
|
||||
>
|
||||
{s.file_name}
|
||||
</td>
|
||||
<td>{s.tx_count || s.record_count}</td>
|
||||
<td style={{ fontSize: 12 }}>{s.imported_at}</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
onClick={() => handleDeleteSource(s.id)}
|
||||
>
|
||||
<Trash2 size={12} /> 删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>还没有导入任何账单</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { CheckCircle, X, Edit3, Brain, Search, Filter } from 'lucide-react';
|
||||
import { getTransactions, updateTransaction, formatAmount, formatDate, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
|
||||
|
||||
export default function Review() {
|
||||
const [transactions, setTransactions] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [editingTx, setEditingTx] = useState(null);
|
||||
const [showReviewed, setShowReviewed] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
loadReviewTransactions();
|
||||
}, [showReviewed, keyword]);
|
||||
|
||||
async function loadCategories() {
|
||||
try {
|
||||
const cats = await getCategories();
|
||||
setCategories(cats);
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function loadReviewTransactions() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = {
|
||||
min_amount: 100, // Only >= 100 RMB
|
||||
limit: 200,
|
||||
sort_by: 'amount',
|
||||
sort_order: 'DESC'
|
||||
};
|
||||
if (!showReviewed) params.reviewed = 0;
|
||||
if (keyword) params.keyword = keyword;
|
||||
|
||||
const result = await getTransactions(params);
|
||||
setTransactions(result.transactions);
|
||||
setTotal(result.total);
|
||||
|
||||
// Update badge count in sidebar
|
||||
try {
|
||||
const badge = document.getElementById('review-badge');
|
||||
if (badge) {
|
||||
// Get fresh unreviewed count
|
||||
const { getOverview } = require('../hooks/useApi');
|
||||
// Just use local count
|
||||
if (!showReviewed) badge.textContent = result.total;
|
||||
}
|
||||
} catch (e) {}
|
||||
} catch (err) {}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
async function handleConfirm(tx) {
|
||||
try {
|
||||
await updateTransaction(tx.id, { reviewed: 1 });
|
||||
loadReviewTransactions();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleUpdateTx(id, updates) {
|
||||
try {
|
||||
await updateTransaction(id, updates);
|
||||
setEditingTx(null);
|
||||
loadReviewTransactions();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleConfirmAll() {
|
||||
if (!window.confirm(`确定要批量确认当前显示的 ${transactions.length} 笔交易吗?`)) return;
|
||||
for (const tx of transactions) {
|
||||
if (!tx.reviewed) {
|
||||
try { await updateTransaction(tx.id, { reviewed: 1 }); } catch (err) {}
|
||||
}
|
||||
}
|
||||
loadReviewTransactions();
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>🔍 大额交易确认</h2>
|
||||
<p>逐笔确认 ≥100 元的交易,核对AI分类和描述是否正确</p>
|
||||
</div>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<div className="form-group" style={{ marginBottom: 0, minWidth: 200 }}>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="🔍 搜索对方/描述..."
|
||||
value={keyword}
|
||||
onChange={e => setKeyword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 14 }}>
|
||||
<input type="checkbox" checked={showReviewed} onChange={e => setShowReviewed(e.target.checked)} />
|
||||
显示已确认
|
||||
</label>
|
||||
<div style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
|
||||
共 <strong>{total}</strong> 笔大额交易
|
||||
{!showReviewed && <span style={{ color: 'var(--warning)' }}>(待确认)</span>}
|
||||
</span>
|
||||
<button className="btn btn-success btn-sm" onClick={handleConfirmAll}>
|
||||
<CheckCircle size={14} /> 全部确认
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Review List */}
|
||||
<div className="card">
|
||||
{loading ? (
|
||||
<div className="loading"><div className="spinner"></div>加载中...</div>
|
||||
) : transactions.length > 0 ? (
|
||||
<div>
|
||||
{transactions.map(tx => (
|
||||
<div key={tx.id} className={`review-item ${tx.reviewed ? 'reviewed' : ''}`}>
|
||||
<div className={`amount-col ${tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}`}>
|
||||
{formatAmount(tx.amount)}
|
||||
</div>
|
||||
|
||||
<div className="info-col">
|
||||
<div className="title">
|
||||
{tx.ai_description || tx.description || '无描述'}
|
||||
</div>
|
||||
<div className="meta">
|
||||
{formatDate(tx.transaction_date)} ·
|
||||
<span className={`source-type-label source-${tx.source_type}`} style={{ marginLeft: 4 }}>
|
||||
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}
|
||||
</span>
|
||||
{tx.counterparty && <span> · {tx.counterparty}</span>}
|
||||
{tx.category && (
|
||||
<span className="tag tag-matched" style={{ marginLeft: 6 }}>{tx.category}</span>
|
||||
)}
|
||||
{tx.reviewed && <span style={{ marginLeft: 6, color: 'var(--success)' }}>✓ 已确认</span>}
|
||||
{tx.matched_transaction_id && (
|
||||
<span className="tag tag-matched" style={{ marginLeft: 6 }}>已对账</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="action-col">
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingTx({ ...tx })}>
|
||||
<Edit3 size={12} /> 编辑
|
||||
</button>
|
||||
{!tx.reviewed && (
|
||||
<button className="btn btn-success btn-sm" onClick={() => handleConfirm(tx)}>
|
||||
<CheckCircle size={12} /> 确认
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">✅</div>
|
||||
<p>{showReviewed ? '没有已确认的大额交易' : '所有大额交易已确认!'}</p>
|
||||
<p style={{ fontSize: 13, marginTop: 8 }}>
|
||||
{showReviewed ? '尝试切换显示模式' : '可以去交易明细页面查看所有记录'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit Modal */}
|
||||
{editingTx && (
|
||||
<div className="modal-overlay" onClick={() => setEditingTx(null)}>
|
||||
<div className="modal" onClick={e => e.stopPropagation()}>
|
||||
<h3>编辑交易分类与描述</h3>
|
||||
|
||||
<div style={{
|
||||
marginBottom: 16, padding: 12, background: 'var(--bg)',
|
||||
borderRadius: 8, fontSize: 13
|
||||
}}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{formatAmount(editingTx.amount)} · {formatDate(editingTx.transaction_date)}
|
||||
</div>
|
||||
<div style={{ color: 'var(--text-secondary)' }}>
|
||||
{editingTx.counterparty} · {editingTx.description}
|
||||
</div>
|
||||
<div style={{ fontFamily: 'monospace', fontSize: 11, color: 'var(--text-secondary)', marginTop: 4 }}>
|
||||
编码: {editingTx.transaction_code}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>分类</label>
|
||||
<select className="form-select" value={editingTx.category || ''}
|
||||
onChange={e => setEditingTx({ ...editingTx, category: e.target.value })}>
|
||||
<option value="">选择分类</option>
|
||||
{categories.map(c => (
|
||||
<option key={c.id} value={c.name}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>交易描述</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={editingTx.ai_description || ''}
|
||||
onChange={e => setEditingTx({ ...editingTx, ai_description: e.target.value })}
|
||||
placeholder="简要描述这笔交易..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>备注</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={editingTx.review_notes || ''}
|
||||
onChange={e => setEditingTx({ ...editingTx, review_notes: e.target.value })}
|
||||
placeholder="人工备注(可选)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
|
||||
<button className="btn btn-secondary" onClick={() => setEditingTx(null)}>取消</button>
|
||||
<button className="btn btn-primary" onClick={() => handleUpdateTx(editingTx.id, {
|
||||
category: editingTx.category,
|
||||
ai_description: editingTx.ai_description,
|
||||
review_notes: editingTx.review_notes,
|
||||
reviewed: 1
|
||||
})}>
|
||||
保存并确认
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw } from 'lucide-react';
|
||||
import { getConfig, updateConfig, testLLM, getCategories, updateCategory } 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 [categories, setCategories] = useState([]);
|
||||
const [llmStatus, setLLMStatus] = useState(null);
|
||||
const [testingLlm, setTestingLlm] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editingCat, setEditingCat] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
|
||||
async function loadAll() {
|
||||
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 handleTestLLM() {
|
||||
setTestingLlm(true);
|
||||
setLLMStatus(null);
|
||||
// Save config first
|
||||
await updateConfig(config);
|
||||
try {
|
||||
const result = await testLLM();
|
||||
setLLMStatus({ success: true, message: `连接成功!模型: ${result.model}, 回复: ${result.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) {}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>⚙️ 系统设置</h2>
|
||||
<p>配置大模型API及管理交易分类</p>
|
||||
</div>
|
||||
|
||||
{/* LLM Configuration */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🤖 大模型配置</h3>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
支持 OpenAI 兼容API(Ollama、DeepSeek、通义千问等)
|
||||
</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 style={{ fontSize: 11, color: 'var(--text-secondary)', marginTop: 4 }}>
|
||||
常用模型: gpt-4o-mini, gpt-4o, deepseek-chat, qwen-turbo, llama3
|
||||
</div>
|
||||
</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>
|
||||
|
||||
{/* Category Management */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 分类管理</h3>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}>
|
||||
<RefreshCw size={14} /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>
|
||||
管理交易分类及其关键词,AI会根据关键词进行自动分类
|
||||
</div>
|
||||
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 60 }}>ID</th>
|
||||
<th>分类名称</th>
|
||||
<th>关键词(逗号分隔)</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{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>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={async () => {
|
||||
const keywords = editingCat.keywords.split(',').map(k => k.trim()).filter(Boolean);
|
||||
await handleUpdateCategory(cat.id, 'name', editingCat.name);
|
||||
await handleUpdateCategory(cat.id, 'keywords', keywords);
|
||||
setEditingCat(null);
|
||||
}}>
|
||||
<Save size={12} /> 保存
|
||||
</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat(null)}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat({
|
||||
...cat,
|
||||
keywords: JSON.parse(cat.keywords || '[]').join(', ')
|
||||
})}>
|
||||
编辑
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* About */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>📦 关于 Reco</h3>
|
||||
</div>
|
||||
<div style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.8 }}>
|
||||
<p><strong>Reco</strong> —— 银行流水对账分析系统 v1.0.0</p>
|
||||
<p>🏦 支持支付宝、微信支付、银行卡、信用卡账单导入</p>
|
||||
<p>🔗 自动匹配跨来源的同一笔交易,实现智能对账</p>
|
||||
<p>🤖 集成大模型能力,自动分类和描述每一笔交易</p>
|
||||
<p>✅ 大额交易确认机制,确保重要交易准确无误</p>
|
||||
<p style={{ marginTop: 12, fontSize: 12 }}>
|
||||
数据存储位置:<code>data/reco.db</code>(SQLite 本地数据库)
|
||||
</p>
|
||||
<p style={{ fontSize: 12 }}>
|
||||
数据完全保存在本地,不会上传到任何服务器
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Search, Filter, RotateCcw, RefreshCw, Link2, Brain, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { getTransactions, updateTransaction, runReconciliation, classifyAll, formatAmount, formatDate, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
|
||||
|
||||
export default function Transactions() {
|
||||
const [data, setData] = useState({ transactions: [], total: 0, page: 1, totalPages: 0 });
|
||||
const [filters, setFilters] = useState({
|
||||
page: 1, limit: 50, start_date: '', end_date: '',
|
||||
source_type: '', direction: '', category: '', reviewed: '', min_amount: '', keyword: '',
|
||||
sort_by: 'transaction_date', sort_order: 'DESC'
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [editingTx, setEditingTx] = useState(null);
|
||||
const [reconciling, setReconciling] = useState(false);
|
||||
const [classifying, setClassifying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadTransactions();
|
||||
}, [filters]);
|
||||
|
||||
async function loadCategories() {
|
||||
try {
|
||||
const cats = await getCategories();
|
||||
setCategories(cats);
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function loadTransactions() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = { ...filters };
|
||||
// Remove empty filter values
|
||||
Object.keys(params).forEach(k => {
|
||||
if (params[k] === '' || params[k] === undefined) delete params[k];
|
||||
});
|
||||
const result = await getTransactions(params);
|
||||
setData(result);
|
||||
} catch (err) {}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
function updateFilter(key, value) {
|
||||
setFilters(prev => ({ ...prev, [key]: value, page: key === 'page' ? value : 1 }));
|
||||
}
|
||||
|
||||
async function handleReconcile() {
|
||||
setReconciling(true);
|
||||
try {
|
||||
const result = await runReconciliation();
|
||||
alert(`对账完成!成功匹配 ${result.matched} 对交易(共检查 ${result.total} 笔)`);
|
||||
loadTransactions();
|
||||
} catch (err) {}
|
||||
setReconciling(false);
|
||||
}
|
||||
|
||||
async function handleClassifyAll() {
|
||||
setClassifying(true);
|
||||
try {
|
||||
const result = await classifyAll();
|
||||
alert(`分类完成!共分类 ${result.classified} 笔交易`);
|
||||
loadTransactions();
|
||||
} catch (err) {}
|
||||
setClassifying(false);
|
||||
}
|
||||
|
||||
async function handleUpdateTx(id, updates) {
|
||||
try {
|
||||
await updateTransaction(id, updates);
|
||||
setEditingTx(null);
|
||||
loadTransactions();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
function openEdit(tx) {
|
||||
setEditingTx({ ...tx });
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>📋 交易明细</h2>
|
||||
<p>查看、筛选、对账和分类所有交易记录</p>
|
||||
</div>
|
||||
|
||||
{/* Action Bar */}
|
||||
<div style={{ display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap' }}>
|
||||
<button className="btn btn-primary" onClick={handleReconcile} disabled={reconciling}>
|
||||
<Link2 size={16} /> {reconciling ? '对账中...' : '自动对账'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={handleClassifyAll} disabled={classifying}>
|
||||
<Brain size={16} /> {classifying ? '分类中...' : 'AI 分类全部'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={() => { setFilters({ page: 1, limit: 50, start_date: '', end_date: '', source_type: '', direction: '', category: '', reviewed: '', min_amount: '', keyword: '', sort_by: 'transaction_date', sort_order: 'DESC' }); }}>
|
||||
<RotateCcw size={16} /> 重置筛选
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="card" style={{ padding: '16px 20px' }}>
|
||||
<div className="filter-bar">
|
||||
<div className="form-group">
|
||||
<label>开始日期</label>
|
||||
<input type="date" className="form-input" value={filters.start_date} onChange={e => updateFilter('start_date', e.target.value)} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>结束日期</label>
|
||||
<input type="date" className="form-input" value={filters.end_date} onChange={e => updateFilter('end_date', e.target.value)} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>来源</label>
|
||||
<select className="form-select" value={filters.source_type} onChange={e => updateFilter('source_type', e.target.value)}>
|
||||
<option value="">全部</option>
|
||||
{Object.entries(SOURCE_TYPE_MAP).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>方向</label>
|
||||
<select className="form-select" value={filters.direction} onChange={e => updateFilter('direction', e.target.value)}>
|
||||
<option value="">全部</option>
|
||||
<option value="income">收入</option>
|
||||
<option value="expense">支出</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>分类</label>
|
||||
<select className="form-select" value={filters.category} onChange={e => updateFilter('category', e.target.value)}>
|
||||
<option value="">全部</option>
|
||||
{categories.map(c => (
|
||||
<option key={c.id} value={c.name}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>确认状态</label>
|
||||
<select className="form-select" value={filters.reviewed} onChange={e => updateFilter('reviewed', e.target.value)}>
|
||||
<option value="">全部</option>
|
||||
<option value="0">未确认</option>
|
||||
<option value="1">已确认</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>关键词</label>
|
||||
<input type="text" className="form-input" placeholder="搜索对方/描述..." value={filters.keyword} onChange={e => updateFilter('keyword', e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transaction Table */}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>共 {data.total} 笔交易</h3>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
|
||||
第 {data.page}/{data.totalPages} 页
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="loading"><div className="spinner"></div>加载中...</div>
|
||||
) : data.transactions.length > 0 ? (
|
||||
<>
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>交易编码</th>
|
||||
<th>日期</th>
|
||||
<th>来源</th>
|
||||
<th>对方</th>
|
||||
<th>描述</th>
|
||||
<th>分类</th>
|
||||
<th style={{ textAlign: 'right' }}>金额</th>
|
||||
<th>方向</th>
|
||||
<th>匹配</th>
|
||||
<th>确认</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.transactions.map(tx => (
|
||||
<tr key={tx.id}>
|
||||
<td style={{ fontFamily: 'monospace', fontSize: 11, color: 'var(--text-secondary)' }}>
|
||||
{tx.transaction_code}
|
||||
</td>
|
||||
<td>{formatDate(tx.transaction_date)}</td>
|
||||
<td>
|
||||
<span className={`source-type-label source-${tx.source_type}`}>
|
||||
{SOURCE_TYPE_MAP[tx.source_type] || tx.source_type}
|
||||
</span>
|
||||
</td>
|
||||
<td>{tx.counterparty || '--'}</td>
|
||||
<td style={{ maxWidth: 150, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{tx.ai_description || tx.description || '--'}
|
||||
</td>
|
||||
<td>
|
||||
{tx.category ? (
|
||||
<span className="tag tag-matched">{tx.category}</span>
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-secondary)', fontSize: 11 }}>未分类</span>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ textAlign: 'right', fontWeight: 600 }} className={tx.direction === 'income' ? 'stat-value income' : 'stat-value expense'}>
|
||||
{formatAmount(tx.amount)}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`tag ${tx.direction === 'income' ? 'tag-income' : 'tag-expense'}`}>
|
||||
{tx.direction === 'income' ? '收入' : '支出'}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{tx.matched_transaction_id ? (
|
||||
<span className="tag tag-matched" title={`匹配得分: ${tx.match_score}`}>已对账</span>
|
||||
) : <span style={{ fontSize: 11, color: 'var(--text-secondary)' }}>--</span>}
|
||||
</td>
|
||||
<td>
|
||||
{tx.reviewed ? (
|
||||
<span style={{ color: 'var(--success)', fontSize: 11 }}>✓ 已确认</span>
|
||||
) : (
|
||||
<span className="tag tag-unreviewed">待确认</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => openEdit(tx)}>
|
||||
编辑
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{data.totalPages > 1 && (
|
||||
<div className="pagination">
|
||||
<button disabled={data.page <= 1} onClick={() => updateFilter('page', data.page - 1)}>
|
||||
<ChevronLeft size={14} /> 上一页
|
||||
</button>
|
||||
{Array.from({ length: Math.min(data.totalPages, 7) }, (_, i) => {
|
||||
const pageNum = i + Math.max(1, data.page - 3);
|
||||
if (pageNum > data.totalPages) return null;
|
||||
return (
|
||||
<button key={pageNum} className={data.page === pageNum ? 'active' : ''}
|
||||
onClick={() => updateFilter('page', pageNum)}>
|
||||
{pageNum}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button disabled={data.page >= data.totalPages} onClick={() => updateFilter('page', data.page + 1)}>
|
||||
下一页 <ChevronRight size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="icon">📭</div>
|
||||
<p>没有找到交易记录</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit Modal */}
|
||||
{editingTx && (
|
||||
<div className="modal-overlay" onClick={() => setEditingTx(null)}>
|
||||
<div className="modal" onClick={e => e.stopPropagation()}>
|
||||
<h3>编辑交易</h3>
|
||||
<div style={{ marginBottom: 12, fontSize: 13, color: 'var(--text-secondary)' }}>
|
||||
{editingTx.transaction_code} | {formatDate(editingTx.transaction_date)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>分类</label>
|
||||
<select className="form-select" value={editingTx.category || ''}
|
||||
onChange={e => setEditingTx({ ...editingTx, category: e.target.value })}>
|
||||
<option value="">选择分类</option>
|
||||
{categories.map(c => (
|
||||
<option key={c.id} value={c.name}>{c.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>AI描述</label>
|
||||
<input type="text" className="form-input" value={editingTx.ai_description || ''}
|
||||
onChange={e => setEditingTx({ ...editingTx, ai_description: e.target.value })} />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>确认状态</label>
|
||||
<select className="form-select" value={editingTx.reviewed || 0}
|
||||
onChange={e => setEditingTx({ ...editingTx, reviewed: parseInt(e.target.value) })}>
|
||||
<option value={0}>未确认</option>
|
||||
<option value={1}>已确认</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
|
||||
<button className="btn btn-secondary" onClick={() => setEditingTx(null)}>取消</button>
|
||||
<button className="btn btn-primary" onClick={() => handleUpdateTx(editingTx.id, {
|
||||
category: editingTx.category,
|
||||
ai_description: editingTx.ai_description,
|
||||
reviewed: editingTx.reviewed
|
||||
})}>保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Generated
+1846
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,9 @@
|
||||
`关闭powershell的脚本限制
|
||||
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
|
||||
|
||||
遭遇zed内npm instal失败问题,报错为sqlite3-better组建需要调用原生node-gyp编译。报错大意为better-sqlite3需要编译原生模块但网络超时调了下梯子和莫名其妙好了的。
|
||||
|
||||
1.先把数据导入的功能做清楚
|
||||
2.把交易合并功能做清楚
|
||||
2.把调用大模型做分类的功能做清楚
|
||||
3.最后调报表
|
||||
@@ -0,0 +1,115 @@
|
||||
const XLSX = require("xlsx");
|
||||
const dayjs = require("dayjs");
|
||||
|
||||
/**
|
||||
* 浦发银行 XLS/XLSX 流水解析
|
||||
*
|
||||
* 格式:
|
||||
* Row 0: 元数据 (账号, 账户类型, 日期范围)
|
||||
* Row 1: 表头 (顺序号, 交易日期, 交易类型, 存入金额, 取出金额, 余额, 交易对手名称, 交易对手账号, 附言)
|
||||
* Row 2+: 数据
|
||||
*/
|
||||
|
||||
function parseSPDBXLS(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 3) return [];
|
||||
|
||||
// 提取账号
|
||||
const accountNo = String(rows[0][1] || "");
|
||||
|
||||
const transactions = [];
|
||||
|
||||
for (let i = 2; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length < 8) continue;
|
||||
|
||||
const dateStr = String(row[1] || "").trim(); // "2025/05/06 01:12:46"
|
||||
const typeRaw = String(row[2] || "").trim(); // "网上支付-财付通—来伊份"
|
||||
const depositStr = row[3]; // 存入金额
|
||||
const withdrawStr = row[4]; // 取出金额
|
||||
const balanceStr = row[5]; // 余额
|
||||
const counterparty = String(row[6] || "").trim(); // 对手名称
|
||||
const opponentAcct = String(row[7] || "").trim(); // 对手账号
|
||||
const appendix = String(row[8] || "").trim(); // 附言
|
||||
|
||||
if (!dateStr) continue;
|
||||
|
||||
// 金额:存入或取出
|
||||
let amount = 0;
|
||||
let direction = "expense";
|
||||
if (depositStr !== "" && depositStr !== undefined && depositStr !== null) {
|
||||
amount = parseFloat(depositStr);
|
||||
direction = "income";
|
||||
} else if (
|
||||
withdrawStr !== "" &&
|
||||
withdrawStr !== undefined &&
|
||||
withdrawStr !== null
|
||||
) {
|
||||
amount = -parseFloat(withdrawStr);
|
||||
direction = "expense";
|
||||
}
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
const balance = balanceStr ? parseFloat(balanceStr) : null;
|
||||
|
||||
// 日期/时间解析
|
||||
const parsed = dayjs(dateStr, [
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY/MM/DD",
|
||||
]);
|
||||
const txDate = parsed.format("YYYY-MM-DD");
|
||||
const txTime = parsed.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
// 交易类型拆解: "网上支付-财付通—来伊份" → type="网上支付-财付通", desc="网上支付-财付通—来伊份"
|
||||
let description = typeRaw;
|
||||
let txType = typeRaw;
|
||||
const dashIdx = typeRaw.indexOf("—");
|
||||
if (dashIdx > 0) {
|
||||
txType = typeRaw.substring(0, dashIdx);
|
||||
}
|
||||
|
||||
// 支付方式
|
||||
let method = "";
|
||||
if (typeRaw.includes("财付通")) method = "财付通";
|
||||
else if (typeRaw.includes("支付宝")) method = "支付宝";
|
||||
else if (typeRaw.includes("工资")) method = "代发工资";
|
||||
else if (typeRaw.includes("转账")) method = "银行转账";
|
||||
else if (typeRaw.includes("银联")) method = "银联";
|
||||
else method = txType;
|
||||
|
||||
transactions.push({
|
||||
transaction_date: txDate,
|
||||
transaction_time: txTime,
|
||||
counterparty,
|
||||
description,
|
||||
notes: appendix, // 附言
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method,
|
||||
account_no: accountNo,
|
||||
opponent_account: opponentAcct,
|
||||
raw_data: JSON.stringify({
|
||||
dateStr,
|
||||
typeRaw,
|
||||
depositStr,
|
||||
withdrawStr,
|
||||
balanceStr,
|
||||
counterparty,
|
||||
opponentAcct,
|
||||
appendix,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseSPDBXLS };
|
||||
@@ -0,0 +1,23 @@
|
||||
const express = require('express');
|
||||
const { classifyTransactions } = 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 classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error('[Reco] 分类失败:', err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,250 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/config - 获取所有配置
|
||||
router.get("/", (req, res) => {
|
||||
const db = getDB();
|
||||
const configs = db.prepare("SELECT key, value FROM config").all();
|
||||
const configMap = {};
|
||||
for (const c of configs) {
|
||||
configMap[c.key] = c.value;
|
||||
}
|
||||
res.json(configMap);
|
||||
});
|
||||
|
||||
// PUT /api/config - 更新配置
|
||||
router.put("/", (req, res) => {
|
||||
const db = getDB();
|
||||
const updates = req.body;
|
||||
|
||||
if (!updates || Object.keys(updates).length === 0) {
|
||||
return res.status(400).json({ error: "请提供要更新的配置" });
|
||||
}
|
||||
|
||||
const upsert = db.prepare(
|
||||
"INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?",
|
||||
);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const [key, value] of Object.entries(updates)) {
|
||||
upsert.run(key, String(value), String(value));
|
||||
}
|
||||
})();
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm - 测试LLM连接(详细调试版)
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
const { getOpenAIClient } = require("../services/llm");
|
||||
|
||||
console.log("[Reco] ========== LLM 连接测试开始 ==========");
|
||||
|
||||
// 1. 检查数据库配置
|
||||
const db = getDB();
|
||||
const apiKeyRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
|
||||
.get();
|
||||
const baseUrlRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
|
||||
.get();
|
||||
const modelRow = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
|
||||
.get();
|
||||
|
||||
console.log("[Reco] [调试] 数据库配置检查:");
|
||||
console.log(" API Key 存在:", !!apiKeyRow?.value);
|
||||
console.log(" API Key 长度:", apiKeyRow?.value?.length || 0);
|
||||
console.log(
|
||||
" Base URL:",
|
||||
baseUrlRow?.value || "(使用默认 https://api.openai.com/v1)",
|
||||
);
|
||||
console.log(" Model:", modelRow?.value || "(使用默认 gpt-4o-mini)");
|
||||
|
||||
// 2. 尝试创建客户端
|
||||
let client;
|
||||
try {
|
||||
client = getOpenAIClient();
|
||||
} catch (clientErr) {
|
||||
console.error("[Reco] [调试] 创建LLM客户端异常:", clientErr.message);
|
||||
return res.status(500).json({
|
||||
error: `创建LLM客户端失败: ${clientErr.message}`,
|
||||
debug: { errorType: "client_init_error", errorDetail: clientErr.message },
|
||||
});
|
||||
}
|
||||
|
||||
if (!client) {
|
||||
console.log("[Reco] [调试] LLM客户端为空 - 请检查API Key配置");
|
||||
return res.status(400).json({
|
||||
error: "请先在系统设置中配置 LLM API Key",
|
||||
debug: {
|
||||
hasApiKey: !!apiKeyRow?.value,
|
||||
hasBaseUrl: !!baseUrlRow?.value,
|
||||
hasModel: !!modelRow?.value,
|
||||
hint: "前往 系统设置 → 大模型配置 填入API Key",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[Reco] [调试] LLM客户端创建成功");
|
||||
console.log(" Model:", client._model);
|
||||
console.log(" BaseURL:", client.baseURL || "(未暴露)");
|
||||
|
||||
// 3. 发送测试请求
|
||||
const startTime = Date.now();
|
||||
try {
|
||||
console.log("[Reco] [调试] 正在发送测试请求 (timeout: 15s)...");
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [{ role: "user", content: '请回复"连接成功"两个字' }],
|
||||
max_tokens: 10,
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const reply = response.choices?.[0]?.message?.content || "(空)";
|
||||
|
||||
console.log(`[Reco] [调试] ✅ LLM测试成功!`);
|
||||
console.log(` 耗时: ${elapsed}ms`);
|
||||
console.log(` 回复: "${reply}"`);
|
||||
console.log(
|
||||
` Token用量:`,
|
||||
response.usage ? JSON.stringify(response.usage) : "未返回",
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
reply,
|
||||
model: client._model,
|
||||
elapsed_ms: elapsed,
|
||||
usage: response.usage || null,
|
||||
});
|
||||
} catch (err) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
|
||||
console.error(`[Reco] [调试] ❌ LLM测试失败! 耗时: ${elapsed}ms`);
|
||||
console.error(" 错误类型:", err.constructor?.name || typeof err);
|
||||
console.error(" 错误消息:", err.message);
|
||||
console.error(" 错误代码:", err.code || "(无)");
|
||||
console.error(" HTTP状态码:", err.status || err.statusCode || "(无)");
|
||||
|
||||
// OpenAI SDK v4 的错误详情
|
||||
if (err.error) {
|
||||
console.error(" API错误详情:", JSON.stringify(err.error));
|
||||
}
|
||||
if (err.response) {
|
||||
console.error(" 响应状态:", err.response.status);
|
||||
console.error(
|
||||
" 响应头:",
|
||||
JSON.stringify(err.response.headers || {}).substring(0, 300),
|
||||
);
|
||||
try {
|
||||
console.error(
|
||||
" 响应体:",
|
||||
JSON.stringify(
|
||||
err.response.data || err.response.body || {},
|
||||
).substring(0, 800),
|
||||
);
|
||||
} catch (e) {}
|
||||
}
|
||||
if (err.stack) {
|
||||
console.error(" 堆栈(首500):", err.stack.substring(0, 500));
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: `LLM 连接失败: ${err.message}`,
|
||||
debug: {
|
||||
errorType: err.constructor?.name || typeof err,
|
||||
errorCode: err.code || null,
|
||||
httpStatus: err.status || err.statusCode || null,
|
||||
elapsed_ms: elapsed,
|
||||
apiBaseUrl: baseUrlRow?.value || "https://api.openai.com/v1",
|
||||
model: client._model,
|
||||
hint: getHint(err),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[Reco] ========== LLM 连接测试结束 ==========");
|
||||
});
|
||||
|
||||
function getHint(err) {
|
||||
const msg = (err.message || "").toLowerCase();
|
||||
if (
|
||||
msg.includes("401") ||
|
||||
msg.includes("unauthorized") ||
|
||||
msg.includes("invalid api key")
|
||||
) {
|
||||
return "API Key 无效或未授权,请检查 Key 是否正确";
|
||||
}
|
||||
if (msg.includes("404") || msg.includes("not found")) {
|
||||
return "模型名称或API端点不存在,请检查 Base URL 和模型名";
|
||||
}
|
||||
if (
|
||||
msg.includes("timeout") ||
|
||||
msg.includes("etimedout") ||
|
||||
msg.includes("enotfound")
|
||||
) {
|
||||
return "网络连接超时或DNS解析失败,请检查 Base URL 和网络";
|
||||
}
|
||||
if (msg.includes("429") || msg.includes("rate")) {
|
||||
return "请求频率过高或被限流,请稍后重试";
|
||||
}
|
||||
if (
|
||||
msg.includes("connect") ||
|
||||
msg.includes("refused") ||
|
||||
msg.includes("econnrefused")
|
||||
) {
|
||||
return "无法连接到API服务器,请确认 Base URL 正确且服务正在运行";
|
||||
}
|
||||
return "请检查 API Key、Base URL 和 Model 配置是否正确";
|
||||
}
|
||||
|
||||
// GET /api/config/categories - 获取分类列表
|
||||
router.get("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
const categories = db.prepare("SELECT * FROM categories ORDER BY id").all();
|
||||
res.json(categories);
|
||||
});
|
||||
|
||||
// PUT /api/config/categories/:id - 更新分类
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords } = req.body;
|
||||
|
||||
db.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 });
|
||||
});
|
||||
|
||||
// POST /api/config/categories - 新增分类
|
||||
router.post("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
const { name, keywords, parent_id } = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: "分类名称不能为空" });
|
||||
}
|
||||
|
||||
const result = db
|
||||
.prepare(
|
||||
"INSERT INTO categories (name, keywords, parent_id) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null);
|
||||
|
||||
res.json({ success: true, id: result.lastInsertRowid });
|
||||
});
|
||||
|
||||
// DELETE /api/config/categories/:id - 删除分类
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
db.prepare("DELETE FROM categories WHERE id = ?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,110 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/stats/overview - 总览统计
|
||||
router.get('/overview', (req, res) => {
|
||||
const db = getDB();
|
||||
const { year, month } = req.query;
|
||||
|
||||
let dateCondition = '';
|
||||
const params = [];
|
||||
|
||||
if (year) {
|
||||
dateCondition = 'WHERE strftime(\'%Y\', transaction_date) = ?';
|
||||
params.push(String(year));
|
||||
if (month) {
|
||||
dateCondition += ' AND strftime(\'%m\', transaction_date) = ?';
|
||||
params.push(String(month).padStart(2, '0'));
|
||||
}
|
||||
}
|
||||
|
||||
const stats = db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as total_count,
|
||||
COALESCE(SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END), 0) as total_income,
|
||||
COALESCE(SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END), 0) as total_expense,
|
||||
COUNT(CASE WHEN reviewed = 0 AND ABS(amount) >= 100 THEN 1 END) as pending_review,
|
||||
COUNT(CASE WHEN reviewed = 1 THEN 1 END) as reviewed_count,
|
||||
COUNT(CASE WHEN matched_transaction_id IS NOT NULL THEN 1 END) as matched_count
|
||||
FROM transactions
|
||||
${dateCondition}
|
||||
`).get(...params);
|
||||
|
||||
// 按分类统计支出
|
||||
const categoryStats = db.prepare(`
|
||||
SELECT
|
||||
category,
|
||||
COUNT(*) as count,
|
||||
SUM(ABS(amount)) as total_amount,
|
||||
AVG(ABS(amount)) as avg_amount
|
||||
FROM transactions
|
||||
${dateCondition}${dateCondition ? ' AND' : 'WHERE'} direction = 'expense' AND category IS NOT NULL
|
||||
GROUP BY category
|
||||
ORDER BY total_amount DESC
|
||||
`).all(...params);
|
||||
|
||||
// 按来源统计
|
||||
const sourceStats = db.prepare(`
|
||||
SELECT
|
||||
t.source_type,
|
||||
s.source_name,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN t.direction = 'income' THEN t.amount ELSE 0 END) as total_income,
|
||||
SUM(CASE WHEN t.direction = 'expense' THEN ABS(t.amount) ELSE 0 END) as total_expense
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
${dateCondition}
|
||||
GROUP BY t.source_type
|
||||
ORDER BY total_expense DESC
|
||||
`).all(...params);
|
||||
|
||||
res.json({
|
||||
overview: stats,
|
||||
categoryStats,
|
||||
sourceStats
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/stats/monthly - 月度趋势
|
||||
router.get('/monthly', (req, res) => {
|
||||
const db = getDB();
|
||||
const { months = 12 } = req.query;
|
||||
|
||||
const monthlyData = db.prepare(`
|
||||
SELECT
|
||||
strftime('%Y-%m', transaction_date) as month,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
|
||||
FROM transactions
|
||||
WHERE transaction_date >= DATE('now', '-${parseInt(months)} months')
|
||||
GROUP BY strftime('%Y-%m', transaction_date)
|
||||
ORDER BY month ASC
|
||||
`).all();
|
||||
|
||||
res.json(monthlyData);
|
||||
});
|
||||
|
||||
// GET /api/stats/daily - 每日统计
|
||||
router.get('/daily', (req, res) => {
|
||||
const db = getDB();
|
||||
const { days = 30 } = req.query;
|
||||
|
||||
const dailyData = db.prepare(`
|
||||
SELECT
|
||||
transaction_date as date,
|
||||
COUNT(*) as count,
|
||||
SUM(CASE WHEN direction = 'income' THEN amount ELSE 0 END) as income,
|
||||
SUM(CASE WHEN direction = 'expense' THEN ABS(amount) ELSE 0 END) as expense
|
||||
FROM transactions
|
||||
WHERE transaction_date >= DATE('now', '-${parseInt(days)} days')
|
||||
GROUP BY transaction_date
|
||||
ORDER BY date ASC
|
||||
`).all();
|
||||
|
||||
res.json(dailyData);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,284 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { runAutoReconciliation } = require('../services/matcher');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/transactions - 获取交易列表(支持筛选和分页)
|
||||
router.get('/', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 50,
|
||||
start_date,
|
||||
end_date,
|
||||
source_type,
|
||||
direction,
|
||||
category,
|
||||
reviewed,
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
sort_by = 'transaction_date',
|
||||
sort_order = 'DESC'
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push('t.transaction_date >= ?');
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push('t.transaction_date <= ?');
|
||||
params.push(end_date);
|
||||
}
|
||||
if (source_type) {
|
||||
conditions.push('t.source_type = ?');
|
||||
params.push(source_type);
|
||||
}
|
||||
if (direction) {
|
||||
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));
|
||||
}
|
||||
if (max_amount) {
|
||||
conditions.push('ABS(t.amount) <= ?');
|
||||
params.push(parseFloat(max_amount));
|
||||
}
|
||||
if (keyword) {
|
||||
conditions.push('(t.counterparty LIKE ? OR t.description LIKE ? OR t.notes LIKE ? OR t.ai_description LIKE ?)');
|
||||
const kw = `%${keyword}%`;
|
||||
params.push(kw, kw, kw, kw);
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
|
||||
|
||||
// 安全的白名单排序
|
||||
const allowedSortFields = ['transaction_date', 'amount', 'created_at', 'counterparty', 'category', 'reviewed'];
|
||||
const safeSortBy = allowedSortFields.includes(sort_by) ? sort_by : 'transaction_date';
|
||||
const safeSortOrder = sort_order === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
const countResult = db.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions t ${whereClause}`
|
||||
).get(...params);
|
||||
|
||||
const transactions = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
${whereClause}
|
||||
ORDER BY t.${safeSortBy} ${safeSortOrder}
|
||||
LIMIT ? OFFSET ?
|
||||
`).all(...params, parseInt(limit), offset);
|
||||
|
||||
res.json({
|
||||
transactions,
|
||||
total: countResult.total,
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit))
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get('/:id', (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`).get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.id = ?
|
||||
`).get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db.prepare(`
|
||||
SELECT t.*, s.source_name
|
||||
FROM transactions t
|
||||
LEFT JOIN sources s ON s.id = t.source_id
|
||||
WHERE t.transaction_code = ? AND t.id != ?
|
||||
`).all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({ transaction: tx, matchedTransaction: matchedTx, relatedTransactions: relatedTxs });
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put('/:id', (req, res) => {
|
||||
const db = getDB();
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
|
||||
const tx = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push('category = ?');
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push('ai_description = ?');
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push('reviewed = ?');
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push('reviewed_at = CURRENT_TIMESTAMP');
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push('review_notes = ?');
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push('tags = ?');
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: '没有提供要更新的字段' });
|
||||
}
|
||||
|
||||
updates.push('updated_at = CURRENT_TIMESTAMP');
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
res.json({ success: true, transaction: updated });
|
||||
});
|
||||
|
||||
// POST /api/transactions/reconcile - 运行自动对账
|
||||
router.post('/reconcile', (req, res) => {
|
||||
const result = runAutoReconciliation();
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post('/classify', 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 classifyTransactions(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all - 对所有未分类的交易进行分类
|
||||
router.post('/classify-all', async (req, res) => {
|
||||
const db = getDB();
|
||||
const unclassified = db.prepare(
|
||||
"SELECT id FROM transactions WHERE ai_category IS NULL OR ai_category = ''"
|
||||
).all();
|
||||
|
||||
if (unclassified.length === 0) {
|
||||
return res.json({ success: true, classified: 0, message: '所有交易已分类' });
|
||||
}
|
||||
|
||||
const ids = unclassified.map(r => r.id);
|
||||
try {
|
||||
// 分批处理,每批50条
|
||||
const batchSize = 50;
|
||||
let totalClassified = 0;
|
||||
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const batch = ids.slice(i, i + batchSize);
|
||||
const result = await classifyTransactions(batch);
|
||||
totalClassified += result.classified;
|
||||
}
|
||||
|
||||
res.json({ success: true, classified: totalClassified, total: ids.length });
|
||||
} catch (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
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,229 @@
|
||||
const express = require("express");
|
||||
const multer = require("multer");
|
||||
const { parse } = require("csv-parse/sync");
|
||||
const crypto = require("crypto");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const { getDB } = require("../db");
|
||||
const { parseAlipayCSV, parseAlipayFromXLSX } = require("../parsers/alipay");
|
||||
const { parseWechatCSV, parseWechatXLSX } = require("../parsers/wechat");
|
||||
const { parseBankCSV, parseBankFromXLSX } = require("../parsers/bank");
|
||||
const {
|
||||
parseCreditCardCSV,
|
||||
parseCreditFromXLSX,
|
||||
} = require("../parsers/credit");
|
||||
const { parseSPDBXLS } = require("../parsers/spdb");
|
||||
const { generateTransactionCode } = require("../utils/transactionCode");
|
||||
const { classifyTransactions } = require("../services/llm");
|
||||
|
||||
const router = express.Router();
|
||||
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
|
||||
|
||||
const ALLOWED_EXTS = [".csv", ".txt", ".xlsx", ".xls"];
|
||||
|
||||
const upload = multer({
|
||||
storage: multer.diskStorage({
|
||||
destination: uploadDir,
|
||||
filename: (req, file, cb) =>
|
||||
cb(
|
||||
null,
|
||||
Date.now() +
|
||||
"-" +
|
||||
Math.round(Math.random() * 1e9) +
|
||||
path.extname(file.originalname),
|
||||
),
|
||||
}),
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (ALLOWED_EXTS.includes(path.extname(file.originalname).toLowerCase()))
|
||||
cb(null, true);
|
||||
else cb(new Error("仅支持 CSV / TXT / XLSX / XLS 文件格式"));
|
||||
},
|
||||
limits: { fileSize: 20 * 1024 * 1024 },
|
||||
});
|
||||
|
||||
router.post("/", upload.single("file"), async (req, res) => {
|
||||
try {
|
||||
const { source_type, source_name } = req.body;
|
||||
if (
|
||||
!source_type ||
|
||||
![
|
||||
"alipay",
|
||||
"wechat",
|
||||
"bank_debit",
|
||||
"bank_credit",
|
||||
"credit_card",
|
||||
].includes(source_type)
|
||||
) {
|
||||
return res.status(400).json({ error: "无效的账单类型" });
|
||||
}
|
||||
if (!req.file) return res.status(400).json({ error: "请选择要上传的文件" });
|
||||
|
||||
const fileExt = path.extname(req.file.originalname).toLowerCase();
|
||||
const isExcel = [".xlsx", ".xls"].includes(fileExt);
|
||||
console.log(
|
||||
`[Reco] 上传: ${req.file.originalname} type=${source_type} ext=${fileExt}`,
|
||||
);
|
||||
|
||||
const fileBuffer = fs.readFileSync(req.file.path);
|
||||
const fileHash = crypto.createHash("md5").update(fileBuffer).digest("hex");
|
||||
const db = getDB();
|
||||
|
||||
const existing = db
|
||||
.prepare("SELECT id FROM sources WHERE file_hash = ?")
|
||||
.get(fileHash);
|
||||
if (existing) {
|
||||
fs.unlinkSync(req.file.path);
|
||||
return res
|
||||
.status(409)
|
||||
.json({ error: "该文件已导入过", source_id: existing.id });
|
||||
}
|
||||
|
||||
let parsedTransactions;
|
||||
|
||||
if (isExcel) {
|
||||
console.log(`[Reco] XLSX解析: ${source_type}`);
|
||||
switch (source_type) {
|
||||
case "alipay":
|
||||
parsedTransactions = parseAlipayFromXLSX(req.file.path);
|
||||
break;
|
||||
case "wechat":
|
||||
parsedTransactions = parseWechatXLSX(req.file.path);
|
||||
break;
|
||||
case "bank_debit":
|
||||
case "bank_credit":
|
||||
parsedTransactions = parseSPDBXLS(req.file.path);
|
||||
break;
|
||||
case "credit_card":
|
||||
parsedTransactions = parseCreditFromXLSX(req.file.path);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
const content = fileBuffer.toString("utf-8");
|
||||
let records;
|
||||
try {
|
||||
records = parse(content, {
|
||||
columns: true,
|
||||
skip_empty_lines: true,
|
||||
bom: true,
|
||||
relax_column_count: true,
|
||||
trim: true,
|
||||
});
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: `CSV解析失败: ${e.message}` });
|
||||
}
|
||||
if (!records?.length)
|
||||
return res.status(400).json({ error: "文件中无有效记录" });
|
||||
switch (source_type) {
|
||||
case "alipay":
|
||||
parsedTransactions = parseAlipayCSV(records);
|
||||
break;
|
||||
case "wechat":
|
||||
parsedTransactions = parseWechatCSV(records);
|
||||
break;
|
||||
case "bank_debit":
|
||||
case "bank_credit":
|
||||
parsedTransactions = parseBankCSV(records);
|
||||
break;
|
||||
case "credit_card":
|
||||
parsedTransactions = parseCreditCardCSV(records);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedTransactions?.length)
|
||||
return res.status(400).json({ error: "未能解析出交易记录" });
|
||||
console.log(`[Reco] 解析完成: ${parsedTransactions.length}条`);
|
||||
|
||||
const sourceName =
|
||||
source_name || `${source_type}_${new Date().toISOString().slice(0, 10)}`;
|
||||
const src = db
|
||||
.prepare(
|
||||
"INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(
|
||||
source_type,
|
||||
sourceName,
|
||||
req.file.originalname,
|
||||
fileHash,
|
||||
parsedTransactions.length,
|
||||
);
|
||||
|
||||
const insertTx = 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, tags
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
const ids = [];
|
||||
let skip = 0;
|
||||
for (const tx of parsedTransactions) {
|
||||
const code = generateTransactionCode(
|
||||
tx.transaction_date,
|
||||
tx.amount,
|
||||
tx.counterparty,
|
||||
tx.description,
|
||||
);
|
||||
const r = insertTx.run(
|
||||
code,
|
||||
src.lastInsertRowid,
|
||||
source_type,
|
||||
tx.transaction_date,
|
||||
tx.transaction_time,
|
||||
tx.counterparty,
|
||||
tx.description,
|
||||
tx.notes || "",
|
||||
tx.amount,
|
||||
tx.direction,
|
||||
tx.status || "",
|
||||
tx.method || "",
|
||||
tx.balance || null,
|
||||
null,
|
||||
);
|
||||
if (r.changes > 0) ids.push(r.lastInsertRowid);
|
||||
else skip++;
|
||||
}
|
||||
console.log(`[Reco] 写入: ${ids.length}条, 跳过: ${skip}条`);
|
||||
|
||||
let classifyResult = { classified: 0, source: "none" };
|
||||
if (ids.length > 0) {
|
||||
try {
|
||||
classifyResult = await classifyTransactions(ids);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
source_id: src.lastInsertRowid,
|
||||
source_name: sourceName,
|
||||
source_type,
|
||||
file_name: req.file.originalname,
|
||||
record_count: parsedTransactions.length,
|
||||
inserted: ids.length,
|
||||
skipped: skip,
|
||||
classified: classifyResult.classified,
|
||||
classify_source: classifyResult.source,
|
||||
sample: parsedTransactions.slice(0, 5),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Reco] 上传失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/sources", (req, res) => {
|
||||
const db = getDB();
|
||||
res.json(
|
||||
db
|
||||
.prepare(
|
||||
`SELECT s.*, COUNT(t.id) as 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`,
|
||||
)
|
||||
.all(),
|
||||
);
|
||||
});
|
||||
|
||||
router.delete("/sources/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,224 @@
|
||||
const { getDB } = require("../db");
|
||||
|
||||
/**
|
||||
* LLM 服务:调用大模型对交易进行分类和描述
|
||||
*
|
||||
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
|
||||
* 如果未配置 API Key,使用本地规则进行降级分类
|
||||
*/
|
||||
let openaiClient = null;
|
||||
|
||||
function getOpenAIClient() {
|
||||
if (openaiClient) return openaiClient;
|
||||
|
||||
const db = getDB();
|
||||
const apiKey = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
|
||||
.get();
|
||||
const baseURL = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
|
||||
.get();
|
||||
const model = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
|
||||
.get();
|
||||
|
||||
if (!apiKey || !apiKey.value) return null;
|
||||
|
||||
const { OpenAI } = require("openai");
|
||||
|
||||
openaiClient = new OpenAI({
|
||||
apiKey: apiKey.value,
|
||||
baseURL: (baseURL && baseURL.value) || "https://api.openai.com/v1",
|
||||
});
|
||||
|
||||
openaiClient._model = (model && model.value) || "gpt-4o-mini";
|
||||
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分类 Prompt
|
||||
*/
|
||||
function buildClassificationPrompt(transactions) {
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
const categoryList = categories
|
||||
.map(
|
||||
(c) =>
|
||||
`${c.name}(关键词:${JSON.parse(c.keywords || "[]").join("、")})`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
const txList = transactions
|
||||
.map(
|
||||
(tx, i) =>
|
||||
`[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || "未知"} | 描述:${tx.description || "无"} | 来源:${tx.source_type}`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
return `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
## 可用分类:
|
||||
${categoryList}
|
||||
|
||||
## 交易记录:
|
||||
${txList}
|
||||
|
||||
## 要求:
|
||||
请为每笔交易返回一个JSON数组,每项包含:
|
||||
- index: 交易序号(整数)
|
||||
- category: 最合适的分类名称(必须从上面的可用分类中选择)
|
||||
- description: 用简洁的中文描述这笔交易(10-30字),例如"在星巴克购买咖啡"、"缴纳本月房租"、"收到工资"
|
||||
- confidence: 你对分类的置信度(0-1之间的浮点数)
|
||||
|
||||
仅返回JSON数组,不要包含其他内容。`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分类交易
|
||||
*/
|
||||
async function classifyTransactions(transactionIds) {
|
||||
const db = getDB();
|
||||
|
||||
const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds];
|
||||
|
||||
const transactions = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM transactions WHERE id IN (${ids.map(() => "?").join(",")})
|
||||
`,
|
||||
)
|
||||
.all(...ids);
|
||||
|
||||
if (transactions.length === 0) return { classified: 0 };
|
||||
|
||||
// 尝试使用LLM
|
||||
const client = getOpenAIClient();
|
||||
|
||||
if (client) {
|
||||
try {
|
||||
const prompt = buildClassificationPrompt(transactions);
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model: client._model,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。",
|
||||
},
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 2000,
|
||||
});
|
||||
|
||||
const content = response.choices[0].message.content;
|
||||
const jsonMatch = content.match(/\[[\s\S]*\]/);
|
||||
if (jsonMatch) {
|
||||
const results = JSON.parse(jsonMatch[0]);
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const item of results) {
|
||||
const tx = transactions[item.index - 1];
|
||||
if (tx) {
|
||||
updateStmt.run(
|
||||
item.category,
|
||||
item.description,
|
||||
item.confidence,
|
||||
item.category,
|
||||
tx.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return { classified: results.length, source: "llm" };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:使用本地关键词规则分类
|
||||
return classifyByRules(transactions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地关键词规则分类(无需LLM)
|
||||
*/
|
||||
function classifyByRules(transactions) {
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
let classified = 0;
|
||||
let needsReview = 0;
|
||||
|
||||
for (const tx of transactions) {
|
||||
const text =
|
||||
`${tx.description || ""} ${tx.counterparty || ""} ${tx.notes || ""}`.toLowerCase();
|
||||
|
||||
// 金额超过100元标记为需要人工确认
|
||||
const largeAmount = Math.abs(tx.amount) >= 100;
|
||||
|
||||
// 关键词匹配
|
||||
let bestCategory = "其他杂项";
|
||||
let bestScore = 0;
|
||||
|
||||
for (const cat of categories) {
|
||||
const keywords = JSON.parse(cat.keywords || "[]");
|
||||
let score = 0;
|
||||
for (const kw of keywords) {
|
||||
if (text.includes(kw.toLowerCase())) {
|
||||
score++;
|
||||
}
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestCategory = cat.name;
|
||||
}
|
||||
}
|
||||
|
||||
// 生成简单描述
|
||||
let aiDescription = "";
|
||||
if (tx.direction === "income") {
|
||||
aiDescription = `收到${tx.counterparty || "对方"} ${Math.abs(tx.amount).toFixed(2)}元`;
|
||||
} else {
|
||||
aiDescription = `向${tx.counterparty || "对方"}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? "(" + tx.description + ")" : ""}`;
|
||||
}
|
||||
|
||||
updateStmt.run(
|
||||
bestCategory,
|
||||
aiDescription.substring(0, 100),
|
||||
bestScore > 0 ? 0.7 : 0.3,
|
||||
bestCategory,
|
||||
tx.id,
|
||||
);
|
||||
|
||||
classified++;
|
||||
if (largeAmount) needsReview++;
|
||||
}
|
||||
|
||||
return { classified, needsReview, source: "rules" };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient };
|
||||
@@ -0,0 +1,198 @@
|
||||
const { getDB } = require('../db');
|
||||
|
||||
/**
|
||||
* 交易匹配服务
|
||||
*
|
||||
* 自动匹配不同来源的相同交易,例如:
|
||||
* - 支付宝消费 → 银行卡扣款
|
||||
* - 微信支付 → 信用卡扣款
|
||||
* - 跨行转账 ↔ 对方账户入账
|
||||
*
|
||||
* 匹配规则(按优先级):
|
||||
* 1. 相同日期 + 相同金额(最可靠)
|
||||
* 2. 日期相近(±1天) + 相同金额 + 描述相似
|
||||
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
|
||||
*/
|
||||
function findMatches(newTransaction) {
|
||||
const db = getDB();
|
||||
|
||||
const absAmount = Math.abs(newTransaction.amount);
|
||||
|
||||
// 只匹配金额 > 0.01 的交易
|
||||
if (absAmount < 0.01) return [];
|
||||
|
||||
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 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
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
const matches = [];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
let score = 0;
|
||||
const reasons = [];
|
||||
|
||||
// 金额得分
|
||||
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
|
||||
if (amountDiff < 0.01) {
|
||||
score += 40;
|
||||
reasons.push('金额完全一致');
|
||||
} else if (amountDiff < 0.1) {
|
||||
score += 35;
|
||||
reasons.push('金额基本一致');
|
||||
} else if (amountDiff < 1.0) {
|
||||
score += 20;
|
||||
reasons.push('金额接近');
|
||||
}
|
||||
|
||||
// 日期得分
|
||||
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('日期相同');
|
||||
} else if (dateDiff <= 1) {
|
||||
score += 20;
|
||||
reasons.push('日期差1天');
|
||||
} else if (dateDiff <= 2) {
|
||||
score += 10;
|
||||
reasons.push('日期差2天');
|
||||
}
|
||||
|
||||
// 对方名称相似度
|
||||
const nameSim = stringSimilarity(
|
||||
(candidate.counterparty || '').toLowerCase(),
|
||||
(newTransaction.counterparty || '').toLowerCase()
|
||||
);
|
||||
if (nameSim > 0.8) {
|
||||
score += 20;
|
||||
reasons.push('对方名称高度相似');
|
||||
} else if (nameSim > 0.5) {
|
||||
score += 10;
|
||||
reasons.push('对方名称部分相似');
|
||||
}
|
||||
|
||||
// 描述相似度
|
||||
const descSim = stringSimilarity(
|
||||
(candidate.description || '').toLowerCase(),
|
||||
(newTransaction.description || '').toLowerCase()
|
||||
);
|
||||
if (descSim > 0.7) {
|
||||
score += 10;
|
||||
reasons.push('描述相似');
|
||||
}
|
||||
|
||||
// 方向互补(一个支出一个收入,说明是转账匹配)
|
||||
if (candidate.direction !== newTransaction.direction) {
|
||||
score += 5;
|
||||
reasons.push('收支方向互补');
|
||||
}
|
||||
|
||||
if (score >= 40) { // 最低匹配阈值
|
||||
matches.push({
|
||||
transaction_id: candidate.id,
|
||||
match_score: Math.min(score, 100) / 100,
|
||||
reasons: reasons.join(';'),
|
||||
candidate
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 按得分排序
|
||||
matches.sort((a, b) => b.match_score - a.match_score);
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行全局自动对账
|
||||
* 对所有未匹配的交易尝试匹配
|
||||
*/
|
||||
function runAutoReconciliation() {
|
||||
const db = getDB();
|
||||
|
||||
const unmatched = db.prepare(`
|
||||
SELECT * FROM transactions
|
||||
WHERE matched_transaction_id IS NULL
|
||||
ORDER BY transaction_date DESC
|
||||
`).all();
|
||||
|
||||
let matchCount = 0;
|
||||
|
||||
const updateStmt = db.prepare(`
|
||||
UPDATE transactions
|
||||
SET matched_transaction_id = ?, match_score = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
const processed = new Set();
|
||||
|
||||
for (const tx of unmatched) {
|
||||
if (processed.has(tx.id)) continue;
|
||||
|
||||
const matches = findMatches(tx);
|
||||
if (matches.length > 0 && matches[0].match_score >= 0.7) {
|
||||
const bestMatch = matches[0];
|
||||
|
||||
// 双向匹配
|
||||
db.transaction(() => {
|
||||
updateStmt.run(bestMatch.transaction_id, bestMatch.match_score, tx.id);
|
||||
updateStmt.run(tx.id, bestMatch.match_score, bestMatch.transaction_id);
|
||||
})();
|
||||
|
||||
processed.add(tx.id);
|
||||
processed.add(bestMatch.transaction_id);
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return { matched: matchCount, total: unmatched.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单的字符串相似度算法(基于重叠字符)
|
||||
*/
|
||||
function stringSimilarity(a, b) {
|
||||
if (!a || !b) return 0;
|
||||
if (a === b) return 1;
|
||||
|
||||
const shorter = a.length < b.length ? a : b;
|
||||
const longer = a.length < b.length ? b : a;
|
||||
|
||||
if (shorter.length === 0) return 0;
|
||||
|
||||
// 使用滑动窗口匹配
|
||||
let matches = 0;
|
||||
for (let i = 0; i < shorter.length - 1; i++) {
|
||||
const bigram = shorter.substring(i, i + 2);
|
||||
if (longer.includes(bigram)) {
|
||||
matches++;
|
||||
}
|
||||
}
|
||||
|
||||
const possibleMatches = shorter.length - 1;
|
||||
if (possibleMatches === 0) return 0;
|
||||
|
||||
return matches / possibleMatches;
|
||||
}
|
||||
|
||||
module.exports = { findMatches, runAutoReconciliation };
|
||||
Reference in New Issue
Block a user