@fantastic.dev/better-stripe 0.45.1 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/MIGRATION.md +6 -4
- package/README.md +8 -6
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +23 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +46 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/refundSync.d.ts +32 -0
- package/dist/client/connect/refundSync.d.ts.map +1 -0
- package/dist/client/connect/refundSync.js +61 -0
- package/dist/client/connect/refundSync.js.map +1 -0
- package/dist/client/connect/refundSyncValidation.d.ts +16 -0
- package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
- package/dist/client/connect/refundSyncValidation.js +87 -0
- package/dist/client/connect/refundSyncValidation.js.map +1 -0
- package/dist/client/index.d.ts +30 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +5 -0
- package/dist/client/index.js.map +1 -1
- package/dist/component/_generated/api.d.ts +12 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +67 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/connect/mutations.d.ts.map +1 -1
- package/dist/component/connect/mutations.js +2 -53
- package/dist/component/connect/mutations.js.map +1 -1
- package/dist/component/connect/refundWrites.d.ts +6 -0
- package/dist/component/connect/refundWrites.d.ts.map +1 -0
- package/dist/component/connect/refundWrites.js +56 -0
- package/dist/component/connect/refundWrites.js.map +1 -0
- package/dist/component/earnings/triggers.d.ts +46 -0
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/refundHistory/originalSeller.d.ts +1 -1
- package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
- package/dist/component/refundHistory/originalSeller.js.map +1 -1
- package/dist/component/refundSync/helpers.d.ts +43 -0
- package/dist/component/refundSync/helpers.d.ts.map +1 -0
- package/dist/component/refundSync/helpers.js +71 -0
- package/dist/component/refundSync/helpers.js.map +1 -0
- package/dist/component/refundSync/mutations.d.ts +56 -0
- package/dist/component/refundSync/mutations.d.ts.map +1 -0
- package/dist/component/refundSync/mutations.js +113 -0
- package/dist/component/refundSync/mutations.js.map +1 -0
- package/dist/component/refundSync/queries.d.ts +12 -0
- package/dist/component/refundSync/queries.d.ts.map +1 -0
- package/dist/component/refundSync/queries.js +10 -0
- package/dist/component/refundSync/queries.js.map +1 -0
- package/dist/component/refundSync/routing.d.ts +8 -0
- package/dist/component/refundSync/routing.d.ts.map +1 -0
- package/dist/component/refundSync/routing.js +42 -0
- package/dist/component/refundSync/routing.js.map +1 -0
- package/dist/component/refundSync/schema.d.ts +25 -0
- package/dist/component/refundSync/schema.d.ts.map +1 -0
- package/dist/component/refundSync/schema.js +15 -0
- package/dist/component/refundSync/schema.js.map +1 -0
- package/dist/component/refundSync/validators.d.ts +164 -0
- package/dist/component/refundSync/validators.d.ts.map +1 -0
- package/dist/component/refundSync/validators.js +32 -0
- package/dist/component/refundSync/validators.js.map +1 -0
- package/dist/component/schema.d.ts +23 -0
- package/dist/component/schema.js +2 -0
- package/dist/component/schema.js.map +1 -1
- package/docs/affiliate-clawbacks.md +3 -3
- package/docs/architecture/component-extraction.md +415 -0
- package/docs/architecture/durable-execution.md +200 -0
- package/docs/architecture/recovery-workflow.md +69 -0
- package/docs/balance-funding-state.md +114 -0
- package/docs/balance-funding-workflow.md +53 -0
- package/docs/example-balance-funding-cutover.md +94 -0
- package/docs/example-recovery-cutover.md +21 -0
- package/docs/processing-cost-reconciliation.md +23 -0
- package/docs/refund-context.md +54 -0
- package/docs/release-handoff.md +196 -0
- package/docs/releasing.md +41 -0
- package/package.json +12 -2
- package/src/client/connect/refundSync.test.ts +239 -0
- package/src/client/connect/refundSync.transport.test.ts +396 -0
- package/src/client/connect/refundSync.ts +125 -0
- package/src/client/connect/refundSyncValidation.ts +120 -0
- package/src/client/index.ts +19 -0
- package/src/component/_generated/api.ts +12 -0
- package/src/component/_generated/component.ts +100 -0
- package/src/component/connect/mutations.ts +2 -67
- package/src/component/connect/refundWrites.ts +76 -0
- package/src/component/refundHistory/originalSeller.ts +4 -1
- package/src/component/refundSync/helpers.ts +99 -0
- package/src/component/refundSync/mutations.ts +131 -0
- package/src/component/refundSync/queries.ts +10 -0
- package/src/component/refundSync/refund-sync.test.ts +255 -0
- package/src/component/refundSync/routing.ts +55 -0
- package/src/component/refundSync/schema.ts +19 -0
- package/src/component/refundSync/validators.ts +35 -0
- package/src/component/schema.ts +2 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Durable recovery groups
|
|
2
|
+
|
|
3
|
+
`stripe.costRecovery.startGroup` runs an already prepared and sealed recovery
|
|
4
|
+
group. The host authorizes the account, scope, currency, source and economic
|
|
5
|
+
allocation before starting. Settlement allocations must include the group's
|
|
6
|
+
exact signed recovery adjustment. The component pins the entire allocation and
|
|
7
|
+
rejects a different allocation, policy, callback, provider handle or API version
|
|
8
|
+
on replay. One settlement source can belong to only one workflow operation.
|
|
9
|
+
`requestKey` is an immutable identity within one BetterStripe component;
|
|
10
|
+
different callers must namespace their keys.
|
|
11
|
+
|
|
12
|
+
The host supplies an internal action reference as `provider`. Its validators
|
|
13
|
+
must accept `RecoveryProviderRequest`. Inside that action, call
|
|
14
|
+
`stripe.costRecovery.executeGroupProvider(ctx, args, {
|
|
15
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY! })`. This options object exists
|
|
16
|
+
only during action execution. Never place credentials in `startGroup`, workflow
|
|
17
|
+
arguments, operation records, callback arguments or logs. The adapter constructs
|
|
18
|
+
a fresh Stripe client using the pinned API version and zero automatic network
|
|
19
|
+
retries. Existing `attachInvoice`, `reconcileInvoice`, settlement execution and
|
|
20
|
+
reserve/seal/finish APIs retain their behavior.
|
|
21
|
+
|
|
22
|
+
The provider action receives only a scoped operation reference, phase and pinned
|
|
23
|
+
versions. The adapter reads the immutable saved inputs and verifies an active
|
|
24
|
+
persisted dispatch before contacting Stripe. Its receipt echoes those references
|
|
25
|
+
and versions plus the source ID. A component bridge rejects unknown fields or
|
|
26
|
+
identity mismatches and sanitizes exceptions before returning a receipt to the
|
|
27
|
+
Workflow journal. It never persists provider response objects or messages.
|
|
28
|
+
|
|
29
|
+
Settlement execution reuses the existing transfer and affiliate allocation
|
|
30
|
+
ledger and its original idempotency keys. Reconciliation reads bounded transfer
|
|
31
|
+
history, mirrors verified transfers and confirms earnings without creating
|
|
32
|
+
missing transfers. Invoice execution reuses the original recovery invoice-item
|
|
33
|
+
key and item binding protocol. Invoice history is capped at 10,000 items;
|
|
34
|
+
incomplete history cannot authorize another write. The host still owns invoice
|
|
35
|
+
creation, finalization/payment policy, seller eligibility and reporting.
|
|
36
|
+
`releaseUncollectible` is an explicit immutable policy; paid invoices collect,
|
|
37
|
+
void invoices release, and uncollectible invoices release only when authorized.
|
|
38
|
+
Other invoice states retain the reservation.
|
|
39
|
+
|
|
40
|
+
`getGroupOperation`, `resumeGroup` and `requestGroupCancel` require the full saved
|
|
41
|
+
scope, operation ID and version. The SDK projects these fields from returned
|
|
42
|
+
statuses before invoking strict component validators. Only known readiness
|
|
43
|
+
observations receive automatic retries, at most `maxAttempts` (1–20) with the
|
|
44
|
+
explicit bounded `retryDelayMs`. An unknown provider effect waits for an explicit
|
|
45
|
+
`resumeGroup`, which performs reconciliation only. Missing transfers, ambiguous
|
|
46
|
+
history or failed reads never trigger new money writes or release reservations.
|
|
47
|
+
|
|
48
|
+
Each Workflow segment has at most 20 provider observations and 20 finish batches
|
|
49
|
+
(of at most 10 reservation operations each). `resumeGroup` continues an exhausted
|
|
50
|
+
or infrastructure-failed segment under the original operation and money keys.
|
|
51
|
+
A persisted verified receipt takes priority: continuation finishes the ledger
|
|
52
|
+
without contacting the provider. Failed receipt/finish/completion database steps
|
|
53
|
+
restart from the failed step while retaining earlier journaled results. No new
|
|
54
|
+
financial execution identity is allocated during resume.
|
|
55
|
+
|
|
56
|
+
An optional internal mutation `completion` runs after successful ledger finish.
|
|
57
|
+
It receives `RecoveryOperationStatus`, must perform database work only and must
|
|
58
|
+
use the operation ID/version as its projection identity. Its database changes
|
|
59
|
+
and the operation's completed status commit atomically. A callback failure can
|
|
60
|
+
be resumed without repeating the provider effect. It is a success callback;
|
|
61
|
+
cancellation does not invoke it.
|
|
62
|
+
|
|
63
|
+
Cancellation before provider dispatch stops execution and keeps the sealed
|
|
64
|
+
reservation. Cancellation during an action cannot undo the provider effect: a
|
|
65
|
+
verified success still completes collection and the callback, with
|
|
66
|
+
`cancelRequested: true`. An uncertain in-flight result keeps the reservation and
|
|
67
|
+
requires reconciliation. A canceled status therefore never means funds were
|
|
68
|
+
released. Hosts must retire their legacy orchestration for a group before using
|
|
69
|
+
this workflow; mixing independent executors defeats ownership of the operation.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Durable balance-funding state
|
|
2
|
+
|
|
3
|
+
The `balanceFunding` component domain implements the persistence boundary from
|
|
4
|
+
[the extraction contract](architecture/component-extraction.md). It stores opaque
|
|
5
|
+
host scope, verified original payment settings, consent reference and timestamp,
|
|
6
|
+
provider API version, operation identity/version, phase keys, receipts and pending
|
|
7
|
+
target. Host code authenticates callers, authorizes the account/subscription,
|
|
8
|
+
captures consent and selects policy before invoking any component method.
|
|
9
|
+
|
|
10
|
+
This domain does not call Stripe or run a workflow. Provider orchestration and
|
|
11
|
+
preview-version opt-in remain the funding workflow workstream. No credentials
|
|
12
|
+
belong in scope keys, consent references, provider receipts, durable arguments or
|
|
13
|
+
operation state. The component's tables are an execution journal, not a money
|
|
14
|
+
ledger.
|
|
15
|
+
|
|
16
|
+
## Preparation and immutable intent
|
|
17
|
+
|
|
18
|
+
The low-level `mutations.prepare` takes the verified original settings in
|
|
19
|
+
`preparation` without a balance payment-method ID, plus `accountId`, `scopeKey`,
|
|
20
|
+
`consent: true`, `consentAt`, `consentReference`, `providerApiVersion` and
|
|
21
|
+
`requestKey`. The runtime must obtain these settings before any create/attach
|
|
22
|
+
write. This persists a pending preparation operation and stable `providerKey`
|
|
23
|
+
and create/attach phase keys. The runtime never recaptures original settings
|
|
24
|
+
from an already-enabled subscription.
|
|
25
|
+
|
|
26
|
+
`finishPreparation` accepts the complete operation reference, verified preparation
|
|
27
|
+
including the new payment-method ID, and the same provider API version. It checks
|
|
28
|
+
the captured restoration settings and active version before saving the result.
|
|
29
|
+
Null and empty restoration values remain distinct. Exact completion is idempotent;
|
|
30
|
+
a contradictory result rejects. A canceled or stale operation cannot finish.
|
|
31
|
+
|
|
32
|
+
The host-facing preparation lookup is `queries.getPreparation`: pass account,
|
|
33
|
+
scope, subscription, operation ID and version. Only a succeeded preparation
|
|
34
|
+
operation returns `status: "prepared"` and its original preparation ID. Pending,
|
|
35
|
+
running, unknown, failed and canceled results expose only operation identity and state,
|
|
36
|
+
with an optional safe failure code.
|
|
37
|
+
Foreign or contradictory bindings return an explicit unavailable outcome. Missing
|
|
38
|
+
operations return null, which does not authorize another provider effect. Recover
|
|
39
|
+
a lost prepare response by replaying its original public request key. Before any
|
|
40
|
+
provider/settings/consent-time recapture, call `findPreparationOperation` with
|
|
41
|
+
account, scope, subscription, request key, API version and `consent: true`.
|
|
42
|
+
This read-only lookup verifies the saved prepare-kind and all those bindings,
|
|
43
|
+
returning only safe operation state/reference or conflict/null. Then call
|
|
44
|
+
`getPreparation` for that same operation. Unknown and failed requests recover
|
|
45
|
+
the original identity without exposing restoration data or phase keys. Null is
|
|
46
|
+
not proof of no provider effect or permission to create a replacement. A new key
|
|
47
|
+
never permits recapturing already-enabled settings or replacing unresolved work.
|
|
48
|
+
Exact low-level prepare snapshots, including consent time, remain immutable.
|
|
49
|
+
|
|
50
|
+
## Apply, inspect and cancel
|
|
51
|
+
|
|
52
|
+
`begin` accepts the saved preparation ID, account/scope, desired `enabled`,
|
|
53
|
+
explicit enable consent and a request key. New request keys bind the full payload;
|
|
54
|
+
replaying one returns the original result even after completion. A changed payload
|
|
55
|
+
conflicts. Same-target pending intents reuse the active operation; opposite targets
|
|
56
|
+
conflict. A scope alias cannot acquire a second preparation or evade the
|
|
57
|
+
account/subscription boundary. New versions are positive safe integers.
|
|
58
|
+
|
|
59
|
+
`start` transitions pending work to running before provider execution. Repeated
|
|
60
|
+
start of running or unknown work does not establish permission to repeat an effect.
|
|
61
|
+
`markUnknown` retains the active claim when the provider outcome is uncertain.
|
|
62
|
+
`finish` checks operation identity, version, target, account/subscription, API
|
|
63
|
+
version and exact observed payment settings before updating enabled state.
|
|
64
|
+
A repeated old completion returns its original receipt without changing a newer
|
|
65
|
+
setting. Provider reconciliation remains necessary after transport uncertainty.
|
|
66
|
+
|
|
67
|
+
`requestCancel` cancels unstarted work and releases its claim transactionally.
|
|
68
|
+
For running/unknown work it records `cancelRequested` and retains the claim until
|
|
69
|
+
the original provider result is reconciled. A successful effect remains succeeded
|
|
70
|
+
even when cancellation was requested. Cancellation never restores payment settings
|
|
71
|
+
or reverses a provider effect by itself.
|
|
72
|
+
|
|
73
|
+
`getOperation` returns safe identity/state/cancellation fields. The server-only
|
|
74
|
+
`readPreparation` and `inspectOperation` queries return restoration data or phase
|
|
75
|
+
keys for trusted provider actions. They require the saved account, scope and
|
|
76
|
+
subscription; operation inspection also requires operation ID/version. Never
|
|
77
|
+
forward those raw records or receipts to browser-facing queries. Status/lookup
|
|
78
|
+
results contain no restoration settings or credentials.
|
|
79
|
+
|
|
80
|
+
`failBeforeStart` records a terminal `failed` state only while the intent is still
|
|
81
|
+
pending, before provider execution begins. It accepts only `invalid_scope`,
|
|
82
|
+
`unsupported_source` or `policy_invalid`, never a provider message. The same
|
|
83
|
+
request replay retains the failed operation; a fresh intent gets a new version
|
|
84
|
+
and phase keys. Running and unknown operations cannot use this transition or
|
|
85
|
+
release their claim. It does not classify provider exceptions or prove no effect
|
|
86
|
+
after provider execution has begun; those paths require reconciliation. Status
|
|
87
|
+
and preparation lookup expose the safe code without restoration data.
|
|
88
|
+
|
|
89
|
+
## Import and migration pause
|
|
90
|
+
|
|
91
|
+
`savePreparation` is for verified complete legacy preparations. Exact replay
|
|
92
|
+
returns the existing ID; changed restoration, scope, consent or API version
|
|
93
|
+
rejects. It does not overwrite existing records.
|
|
94
|
+
|
|
95
|
+
`importPreparation` also preserves the legacy enabled state, operation version,
|
|
96
|
+
pending target and exact provider base key. Its source key binds the complete
|
|
97
|
+
import payload. Exact replay remains a no-op after the imported operation has
|
|
98
|
+
advanced; changed imports reject transactionally. A different source cannot
|
|
99
|
+
replace an existing account/subscription record.
|
|
100
|
+
|
|
101
|
+
Imported pending operations start unknown and paused. Pending preparation imports
|
|
102
|
+
use `pending.kind: "prepare"` and may omit the balance payment-method ID. Preserve
|
|
103
|
+
`example_balance_prepare_${subscriptionId}` for their base key and its create/
|
|
104
|
+
attach suffixes. Pending apply imports preserve
|
|
105
|
+
`example_balance_${subscriptionId}_${version}` and enable/disable suffixes. Never
|
|
106
|
+
replace a legacy key with the new-operation namespace.
|
|
107
|
+
|
|
108
|
+
`setStartsPaused` blocks new intents and pending-to-running transitions while
|
|
109
|
+
keeping original status, cancellation, receipt reconciliation and completion
|
|
110
|
+
available. Imports begin paused; resume starts only after stopping the old writer
|
|
111
|
+
and checking the imported state. A paused replay can recover an existing intent,
|
|
112
|
+
but cannot authorize a new provider effect. Pause old starts rather than disabling
|
|
113
|
+
finish handlers needed to reconcile in-flight receipts. Rollback requires one
|
|
114
|
+
writer and verified state; reverting code alone cannot undo provider effects.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Durable balance funding
|
|
2
|
+
|
|
3
|
+
`BetterStripe.balanceFundingWorkflow` adds component-owned preparation and apply workflows. The existing `prepareBalanceFunding` and `setBalanceFunding` methods remain available. The new interface requires explicit `STRIPE_CUSTOMER_PREVIEW_API_VERSION` configuration; the provider action checks the actual Stripe SDK version against the immutable operation snapshot before admitting a provider phase. Stripe still determines live account and preview eligibility.
|
|
4
|
+
|
|
5
|
+
The host authorizes the account, subscription and opaque scope, records consent, and supplies an internal provider action reference. Construct the Stripe client inside that action using the host's runtime secret. The component stores only the function handle, immutable scope/API/definition versions, phase keys and allowlisted receipts. Never put keys, raw provider objects, raw exceptions or restoration settings into workflow arguments or completion context.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {
|
|
9
|
+
BetterStripe,
|
|
10
|
+
STRIPE_CUSTOMER_PREVIEW_API_VERSION,
|
|
11
|
+
} from "@fantastic.dev/better-stripe";
|
|
12
|
+
|
|
13
|
+
// Host internal action. Instantiate BetterStripe at execution, not in durable args.
|
|
14
|
+
const stripe = () =>
|
|
15
|
+
new BetterStripe(components.betterStripe, {
|
|
16
|
+
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
|
|
17
|
+
stripeApiVersion: STRIPE_CUSTOMER_PREVIEW_API_VERSION,
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// The action's args validator must match FundingProviderPhaseOptions:
|
|
21
|
+
// accountId, scopeKey, operationId, version, stripeSubscriptionId,
|
|
22
|
+
// providerApiVersion, definitionVersion, phase (create|attach|apply), providerKey.
|
|
23
|
+
// Use ordinary string validators for component operation IDs in the host.
|
|
24
|
+
export const fundingProvider = internalAction({
|
|
25
|
+
args: providerPhaseArgs,
|
|
26
|
+
handler: (ctx, args) =>
|
|
27
|
+
stripe().balanceFundingWorkflow.executeProviderPhase(ctx, args),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Inside an authorized host action:
|
|
31
|
+
const result = await stripe().balanceFundingWorkflow.prepare(ctx, {
|
|
32
|
+
accountId,
|
|
33
|
+
scopeKey,
|
|
34
|
+
stripeSubscriptionId,
|
|
35
|
+
requestKey,
|
|
36
|
+
consent: true,
|
|
37
|
+
consentAt,
|
|
38
|
+
consentReference,
|
|
39
|
+
providerAction: internal.billing.fundingProvider,
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`prepare` recovers the original public request before reading provider settings again. A new request for an existing canonical preparation uses its original consent and restoration snapshot. Capture performs read-only provider calls; the component persists that snapshot before scheduling create or attach. Duplicate requests join the bound workflow. A successful preparation does not enable funding: use the existing safe `getPreparation` query to obtain a verified preparation ID, then call `apply(ctx, { accountId, scopeKey, stripeSubscriptionId, preparationId, enabled, consent, requestKey, providerAction })`. Enabling requires consent. Disabling restores the persisted original payment method and nullable payment-method-type settings, never current subscription prices or host metadata.
|
|
44
|
+
|
|
45
|
+
`inspect(ctx, operationReference)` returns only scoped operation state, version and cancellation state. `resume` and `cancel` accept the same account/scope/subscription/operation/version reference. These control paths do not instantiate Stripe or require its secret. The host must authorize these operations before calling them; component APIs are server capabilities, not browser authorization policies.
|
|
46
|
+
|
|
47
|
+
Every provider phase has one atomic dispatch claim and its original idempotency key. SDK write retries and Workflow action retries are disabled. A lost create response with no verified payment-method ID remains held: ordinary PaymentMethod reads cannot prove which unattached resource was created. Resume never creates another method in that state. Unknown attachment or apply outcomes use known-ID, read-only provider reconciliation; an inconclusive readback stays held and does not repeat the write. Conflicting targets cannot replace the active operation or its original restoration settings.
|
|
48
|
+
|
|
49
|
+
Positive receipts are persisted before the bridge returns and again in a separate workflow mutation. If storage fails after provider success, retained, scope-bound provider journal receipts can restore canonical evidence. Resume restarts only a known failed step or finishes from complete verified receipts; it does not repeat completed provider effects. Cancellation is a request, not proof that an in-flight provider call stopped. It retains uncertain claims and restoration data; known positive receipts may still be reconciled and finished afterward.
|
|
50
|
+
|
|
51
|
+
Operations pin `balance-funding/v1` and their original provider API version. A changed definition or API version is held rather than replayed. Compatible old definitions and pinned host provider configuration must remain available while operations are incomplete. History reads are bounded and require completeness. Cleaned, missing or incompatible history cannot authorize a new workflow or effect; retained operation receipts are never deleted by this interface. Do not clean workflow history while uncertain operations still need reconciliation.
|
|
52
|
+
|
|
53
|
+
This proves durable local orchestration and conservative replay boundaries, not exactly-once provider effects. Tests use the actual nested Workflow/Workpool components and real Stripe SDK transport with synthetic responses. The local installation uses a dummy key and does not establish live Stripe eligibility or perform live provider writes.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Example balance-funding cutover
|
|
2
|
+
|
|
3
|
+
The cutover moves the example's financial preparation and execution into the installed
|
|
4
|
+
BetterStripe component. `storeBalanceRequests` stores host consent intents and
|
|
5
|
+
component references, not provider execution history. Queueing and initial
|
|
6
|
+
scheduling happen in one mutation. A ten-minute observer watchdog makes abandoned pending intents held and
|
|
7
|
+
retryable. Watchdogs are fenced by an observation epoch; an obsolete timeout
|
|
8
|
+
cannot hold a newer retry. Same-target retries reschedule even an existing pending
|
|
9
|
+
intent and retain its original request and financial operation.
|
|
10
|
+
Provider writes and uncertain outcomes belong to the component workflow.
|
|
11
|
+
|
|
12
|
+
The example still enforces sandbox mode, seller role, current account and plan,
|
|
13
|
+
and the subscription's `storeBilling` and `sellerId` metadata. It uses demo
|
|
14
|
+
personas. Production hosts must derive the seller from an authenticated session.
|
|
15
|
+
No migration action runs automatically on deploy. Starting a payment-source change
|
|
16
|
+
migrates that seller's existing legacy record first, if one exists.
|
|
17
|
+
|
|
18
|
+
## Compatibility and verification
|
|
19
|
+
|
|
20
|
+
Keep the old `storeBalanceFunding` rows and original host functions throughout
|
|
21
|
+
the compatibility window. The importer preserves original method/type restoration
|
|
22
|
+
settings, including `null` versus an empty list, consent timestamp, operation
|
|
23
|
+
version and provider keys. It pins the legacy `2026-09-30.preview` API version.
|
|
24
|
+
It never prepares again from a subscription whose settings have already changed.
|
|
25
|
+
|
|
26
|
+
Before import, old starts are paused. A late old finish is allowed before the
|
|
27
|
+
snapshot is imported; the snapshot hash then changes and must be read again.
|
|
28
|
+
After import, old finishes are rejected and must reconcile the component receipt.
|
|
29
|
+
Unknown legacy operations have no workflow journal. First stop and drain every legacy worker that could still dispatch its old
|
|
30
|
+
provider key, then record an operator audit reference for that exact source
|
|
31
|
+
snapshot. Only after this attestation can scoped, verified Stripe readback finish
|
|
32
|
+
the operation. Matching target settings alone do not prove an old worker stopped. Missing, mismatched or ambiguous evidence stays held;
|
|
33
|
+
it does not start another workflow or provider write.
|
|
34
|
+
|
|
35
|
+
The action verifies original account, subscription metadata and payment-method
|
|
36
|
+
ownership. Import and its checkpoint commit together, with the source hash and
|
|
37
|
+
current seller binding checked again. Replacement accounts or subscriptions are
|
|
38
|
+
held for explicit review. Original source rows are never deleted by this adapter.
|
|
39
|
+
|
|
40
|
+
For a pending legacy row, pause and read its `fundingId` and `snapshot` using
|
|
41
|
+
`storeBalance/funding/internal/migration:pause`. After independently stopping and
|
|
42
|
+
draining old workers, call
|
|
43
|
+
`storeBalance/funding/internal/quiescence:confirm` with those values and a bounded
|
|
44
|
+
`reference` identifying the operational audit. This is a trusted operator
|
|
45
|
+
attestation, not an automated proof. Do not confirm it while an old provider call
|
|
46
|
+
could still complete. Re-run the seller migration or backfill after confirmation.
|
|
47
|
+
A changed legacy snapshot invalidates the attestation.
|
|
48
|
+
|
|
49
|
+
## Bounded backfill
|
|
50
|
+
|
|
51
|
+
Use an isolated sandbox first. Run these internal functions with the intended
|
|
52
|
+
example deployment selected. Do not point this runbook at another app's database.
|
|
53
|
+
An operator needs the deployment's admin authorization.
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
pnpm --filter ./example exec convex run storeBalance/backfill/mutations:start '{}'
|
|
57
|
+
# Copy the returned runId into each following command.
|
|
58
|
+
pnpm --filter ./example exec convex run storeBalance/backfill/actions:step '{"runId":"..."}'
|
|
59
|
+
pnpm --filter ./example exec convex run storeBalance/backfill/queries:state '{"runId":"..."}'
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Starting a run fences all legacy starts before scanning. Each `step` processes at
|
|
63
|
+
most ten rows. The reserved page is persisted before provider reads; interrupted
|
|
64
|
+
actions replay it. Acknowledgements use the saved cursor and count each page once.
|
|
65
|
+
Counts are derived from current scoped component state. Repeat `step` while the
|
|
66
|
+
run is `running`. `verified` means `scanned === active` and `held === 0` at the
|
|
67
|
+
checkpoint. It is not proof that live Stripe preview eligibility exists or that
|
|
68
|
+
later external changes cannot occur.
|
|
69
|
+
|
|
70
|
+
A run with unresolved rows finishes as `held`. Reconcile those original records,
|
|
71
|
+
then call `start` with `{"rescan":true}` to audit all rows again. Do not delete
|
|
72
|
+
source records or disable compatibility readers solely because a scan ended.
|
|
73
|
+
Check pending component operations and actual Stripe settings before retirement.
|
|
74
|
+
The component remains the sole financial writer after activation; a repeated
|
|
75
|
+
scan reads its current verified state rather than restoring the old enabled flag.
|
|
76
|
+
|
|
77
|
+
## Rollback
|
|
78
|
+
|
|
79
|
+
Before a global run starts, `funding/internal/migration:rollback` can restore the
|
|
80
|
+
legacy writer for one record only if its original source hash, enabled state and
|
|
81
|
+
operation version still match, with no active component operation. It pauses
|
|
82
|
+
component starts before releasing the old writer. This is a data rollback, not a
|
|
83
|
+
Stripe reversal.
|
|
84
|
+
|
|
85
|
+
After new component operations or a global run, that shortcut is rejected. Pause
|
|
86
|
+
starts, reconcile pending provider outcomes and explicitly verify a reverse
|
|
87
|
+
mapping before a reviewed deployment rollback. Never recreate old operation
|
|
88
|
+
versions or reuse an old provider key for a different effect. Retain component
|
|
89
|
+
history and original source records until the compatibility audit is complete.
|
|
90
|
+
|
|
91
|
+
The sandbox renewal retry reads only verified, enabled component funding with no
|
|
92
|
+
active operation and no paused starts. It cannot collect using a stale legacy
|
|
93
|
+
payment-method record. An insufficient balance does not authorize card fallback;
|
|
94
|
+
that remains an explicit seller recovery choice.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Example recovery cutover
|
|
2
|
+
|
|
3
|
+
The example keeps seller eligibility, original catalog ownership, affiliate allocation, store plan commission, webhook routing and reporting projections. The component owns reservation preparation, provider execution, retries, receipt persistence, collection and processing-cost rollback.
|
|
4
|
+
|
|
5
|
+
Settlement and plan-invoice entry points enqueue component recovery workflows. A provider action reads its credentials at execution time. The host `recoveryJobs` table contains routing and operation references only; component claims and reservations remain the financial ledger. `sellerCosts.workflow.queries.list` exposes bounded operation status, and `blockedSummary` returns at most 100 blocked jobs with an explicit `hasMore` flag. These queries follow the example's existing selected-seller authorization model.
|
|
6
|
+
|
|
7
|
+
A settlement with no owned recovery reservation retains the existing direct payout policy, including when another invoice owns the active recovery group. An owned reservation uses the durable workflow. Replayed events resume the same operation; a saved receipt can finish a failed database projection without another provider call. Processing-cost reconciliation supplies the host's explicit deficit policy, independently pins main and rollback claim revisions, and adopts an eligible legacy claim and its host marker in the same transaction as the final projection.
|
|
8
|
+
|
|
9
|
+
## Legacy records
|
|
10
|
+
|
|
11
|
+
Existing sealed, unattempted groups can start the new workflow. Existing collected settlement groups require exact transfer mirrors for every positive allocation leg before the host marks the sale settled. A partially collecting settlement group uses those same verified mirrors and finishes one bounded database batch per invocation. It never creates a new transfer or provider idempotency key.
|
|
12
|
+
|
|
13
|
+
Invoice compatibility uses `costRecovery.verifyInvoiceReceipt`. This read-only method requires the previously bound item, exact account/scope/invoice/currency/amount bindings, one unambiguous item and complete history within five pages and 500 items. It uses GETs only and performs no item binding or financial mutation. Unknown, incomplete or malformed evidence leaves reservations held. A verified paid invoice can continue an already collecting group; a verified void invoice can continue an already releasing group. The host never switches the persisted direction because a later invoice was canceled. Each invocation finishes one bounded database batch and schedules another invocation if needed.
|
|
14
|
+
|
|
15
|
+
Legacy transfer attempts with no conclusive mirror, unmapped historical recovery amounts, and unknown in-flight groups stay blocked. Their status identifies `legacy_inflight_unknown`, `legacy_mapping_required` or `settlement_pending`. Operators must establish an explicit historical mapping and receipt before retrying. The cutover does not infer a collected group, forgive a claim, run a backfill, or release an unknown provider attempt. The legacy import helper retains its invoice and pending-settlement guards.
|
|
16
|
+
|
|
17
|
+
A refund before new settlement dispatch cancels the workflow and keeps the sealed reservation held. An in-flight refund also holds the reservation until the existing settlement is reconciled. Cancellation alone does not release financial reservations. These cases require explicit manual resolution when no verified completion exists. If a blocked cost observation was waiting for settlement, a verified settlement projection schedules reconciliation against the now-collected group.
|
|
18
|
+
|
|
19
|
+
## Verification
|
|
20
|
+
|
|
21
|
+
Co-located tests run real nested component workflows and cover duplicate events, provider success followed by failed host projection, explicit resume, unknown attempts, original catalog ownership, cancellation, independent revision guards, legacy import/projection atomicity and observable blocked status. Eleven-reservation fixtures cover partially completed legacy settlement and invoice collections, release direction, replay and mismatched proof. Provider-boundary fixtures exercise the host adapters without live Stripe requests; separate package tests use the actual Stripe SDK transport to verify GET-only invoice proof, pagination caps and mismatches.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Processing-cost reconciliation
|
|
2
|
+
|
|
3
|
+
`betterStripe.costRecovery.startProcessingCostReconciliation` observes provider costs and records a revised deficit in the existing recovery ledger. It never collects money itself. A host supplies authorization, an internal provider action, an explicit deficit policy, and optional internal import/projection mutations. Use `startRecoveryWorkflow` separately to collect the resulting ledger balance.
|
|
4
|
+
|
|
5
|
+
The immutable request binds account, scope, currency, claim key, original payment and gross, expected claim revision, policy, provider/API definition version, callback handles, and retry bounds. Reusing a request key with a changed binding returns `identity_changed`. A scoped payment retains one claim key. Original selling fee and verified provenance cannot change after the first completed observation. A changed authoritative claim revision returns `revision_changed`; a new host decision must use a new request and the newly read revision. Resume never refreshes it implicitly.
|
|
6
|
+
|
|
7
|
+
## Provider action boundary
|
|
8
|
+
|
|
9
|
+
The host's internal action receives only the scoped operation reference and pinned versions. Call `betterStripe.costRecovery.observeProcessingCosts(ctx, request, { stripeSecretKey })` inside that action. Resolve credentials there; never put them in operation arguments, callback payloads, or Workflow state. The adapter creates a fresh Stripe client pinned to the saved API version, disables SDK network retries, and only issues GET requests. The component bridge validates a closed receipt before Workflow journals it. Provider bodies, metadata, credentials, and exception text are excluded.
|
|
10
|
+
|
|
11
|
+
Sale mode verifies the original invoice payment and historical price/product using the payment-source resolver. It does not infer provenance from metadata or a current subscription item. Explicit `invoice_recovery` mode requires a matching collected invoice recovery group and rollback group. It verifies the bound invoice item, the full invoice amount, one complete forward and inverse funding relationship, the original charge, and its fee. This mode carries invoice/item/funding provenance and does not invent a price or product.
|
|
12
|
+
|
|
13
|
+
Provider histories are limited to five pages and 500 items per collection. Repeated IDs, malformed pages, exhausted budgets, incomplete histories, partial funding, and ambiguous funding fail closed. Unknown and unavailable observations never write zero costs. Known `not_ready` outcomes retry up to `maxAttempts` (1–20); unknown outcomes stop for explicit host resume. Resume performs read-only observation again, using the same binding and revision guards.
|
|
14
|
+
|
|
15
|
+
## Atomic adoption, rollback, and projections
|
|
16
|
+
|
|
17
|
+
Use `expectedRevision: -1` for an absent live claim. An optional import hook runs only when that claim is absent, after identity and revision checks. The host verifies its historical record and returns either `null` or an opening snapshot containing an immutable `operationKey`, `amountDue`, `collectedAmount`, and `revision`. The component imports through the existing opening-claim ledger and advances that revision once. A host migration marker written by the hook shares the transaction; hook or projection failure rolls back both host and component changes.
|
|
18
|
+
|
|
19
|
+
An optional rollback binds a collected original recovery group and its own `expectedRevision`. Its revision guard is independent of the main claim. The original group's funding identity and economics must match the observed payment before any import, claim, rollback, or funding-binding write. Refund/dispute principal adjusts the existing rollback claim. A later won dispute can reduce an already collected rollback obligation into a ledger credit without collecting or releasing funds again.
|
|
20
|
+
|
|
21
|
+
The projection callback is a database-only internal mutation invoked with the completed scoped result. It shares the transaction with both claim updates and completion. A failed projection leaves all changes unapplied. Resume restarts the failed apply step using its saved provider observation, without reading the provider again. Completed operation replay returns its original result even after newer operations have advanced the ledger; it never rewrites that newer state.
|
|
22
|
+
|
|
23
|
+
Host store eligibility, liability policy, economic allocation, reports, and migration cutover remain host decisions. The component stores generic operation metadata and uses existing claims, opening imports, balances, and rollback reservations for financial accounting.
|
package/docs/refund-context.md
CHANGED
|
@@ -82,3 +82,57 @@ PaymentIntent's refund authority. Deny ambiguous cross-invoice/community scopes
|
|
|
82
82
|
until a safe original-payment binding is established. A ready zero remainder
|
|
83
83
|
must not enable another refund. This reader does not grant authority to remove
|
|
84
84
|
access, cancel a subscription or change the original financial recipients.
|
|
85
|
+
|
|
86
|
+
## Current refund synchronization
|
|
87
|
+
|
|
88
|
+
`betterStripe.syncRefundFromStripe(ctx, { stripeRefundId, scope })` is a separate
|
|
89
|
+
trusted-host operation. It retrieves the current provider refund and synchronizes
|
|
90
|
+
the existing component refund/payment projection. It never creates or cancels a
|
|
91
|
+
refund, reverses transfers, changes access or authorizes a retry. Hosts must
|
|
92
|
+
authenticate and authorize the original refund and provider API scope before
|
|
93
|
+
calling it; the method is not an application authorization boundary.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
const observation = await betterStripe.syncRefundFromStripe(ctx, {
|
|
97
|
+
stripeRefundId: originalRefundId,
|
|
98
|
+
scope: { type: "platform" },
|
|
99
|
+
});
|
|
100
|
+
// Or use { type: "connected", accountId: trustedOriginalApiAccount }.
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The API namespace is required and runtime validated before component/provider
|
|
104
|
+
access. A connected API account is not a buyer, destination merchant or seller
|
|
105
|
+
entitlement. Provider metadata cannot select that account. Original merchant
|
|
106
|
+
attribution uses the existing immutable store-allocation proof, or the original
|
|
107
|
+
charge's destination when needed to qualify a legacy destination fallback.
|
|
108
|
+
Known original merchant/PI/charge/currency/amount disagreement or ambiguous evidence
|
|
109
|
+
holds the observation. An unattributed refund can remain unattributed where no
|
|
110
|
+
legacy destination fallback would invent an owner. This does not establish seller
|
|
111
|
+
authorization or historical ingestion completeness.
|
|
112
|
+
|
|
113
|
+
Each current read receives a durable per-refund generation. Only the newest
|
|
114
|
+
claimed generation can commit the qualified snapshot and existing cumulative
|
|
115
|
+
payment projection together. An older completion returns `superseded` without
|
|
116
|
+
writing that snapshot, including when the newer read failed. Superseded is not
|
|
117
|
+
proof that any newer observation succeeded. `accepted` returns the generation,
|
|
118
|
+
`changed` and stored refund; it is an observation, not financial completion.
|
|
119
|
+
Current `succeeded` may legitimately become `requires_action`, `pending` or later
|
|
120
|
+
failure. No status ordering, provider revision or webhook timestamp is invented.
|
|
121
|
+
|
|
122
|
+
Provider or accepting-transaction failures propagate rather than falling back to
|
|
123
|
+
a notification snapshot. A failed pending generation is marked unknown when that
|
|
124
|
+
marker can be saved. Lost responses can leave a pending or accepted generation;
|
|
125
|
+
a fresh explicit observation obtains a new generation. It does not dispatch a
|
|
126
|
+
refund. The original cumulative writer remains a complete indexed collection of
|
|
127
|
+
all refund rows for the payment, excluding failed/canceled contributions. Failed
|
|
128
|
+
history is not cardinality bounded: native resource limits can abort the whole
|
|
129
|
+
accepting transaction, preserving the last committed projection. There is no
|
|
130
|
+
partial sum, silent truncation or all-backlog-capacity guarantee.
|
|
131
|
+
|
|
132
|
+
This primitive does **not** yet route the legacy signed refund webhook pipeline
|
|
133
|
+
through generation qualification. Legacy `upsertRefund` and raw callbacks remain
|
|
134
|
+
unfenced; they can still overwrite observations outside this operation. The
|
|
135
|
+
separate shared-pipeline integration must preserve generation qualification
|
|
136
|
+
through its callback transaction before hosts claim webhook-wide convergence.
|
|
137
|
+
The server-only Vite reference is
|
|
138
|
+
[`example/convex/connect/refundSync.ts`](../example/convex/connect/refundSync.ts).
|