@fantastic.dev/better-stripe 0.39.0 → 0.41.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 (137) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +442 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +221 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +442 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +221 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/costRecovery-invoices.d.ts +2 -2
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +7 -6
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +5 -2
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +3 -1
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/index.d.ts +3 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +2 -2
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/paymentSource/client.d.ts +21 -0
  24. package/dist/client/paymentSource/client.d.ts.map +1 -0
  25. package/dist/client/paymentSource/client.js +8 -0
  26. package/dist/client/paymentSource/client.js.map +1 -0
  27. package/dist/client/paymentSource/contracts.d.ts +30 -0
  28. package/dist/client/paymentSource/contracts.d.ts.map +1 -0
  29. package/dist/client/paymentSource/contracts.js +16 -0
  30. package/dist/client/paymentSource/contracts.js.map +1 -0
  31. package/dist/client/paymentSource/economics.d.ts +12 -0
  32. package/dist/client/paymentSource/economics.d.ts.map +1 -0
  33. package/dist/client/paymentSource/economics.js +13 -0
  34. package/dist/client/paymentSource/economics.js.map +1 -0
  35. package/dist/client/paymentSource/funding.d.ts +10 -0
  36. package/dist/client/paymentSource/funding.d.ts.map +1 -0
  37. package/dist/client/paymentSource/funding.js +12 -0
  38. package/dist/client/paymentSource/funding.js.map +1 -0
  39. package/dist/client/paymentSource/history.d.ts +13 -0
  40. package/dist/client/paymentSource/history.d.ts.map +1 -0
  41. package/dist/client/paymentSource/history.js +41 -0
  42. package/dist/client/paymentSource/history.js.map +1 -0
  43. package/dist/client/paymentSource/resolver.d.ts +6 -0
  44. package/dist/client/paymentSource/resolver.d.ts.map +1 -0
  45. package/dist/client/paymentSource/resolver.js +222 -0
  46. package/dist/client/paymentSource/resolver.js.map +1 -0
  47. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  48. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  49. package/dist/client/recoveryWorkflow/client.js +34 -0
  50. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  51. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  52. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  53. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  54. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  55. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  56. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  57. package/dist/client/recoveryWorkflow/provider.js +80 -0
  58. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  59. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  60. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  61. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  62. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  63. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  64. package/dist/client/settlement/verifiedSale.js +4 -6
  65. package/dist/client/settlement/verifiedSale.js.map +1 -1
  66. package/dist/component/_generated/api.d.ts +12 -0
  67. package/dist/component/_generated/api.d.ts.map +1 -1
  68. package/dist/component/_generated/api.js.map +1 -1
  69. package/dist/component/_generated/component.d.ts +164 -0
  70. package/dist/component/_generated/component.d.ts.map +1 -1
  71. package/dist/component/earnings/triggers.d.ts +194 -0
  72. package/dist/component/earnings/triggers.d.ts.map +1 -1
  73. package/dist/component/payoutRelease/queries.d.ts +2 -2
  74. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  75. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  76. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  77. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  78. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  79. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  80. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  81. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  82. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  83. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  84. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  85. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  86. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  87. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  88. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  89. package/dist/component/recoveryWorkflow/queries.js +20 -0
  90. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  91. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  92. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  93. package/dist/component/recoveryWorkflow/schema.js +81 -0
  94. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  95. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  96. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  97. package/dist/component/recoveryWorkflow/steps.js +94 -0
  98. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  99. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  100. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  101. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  102. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  103. package/dist/component/schema.d.ts +221 -0
  104. package/dist/component/schema.js +3 -0
  105. package/dist/component/schema.js.map +1 -1
  106. package/docs/settlement.md +48 -0
  107. package/package.json +1 -1
  108. package/src/client/costRecovery-invoices.ts +9 -7
  109. package/src/client/costRecovery.ts +8 -3
  110. package/src/client/index.ts +6 -2
  111. package/src/client/paymentSource/client.ts +13 -0
  112. package/src/client/paymentSource/contracts.ts +33 -0
  113. package/src/client/paymentSource/economics.ts +20 -0
  114. package/src/client/paymentSource/funding.ts +23 -0
  115. package/src/client/paymentSource/history.ts +48 -0
  116. package/src/client/paymentSource/resolver.test.ts +582 -0
  117. package/src/client/paymentSource/resolver.ts +350 -0
  118. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  119. package/src/client/recoveryWorkflow/client.ts +76 -0
  120. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  121. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  122. package/src/client/recoveryWorkflow/provider.ts +119 -0
  123. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  124. package/src/client/settlement/verifiedSale.ts +4 -10
  125. package/src/component/_generated/api.ts +12 -0
  126. package/src/component/_generated/component.ts +222 -0
  127. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  128. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  129. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  130. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  131. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  132. package/src/component/recoveryWorkflow/queries.ts +19 -0
  133. package/src/component/recoveryWorkflow/schema.ts +92 -0
  134. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  135. package/src/component/recoveryWorkflow/steps.ts +97 -0
  136. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  137. package/src/component/schema.ts +6 -0
