Add reclassifyAffected API and improve category management UX
This commit is contained in:
@@ -120,7 +120,10 @@ export async function getOverview(params = {}) {
|
||||
}
|
||||
|
||||
export async function getMonthly(months = 12, categories) {
|
||||
const params = { months }; if (categories && categories.length > 0) params.categories = categories.join(","); const res = await api.get("/stats/monthly", { params });
|
||||
const params = { months };
|
||||
if (categories && categories.length > 0)
|
||||
params.categories = categories.join(",");
|
||||
const res = await api.get("/stats/monthly", { params });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@@ -162,6 +165,14 @@ export async function updateCategory(id, data) {
|
||||
const res = await api.put(`/config/categories/${id}`, data);
|
||||
return res.data;
|
||||
}
|
||||
export async function reclassifyAffected(ids) {
|
||||
const res = await api.post(
|
||||
"/config/categories/reclassify-affected",
|
||||
{ ids },
|
||||
{ timeout: 300000 },
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export function formatAmount(amount) {
|
||||
if (amount === null || amount === undefined) return "--";
|
||||
|
||||
@@ -191,7 +191,7 @@ export default function Review() {
|
||||
{deal.category}
|
||||
</span>
|
||||
)}
|
||||
{deal.reviewed && (
|
||||
{deal.reviewed === 1 && (
|
||||
<span style={{ marginLeft: 6, color: "var(--success)" }}>
|
||||
✓ 已确认
|
||||
</span>
|
||||
|
||||
+395
-52
@@ -1,64 +1,223 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw, X } from 'lucide-react';
|
||||
import { getConfig, updateConfig, testLLM, getCategories, updateCategory, createCategory, deleteCategory } from '../hooks/useApi';
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Save, Zap, Plus, Trash2, RefreshCw, X } from "lucide-react";
|
||||
import {
|
||||
getConfig,
|
||||
updateConfig,
|
||||
testLLM,
|
||||
getCategories,
|
||||
updateCategory,
|
||||
createCategory,
|
||||
deleteCategory,
|
||||
reclassifyAffected,
|
||||
} from "../hooks/useApi";
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [config, setConfig] = useState({ llm_api_key: '', llm_base_url: 'https://api.openai.com/v1', llm_model: 'gpt-4o-mini' });
|
||||
const [config, setConfig] = useState({
|
||||
llm_api_key: "",
|
||||
llm_base_url: "https://api.openai.com/v1",
|
||||
llm_model: "gpt-4o-mini",
|
||||
});
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [llmStatus, setLLMStatus] = useState(null);
|
||||
const [testingLlm, setTestingLlm] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editingCat, setEditingCat] = useState(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [newCat, setNewCat] = useState({ name: '', keywords: '' });
|
||||
const [newCat, setNewCat] = useState({ name: "", keywords: "" });
|
||||
const [reclassifying, setReclassifying] = useState(false);
|
||||
const [reclassifyMsg, setReclassifyMsg] = useState(null);
|
||||
|
||||
useEffect(() => { loadAll(); }, []);
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
|
||||
async function loadAll() {
|
||||
try { const [cfg, cats] = await Promise.all([getConfig(), getCategories()]); setConfig(prev => ({ ...prev, ...cfg })); setCategories(cats); } catch (err) {}
|
||||
try {
|
||||
const [cfg, cats] = await Promise.all([getConfig(), getCategories()]);
|
||||
setConfig((prev) => ({ ...prev, ...cfg }));
|
||||
setCategories(cats);
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleSaveConfig() { setSaving(true); try { await updateConfig(config); alert('保存成功!'); } catch (err) {} setSaving(false); }
|
||||
async function handleSaveConfig() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateConfig(config);
|
||||
alert("保存成功!");
|
||||
} catch (err) {}
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
async function handleTestLLM() {
|
||||
setTestingLlm(true); setLLMStatus(null);
|
||||
setTestingLlm(true);
|
||||
setLLMStatus(null);
|
||||
await updateConfig(config);
|
||||
try { const r = await testLLM(); setLLMStatus({ success: true, message: `连接成功!模型: ${r.model}, 回复: ${r.reply}` }); }
|
||||
catch (err) { setLLMStatus({ success: false, message: err.response?.data?.error || err.message }); }
|
||||
try {
|
||||
const r = await testLLM();
|
||||
setLLMStatus({
|
||||
success: true,
|
||||
message: `连接成功!模型: ${r.model}, 回复: ${r.reply}`,
|
||||
});
|
||||
} catch (err) {
|
||||
setLLMStatus({
|
||||
success: false,
|
||||
message: err.response?.data?.error || err.message,
|
||||
});
|
||||
}
|
||||
setTestingLlm(false);
|
||||
}
|
||||
|
||||
async function handleUpdateCategory(id, field, value) { try { await updateCategory(id, { [field]: value }); loadAll(); } catch (err) {} }
|
||||
async function handleUpdateCategory(id, field, value) {
|
||||
try {
|
||||
const result = await updateCategory(id, { [field]: value });
|
||||
loadAll();
|
||||
if (result.affectedDeals > 0) {
|
||||
setReclassifyMsg({
|
||||
type: "info",
|
||||
text: `分类名称已更新,${result.affectedDeals} 条历史交易记录已自动同步新名称。`,
|
||||
});
|
||||
setTimeout(() => setReclassifyMsg(null), 6000);
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleAddCategory() {
|
||||
if (!newCat.name.trim()) return;
|
||||
try {
|
||||
await createCategory({ name: newCat.name.trim(), keywords: newCat.keywords.split(',').map(k => k.trim()).filter(Boolean) });
|
||||
setNewCat({ name: '', keywords: '' }); setAdding(false); loadAll();
|
||||
await createCategory({
|
||||
name: newCat.name.trim(),
|
||||
keywords: newCat.keywords
|
||||
.split(",")
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
setNewCat({ name: "", keywords: "" });
|
||||
setAdding(false);
|
||||
loadAll();
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleDeleteCategory(id, name) {
|
||||
if (!window.confirm(`确定删除分类「${name}」吗?`)) return;
|
||||
try { await deleteCategory(id); loadAll(); } catch (err) {}
|
||||
if (
|
||||
!window.confirm(
|
||||
`确定删除分类「${name}」吗?\n\n删除后,使用该分类的历史交易将标记为"待分类",可重新进行AI分类。`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
const result = await deleteCategory(id);
|
||||
loadAll();
|
||||
if (result.affectedDeals > 0) {
|
||||
const ids = result.affectedIds || [];
|
||||
setReclassifyMsg({
|
||||
type: "warning",
|
||||
text: `已删除「${name}」,${result.affectedDeals} 条历史交易(${ids.length} 笔deal)已重置为待分类状态。`,
|
||||
ids,
|
||||
});
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
async function handleReclassify(ids) {
|
||||
setReclassifying(true);
|
||||
setReclassifyMsg(null);
|
||||
try {
|
||||
const result = await reclassifyAffected(ids);
|
||||
setReclassifyMsg({
|
||||
type: "success",
|
||||
text: `重分类完成!${result.classified} 条交易已重新分类(来源: ${result.source === "llm" ? "AI" : "规则匹配"})。`,
|
||||
});
|
||||
loadAll();
|
||||
} catch (err) {
|
||||
setReclassifyMsg({
|
||||
type: "error",
|
||||
text: "重分类失败: " + (err.response?.data?.error || err.message),
|
||||
});
|
||||
}
|
||||
setReclassifying(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header"><h2>⚙️ 系统设置</h2><p>配置大模型API及管理交易分类</p></div>
|
||||
<div className="page-header">
|
||||
<h2>⚙️ 系统设置</h2>
|
||||
<p>配置大模型API及管理交易分类</p>
|
||||
</div>
|
||||
|
||||
{/* LLM Config */}
|
||||
<div className="card">
|
||||
<div className="card-header"><h3>🤖 大模型配置</h3><span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>支持 OpenAI 兼容API</span></div>
|
||||
<div className="form-group"><label>API Key</label><input type="password" className="form-input" placeholder="sk-..." value={config.llm_api_key || ''} onChange={e => setConfig({ ...config, llm_api_key: e.target.value })} /></div>
|
||||
<div className="form-group"><label>API Base URL</label><input type="text" className="form-input" placeholder="https://api.openai.com/v1" value={config.llm_base_url || ''} onChange={e => setConfig({ ...config, llm_base_url: e.target.value })} /></div>
|
||||
<div className="form-group"><label>模型名称</label><input type="text" className="form-input" placeholder="gpt-4o-mini" value={config.llm_model || ''} onChange={e => setConfig({ ...config, llm_model: e.target.value })} /></div>
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<button className="btn btn-primary" onClick={handleSaveConfig} disabled={saving}><Save size={16} /> {saving ? '保存中...' : '保存配置'}</button>
|
||||
<button className="btn btn-secondary" onClick={handleTestLLM} disabled={testingLlm}><Zap size={16} /> {testingLlm ? '测试中...' : '测试连接'}</button>
|
||||
<div className="card-header">
|
||||
<h3>🤖 大模型配置</h3>
|
||||
<span style={{ fontSize: 12, color: "var(--text-secondary)" }}>
|
||||
支持 OpenAI 兼容API
|
||||
</span>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>API Key</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
placeholder="sk-..."
|
||||
value={config.llm_api_key || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_api_key: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>API Base URL</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
value={config.llm_base_url || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_base_url: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>模型名称</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="gpt-4o-mini"
|
||||
value={config.llm_model || ""}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, llm_model: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 10 }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleSaveConfig}
|
||||
disabled={saving}
|
||||
>
|
||||
<Save size={16} /> {saving ? "保存中..." : "保存配置"}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={handleTestLLM}
|
||||
disabled={testingLlm}
|
||||
>
|
||||
<Zap size={16} /> {testingLlm ? "测试中..." : "测试连接"}
|
||||
</button>
|
||||
</div>
|
||||
{llmStatus && (
|
||||
<div style={{ marginTop: 16, padding: '12px 16px', borderRadius: 8, fontSize: 14, background: llmStatus.success ? '#f0fdf4' : '#fef2f2', color: llmStatus.success ? 'var(--success)' : 'var(--danger)', border: `1px solid ${llmStatus.success ? '#bbf7d0' : '#fecaca'}` }}>{llmStatus.message}</div>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
padding: "12px 16px",
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
background: llmStatus.success ? "#f0fdf4" : "#fef2f2",
|
||||
color: llmStatus.success ? "var(--success)" : "var(--danger)",
|
||||
border: `1px solid ${llmStatus.success ? "#bbf7d0" : "#fecaca"}`,
|
||||
}}
|
||||
>
|
||||
{llmStatus.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -66,53 +225,237 @@ export default function SettingsPage() {
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3>🏷️ 分类管理</h3>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => setAdding(true)}><Plus size={14} /> 新增</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}><RefreshCw size={14} /> 刷新</button>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => setAdding(true)}
|
||||
>
|
||||
<Plus size={14} /> 新增
|
||||
</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={loadAll}>
|
||||
<RefreshCw size={14} /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>管理交易分类及关键词,AI 根据关键词自动分类</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 13,
|
||||
color: "var(--text-secondary)",
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
管理交易分类及关键词,AI 根据关键词自动分类。
|
||||
<br />
|
||||
重命名分类会自动同步历史数据;删除分类后历史交易将标记为待分类。
|
||||
</div>
|
||||
|
||||
{/* Reclassify notification */}
|
||||
{reclassifyMsg && (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: "12px 16px",
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
background:
|
||||
reclassifyMsg.type === "success"
|
||||
? "#f0fdf4"
|
||||
: reclassifyMsg.type === "warning"
|
||||
? "#fffbeb"
|
||||
: reclassifyMsg.type === "error"
|
||||
? "#fef2f2"
|
||||
: "#eff6ff",
|
||||
color:
|
||||
reclassifyMsg.type === "success"
|
||||
? "var(--success)"
|
||||
: reclassifyMsg.type === "warning"
|
||||
? "#92400e"
|
||||
: reclassifyMsg.type === "error"
|
||||
? "var(--danger)"
|
||||
: "var(--text-primary)",
|
||||
border: `1px solid ${reclassifyMsg.type === "success" ? "#bbf7d0" : reclassifyMsg.type === "warning" ? "#fde68a" : reclassifyMsg.type === "error" ? "#fecaca" : "#bfdbfe"}`,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<span>{reclassifyMsg.text}</span>
|
||||
{reclassifyMsg.ids && reclassifyMsg.ids.length > 0 && (
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => handleReclassify(reclassifyMsg.ids)}
|
||||
disabled={reclassifying}
|
||||
style={{ whiteSpace: "nowrap" }}
|
||||
>
|
||||
<Zap size={12} /> {reclassifying ? "重分类中..." : "立即重分类"}
|
||||
</button>
|
||||
)}
|
||||
{!reclassifyMsg.ids && (
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => setReclassifyMsg(null)}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New category inline form */}
|
||||
{adding && (
|
||||
<div style={{ display: 'flex', gap: 10, marginBottom: 12, padding: '10px 12px', background: 'var(--primary-bg)', borderRadius: 8, alignItems: 'center' }}>
|
||||
<input type="text" className="form-input" style={{ width: 130 }} placeholder="分类名称" value={newCat.name} onChange={e => setNewCat({ ...newCat, name: e.target.value })} />
|
||||
<input type="text" className="form-input" style={{ flex: 1 }} placeholder="关键词,逗号,分隔" value={newCat.keywords} onChange={e => setNewCat({ ...newCat, keywords: e.target.value })} />
|
||||
<button className="btn btn-primary btn-sm" onClick={handleAddCategory}><Plus size={12} /> 添加</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => { setAdding(false); setNewCat({ name: '', keywords: '' }); }}><X size={12} /></button>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: 10,
|
||||
marginBottom: 12,
|
||||
padding: "10px 12px",
|
||||
background: "var(--primary-bg)",
|
||||
borderRadius: 8,
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: 130 }}
|
||||
placeholder="分类名称"
|
||||
value={newCat.name}
|
||||
onChange={(e) => setNewCat({ ...newCat, name: e.target.value })}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ flex: 1 }}
|
||||
placeholder="关键词,逗号,分隔"
|
||||
value={newCat.keywords}
|
||||
onChange={(e) =>
|
||||
setNewCat({ ...newCat, keywords: e.target.value })
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={handleAddCategory}
|
||||
>
|
||||
<Plus size={12} /> 添加
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => {
|
||||
setAdding(false);
|
||||
setNewCat({ name: "", keywords: "" });
|
||||
}}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="table-container">
|
||||
<table>
|
||||
<thead><tr><th style={{ width: 50 }}>ID</th><th>分类名称</th><th>关键词</th><th style={{ width: 160 }}>操作</th></tr></thead>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 50 }}>ID</th>
|
||||
<th>分类名称</th>
|
||||
<th>关键词</th>
|
||||
<th style={{ width: 160 }}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categories.map(cat => (
|
||||
{categories.map((cat) => (
|
||||
<tr key={cat.id}>
|
||||
<td>{cat.id}</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: 120 }} value={editingCat.name} onChange={e => setEditingCat({ ...editingCat, name: e.target.value })} />
|
||||
: <strong>{cat.name}</strong>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id
|
||||
? <input type="text" className="form-input" style={{ width: '100%' }} value={editingCat.keywords} onChange={e => setEditingCat({ ...editingCat, keywords: e.target.value })} />
|
||||
: <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{JSON.parse(cat.keywords || '[]').join(', ') || '(无)'}</span>
|
||||
}
|
||||
{editingCat?.id === cat.id ? (
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: 120 }}
|
||||
value={editingCat.name}
|
||||
onChange={(e) =>
|
||||
setEditingCat({ ...editingCat, name: e.target.value })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<strong>{cat.name}</strong>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-primary btn-sm" onClick={async () => { await handleUpdateCategory(cat.id, 'name', editingCat.name); await handleUpdateCategory(cat.id, 'keywords', editingCat.keywords.split(',').map(k => k.trim()).filter(Boolean)); setEditingCat(null); }}><Save size={12} /> 保存</button>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat(null)}>取消</button>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: "100%" }}
|
||||
value={editingCat.keywords}
|
||||
onChange={(e) =>
|
||||
setEditingCat({
|
||||
...editingCat,
|
||||
keywords: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
style={{ fontSize: 12, color: "var(--text-secondary)" }}
|
||||
>
|
||||
{JSON.parse(cat.keywords || "[]").join(", ") ||
|
||||
"(无)"}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingCat?.id === cat.id ? (
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={async () => {
|
||||
await handleUpdateCategory(
|
||||
cat.id,
|
||||
"name",
|
||||
editingCat.name,
|
||||
);
|
||||
await handleUpdateCategory(
|
||||
cat.id,
|
||||
"keywords",
|
||||
editingCat.keywords
|
||||
.split(",")
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
setEditingCat(null);
|
||||
}}
|
||||
>
|
||||
<Save size={12} /> 保存
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
onClick={() => setEditingCat(null)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditingCat({ ...cat, keywords: JSON.parse(cat.keywords || '[]').join(', ') })}>编辑</button>
|
||||
<button className="btn btn-danger btn-sm" onClick={() => handleDeleteCategory(cat.id, cat.name)}><Trash2 size={12} /></button>
|
||||
<div style={{ display: "flex", gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-secondary btn-sm"
|
||||
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>
|
||||
|
||||
+88
-8
@@ -64,12 +64,34 @@ router.get("/categories", (req, res) => {
|
||||
|
||||
router.put("/categories/:id", (req, res) => {
|
||||
const { name, keywords } = req.body;
|
||||
getDB()
|
||||
.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?",
|
||||
)
|
||||
.run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
res.json({ success: true });
|
||||
const db = getDB();
|
||||
|
||||
// 获取旧名称,用于级联更新 deals
|
||||
const oldCat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const oldName = oldCat?.name;
|
||||
|
||||
db.prepare(
|
||||
"UPDATE categories SET name=COALESCE(?,name), keywords=COALESCE(?,keywords) WHERE id=?",
|
||||
).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id);
|
||||
|
||||
// 如果名称变更,级联更新 deals 中的分类名
|
||||
let affectedDeals = 0;
|
||||
if (name && oldName && name !== oldName) {
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=? WHERE category=?")
|
||||
.run(name, oldName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=? WHERE ai_category=?")
|
||||
.run(name, oldName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
console.log(
|
||||
`[Reco] 分类重命名: "${oldName}" -> "${name}", 影响 ${affectedDeals} 条 deal`,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true, affectedDeals });
|
||||
});
|
||||
|
||||
router.post("/categories", (req, res) => {
|
||||
@@ -82,8 +104,66 @@ router.post("/categories", (req, res) => {
|
||||
});
|
||||
|
||||
router.delete("/categories/:id", (req, res) => {
|
||||
getDB().prepare("DELETE FROM categories WHERE id=?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
const db = getDB();
|
||||
|
||||
// 获取分类名,用于清理 deals 引用
|
||||
const cat = db
|
||||
.prepare("SELECT name FROM categories WHERE id=?")
|
||||
.get(req.params.id);
|
||||
const catName = cat?.name;
|
||||
|
||||
// 删除分类
|
||||
db.prepare("DELETE FROM categories WHERE id=?").run(req.params.id);
|
||||
|
||||
// 将使用该分类的 deals 置为待重分类状态
|
||||
let affectedDeals = 0;
|
||||
const affectedIds = [];
|
||||
if (catName) {
|
||||
const deals1 = db
|
||||
.prepare("SELECT id FROM deals WHERE category=?")
|
||||
.all(catName);
|
||||
const deals2 = db
|
||||
.prepare("SELECT id FROM deals WHERE ai_category=? AND category!=?")
|
||||
.all(catName, catName);
|
||||
const r1 = db
|
||||
.prepare("UPDATE deals SET category=NULL WHERE category=?")
|
||||
.run(catName);
|
||||
const r2 = db
|
||||
.prepare("UPDATE deals SET ai_category=NULL WHERE ai_category=?")
|
||||
.run(catName);
|
||||
affectedDeals = r1.changes + r2.changes;
|
||||
// 收集受影响的 deal ID(去重)
|
||||
const idSet = new Set();
|
||||
for (const d of deals1) idSet.add(d.id);
|
||||
for (const d of deals2) idSet.add(d.id);
|
||||
for (const id of idSet) affectedIds.push(id);
|
||||
console.log(
|
||||
`[Reco] 删除分类: "${catName}", 影响 ${affectedDeals} 条 deal (${affectedIds.length} 条唯一 deal)`,
|
||||
);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
affectedDeals,
|
||||
affectedIds,
|
||||
categoryName: catName,
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/config/categories/reclassify-affected — 重分类受影响的 deals
|
||||
router.post("/categories/reclassify-affected", async (req, res) => {
|
||||
const { ids } = req.body;
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ error: "请提供deal ID列表" });
|
||||
}
|
||||
try {
|
||||
const { classifyDeals } = require("../services/llm");
|
||||
const result = await classifyDeals(ids);
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
console.error("[Reco] 重分类失败:", err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user