fix(payments): close the double-refund path and price in the core #13

Sammanfogat
supernaut sammanfogade 6 incheckningar från fix/refund-idempotency in i main 2026-08-01 16:51:29 +00:00
Ägare

Six issues, each written test-first with the red run observed before the fix.

Tracked in the other private repo, so these cannot be closed by keyword from here and must be closed by
hand when this merges: gitborg/gitborg-internal#53, #54, #50, #46, #49, #52.

#53 — refund could double-charge

All three defects the issue names:

  • Idempotency. A caller-supplied key is threaded into paymentRefunds.create, derived
    deterministically by refundIdempotencyKey. It is a digest rather than a composed string,
    because the provider caps the key at 40 characters and a silently truncated key stops deduping —
    which is the failure this fix exists to prevent.
  • Local record. A refund table with idempotency_key UNIQUE and a unique provider_refund_ref.
  • Actionable status. The return type widens to pending | succeeded | failed with
    providerRefundRef, and getRefundStatus is added. Unknown provider states map to pending,
    never to a confirmed outcome
    — the old code reported failed for queued, pending and
    processing, which is how a refund that is actually in flight gets retried.

#54 — provider_event swallowed refund webhooks

Premise confirmed, and #53 did change the shape of the fix: with a local refund row keyed to a provider
refund ref, keying events off the refund object — the issue's preferred option — composes cleanly.

parseCallback now returns ProviderEvent[], with refunds and chargebacks emitted as their own events
keyed re_1:refunded / chb_1:open|reversed. Sub-resources are only listed when the payment actually
carries the field, so an ordinary webhook still costs one API call.

Chargebacks were adjacent rather than in scope ("likely the same shape"), and are included: they are
silently dropped for exactly the same reason.

#50, #46, #49, #52

  • #50 — the provider customer create now carries our metadata and an idempotency key, so a retry
    cannot leave an orphan; last4 was storing the full number and is now sliced.
  • #46 — a new startCheckout resolves VAT and price in the core and hands the adapter a bare
    amountMinor. The adapter's PLANS import, amountMinorFor and the org_seat throw are gone, which
    is what closed the VAT gap. Seat cases are covered: SE B2B 3 seats, DE B2B validated at 0% reverse
    charge (explicitly not Swedish VAT), DE B2C under OSS, NO VOEC. A test asserts no VAT context
    crosses the adapter boundary and that pricing fails closed before any provider call.
  • #49 — the blind spot was verified by injecting the exact regression the issue names
    (String(amountMinor / 100) in place of toFixed): 1 test failed before the new tests, 10 after.
    Adds the öre→decimal table on both paths, the full subscription lifecycle including the
    customerId:subscriptionId round trip and its malformed-ref refusals, every getStatus branch, and
    pins the inclusive-plan-at-0%-VAT commercial consequence.
  • #52 — FK indexes, a partial unique index on unreleased seats, vat_rate → vat_rate_bps.
    money.ts now refuses negative and non-integer amounts and documents roundHalfUp's exact range;
    add-on names are validated before they can become group names.

Migration SQL, reviewed rather than trusted

drizzle/0002_parched_zzzax.sql is two RENAME COLUMNs, six CREATE INDEX, and the partial unique
index with WHERE "seat_assignment"."released_at" is null. No drops and no data movement. The
renamed columns were already integer holding basis points — the unit was previously only in a comment,
so this moves it into the name where it travels with the value. Generated by driving drizzle-kit's rename
prompt (it needs a TTY); "rename" was chosen, not create/drop.

Verified

pnpm test 166 passed / 11 files · pnpm -r typecheck clean · pnpm eslint clean ·
pnpm format:check clean · pnpm drizzle-kit check "Everything's fine" · pnpm -r build clean.
Coverage 96.17% statements, 100% branch. Each commit also passes its own suite in isolation
(84 / 90 / 93 / 102 / 144 / 166).

Three things to know before this is relied on

  1. No writer exists yet, so the durable guard is latent. refund.idempotency_key UNIQUE and
    refundIdempotencyKey have no non-test caller until the refund/webhook handler is built. The
    required order is documented in both refunds.ts and schema.ts: insert the local row first, and
    call the provider only if that insert succeeded.
    Getting that order wrong reopens #53 with the
    table in place.
  2. Add-on names must now match ent_*, excluding tier_* and idm_* so an add-on string can never
    grant a tier or an admin group. That mirrors ADR 0016's naming; if the real add-on group names
    differ, relax the pattern.
  3. parseCallback emits chargeback events but there is no chargeback table or handler yet —
    filed separately.

