Skip to content
Merged
Show file tree
Hide file tree
Changes from 43 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
dc137e9
Keep existing payments refundable when new sales are off
stefan-burke Jul 31, 2026
bc4a6dc
Address review: shared provider type, atomic provider transition
stefan-burke Aug 1, 2026
dd7c324
Update equivalent-mutant line numbers after review refactor
stefan-burke Aug 1, 2026
3fbb3d6
Tighten wording and use using-declarations for test stubs
stefan-burke Aug 1, 2026
f0d6acc
Keep operator UI correct when sales are off; fix broken flake
stefan-burke Aug 1, 2026
5345a26
Fix pre-existing none recovery and concurrency race
stefan-burke Aug 2, 2026
16e318d
Address review: unified provider resolver, RETURNING, revert templates
stefan-burke Aug 2, 2026
248967e
Add raw-writes mirror test; lint fixes
stefan-burke Aug 2, 2026
17a9483
Replace rawWritesApi with valibot tupleWithRest; restore distinct las…
stefan-burke Aug 2, 2026
9c67112
Kill template mutation survivors; fix stale equivalent entries
stefan-burke Aug 2, 2026
b6dbcd7
Kill 65/94 mutation survivors with compact table-driven assertions
stefan-burke Aug 2, 2026
5f757d5
Kill remaining 27 mutation survivors; compact tests under line cap
stefan-burke Aug 2, 2026
d98a098
Remove as-unknown-as cast; use typed signedMeta input for thank_you_url
stefan-burke Aug 2, 2026
80e7542
Save WIP
stefan-burke Aug 2, 2026
db336b4
Delete dead loaded.add writes; kill client.ts mutants
stefan-burke Aug 3, 2026
aa3aaaa
Move invalidation test to client suite; use CREATE TABLE for bare DB
stefan-burke Aug 3, 2026
3ea050a
Use unique test-only table for invalidation assertion
stefan-burke Aug 3, 2026
f18d7b0
Use INSERT not CREATE so invalidation parser fires on mutant
stefan-burke Aug 3, 2026
2b8bc24
Behavior-focused webhooks tests without mutation jargon
stefan-burke Aug 3, 2026
81a9425
Add behavior tests for distinguishable webhook mutants
stefan-burke Aug 3, 2026
7ec84c7
Extract failureDetail helper; separate specific log assertions
stefan-burke Aug 3, 2026
b906cbf
Fix equivalent-mutant line numbers after failureDetail extraction
stefan-burke Aug 3, 2026
6a835c8
Fix missing setupStripe in helper; add 503/data-payment-result/empty-…
stefan-burke Aug 3, 2026
d6c57df
Split webhook edge-case tests by route
stefan-burke Aug 3, 2026
656c954
Cover every payment callback mutation
stefan-burke Aug 3, 2026
c988434
Complete existing payment provider recovery
stefan-burke Aug 3, 2026
45e7840
Add direct settings route contract
stefan-burke Aug 3, 2026
704933b
Move provider recovery tests to mirror
stefan-burke Aug 3, 2026
cd669d0
Kill remaining payment safety mutants
stefan-burke Aug 3, 2026
92fc06c
Verify settings POST route dispatch
stefan-burke Aug 3, 2026
7daf37c
Harden payment provider recovery
stefan-burke Aug 3, 2026
f1eec7a
Add direct domain settings tests
stefan-burke Aug 3, 2026
a8f275d
Mirror payment provider form tests
stefan-burke Aug 3, 2026
55d10e2
Add payment provider recovery stories
stefan-burke Aug 3, 2026
6df7bd4
Exclude concurrent mutation test work
stefan-burke Aug 3, 2026
ff728d1
Finish payment provider recovery review fixes
stefan-burke Aug 3, 2026
05ca3c6
Cover payment provider form mutations
stefan-burke Aug 3, 2026
862bdd0
Finish payment recovery review fixes
stefan-burke Aug 3, 2026
bdefe2d
Cover atomic provider recovery state
stefan-burke Aug 3, 2026
0c4b76e
Preserve concurrent provider settings
stefan-burke Aug 3, 2026
ff70865
Merge remote-tracking branch 'origin/main' into payment-aggregate/01-…
stefan-burke Aug 4, 2026
17e3ea5
Use split Stripe configuration in tests
stefan-burke Aug 4, 2026
909b396
Serialize provider settings changes
stefan-burke Aug 4, 2026
2871d65
Merge remote-tracking branch 'origin/main' into payment-aggregate/01-…
stefan-burke Aug 4, 2026
a2676cc
Fix settings revision CI failures
stefan-burke Aug 4, 2026
6f4fafc
Resolve final provider settings checks
stefan-burke Aug 4, 2026
550b6ce
Cover provider settings guards
stefan-burke Aug 4, 2026
8fba391
Merge remote-tracking branch 'origin/main' into payment-aggregate/01-…
stefan-burke Aug 4, 2026
adab54e
Check what the customer was actually charged, and never lose a paymen…
stefan-burke Aug 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,51 @@ look.
fail-closed behaviour. See the "Respect the subrequest budget" guidance in
AGENTS.md.

