version 0.3
This commit is contained in:
+51
@@ -0,0 +1,51 @@
|
||||
const fs=require('fs');
|
||||
let f=fs.readFileSync('client/src/pages/Transactions.js','utf8');
|
||||
|
||||
// 1. Import classifyTransactions
|
||||
f=f.replace('classifyAll,', 'classifyAll, classifyTransactions,');
|
||||
|
||||
// 2. Add progress state
|
||||
f=f.replace("const [classifying, setClassifying] = useState(false);",
|
||||
"const [classifying, setClassifying] = useState(false);\n const [classifyProgress, setClassifyProgress] = useState(0);");
|
||||
|
||||
// 3. Replace handleClassifyAll - find exact match
|
||||
const match = ' async function handleClassifyAll() {\n' +
|
||||
' setClassifying(true);\n' +
|
||||
' try {\n' +
|
||||
' const r = await classifyAll();\n' +
|
||||
' alert("分类完成!共分类 " + r.classified + " 笔交易");\n' +
|
||||
' loadTransactions();\n' +
|
||||
' } catch (err) {}\n' +
|
||||
' setClassifying(false);\n' +
|
||||
' }';
|
||||
|
||||
if(!f.includes(match)) { console.log('FUNCTION NOT FOUND'); process.exit(1); }
|
||||
|
||||
const newFunc = ' async function handleClassifyAll() {\n' +
|
||||
' setClassifying(true); setClassifyProgress(0);\n' +
|
||||
' try {\n' +
|
||||
' const res = await fetch("/api/transactions/needs-classify");\n' +
|
||||
' const { ids, total } = await res.json();\n' +
|
||||
' if (!ids.length) { alert("所有交易分类均有效!"); setClassifying(false); return; }\n' +
|
||||
' const B = 50; let done = 0;\n' +
|
||||
' for (let i = 0; i < ids.length; i += B) {\n' +
|
||||
' await classifyTransactions(ids.slice(i, i + B));\n' +
|
||||
' done += Math.min(B, ids.length - i);\n' +
|
||||
' setClassifyProgress(Math.round(done / total * 100));\n' +
|
||||
' }\n' +
|
||||
' alert("分类完成!共重分类 " + total + " 笔交易");\n' +
|
||||
' loadTransactions();\n' +
|
||||
' } catch (e) { alert("分类失败: " + (e.message || e)); }\n' +
|
||||
' setClassifying(false);\n' +
|
||||
' }';
|
||||
|
||||
f=f.replace(match, newFunc);
|
||||
|
||||
// 4. Update button
|
||||
f=f.replace(
|
||||
'{classifying ? "分类中..." : "AI 分类全部"}',
|
||||
'{classifying ? `分类中 ${classifyProgress}%` : "AI 分类全部"}'
|
||||
);
|
||||
|
||||
fs.writeFileSync('client/src/pages/Transactions.js',f);
|
||||
console.log('done');
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
const fs=require('fs');
|
||||
let f=fs.readFileSync('client/src/pages/Transactions.js','utf8');
|
||||
|
||||
// 1. Import classifyTransactions
|
||||
f=f.replace('classifyAll,', 'classifyAll, classifyTransactions,');
|
||||
|
||||
// 2. Add progress state
|
||||
f=f.replace("const [classifying, setClassifying] = useState(false);",
|
||||
"const [classifying, setClassifying] = useState(false);\n const [classifyProgress, setClassifyProgress] = useState(0);");
|
||||
|
||||
// 3. Replace handleClassifyAll
|
||||
const oldFunc = ` async function handleClassifyAll() {
|
||||
setClassifying(true);
|
||||
try {
|
||||
const result = await classifyAll();
|
||||
alert(\`分类完成!共分类 \${result.classified} 笔交易\`);
|
||||
loadTransactions();
|
||||
} catch (err) {}
|
||||
setClassifying(false);
|
||||
}`;
|
||||
|
||||
const newFunc = ` async function handleClassifyAll() {
|
||||
setClassifying(true); setClassifyProgress(0);
|
||||
try {
|
||||
const res = await fetch("/api/transactions/needs-classify");
|
||||
const { ids, total } = await res.json();
|
||||
if (!ids.length) { alert("所有交易分类均有效!"); setClassifying(false); return; }
|
||||
const B = 50; let done = 0;
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
await classifyTransactions(ids.slice(i, i + B));
|
||||
done += Math.min(B, ids.length - i);
|
||||
setClassifyProgress(Math.round(done / total * 100));
|
||||
}
|
||||
alert("分类完成!共重分类 " + total + " 笔交易");
|
||||
loadTransactions();
|
||||
} catch (e) { alert("分类失败: " + (e.response?.data?.error || e.message)); }
|
||||
setClassifying(false);
|
||||
}`;
|
||||
|
||||
if(!f.includes(oldFunc)){console.log('OLD FUNC NOT FOUND');process.exit(1);}
|
||||
f=f.replace(oldFunc, newFunc);
|
||||
|
||||
// 4. Update button
|
||||
f=f.replace("{classifying ? '分类中...' : 'AI 分类全部'}", "{classifying ? `分类中 ${classifyProgress}%` : 'AI 分类全部'}");
|
||||
|
||||
fs.writeFileSync('client/src/pages/Transactions.js',f);
|
||||
console.log('done');
|
||||
@@ -497,6 +497,7 @@ tr:hover { background: var(--bg); }
|
||||
.source-wechat { background: #d1fae5; color: #065f46; }
|
||||
.source-bank_debit { background: #fef3c7; color: #92400e; }
|
||||
.source-bank_credit { background: #fef3c7; color: #92400e; }
|
||||
.source-abc { background: #e0e7ff; color: #3730a3; }
|
||||
.source-credit_card { background: #fee2e2; color: #991b1b; }
|
||||
|
||||
/* Loading */
|
||||
|
||||
@@ -126,6 +126,8 @@ export async function getCategories() {
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function createCategory(data) { const res = await api.post("/config/categories", data); return res.data; }
|
||||
export async function deleteCategory(id) { const res = await api.delete("/config/categories/" + id); return res.data; }
|
||||
export async function updateCategory(id, data) {
|
||||
const res = await api.put(`/config/categories/${id}`, data);
|
||||
return res.data;
|
||||
@@ -144,9 +146,8 @@ export function formatDate(dateStr) {
|
||||
}
|
||||
|
||||
export const SOURCE_TYPE_MAP = {
|
||||
alipay: '支付宝',
|
||||
wechat: '微信支付',
|
||||
bank_debit: '银行借记卡',
|
||||
bank_credit: '银行贷记卡',
|
||||
credit_card: '信用卡'
|
||||
alipay: "支付宝",
|
||||
wechat: "微信支付",
|
||||
bank_debit: "浦发银行",
|
||||
abc: "农业银行"
|
||||
};
|
||||
|
||||
@@ -167,7 +167,7 @@ export default function Dashboard() {
|
||||
{s.source_type === 'wechat' && '微信支付'}
|
||||
{s.source_type === 'bank_debit' && '银行借记卡'}
|
||||
{s.source_type === 'bank_credit' && '银行贷记卡'}
|
||||
{s.source_type === 'credit_card' && '信用卡'}
|
||||
{s.source_type === 'abc' && '农业银行'}
|
||||
</span>
|
||||
</td>
|
||||
<td>{s.count}</td>
|
||||
|
||||
@@ -10,30 +10,10 @@ import {
|
||||
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: "信用卡账单文件",
|
||||
},
|
||||
{ value: "alipay", label: "支付宝", icon: "🔵", desc: "支付宝账单 CSV 文件" },
|
||||
{ value: "wechat", label: "微信支付", icon: "🟢", desc: "微信支付账单 XLSX 文件" },
|
||||
{ value: "bank_debit", label: "浦发银行", icon: "🏦", desc: "浦发银行流水 XLS 文件" },
|
||||
{ value: "abc", label: "农业银行", icon: "🏦", desc: "农业银行流水 XLSX 文件" },
|
||||
];
|
||||
|
||||
const ALLOWED_EXTS = ["csv", "txt", "xlsx", "xls"];
|
||||
|
||||
+61
-173
@@ -1,131 +1,64 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw } from 'lucide-react';
|
||||
import { getConfig, updateConfig, testLLM, getCategories, updateCategory } from '../hooks/useApi';
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw, X } from 'lucide-react';
|
||||
import { getConfig, updateConfig, testLLM, getCategories, updateCategory, createCategory, deleteCategory } from '../hooks/useApi';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [config, setConfig] = useState({
|
||||
llm_api_key: '',
|
||||
llm_base_url: 'https://api.openai.com/v1',
|
||||
llm_model: 'gpt-4o-mini'
|
||||
});
|
||||
const [config, setConfig] = useState({ llm_api_key: '', llm_base_url: 'https://api.openai.com/v1', llm_model: 'gpt-4o-mini' });
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [llmStatus, setLLMStatus] = useState(null);
|
||||
const [testingLlm, setTestingLlm] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editingCat, setEditingCat] = useState(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [newCat, setNewCat] = useState({ name: '', keywords: '' });
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
useEffect(() => { loadAll(); }, []);
|
||||
|
||||
async function loadAll() {
|
||||
try {
|
||||
const [cfg, cats] = await Promise.all([getConfig(), getCategories()]);
|
||||
setConfig(prev => ({ ...prev, ...cfg }));
|
||||
setCategories(cats);
|
||||
} catch (err) {}
|
||||
try { const [cfg, cats] = await Promise.all([getConfig(), getCategories()]); setConfig(prev => ({ ...prev, ...cfg })); setCategories(cats); } catch (err) {}
|
||||
}
|
||||
|
||||
async function handleSaveConfig() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateConfig(config);
|
||||
alert('配置保存成功!');
|
||||
} catch (err) {}
|
||||
setSaving(false);
|
||||
}
|
||||
async function handleSaveConfig() { setSaving(true); try { await updateConfig(config); alert('保存成功!'); } catch (err) {} setSaving(false); }
|
||||
|
||||
async function handleTestLLM() {
|
||||
setTestingLlm(true);
|
||||
setLLMStatus(null);
|
||||
// Save config first
|
||||
setTestingLlm(true); setLLMStatus(null);
|
||||
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 });
|
||||
}
|
||||
try { const r = await testLLM(); setLLMStatus({ success: true, message: `连接成功!模型: ${r.model}, 回复: ${r.reply}` }); }
|
||||
catch (err) { setLLMStatus({ success: false, message: err.response?.data?.error || err.message }); }
|
||||
setTestingLlm(false);
|
||||
}
|
||||
|
||||
async function handleUpdateCategory(id, field, value) {
|
||||
async function handleUpdateCategory(id, field, value) { try { await updateCategory(id, { [field]: value }); loadAll(); } catch (err) {} }
|
||||
|
||||
async function handleAddCategory() {
|
||||
if (!newCat.name.trim()) return;
|
||||
try {
|
||||
await updateCategory(id, { [field]: value });
|
||||
loadAll();
|
||||
await createCategory({ name: newCat.name.trim(), keywords: newCat.keywords.split(',').map(k => k.trim()).filter(Boolean) });
|
||||
setNewCat({ name: '', keywords: '' }); setAdding(false); loadAll();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleDeleteCategory(id, name) {
|
||||
if (!window.confirm(`确定删除分类「${name}」吗?`)) return;
|
||||
try { await deleteCategory(id); loadAll(); } catch (err) {}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h2>⚙️ 系统设置</h2>
|
||||
<p>配置大模型API及管理交易分类</p>
|
||||
</div>
|
||||
<div className="page-header"><h2>⚙️ 系统设置</h2><p>配置大模型API及管理交易分类</p></div>
|
||||
|
||||
{/* LLM Configuration */}
|
||||
{/* LLM Config */}
|
||||
<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 className="card-header"><h3>🤖 大模型配置</h3><span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>支持 OpenAI 兼容API</span></div>
|
||||
<div className="form-group"><label>API Key</label><input type="password" className="form-input" placeholder="sk-..." value={config.llm_api_key || ''} onChange={e => setConfig({ ...config, llm_api_key: e.target.value })} /></div>
|
||||
<div className="form-group"><label>API Base URL</label><input type="text" className="form-input" placeholder="https://api.openai.com/v1" value={config.llm_base_url || ''} onChange={e => setConfig({ ...config, llm_base_url: e.target.value })} /></div>
|
||||
<div className="form-group"><label>模型名称</label><input type="text" className="form-input" placeholder="gpt-4o-mini" value={config.llm_model || ''} onChange={e => setConfig({ ...config, llm_model: e.target.value })} /></div>
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<button className="btn btn-primary" onClick={handleSaveConfig} disabled={saving}>
|
||||
<Save size={16} /> {saving ? '保存中...' : '保存配置'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={handleTestLLM} disabled={testingLlm}>
|
||||
<Zap size={16} /> {testingLlm ? '测试中...' : '测试连接'}
|
||||
</button>
|
||||
<button className="btn btn-primary" onClick={handleSaveConfig} disabled={saving}><Save size={16} /> {saving ? '保存中...' : '保存配置'}</button>
|
||||
<button className="btn btn-secondary" onClick={handleTestLLM} disabled={testingLlm}><Zap size={16} /> {testingLlm ? '测试中...' : '测试连接'}</button>
|
||||
</div>
|
||||
|
||||
{llmStatus && (
|
||||
<div style={{
|
||||
marginTop: 16, padding: '12px 16px', borderRadius: 8, fontSize: 14,
|
||||
background: llmStatus.success ? '#f0fdf4' : '#fef2f2',
|
||||
color: llmStatus.success ? 'var(--success)' : 'var(--danger)',
|
||||
border: `1px solid ${llmStatus.success ? '#bbf7d0' : '#fecaca'}`
|
||||
}}>
|
||||
{llmStatus.message}
|
||||
</div>
|
||||
<div style={{ marginTop: 16, padding: '12px 16px', borderRadius: 8, fontSize: 14, background: llmStatus.success ? '#f0fdf4' : '#fef2f2', color: llmStatus.success ? 'var(--success)' : 'var(--danger)', border: `1px solid ${llmStatus.success ? '#bbf7d0' : '#fecaca'}` }}>{llmStatus.message}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -133,79 +66,54 @@ export default function SettingsPage() {
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 分类管理</h3>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}>
|
||||
<RefreshCw size={14} /> 刷新
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => setAdding(true)}><Plus size={14} /> 新增</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}><RefreshCw size={14} /> 刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>
|
||||
管理交易分类及其关键词,AI会根据关键词进行自动分类
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>管理交易分类及关键词,AI 根据关键词自动分类</div>
|
||||
|
||||
{/* New category inline form */}
|
||||
{adding && (
|
||||
<div style={{ display: 'flex', gap: 10, marginBottom: 12, padding: '10px 12px', background: 'var(--primary-bg)', borderRadius: 8, alignItems: 'center' }}>
|
||||
<input type="text" className="form-input" style={{ width: 130 }} placeholder="分类名称" value={newCat.name} onChange={e => setNewCat({ ...newCat, name: e.target.value })} />
|
||||
<input type="text" className="form-input" style={{ flex: 1 }} placeholder="关键词,逗号,分隔" value={newCat.keywords} onChange={e => setNewCat({ ...newCat, keywords: e.target.value })} />
|
||||
<button className="btn btn-primary btn-sm" onClick={handleAddCategory}><Plus size={12} /> 添加</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => { setAdding(false); setNewCat({ name: '', keywords: '' }); }}><X size={12} /></button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 60 }}>ID</th>
|
||||
<th>分类名称</th>
|
||||
<th>关键词(逗号分隔)</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<thead><tr><th style={{ width: 50 }}>ID</th><th>分类名称</th><th>关键词</th><th style={{ width: 160 }}>操作</th></tr></thead>
|
||||
<tbody>
|
||||
{categories.map(cat => (
|
||||
<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>
|
||||
)}
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: 120 }} value={editingCat.name} onChange={e => setEditingCat({ ...editingCat, name: e.target.value })} />
|
||||
: <strong>{cat.name}</strong>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={editingCat.keywords}
|
||||
onChange={e => setEditingCat({ ...editingCat, keywords: e.target.value })}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
{JSON.parse(cat.keywords || '[]').join(', ') || '(无关键词)'}
|
||||
</span>
|
||||
)}
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: '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>
|
||||
<button className="btn btn-primary btn-sm" onClick={async () => { await handleUpdateCategory(cat.id, 'name', editingCat.name); await handleUpdateCategory(cat.id, 'keywords', editingCat.keywords.split(',').map(k => k.trim()).filter(Boolean)); setEditingCat(null); }}><Save size={12} /> 保存</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat(null)}>取消</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat({
|
||||
...cat,
|
||||
keywords: JSON.parse(cat.keywords || '[]').join(', ')
|
||||
})}>
|
||||
编辑
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat({ ...cat, keywords: JSON.parse(cat.keywords || '[]').join(', ') })}>编辑</button>
|
||||
<button className="btn btn-danger btn-sm" onClick={() => handleDeleteCategory(cat.id, cat.name)}><Trash2 size={12} /></button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -214,26 +122,6 @@ export default function SettingsPage() {
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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';
|
||||
import { getTransactions, updateTransaction, runReconciliation, classifyAll, classifyTransactions, formatAmount, formatDate, SOURCE_TYPE_MAP, getCategories } from '../hooks/useApi';
|
||||
|
||||
export default function Transactions() {
|
||||
const [data, setData] = useState({ transactions: [], total: 0, page: 1, totalPages: 0 });
|
||||
@@ -14,6 +14,7 @@ export default function Transactions() {
|
||||
const [editingTx, setEditingTx] = useState(null);
|
||||
const [reconciling, setReconciling] = useState(false);
|
||||
const [classifying, setClassifying] = useState(false);
|
||||
const [classifyProgress, setClassifyProgress] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
@@ -59,12 +60,20 @@ export default function Transactions() {
|
||||
}
|
||||
|
||||
async function handleClassifyAll() {
|
||||
setClassifying(true);
|
||||
setClassifying(true); setClassifyProgress(0);
|
||||
try {
|
||||
const result = await classifyAll();
|
||||
alert(`分类完成!共分类 ${result.classified} 笔交易`);
|
||||
const res = await fetch("/api/transactions/needs-classify");
|
||||
const { ids, total } = await res.json();
|
||||
if (!ids.length) { alert("所有交易分类均有效!"); setClassifying(false); return; }
|
||||
const B = 50; let done = 0;
|
||||
for (let i = 0; i < ids.length; i += B) {
|
||||
await classifyTransactions(ids.slice(i, i + B));
|
||||
done += Math.min(B, ids.length - i);
|
||||
setClassifyProgress(Math.round(done / total * 100));
|
||||
}
|
||||
alert("分类完成!共重分类 " + total + " 笔交易");
|
||||
loadTransactions();
|
||||
} catch (err) {}
|
||||
} catch (e) { alert("分类失败: " + (e.response?.data?.error || e.message)); }
|
||||
setClassifying(false);
|
||||
}
|
||||
|
||||
@@ -93,7 +102,7 @@ export default function Transactions() {
|
||||
<Link2 size={16} /> {reconciling ? '对账中...' : '自动对账'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={handleClassifyAll} disabled={classifying}>
|
||||
<Brain size={16} /> {classifying ? '分类中...' : 'AI 分类全部'}
|
||||
<Brain size={16} /> {classifying ? `分类中 ${classifyProgress}%` : '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} /> 重置筛选
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
支付宝交易记录明细查询
|
||||
账号:[13802885124]
|
||||
起始日期:[2025-05-05 00:00:00] 终止日期:[2026-05-05 15:18:22]
|
||||
---------------------------------交易记录明细列表------------------------------------
|
||||
交易号 ,商家订单号 ,交易创建时间 ,付款时间 ,最近修改时间 ,交易来源地 ,类型 ,交易对方 ,商品名称 ,金额(元) ,收/支 ,交易状态 ,服务费(元) ,成功退款(元) ,备注 ,资金状态 ,
|
||||
2026050223001109201445664368 ,T200P3299057294183028176 ,2026-05-02 12:10:05 ,2026-05-02 12:10:07 ,2026-05-05 15:17:56 ,淘宝 ,支付宝担保交易 ,x***7 ,[7.5可用]FF14橙月土月猫月橙卫月解决Dalamud版,6.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026050222001409201442882141 ,20260502ALPP000227655513 ,2026-05-02 10:33:14 ,2026-05-02 10:33:16 ,2026-05-02 10:33:16 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,单程盐城广州 ,3840.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026050122001409201442080891 ,20260501ALPP000092752208 ,2026-05-01 14:03:01 ,2026-05-01 14:03:02 ,2026-05-01 14:03:02 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海携程国际旅行社有限公司 ,黄海森林公园 ,124.65 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026050122001409201435299245 ,20260501ALPP000056824011 ,2026-05-01 11:02:06 ,2026-05-01 11:02:07 ,2026-05-01 11:02:07 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海携程国际旅行社有限公司 ,中华麋鹿园 ,192.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026042922001409201418325725_20260429177741117683e49c1118 ,NP177739970254030237335270ef8218 ,2026-04-29 05:19:37 , ,2026-04-29 05:19:37 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,退款-火车票 ,532.00 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026042922001409201418325725 ,NP177739970254030237335270ef8218 ,2026-04-29 02:08:22 ,2026-04-29 02:08:23 ,2026-04-29 05:19:37 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,火车票 ,532.00 ,支出 ,交易关闭 ,0.00 ,532.00 , ,已支出 ,
|
||||
2026042822001409201418200406_20260428ALRP003736871005 ,20260428ALPP003735934411 ,2026-04-28 20:25:47 , ,2026-04-28 20:25:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海顺途科技有限公司 ,退款-北京南盐城 ,53.50 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026042822001409201418200406_20260428ALRP003737148909 ,20260428ALPP003735934411 ,2026-04-28 20:20:47 , ,2026-04-28 20:20:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海顺途科技有限公司 ,退款-北京南盐城 ,451.00 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026042822001409201418200406 ,20260428ALPP003735934411 ,2026-04-28 20:15:16 ,2026-04-28 20:15:17 ,2026-04-28 20:25:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海顺途科技有限公司 ,北京南盐城 ,564.00 ,支出 ,交易成功 ,0.00 ,504.50 , ,已支出 ,
|
||||
2026042822001409201417926155_202604281777376687046543cb19 ,NP17773764815397470959e6e7fc1619 ,2026-04-28 19:44:49 , ,2026-04-28 19:44:49 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,退款-火车票 ,502.00 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026042822001409201417926155 ,NP17773764815397470959e6e7fc1619 ,2026-04-28 19:41:22 ,2026-04-28 19:41:23 ,2026-04-28 19:44:49 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,火车票 ,502.00 ,支出 ,交易关闭 ,0.00 ,502.00 , ,已支出 ,
|
||||
2026042823001409201419432509_20260428177737627241d373ec27 ,NP17773761505395610096c9a5983127 ,2026-04-28 19:37:55 , ,2026-04-28 19:37:55 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,退款-火车票 ,507.00 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026042823001409201419432509 ,NP17773761505395610096c9a5983127 ,2026-04-28 19:35:50 ,2026-04-28 19:35:51 ,2026-04-28 19:37:55 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,火车票 ,507.00 ,支出 ,交易关闭 ,0.00 ,507.00 , ,已支出 ,
|
||||
2026042623001109201401468512 ,T200P3298612404640064186 ,2026-04-26 12:29:08 ,2026-04-26 12:32:02 ,2026-04-26 12:46:07 ,淘宝 ,支付宝担保交易 ,不***i ,【ptcg live】50包 code 兑换码 朱紫 meg,315.00 ,支出 ,等待确认收货 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026042523001109201457524649 ,T200P3297788403587018994 ,2026-04-25 14:26:59 ,2026-04-25 14:27:01 ,2026-05-05 14:27:16 ,淘宝 ,支付宝担保交易 ,x***8 ,win11专业版密钥激活密钥10专业版激活密钥windows,1.96 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026042323001409201450745150 ,P18M6666031260423967501802159 ,2026-04-23 19:19:06 ,2026-04-23 19:19:08 ,2026-04-23 19:19:08 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,盒马 ,单粒寿司-蓉锦 ,25.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026040523001109201409726331 ,T200P2701820715082028176 ,2026-04-05 22:19:39 ,2026-04-05 22:19:42 ,2026-04-06 08:34:15 ,淘宝 ,支付宝担保交易 ,t***7 ,simbrief软件资源分享 ,23.88 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026040523001109201404249215 ,T200P2701816500075018994 ,2026-04-05 08:55:13 ,2026-04-05 08:55:19 ,2026-04-09 00:02:31 ,淘宝 ,支付宝担保交易 ,t***4 ,即买即用广州正佳极地海洋馆门票双人票 ,309.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026040322001409201402254886 ,20260403ALPP000400465902 ,2026-04-03 20:19:34 ,2026-04-03 20:19:35 ,2026-04-03 20:19:35 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,单程广州盐城 ,1135.21 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026032222001409201455206260 ,P18M6666031260322706262802159 ,2026-03-22 16:24:54 ,2026-03-22 16:24:55 ,2026-03-22 16:24:55 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,盒马 ,盒马 HPP羽衣甘蓝复合果蔬汁 300mL*4等3类商品,181.23 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026032222001409201455411005 ,P18M6666031260322724186802159 ,2026-03-22 16:15:12 ,2026-03-22 16:15:13 ,2026-03-22 16:15:13 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,盒马 ,盒马工坊 金陵大肉包 150g(1个) ,6.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026032223001409201453686095 ,P18M6666031260322677416802159 ,2026-03-22 16:11:11 ,2026-03-22 16:11:12 ,2026-03-22 16:11:12 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,盒马 ,国潮蜜汁烤猪肋排(1-2人份) ,59.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026032022001409201445361074 ,17740099364712678509201 ,2026-03-20 20:32:16 ,2026-03-20 20:32:21 ,2026-03-20 20:32:21 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,泽华超市 ,经营码交易 ,490.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026031923001109201434265756 ,T200P2701753323061100196 ,2026-03-19 09:18:13 ,2026-03-19 09:18:15 ,2026-03-29 09:18:50 ,淘宝 ,支付宝担保交易 ,x***2 ,Figma专业版原号升级有Make AI,39.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026030723001409201435355105 ,visionpayF57BE6325082150775439DFF ,2026-03-07 10:53:57 ,2026-03-07 10:53:59 ,2026-03-07 10:53:59 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,大黄鹅 ,智能货柜消费_LD小白奶皮面包原味等_消费时间:2026-03-07 10:51:48,17.21 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026022823001409201457376737 ,P18M6666031260228963609802159 ,2026-02-28 19:22:22 ,2026-02-28 19:22:23 ,2026-02-28 19:22:23 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,盒马 ,盒马烘焙 安心欧坦得系列原味酵醒面包 100g等3类商品,99.40 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026022822001409201458629661 ,XSFF-GD202602281249312679241 ,2026-02-28 12:49:55 ,2026-02-28 12:49:57 ,2026-02-28 12:49:57 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,中国人民财产保险股份有限公司 ,中国人保广东省分公司收保费 ,3419.06 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026022723001109201448207108 ,T200P3264378672192802159 ,2026-02-27 00:10:34 ,2026-02-27 00:10:37 ,2026-03-09 00:21:02 ,淘宝 ,支付宝担保交易 ,窝***族 ,FAA飞行员考试题库 私商仪ATP Pilot Test P,6.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026022523001109201443230234 ,T200P3262125360210802159 ,2026-02-25 21:27:53 ,2026-02-25 21:27:59 ,2026-03-07 21:44:11 ,淘宝 ,支付宝担保交易 ,tb**7 ,Steam正版 微软飞行模拟2024 国区礼物激活码cdk Microsoft 2024,297.19 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026022523001109201443220506_3261338763961802159 ,T200P3261338763961802159 ,2026-02-25 19:39:40 , ,2026-02-25 19:39:40 ,淘宝 ,支付宝担保交易 ,t***e ,退款-Steam模拟飞行12激活码CDKEY国区全球区XPlane,5.80 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2026022523001109201443220506 ,T200P3261338763961802159 ,2026-02-25 19:25:19 ,2026-02-25 19:25:21 ,2026-02-25 19:39:40 ,淘宝 ,支付宝担保交易 ,t***e ,Steam模拟飞行12激活码CDKEY国区全球区XPlane,5.80 ,支出 ,交易关闭 ,0.00 ,5.80 , ,已支出 ,
|
||||
2026022022001409201419705507 ,20260220ALPP002851716816 ,2026-02-20 15:51:38 ,2026-02-20 15:51:38 ,2026-02-20 15:51:38 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,单程盐城广州 ,1435.39 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026021323001109201445081386 ,T200P3246505574155802159 ,2026-02-13 16:24:10 ,2026-02-13 16:24:12 ,2026-02-23 22:24:29 ,淘宝 ,支付宝担保交易 ,褚***侠 ,雷神时长兑换卡100小时cdkey自动发货非uu非租号,1.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026021323001109201447136370 ,T200P3246755772950802159 ,2026-02-13 12:59:01 ,2026-02-13 12:59:03 ,2026-02-23 13:00:15 ,淘宝 ,支付宝担保交易 ,x***0 ,腾讯元宝派内测码邀请码 元宝派建群群内可以领红包 多建多拿,1.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026021123001109201435704237 ,T200P3244338264372802159 ,2026-02-11 22:30:44 ,2026-02-11 22:30:45 ,2026-02-21 22:30:57 ,淘宝 ,支付宝担保交易 ,tb**6 ,(炉石传说脚本)正版防封最稳定防封版刷金币刷通行证刷金币,9.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026021123001109201432969056 ,T200P3242033078725802159 ,2026-02-11 02:02:04 ,2026-02-11 02:02:05 ,2026-02-11 22:02:20 ,淘宝 ,支付宝担保交易 ,t***9 ,炉石传说最多13卡包国服礼包cdk全套兑换码,1.01 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026021123001109201430744534 ,T200P3242573040679802159 ,2026-02-11 02:00:18 ,2026-02-11 02:00:20 ,2026-02-11 22:02:05 ,淘宝 ,支付宝担保交易 ,x***2 ,炉石传说卡包兑换码,秒发!8包,国服全平台互通客户端都能用。,2.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026020723001409201413875189 ,2026020719074101000630002427853 ,2026-02-07 17:25:24 ,2026-02-07 17:25:41 ,2026-02-07 17:25:41 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,我的書房 ,商品 ,160.26 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026020223001109201444861872 ,T200P3222072951103802159 ,2026-02-02 01:26:06 ,2026-02-02 01:26:07 ,2026-02-12 08:59:05 ,淘宝 ,支付宝担保交易 ,眼镜**店 ,毛毡板墙贴高级感客厅玄关照片墙背景板羊毛粘组合相框创意墙面装饰软木留言板拍立得相片墙家庭相册墙文化墙,78.60 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026013122001409201438225460 ,00172026013121230205277970825432 ,2026-01-31 21:23:10 ,2026-01-31 21:23:15 ,2026-05-04 21:23:29 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,暴雪游戏 ,128符文石 X 1 ,128.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026013022001409201436326676 ,0bd3ef161dce1f9e1be9ce59eabdc2c8 ,2026-01-30 21:28:32 ,2026-01-30 21:28:39 ,2026-01-30 21:28:39 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,抚州晴朗广告传媒有限公司 ,0bd3ef161dce1f9e1be9ce59eabdc2c8,148.40 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026013023001409201428414995 ,5058598044863960565 ,2026-01-30 06:17:26 ,2026-01-30 06:17:27 ,2026-01-30 06:17:27 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,哔哩哔哩弹幕网 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026012123001109201446479713 ,T200P3198650448837802159 ,2026-01-21 13:37:09 ,2026-01-21 13:37:10 ,2026-01-31 15:42:28 ,淘宝 ,支付宝担保交易 ,晨光**店 ,晨光勾线笔小双头防水记号笔粗细两头小学生幼儿园美术绘画专用儿童画画文具马克笔描边速干工地划线油性笔,38.30 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026012022001409201438771751 ,00552026012008081512578667521172 ,2026-01-20 08:08:25 ,2026-01-20 08:08:25 ,2026-01-20 08:08:25 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,中国移动 ,为138****5124话费充值 ,200.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20260109092036491870 ,alipay01-P260109211537344 ,2026-01-09 21:15:29 ,2026-01-09 21:15:29 ,2026-01-09 21:15:43 ,支付宝网站 ,即时到账交易 ,广州市普晖药业连锁有限公司万东店(医保),医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20260109092036612002 ,440120260109835281107 ,2026-01-09 21:15:11 ,2026-01-09 21:15:11 ,2026-01-09 21:15:55 ,支付宝网站 ,即时到账交易 ,广州市普晖药业连锁有限公司万东店,医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20260105300000015409201253101770 ,T200P3145065711309802159 ,2026-01-05 13:21:02 ,2026-01-05 13:21:02 ,2026-01-05 13:21:02 ,淘宝 ,支付宝担保交易 ,zh**店 ,磁性贴标签姓名贴纸软白板磁力贴教学磁吸教具磁铁可擦书写磁片英语单词卡片公开课板书黑板贴货架展示标记牌 等多件,98.66 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2026010522001409201419973760 ,NP17675885974ac654717483455ba731 ,2026-01-05 12:49:57 ,2026-01-05 12:49:59 ,2026-01-05 12:49:59 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,华程西南 ,租车费 ,719.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025123122001409201455986237 ,11P2088721085226061W03_120251231000097867991 ,2025-12-31 21:03:36 ,2025-12-31 21:03:41 ,2025-12-31 21:03:41 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,中海物业管理有限公司 ,中海物业管理有限公司-消费 ,267.30 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025123022001409201442535574 ,5046650175654826252 ,2025-12-30 06:13:33 ,2025-12-30 06:13:34 ,2025-12-30 06:13:34 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,哔哩哔哩 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025122922001409201445345435 ,2025122919074101000730081550099 ,2025-12-29 17:33:29 ,2025-12-29 17:33:47 ,2025-12-29 17:33:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,Agoda Company Pte. Ltd.,成都雅诗阁来福士 (Ascott Raffles City Chengdu),3721.55 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025122622001109201423526004 ,T200P3145065711309802159 ,2025-12-26 09:59:37 ,2025-12-26 09:59:37 ,2025-12-26 09:59:37 ,淘宝 ,支付宝担保交易 ,zh**店 ,磁性贴标签姓名贴纸软白板磁力贴教学磁吸教具磁铁可擦书写磁片英语单词卡片公开课板书黑板贴货架展示标记牌 等多件,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025121323001409201412186064 ,1721202512135989401120104322 ,2025-12-13 16:43:46 ,2025-12-13 16:43:47 ,2025-12-13 16:43:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,友宝智能货柜 ,售货柜_消费时间:2025-12-13 16:38:12,14.78 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025120823001109201443003773 ,T200P3110955744343802159 ,2025-12-08 21:59:08 ,2025-12-08 21:59:09 ,2025-12-18 22:05:53 ,淘宝 ,支付宝担保交易 ,记***9 ,【Nature】英国版科学杂志2022-2025年第0206,0.95 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025120823001109201441239660_3110549414268802159 ,T200P3110549414268802159 ,2025-12-08 21:57:15 , ,2025-12-08 21:57:15 ,淘宝 ,支付宝担保交易 ,x***2 ,退款-自然Nature外刊高清《Nature》2015-2025全,1.00 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2025120823001109201441239660 ,T200P3110549414268802159 ,2025-12-08 21:56:20 ,2025-12-08 21:56:21 ,2025-12-08 21:57:15 ,淘宝 ,支付宝担保交易 ,x***2 ,自然Nature外刊高清《Nature》2015-2025全,1.00 ,支出 ,交易关闭 ,0.00 ,1.00 , ,已支出 ,
|
||||
2025112922001409201440284200 ,5036181859766112607 ,2025-11-29 06:17:15 ,2025-11-29 06:17:16 ,2025-11-29 06:17:16 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,哔哩哔哩 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025111522001409201416720885 ,31P2088721085226061W03_120251115000095209859 ,2025-11-15 15:06:43 ,2025-11-15 15:07:56 ,2025-11-15 15:07:56 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,中海物业管理有限公司 ,中海物业管理有限公司-消费 ,1383.17 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20251112092098106478 ,alipay01-P251112163559814 ,2025-11-12 16:35:52 ,2025-11-12 16:35:52 ,2025-11-12 16:36:13 ,支付宝网站 ,即时到账交易 ,中山大学附属第三医院岭南医院 ,医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20251111300000015409201230373599 ,T200P3033483027324802159 ,2025-11-11 13:24:30 ,2025-11-11 13:24:30 ,2025-11-11 13:24:30 ,淘宝 ,支付宝担保交易 ,三星**店 ,三星tf内存卡512G无人机手机相机switch存储卡MicroSD,279.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025110123001109201440793745 ,T200P3035329033797802159 ,2025-11-01 20:11:51 ,2025-11-01 20:11:52 ,2025-11-12 11:34:25 ,淘宝 ,支付宝担保交易 ,ha**店 ,【优惠价】HAOLOCM适用任天堂Switchar膜高清全屏膜新款低反射OLED钢化膜6.2贴膜7英寸游戏机防反光S,31.30 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025110123001109201431310569 ,T200P3033483027324802159 ,2025-11-01 09:56:48 ,2025-11-01 09:56:49 ,2025-11-01 09:56:49 ,淘宝 ,支付宝担保交易 ,三星**店 ,三星tf内存卡512G无人机手机相机switch存储卡MicroSD,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025103023001109201423057089 ,T200P3031020408918802159 ,2025-10-30 21:24:44 ,2025-10-30 21:24:54 ,2025-11-02 08:58:02 ,淘宝 ,支付宝担保交易 ,tb**1 ,电磁猫适用oppofindx8ultra钢化膜findx8s/OPPO Find X9 Pro手机膜秒贴盒除尘仓高清 等多件,60.70 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102922001409201411937423 ,3959672142825460539 ,2025-10-29 06:10:46 ,2025-10-29 06:10:47 ,2025-10-29 06:10:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,哔哩哔哩 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102623001109201449839060 ,T200P3022551732781802159 ,2025-10-26 20:35:51 ,2025-10-26 20:35:57 ,2025-11-02 08:58:02 ,淘宝 ,支付宝担保交易 ,绿联**店 ,绿联magsafe磁吸无线充电器适用于iPhone17/16promax手机安卓桌面支架底座配件20w快充电线板通用,114.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102623001109201453026140 ,T200P3022254627331802159 ,2025-10-26 20:22:05 ,2025-10-26 20:22:06 ,2025-11-02 08:58:02 ,淘宝 ,支付宝担保交易 ,亨达**店 ,【优惠价】液态硅胶适用OPPOfindx8/S手机壳新款findx8ultra磁吸保护套全包findx8pro防摔f,15.10 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102623001109201452477977_3022283678505802159 ,T200P3022283678505802159 ,2025-10-26 20:00:28 , ,2025-10-26 20:00:28 ,淘宝 ,支付宝担保交易 ,ba**店 ,退款-【优惠价】Balueus适用oppofindx8ultra手机壳findx8pro保护套oppo高级感findx8s,57.80 ,不计收支 ,退款成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2025102623001109201455732788 ,T200P3022489129609802159 ,2025-10-26 20:00:01 ,2025-10-26 20:00:02 ,2025-11-01 20:08:00 ,淘宝 ,支付宝担保交易 ,ba**店 ,【优惠价】Balueus适用oppofindx8ultra手机壳findx8pro保护套oppo高级感findx8s,57.80 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102623001109201452477977 ,T200P3022283678505802159 ,2025-10-26 19:59:53 ,2025-10-26 19:59:54 ,2025-10-26 20:00:28 ,淘宝 ,支付宝担保交易 ,ba**店 ,【优惠价】Balueus适用oppofindx8ultra手机壳findx8pro保护套oppo高级感findx8s,57.80 ,支出 ,交易关闭 ,0.00 ,57.80 , ,已支出 ,
|
||||
2025102623001109201452956421 ,T200P3021145287024802159 ,2025-10-26 12:33:55 ,2025-10-26 12:34:01 ,2025-11-01 20:07:46 ,淘宝 ,支付宝担保交易 ,楚** ,维修SHOKZ韶音耳机OpenFit/T910断裂不通话AS800/810换电池不开机,136.89 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102523001109201445930694 ,T200P3019681778942802159 ,2025-10-25 17:55:10 ,2025-10-25 17:55:20 ,2025-11-01 20:07:54 ,淘宝 ,支付宝担保交易 ,ko**e ,德国手拍鼓婴儿早教拍拍益智玩具0一1岁6-12个月儿童音乐玩具礼盒 等多件,377.52 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20251023092084708205 ,alipay01-P251023203002028 ,2025-10-23 20:29:47 ,2025-10-23 20:29:47 ,2025-10-23 20:30:09 ,支付宝网站 ,即时到账交易 ,广州市普晖药业连锁有限公司万东店(医保),医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20251023092084892156 ,440120251023764018557 ,2025-10-23 20:29:38 ,2025-10-23 20:29:38 ,2025-10-23 20:30:21 ,支付宝网站 ,即时到账交易 ,广州市普晖药业连锁有限公司万东店,医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025102323001109201433117356 ,T200P3013956372800802159 ,2025-10-23 09:11:23 , ,2025-10-23 09:11:48 ,淘宝 ,支付宝担保交易 ,喵速**店 ,【优惠价】【 政府补贴】一加 13T 性能超强小直屏 高通骁龙 8 至尊版 小屏大魔王学生游戏拍照手机,3190.02 ,不计收支 ,交易关闭 ,0.00 ,0.00 , , ,
|
||||
2025101923001109201402251275 ,T200P3005227056037802159 ,2025-10-19 21:03:28 ,2025-10-19 21:03:34 ,2025-10-28 14:48:08 ,淘宝 ,支付宝担保交易 ,lx**e ,小米米家新风空调HEPA滤芯立式挂机专用1.5p2p3p官网原装正品滤芯,139.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025100123001109201458086898 ,T200P2968236338247802159 ,2025-10-01 12:28:56 ,2025-10-01 12:28:57 ,2025-10-11 12:29:11 ,淘宝 ,支付宝担保交易 ,tb**9 ,S15云顶端游记牌器自动拿牌三星预警云顶之弈辅助诸葛助手阵容,30.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025093022001409201452602755 ,P18M6666031250930160191802159 ,2025-09-30 17:37:33 ,2025-09-30 17:37:34 ,2025-09-30 17:37:34 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,HM 盒马中号生物降解购物袋-HC-0.040mm等3类商品,68.60 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025093022001409201445849145 ,P18M6666031250930371215802159 ,2025-09-30 17:07:21 ,2025-09-30 17:07:22 ,2025-09-30 17:07:22 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,泰式咖喱虾 250g等2类商品 ,64.80 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025093022001409201445866349 ,ROBOT1759222267000549210 ,2025-09-30 16:52:28 ,2025-09-30 16:52:34 ,2025-09-30 16:52:34 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,天津泡泡玛特文化传播有限公司 ,泡泡玛特-消费 ,158.99 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025093022001409201446024651 ,2025093015153520120663325 ,2025-09-30 15:15:36 ,2025-09-30 15:15:44 ,2025-09-30 15:15:44 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,途虎养车 ,途虎养车TH1145519605112932755订单,1978.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025092823001409201430606843 ,3959621593073390345 ,2025-09-28 06:14:08 ,2025-09-28 06:14:09 ,2025-09-28 06:14:09 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025091823001109201419821724 ,T200P2941462957803802159 ,2025-09-18 13:24:58 ,2025-09-18 13:25:05 ,2025-09-28 15:36:08 ,淘宝 ,支付宝担保交易 ,周大**店 ,周大福MONOLOGUE独白鬼灭之刃复古黄金转运珠多款【售完不补】,1396.50 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025091423001409201446793131 ,908557225029566476 ,2025-09-14 09:06:17 ,2025-09-14 09:06:17 ,2025-09-14 09:06:17 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,千岛 ,千岛卖家老板请收货(848428678244218990),订单号908557217763928506,38.46 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20250913200040011100200070649422 ,c7f04d9be6b0678280f189e3c913c0b1 ,2025-09-13 13:14:19 ,2025-09-13 13:14:20 ,2025-09-13 13:14:21 ,支付宝网站 ,即时到账交易 ,浦发银行 ,提现-实时提现 ,13.26 ,不计收支 ,交易成功 ,0.10 ,0.00 , ,资金转移 ,
|
||||
2025082922001409201415083173 ,20250829ALPP004287353111 ,2025-08-29 19:52:55 ,2025-08-29 19:52:55 ,2025-08-29 19:52:55 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,单程广州盐城 ,1040.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025082822001409201402895388 ,3946655946639021836 ,2025-08-28 06:15:37 ,2025-08-28 06:15:38 ,2025-08-28 06:15:38 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025082610032004720261895397 , ,2025-08-26 22:36:30 , ,2025-08-26 22:36:31 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,杭州闲鱼信息技术有限公司 ,分账-基础软件服务费(4704709323855807423)扣款,1.26 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025082623001107721440477440 ,T200P4704709323855807423 ,2025-08-26 22:35:41 ,2025-08-26 22:35:46 ,2025-08-26 22:36:28 ,淘宝 ,支付宝担保交易 ,****5 ,澳门英皇葡京人影院8月30日(周六下午1点)鬼灭之刃无限城篇,210.00 ,收入 ,交易成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2025082623001107721439861713 ,T200P4704531770319807423 ,2025-08-26 22:33:55 ,2025-08-26 22:34:02 ,2025-08-26 22:34:48 ,淘宝 ,支付宝担保交易 ,****5 ,澳门英皇葡京人影院8月30日(周六下午1点)鬼灭之刃无限城篇,249.00 ,收入 ,交易关闭 ,0.00 ,249.00 , ,已收入 ,
|
||||
2025082623001107721441015774 ,T200P4704506318268807423 ,2025-08-26 22:14:50 , ,2025-08-26 22:19:55 ,淘宝 ,支付宝担保交易 ,****5 ,澳门英皇葡京人影院8月30日(周六下午1点)鬼灭之刃无限城篇,249.00 ,不计收支 ,交易关闭 ,0.00 ,0.00 , , ,
|
||||
2025082423001109201448829864 ,T200P2893031079896802159 ,2025-08-24 13:07:47 ,2025-08-24 13:07:57 ,2025-08-24 13:21:54 ,淘宝 ,支付宝担保交易 ,x***9 ,流放之路2 新服 崇高石1000个=标价 库存充足 现货秒发,1.50 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025082423001109201449996923 ,T200P2893035075217802159 ,2025-08-24 13:07:24 ,2025-08-24 13:08:23 ,2025-08-24 13:21:43 ,淘宝 ,支付宝担保交易 ,x***9 ,流放之路2 新赛季新区 神圣石100个=标价,库存充足,现货,24.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025082022001409201424285111 ,20250820190142351755 ,2025-08-20 19:02:06 ,2025-08-20 19:02:07 ,2025-08-20 19:02:07 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,北京轨道交通路网管理有限公司 ,地铁_太平桥_2025-08-20 18:34:20_东管头_2025-08-20 19:01:16,4.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025081622001473021421565076 ,47553338181022064773021 ,2025-08-16 16:43:40 ,2025-08-16 16:43:45 ,2025-08-16 16:43:45 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,**阳 ,收钱码收款 ,810.00 ,收入 ,交易成功 ,0.00 ,0.00 , ,已收入 ,
|
||||
2025081023001109201440197928 ,T200P2872074974855802159 ,2025-08-10 17:03:38 ,2025-08-10 17:03:44 ,2025-08-10 17:56:24 ,淘宝 ,支付宝担保交易 ,t***0 ,暗黑4 S9赛季 - 折磨4彼列50次速刷套餐(4.98元超,4.98 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025081023001109201440594559 ,T200P2871930975876802159 ,2025-08-10 16:40:53 ,2025-08-10 16:40:59 ,2025-08-10 16:44:32 ,淘宝 ,支付宝担保交易 ,t***0 ,暗黑4秒开折磨4难度 - 1元1分钟极速解锁!,1.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025072822001409201425176326 ,3939387104559567552 ,2025-07-28 06:17:14 ,2025-07-28 06:17:15 ,2025-07-28 06:17:15 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025072722001409201427577378 ,108da8bae9ea8a0e0a078c1881a38096 ,2025-07-27 21:35:02 ,2025-07-27 21:35:12 ,2025-07-27 21:35:12 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,义乌市申旭文化传媒有限公司 ,108da8bae9ea8a0e0a078c1881a38096,148.40 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20250720020070011580200064135472 ,FP301_7042395238080142 ,2025-07-20 23:27:17 ,2025-07-20 23:27:18 ,2025-07-20 23:27:18 ,支付宝网站 ,即时到账交易 ,*挺 ,支付宝转账小额打款-关联订单号:2623529461253802159,100.00 ,收入 ,交易成功 ,0.00 ,0.00 ,支付宝转账小额打款-关联订单号:2623529461253802159,已收入 ,
|
||||
2025072023001109201448348472 ,T200P2839671626173802159 ,2025-07-20 16:20:39 ,2025-07-20 16:20:43 ,2025-07-30 16:20:57 ,淘宝 ,支付宝担保交易 ,嗷嗷**块 ,F1 TV Premium 2025赛季/F1TV PRO/F1直播 F1赛车/F1TV会员,23.15 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025071923001109201436610173 ,T200P2836832053749802159 ,2025-07-19 10:23:42 ,2025-07-19 10:23:56 ,2025-07-19 10:27:40 ,淘宝 ,支付宝担保交易 ,2***螂 ,(自动发货)特价出W+ 万达影城会员卡 2025新版!,187.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20250712092016458479 ,alipay01-P250712101648603 ,2025-07-12 10:16:32 ,2025-07-12 10:16:32 ,2025-07-12 10:16:52 ,支付宝网站 ,即时到账交易 ,广州医科大学附属第三医院 ,医保支付(不含自费) ,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025070523001109201422018301 ,T200P2814467163755802159 ,2025-07-05 12:53:52 ,2025-07-05 12:53:53 ,2025-07-15 13:23:39 ,淘宝 ,支付宝担保交易 ,a1**7 ,ps5最终幻想7重生 FF7rb 中文下载版 出租 租赁 认证非认证,10.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025070322001409201410356457 ,4895191022886 ,2025-07-03 19:26:17 ,2025-07-03 19:26:18 ,2025-07-03 19:26:18 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,百度 ,百度网盘超级会员(1个月-自动续费) ,25.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062723001109201443376098 ,T200P2803083097673802159 ,2025-06-27 20:10:47 ,2025-06-27 20:10:48 ,2025-07-07 20:11:22 ,淘宝 ,支付宝担保交易 ,a1**7 ,ps5最终幻想7重生 FF7rb 中文下载版 出租 租赁 认证非认证,10.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062722001409201439330939 ,3928461282379470495 ,2025-06-27 06:09:30 ,2025-06-27 06:09:31 ,2025-06-27 06:09:31 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062422001409201417628729 ,20P2088721085226061W03_120250624000089470495 ,2025-06-24 15:54:26 ,2025-06-24 15:55:11 ,2025-06-24 15:55:11 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,中海物业管理有限公司 ,中海物业管理有限公司-消费 ,534.98 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062422001409201424139286 ,20250624ALPP002288680903 ,2025-06-24 14:15:01 ,2025-06-24 14:15:02 ,2025-06-24 14:15:02 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,携程旅行网 ,单程盐城深圳 ,610.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062223001109201414474418 ,T200P2623134864177802159 ,2025-06-22 15:43:47 ,2025-06-22 15:43:48 ,2025-07-02 16:19:52 ,淘宝 ,支付宝担保交易 ,a1**7 ,ps5/ps4国行备份恢复还原 ,5.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062223001109201410736617 ,T200P2623529461253802159 ,2025-06-22 12:46:48 ,2025-06-22 12:46:49 ,2025-07-02 16:20:00 ,淘宝 ,支付宝担保交易 ,a1**7 ,游戏押金 ,100.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025062223001109201410721727 ,T200P2623530037105802159 ,2025-06-22 12:46:30 ,2025-06-22 12:46:31 ,2025-07-02 16:19:59 ,淘宝 ,支付宝担保交易 ,a1**7 ,ps5最终幻想7重生 FF7rb 中文下载版 出租 租赁 认证非认证,10.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025061922001409201441584256 ,493977700219778586 ,2025-06-19 05:42:02 ,2025-06-19 05:42:03 ,2025-06-19 05:42:03 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州市动景计算机科技有限公司 ,连续包月(网盘SVIP会员) ,19.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025061522001409201428856484 ,CPR2506151519214771422775960J ,2025-06-15 15:19:21 ,2025-06-15 15:19:22 ,2025-06-15 15:19:22 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,哈啰出行 ,哈啰单车骑行 ,2.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060322001409201419414878 ,4865811769433 ,2025-06-03 19:16:59 ,2025-06-03 19:17:00 ,2025-06-03 19:17:00 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,百度 ,百度网盘超级会员(1个月-自动续费) ,25.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060122001409201402867048 ,P18M6666031250601596423802159 ,2025-06-01 12:32:46 ,2025-06-01 12:32:47 ,2025-06-01 12:32:47 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,东魁杨梅 450g等2类商品 ,35.80 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060122001409201406746610 ,P18M6666031250601590374802159 ,2025-06-01 11:52:55 ,2025-06-01 11:52:56 ,2025-06-01 11:52:56 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,SCHWEPPES/怡泉 +C 柠檬味 汽水 400ml,3.50 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060122001409201406735405 ,P18M6666031250601602373802159 ,2025-06-01 11:48:43 ,2025-06-01 11:48:44 ,2025-06-01 11:48:44 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,广式清补凉 550ml ,9.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060122001409201402714138 ,P18M6666031250601614326802159 ,2025-06-01 11:48:26 ,2025-06-01 11:48:27 ,2025-06-01 11:48:27 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,【新虾上市】小龙虾神鲜桶(蒜蓉) 4-6钱 1.5kg,99.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025060122001409201400485022 ,P18M6666031250601639367802159 ,2025-06-01 11:46:13 ,2025-06-01 11:46:14 ,2025-06-01 11:46:14 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,韭菜水晶饺-中份-潮祥记等2类商品 ,25.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025053123001109201458551523 ,T200P2590092913073802159 ,2025-05-31 17:03:30 ,2025-05-31 19:02:16 ,2025-05-31 19:35:28 ,淘宝 ,支付宝担保交易 ,t***2 ,国际象棋chessbase18软件 ,20.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025053123001109201458534570 ,T200P2589225134161802159 ,2025-05-31 12:58:31 ,2025-05-31 12:58:32 ,2025-06-10 14:19:35 ,淘宝 ,支付宝担保交易 ,其** ,原装小1u电源200W300W通用FSP270-60LE FLEX NAS小机箱台式机静音,46.65 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025052722001409201422355684 ,3916129009402909158 ,2025-05-27 06:11:06 ,2025-05-27 06:11:07 ,2025-05-27 06:11:07 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,购买大会员连续包月 ,15.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025052422001409201410004932 ,P18M6666031250524453357802159 ,2025-05-24 17:00:54 ,2025-05-24 17:00:55 ,2025-05-24 17:00:55 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州盒马 ,盒马 无抗大码富硒谷物蛋20枚 1.2kg等3类商品,157.09 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
20250521300000015909201257998362 ,T200P2559964983224802159 ,2025-05-21 14:43:34 ,2025-05-21 14:43:34 ,2025-05-21 14:43:34 ,淘宝 ,支付宝担保交易 ,xy**g ,T0任天堂switch漂移TMR摇杆joycon手柄维修JOY-CON磁阻高精度摇杆,46.11 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025052022001409201428528574 ,488541211077483773 ,2025-05-20 05:36:43 ,2025-05-20 05:36:44 ,2025-05-20 05:36:44 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,广州市动景计算机科技有限公司 ,连续包月(网盘SVIP会员) ,19.90 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025051823001109201417191736 ,T200P2571317725811802159 ,2025-05-18 14:49:24 ,2025-05-18 14:49:43 ,2025-05-28 14:49:53 ,淘宝 ,支付宝担保交易 ,t***9 ,【自动发货】PC微软飞行模拟2020中文不限速 模拟经营,1.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025051722001409201408914228 ,4908242128243495529 ,2025-05-17 20:05:08 ,2025-05-17 20:05:08 ,2025-05-17 20:05:08 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,上海宽娱数码科技有限公司 ,付费-《红辣椒》 ,2.40 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025051322001409201436252545 ,20250513084942405755 ,2025-05-13 08:56:30 ,2025-05-13 08:56:31 ,2025-05-13 08:56:31 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,北京轨道交通路网管理有限公司 ,地铁_东管头_2025-05-13 08:24:49_太平桥_2025-05-13 08:49:24,4.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025051222001409201431920402 ,20250512083702413755 ,2025-05-12 08:41:45 ,2025-05-12 08:41:46 ,2025-05-12 08:41:46 ,其他(包括阿里巴巴和外部商家),即时到账交易 ,北京轨道交通路网管理有限公司 ,地铁_东管头_2025-05-12 08:13:00_太平桥_2025-05-12 08:36:16,4.00 ,支出 ,交易成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
2025051123001109201425526597 ,T200P2559964983224802159 ,2025-05-11 07:56:14 ,2025-05-11 07:56:14 ,2025-05-11 07:56:14 ,淘宝 ,支付宝担保交易 ,xy**g ,T0任天堂switch漂移TMR摇杆joycon手柄维修JOY-CON磁阻高精度摇杆,0.00 ,支出 ,支付成功 ,0.00 ,0.00 , ,已支出 ,
|
||||
------------------------------------------------------------------------------------
|
||||
共130笔记录
|
||||
已收入:4笔,1120.00元
|
||||
待收入:0笔,0.00元
|
||||
已支出:115笔,27403.24元
|
||||
待支出:0笔,0.00元
|
||||
导出时间:[2026-05-05 15:18:22] 用户:傅堃
|
||||
|
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"llm_api_key": "sk-138e94b85f664fac858cc27525dd37f1",
|
||||
"llm_base_url": "https://api.deepseek.com",
|
||||
"llm_model": "deepseek-v4-flash"
|
||||
}
|
||||
Generated
+33
-4
@@ -14,6 +14,7 @@
|
||||
"csv-parse": "^5.6.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"express": "^4.21.0",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"openai": "^4.73.0",
|
||||
"uuid": "^10.0.0",
|
||||
@@ -192,6 +193,18 @@
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/qs": {
|
||||
"version": "6.15.1",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/qs/-/qs-6.15.1.tgz",
|
||||
@@ -887,15 +900,19 @@
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/iconv-lite/-/iconv-lite-0.7.2.tgz",
|
||||
"integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
@@ -1327,6 +1344,18 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body/node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rc": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://mirrors.huaweicloud.com/repository/npm/rc/-/rc-1.2.8.tgz",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"csv-parse": "^5.6.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"express": "^4.21.0",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"openai": "^4.73.0",
|
||||
"uuid": "^10.0.0",
|
||||
|
||||
+22
-28
@@ -107,34 +107,28 @@ function initDB() {
|
||||
CREATE INDEX IF NOT EXISTS idx_tx_category ON transactions(category);
|
||||
`);
|
||||
|
||||
// 插入默认分类
|
||||
const insertCategory = database.prepare(
|
||||
'INSERT OR IGNORE INTO categories (id, name, keywords) VALUES (?, ?, ?)'
|
||||
);
|
||||
|
||||
const defaultCategories = [
|
||||
[1, '餐饮美食', '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
[2, '交通出行', '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
|
||||
[3, '购物消费', '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
|
||||
[4, '住房相关', '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
[5, '通讯网络', '["话费","宽带","流量"]'],
|
||||
[6, '投资理财', '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
[7, '工资收入', '["工资","薪资","奖金","报销","劳务"]'],
|
||||
[8, '转账红包', '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
[9, '医疗健康', '["医院","药店","挂号","体检","保险"]'],
|
||||
[10, '教育学习', '["学费","培训","书本","课程","考试"]'],
|
||||
[11, '娱乐休闲', '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
[12, '信用卡还款', '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
[13, '其他杂项', '[]']
|
||||
];
|
||||
|
||||
const insertMany = database.transaction((cats) => {
|
||||
for (const cat of cats) {
|
||||
insertCategory.run(cat[0], cat[1], cat[2]);
|
||||
}
|
||||
});
|
||||
|
||||
insertMany(defaultCategories);
|
||||
// 仅首次初始化时插入默认分类(不再用固定ID)
|
||||
const catCount = database.prepare("SELECT COUNT(*) as c FROM categories").get().c;
|
||||
if (catCount === 0) {
|
||||
const insertCategory = database.prepare("INSERT INTO categories (name, keywords) VALUES (?, ?)");
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
["交通出行", '["公交","地铁","打车","出租车","加油","停车","高速","火车","飞机","骑行"]'],
|
||||
["购物消费", '["淘宝","京东","拼多多","超市","百货","服饰","数码","家电","日用品"]'],
|
||||
["住房相关", '["房租","房贷","物业","水电","燃气","维修","装修"]'],
|
||||
["通讯网络", '["话费","宽带","流量"]'],
|
||||
["投资理财", '["基金","股票","理财","定期","转入","转出","收益"]'],
|
||||
["工资收入", '["工资","薪资","奖金","报销","劳务"]'],
|
||||
["转账红包", '["转账","红包","汇款","收款","提现","充值"]'],
|
||||
["医疗健康", '["医院","药店","挂号","体检","保险"]'],
|
||||
["教育学习", '["学费","培训","书本","课程","考试"]'],
|
||||
["娱乐休闲", '["电影","演出","旅游","酒店","游戏","充值","会员"]'],
|
||||
["信用卡还款", '["还款","信用卡","花呗","借呗","白条"]'],
|
||||
["其他杂项", "[]"]
|
||||
];
|
||||
database.transaction(() => { defaults.forEach(c => insertCategory.run(c[0], c[1])); })();
|
||||
console.log("[Reco] 已初始化默认分类");
|
||||
}
|
||||
|
||||
console.log('[Reco] 数据库初始化完成');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
const XLSX = require('xlsx');
|
||||
const dayjs = require('dayjs');
|
||||
|
||||
/**
|
||||
* 农业银行 XLSX 流水解析
|
||||
*
|
||||
* 多 Sheet,每个 Sheet 结构:
|
||||
* R0-R2: 元数据 (户名、币种、起止日期)
|
||||
* R3: 表头 (交易日期,交易时间,交易摘要,交易金额,,本次余额,对手信息,日志号,交易渠道,交易附言)
|
||||
* R4+: 数据(部分交易跨2行)
|
||||
*/
|
||||
|
||||
function parseABC(filePath) {
|
||||
const wb = XLSX.readFile(filePath);
|
||||
const transactions = [];
|
||||
|
||||
for (const name of wb.SheetNames) {
|
||||
const ws = wb.Sheets[name];
|
||||
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '', raw: true });
|
||||
if (!rows || rows.length < 5) continue;
|
||||
|
||||
// 收集有效数据行(跳过空行、元数据、页脚)
|
||||
const dataRows = [];
|
||||
for (let i = 4; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length === 0) continue;
|
||||
const hasContent = row.some(c => c !== '');
|
||||
const isFooter = String(row[0] || '').includes('该交易明细') || String(row[0] || '').includes('第') && String(row[0] || '').includes('页');
|
||||
if (hasContent && !isFooter) dataRows.push(row);
|
||||
}
|
||||
|
||||
// 合并多行:如果 row[0] 为空,附加到上一行
|
||||
const merged = [];
|
||||
for (const row of dataRows) {
|
||||
if (!row[0] && merged.length > 0) {
|
||||
// 合并: 时间取 row[1],对手信息拼接 row[6]
|
||||
const prev = merged[merged.length - 1];
|
||||
if (row[1] && !prev[1]) prev[1] = row[1];
|
||||
if (row[6]) prev[6] = (prev[6] || '') + row[6];
|
||||
if (row[3] && !prev[3]) prev[3] = row[3];
|
||||
} else if (row[0]) {
|
||||
merged.push([...row]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of merged) {
|
||||
const dateRaw = row[0]; // 20250507
|
||||
const timeRaw = row[1]; // 080222 或空
|
||||
const summary = String(row[2] || '').trim(); // 转支/南网电费/转存...
|
||||
const amountRaw = row[3]; // -2.85 / 832
|
||||
const balanceRaw = row[5]; // 本次余额
|
||||
const counterpartyRaw = String(row[6] || '').trim(); // 对手信息
|
||||
const channel = String(row[8] || '').trim(); // 交易渠道
|
||||
const notes = String(row[9] || '').trim(); // 交易附言
|
||||
|
||||
if (!dateRaw) continue;
|
||||
|
||||
const amount = parseFloat(amountRaw);
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
// 日期
|
||||
const ds = String(dateRaw);
|
||||
let dateStr;
|
||||
if (ds.length === 8) dateStr = `${ds.substring(0, 4)}-${ds.substring(4, 6)}-${ds.substring(6, 8)}`;
|
||||
else dateStr = dayjs(ds).format('YYYY-MM-DD');
|
||||
|
||||
// 时间
|
||||
let timeStr = '';
|
||||
const ts = String(timeRaw || '').trim();
|
||||
if (ts.length === 6) timeStr = `${ts.substring(0, 2)}:${ts.substring(2, 4)}:${ts.substring(4, 6)}`;
|
||||
const txTime = timeStr ? `${dateStr} ${timeStr}` : dateStr;
|
||||
|
||||
const direction = amount >= 0 ? 'income' : 'expense';
|
||||
const balance = balanceRaw ? parseFloat(balanceRaw) : null;
|
||||
|
||||
// 支付方式
|
||||
let method = '';
|
||||
if (channel === '电子商务') method = '电子商务';
|
||||
else if (summary.includes('转支')) method = '转账支出';
|
||||
else if (summary.includes('转存')) method = '转账存入';
|
||||
else if (summary.includes('还房贷')) method = '房贷还款';
|
||||
else if (summary.includes('电费')) method = '电费扣款';
|
||||
else if (summary.includes('还款')) method = '信用卡还款';
|
||||
else method = summary;
|
||||
|
||||
transactions.push({
|
||||
transaction_date: dateStr,
|
||||
transaction_time: txTime,
|
||||
counterparty: counterpartyRaw || '--',
|
||||
description: summary,
|
||||
notes,
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method,
|
||||
raw_data: JSON.stringify({ dateRaw, timeRaw, summary, amountRaw, balanceRaw, counterpartyRaw, channel, notes })
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseABC };
|
||||
+103
-190
@@ -1,208 +1,121 @@
|
||||
const dayjs = require("dayjs");
|
||||
const XLSX = require('xlsx');
|
||||
const iconv = require('iconv-lite');
|
||||
const fs = require('fs');
|
||||
const dayjs = require('dayjs');
|
||||
|
||||
/**
|
||||
* 支付宝账单CSV解析器
|
||||
*
|
||||
* 支付宝导出的CSV通常有两种格式:
|
||||
* 1. 标准版:交易时间,交易对方,商品说明,收/支,金额,交易状态,交易订单号,收/付款方式...
|
||||
* 2. 新版:可能列名略有不同
|
||||
*
|
||||
* 此解析器尝试自动识别列名
|
||||
*/
|
||||
function parseAlipayCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
// 跳过空行和标题行
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
// 尝试多种可能的列名映射
|
||||
const dateStr =
|
||||
record["交易时间"] ||
|
||||
record["交易日期"] ||
|
||||
record["time"] ||
|
||||
record["date"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["交易对象"] ||
|
||||
record["counterparty"] ||
|
||||
record["merchant"] ||
|
||||
"";
|
||||
const description =
|
||||
record["商品说明"] ||
|
||||
record["商品"] ||
|
||||
record["商品名称"] ||
|
||||
record["description"] ||
|
||||
record["product"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || "";
|
||||
const directionStr =
|
||||
record["收/支"] ||
|
||||
record["收支"] ||
|
||||
record["direction"] ||
|
||||
record["type"] ||
|
||||
"";
|
||||
const amountStr =
|
||||
record["金额"] || record["amount"] || record["money"] || "0";
|
||||
const status =
|
||||
record["交易状态"] || record["status"] || record["交易状态"] || "";
|
||||
const method =
|
||||
record["收/付款方式"] ||
|
||||
record["支付方式"] ||
|
||||
record["method"] ||
|
||||
record["payment"] ||
|
||||
"";
|
||||
const orderNo =
|
||||
record["交易订单号"] ||
|
||||
record["订单号"] ||
|
||||
record["order_no"] ||
|
||||
record["trade_no"] ||
|
||||
"";
|
||||
const dateStr = record['交易时间'] || record['交易创建时间'] || record['交易日期'] || record['付款时间'] || '';
|
||||
const counterparty = record['交易对方'] || record['交易对象'] || record['counterparty'] || '';
|
||||
const description = record['商品说明'] || record['商品名称'] || record['商品'] || record['description'] || '';
|
||||
const notes = record['备注'] || record['memo'] || '';
|
||||
const directionStr = record['收/支'] || record['收支'] || record['direction'] || '';
|
||||
const amountStr = record['金额'] || record['金额(元)'] || record['amount'] || '0';
|
||||
const status = record['交易状态'] || record['status'] || '';
|
||||
const method = record['收/付款方式'] || record['支付方式'] || record['method'] || '支付宝';
|
||||
const orderNo = record['交易号'] || record['交易订单号'] || record['订单号'] || '';
|
||||
|
||||
if (!dateStr && !amountStr) continue;
|
||||
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ''));
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
// 确定收支方向
|
||||
let direction = "expense";
|
||||
if (
|
||||
directionStr.includes("收入") ||
|
||||
directionStr.includes("收") ||
|
||||
directionStr === "收入"
|
||||
) {
|
||||
direction = "income";
|
||||
} else if (directionStr.includes("支") || directionStr.includes("支出")) {
|
||||
direction = "expense";
|
||||
} else if (amount > 0) {
|
||||
direction = "income";
|
||||
} else {
|
||||
amount = -Math.abs(amount);
|
||||
direction = "expense";
|
||||
}
|
||||
let direction = 'expense';
|
||||
if (directionStr.includes('收入') || directionStr === '收入') direction = 'income';
|
||||
else if (directionStr.includes('支')) direction = 'expense';
|
||||
|
||||
// 统一金额符号:支出为负
|
||||
if (direction === "expense") {
|
||||
amount = -Math.abs(amount);
|
||||
} else {
|
||||
amount = Math.abs(amount);
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
status: status.trim(),
|
||||
method: method.trim(),
|
||||
order_no: orderNo.trim(),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
function parseDate(dateStr) {
|
||||
if (!dateStr) return dayjs().format("YYYY-MM-DD");
|
||||
|
||||
// 尝试多种日期格式
|
||||
const formats = [
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm",
|
||||
"YYYY-MM-DD",
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY/MM/DD HH:mm",
|
||||
"YYYY/MM/DD",
|
||||
"MM/DD/YYYY HH:mm:ss",
|
||||
"MM/DD/YYYY",
|
||||
"YYYY年MM月DD日 HH:mm:ss",
|
||||
"YYYY年MM月DD日 HH:mm",
|
||||
"YYYY年MM月DD日",
|
||||
];
|
||||
|
||||
for (const fmt of formats) {
|
||||
const d = dayjs(dateStr, fmt);
|
||||
if (d.isValid()) return d.format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
// 最后尝试直接解析
|
||||
const d = dayjs(dateStr);
|
||||
if (d.isValid()) return d.format("YYYY-MM-DD");
|
||||
|
||||
return dayjs().format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseAlipayFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
|
||||
// 假设第一行是表头
|
||||
const headers = rows[0];
|
||||
const headerMap = {};
|
||||
headers.forEach((h, i) => {
|
||||
headerMap[h] = i;
|
||||
});
|
||||
|
||||
const transactions = [];
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
const row = rows[i];
|
||||
if (!row || row.length === 0) continue;
|
||||
|
||||
const dateStr = String(
|
||||
row[headerMap["交易时间"] || headerMap["交易日期"]] || row[0] || "",
|
||||
);
|
||||
const counterparty = String(
|
||||
row[headerMap["交易对方"]] || row[2] || "",
|
||||
).trim();
|
||||
const description = String(
|
||||
row[headerMap["商品说明"] || headerMap["商品"]] || row[3] || "",
|
||||
).trim();
|
||||
const directionStr = String(row[headerMap["收/支"]] || row[4] || "").trim();
|
||||
const amountRaw = row[headerMap["金额"]] || row[5] || 0;
|
||||
|
||||
let amount = parseFloat(amountRaw);
|
||||
if (isNaN(amount)) amount = 0;
|
||||
let direction = "expense";
|
||||
if (directionStr.includes("收入") || directionStr.includes("收"))
|
||||
direction = "income";
|
||||
else if (directionStr.includes("支出") || directionStr.includes("支"))
|
||||
direction = "expense";
|
||||
|
||||
if (direction === "expense") amount = -Math.abs(amount);
|
||||
if (direction === 'expense') amount = -Math.abs(amount);
|
||||
else amount = Math.abs(amount);
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty,
|
||||
description,
|
||||
notes: "",
|
||||
amount,
|
||||
direction,
|
||||
status: "",
|
||||
method: "",
|
||||
order_no: "",
|
||||
raw_data: JSON.stringify(row),
|
||||
transaction_date: parseDate(dateStr),
|
||||
transaction_time: dateStr.includes(':') ? dateStr.trim() : parseDate(dateStr),
|
||||
counterparty: counterparty.trim(), description: description.trim(), notes: notes.trim(),
|
||||
amount, direction, status: status.trim(), method, order_no: orderNo.trim(),
|
||||
raw_data: JSON.stringify(record)
|
||||
});
|
||||
}
|
||||
return transactions;
|
||||
}
|
||||
|
||||
module.exports = { parseAlipayCSV, parseAlipayFromXLSX, parseDate };
|
||||
function parseDate(s) {
|
||||
if (!s) return dayjs().format('YYYY-MM-DD');
|
||||
const fmts = ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm', 'YYYY-MM-DD', 'YYYY/MM/DD HH:mm:ss', 'YYYY/MM/DD'];
|
||||
for (const f of fmts) { const d = dayjs(s, f); if (d.isValid()) return d.format('YYYY-MM-DD'); }
|
||||
const d = dayjs(s); return d.isValid() ? d.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD');
|
||||
}
|
||||
|
||||
// ── 新版支付宝 GBK CSV(Tab+逗号混合分隔) ──
|
||||
|
||||
function parseAlipayFile(filePath) {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
let content;
|
||||
try { content = iconv.decode(buf, 'gbk'); } catch (e) { content = buf.toString('utf-8'); }
|
||||
|
||||
const lines = content.split('\n').filter(l => l.trim());
|
||||
if (lines.length < 5) return [];
|
||||
|
||||
const skip = ['支付宝', '账号', '起始日期', '---', '导出时间', '待收入', '已支出', '待支出', '交易号'];
|
||||
|
||||
const transactions = [];
|
||||
for (const line of lines) {
|
||||
if (skip.some(p => line.startsWith(p))) continue;
|
||||
|
||||
// 逗号分割 + 清理前导 tab 和空白
|
||||
const cols = line.split(',').map(c => c.replace(/^\t/, '').trim());
|
||||
if (cols.length < 12) continue;
|
||||
|
||||
const tradeNo = cols[0];
|
||||
const createTime = cols[2]; // 交易创建时间
|
||||
const payTime = cols[3]; // 付款时间
|
||||
const source = cols[5]; // 交易来源地
|
||||
const type = cols[6]; // 类型
|
||||
const counterparty = cols[7]; // 交易对方
|
||||
const product = cols[8]; // 商品名称
|
||||
const amountStr = cols[9]; // 金额
|
||||
const directionStr = cols[10]; // 收/支
|
||||
const status = cols[11]; // 交易状态
|
||||
const refundStr = cols[13]; // 成功退款(元)
|
||||
const notes = cols[14] || ''; // 备注
|
||||
|
||||
// 跳过:不计收支 / 已成功退款的交易
|
||||
if (directionStr.includes('不计收支')) continue;
|
||||
if (refundStr && parseFloat(refundStr) > 0) continue;
|
||||
|
||||
// 优先付款时间,退款时可能为空
|
||||
const dateStr = payTime || createTime;
|
||||
if (!dateStr || !amountStr) continue;
|
||||
|
||||
let amount = parseFloat(amountStr);
|
||||
if (isNaN(amount) || amount === 0) continue;
|
||||
|
||||
let direction = 'expense';
|
||||
if (directionStr.includes('收入')) direction = 'income';
|
||||
else if (directionStr.includes('不计收支')) direction = 'income';
|
||||
else if (directionStr.includes('支出')) direction = 'expense';
|
||||
|
||||
if (direction === 'expense') amount = -Math.abs(amount);
|
||||
else amount = Math.abs(amount);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parseDate(dateStr),
|
||||
transaction_time: dateStr.includes(':') ? dateStr : parseDate(dateStr),
|
||||
counterparty, description: product || type, notes, amount, direction, status,
|
||||
method: source.includes('淘宝') ? '淘宝' : '支付宝', order_no: tradeNo,
|
||||
raw_data: JSON.stringify({ cols })
|
||||
});
|
||||
}
|
||||
return transactions;
|
||||
}
|
||||
|
||||
function parseAlipayFromXLSX(filePath) {
|
||||
const wb = XLSX.readFile(filePath);
|
||||
const ws = wb.Sheets[wb.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '', raw: true });
|
||||
if (!rows || rows.length < 2) return [];
|
||||
const headers = rows[0];
|
||||
return parseAlipayCSV(rows.slice(1).map(row => { const o = {}; headers.forEach((h, i) => { o[h] = row[i]; }); return o; }));
|
||||
}
|
||||
|
||||
module.exports = { parseAlipayCSV, parseAlipayFromXLSX, parseAlipayFile };
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
const { parseDate } = require("./alipay");
|
||||
|
||||
/**
|
||||
* 银行卡流水CSV解析器
|
||||
*
|
||||
* 银行导出的CSV格式因银行而异,常见格式:
|
||||
* 交易日期,摘要,交易金额,余额,交易对方,备注
|
||||
* 交易日期,收入金额,支出金额,余额,摘要
|
||||
* 日期,类型,金额,余额,说明
|
||||
*
|
||||
* 此解析器尝试自动识别列名
|
||||
*/
|
||||
function parseBankCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
const dateStr =
|
||||
record["交易日期"] ||
|
||||
record["日期"] ||
|
||||
record["交易时间"] ||
|
||||
record["date"] ||
|
||||
record["time"] ||
|
||||
"";
|
||||
const description =
|
||||
record["摘要"] ||
|
||||
record["说明"] ||
|
||||
record["description"] ||
|
||||
record["summary"] ||
|
||||
record["用途"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["对方"] ||
|
||||
record["counterparty"] ||
|
||||
record["对方户名"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || record["附言"] || "";
|
||||
const balanceStr = record["余额"] || record["balance"] || "";
|
||||
const method =
|
||||
record["交易方式"] || record["渠道"] || record["method"] || "";
|
||||
|
||||
// 银行通常有两种格式:单列金额(正负表示方向) 或 分列收入/支出
|
||||
let amount = 0;
|
||||
let direction = "expense";
|
||||
|
||||
const amountStr =
|
||||
record["交易金额"] || record["金额"] || record["amount"] || "";
|
||||
const incomeStr =
|
||||
record["收入金额"] ||
|
||||
record["收入"] ||
|
||||
record["credit"] ||
|
||||
record["贷方金额"] ||
|
||||
"";
|
||||
const expenseStr =
|
||||
record["支出金额"] ||
|
||||
record["支出"] ||
|
||||
record["debit"] ||
|
||||
record["借方金额"] ||
|
||||
"";
|
||||
|
||||
if (
|
||||
incomeStr &&
|
||||
parseFloat(String(incomeStr).replace(/[,,¥¥\s]/g, "")) !== 0
|
||||
) {
|
||||
amount = parseFloat(String(incomeStr).replace(/[,,¥¥\s]/g, ""));
|
||||
direction = "income";
|
||||
} else if (
|
||||
expenseStr &&
|
||||
parseFloat(String(expenseStr).replace(/[,,¥¥\s]/g, "")) !== 0
|
||||
) {
|
||||
amount = -parseFloat(String(expenseStr).replace(/[,,¥¥\s]/g, ""));
|
||||
direction = "expense";
|
||||
} else if (amountStr) {
|
||||
amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (amount < 0) {
|
||||
direction = "expense";
|
||||
} else {
|
||||
direction = "income";
|
||||
}
|
||||
}
|
||||
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
let balance = null;
|
||||
if (balanceStr) {
|
||||
balance = parseFloat(String(balanceStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (isNaN(balance)) balance = null;
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
balance,
|
||||
method: method.trim(),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseBankFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
// Fallback: use CSV parser on the rows treated as records
|
||||
const headerRow = rows[0];
|
||||
const dataRows = rows.slice(1).map((row) => {
|
||||
const obj = {};
|
||||
headerRow.forEach((h, i) => {
|
||||
obj[h] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
return parseBankCSV(dataRows);
|
||||
}
|
||||
|
||||
module.exports = { parseBankCSV, parseBankFromXLSX };
|
||||
@@ -1,100 +0,0 @@
|
||||
const { parseDate } = require("./alipay");
|
||||
|
||||
/**
|
||||
* 信用卡账单CSV解析器
|
||||
*
|
||||
* 信用卡账单通常格式:
|
||||
* 交易日期,入账日期,交易说明,交易金额,入账金额
|
||||
* 交易日期,交易描述,人民币金额,交易类型
|
||||
*/
|
||||
function parseCreditCardCSV(records) {
|
||||
const transactions = [];
|
||||
|
||||
for (const record of records) {
|
||||
if (!record || Object.keys(record).length === 0) continue;
|
||||
|
||||
const dateStr =
|
||||
record["交易日期"] ||
|
||||
record["交易日"] ||
|
||||
record["date"] ||
|
||||
record["transaction_date"] ||
|
||||
"";
|
||||
const postDateStr =
|
||||
record["入账日期"] || record["记账日"] || record["post_date"] || dateStr;
|
||||
const description =
|
||||
record["交易说明"] ||
|
||||
record["交易描述"] ||
|
||||
record["description"] ||
|
||||
record["商品"] ||
|
||||
"";
|
||||
const counterparty =
|
||||
record["交易对方"] ||
|
||||
record["商户名称"] ||
|
||||
record["merchant"] ||
|
||||
record["counterparty"] ||
|
||||
"";
|
||||
const notes = record["备注"] || record["memo"] || "";
|
||||
|
||||
// 信用卡金额通常是正数表示消费(支出),负数表示还款(收入)
|
||||
const amountStr =
|
||||
record["交易金额"] ||
|
||||
record["人民币金额"] ||
|
||||
record["金额"] ||
|
||||
record["amount"] ||
|
||||
"0";
|
||||
const postAmountStr = record["入账金额"] || record["记账金额"] || "";
|
||||
|
||||
let amount = parseFloat(String(amountStr).replace(/[,,¥¥\s]/g, ""));
|
||||
if (isNaN(amount)) amount = 0;
|
||||
|
||||
// 信用卡:正数=消费(欠款增加,对用户来说是支出)
|
||||
let direction = "expense";
|
||||
if (amount < 0) {
|
||||
direction = "income"; // 负数=还款/退款
|
||||
amount = Math.abs(amount); // 存储为正值收入
|
||||
} else {
|
||||
amount = -Math.abs(amount); // 存储为负值支出
|
||||
}
|
||||
|
||||
const parsedDate = parseDate(dateStr);
|
||||
|
||||
transactions.push({
|
||||
transaction_date: parsedDate,
|
||||
transaction_time: dateStr,
|
||||
counterparty: counterparty.trim(),
|
||||
description: description.trim(),
|
||||
notes: notes.trim(),
|
||||
amount,
|
||||
direction,
|
||||
post_date: parseDate(postDateStr),
|
||||
raw_data: JSON.stringify(record),
|
||||
});
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
const XLSX = require("xlsx");
|
||||
|
||||
function parseCreditFromXLSX(filePath) {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: "",
|
||||
raw: true,
|
||||
});
|
||||
if (!rows || rows.length < 2) return [];
|
||||
const headerRow = rows[0];
|
||||
const dataRows = rows.slice(1).map((row) => {
|
||||
const obj = {};
|
||||
headerRow.forEach((h, i) => {
|
||||
obj[h] = row[i];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
return parseCreditCardCSV(dataRows);
|
||||
}
|
||||
|
||||
module.exports = { parseCreditCardCSV, parseCreditFromXLSX };
|
||||
@@ -59,11 +59,13 @@ function parseSPDBXLS(filePath) {
|
||||
const balance = balanceStr ? parseFloat(balanceStr) : null;
|
||||
|
||||
// 日期/时间解析
|
||||
const parsed = dayjs(dateStr, [
|
||||
let parsed = dayjs(dateStr, [
|
||||
"YYYY/MM/DD HH:mm:ss",
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
"YYYY/MM/DD",
|
||||
]);
|
||||
// UTC → CST (+8h)
|
||||
parsed = parsed.add(8, "hour");
|
||||
const txDate = parsed.format("YYYY-MM-DD");
|
||||
const txTime = parsed.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
|
||||
+41
-220
@@ -1,249 +1,70 @@
|
||||
const express = require("express");
|
||||
const { getDB } = require("../db");
|
||||
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { loadConfig, saveConfig, getOpenAIClient, resetClient } = require('../services/llm');
|
||||
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);
|
||||
// GET /api/config
|
||||
router.get('/', (req, res) => {
|
||||
res.json(loadConfig());
|
||||
});
|
||||
|
||||
// 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));
|
||||
}
|
||||
})();
|
||||
|
||||
// PUT /api/config — 同时存 JSON + 清 LLM 缓存
|
||||
router.put('/', (req, res) => {
|
||||
const cfg = { ...loadConfig(), ...req.body };
|
||||
saveConfig(cfg);
|
||||
resetClient();
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/test-llm - 测试LLM连接(详细调试版)
|
||||
router.post("/test-llm", async (req, res) => {
|
||||
const { getOpenAIClient } = require("../services/llm");
|
||||
// POST /api/config/test-llm
|
||||
router.post('/test-llm', async (req, res) => {
|
||||
console.log('[Reco] === LLM 连接测试 ===');
|
||||
const cfg = loadConfig();
|
||||
console.log(' API Key:', cfg.llm_api_key ? cfg.llm_api_key.substring(0, 8) + '...' : '(无)');
|
||||
console.log(' Base URL:', cfg.llm_base_url || '默认');
|
||||
console.log(' Model:', cfg.llm_model || '默认');
|
||||
|
||||
console.log("[Reco] ========== LLM 连接测试开始 ==========");
|
||||
const client = getOpenAIClient();
|
||||
if (!client) return res.status(400).json({ error: '请先配置 LLM API Key' });
|
||||
|
||||
// 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;
|
||||
const t0 = Date.now();
|
||||
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({
|
||||
const resp = 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,
|
||||
messages: [{ role: 'user', content: '回复"连接成功"' }],
|
||||
max_tokens: 10, timeout: 15000,
|
||||
});
|
||||
const reply = resp.choices?.[0]?.message?.content || '(空)';
|
||||
console.log(` 成功 ${Date.now() - t0}ms: ${reply}`);
|
||||
res.json({ success: true, reply, model: client._model, elapsed_ms: Date.now() - t0 });
|
||||
} 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.error(` 失败 ${Date.now() - t0}ms:`, err.message);
|
||||
res.status(500).json({ error: `连接失败: ${err.message}` });
|
||||
}
|
||||
|
||||
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);
|
||||
// Categories
|
||||
router.get('/categories', (req, res) => {
|
||||
res.json(getDB().prepare('SELECT * FROM categories ORDER BY id').all());
|
||||
});
|
||||
|
||||
// PUT /api/config/categories/:id - 更新分类
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
router.put('/categories/:id', (req, res) => {
|
||||
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);
|
||||
|
||||
getDB().prepare('UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?')
|
||||
.run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/config/categories - 新增分类
|
||||
router.post("/categories", (req, res) => {
|
||||
const db = getDB();
|
||||
router.post('/categories', (req, res) => {
|
||||
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 (?, ?, ?)",
|
||||
)
|
||||
if (!name) return res.status(400).json({ error: '分类名称不能为空' });
|
||||
const r = getDB().prepare('INSERT INTO categories (name,keywords,parent_id) VALUES (?,?,?)')
|
||||
.run(name, JSON.stringify(keywords || []), parent_id || null);
|
||||
|
||||
res.json({ success: true, id: result.lastInsertRowid });
|
||||
res.json({ success: true, id: r.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);
|
||||
router.delete('/categories/:id', (req, res) => {
|
||||
getDB().prepare('DELETE FROM categories WHERE id=?').run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+151
-94
@@ -1,12 +1,12 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../db');
|
||||
const { runAutoReconciliation } = require('../services/matcher');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
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) => {
|
||||
router.get("/", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const {
|
||||
@@ -21,8 +21,8 @@ router.get('/', (req, res) => {
|
||||
min_amount,
|
||||
max_amount,
|
||||
keyword,
|
||||
sort_by = 'transaction_date',
|
||||
sort_order = 'DESC'
|
||||
sort_by = "transaction_date",
|
||||
sort_order = "DESC",
|
||||
} = req.query;
|
||||
|
||||
const offset = (parseInt(page) - 1) * parseInt(limit);
|
||||
@@ -30,171 +30,220 @@ router.get('/', (req, res) => {
|
||||
const params = [];
|
||||
|
||||
if (start_date) {
|
||||
conditions.push('t.transaction_date >= ?');
|
||||
conditions.push("t.transaction_date >= ?");
|
||||
params.push(start_date);
|
||||
}
|
||||
if (end_date) {
|
||||
conditions.push('t.transaction_date <= ?');
|
||||
conditions.push("t.transaction_date <= ?");
|
||||
params.push(end_date);
|
||||
}
|
||||
if (source_type) {
|
||||
conditions.push('t.source_type = ?');
|
||||
conditions.push("t.source_type = ?");
|
||||
params.push(source_type);
|
||||
}
|
||||
if (direction) {
|
||||
conditions.push('t.direction = ?');
|
||||
conditions.push("t.direction = ?");
|
||||
params.push(direction);
|
||||
}
|
||||
if (category) {
|
||||
conditions.push('t.category = ?');
|
||||
conditions.push("t.category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
conditions.push('t.reviewed = ?');
|
||||
conditions.push("t.reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
}
|
||||
if (min_amount) {
|
||||
conditions.push('ABS(t.amount) >= ?');
|
||||
conditions.push("ABS(t.amount) >= ?");
|
||||
params.push(parseFloat(min_amount));
|
||||
}
|
||||
if (max_amount) {
|
||||
conditions.push('ABS(t.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 ?)');
|
||||
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 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 allowedSortFields = [
|
||||
"transaction_time",
|
||||
"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 countResult = db
|
||||
.prepare(`SELECT COUNT(*) as total FROM transactions t ${whereClause}`)
|
||||
.get(...params);
|
||||
|
||||
const transactions = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(...params, parseInt(limit), offset);
|
||||
|
||||
res.json({
|
||||
transactions,
|
||||
total: countResult.total,
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit))
|
||||
totalPages: Math.ceil(countResult.total / parseInt(limit)),
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/needs-classify", (req, res) => {
|
||||
const db = getDB();
|
||||
const validCats = db.prepare('SELECT name FROM categories').all().map(r => r.name);
|
||||
if (validCats.length === 0) return res.json({ ids: [], total: 0 });
|
||||
const ph = validCats.map(() => '?').join(',');
|
||||
const stale = db.prepare(`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`).all(...validCats);
|
||||
res.json({ ids: stale.map(r => r.id), total: stale.length });
|
||||
});
|
||||
|
||||
|
||||
// GET /api/transactions/:id - 获取单笔交易详情
|
||||
router.get('/:id', (req, res) => {
|
||||
router.get("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
|
||||
const tx = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.get(req.params.id);
|
||||
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
// 获取关联的匹配交易
|
||||
let matchedTx = null;
|
||||
if (tx.matched_transaction_id) {
|
||||
matchedTx = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.get(tx.matched_transaction_id);
|
||||
}
|
||||
|
||||
// 获取同一编码的交易(聚合组)
|
||||
const relatedTxs = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(tx.transaction_code, tx.id);
|
||||
|
||||
res.json({ transaction: tx, matchedTransaction: matchedTx, relatedTransactions: relatedTxs });
|
||||
res.json({
|
||||
transaction: tx,
|
||||
matchedTransaction: matchedTx,
|
||||
relatedTransactions: relatedTxs,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/transactions/:id - 更新交易(人工确认/修改分类和描述)
|
||||
router.put('/:id', (req, res) => {
|
||||
router.put("/:id", (req, res) => {
|
||||
const db = getDB();
|
||||
const { category, ai_description, reviewed, review_notes, tags } = req.body;
|
||||
|
||||
const tx = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
const tx = db
|
||||
.prepare("SELECT * FROM transactions WHERE id = ?")
|
||||
.get(req.params.id);
|
||||
if (!tx) {
|
||||
return res.status(404).json({ error: '交易不存在' });
|
||||
return res.status(404).json({ error: "交易不存在" });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (category !== undefined) {
|
||||
updates.push('category = ?');
|
||||
updates.push("category = ?");
|
||||
params.push(category);
|
||||
}
|
||||
if (ai_description !== undefined) {
|
||||
updates.push('ai_description = ?');
|
||||
updates.push("ai_description = ?");
|
||||
params.push(ai_description);
|
||||
}
|
||||
if (reviewed !== undefined) {
|
||||
updates.push('reviewed = ?');
|
||||
updates.push("reviewed = ?");
|
||||
params.push(parseInt(reviewed));
|
||||
if (parseInt(reviewed) === 1) {
|
||||
updates.push('reviewed_at = CURRENT_TIMESTAMP');
|
||||
updates.push("reviewed_at = CURRENT_TIMESTAMP");
|
||||
}
|
||||
}
|
||||
if (review_notes !== undefined) {
|
||||
updates.push('review_notes = ?');
|
||||
updates.push("review_notes = ?");
|
||||
params.push(review_notes);
|
||||
}
|
||||
if (tags !== undefined) {
|
||||
updates.push('tags = ?');
|
||||
updates.push("tags = ?");
|
||||
params.push(JSON.stringify(tags));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return res.status(400).json({ error: '没有提供要更新的字段' });
|
||||
return res.status(400).json({ error: "没有提供要更新的字段" });
|
||||
}
|
||||
|
||||
updates.push('updated_at = CURRENT_TIMESTAMP');
|
||||
updates.push("updated_at = CURRENT_TIMESTAMP");
|
||||
params.push(req.params.id);
|
||||
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
db.prepare(`UPDATE transactions SET ${updates.join(", ")} WHERE id = ?`).run(
|
||||
...params,
|
||||
);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM transactions WHERE id = ?').get(req.params.id);
|
||||
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) => {
|
||||
router.post("/reconcile", (req, res) => {
|
||||
const result = runAutoReconciliation();
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify - 对选中的交易重新分类
|
||||
router.post('/classify', async (req, res) => {
|
||||
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列表' });
|
||||
return res.status(400).json({ error: "请提供要分类的交易ID列表" });
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -205,37 +254,28 @@ router.post('/classify', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/transactions/classify-all - 对所有未分类的交易进行分类
|
||||
router.post('/classify-all', async (req, res) => {
|
||||
// GET /api/transactions/needs-classify
|
||||
// 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();
|
||||
const validCats = db.prepare('SELECT name FROM categories').all().map(r => r.name);
|
||||
if (validCats.length === 0) return res.json({ success: true, classified: 0, message: '无分类配置' });
|
||||
|
||||
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 });
|
||||
const ph = validCats.map(() => '?').join(',');
|
||||
const stale = db.prepare(`SELECT id FROM transactions WHERE category IS NULL OR category NOT IN (${ph})`).all(...validCats);
|
||||
if (stale.length === 0) return res.json({ success: true, classified: 0, total: 0, message: '所有交易分类均有效' });
|
||||
|
||||
const ids = stale.map(r => r.id), batchSize = 50;
|
||||
let classified = 0;
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const r = await classifyTransactions(ids.slice(i, i + batchSize));
|
||||
classified += r.classified;
|
||||
}
|
||||
res.json({ success: true, classified, total: ids.length });
|
||||
});
|
||||
|
||||
// GET /api/transactions/stats/summary - 获取汇总统计
|
||||
router.get('/stats/summary', (req, res) => {
|
||||
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();
|
||||
|
||||
@@ -243,33 +283,50 @@ router.get('/stats/summary', (req, res) => {
|
||||
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); }
|
||||
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 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 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 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 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 unreviewedCount = db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) as total FROM transactions ${where} AND reviewed = 0 AND ABS(amount) >= 100`,
|
||||
)
|
||||
.get(...params);
|
||||
|
||||
const categoryBreakdown = db.prepare(`
|
||||
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);
|
||||
`,
|
||||
)
|
||||
.all(...params);
|
||||
|
||||
res.json({
|
||||
totalIncome: incomeResult.total,
|
||||
@@ -277,7 +334,7 @@ router.get('/stats/summary', (req, res) => {
|
||||
netAmount: incomeResult.total - expenseResult.total,
|
||||
totalCount: countResult.total,
|
||||
unreviewedCount: unreviewedCount.total,
|
||||
categoryBreakdown
|
||||
categoryBreakdown,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+63
-174
@@ -1,228 +1,117 @@
|
||||
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 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 { parseAlipayFile, parseAlipayFromXLSX } = require('../parsers/alipay');
|
||||
const { parseWechatCSV, parseWechatXLSX } = require('../parsers/wechat');
|
||||
const { parseSPDBXLS } = require('../parsers/spdb');
|
||||
const { parseABC } = require('../parsers/abc');
|
||||
const { generateTransactionCode } = require('../utils/transactionCode');
|
||||
const { classifyTransactions } = require('../services/llm');
|
||||
|
||||
const router = express.Router();
|
||||
const uploadDir = path.join(__dirname, "..", "..", "data", "uploads");
|
||||
const uploadDir = path.join(__dirname, '..', '..', 'data', 'uploads');
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
|
||||
|
||||
const ALLOWED_EXTS = [".csv", ".txt", ".xlsx", ".xls"];
|
||||
const ALLOWED_EXTS = ['.csv', '.txt', '.xlsx', '.xls'];
|
||||
const VALID_TYPES = ['alipay', 'wechat', 'bank_debit', 'abc'];
|
||||
|
||||
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),
|
||||
),
|
||||
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 文件格式"));
|
||||
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 },
|
||||
limits: { fileSize: 20 * 1024 * 1024 }
|
||||
});
|
||||
|
||||
router.post("/", upload.single("file"), async (req, res) => {
|
||||
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: "请选择要上传的文件" });
|
||||
if (!VALID_TYPES.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 isExcel = ['.xlsx', '.xls'].includes(fileExt);
|
||||
|
||||
const fileBuffer = fs.readFileSync(req.file.path);
|
||||
const fileHash = crypto.createHash("md5").update(fileBuffer).digest("hex");
|
||||
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) {
|
||||
if (db.prepare('SELECT id FROM sources WHERE file_hash = ?').get(fileHash)) {
|
||||
fs.unlinkSync(req.file.path);
|
||||
return res
|
||||
.status(409)
|
||||
.json({ error: "该文件已导入过", source_id: existing.id });
|
||||
return res.status(409).json({ error: '该文件已导入过' });
|
||||
}
|
||||
|
||||
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;
|
||||
case 'alipay': parsedTransactions = parseAlipayFromXLSX(req.file.path); break;
|
||||
case 'wechat': parsedTransactions = parseWechatXLSX(req.file.path); break;
|
||||
case 'bank_debit': parsedTransactions = parseSPDBXLS(req.file.path); break;
|
||||
case 'abc': parsedTransactions = parseABC(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;
|
||||
// CSV: alipay uses GBK parser, wechat/bank use csv-parse
|
||||
if (source_type === 'alipay') {
|
||||
parsedTransactions = parseAlipayFile(req.file.path);
|
||||
} 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: `解析失败: ${e.message}` }); }
|
||||
if (!records?.length) return res.status(400).json({ error: '无有效记录' });
|
||||
parsedTransactions = parseWechatCSV(records);
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedTransactions?.length)
|
||||
return res.status(400).json({ error: "未能解析出交易记录" });
|
||||
console.log(`[Reco] 解析完成: ${parsedTransactions.length}条`);
|
||||
if (!parsedTransactions?.length) return res.status(400).json({ error: '未能解析出交易记录' });
|
||||
console.log(`[Reco] ${source_type}: ${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 src = db.prepare('INSERT INTO sources (source_type, source_name, file_name, file_hash, record_count) VALUES (?,?,?,?,?)')
|
||||
.run(source_type, source_name || source_type, req.file.originalname, fileHash, parsedTransactions.length);
|
||||
|
||||
const insertTx = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
const ins = db.prepare(`INSERT OR IGNORE INTO transactions (
|
||||
transaction_code, source_id, source_type, transaction_date, transaction_time,
|
||||
counterparty, description, notes, amount, direction, status, method, balance, tags
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);
|
||||
|
||||
const ids = [];
|
||||
let skip = 0;
|
||||
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++;
|
||||
const code = generateTransactionCode(tx.transaction_date, tx.amount, tx.counterparty, tx.description);
|
||||
const r = ins.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) {}
|
||||
}
|
||||
let classifyResult = { classified: 0, source: 'none' };
|
||||
if (ids.length) 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),
|
||||
success: true, source_id: src.lastInsertRowid, source_name: source_name || source_type, source_type,
|
||||
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);
|
||||
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.get('/sources', (req, res) => {
|
||||
res.json(getDB().prepare('SELECT s.*, COUNT(t.id) tx_count FROM sources s LEFT JOIN transactions t ON t.source_id=s.id GROUP BY s.id ORDER BY s.imported_at DESC').all());
|
||||
});
|
||||
|
||||
router.delete("/sources/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM sources WHERE id = ?").run(req.params.id);
|
||||
router.delete('/sources/:id', (req, res) => {
|
||||
getDB().prepare('DELETE FROM sources WHERE id = ?').run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
|
||||
+58
-149
@@ -1,63 +1,54 @@
|
||||
const { getDB } = require("../db");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json');
|
||||
|
||||
/**
|
||||
* LLM 服务:调用大模型对交易进行分类和描述
|
||||
*
|
||||
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
|
||||
* 如果未配置 API Key,使用本地规则进行降级分类
|
||||
*/
|
||||
let openaiClient = null;
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
|
||||
} catch (e) {}
|
||||
return {};
|
||||
}
|
||||
|
||||
function saveConfig(cfg) {
|
||||
const dir = path.dirname(CONFIG_PATH);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
function resetClient() {
|
||||
openaiClient = null;
|
||||
}
|
||||
|
||||
function 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();
|
||||
const cfg = loadConfig();
|
||||
const apiKey = cfg.llm_api_key;
|
||||
const baseURL = cfg.llm_base_url || 'https://api.openai.com/v1';
|
||||
const model = cfg.llm_model || 'gpt-4o-mini';
|
||||
|
||||
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";
|
||||
if (!apiKey) return null;
|
||||
|
||||
const { OpenAI } = require('openai');
|
||||
openaiClient = new OpenAI({ apiKey, baseURL });
|
||||
openaiClient._model = model;
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分类 Prompt
|
||||
*/
|
||||
function buildClassificationPrompt(transactions) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
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");
|
||||
.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");
|
||||
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 `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
@@ -77,148 +68,66 @@ ${txList}
|
||||
仅返回JSON数组,不要包含其他内容。`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分类交易
|
||||
*/
|
||||
async function classifyTransactions(transactionIds) {
|
||||
const { getDB } = require('../db');
|
||||
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);
|
||||
|
||||
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 },
|
||||
{ role: 'system', content: '你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 2000,
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
if (tx) updateStmt.run(item.category, item.description, item.confidence, item.category, tx.id);
|
||||
}
|
||||
})();
|
||||
|
||||
return { classified: results.length, source: "llm" };
|
||||
return { classified: results.length, source: 'llm' };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
|
||||
console.error('[Reco] LLM分类失败,降级规则匹配:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:使用本地关键词规则分类
|
||||
return classifyByRules(transactions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地关键词规则分类(无需LLM)
|
||||
*/
|
||||
function classifyByRules(transactions) {
|
||||
const { getDB } = require('../db');
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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;
|
||||
|
||||
const text = `${tx.description || ''} ${tx.counterparty || ''} ${tx.notes || ''}`.toLowerCase();
|
||||
let bestCategory = '其他杂项', 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;
|
||||
}
|
||||
for (const kw of JSON.parse(cat.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,
|
||||
);
|
||||
|
||||
const desc = tx.direction === 'income'
|
||||
? `收到${tx.counterparty || '对方'} ${Math.abs(tx.amount).toFixed(2)}元`
|
||||
: `向${tx.counterparty || '对方'}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? '(' + tx.description + ')' : ''}`;
|
||||
updateStmt.run(bestCategory, desc.substring(0, 100), bestScore > 0 ? 0.7 : 0.3, bestCategory, tx.id);
|
||||
classified++;
|
||||
if (largeAmount) needsReview++;
|
||||
}
|
||||
|
||||
return { classified, needsReview, source: "rules" };
|
||||
return { classified, source: 'rules' };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient };
|
||||
module.exports = { classifyTransactions, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
|
||||
Reference in New Issue
Block a user