48 lines
1.5 KiB
JavaScript
48 lines
1.5 KiB
JavaScript
const crypto = require('crypto');
|
|
|
|
/**
|
|
* 生成统一交易编码
|
|
* 规则:基于日期+金额+交易对方的MD5哈希前12位
|
|
* 相同日期、相同金额、相同对方的交易会被合并到同一个编码
|
|
*/
|
|
function generateTransactionCode(dateStr, amount, counterparty, description) {
|
|
// 金额保留2位小数
|
|
const amountFixed = parseFloat(amount).toFixed(2);
|
|
// 截取日期到天
|
|
const dateDay = String(dateStr).substring(0, 10);
|
|
|
|
const raw = `${dateDay}|${amountFixed}|${(counterparty || '').trim()}|${(description || '').trim()}`;
|
|
return 'TX' + crypto.createHash('md5').update(raw).digest('hex').substring(0, 12).toUpperCase();
|
|
}
|
|
|
|
/**
|
|
* 聚合交易:将相同交易编码的交易合并
|
|
* 保留最详细的信息
|
|
*/
|
|
function mergeTransactions(txs) {
|
|
if (txs.length === 0) return null;
|
|
if (txs.length === 1) return txs[0];
|
|
|
|
// 按 info 优先级:优先保留有更多字段的交易
|
|
const merged = { ...txs[0] };
|
|
const fieldsToPickBest = ['counterparty', 'description', 'notes', 'method', 'status'];
|
|
|
|
for (const field of fieldsToPickBest) {
|
|
for (const tx of txs) {
|
|
if (tx[field] && !merged[field]) {
|
|
merged[field] = tx[field];
|
|
}
|
|
}
|
|
}
|
|
|
|
// 合并 source_type(记录多个来源)
|
|
const sourceTypes = [...new Set(txs.map(t => t.source_type))];
|
|
merged.source_type = sourceTypes.join(',');
|
|
merged._merged_from = txs.length;
|
|
merged._source_ids = txs.map(t => t.source_id);
|
|
|
|
return merged;
|
|
}
|
|
|
|
module.exports = { generateTransactionCode, mergeTransactions };
|