version 0.1

This commit is contained in:
2026-05-05 14:53:38 +08:00
parent 1da3bf9dd9
commit 6402a03026
27 changed files with 24704 additions and 0 deletions
+224
View File
@@ -0,0 +1,224 @@
const { getDB } = require("../db");
/**
* LLM 服务:调用大模型对交易进行分类和描述
*
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
* 如果未配置 API Key,使用本地规则进行降级分类
*/
let openaiClient = null;
function getOpenAIClient() {
if (openaiClient) return openaiClient;
const db = getDB();
const apiKey = db
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
.get();
const baseURL = db
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
.get();
const model = db
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
.get();
if (!apiKey || !apiKey.value) return null;
const { OpenAI } = require("openai");
openaiClient = new OpenAI({
apiKey: apiKey.value,
baseURL: (baseURL && baseURL.value) || "https://api.openai.com/v1",
});
openaiClient._model = (model && model.value) || "gpt-4o-mini";
return openaiClient;
}
/**
* 构建分类 Prompt
*/
function buildClassificationPrompt(transactions) {
const db = getDB();
const categories = db
.prepare("SELECT id, name, keywords FROM categories")
.all();
const categoryList = categories
.map(
(c) =>
`${c.name}(关键词:${JSON.parse(c.keywords || "[]").join("、")})`,
)
.join("\n");
const txList = transactions
.map(
(tx, i) =>
`[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || "未知"} | 描述:${tx.description || "无"} | 来源:${tx.source_type}`,
)
.join("\n");
return `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
## 可用分类:
${categoryList}
## 交易记录:
${txList}
## 要求:
请为每笔交易返回一个JSON数组,每项包含:
- index: 交易序号(整数)
- category: 最合适的分类名称(必须从上面的可用分类中选择)
- description: 用简洁的中文描述这笔交易(10-30字),例如"在星巴克购买咖啡"、"缴纳本月房租"、"收到工资"
- confidence: 你对分类的置信度(0-1之间的浮点数)
仅返回JSON数组,不要包含其他内容。`;
}
/**
* 批量分类交易
*/
async function classifyTransactions(transactionIds) {
const db = getDB();
const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds];
const transactions = db
.prepare(
`
SELECT * FROM transactions WHERE id IN (${ids.map(() => "?").join(",")})
`,
)
.all(...ids);
if (transactions.length === 0) return { classified: 0 };
// 尝试使用LLM
const client = getOpenAIClient();
if (client) {
try {
const prompt = buildClassificationPrompt(transactions);
const response = await client.chat.completions.create({
model: client._model,
messages: [
{
role: "system",
content:
"你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。",
},
{ role: "user", content: prompt },
],
temperature: 0.3,
max_tokens: 2000,
});
const content = response.choices[0].message.content;
const jsonMatch = content.match(/\[[\s\S]*\]/);
if (jsonMatch) {
const results = JSON.parse(jsonMatch[0]);
const updateStmt = db.prepare(`
UPDATE transactions
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
db.transaction(() => {
for (const item of results) {
const tx = transactions[item.index - 1];
if (tx) {
updateStmt.run(
item.category,
item.description,
item.confidence,
item.category,
tx.id,
);
}
}
})();
return { classified: results.length, source: "llm" };
}
} catch (err) {
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
}
}
// 降级:使用本地关键词规则分类
return classifyByRules(transactions);
}
/**
* 本地关键词规则分类(无需LLM)
*/
function classifyByRules(transactions) {
const db = getDB();
const categories = db
.prepare("SELECT id, name, keywords FROM categories")
.all();
const updateStmt = db.prepare(`
UPDATE transactions
SET ai_category = ?, ai_description = ?, ai_confidence = ?, category = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
let classified = 0;
let needsReview = 0;
for (const tx of transactions) {
const text =
`${tx.description || ""} ${tx.counterparty || ""} ${tx.notes || ""}`.toLowerCase();
// 金额超过100元标记为需要人工确认
const largeAmount = Math.abs(tx.amount) >= 100;
// 关键词匹配
let bestCategory = "其他杂项";
let bestScore = 0;
for (const cat of categories) {
const keywords = JSON.parse(cat.keywords || "[]");
let score = 0;
for (const kw of keywords) {
if (text.includes(kw.toLowerCase())) {
score++;
}
}
if (score > bestScore) {
bestScore = score;
bestCategory = cat.name;
}
}
// 生成简单描述
let aiDescription = "";
if (tx.direction === "income") {
aiDescription = `收到${tx.counterparty || "对方"} ${Math.abs(tx.amount).toFixed(2)}元`;
} else {
aiDescription = `向${tx.counterparty || "对方"}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? "(" + tx.description + ")" : ""}`;
}
updateStmt.run(
bestCategory,
aiDescription.substring(0, 100),
bestScore > 0 ? 0.7 : 0.3,
bestCategory,
tx.id,
);
classified++;
if (largeAmount) needsReview++;
}
return { classified, needsReview, source: "rules" };
}
module.exports = { classifyTransactions, getOpenAIClient };
+198
View File
@@ -0,0 +1,198 @@
const { getDB } = require('../db');
/**
* 交易匹配服务
*
* 自动匹配不同来源的相同交易,例如:
* - 支付宝消费 → 银行卡扣款
* - 微信支付 → 信用卡扣款
* - 跨行转账 ↔ 对方账户入账
*
* 匹配规则(按优先级):
* 1. 相同日期 + 相同金额(最可靠)
* 2. 日期相近(±1天) + 相同金额 + 描述相似
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
*/
function findMatches(newTransaction) {
const db = getDB();
const absAmount = Math.abs(newTransaction.amount);
// 只匹配金额 > 0.01 的交易
if (absAmount < 0.01) return [];
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 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
);
if (candidates.length === 0) return [];
const matches = [];
for (const candidate of candidates) {
let score = 0;
const reasons = [];
// 金额得分
const amountDiff = Math.abs(Math.abs(candidate.amount) - absAmount);
if (amountDiff < 0.01) {
score += 40;
reasons.push('金额完全一致');
} else if (amountDiff < 0.1) {
score += 35;
reasons.push('金额基本一致');
} else if (amountDiff < 1.0) {
score += 20;
reasons.push('金额接近');
}
// 日期得分
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('日期相同');
} else if (dateDiff <= 1) {
score += 20;
reasons.push('日期差1天');
} else if (dateDiff <= 2) {
score += 10;
reasons.push('日期差2天');
}
// 对方名称相似度
const nameSim = stringSimilarity(
(candidate.counterparty || '').toLowerCase(),
(newTransaction.counterparty || '').toLowerCase()
);
if (nameSim > 0.8) {
score += 20;
reasons.push('对方名称高度相似');
} else if (nameSim > 0.5) {
score += 10;
reasons.push('对方名称部分相似');
}
// 描述相似度
const descSim = stringSimilarity(
(candidate.description || '').toLowerCase(),
(newTransaction.description || '').toLowerCase()
);
if (descSim > 0.7) {
score += 10;
reasons.push('描述相似');
}
// 方向互补(一个支出一个收入,说明是转账匹配)
if (candidate.direction !== newTransaction.direction) {
score += 5;
reasons.push('收支方向互补');
}
if (score >= 40) { // 最低匹配阈值
matches.push({
transaction_id: candidate.id,
match_score: Math.min(score, 100) / 100,
reasons: reasons.join(';'),
candidate
});
}
}
// 按得分排序
matches.sort((a, b) => b.match_score - a.match_score);
return matches;
}
/**
* 运行全局自动对账
* 对所有未匹配的交易尝试匹配
*/
function runAutoReconciliation() {
const db = getDB();
const unmatched = db.prepare(`
SELECT * FROM transactions
WHERE matched_transaction_id IS NULL
ORDER BY transaction_date DESC
`).all();
let matchCount = 0;
const updateStmt = db.prepare(`
UPDATE transactions
SET matched_transaction_id = ?, match_score = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
const processed = new Set();
for (const tx of unmatched) {
if (processed.has(tx.id)) continue;
const matches = findMatches(tx);
if (matches.length > 0 && matches[0].match_score >= 0.7) {
const bestMatch = matches[0];
// 双向匹配
db.transaction(() => {
updateStmt.run(bestMatch.transaction_id, bestMatch.match_score, tx.id);
updateStmt.run(tx.id, bestMatch.match_score, bestMatch.transaction_id);
})();
processed.add(tx.id);
processed.add(bestMatch.transaction_id);
matchCount++;
}
}
return { matched: matchCount, total: unmatched.length };
}
/**
* 简单的字符串相似度算法(基于重叠字符)
*/
function stringSimilarity(a, b) {
if (!a || !b) return 0;
if (a === b) return 1;
const shorter = a.length < b.length ? a : b;
const longer = a.length < b.length ? b : a;
if (shorter.length === 0) return 0;
// 使用滑动窗口匹配
let matches = 0;
for (let i = 0; i < shorter.length - 1; i++) {
const bigram = shorter.substring(i, i + 2);
if (longer.includes(bigram)) {
matches++;
}
}
const possibleMatches = shorter.length - 1;
if (possibleMatches === 0) return 0;
return matches / possibleMatches;
}
module.exports = { findMatches, runAutoReconciliation };