仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
61 lines
2.6 KiB
JavaScript
61 lines
2.6 KiB
JavaScript
'use strict';
|
|
// 店铺配置只用于新单。历史单据缺快照时回到原逐笔费率,不能用今天的设置补历史。
|
|
const Cards = require('./public/credit-card-fees');
|
|
const tableFor = kind => (kind === 'order' ? 'orders' : kind === 'price_lock' ? 'price_locks' : null);
|
|
function initialize(ledger) {
|
|
// 独立表避免改变旧订单的 SELECT * 结果及待审批申请的快照哈希。
|
|
ledger.db.exec(
|
|
"CREATE TABLE IF NOT EXISTS credit_card_rate_snapshots(kind TEXT NOT NULL CHECK(kind IN ('order','price_lock')),entity_id TEXT NOT NULL,rate_permille INTEGER NOT NULL CHECK(rate_permille BETWEEN 0 AND 1000),PRIMARY KEY(kind,entity_id))",
|
|
);
|
|
}
|
|
function current(ledger) {
|
|
return Cards.rate(require('./shop-settings').read(ledger).creditCardRatePermille);
|
|
}
|
|
function recordedRate(fee) {
|
|
const value = fee.rate_permille ?? fee.card_fee_rate;
|
|
if (Number.isSafeInteger(value) && value >= 0 && value <= 1000) return value;
|
|
const match = String(fee.note ?? fee.card_fee_note ?? '').match(/^信用卡手续费((\d+)‰)$/);
|
|
if (match && Number(match[1]) <= 1000) return Number(match[1]);
|
|
return null;
|
|
}
|
|
function read(ledger, kind, id) {
|
|
const table = tableFor(kind);
|
|
if (!table) throw new Error('信用卡费率单据类型无效');
|
|
const snapshot = ledger.one(
|
|
'SELECT rate_permille FROM credit_card_rate_snapshots WHERE kind=? AND entity_id=?',
|
|
kind,
|
|
id,
|
|
);
|
|
if (snapshot) return Cards.rate(snapshot.rate_permille);
|
|
const row = ledger.one('SELECT * FROM ' + table + ' WHERE id=?', id);
|
|
if (!row) throw new Error('信用卡费率单据不存在');
|
|
const fees =
|
|
kind === 'order'
|
|
? JSON.parse(row.fee_items).filter(Cards.isFee)
|
|
: ledger.rows(
|
|
'SELECT card_fee_rate,card_fee_note FROM price_lock_events WHERE price_lock_id=? AND card_fee_amount IS NOT NULL ORDER BY created,rowid',
|
|
id,
|
|
);
|
|
for (const fee of fees) {
|
|
const rate = recordedRate(fee);
|
|
if (rate !== null) return rate;
|
|
}
|
|
return Cards.ratePermille;
|
|
}
|
|
function capture(ledger, kind, id, value = current(ledger)) {
|
|
const table = tableFor(kind);
|
|
if (!table) throw new Error('信用卡费率单据类型无效');
|
|
const rate = Cards.rate(value);
|
|
ledger.run(
|
|
'INSERT INTO credit_card_rate_snapshots(kind,entity_id,rate_permille) VALUES (?,?,?) ON CONFLICT(kind,entity_id) DO UPDATE SET rate_permille=excluded.rate_permille',
|
|
kind,
|
|
id,
|
|
rate,
|
|
);
|
|
return rate;
|
|
}
|
|
function remove(ledger, kind, id) {
|
|
ledger.run('DELETE FROM credit_card_rate_snapshots WHERE kind=? AND entity_id=?', kind, id);
|
|
}
|
|
module.exports = { initialize, current, read, capture, remove };
|