@@ -0,0 +1,350 @@
1
+ import type Stripe from "stripe";
2
+ import type {
3
+ FinancialOutcome,
4
+ FinancialUnavailable,
5
+ } from "../financialOutcomes/contracts.js";
6
+ import {
7
+ paymentSourceOptions,
8
+ type VerifiedPaymentSource,
9
+ type VerifiedPaymentSourceOptions,
10
+ } from "./contracts.js";
11
+ import { completeHistory } from "./history.js";
12
+ import { saleAmountFailure } from "./economics.js";
13
+ import { singleInvoiceFunding } from "./funding.js";
14
+
15
+ const reject = (
16
+ reason: Extract<FinancialUnavailable, { status: "rejected" }>["reason"],
17
+ ): FinancialUnavailable => ({ status: "rejected", reason, retryable: false });
18
+ const identity = (): FinancialUnavailable => ({
19
+ status: "conflict",
20
+ reason: "identity_changed",
21
+ retryable: false,
22
+ });
23
+ const incomplete = (): FinancialUnavailable => ({
24
+ status: "unknown",
25
+ reason: "history_incomplete",
26
+ retryable: false,
27
+ });
28
+ class SourceUnavailable extends Error {
29
+ constructor(readonly outcome: FinancialUnavailable) {
30
+ super(outcome.reason);
31
+ }
32
+ }
33
+ function requireSource(
34
+ condition: unknown,
35
+ outcome: FinancialUnavailable,
36
+ ): asserts condition {
37
+ if (!condition) throw new SourceUnavailable(outcome);
38
+ }
39
+ const objectId = (value: string | { id: string } | null | undefined) => {
40
+ const candidate = typeof value === "string" ? value : value?.id;
41
+ return typeof candidate === "string" && candidate.length > 0
42
+ ? candidate
43
+ : undefined;
44
+ };
45
+ const integer = (value: number) => Number.isSafeInteger(value) && value >= 0;
46
+
47
+ /** Read-only provenance. Current subscription items and application metadata never prove original price/funding. */
48
+ export async function resolveVerifiedPaymentSource(
49
+ stripe: Stripe,
50
+ input: VerifiedPaymentSourceOptions,
51
+ ): Promise<FinancialOutcome<VerifiedPaymentSource>> {
52
+ const parsed = paymentSourceOptions.safeParse(input);
53
+ if (!parsed.success) return reject("invalid_scope");
54
+ const opts = parsed.data;
55
+ const requestOptions = opts.stripeAccountId
56
+ ? { stripeAccount: opts.stripeAccountId }
57
+ : undefined;
58
+ try {
59
+ const payment = await stripe.paymentIntents.retrieve(
60
+ opts.paymentIntentId,
61
+ { expand: ["latest_charge.balance_transaction"] },
62
+ requestOptions,
63
+ );
64
+ requireSource(
65
+ payment.object === "payment_intent" &&
66
+ payment.id === opts.paymentIntentId,
67
+ identity(),
68
+ );
69
+ if (payment.status === "processing")
70
+ return {
71
+ status: "not_ready",
72
+ reason: "provider_pending",
73
+ retryable: true,
74
+ };
75
+ if (payment.status !== "succeeded") return reject("payment_not_payable");
76
+ const charge = payment.latest_charge;
77
+ if (!charge || typeof charge === "string")
78
+ return {
79
+ status: "not_ready",
80
+ reason: "provider_pending",
81
+ retryable: true,
82
+ };
83
+ requireSource(
84
+ charge.object === "charge" &&
85
+ typeof charge.id === "string" &&
86
+ !!charge.id &&
87
+ objectId(charge.payment_intent) === payment.id,
88
+ identity(),
89
+ );
90
+ requireSource(
91
+ payment.currency === opts.currency,
92
+ reject("currency_mismatch"),
93
+ );
94
+ requireSource(
95
+ integer(payment.amount_received) &&
96
+ payment.amount_received === opts.gross &&
97
+ payment.amount === opts.gross,
98
+ reject("unsupported_source"),
99
+ );
100
+ requireSource(
101
+ charge.paid &&
102
+ charge.captured &&
103
+ charge.status === "succeeded" &&
104
+ charge.amount_captured === opts.gross,
105
+ reject("unsupported_source"),
106
+ );
107
+ requireSource(
108
+ typeof payment.livemode === "boolean" &&
109
+ charge.livemode === payment.livemode,
110
+ identity(),
111
+ );
112
+ requireSource(
113
+ typeof payment.customer_account === "string" &&
114
+ !!payment.customer_account,
115
+ reject("unsupported_source"),
116
+ );
117
+ if (opts.customerAccountId)
118
+ requireSource(
119
+ payment.customer_account === opts.customerAccountId,
120
+ identity(),
121
+ );
122
+ const customerAccountId = payment.customer_account!;
123
+ const balanceRef = charge.balance_transaction;
124
+ if (!balanceRef)
125
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
126
+ const balance =
127
+ typeof balanceRef === "string"
128
+ ? await stripe.balanceTransactions.retrieve(
129
+ balanceRef,
130
+ {},
131
+ requestOptions,
132
+ )
133
+ : balanceRef;
134
+ if (typeof balanceRef === "string")
135
+ requireSource(balance.id === balanceRef, identity());
136
+ requireSource(
137
+ balance.object === "balance_transaction" &&
138
+ typeof balance.id === "string" &&
139
+ !!balance.id &&
140
+ objectId(balance.source) === charge.id,
141
+ identity(),
142
+ );
143
+ const amountFailure = saleAmountFailure(payment, charge, balance);
144
+ requireSource(amountFailure !== "currency", reject("currency_mismatch"));
145
+ requireSource(
146
+ !amountFailure &&
147
+ integer(balance.amount) &&
148
+ integer(balance.net) &&
149
+ balance.amount === opts.gross &&
150
+ balance.amount - balance.fee === balance.net,
151
+ reject("unsupported_source"),
152
+ );
153
+ const read = <T extends { id: string }>(
154
+ fetch: (
155
+ cursor: string | undefined,
156
+ limit: number,
157
+ ) => Promise<Stripe.ApiList<T>>,
158
+ ) => completeHistory(fetch, opts.maxHistoryPages, opts.maxHistoryItems);
159
+ const inverse = await read((cursor, limit) =>
160
+ stripe.invoicePayments.list(
161
+ {
162
+ payment: { type: "payment_intent", payment_intent: payment.id },
163
+ limit,
164
+ ...(cursor ? { starting_after: cursor } : {}),
165
+ },
166
+ requestOptions,
167
+ ),
168
+ );
169
+ if (inverse.status !== "complete") return inverse;
170
+ for (const row of inverse.data) {
171
+ requireSource(
172
+ row.object === "invoice_payment" &&
173
+ ["paid", "open", "canceled"].includes(row.status),
174
+ incomplete(),
175
+ );
176
+ requireSource(
177
+ row.payment.type === "payment_intent" &&
178
+ objectId(row.payment.payment_intent) === payment.id &&
179
+ row.livemode === payment.livemode,
180
+ identity(),
181
+ );
182
+ requireSource(
183
+ row.currency === opts.currency,
184
+ reject("currency_mismatch"),
185
+ );
186
+ }
187
+ const original = singleInvoiceFunding(inverse.data, opts.gross);
188
+ requireSource(original, reject("unsupported_source"));
189
+ const invoiceId = objectId(original!.invoice);
190
+ requireSource(invoiceId, identity());
191
+ if (opts.invoiceId) requireSource(invoiceId === opts.invoiceId, identity());
192
+ const invoice = await stripe.invoices.retrieve(
193
+ invoiceId!,
194
+ {},
195
+ requestOptions,
196
+ );
197
+ requireSource(
198
+ invoice.object === "invoice" &&
199
+ invoice.id === invoiceId &&
200
+ invoice.customer_account === customerAccountId &&
201
+ invoice.livemode === payment.livemode,
202
+ identity(),
203
+ );
204
+ requireSource(
205
+ invoice.currency === opts.currency,
206
+ reject("currency_mismatch"),
207
+ );
208
+ if (invoice.status !== "paid")
209
+ return {
210
+ status: "not_ready",
211
+ reason: "provider_pending",
212
+ retryable: true,
213
+ };
214
+ requireSource(
215
+ [invoice.amount_paid, invoice.amount_due, invoice.total].every(
216
+ (value) => integer(value) && value === opts.gross,
217
+ ) &&
218
+ invoice.amount_remaining === 0 &&
219
+ invoice.amount_overpaid === 0,
220
+ reject("unsupported_source"),
221
+ );
222
+ const funding = await read((cursor, limit) =>
223
+ stripe.invoicePayments.list(
224
+ {
225
+ invoice: invoice.id,
226
+ limit,
227
+ ...(cursor ? { starting_after: cursor } : {}),
228
+ },
229
+ requestOptions,
230
+ ),
231
+ );
232
+ if (funding.status !== "complete") return funding;
233
+ for (const row of funding.data) {
234
+ requireSource(
235
+ row.object === "invoice_payment" &&
236
+ ["paid", "open", "canceled"].includes(row.status),
237
+ incomplete(),
238
+ );
239
+ requireSource(
240
+ objectId(row.invoice) === invoice.id &&
241
+ row.livemode === payment.livemode,
242
+ identity(),
243
+ );
244
+ requireSource(
245
+ row.currency === opts.currency,
246
+ reject("currency_mismatch"),
247
+ );
248
+ }
249
+ const funded = singleInvoiceFunding(funding.data, invoice.amount_paid);
250
+ requireSource(funded, reject("unsupported_source"));
251
+ requireSource(
252
+ funded!.id === original!.id &&
253
+ objectId(funded!.payment.payment_intent) === payment.id,
254
+ identity(),
255
+ );
256
+ requireSource(
257
+ original!.amount_requested === opts.gross &&
258
+ funded!.amount_requested === opts.gross,
259
+ reject("unsupported_source"),
260
+ );
261
+ const subscriptionId = objectId(
262
+ invoice.parent?.subscription_details?.subscription,
263
+ );
264
+ if (opts.subscriptionId)
265
+ requireSource(subscriptionId === opts.subscriptionId, identity());
266
+ if (subscriptionId) {
267
+ const subscription = await stripe.subscriptions.retrieve(
268
+ subscriptionId,
269
+ {},
270
+ requestOptions,
271
+ );
272
+ requireSource(
273
+ subscription.object === "subscription" &&
274
+ subscription.id === subscriptionId &&
275
+ subscription.customer_account === customerAccountId &&
276
+ subscription.livemode === payment.livemode,
277
+ identity(),
278
+ );
279
+ }
280
+ const lines = await read((cursor, limit) =>
281
+ stripe.invoices.listLineItems(
282
+ invoice.id,
283
+ { limit, ...(cursor ? { starting_after: cursor } : {}) },
284
+ requestOptions,
285
+ ),
286
+ );
287
+ if (lines.status !== "complete") return lines;
288
+ requireSource(lines.data.length === 1, reject("unsupported_source"));
289
+ const line = lines.data[0]!;
290
+ requireSource(
291
+ line.object === "line_item" &&
292
+ line.invoice === invoice.id &&
293
+ line.livemode === payment.livemode,
294
+ identity(),
295
+ );
296
+ requireSource(line.currency === opts.currency, reject("currency_mismatch"));
297
+ requireSource(
298
+ integer(line.amount) &&
299
+ line.amount > 0 &&
300
+ Number.isSafeInteger(line.quantity) &&
301
+ line.quantity! > 0,
302
+ reject("unsupported_source"),
303
+ );
304
+ const parent = line.parent;
305
+ const lineSubscription =
306
+ parent?.subscription_item_details?.subscription ??
307
+ parent?.invoice_item_details?.subscription ??
308
+ undefined;
309
+ requireSource(lineSubscription === subscriptionId, identity());
310
+ requireSource(
311
+ !parent?.subscription_item_details?.proration &&
312
+ !parent?.invoice_item_details?.proration,
313
+ reject("unsupported_source"),
314
+ );
315
+ const price = line.pricing?.price_details;
316
+ const priceId = objectId(price?.price);
317
+ const productId = objectId(price?.product);
318
+ requireSource(
319
+ line.pricing?.type === "price_details" && priceId && productId,
320
+ reject("unsupported_source"),
321
+ );
322
+ return {
323
+ status: "ready",
324
+ value: {
325
+ paymentIntentId: payment.id,
326
+ chargeId: charge.id,
327
+ invoiceId: invoice.id,
328
+ invoicePaymentId: funded!.id,
329
+ ...(subscriptionId ? { subscriptionId } : {}),
330
+ customerAccountId,
331
+ ...(opts.stripeAccountId
332
+ ? { stripeAccountId: opts.stripeAccountId }
333
+ : {}),
334
+ stripePriceId: priceId,
335
+ stripeProductId: productId,
336
+ gross: opts.gross,
337
+ processingFee: balance.fee,
338
+ currency: opts.currency,
339
+ livemode: payment.livemode,
340
+ },
341
+ };
342
+ } catch (error) {
343
+ if (error instanceof SourceUnavailable) return error.outcome;
344
+ return {
345
+ status: "unknown",
346
+ reason: "provider_outcome_unknown",
347
+ retryable: false,
348
+ };
349
+ }
350
+ }
@@ -0,0 +1,37 @@
1
+ import { componentsGeneric } from "convex/server";
2
+ import { expect, it } from "vitest";
3
+ import { CostRecoveryClient } from "../costRecovery.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ it("projects operation refs before sending them to strict component validators", async () => {
6
+ let actual: unknown;
7
+ const client = new CostRecoveryClient(
8
+ componentsGeneric().betterStripe as unknown as Component,
9
+ );
10
+ const ctx = {
11
+ runQuery: async (_ref: unknown, args: unknown) => {
12
+ actual = args;
13
+ return args;
14
+ },
15
+ } as unknown as RunCtx;
16
+ const op = {
17
+ accountId: "acct_a",
18
+ scopeKey: "store",
19
+ currency: "usd",
20
+ groupKey: "g",
21
+ operationId: "operation",
22
+ version: 1,
23
+ status: "completed" as const,
24
+ sourceId: "in_a",
25
+ sourceKind: "invoice" as const,
26
+ cancelRequested: false,
27
+ };
28
+ await client.getGroupOperation(ctx, op);
29
+ expect(actual).toEqual({
30
+ accountId: "acct_a",
31
+ scopeKey: "store",
32
+ currency: "usd",
33
+ groupKey: "g",
34
+ operationId: "operation",
35
+ version: 1,
36
+ });
37
+ });
@@ -0,0 +1,76 @@
1
+ import { createFunctionHandle } from "convex/server";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { operationRef } from "./contracts.js";
6
+ import type {
7
+ RecoveryOperationRef,
8
+ RecoveryOperationStatus,
9
+ RecoveryProviderRequest,
10
+ RecoveryStartOptions,
11
+ RecoveryStartResult,
12
+ } from "./contracts.js";
13
+ import {
14
+ executeRecoveryProvider,
15
+ type RecoveryProviderOptions,
16
+ } from "./provider.js";
17
+ export abstract class RecoveryWorkflowClient {
18
+ protected abstract readonly component: Component;
19
+ /** Authorize the full scope and allocation in the host mutation. requestKey is immutable per component. */
20
+ async startGroup(
21
+ ctx: RunCtx,
22
+ opts: RecoveryStartOptions,
23
+ ): Promise<RecoveryStartResult> {
24
+ const { provider, completion, ...args } = opts;
25
+ return (await runMutationOrThrow(
26
+ ctx,
27
+ componentRef(this.component, "recoveryWorkflow/mutations/start"),
28
+ {
29
+ ...args,
30
+ provider: await createFunctionHandle(provider),
31
+ ...(completion
32
+ ? { completion: await createFunctionHandle(completion) }
33
+ : {}),
34
+ maxAttempts: opts.maxAttempts ?? 3,
35
+ retryDelayMs: opts.retryDelayMs ?? 1000,
36
+ },
37
+ )) as RecoveryStartResult;
38
+ }
39
+ getGroupOperation(
40
+ ctx: RunCtx,
41
+ op: RecoveryOperationRef,
42
+ ): Promise<RecoveryOperationStatus> {
43
+ return ctx.runQuery(
44
+ componentRef(this.component, "recoveryWorkflow/queries/get"),
45
+ operationRef(op),
46
+ ) as Promise<RecoveryOperationStatus>;
47
+ }
48
+ resumeGroup(
49
+ ctx: RunCtx,
50
+ op: RecoveryOperationRef,
51
+ ): Promise<RecoveryOperationStatus> {
52
+ return runMutationOrThrow(
53
+ ctx,
54
+ componentRef(this.component, "recoveryWorkflow/mutations/resume"),
55
+ operationRef(op),
56
+ ) as Promise<RecoveryOperationStatus>;
57
+ }
58
+ requestGroupCancel(
59
+ ctx: RunCtx,
60
+ op: RecoveryOperationRef,
61
+ ): Promise<RecoveryOperationStatus> {
62
+ return runMutationOrThrow(
63
+ ctx,
64
+ componentRef(this.component, "recoveryWorkflow/mutations/requestCancel"),
65
+ operationRef(op),
66
+ ) as Promise<RecoveryOperationStatus>;
67
+ }
68
+ /** Call only inside the registered internal host action. Inject credentials from runtime env, never workflow args. */
69
+ executeGroupProvider(
70
+ ctx: RunCtx,
71
+ request: RecoveryProviderRequest,
72
+ options: RecoveryProviderOptions,
73
+ ) {
74
+ return executeRecoveryProvider(this.component, ctx, request, options);
75
+ }
76
+ }
@@ -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
+ }