## Payment aggregate — safety behaviour (PR 1)

New sales and existing payments are now resolved by different questions:
`getActivePaymentProvider()` / `isPaymentsEnabled()` gate new checkouts;
`getPaymentProviderForExistingPayments()` resolves refunds, replayed
callbacks, and completion. When sales are off, the existing-payment path
falls back to the last activated provider. A site already on `none`
recovers when exactly one provider has stored credentials; when multiple
do, the operator must choose the provider in a recovery form that keeps new
sales off. `setPaymentProviderNone` reads the
current provider via an atomic INSERT ... SELECT subquery so a concurrent
activation cannot land between the read and the write.

The seven accepted safety rules are recorded as acceptance constraints in
[`docs/payment-aggregate-acceptance.md`](docs/payment-aggregate-acceptance.md).

- **Track the provider each charge was captured with.** `main` stores only the
opaque `payment_reference` per processed payment, not which provider captured
it. So after an operator switches providers (Stripe → Square) and then selects
"none", the last-active fallback resolves every payment through Square, and
an older Stripe charge cannot be refunded or reconciled against the provider
that captured it. This predates PR 1 and is future aggregate work. Fix
direction: store the provider type on each `processed_payments` row at capture
time and dispatch existing-payment work from that per-charge provider instead
of one global fallback. Referenced from
`docs/payment-aggregate-acceptance.md` rule 2.

- **Split payment-provider persistence out of `src/shared/db/settings.ts`.**
Review of PR 1 correctly noted that the settings assembly is already over the
preferred 400-line size and now also owns provider activation, recovery,
credential-state preservation, and cache synchronization. The clean starting
point is `src/shared/db/settings/payment-provider.ts`, moving the provider
getters and `settings.update` methods together with mirror tests under
`test/shared/db/settings/payment-provider/`. This is deferred because that
extraction would take PR 1 beyond its strict 800-line source-change limit.

- **Split provider credential routes out of
`src/features/admin/settings-helpers.ts`.** The generic helper now also owns
`ProviderCredentialsConfig`, `persistProviderCredentials`, and
`defineProviderCredentialsRoute`. Move that block to a focused admin settings
module and move its mirror tests from
`test/features/admin/settings-helpers/provider-credentials.test.ts` with it.
This is deferred because doing the move in PR 1 would break the same strict
800-line source-change limit.

## Request performance: consolidate AsyncLocalStorage scopes

`src/features/app/request.ts` enters eleven nested request scopes for locale, client
Expand Down
88 changes: 88 additions & 0 deletions docs/payment-aggregate-acceptance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Payment aggregate — accepted safety rules

These seven rules are the safety contract the payment aggregate must satisfy.
Some describe behaviour not yet on `main` (owner-review flow, queued owner
email, aggregate activation) — future aggregate work. They are recorded here
so earlier work does not paint the aggregate into a corner.

Each rule names the current behaviour where one exists. Nothing here is
implemented ahead of its time; this document is the contract, not scaffolding.

## The separation this PR establishes

- **New sales** — `getActivePaymentProvider()` / `isPaymentsEnabled()`. Null
when the provider is saved as "none".
- **Existing payments** — `getPaymentProviderForExistingPayments()`. Refunds,
reconciliation, replayed callbacks, and completion use this. When new sales
are off, it falls back to the last activated provider (whose credentials stay
stored), so payments captured by that provider stay refundable.

