Share funktion

This commit is contained in:
2026-07-16 17:13:37 +02:00
parent 52c9dfb472
commit c7c1864fc6
9 changed files with 311 additions and 27 deletions

View File

@@ -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,