bidstage/lib/creem-refund.ts
caelum0x c709b0d3ec feat: harden money-path idempotency across checkout, settlement, and reversal
- Send stable per-checkout Idempotency-Key headers to Creem and Dodo so
  concurrent retries converge on one payable provider session
- State-guarded provider-session persistence: a late provider response can
  no longer clobber a checkout a webhook already settled/reversed
- Key refund/dispute idempotency on the provider adjustment id (not the
  webhook event id) with ON CONFLICT claim, preventing double-subtraction
  when the same refund replays under a new event id
- Surface a conflicting second capture on an already-fulfilled checkout as
  an incident instead of silently swallowing it
- Clamp reversals to the settled contribution so post-dispute refunds are
  zero-delta no-ops instead of jamming the webhook forever
- Unique indexes: (provider, provider_adjustment_id) on payment_adjustments,
  partial (provider, provider_transaction_id) on bids (migration 0024)
- 4 new unit tests + 5 new Postgres integration scenarios (all green vs
  real Postgres 16)
2026-09-05 17:09:23 +03:00

45 lines
1.8 KiB
TypeScript

/**
* Pure, validated conversion of Creem's externally reported refund amounts into
* the cumulative amount to reverse against the Bidstage contribution.
*
* Creem reports `amount_paid` (what the buyer paid) and `refunded_amount`
* (cumulative refunded) on the transaction, while Bidstage credits its own
* `transaction.amount`. These can legitimately differ (fees, currency display),
* so the refunded amount is scaled into Bidstage's contribution space. Because
* this trusts external numbers, the inputs are validated for internal
* consistency and the result is clamped so a reversal can never exceed the
* contribution — an inconsistent payload is rejected rather than guessed.
*
* Extracted from the Creem webhook so the arithmetic is unit-testable.
*/
export type CreemRefundAmounts = {
/** Bidstage's credited contribution amount (transaction.amount), in cents. */
transactionAmount: number;
/** Provider-reported amount the buyer paid, in cents. */
amountPaid: number;
/** Provider-reported cumulative refunded amount, in cents. */
refundedAmount: number;
};
function positiveInt(value: number, label: string): number {
if (!Number.isSafeInteger(value) || value <= 0) {
throw new Error(`${label} must be a positive integer`);
}
return value;
}
export function creemCumulativeReversedCents(
input: Readonly<CreemRefundAmounts>,
): number {
const transactionAmount = positiveInt(input.transactionAmount, "Creem transaction amount");
const amountPaid = positiveInt(input.amountPaid, "Creem paid amount");
const refundedAmount = positiveInt(input.refundedAmount, "Creem cumulative refunded amount");
if (refundedAmount > amountPaid) {
throw new Error("Creem cumulative refund exceeds the amount paid");
}
return Math.min(
transactionAmount,
Math.round((transactionAmount * refundedAmount) / amountPaid),
);
}