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,
};
+51 -37
View File
@@ -1,4 +1,4 @@
const { getDB } = require('../db');
const { getDB } = require("../db");
/**
* 交易匹配服务
@@ -13,7 +13,7 @@ const { getDB } = require('../db');
* 2. 日期相近(±1天) + 相同金额 + 描述相似
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
*/
function findMatches(newTransaction) {
function findMatches(newTransaction, userId) {
const db = getDB();
const absAmount = Math.abs(newTransaction.amount);
@@ -21,25 +21,31 @@ function findMatches(newTransaction) {
// 只匹配金额 > 0.01 的交易
if (absAmount < 0.01) return [];
const candidates = db.prepare(`
const candidates = db
.prepare(
`
SELECT id, transaction_code, transaction_date, amount, counterparty,
description, source_type, direction, category
FROM transactions
WHERE id != ?
AND source_id != ?
AND user_id = ?
AND reviewed = 0
AND ABS(ABS(amount) - ?) <= 1.0
AND transaction_date BETWEEN DATE(?, '-2 days') AND DATE(?, '+2 days')
ORDER BY ABS(julianday(transaction_date) - julianday(?)) ASC
LIMIT 20
`).all(
newTransaction.id || -1,
newTransaction.source_id || -1,
absAmount,
newTransaction.transaction_date,
newTransaction.transaction_date,
newTransaction.transaction_date
);
`,
)
.all(
newTransaction.id || -1,
newTransaction.source_id || -1,
userId,
absAmount,
newTransaction.transaction_date,
newTransaction.transaction_date,
newTransaction.transaction_date,
);
if (candidates.length === 0) return [];
@@ -53,66 +59,70 @@ function findMatches(newTransaction) {
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
if (amountDiff < 0.01) {
score += 40;
reasons.push('金额完全一致');
reasons.push("金额完全一致");
} else if (amountDiff < 0.1) {
score += 35;
reasons.push('金额基本一致');
reasons.push("金额基本一致");
} else if (amountDiff < 1.0) {
score += 20;
reasons.push('金额接近');
reasons.push("金额接近");
}
// 日期得分
const dateDiff = Math.abs(
new Date(candidate.transaction_date) - new Date(newTransaction.transaction_date)
) / (1000 * 60 * 60 * 24);
const dateDiff =
Math.abs(
new Date(candidate.transaction_date) -
new Date(newTransaction.transaction_date),
) /
(1000 * 60 * 60 * 24);
if (dateDiff < 0.01) {
score += 30;
reasons.push('日期相同');
reasons.push("日期相同");
} else if (dateDiff <= 1) {
score += 20;
reasons.push('日期差1天');
reasons.push("日期差1天");
} else if (dateDiff <= 2) {
score += 10;
reasons.push('日期差2天');
reasons.push("日期差2天");
}
// 对方名称相似度
const nameSim = stringSimilarity(
(candidate.counterparty || '').toLowerCase(),
(newTransaction.counterparty || '').toLowerCase()
(candidate.counterparty || "").toLowerCase(),
(newTransaction.counterparty || "").toLowerCase(),
);
if (nameSim > 0.8) {
score += 20;
reasons.push('对方名称高度相似');
reasons.push("对方名称高度相似");
} else if (nameSim > 0.5) {
score += 10;
reasons.push('对方名称部分相似');
reasons.push("对方名称部分相似");
}
// 描述相似度
const descSim = stringSimilarity(
(candidate.description || '').toLowerCase(),
(newTransaction.description || '').toLowerCase()
(candidate.description || "").toLowerCase(),
(newTransaction.description || "").toLowerCase(),
);
if (descSim > 0.7) {
score += 10;
reasons.push('描述相似');
reasons.push("描述相似");
}
// 方向互补(一个支出一个收入,说明是转账匹配)
if (candidate.direction !== newTransaction.direction) {
score += 5;
reasons.push('收支方向互补');
reasons.push("收支方向互补");
}
if (score >= 40) { // 最低匹配阈值
if (score >= 40) {
// 最低匹配阈值
matches.push({
transaction_id: candidate.id,
match_score: Math.min(score, 100) / 100,
reasons: reasons.join(';'),
candidate
reasons: reasons.join(";"),
candidate,
});
}
}
@@ -124,17 +134,21 @@ function findMatches(newTransaction) {
}
/**
* 运行全局自动对账
* 运行全局自动对账(限定当前用户)
* 对所有未匹配的交易尝试匹配
*/
function runAutoReconciliation() {
function runAutoReconciliation(userId) {
const db = getDB();
const unmatched = db.prepare(`
const unmatched = db
.prepare(
`
SELECT * FROM transactions
WHERE matched_transaction_id IS NULL
WHERE matched_transaction_id IS NULL AND user_id = ?
ORDER BY transaction_date DESC
`).all();
`,
)
.all(userId);
let matchCount = 0;
@@ -149,7 +163,7 @@ function runAutoReconciliation() {
for (const tx of unmatched) {
if (processed.has(tx.id)) continue;
const matches = findMatches(tx);
const matches = findMatches(tx, userId);
if (matches.length > 0 && matches[0].match_score >= 0.7) {
const bestMatch = matches[0];