@fantastic.dev/better-stripe 0.40.0 → 0.42.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.
Files changed (183) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/client/balanceFundingWorkflow/client.d.ts +172 -0
  4. package/dist/client/balanceFundingWorkflow/client.d.ts.map +1 -0
  5. package/dist/client/balanceFundingWorkflow/client.js +289 -0
  6. package/dist/client/balanceFundingWorkflow/client.js.map +1 -0
  7. package/dist/client/billing/balanceFunding.d.ts +5 -0
  8. package/dist/client/billing/balanceFunding.d.ts.map +1 -1
  9. package/dist/client/billing/balanceFunding.js +30 -0
  10. package/dist/client/billing/balanceFunding.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +808 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +404 -1
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +808 -2
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +404 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +2 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +4 -1
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +5 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +3 -1
  26. package/dist/client/costRecovery.js.map +1 -1
  27. package/dist/client/index.d.ts +3 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +4 -0
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  32. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  33. package/dist/client/recoveryWorkflow/client.js +34 -0
  34. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  35. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  36. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  37. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  38. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  39. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  40. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  41. package/dist/client/recoveryWorkflow/provider.js +80 -0
  42. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  43. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  44. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  45. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  46. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  47. package/dist/component/_generated/api.d.ts +30 -0
  48. package/dist/component/_generated/api.d.ts.map +1 -1
  49. package/dist/component/_generated/api.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +637 -0
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  53. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  54. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  55. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  56. package/dist/component/balanceFunding/internal/actions.js +80 -0
  57. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  58. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  59. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  61. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  62. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  63. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/queries.js +35 -0
  65. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  67. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  69. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  70. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  71. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  72. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  73. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  74. package/dist/component/balanceFunding/mutations.js +24 -0
  75. package/dist/component/balanceFunding/mutations.js.map +1 -1
  76. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  77. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  78. package/dist/component/balanceFunding/queries.d.ts +78 -0
  79. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/queries.js +35 -0
  81. package/dist/component/balanceFunding/queries.js.map +1 -1
  82. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  83. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  84. package/dist/component/balanceFunding/receipt.js +37 -0
  85. package/dist/component/balanceFunding/receipt.js.map +1 -0
  86. package/dist/component/balanceFunding/schema.d.ts +506 -2
  87. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/schema.js +2 -0
  89. package/dist/component/balanceFunding/schema.js.map +1 -1
  90. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  91. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  92. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  93. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  94. package/dist/component/balanceFunding/workflowControl.js +149 -0
  95. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  96. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  97. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  98. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  99. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  100. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  101. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowState.js +194 -0
  103. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  105. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  107. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  108. package/dist/component/earnings/triggers.d.ts +280 -2
  109. package/dist/component/earnings/triggers.d.ts.map +1 -1
  110. package/dist/component/payoutRelease/queries.d.ts +2 -2
  111. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  112. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  113. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  114. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  115. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  116. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  117. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  118. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  119. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  120. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  121. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  122. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  123. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  124. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  125. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  126. package/dist/component/recoveryWorkflow/queries.js +20 -0
  127. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  128. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  129. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  130. package/dist/component/recoveryWorkflow/schema.js +81 -0
  131. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  132. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  133. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  134. package/dist/component/recoveryWorkflow/steps.js +94 -0
  135. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  136. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  137. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  138. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  139. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  140. package/dist/component/schema.d.ts +404 -1
  141. package/dist/component/schema.js +3 -0
  142. package/dist/component/schema.js.map +1 -1
  143. package/package.json +1 -1
  144. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  145. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  146. package/src/client/billing/balanceFunding.ts +50 -0
  147. package/src/client/costRecovery-invoices.ts +6 -0
  148. package/src/client/costRecovery.ts +8 -3
  149. package/src/client/index.ts +15 -0
  150. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  151. package/src/client/recoveryWorkflow/client.ts +76 -0
  152. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  153. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  154. package/src/client/recoveryWorkflow/provider.ts +119 -0
  155. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  156. package/src/component/_generated/api.ts +30 -0
  157. package/src/component/_generated/component.ts +746 -0
  158. package/src/component/balanceFunding/internal/actions.ts +107 -0
  159. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  160. package/src/component/balanceFunding/internal/queries.ts +34 -0
  161. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  162. package/src/component/balanceFunding/mutations.ts +34 -0
  163. package/src/component/balanceFunding/queries.ts +38 -0
  164. package/src/component/balanceFunding/receipt.ts +48 -0
  165. package/src/component/balanceFunding/schema.ts +2 -0
  166. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  167. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  168. package/src/component/balanceFunding/workflow.test.ts +552 -0
  169. package/src/component/balanceFunding/workflowControl.ts +198 -0
  170. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  171. package/src/component/balanceFunding/workflowState.ts +285 -0
  172. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  173. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  174. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  175. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  176. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  177. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  178. package/src/component/recoveryWorkflow/queries.ts +19 -0
  179. package/src/component/recoveryWorkflow/schema.ts +92 -0
  180. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  181. package/src/component/recoveryWorkflow/steps.ts +97 -0
  182. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  183. package/src/component/schema.ts +6 -0
