Move category CRUD into the config route so renames sync historical deals, feed per-user categories into the LLM prompt, cache clients per user, and drop the separate classify route.
202 lines
6.2 KiB
JavaScript
202 lines
6.2 KiB
JavaScript
const express = require("express");
|
|
const { getDB } = require("../db");
|
|
const router = express.Router();
|
|
|
|
// 从 DB 读取当前用户的 LLM 配置
|
|
function loadUserLLMConfig(userId) {
|
|
const db = getDB();
|
|
const row = db
|
|
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
|
.get("llm_config", userId);
|
|
return row ? JSON.parse(row.value) : {};
|
|
}
|
|
|
|
// 为当前用户创建 LLM 客户端
|
|
function getUserLLMClient(userId) {
|
|
const cfg = loadUserLLMConfig(userId);
|
|
if (!cfg.llm_api_key) return null;
|
|
const { OpenAI } = require("openai");
|
|
const client = new OpenAI({
|
|
apiKey: cfg.llm_api_key,
|
|
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
|
});
|
|
client._model = cfg.llm_model || "gpt-4o-mini";
|
|
return client;
|
|
}
|
|
|
|
// GET /api/config
|
|
router.get("/", (req, res) => {
|
|
res.json(loadUserLLMConfig(req.userId));
|
|
});
|
|
|
|
// PUT /api/config
|
|
router.put("/", (req, res) => {
|
|
const db = getDB();
|
|
const value = JSON.stringify(req.body);
|
|
|
|
const row = db
|
|
.prepare("SELECT id FROM config WHERE key = ? AND user_id = ?")
|
|
.get("llm_config", req.userId);
|
|
if (row) {
|
|
db.prepare("UPDATE config SET value = ? WHERE id = ?").run(value, row.id);
|
|
} else {
|
|
db.prepare("INSERT INTO config (key, value, user_id) VALUES (?, ?, ?)").run(
|
|
"llm_config",
|
|
value,
|
|
req.userId,
|
|
);
|
|
}
|
|
|
|
res.json({ success: true });
|
|
});
|
|
|
|
// POST /api/config/test-llm
|
|
router.post("/test-llm", async (req, res) => {
|
|
console.log("[Reco] === LLM 连接测试 ===");
|
|
const client = getUserLLMClient(req.userId);
|
|
|
|
if (!client) {
|
|
return res.status(400).json({ error: "请先配置 LLM API Key" });
|
|
}
|
|
|
|
console.log(" Model:", client._model);
|
|
|
|
const t0 = Date.now();
|
|
try {
|
|
const resp = await client.chat.completions.create({
|
|
model: client._model,
|
|
messages: [{ role: "user", content: '回复"连接成功"' }],
|
|
max_tokens: 10,
|
|
timeout: 15000,
|
|
});
|
|
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) {
|
|
console.error(` 失败 ${Date.now() - t0}ms:`, err.message);
|
|
res.status(500).json({ error: `连接失败: ${err.message}` });
|
|
}
|
|
});
|
|
|
|
// Categories
|
|
router.get("/categories", (req, res) => {
|
|
res.json(
|
|
getDB()
|
|
.prepare("SELECT * FROM categories WHERE user_id = ? ORDER BY id")
|
|
.all(req.userId),
|
|
);
|
|
});
|
|
|
|
router.put("/categories/:id", (req, res) => {
|
|
const db = getDB();
|
|
const { name, keywords } = req.body;
|
|
const current = db
|
|
.prepare("SELECT * FROM categories WHERE id = ? AND user_id = ?")
|
|
.get(req.params.id, req.userId);
|
|
if (!current) return res.status(404).json({ error: "分类不存在" });
|
|
if (current.is_locked)
|
|
return res.status(403).json({ error: "内置分类不可修改" });
|
|
|
|
const newName = name === undefined ? current.name : String(name).trim();
|
|
if (!newName) return res.status(400).json({ error: "分类名称不能为空" });
|
|
|
|
const affectedIds = [];
|
|
try {
|
|
db.transaction(() => {
|
|
if (newName !== current.name) {
|
|
const dup = db
|
|
.prepare(
|
|
"SELECT id FROM categories WHERE user_id = ? AND name = ? AND id <> ?",
|
|
)
|
|
.get(req.userId, newName, req.params.id);
|
|
if (dup) {
|
|
const err = new Error("已存在同名分类");
|
|
err.status = 409;
|
|
throw err;
|
|
}
|
|
// 重命名:同步历史 deal 的分类名
|
|
for (const row of db
|
|
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
|
.all(req.userId, current.name))
|
|
affectedIds.push(row.id);
|
|
db.prepare(
|
|
"UPDATE deals SET category = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
|
).run(newName, req.userId, current.name);
|
|
}
|
|
const sets = [];
|
|
const params = [];
|
|
if (newName !== current.name) {
|
|
sets.push("name = ?");
|
|
params.push(newName);
|
|
}
|
|
if (keywords !== undefined) {
|
|
sets.push("keywords = ?");
|
|
params.push(JSON.stringify(Array.isArray(keywords) ? keywords : []));
|
|
}
|
|
if (sets.length) {
|
|
db.prepare(
|
|
`UPDATE categories SET ${sets.join(", ")} WHERE id = ? AND user_id = ?`,
|
|
).run(...params, req.params.id, req.userId);
|
|
}
|
|
})();
|
|
} catch (err) {
|
|
return res
|
|
.status(err.status || 500)
|
|
.json({ error: err.message || "更新失败" });
|
|
}
|
|
|
|
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
|
});
|
|
|
|
router.post("/categories", (req, res) => {
|
|
const db = getDB();
|
|
const { name, keywords } = req.body;
|
|
const trimmed = typeof name === "string" ? name.trim() : "";
|
|
if (!trimmed) return res.status(400).json({ error: "分类名称不能为空" });
|
|
const dup = db
|
|
.prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?")
|
|
.get(req.userId, trimmed);
|
|
if (dup) return res.status(409).json({ error: "已存在同名分类" });
|
|
const r = db
|
|
.prepare(
|
|
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
|
)
|
|
.run(trimmed, JSON.stringify(keywords || []), req.userId);
|
|
res.json({ success: true, id: r.lastInsertRowid });
|
|
});
|
|
|
|
router.delete("/categories/:id", (req, res) => {
|
|
const db = getDB();
|
|
const cat = db
|
|
.prepare("SELECT name, is_locked FROM categories WHERE id = ? AND user_id = ?")
|
|
.get(req.params.id, req.userId);
|
|
if (!cat) return res.status(404).json({ error: "分类不存在" });
|
|
if (cat.is_locked)
|
|
return res.status(403).json({ error: "内置分类不可删除" });
|
|
|
|
const affectedIds = db
|
|
.prepare("SELECT id FROM deals WHERE user_id = ? AND category = ?")
|
|
.all(req.userId, cat.name)
|
|
.map((r) => r.id);
|
|
|
|
db.transaction(() => {
|
|
// 历史 deal 重置为待分类
|
|
db.prepare(
|
|
"UPDATE deals SET category = NULL, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND category = ?",
|
|
).run(req.userId, cat.name);
|
|
db.prepare("DELETE FROM categories WHERE id = ? AND user_id = ?").run(
|
|
req.params.id,
|
|
req.userId,
|
|
);
|
|
})();
|
|
|
|
res.json({ success: true, affectedDeals: affectedIds.length, affectedIds });
|
|
});
|
|
|
|
module.exports = router;
|