Rework LLM classification around user categories
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.
This commit is contained in:
+83
-3
@@ -1,7 +1,11 @@
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
|
||||
const DB_PATH = path.join(__dirname, "..", "data", "reco.db");
|
||||
const DB_PATH =
|
||||
process.env.RECO_DB_PATH || path.join(__dirname, "..", "data", "reco.db");
|
||||
|
||||
// 系统兜底分类:所有用户都不允许修改/删除
|
||||
const SYSTEM_LOCKED_CATEGORIES = ["其他杂项"];
|
||||
|
||||
const fs = require("fs");
|
||||
const dataDir = path.join(__dirname, "..", "data");
|
||||
@@ -68,6 +72,7 @@ function initDB() {
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
keywords TEXT,
|
||||
is_locked INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -186,6 +191,74 @@ function initDB() {
|
||||
console.error("[Reco] config 迁移失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:分类锁定标记。
|
||||
// 内置基础分类(最初的 1-10 号)和系统兜底分类(其他杂项)不允许修改/删除。
|
||||
try {
|
||||
const catCols = database
|
||||
.prepare("PRAGMA table_info(categories)")
|
||||
.all()
|
||||
.map((r) => r.name);
|
||||
if (!catCols.includes("is_locked")) {
|
||||
database.exec(
|
||||
"ALTER TABLE categories ADD COLUMN is_locked INTEGER DEFAULT 0",
|
||||
);
|
||||
}
|
||||
database.prepare("UPDATE categories SET is_locked = 1 WHERE id <= 10").run();
|
||||
if (SYSTEM_LOCKED_CATEGORIES.length) {
|
||||
const ph = SYSTEM_LOCKED_CATEGORIES.map(() => "?").join(",");
|
||||
database
|
||||
.prepare(`UPDATE categories SET is_locked = 1 WHERE name IN (${ph})`)
|
||||
.run(...SYSTEM_LOCKED_CATEGORIES);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类锁定初始化失败:", e.message);
|
||||
}
|
||||
|
||||
// 兼容旧库:合并同名重复分类。
|
||||
// 老用户的历史分类 user_id 为 NULL,之后初始化默认分类时按 user_id 计数为 0,
|
||||
// 于是又插入了一整套默认分类,导致同名分类出现两份。
|
||||
// 合并策略:保留 id 最小的一行(通常是用户手工维护过的),关键词取并集,删除其余行。
|
||||
try {
|
||||
const dupGroups = database
|
||||
.prepare(
|
||||
`SELECT user_id, name, COUNT(*) AS c FROM categories
|
||||
GROUP BY user_id, name HAVING c > 1`,
|
||||
)
|
||||
.all();
|
||||
if (dupGroups.length) {
|
||||
const rowsStmt = database.prepare(
|
||||
"SELECT id, keywords FROM categories WHERE name = ? AND user_id IS ? ORDER BY id",
|
||||
);
|
||||
const setKeywords = database.prepare(
|
||||
"UPDATE categories SET keywords = ? WHERE id = ?",
|
||||
);
|
||||
const delCategory = database.prepare("DELETE FROM categories WHERE id = ?");
|
||||
database.transaction(() => {
|
||||
for (const g of dupGroups) {
|
||||
const rows = rowsStmt.all(g.name, g.user_id);
|
||||
const merged = [];
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const arr = JSON.parse(r.keywords || "[]");
|
||||
if (Array.isArray(arr))
|
||||
for (const k of arr)
|
||||
if (k && !merged.includes(k)) merged.push(k);
|
||||
} catch (e) {}
|
||||
}
|
||||
setKeywords.run(JSON.stringify(merged), rows[0].id);
|
||||
for (const r of rows.slice(1)) delCategory.run(r.id);
|
||||
}
|
||||
})();
|
||||
console.log(`[Reco] 已合并 ${dupGroups.length} 组重复分类`);
|
||||
}
|
||||
// 唯一索引:同一用户下不允许同名分类
|
||||
database.exec(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_categories_user_name ON categories(user_id, name)",
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("[Reco] 分类去重失败:", e.message);
|
||||
}
|
||||
|
||||
console.log("[Reco] 数据库初始化完成");
|
||||
}
|
||||
|
||||
@@ -198,7 +271,7 @@ function initDefaultCategories(userId) {
|
||||
if (existing > 0) return;
|
||||
|
||||
const ins = database.prepare(
|
||||
"INSERT INTO categories (name, keywords, user_id) VALUES (?, ?, ?)",
|
||||
"INSERT OR IGNORE INTO categories (name, keywords, user_id, is_locked) VALUES (?, ?, ?, ?)",
|
||||
);
|
||||
const defaults = [
|
||||
["餐饮美食", '["餐厅","外卖","食堂","咖啡","奶茶","零食","水果","买菜"]'],
|
||||
@@ -222,7 +295,14 @@ function initDefaultCategories(userId) {
|
||||
["其他杂项", "[]"],
|
||||
];
|
||||
database.transaction(() => {
|
||||
defaults.forEach((c) => ins.run(c[0], c[1], userId));
|
||||
defaults.forEach((c) =>
|
||||
ins.run(
|
||||
c[0],
|
||||
c[1],
|
||||
userId,
|
||||
SYSTEM_LOCKED_CATEGORIES.includes(c[0]) ? 1 : 0,
|
||||
),
|
||||
);
|
||||
})();
|
||||
console.log(`[Reco] 已为用户 ${userId} 初始化默认分类`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user