@@ -0,0 +1,72 @@
1
+ import type { FunctionReference } from "convex/server";
2
+ import type { RecoveryScope } from "../costRecovery.js";
3
+ import type { ResolvedSettlement } from "../settlement/execution.js";
4
+ export type RecoveryOperationRef = RecoveryScope & {
5
+ groupKey: string;
6
+ operationId: string;
7
+ version: number;
8
+ };
9
+ export type RecoveryOperationStatus = RecoveryOperationRef & {
10
+ sourceKind: "settlement" | "invoice";
11
+ sourceId: string;
12
+ status:
13
+ "queued" | "running" | "waiting" | "unknown" | "completed" | "canceled";
14
+ cancelRequested: boolean;
15
+ outcome?: "collect" | "release";
16
+ };
17
+ export type RecoveryProviderRequest = RecoveryOperationRef & {
18
+ phase: "execute" | "reconcile";
19
+ providerApiVersion: string;
20
+ definitionVersion: number;
21
+ };
22
+ export type RecoveryProviderReceipt = RecoveryProviderRequest & {
23
+ sourceId: string;
24
+ } & (
25
+ | { status: "ready"; outcome: "collect" | "release" }
26
+ | { status: "not_ready"; reason: "provider_pending" }
27
+ | { status: "unknown"; reason: "provider_outcome_unknown" }
28
+ );
29
+ export type RecoveryStartOptions = RecoveryScope & {
30
+ groupKey: string;
31
+ requestKey: string;
32
+ provider: FunctionReference<
33
+ "action",
34
+ "internal",
35
+ RecoveryProviderRequest,
36
+ RecoveryProviderReceipt
37
+ >;
38
+ completion?: FunctionReference<
39
+ "mutation",
40
+ "internal",
41
+ RecoveryOperationStatus,
42
+ unknown
43
+ >;
44
+ providerApiVersion: string;
45
+ definitionVersion: 1;
46
+ releaseUncollectible: boolean;
47
+ allocation?: ResolvedSettlement;
48
+ maxAttempts?: number;
49
+ retryDelayMs?: number;
50
+ };
51
+ export type RecoveryStartResult =
52
+ | RecoveryOperationStatus
53
+ | { status: "conflict"; reason: "identity_changed"; retryable: false }
54
+ | { status: "not_ready"; reason: "history_incomplete"; retryable: true };
55
+ export type RecoverySnapshot = RecoveryOperationStatus & {
56
+ providerStarted: boolean;
57
+ activePhase?: "execute" | "reconcile";
58
+ providerApiVersion: string;
59
+ definitionVersion: number;
60
+ allocation?: ResolvedSettlement;
61
+ releaseUncollectible: boolean;
62
+ };
63
+ export function operationRef(op: RecoveryOperationRef): RecoveryOperationRef {
64
+ return {
65
+ accountId: op.accountId,
66
+ scopeKey: op.scopeKey,
67
+ currency: op.currency,
68
+ groupKey: op.groupKey,
69
+ operationId: op.operationId,
70
+ version: op.version,
71
+ };
72
+ }
@@ -0,0 +1,424 @@
1
+ import Stripe from "stripe";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import { componentsGeneric, type FunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { initConvexTest } from "../setup.test.js";
6
+ import schema from "../../component/schema.js";
7
+ import { CostRecoveryClient } from "../costRecovery.js";
8
+ import type { Component, RunCtx } from "../helpers.js";
9
+ import type { RecoveryProviderRequest } from "./contracts.js";
10
+ const modules = import.meta.glob("../../component/**/*.ts");
11
+ const nested = componentsGeneric();
12
+ const scope = {
13
+ accountId: "acct_owner",
14
+ scopeKey: "store",
15
+ currency: "usd",
16
+ groupKey: "group",
17
+ };
18
+ async function setup(
19
+ kind: "invoice" | "settlement" = "invoice",
20
+ dispatch = true,
21
+ releaseUncollectible = false,
22
+ ) {
23
+ const t = initConvexTest();
24
+ t.registerComponent("betterStripe", schema, modules);
25
+ workflowTest.register(t, "betterStripe/workflow");
26
+ const component = nested.betterStripe as unknown as Component;
27
+ const client = new CostRecoveryClient(component);
28
+ let writes = 0,
29
+ failWrite = 0;
30
+ const ctx = {
31
+ runQuery: (
32
+ ref: FunctionReference<"query">,
33
+ args: Record<string, unknown>,
34
+ ) => t.query(ref, args),
35
+ runMutation: (
36
+ ref: FunctionReference<"mutation">,
37
+ args: Record<string, unknown>,
38
+ ) => {
39
+ if (++writes === failWrite) throw new Error("private database detail");
40
+ return t.mutation(ref, args);
41
+ },
42
+ } as unknown as RunCtx;
43
+ await client.recordClaim(ctx, {
44
+ accountId: scope.accountId,
45
+ scopeKey: scope.scopeKey,
46
+ currency: scope.currency,
47
+ claimKey: "claim",
48
+ sourceChargeId: "ch_original",
49
+ sourceGross: 1000,
50
+ sourceProcessingFee: 30,
51
+ amountDue: 30,
52
+ revision: 1,
53
+ });
54
+ const allocation = {
55
+ sourceChargeId: "ch_source",
56
+ gross: 1000,
57
+ currency: "usd",
58
+ processingFee: 30,
59
+ platformNet: 40,
60
+ adjustmentAmount: 30,
61
+ transfers: [
62
+ {
63
+ destinationAccountId: "acct_seller",
64
+ role: "store" as const,
65
+ amount: 900,
66
+ },
67
+ ],
68
+ };
69
+ await client.prepareGroup(ctx, {
70
+ ...scope,
71
+ ...(kind === "settlement"
72
+ ? {
73
+ sourceKind: "settlement" as const,
74
+ sourceId: "ch_source",
75
+ sourceGross: 1000,
76
+ sourceProcessingFee: 30,
77
+ }
78
+ : { sourceKind: "invoice" as const, sourceId: "in_source" }),
79
+ maxDebit: 1000,
80
+ maxCredit: 0,
81
+ });
82
+ const op = await t.mutation(
83
+ nested.betterStripe.recoveryWorkflow.mutations.start,
84
+ {
85
+ ...scope,
86
+ requestKey: "request",
87
+ provider: "function://fixture/provider",
88
+ providerApiVersion: "2026-09-30.endive",
89
+ definitionVersion: 1,
90
+ releaseUncollectible,
91
+ maxAttempts: 2,
92
+ retryDelayMs: 1,
93
+ ...(kind === "settlement" ? { allocation } : {}),
94
+ },
95
+ );
96
+ const request: RecoveryProviderRequest = {
97
+ ...scope,
98
+ operationId: op.operationId,
99
+ version: op.version,
100
+ phase: "execute",
101
+ providerApiVersion: "2026-09-30.endive",
102
+ definitionVersion: 1,
103
+ };
104
+ if (dispatch)
105
+ await t.mutation(nested.betterStripe.recoveryWorkflow.steps.beginProvider, {
106
+ ...scope,
107
+ operationId: op.operationId,
108
+ version: 1,
109
+ phase: "execute",
110
+ });
111
+ return {
112
+ dispatchReconcile: () =>
113
+ t.mutation(nested.betterStripe.recoveryWorkflow.steps.beginProvider, {
114
+ ...scope,
115
+ operationId: op.operationId,
116
+ version: 1,
117
+ phase: "reconcile",
118
+ }),
119
+ t,
120
+ client,
121
+ ctx,
122
+ request,
123
+ group: (await client.getGroup(ctx, { groupKey: scope.groupKey }))!,
124
+ failNext: (offset = 1) => {
125
+ failWrite = writes + offset;
126
+ },
127
+ };
128
+ }
129
+ it("recovers invoice-item provider success/database failure with the real Stripe SDK and original key", async () => {
130
+ const f = await setup();
131
+ let status = "draft";
132
+ let item: Record<string, unknown> | null = null;
133
+ let creates = 0;
134
+ const headers: {
135
+ version: string | null;
136
+ authorized: boolean;
137
+ key: string | null;
138
+ }[] = [];
139
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
140
+ const h = new Headers(init?.headers);
141
+ headers.push({
142
+ version: h.get("Stripe-Version"),
143
+ authorized: h.get("Authorization") === "Bearer sk_test_runtime_only",
144
+ key: h.get("Idempotency-Key"),
145
+ });
146
+ let body: unknown;
147
+ if (String(url).includes("/invoices/"))
148
+ body = {
149
+ id: "in_source",
150
+ customer_account: scope.accountId,
151
+ currency: "usd",
152
+ status,
153
+ };
154
+ else if (init?.method === "POST") {
155
+ creates++;
156
+ item = {
157
+ id: "ii_recovery",
158
+ invoice: "in_source",
159
+ customer_account: scope.accountId,
160
+ currency: "usd",
161
+ amount: 30,
162
+ discountable: false,
163
+ metadata: { bsRecoveryGroup: f.group._id },
164
+ };
165
+ body = item;
166
+ } else body = { object: "list", data: item ? [item] : [], has_more: false };
167
+ return new Response(JSON.stringify(body), {
168
+ status: 200,
169
+ headers: { "content-type": "application/json" },
170
+ });
171
+ });
172
+ f.failNext();
173
+ expect(
174
+ await f.client.executeGroupProvider(f.ctx, f.request, {
175
+ stripeSecretKey: "sk_test_runtime_only",
176
+ httpClient,
177
+ }),
178
+ ).toMatchObject({ status: "unknown" });
179
+ expect(creates).toBe(1);
180
+ status = "paid";
181
+ await f.dispatchReconcile();
182
+ expect(
183
+ await f.client.executeGroupProvider(
184
+ f.ctx,
185
+ { ...f.request, phase: "reconcile" },
186
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
187
+ ),
188
+ ).toMatchObject({
189
+ status: "ready",
190
+ outcome: "collect",
191
+ sourceId: "in_source",
192
+ });
193
+ expect(creates).toBe(1);
194
+ expect(
195
+ headers.every(
196
+ (h) => h.authorized && h.version === f.request.providerApiVersion,
197
+ ),
198
+ ).toBe(true);
199
+ expect(headers.find((h) => h.key)?.key).toBe(
200
+ `better-stripe:recovery:${f.group._id}`,
201
+ );
202
+ expect(
203
+ (await f.client.getGroup(f.ctx, { groupKey: scope.groupKey }))?.status,
204
+ ).toBe("sealed");
205
+ });
206
+ it("recovers a successful transfer after mirror failure without another provider write", async () => {
207
+ const f = await setup("settlement");
208
+ let transfer: Record<string, unknown> | null = null;
209
+ let creates = 0;
210
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
211
+ let body: unknown;
212
+ if (String(url).includes("/charges/"))
213
+ body = { id: "ch_source", created: 1 };
214
+ else if (init?.method === "POST") {
215
+ creates++;
216
+ transfer = {
217
+ id: "tr_source",
218
+ destination: "acct_seller",
219
+ amount: 900,
220
+ currency: "usd",
221
+ source_transaction: "ch_source",
222
+ amount_reversed: 0,
223
+ metadata: { bsRole: "store", bsSourceCharge: "ch_source" },
224
+ };
225
+ body = transfer;
226
+ } else
227
+ body = {
228
+ object: "list",
229
+ data: transfer ? [transfer] : [],
230
+ has_more: false,
231
+ };
232
+ return new Response(JSON.stringify(body), {
233
+ status: 200,
234
+ headers: { "content-type": "application/json" },
235
+ });
236
+ });
237
+ f.failNext(2); // Reserve allocation succeeds; transfer mirror fails after provider success.
238
+ expect(
239
+ await f.client.executeGroupProvider(f.ctx, f.request, {
240
+ stripeSecretKey: "sk_test_runtime_only",
241
+ httpClient,
242
+ }),
243
+ ).toMatchObject({ status: "unknown" });
244
+ expect(creates).toBe(1);
245
+ await f.dispatchReconcile();
246
+ expect(
247
+ await f.client.executeGroupProvider(
248
+ f.ctx,
249
+ { ...f.request, phase: "reconcile" },
250
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
251
+ ),
252
+ ).toMatchObject({ status: "ready", outcome: "collect" });
253
+ expect(creates).toBe(1);
254
+ expect(
255
+ await f.t.query(nested.betterStripe.connect.queries.listTransfersByCharge, {
256
+ sourceChargeId: "ch_source",
257
+ }),
258
+ ).toMatchObject([{ stripeTransferId: "tr_source", amount: 900 }]);
259
+ });
260
+ it("holds missing settlement legs on reconciliation and never creates them", async () => {
261
+ const f = await setup("settlement");
262
+ let creates = 0;
263
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
264
+ if (init?.method === "POST") creates++;
265
+ const body = String(url).includes("/charges/")
266
+ ? { id: "ch_source", created: 1 }
267
+ : { object: "list", data: [], has_more: false };
268
+ return new Response(JSON.stringify(body), {
269
+ status: 200,
270
+ headers: { "content-type": "application/json" },
271
+ });
272
+ });
273
+ await f.dispatchReconcile();
274
+ expect(
275
+ await f.client.executeGroupProvider(
276
+ f.ctx,
277
+ { ...f.request, phase: "reconcile" },
278
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
279
+ ),
280
+ ).toMatchObject({ status: "unknown" });
281
+ expect(creates).toBe(0);
282
+ });
283
+
284
+ it("refuses provider work without an active persisted dispatch", async () => {
285
+ const f = await setup("invoice", false);
286
+ let calls = 0;
287
+ const httpClient = Stripe.createFetchHttpClient(async () => {
288
+ calls++;
289
+ return new Response("{}", { status: 200 });
290
+ });
291
+ expect(
292
+ await f.client.executeGroupProvider(f.ctx, f.request, {
293
+ stripeSecretKey: "sk_test_runtime_only",
294
+ httpClient,
295
+ }),
296
+ ).toMatchObject({ status: "unknown" });
297
+ expect(calls).toBe(0);
298
+ });
299
+ it("holds incomplete invoice history instead of creating an item after the scan bound", async () => {
300
+ const f = await setup();
301
+ let creates = 0;
302
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
303
+ if (init?.method === "POST") creates++;
304
+ const body = String(url).includes("/invoices/")
305
+ ? {
306
+ id: "in_source",
307
+ customer_account: scope.accountId,
308
+ currency: "usd",
309
+ status: "draft",
310
+ }
311
+ : {
312
+ object: "list",
313
+ data: Array.from({ length: 10001 }, (_, i) => ({
314
+ id: `ii_other_${i}`,
315
+ metadata: {},
316
+ })),
317
+ has_more: false,
318
+ };
319
+ return new Response(JSON.stringify(body), {
320
+ status: 200,
321
+ headers: { "content-type": "application/json" },
322
+ });
323
+ });
324
+ expect(
325
+ await f.client.executeGroupProvider(f.ctx, f.request, {
326
+ stripeSecretKey: "sk_test_runtime_only",
327
+ httpClient,
328
+ }),
329
+ ).toMatchObject({ status: "unknown" });
330
+ expect(creates).toBe(0);
331
+ });
332
+ it("rejects a changed provider definition or API version before transport", async () => {
333
+ const f = await setup();
334
+ let calls = 0;
335
+ const httpClient = Stripe.createFetchHttpClient(async () => {
336
+ calls++;
337
+ return new Response("{}", { status: 200 });
338
+ });
339
+ for (const patch of [
340
+ { providerApiVersion: "2026-01-01.changed" },
341
+ { definitionVersion: 2 },
342
+ { phase: "reconcile" as const },
343
+ ]) {
344
+ expect(
345
+ await f.client.executeGroupProvider(
346
+ f.ctx,
347
+ { ...f.request, ...patch },
348
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
349
+ ),
350
+ ).toMatchObject({ status: "unknown" });
351
+ }
352
+ expect(calls).toBe(0);
353
+ });
354
+ it("accepts a terminal void invoice without attempting to create an item", async () => {
355
+ const f = await setup();
356
+ let creates = 0;
357
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
358
+ if (init?.method === "POST") creates++;
359
+ const body = String(url).includes("/invoices/")
360
+ ? {
361
+ id: "in_source",
362
+ customer_account: scope.accountId,
363
+ currency: "usd",
364
+ status: "void",
365
+ }
366
+ : { object: "list", data: [], has_more: false };
367
+ return new Response(JSON.stringify(body), {
368
+ status: 200,
369
+ headers: { "content-type": "application/json" },
370
+ });
371
+ });
372
+ expect(
373
+ await f.client.executeGroupProvider(f.ctx, f.request, {
374
+ stripeSecretKey: "sk_test_runtime_only",
375
+ httpClient,
376
+ }),
377
+ ).toMatchObject({ status: "ready", outcome: "release" });
378
+ expect(creates).toBe(0);
379
+ });
380
+
381
+ it.each([false, true])(
382
+ "pins explicit uncollectible release policy %s",
383
+ async (release) => {
384
+ const f = await setup("invoice", true, release);
385
+ const httpClient = Stripe.createFetchHttpClient(async (url) => {
386
+ const body = String(url).includes("/invoices/")
387
+ ? {
388
+ id: "in_source",
389
+ customer_account: scope.accountId,
390
+ currency: "usd",
391
+ status: "uncollectible",
392
+ }
393
+ : {
394
+ object: "list",
395
+ data: [
396
+ {
397
+ id: "ii_recovery",
398
+ invoice: "in_source",
399
+ customer_account: scope.accountId,
400
+ currency: "usd",
401
+ amount: 30,
402
+ discountable: false,
403
+ metadata: { bsRecoveryGroup: f.group._id },
404
+ },
405
+ ],
406
+ has_more: false,
407
+ };
408
+ return new Response(JSON.stringify(body), {
409
+ status: 200,
410
+ headers: { "content-type": "application/json" },
411
+ });
412
+ });
413
+ expect(
414
+ await f.client.executeGroupProvider(f.ctx, f.request, {
415
+ stripeSecretKey: "sk_test_runtime_only",
416
+ httpClient,
417
+ }),
418
+ ).toMatchObject(
419
+ release
420
+ ? { status: "ready", outcome: "release" }
421
+ : { status: "not_ready", reason: "provider_pending" },
422
+ );
423
+ },
424
+ );
@@ -0,0 +1,119 @@
1
+ import Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { attachRecoveryInvoice } from "../costRecovery-invoices.js";
6
+ import type { RecoveryGroup } from "../costRecovery.js";
7
+ import { executeResolvedTransfers } from "../settlement/execution.js";
8
+ import { reconcileRecoverySettlement } from "./settlement.js";
9
+ import { operationRef } from "./contracts.js";
10
+ import type {
11
+ RecoveryProviderRequest,
12
+ RecoveryProviderReceipt,
13
+ RecoverySnapshot,
14
+ } from "./contracts.js";
15
+ export type RecoveryProviderOptions = {
16
+ /** Runtime-only secret, supplied inside the registered internal host action. */
17
+ stripeSecretKey: string;
18
+ httpClient?: NonNullable<
19
+ ConstructorParameters<typeof Stripe>[1]
20
+ >["httpClient"];
21
+ };
22
+ export async function executeRecoveryProvider(
23
+ component: Component,
24
+ ctx: RunCtx,
25
+ request: RecoveryProviderRequest,
26
+ options: RecoveryProviderOptions,
27
+ ): Promise<RecoveryProviderReceipt> {
28
+ const unknown = {
29
+ ...operationRef(request),
30
+ phase: request.phase,
31
+ providerApiVersion: request.providerApiVersion,
32
+ definitionVersion: request.definitionVersion,
33
+ sourceId: "",
34
+ status: "unknown",
35
+ reason: "provider_outcome_unknown",
36
+ } as const;
37
+ try {
38
+ const op = (await ctx.runQuery(
39
+ componentRef(component, "recoveryWorkflow/queries/snapshot"),
40
+ operationRef(request),
41
+ )) as RecoverySnapshot;
42
+ const base = {
43
+ ...operationRef(request),
44
+ phase: request.phase,
45
+ providerApiVersion: request.providerApiVersion,
46
+ definitionVersion: request.definitionVersion,
47
+ sourceId: op.sourceId,
48
+ };
49
+ if (
50
+ op.status !== "running" ||
51
+ !op.providerStarted ||
52
+ op.activePhase !== request.phase ||
53
+ op.providerApiVersion !== request.providerApiVersion ||
54
+ op.definitionVersion !== request.definitionVersion ||
55
+ request.definitionVersion !== 1 ||
56
+ (request.phase !== "execute" && request.phase !== "reconcile")
57
+ )
58
+ return { ...base, status: "unknown", reason: "provider_outcome_unknown" };
59
+ const stripe = new Stripe(options.stripeSecretKey, {
60
+ apiVersion: request.providerApiVersion as Stripe.LatestApiVersion,
61
+ maxNetworkRetries: 0,
62
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
63
+ });
64
+ if (op.sourceKind === "settlement") {
65
+ if (!op.allocation)
66
+ return {
67
+ ...base,
68
+ status: "unknown",
69
+ reason: "provider_outcome_unknown",
70
+ };
71
+ if (request.phase === "execute")
72
+ await executeResolvedTransfers(stripe, component, ctx, op.allocation);
73
+ else if (
74
+ !(await reconcileRecoverySettlement(
75
+ stripe,
76
+ component,
77
+ ctx,
78
+ op.allocation,
79
+ ))
80
+ )
81
+ return {
82
+ ...base,
83
+ status: "unknown",
84
+ reason: "provider_outcome_unknown",
85
+ };
86
+ return { ...base, status: "ready", outcome: "collect" };
87
+ }
88
+ const group = (await ctx.runQuery(
89
+ componentRef(component, "costRecovery/queries/group"),
90
+ { groupKey: op.groupKey },
91
+ )) as RecoveryGroup | null;
92
+ const bind = (invoiceItemId: string) =>
93
+ runMutationOrThrow(
94
+ ctx,
95
+ componentRef(component, "costRecovery/mutations/bindInvoiceItem"),
96
+ { groupKey: op.groupKey, invoiceItemId },
97
+ ) as Promise<RecoveryGroup>;
98
+ const create =
99
+ request.phase === "execute" &&
100
+ (await stripe.invoices.retrieve(op.sourceId)).status === "draft";
101
+ const receipt = create
102
+ ? await attachRecoveryInvoice(stripe, group, op, bind, true, 10000)
103
+ : await attachRecoveryInvoice(stripe, group, op, bind, false, 10000);
104
+ const outcome =
105
+ receipt.invoiceStatus === "paid"
106
+ ? "collect"
107
+ : receipt.invoiceStatus === "void" ||
108
+ (receipt.invoiceStatus === "uncollectible" &&
109
+ op.releaseUncollectible)
110
+ ? "release"
111
+ : null;
112
+ return outcome
113
+ ? { ...base, status: "ready", outcome }
114
+ : { ...base, status: "not_ready", reason: "provider_pending" };
115
+ } catch {
116
+ // Returning a closed outcome also prevents the host action from logging raw SDK failures.
117
+ return unknown;
118
+ }
119
+ }
@@ -0,0 +1,67 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import {
6
+ matchingTransfer,
7
+ sourceTransfers,
8
+ recordSettlementTransfer,
9
+ } from "../settlement/reconciliation.js";
10
+ import type { ResolvedSettlement } from "../settlement/execution.js";
11
+ /** Read-only provider recovery: missing legs never create a second money attempt. */
12
+ export async function reconcileRecoverySettlement(
13
+ stripe: Stripe,
14
+ component: Component,
15
+ ctx: RunCtx,
16
+ claim: ResolvedSettlement,
17
+ ): Promise<boolean> {
18
+ const effective = [];
19
+ for (const leg of claim.transfers) {
20
+ const earning =
21
+ leg.role === "affiliate" && leg.amount > 0
22
+ ? ((await ctx.runQuery(
23
+ componentRef(component, "affiliateRecovery/queries/getEarning"),
24
+ {
25
+ sourceChargeId: claim.sourceChargeId,
26
+ affiliateAccountId: leg.destinationAccountId,
27
+ },
28
+ )) as { _id: string; releaseAmount: number } | null)
29
+ : null;
30
+ if (leg.role === "affiliate" && leg.amount > 0 && !earning) return false;
31
+ effective.push({
32
+ leg: { ...leg, amount: earning?.releaseAmount ?? leg.amount },
33
+ earning,
34
+ });
35
+ }
36
+ let provider = await sourceTransfers(stripe, claim.sourceChargeId);
37
+ if (
38
+ effective.some(
39
+ ({ leg }) => leg.amount > 0 && !matchingTransfer(provider, claim, leg),
40
+ )
41
+ )
42
+ provider = [
43
+ ...new Map(
44
+ [
45
+ ...provider,
46
+ ...(await sourceTransfers(stripe, claim.sourceChargeId, true)),
47
+ ].map((t) => [t.id, t]),
48
+ ).values(),
49
+ ];
50
+ for (const { leg, earning } of effective) {
51
+ const transfer =
52
+ leg.amount > 0 ? matchingTransfer(provider, claim, leg) : undefined;
53
+ if (leg.amount > 0 && !transfer) return false;
54
+ if (transfer)
55
+ await recordSettlementTransfer(component, ctx, claim, leg, transfer);
56
+ if (earning)
57
+ await runMutationOrThrow(
58
+ ctx,
59
+ componentRef(component, "affiliateEarnings/mutations/confirmEarning"),
60
+ {
61
+ earningId: earning._id,
62
+ ...(transfer ? { stripeTransferId: transfer.id } : {}),
63
+ },
64
+ );
65
+ }
66
+ return true;
67
+ }