The rules below assume that separation holds.

> **Sales-off recovery.** A site may have no remembered provider. The resolver
> uses the sole provider with stored credentials when that choice is clear. If
> several providers have credentials, the settings page requires the operator
> to choose which one took the existing payments. Saving that choice records
> the provider and keeps new sales off. The system never guesses.

## 1. Failed checkout plus captured money becomes owner review with complete-or-refund choices

A captured charge whose booking cannot be honoured is surfaced for the
operator to either complete or refund.

*On `main` today:* refunded automatically (`storeRefundedBooking` /
`refundAndFail`). The "complete-or-refund" choice is future aggregate work;
the current path must keep refunding safely so the aggregate can later
replace the automatic refund with a review.

## 2. Completed refunds count immediately while overlapping refunds are blocked until provider totals catch up

A refund that succeeds is recorded at once. A second attempt for the same
charge is treated as done once the provider's own refund total confirms it.

*On `main` today:* `tryRefund` treats a payment the provider reports as
already refunded as success, and each charge carries a `provider_refunded_at`
marker so a later attempt skips the provider call. This must stay.

> **Known gap (provider switching).** `main` does not record which provider
> captured a charge — only the opaque `payment_reference`. So after an operator
> switches providers (Stripe → Square) and then selects "none", the last-active
> fallback resolves every existing payment through Square, and an older Stripe
> charge cannot be refunded. This predates this PR. Per-charge provider
> tracking is future aggregate work; recorded in TODO.md.

## 3. Multiple captured charges require owner review

A buyer with more than one captured charge must have the set surfaced for
the operator to decide, not auto-resolved.

*On `main` today:* merged attendees carry several references, handled as a
batch without review. Future aggregate work.

## 4. Queued owner email uses the current business address but stored body/buyer facts

The recipient address is read at send time. The body and buyer facts come from
when the case was raised, so the message describes what happened then.

*On `main` today:* there is no queued owner-email path; notifications are sent
inline. This is future aggregate work.

## 5. Malformed legacy records migrate without invented facts into owner review

A malformed record is carried forward only as far as it can be honestly read
and lands in owner review. `main` copies what is provably there and invents
nothing. This must stay.

## 6. A buyer with a paid booking under review sees "payment received" and gets a stable reload

A buyer must not be offered a way to pay again. A reload must return the same
state. `main` replays as success and never re-processes (`replaySessionFromLedger`).
The "under review" state is future aggregate work.

## 7. Aggregate activation waits for complete owner case pages/actions

The aggregate is only switched on once every owner-case page and action it
depends on exists. No half-enabled state.

*On `main` today:* there is no aggregate. Future work must clear this gate
before it takes over any payment path.
6 changes: 6 additions & 0 deletions scripts/mutation/equivalent-mutants/features.txt
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ src/features/api/payment-processing/package-pricing.ts:242:19 false → true
src/features/api/payment-processing/package-pricing.ts:259:60 ?? → || # intent.allocations is an array or undefined, and arrays (including []) are truthy
src/features/api/payment-processing/package-pricing.ts:295:51 ?? → || # the allocated quantity is non-negative and the fallback is 0, so both operators agree for 0 and undefined

# Payment success replay only loads a listing fallback while thankYouUrl is the
# empty string, so assignment and append produce the same string for every path.
src/features/api/webhooks.ts:173:16 = → += # the enclosing !thankYouUrl guard narrows the string to "" before this assignment, and "" + fallback equals fallback
src/ui/templates/admin/settings/payment.tsx:88:51 ?? → || # both operands are PaymentProviderType|null; every provider id is non-empty and truthy, while null selects the same fallback under either operator

