Share funktion
This commit is contained in:
@@ -623,6 +623,37 @@ const consumeCreditsWithIdempotency = async (db, userId, key, cost) => {
|
||||
});
|
||||
};
|
||||
|
||||
const refundCredits = (account, amount) => {
|
||||
if (amount <= 0) return 0;
|
||||
|
||||
// Spiegelbildlich zu consumeCredits: zuerst das Monatskontingent entlasten,
|
||||
// ein etwaiger Rest wandert auf das Topup-Guthaben zurück.
|
||||
let remaining = amount;
|
||||
const monthlyRefund = Math.min(account.usedThisCycle, remaining);
|
||||
account.usedThisCycle -= monthlyRefund;
|
||||
remaining -= monthlyRefund;
|
||||
|
||||
if (remaining > 0) {
|
||||
account.topupBalance += remaining;
|
||||
}
|
||||
|
||||
return amount;
|
||||
};
|
||||
|
||||
const refundCreditsWithIdempotency = async (db, userId, key, amount) => {
|
||||
return runInTransaction(db, async (tx) => {
|
||||
const existing = await readIdempotentValue(tx, key);
|
||||
if (existing && typeof existing.refunded === 'number') return existing.refunded;
|
||||
|
||||
const account = await getOrCreateAccount(tx, userId);
|
||||
const refunded = refundCredits(account, amount);
|
||||
account.updatedAt = nowIso();
|
||||
await upsertAccount(tx, account);
|
||||
await writeIdempotentValue(tx, key, { refunded });
|
||||
return refunded;
|
||||
});
|
||||
};
|
||||
|
||||
const getBillingSummary = async (db, userId) => {
|
||||
if (userId === 'guest') {
|
||||
return {
|
||||
@@ -820,6 +851,7 @@ module.exports = {
|
||||
chargeKey,
|
||||
claimNotificationOnce,
|
||||
consumeCreditsWithIdempotency,
|
||||
refundCreditsWithIdempotency,
|
||||
endpointKey,
|
||||
ensureBillingSchema,
|
||||
getAccountSnapshot,
|
||||
|
||||
Reference in New Issue
Block a user