Left out deliberately

#50's Containerfile items (the issue folds them into deploy-role work) and the
minimumReleaseAgeExclude guard (supply-chain config, not correctness); #52's
payment_method.status enum (needs Mollie's real mandate vocabulary — documented as text for now),
gapless invoice numbering (needs a design), and the retention / ON DELETE ADR, which belongs in
the public docs repo. The ON DELETE decision is documented in schema.ts and guarded by a test.

The design document needs updating for the interface changes here; that is a separate docs change.

Six issues, each written test-first with the red run observed before the fix. Tracked in the other private repo, so these cannot be closed by keyword from here and must be closed by hand when this merges: gitborg/gitborg-internal#53, #54, #50, #46, #49, #52. ## #53 — refund could double-charge All three defects the issue names: - **Idempotency.** A caller-supplied key is threaded into `paymentRefunds.create`, derived deterministically by `refundIdempotencyKey`. It is a **digest** rather than a composed string, because the provider caps the key at 40 characters and a silently truncated key stops deduping — which is the failure this fix exists to prevent. - **Local record.** A `refund` table with `idempotency_key UNIQUE` and a unique `provider_refund_ref`. - **Actionable status.** The return type widens to `pending | succeeded | failed` with `providerRefundRef`, and `getRefundStatus` is added. **Unknown provider states map to `pending`, never to a confirmed outcome** — the old code reported `failed` for `queued`, `pending` and `processing`, which is how a refund that is actually in flight gets retried. ## #54 — `provider_event` swallowed refund webhooks Premise confirmed, and #53 did change the shape of the fix: with a local refund row keyed to a provider refund ref, keying events off the refund object — the issue's preferred option — composes cleanly. `parseCallback` now returns `ProviderEvent[]`, with refunds and chargebacks emitted as their own events keyed `re_1:refunded` / `chb_1:open|reversed`. Sub-resources are only listed when the payment actually carries the field, so an ordinary webhook still costs one API call. Chargebacks were adjacent rather than in scope ("likely the same shape"), and are included: they are silently dropped for exactly the same reason. ## #50, #46, #49, #52 - **#50** — the provider customer create now carries our metadata and an idempotency key, so a retry cannot leave an orphan; `last4` was storing the full number and is now sliced. - **#46** — a new `startCheckout` resolves VAT and price in the **core** and hands the adapter a bare `amountMinor`. The adapter's `PLANS` import, `amountMinorFor` and the `org_seat` throw are gone, which is what closed the VAT gap. Seat cases are covered: SE B2B 3 seats, DE B2B validated at 0% reverse charge (explicitly *not* Swedish VAT), DE B2C under OSS, NO VOEC. A test asserts no VAT context crosses the adapter boundary and that pricing fails closed **before** any provider call. - **#49** — the blind spot was verified by injecting the exact regression the issue names (`String(amountMinor / 100)` in place of `toFixed`): **1 test failed before the new tests, 10 after**. Adds the öre→decimal table on both paths, the full subscription lifecycle including the `customerId:subscriptionId` round trip and its malformed-ref refusals, every `getStatus` branch, and pins the inclusive-plan-at-0%-VAT commercial consequence. - **#52** — FK indexes, a **partial** unique index on unreleased seats, `vat_rate` → `vat_rate_bps`. `money.ts` now refuses negative and non-integer amounts and documents `roundHalfUp`'s exact range; add-on names are validated before they can become group names. ### Migration SQL, reviewed rather than trusted `drizzle/0002_parched_zzzax.sql` is two `RENAME COLUMN`s, six `CREATE INDEX`, and the partial unique index with `WHERE "seat_assignment"."released_at" is null`. **No drops and no data movement.** The renamed columns were already `integer` holding basis points — the unit was previously only in a comment, so this moves it into the name where it travels with the value. Generated by driving drizzle-kit's rename prompt (it needs a TTY); "rename" was chosen, not create/drop. ## Verified `pnpm test` **166 passed / 11 files** · `pnpm -r typecheck` clean · `pnpm eslint` clean · `pnpm format:check` clean · `pnpm drizzle-kit check` "Everything's fine" · `pnpm -r build` clean. Coverage **96.17% statements, 100% branch**. Each commit also passes its own suite in isolation (84 / 90 / 93 / 102 / 144 / 166). ## Three things to know before this is relied on 1. **No writer exists yet, so the durable guard is latent.** `refund.idempotency_key UNIQUE` and `refundIdempotencyKey` have no non-test caller until the refund/webhook handler is built. The required order is documented in both `refunds.ts` and `schema.ts`: **insert the local row first, and call the provider only if that insert succeeded.** Getting that order wrong reopens #53 with the table in place. 2. **Add-on names must now match `ent_*`**, excluding `tier_*` and `idm_*` so an add-on string can never grant a tier or an admin group. That mirrors ADR 0016's naming; if the real add-on group names differ, relax the pattern. 3. **`parseCallback` emits chargeback events but there is no `chargeback` table or handler yet** — filed separately. ## Left out deliberately #50's `Containerfile` items (the issue folds them into deploy-role work) and the `minimumReleaseAgeExclude` guard (supply-chain config, not correctness); #52's `payment_method.status` enum (needs Mollie's real mandate vocabulary — documented as text for now), gapless invoice numbering (needs a design), and the retention / `ON DELETE` **ADR**, which belongs in the public docs repo. The `ON DELETE` decision is documented in `schema.ts` and guarded by a test. The design document needs updating for the interface changes here; that is a separate docs change.
supernaut lade till 6 incheckningar 2026-08-01 14:29:34 +00:00
Refunding twice sends a customer double their money back, and all three of the
gaps that made that reachable are addressed together:

1. `PaymentProvider.refund` now takes a caller-supplied `idempotencyKey`. Passing
   nothing was not a neutral default: the Mollie SDK generates a fresh RANDOM key
   per call, so a retry genuinely created a SECOND refund. `refundIdempotencyKey`
   (src/refunds.ts) derives it deterministically from charge id + amount — as a
   digest, because the provider caps the key at 40 characters and a truncated key
   does not dedupe.

2. A `refund` table with `idempotency_key UNIQUE` is the durable guard: the
   provider's replay window is roughly an hour while an in-flight refund can
   persist ~2 hours, so idempotency only narrows the window. Claim the local row
   first; a conflict means "already refunded". The provider refund ref is now
   returned instead of discarded, and stored uniquely.

3. `refund` no longer reports in-flight states as `"failed"`. `RefundStatus`
   widens to pending|succeeded|failed and `getRefundStatus` makes a pending refund
   resolvable — the old JSDoc told callers to reconcile via a refund status the
   interface had no way to read. Unknown provider states map to pending, never to
   a confirmed outcome.

Tests cover the forwarded key, the returned ref, every Mollie refund state, the
unknown-state fallback, the composite-ref round trip and its malformed-input
throw, plus the schema constraints.

Refs #53
`provider_event.provider_event_id` was synthesized as "<paymentId>:<status>",
which stopped the outright UNIQUE collision but not the loss: the transitions
that move money back out do not change the payment's status. A refunded Mollie
payment stays `paid`, so the refund webhook produced a key identical to the
original payment event's and the dedupe guard swallowed it — the same failure
mode, displaced from "collides" to "silently deduped". Chargebacks have the same
shape.

Refunds and chargebacks are now treated as the separate objects they are, each
emitted as its own event keyed on its own id and state, so `parseCallback`
returns every transition the authenticated re-fetch reveals rather than one
event per webhook (`ProviderEvent[]`; empty array replaces `null`). No field of
the payment has to be nominated as a "signals a transition" marker any more, and
a refund event that can be recorded is a refund that can be reconciled against
the local refund row.

Sub-resources are only listed when the payment says they exist, so an ordinary
payment webhook still costs a single API call.

Refs #54
`beginCheckout` dropped `customer.id`, so nothing on the provider side pointed at
our `customer` row — the link reconciliation, accounting and a GDPR erasure
request all need. It also passed the idempotency key to the payment create only,
so every abandoned-then-retried checkout left an orphan provider customer behind.
Both now go to the customer create.

Also slices the stored `last4` to four digits. Mollie documents the field as the
last four already, so it is a no-op today; it makes persisting a full PAN — the
one thing that would take this service out of PCI SAQ-A scope — structurally
impossible if that ever changes.

Refs #50
`priceFor` had no non-test caller: the only money-charging path reached around it
and imported the plan catalogue into the vendor adapter — a layering inversion,
and the reason org_seat checkout threw. Its charge is net x seats PLUS
destination VAT, so it depends on the customer's country and business status,
which `CustomerRef` deliberately does not carry.

`startCheckout` (src/checkout.ts) now resolves VAT and the plan price first and
passes `amountMinor` into `beginCheckout`, symmetrically with
`createSubscription`. So the adapter owns no plan catalogue and no VAT
knowledge, no VAT context crosses the provider boundary, and org seats can be
charged correctly. The returned `PriceLine` is what the caller writes onto the
charge and the invoice, rather than re-deriving it later and risking a different
answer than the customer was charged.

Pricing runs before the provider call, so an unsupported country or an
unpriceable quantity still fails closed — without moving money. Tests cover the
seat cases that could not previously be expressed, including a validated EU
business paying no VAT rather than the Swedish rate.

Refs #46
Five of the eight PaymentProvider methods had no tests, and `beginCheckout` never
asserted the amount — so the one conversion from integer öre to the provider's
decimal string could have lost `toFixed` and the suite would have stayed green.
Verified by injecting exactly that regression: it broke a single unrelated
assertion before, and 10 after.

Adds: the minor-unit table (one öre, trailing zeros, whole kronor, VAT-bearing
seat amounts, a large amount) on both the checkout and the recurring path; the
subscription lifecycle including the composite providerSubRef round trip through
update and cancel, its malformed-ref refusal and the missing-mandate refusal;
every payment-status branch of getStatus including an unrecognised one; the
empty display-metadata path; the empty-string MOLLIE_API_KEY throw; lowercase
country normalisation; and the entitlement cases that were unexercised
(incomplete grants nothing, add-ons ride along per seat, a billing owner holding
no seat gets nothing).

Also pins, rather than changes, the commercial consequence of an inclusive plan
under a 0% VAT basis: the full gross becomes net revenue. That is a pricing
decision, so it now has a test that has to be edited deliberately.

Refs #49
refactor(db): greenfield schema hardening — indexes, seat uniqueness, vat_rate_bps
Alla kontroller lyckades
ci / ci (pull_request) Successful in 35s
72043a9cdf
All of these are free while `gitborg_payment` has zero rows and get expensive
later.

* Indexes on every foreign key. Postgres indexes a UNIQUE/PRIMARY KEY column for
  free but never a plain FK, so each one was a sequential scan per join and per
  referential check.
* A PARTIAL unique index on seat_assignment (subscription_id, kanidm_user) where
  the seat is unreleased. Duplicate live rows would inflate the seat count an org
  is billed for; partial, so a released seat can still be re-assigned to the same
  person later.
* `vat_rate` renamed to `vat_rate_bps` on charge and invoice. Basis points lived
  in a comment, and a 25 written where 2500 belongs is an invisible 100x tax
  error — the unit belongs in the name. Generated as two RENAME COLUMNs, no data
  movement.
* money.ts refuses negative amounts and rates, and documents the exact range of
  `roundHalfUp`. A negative .5 tie rounds toward zero where a positive one rounds
  away, so a credit note derived from a negative amount could differ by an öre
  from the invoice it reverses; money moving back to a customer is a refund with
  its own positive amount and its own row.
* Add-on names are validated before they become Kanidm group names. An add-on
  string is a direct group-grant primitive, so it must look like an entitlement
  group (`ent_*`) — which excludes `tier_*` (decided here, never by an add-on)
  and `idm_*` (Kanidm's own admin groups). Shape guard pending the real add-on
  catalogue.
* Documents in one place the decisions that were previously implicit: ON DELETE
  no action is deliberate for financial records (so account deletion is a
  retention policy to design, not a cascade), the completed/succeeded vocabulary
  split, why payment_method.status stays text, and that gapless invoice
  numbering still needs an allocation mechanism.

Refs #52
supernaut sammanfogade incheckning a84173039e till main 2026-08-01 16:51:29 +00:00
supernaut tog bort grenen fix/refund-idempotency 2026-08-01 16:51:29 +00:00
Logga in för att delta i denna konversation.
Inga granskare
Ingen milstolpe
Inget projekt
Inga tilldelade
1 deltagare
Notiser
Förfallodatum
Förfallodatumet är ogiltigt eller utanför gränserna. Använd formatet "åååå-mm-dd".

Inget förfallodatum satt.

Beroenden

Inga beroenden satta

Referens
bitborg/bitborg-payment!13
Ingen beskrivning angiven.