# Folded API booking: equivalents for schema-validated inputs and unused paths.
src/features/api/folded-booking.ts:87:42 ?? → || # childrenByParentId is Map<number, TicketListing[]>; get returns an array (always truthy, even []) or undefined, so ?? and || agree
src/features/api/folded-booking.ts:118:31 ?? → || # qtyByChild accumulates ApiQuantitySchema values (positive integers >= 1) or is unset; it is never 0 or NaN for validated inputs, so ?? 0 and || 0 agree
Expand All @@ -164,3 +169,4 @@ src/features/api/folded-booking.ts:381:17 1 → 0 # base.dayCount is read onl
# placeholder and a throw-only label that can never throw.
src/features/admin/questions/answers.ts:88:45 0 → 1 # the inserted sortOrder is a placeholder: insertScopedOrderedRow runs order.append in the same transaction, and append sets sort_order from MAX over siblings that explicitly exclude the row itself, then overwrites it unconditionally before commit — the placeholder value is never read by anything
src/features/admin/questions/forms.ts:32:9 Display as → "" # requireChoiceOptions reads its label only in its two throw paths: an empty options list, or a value failing an invalid-rule. QUESTION_DISPLAY_TYPES is a non-empty picklist constant and requireChoiceOptions carries no invalid rule, so neither throw is reachable and the label is never read
src/features/admin/settings-page.ts:132:56 0 → 1 # existingPaymentProviderState resolves one configured provider directly; recoveryChoices is therefore either empty or has at least two providers, so both comparisons agree
1 change: 0 additions & 1 deletion scripts/mutation/equivalent-mutants/shared-a-l.txt
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ src/shared/accounting/rows.ts:262:64 ?? → || # selectById (await …)[0]: T
src/shared/accounting/rows.ts:138:72 ?? → || # renderInsert guard?.args: InValue[]|undefined — an array is always truthy
src/shared/accounting/manual-entries.ts:236:29 ?? → || # guard error message `transfer.kind ?? ""`: string|undefined, "" ?? "" === "" || ""
src/shared/checkout-ledger.ts:42:72 ?? → || # find(...)?.amount: number|undefined; the only falsy-non-null amount is 0 and 0 ?? 0 === 0 || 0
src/features/settings-bundles.ts:247:40 ?? → || # bundle is a readonly string[] or undefined; every present array, including [], is truthy
src/shared/maintenance/runner.ts:183:5 0 → 1 # every non-empty run needs at least two startup calls, so both allowances skip it; an empty run makes no calls
src/shared/maintenance/runner.ts:190:5 0 → 1 # every non-empty run needs at least two database startup calls, so both allowances skip it; an empty run makes no calls
src/shared/maintenance/runner.ts:202:23 ?? → || # wakePolicy is a non-empty MaintenanceWakePolicy value or undefined, so only undefined reaches the fallback
Expand Down
23 changes: 22 additions & 1 deletion scripts/mutation/equivalent-mutants/shared-m-z.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ src/shared/rest/crud-api.ts:367:31 ?? → || # hydrated map values are record
src/shared/rest/crud-api.ts:577:27 ?? → || # extraRoutes is a route object or undefined
src/shared/rest/resource.ts:158:25 ?? → || # validationError is an ErrorResult object or null; an object is truthy

# settings-bundles.ts: bundle is ALL_SNAPSHOT_SETTINGS when undefined (a readonly
# array, always truthy), so ?? and || agree.
src/features/settings-bundles.ts:244:40 ?? → || # bundle is a readonly array or undefined; an array is truthy

# webhooks.ts: listing?.thank_you_url.trim() ?? "" — trim() returns
# string|undefined; for "" both ?? "" and || "" yield "".
src/features/api/webhooks.ts:113:39 ?? → || # string|"" fallback; "" ?? "" = "" || "" = ""

# webhooks.ts: intent.thankYouUrl ?? "" — string|undefined; for ""
# both ?? "" and || "" yield "".
src/features/api/webhooks.ts:128:62 ?? → || # string|"" fallback; "" ?? "" = "" || "" = ""

# webhooks.ts: .find(Boolean) returns undefined|truthy (Boolean("") is
# false, so "" never returned). ?? null and || null agree.
src/features/api/webhooks.ts:313:4 ?? → || # find(Boolean) → undefined|truthy; never ""
src/features/api/webhooks.ts:341:55 ?? → || # getWebhookSignatureHeader → null|truthy; never ""

# require-provider.ts: getPaymentProviderForExistingPayments() returns
# Promise<ExistingPaymentProvider>; its awaited PaymentProvider|null value is
# always truthy when present.
src/features/admin/require-provider.ts:11:18 ?? → || # PaymentProvider|null; never falsy-but-non-null

