Add user authentication with JWT login and registration

This commit is contained in:
2026-05-16 19:27:04 +08:00
parent 27a170ec0c
commit 99837bea9a
22 changed files with 1219 additions and 474 deletions
+46 -114
View File
@@ -1,54 +1,39 @@
const fs = require("fs");
const path = require("path");
const CONFIG_PATH = path.join(__dirname, "..", "..", "data", "llm_config.json");
const BATCH_SIZE = 30; // 每批发送给 LLM 的 deal 数量
const CONCURRENCY = 5; // 并行调用 LLM 的最大并发数
let openaiClient = null;
const BATCH_SIZE = 30;
const CONCURRENCY = 5;
/* ============================== 配置管理 ============================== */
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 loadUserLLMConfig(userId) {
const { getDB } = require("../db");
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) : {};
}
function getOpenAIClient() {
if (openaiClient) return openaiClient;
const cfg = loadConfig();
function getOpenAIClient(userId) {
const cfg = loadUserLLMConfig(userId);
if (!cfg.llm_api_key) {
console.log("[Reco] LLM 未配置 API Key");
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
return null;
}
const { OpenAI } = require("openai");
openaiClient = new OpenAI({
const client = new OpenAI({
apiKey: cfg.llm_api_key,
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
});
openaiClient._model = cfg.llm_model || "gpt-4o-mini";
console.log(
`[Reco] LLM 客户端已初始化 — 模型: ${openaiClient._model}, BaseURL: ${cfg.llm_base_url || "默认"}`,
);
return openaiClient;
client._model = cfg.llm_model || "gpt-4o-mini";
return client;
}
/* ============================== Prompt 构建 ============================== */
function buildPrompt(deals) {
function buildPrompt(deals, userId) {
const { getDB } = require("../db");
const db = getDB();
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
const cats = db
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
.all(userId);
const catList = cats
.map(
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
@@ -58,7 +43,6 @@ function buildPrompt(deals) {
let txTotal = 0;
const dealList = deals
.map((d, i) => {
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
const txs = db
.prepare(
`
@@ -126,12 +110,10 @@ ${dealList}
/* ============================== JSON 提取 ============================== */
function extractJsonArray(text) {
if (!text) return null;
// 先尝试直接解析
try {
const r = JSON.parse(text);
if (Array.isArray(r)) return r;
} catch (e) {}
// 找到第一个 [ 和最后一个 ]
const start = text.indexOf("[");
const end = text.lastIndexOf("]");
if (start === -1 || end === -1 || start >= end) return null;
@@ -142,28 +124,27 @@ function extractJsonArray(text) {
}
/* ============================== 单批 LLM 分类 ============================== */
async function classifyDeals(dealIds) {
async function classifyDeals(dealIds, userId) {
const { getDB } = require("../db");
const db = getDB();
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
if (ids.length === 0) return { classified: 0 };
console.log(`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID`);
console.log(
`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID (userId=${userId})`,
);
const deals = db
.prepare(
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")}) AND user_id = ?`,
)
.all(...ids);
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
.all(...ids, userId);
if (!deals.length) return { classified: 0 };
const client = getOpenAIClient();
const client = getOpenAIClient(userId);
if (client) {
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
try {
const prompt = buildPrompt(deals);
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
const prompt = buildPrompt(deals, userId);
const t0 = Date.now();
const response = await client.chat.completions.create({
model: client._model,
@@ -178,31 +159,20 @@ async function classifyDeals(dealIds) {
temperature: 0.3,
max_tokens: 4000,
});
const elapsed = Date.now() - t0;
console.log(
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
);
const rawContent = response.choices[0]?.message?.content || "";
console.log(
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
);
const results = extractJsonArray(rawContent);
console.log(
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
);
if (results && results.length > 0) {
const upd = db.prepare(
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
);
const t1 = Date.now();
db.transaction(() => {
for (const item of results) {
const d = deals[item.index - 1];
if (d && item.category) {
upd.run(
item.category,
item.description || "",
item.confidence || 0.8,
item.category,
@@ -212,34 +182,29 @@ async function classifyDeals(dealIds) {
}
})();
console.log(
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
);
return { classified: results.length, source: "llm" };
}
console.log(`[Reco] classifyDeals — JSON解析为空,降级到规则匹配 ⚠️`);
} catch (e) {
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
}
} else {
console.log(`[Reco] classifyDeals — 未配置LLM,使用规则匹配`);
}
// LLM 不可用或失败 → 降级为规则匹配
return classifyDealsByRules(deals);
return classifyDealsByRules(deals, userId);
}
/* ============================== 规则兜底分类 ============================== */
function classifyDealsByRules(deals) {
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
function classifyDealsByRules(deals, userId) {
const { getDB } = require("../db");
const db = getDB();
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
const cats = db
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
.all(userId);
const upd = db.prepare(
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
);
const t0 = Date.now();
// 包裹在事务中批量更新
db.transaction(() => {
for (const d of deals) {
const text = (d.description + " " + d.counterparty).toLowerCase();
@@ -263,94 +228,64 @@ function classifyDealsByRules(deals) {
actionText +
Math.abs(d.amount).toFixed(2) +
"元";
upd.run(desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
}
})();
console.log(
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
);
return { classified: deals.length, source: "rules" };
}
/* ============================== AI分类全部(并行) ============================== */
async function classifyAllDeals() {
async function classifyAllDeals(userId) {
const { getDB } = require("../db");
const db = getDB();
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
// 1. 取出全部未分类或分类已过时的 deal
const cats = db
.prepare("SELECT name FROM categories")
.all()
.prepare("SELECT name FROM categories WHERE user_id = ?")
.all(userId)
.map((r) => r.name);
console.log(
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
);
if (!cats.length) {
console.log(`[Reco] classifyAllDeals — 无分类,退出`);
return { classified: 0, total: 0, source: "none" };
}
const ph = cats.map(() => "?").join(",");
const stale = db
.prepare(
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
`SELECT id FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
)
.all(...cats);
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
.all(...cats, userId);
if (!stale.length) {
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
return { classified: 0, total: 0, source: "none" };
}
const ids = stale.map((r) => r.id);
// 2. 分批
const batches = [];
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
batches.push(ids.slice(i, i + BATCH_SIZE));
}
console.log(
`[Reco] classifyAllDeals — 共 ${batches.length} 批 (每批≤${BATCH_SIZE}条), 最大并发 ${CONCURRENCY}`,
);
// 3. 并行处理(带并发限制)
let totalClassified = 0;
let source = "rules";
const tStart = Date.now();
let round = 0;
for (let i = 0; i < batches.length; i += CONCURRENCY) {
round++;
const chunk = batches.slice(i, i + CONCURRENCY);
const from = i + 1;
const to = Math.min(i + CONCURRENCY, batches.length);
console.log(
`[Reco] classifyAllDeals — 第 ${round} 轮: 并行处理第 ${from}-${to} 批 (共 ${chunk.length} 批)`,
const results = await Promise.all(
chunk.map((b) => classifyDeals(b, userId)),
);
const tRound = Date.now();
const results = await Promise.all(chunk.map((b) => classifyDeals(b)));
const roundElapsed = Date.now() - tRound;
for (const r of results) {
totalClassified += r.classified;
if (r.source === "llm") source = "llm";
}
console.log(
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
);
}
const totalElapsed = Date.now() - tStart;
console.log(
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
);
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
return { classified: totalClassified, total: ids.length, source };
}
@@ -359,7 +294,4 @@ module.exports = {
classifyDeals,
classifyAllDeals,
getOpenAIClient,
loadConfig,
saveConfig,
resetClient,
};