Files
reco/server/services/matcher.js
T

212 lines
5.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const { getDB } = require("../db");
/**
* 交易匹配服务
*
* 自动匹配不同来源的相同交易,例如:
* - 支付宝消费 → 银行卡扣款
* - 微信支付 → 信用卡扣款
* - 跨行转账 ↔ 对方账户入账
*
* 匹配规则(按优先级):
* 1. 相同日期 + 相同金额(最可靠)
* 2. 日期相近(±1天) + 相同金额 + 描述相似
* 3. 日期相近(±2天) + 金额相近(±1元) + 对方名称相似
*/
function findMatches(newTransaction, userId) {
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
FROM transactions
WHERE id != ?
AND source_id != ?
AND user_id = ?
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,
userId,
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(userId) {
const db = getDB();
const unmatched = db
.prepare(
`
SELECT * FROM transactions
WHERE matched_transaction_id IS NULL AND user_id = ?
ORDER BY transaction_date DESC
`,
)
.all(userId);
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, userId);
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 };