# request-scoped ambient fallback: scope.current() is T|undefined where T is
# always a truthy container object (never a falsy-non-null value), so
# `?? fallback` and `|| fallback` always agree. (createScopedValue's ?? is NOT
Expand Down Expand Up @@ -232,4 +254,3 @@ src/shared/rebrand.ts:138:26 false → true # stepTag's tagIsCode reset after
src/shared/rebrand.ts:152:36 + → * # `open + 1` → `open * 1` = open: the scan starts on the inert "<" and behaves identically
src/shared/rebrand.ts:152:39 1 → 0 # `open + 0` = open: same inert-"<" start, identical result
src/features/admin/attributes.ts:215:46 0 → 1 # option insert's sortOrder is a placeholder: the same transaction's append overwrites it before commit, and a failed append rolls the row back — no committed state can carry the inserted value

3 changes: 2 additions & 1 deletion scripts/screenshots/app-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ const startAppServer = async ({
Deno.env.set("DB_ENCRYPTION_KEY", DB_KEY);
Deno.env.set("DB_URL", dbUrl);
const { settings } = await import("#shared/db/settings.ts");
await settings.update.stripe.activate({
await settings.update.stripe.configure({
secretKey: STRIPE_KEY,
webhookEndpointId: "we_screenshots",
webhookSecret: "whsec_screenshots",
});
await settings.update.paymentProvider("stripe");
},
stop: run,
};
Expand Down
42 changes: 42 additions & 0 deletions specs/payments/payment-provider-choice.feature
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,45 @@ Feature: An organiser chooses a payment provider
Given a Stripe test key is saved while Square takes payments
When the organiser changes the payment provider to Stripe
Then the payment settings show Stripe selected with its saved key in test mode

@rule:payments.existing-provider-recovery-keeps-sales-off
Rule: Choosing the provider for existing payments does not restart sales
When saved settings do not show which provider took earlier payments, the
organiser must choose one. This choice is only for those earlier payments.

@case:payments.recover-existing-provider
Scenario: The organiser chooses Stripe for existing payments
Given Stripe and Square were configured before new sales were turned off
When the organiser opens the payment settings
Then the organiser must choose the provider for existing payments
When the organiser chooses Stripe for existing payments
Then new sales stay off and the saved Stripe settings remain available

@rule:payments.provider-recovery-blocks-custom-domain
Rule: A custom domain cannot change before provider recovery is complete
A domain change also changes payment callback addresses. The organiser must
first say which provider still owns existing payments.

@case:payments.recovery-blocks-custom-domain
Scenario: The organiser recovers the provider before changing a custom domain
Given provider recovery is needed and both domain options are available
When the organiser opens the domain settings
Then custom domain changes are unavailable until a provider is chosen
When the organiser chooses Stripe for existing payments
Then custom domain changes are available again

@rule:payments.provider-recovery-blocks-host-subdomain
Rule: A host subdomain cannot be registered before provider recovery is complete
The organiser may check a name, but cannot register it until the provider
for existing payments is known.

@case:payments.recovery-blocks-host-subdomain
Scenario: The organiser recovers the provider before registering a host subdomain
Given provider recovery is needed and both domain options are available
When the organiser checks whether the host subdomain "mylisting" is available
Then host subdomain registration is unavailable until a provider is chosen
When the organiser chooses Stripe for existing payments
And the organiser checks whether the host subdomain "mylisting" is available
Then host subdomain registration is available again
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
When the organiser registers the host subdomain "mylisting"
Then the host subdomain "mylisting.tickets" is registered
8 changes: 3 additions & 5 deletions src/features/admin/require-provider.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import {
getActivePaymentProvider,
getPaymentProviderForExistingPayments,
type PaymentProvider,
} from "#shared/payments.ts";

/** The active payment provider, or the caller's `onMissing` fallback (a redirect
* or error Response) when none is configured. The refund and refresh POSTs share
* this "need a provider before we touch money" guard instead of each re-checking. */
/** Uses the existing-payment provider so refunds still work while sales are off. */
export const requirePaymentProvider = async <T>(
onMissing: () => T,
): Promise<PaymentProvider | T> => {
const provider = await getActivePaymentProvider();
const provider = await getPaymentProviderForExistingPayments();
return provider ?? onMissing();
};
Loading