@fantastic.dev/better-stripe 0.41.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 (108) hide show
  1. package/CHANGELOG.md +10 -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 +366 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +199 -17
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +199 -17
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +3 -0
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +4 -0
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/component/_generated/api.d.ts +18 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -1
  25. package/dist/component/_generated/api.js.map +1 -1
  26. package/dist/component/_generated/component.d.ts +473 -0
  27. package/dist/component/_generated/component.d.ts.map +1 -1
  28. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  29. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  30. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  31. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  32. package/dist/component/balanceFunding/internal/actions.js +80 -0
  33. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  34. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  35. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  36. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  37. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  38. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  39. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  40. package/dist/component/balanceFunding/internal/queries.js +35 -0
  41. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  42. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  43. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  44. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  45. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  46. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  47. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/mutations.d.ts +403 -0
  49. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  50. package/dist/component/balanceFunding/mutations.js +24 -0
  51. package/dist/component/balanceFunding/mutations.js.map +1 -1
  52. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  53. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  54. package/dist/component/balanceFunding/queries.d.ts +78 -0
  55. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  56. package/dist/component/balanceFunding/queries.js +35 -0
  57. package/dist/component/balanceFunding/queries.js.map +1 -1
  58. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  59. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/receipt.js +37 -0
  61. package/dist/component/balanceFunding/receipt.js.map +1 -0
  62. package/dist/component/balanceFunding/schema.d.ts +506 -2
  63. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  64. package/dist/component/balanceFunding/schema.js +2 -0
  65. package/dist/component/balanceFunding/schema.js.map +1 -1
  66. package/dist/component/balanceFunding/stateHandlers.d.ts +50 -8
  67. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  68. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  69. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  70. package/dist/component/balanceFunding/workflowControl.js +149 -0
  71. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  72. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  73. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  74. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  75. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  76. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  77. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  78. package/dist/component/balanceFunding/workflowState.js +194 -0
  79. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  80. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  81. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  82. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  83. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  84. package/dist/component/earnings/triggers.d.ts +102 -18
  85. package/dist/component/earnings/triggers.d.ts.map +1 -1
  86. package/dist/component/schema.d.ts +183 -1
  87. package/package.json +1 -1
  88. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  89. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  90. package/src/client/billing/balanceFunding.ts +50 -0
  91. package/src/client/index.ts +15 -0
  92. package/src/component/_generated/api.ts +18 -0
  93. package/src/component/_generated/component.ts +524 -0
  94. package/src/component/balanceFunding/internal/actions.ts +107 -0
  95. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  96. package/src/component/balanceFunding/internal/queries.ts +34 -0
  97. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  98. package/src/component/balanceFunding/mutations.ts +34 -0
  99. package/src/component/balanceFunding/queries.ts +38 -0
  100. package/src/component/balanceFunding/receipt.ts +48 -0
  101. package/src/component/balanceFunding/schema.ts +2 -0
  102. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  103. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  104. package/src/component/balanceFunding/workflow.test.ts +552 -0
  105. package/src/component/balanceFunding/workflowControl.ts +198 -0
  106. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  107. package/src/component/balanceFunding/workflowState.ts +285 -0
  108. package/src/component/balanceFunding/workflowValidators.ts +40 -0
@@ -0,0 +1,198 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { WorkflowId } from "@convex-dev/workflow";
3
+ import type { MutationCtx } from "../_generated/server.js";
4
+ import { internal } from "../_generated/api.js";
5
+ import { executionWorkflow } from "../durableExecution/runtime.js";
6
+ import { ref, same } from "./helpers.js";
7
+ import { normalizeReceipt } from "./receipt.js";
8
+ import { requestCancelHandler } from "./lifecycleHandlers.js";
9
+ import {
10
+ finishFromReceiptsHandler,
11
+ recordProviderReceiptHandler,
12
+ phaseKey,
13
+ FundingWorkflowError,
14
+ readWorkflowContext,
15
+ requireWorkflow,
16
+ conflict,
17
+ unknown,
18
+ } from "./workflowState.js";
19
+ import {
20
+ workflowStartResult,
21
+ type FundingWorkflowRef,
22
+ } from "./workflowValidators.js";
23
+ type StartResult = Infer<typeof workflowStartResult>;
24
+ const failure = (e: unknown) => {
25
+ if (e instanceof FundingWorkflowError) return e.outcome;
26
+ throw new Error("Balance funding workflow storage or scheduling failed.");
27
+ };
28
+ export async function startWorkflowHandler(
29
+ ctx: MutationCtx,
30
+ args: FundingWorkflowRef & { providerAction: string },
31
+ ): Promise<StartResult> {
32
+ try {
33
+ const { operation } = await readWorkflowContext(ctx, args, false);
34
+ const operationRef = ref(operation);
35
+ const execution = operation.execution;
36
+ if (execution) {
37
+ requireWorkflow(
38
+ execution.providerAction === args.providerAction &&
39
+ execution.definitionVersion === args.definitionVersion &&
40
+ execution.providerApiVersion === args.providerApiVersion,
41
+ conflict("identity_changed"),
42
+ );
43
+ return {
44
+ status: "accepted",
45
+ operation: operationRef,
46
+ ...(execution.workflowId ? { workflowId: execution.workflowId } : {}),
47
+ };
48
+ }
49
+ if (operation.state === "canceled")
50
+ return { status: "canceled", operation: operationRef };
51
+ if (operation.state === "succeeded")
52
+ return { status: "accepted", operation: operationRef };
53
+ requireWorkflow(operation.state === "pending", unknown());
54
+ const { providerAction, ...base } = args;
55
+ const binding = {
56
+ definitionVersion: args.definitionVersion,
57
+ providerApiVersion: args.providerApiVersion,
58
+ providerAction,
59
+ };
60
+ const workflowId = await executionWorkflow.start(
61
+ ctx,
62
+ internal.balanceFunding.internal.workflow.run,
63
+ base,
64
+ {
65
+ startAsync: true,
66
+ onComplete: internal.balanceFunding.internal.mutations.onComplete,
67
+ context: base,
68
+ },
69
+ );
70
+ await ctx.db.patch("balanceFundingOperations", operation._id, {
71
+ execution: { ...binding, workflowId },
72
+ });
73
+ return { status: "accepted", operation: operationRef, workflowId };
74
+ } catch (e) {
75
+ return failure(e);
76
+ }
77
+ }
78
+ export async function resumeWorkflowHandler(
79
+ ctx: MutationCtx,
80
+ args: FundingWorkflowRef,
81
+ ): Promise<StartResult> {
82
+ try {
83
+ const { operation } = await readWorkflowContext(ctx, args);
84
+ const workflowId = operation.execution?.workflowId as
85
+ WorkflowId | undefined;
86
+ requireWorkflow(workflowId, unknown("history_incomplete"));
87
+ const accepted: StartResult = {
88
+ status: "accepted",
89
+ operation: ref(operation),
90
+ workflowId,
91
+ };
92
+ if (operation.state === "succeeded") return accepted;
93
+ if (operation.state === "canceled")
94
+ return { status: "canceled", operation: ref(operation) };
95
+ const status = await executionWorkflow
96
+ .status(ctx, workflowId)
97
+ .catch(() => null);
98
+ requireWorkflow(status, unknown("history_incomplete"));
99
+ if (status.type === "inProgress") return accepted;
100
+ const history = await executionWorkflow.listSteps(ctx, workflowId, {
101
+ paginationOpts: { cursor: null, numItems: 32 },
102
+ order: "asc",
103
+ });
104
+ requireWorkflow(
105
+ history.isDone && history.page.length > 0,
106
+ unknown("history_incomplete"),
107
+ );
108
+ const names = new Set([
109
+ "plan-v1",
110
+ "create-provider-v1",
111
+ "create-record-v1",
112
+ "attach-provider-v1",
113
+ "attach-record-v1",
114
+ "finish-v1",
115
+ "apply-provider-v1",
116
+ "apply-record-v1",
117
+ ]);
118
+ requireWorkflow(
119
+ history.page.every((s) => names.has(s.name)),
120
+ conflict("revision_changed"),
121
+ );
122
+ for (const step of history.page) {
123
+ if (
124
+ !step.name.endsWith("-provider-v1") ||
125
+ step.runResult?.kind !== "success"
126
+ )
127
+ continue;
128
+ const phase =
129
+ step.name === "create-provider-v1"
130
+ ? "create"
131
+ : step.name === "attach-provider-v1"
132
+ ? "attach"
133
+ : "apply";
134
+ const providerKey = phaseKey(operation, phase);
135
+ requireWorkflow(providerKey, conflict("identity_changed"));
136
+ const phaseArgs = { ...args, phase, providerKey } as const;
137
+ requireWorkflow(same(step.args, phaseArgs), conflict("identity_changed"));
138
+ const result = step.runResult.returnValue as {
139
+ status?: string;
140
+ value?: unknown;
141
+ } | null;
142
+ if (result?.status !== "ready") continue;
143
+ const receipt = normalizeReceipt(result.value, phaseArgs);
144
+ requireWorkflow(receipt, conflict("identity_changed"));
145
+ await recordProviderReceiptHandler(ctx, { ...phaseArgs, receipt });
146
+ }
147
+ const { operation: reconciled } = await readWorkflowContext(ctx, args);
148
+ const failed = history.page.find(
149
+ (s) => s.runResult?.kind === "failed" || s.runResult?.kind === "canceled",
150
+ );
151
+ const uncertain = history.page.find(
152
+ (s) =>
153
+ s.name.endsWith("-provider-v1") &&
154
+ s.runResult?.kind === "success" &&
155
+ (s.runResult.returnValue as { status?: string } | null)?.status !==
156
+ "ready",
157
+ );
158
+ const from = failed?.name ?? uncertain?.name;
159
+ if (
160
+ !from &&
161
+ ((reconciled.kind === "prepare" &&
162
+ reconciled.execution?.create?.state === "succeeded" &&
163
+ reconciled.execution.attach?.state === "succeeded") ||
164
+ (reconciled.kind === "apply" &&
165
+ reconciled.execution?.apply?.state === "succeeded"))
166
+ ) {
167
+ await finishFromReceiptsHandler(ctx, args);
168
+ return accepted;
169
+ }
170
+ requireWorkflow(from, unknown("history_incomplete"));
171
+ await executionWorkflow.restart(ctx, workflowId, {
172
+ from,
173
+ startAsync: true,
174
+ });
175
+ return accepted;
176
+ } catch (e) {
177
+ return failure(e);
178
+ }
179
+ }
180
+ export async function cancelWorkflowHandler(
181
+ ctx: MutationCtx,
182
+ args: FundingWorkflowRef,
183
+ ) {
184
+ const { operation } = await readWorkflowContext(ctx, args);
185
+ const updated = await requestCancelHandler(ctx, ref(operation));
186
+ const workflowId = operation.execution?.workflowId as WorkflowId | undefined;
187
+ if (
188
+ workflowId &&
189
+ (await executionWorkflow.status(ctx, workflowId)).type === "inProgress"
190
+ )
191
+ await executionWorkflow.cancel(ctx, workflowId);
192
+ return {
193
+ ...ref(updated),
194
+ state: updated.state,
195
+ cancelRequested: updated.cancelRequested,
196
+ ...(updated.failureCode ? { failureCode: updated.failureCode } : {}),
197
+ };
198
+ }
@@ -0,0 +1,78 @@
1
+ import { v, type Infer } from "convex/values";
2
+ export const FUNDING_WORKFLOW_VERSION = "balance-funding/v1";
3
+ export const providerPhase = v.union(
4
+ v.literal("create"),
5
+ v.literal("attach"),
6
+ v.literal("apply"),
7
+ );
8
+ export type ProviderPhase = Infer<typeof providerPhase>;
9
+ export const provisioningReceipt = v.object({
10
+ phase: providerPhase,
11
+ customerAccount: v.string(),
12
+ stripeSubscriptionId: v.string(),
13
+ paymentMethodId: v.union(v.string(), v.null()),
14
+ paymentMethodTypes: v.optional(v.union(v.array(v.string()), v.null())),
15
+ enabled: v.optional(v.boolean()),
16
+ providerApiVersion: v.string(),
17
+ });
18
+ export type ProvisioningReceipt = Infer<typeof provisioningReceipt>;
19
+ const phaseState = v.object({
20
+ state: v.union(
21
+ v.literal("running"),
22
+ v.literal("unknown"),
23
+ v.literal("succeeded"),
24
+ ),
25
+ receipt: v.optional(provisioningReceipt),
26
+ });
27
+ export const workflowBinding = v.object({
28
+ workflowId: v.optional(v.string()),
29
+ definitionVersion: v.string(),
30
+ providerApiVersion: v.string(),
31
+ providerAction: v.string(),
32
+ create: v.optional(phaseState),
33
+ attach: v.optional(phaseState),
34
+ apply: v.optional(phaseState),
35
+ });
36
+ export const providerUnknown = v.object({
37
+ status: v.literal("unknown"),
38
+ reason: v.union(
39
+ v.literal("provider_outcome_unknown"),
40
+ v.literal("history_incomplete"),
41
+ ),
42
+ retryable: v.literal(false),
43
+ });
44
+ export const providerConflict = v.object({
45
+ status: v.literal("conflict"),
46
+ reason: v.union(
47
+ v.literal("scope_busy"),
48
+ v.literal("identity_changed"),
49
+ v.literal("revision_changed"),
50
+ ),
51
+ retryable: v.literal(false),
52
+ });
53
+ export const providerRejected = v.object({
54
+ status: v.literal("rejected"),
55
+ reason: v.union(
56
+ v.literal("invalid_scope"),
57
+ v.literal("unsupported_source"),
58
+ v.literal("policy_invalid"),
59
+ ),
60
+ retryable: v.literal(false),
61
+ });
62
+ export const providerNotReady = v.object({
63
+ status: v.literal("not_ready"),
64
+ reason: v.literal("provider_pending"),
65
+ retryable: v.literal(true),
66
+ });
67
+ export const workflowUnavailable = v.union(
68
+ providerUnknown,
69
+ providerConflict,
70
+ providerRejected,
71
+ providerNotReady,
72
+ );
73
+ export type WorkflowUnavailable = Infer<typeof workflowUnavailable>;
74
+ export const providerResult = v.union(
75
+ v.object({ status: v.literal("ready"), value: provisioningReceipt }),
76
+ workflowUnavailable,
77
+ );
78
+ export type ProviderResult = Infer<typeof providerResult>;
@@ -0,0 +1,285 @@
1
+ import type { QueryCtx, MutationCtx } from "../_generated/server.js";
2
+ import type {
3
+ FundingWorkflowRef,
4
+ FundingPhaseRef,
5
+ } from "./workflowValidators.js";
6
+ import {
7
+ FUNDING_WORKFLOW_VERSION,
8
+ type WorkflowUnavailable,
9
+ type ProvisioningReceipt,
10
+ } from "./workflowSchema.js";
11
+ import { finishPreparationHandler } from "./preparationHandlers.js";
12
+ import { finishHandler } from "./stateHandlers.js";
13
+ import { ref, same } from "./helpers.js";
14
+
15
+ export const unknown = (
16
+ reason:
17
+ | "provider_outcome_unknown"
18
+ | "history_incomplete" = "provider_outcome_unknown",
19
+ ): WorkflowUnavailable => ({ status: "unknown", reason, retryable: false });
20
+ export const conflict = (
21
+ reason: "identity_changed" | "revision_changed" | "scope_busy",
22
+ ): WorkflowUnavailable => ({ status: "conflict", reason, retryable: false });
23
+ export class FundingWorkflowError extends Error {
24
+ constructor(readonly outcome: WorkflowUnavailable) {
25
+ super("Balance funding workflow requires reconciliation.");
26
+ }
27
+ }
28
+ export function requireWorkflow(
29
+ value: unknown,
30
+ outcome: WorkflowUnavailable,
31
+ ): asserts value {
32
+ if (!value) throw new FundingWorkflowError(outcome);
33
+ }
34
+ export async function readWorkflowContext(
35
+ ctx: QueryCtx | MutationCtx,
36
+ args: FundingWorkflowRef,
37
+ binding = true,
38
+ ) {
39
+ requireWorkflow(
40
+ args.definitionVersion === FUNDING_WORKFLOW_VERSION,
41
+ conflict("revision_changed"),
42
+ );
43
+ const operation = await ctx.db.get(
44
+ "balanceFundingOperations",
45
+ args.operationId,
46
+ );
47
+ requireWorkflow(
48
+ operation &&
49
+ operation.accountId === args.accountId &&
50
+ operation.scopeKey === args.scopeKey &&
51
+ operation.version === args.version,
52
+ conflict("identity_changed"),
53
+ );
54
+ const preparation = await ctx.db.get(
55
+ "balanceFundingPreparations",
56
+ operation.preparationId,
57
+ );
58
+ requireWorkflow(
59
+ preparation &&
60
+ preparation.accountId === args.accountId &&
61
+ preparation.scopeKey === args.scopeKey &&
62
+ preparation.preparation.stripeSubscriptionId ===
63
+ args.stripeSubscriptionId &&
64
+ preparation.providerApiVersion === args.providerApiVersion,
65
+ conflict("identity_changed"),
66
+ );
67
+ if (binding)
68
+ requireWorkflow(
69
+ operation.execution &&
70
+ operation.execution.definitionVersion === args.definitionVersion &&
71
+ operation.execution.providerApiVersion === args.providerApiVersion,
72
+ conflict("revision_changed"),
73
+ );
74
+ return { operation, preparation };
75
+ }
76
+ function active(context: Awaited<ReturnType<typeof readWorkflowContext>>) {
77
+ requireWorkflow(
78
+ context.preparation.activeOperationId === context.operation._id &&
79
+ context.preparation.operationVersion === context.operation.version,
80
+ conflict("revision_changed"),
81
+ );
82
+ }
83
+ export async function claimProviderPhaseHandler(
84
+ ctx: MutationCtx,
85
+ args: FundingPhaseRef,
86
+ ) {
87
+ const context = await readWorkflowContext(ctx, args);
88
+ const { operation: op, preparation } = context;
89
+ requireWorkflow(
90
+ (op.kind === "prepare" && args.phase !== "apply") ||
91
+ (op.kind === "apply" && args.phase === "apply"),
92
+ {
93
+ status: "rejected",
94
+ reason: "unsupported_source",
95
+ retryable: false,
96
+ },
97
+ );
98
+ requireWorkflow(
99
+ phaseKey(op, args.phase) === args.providerKey,
100
+ conflict("identity_changed"),
101
+ );
102
+ const phase = op.execution![args.phase];
103
+ if (phase?.state === "succeeded" && phase.receipt)
104
+ return { status: "ready" as const, value: phase.receipt };
105
+ active(context);
106
+ if (op.state === "canceled" || op.state === "failed") return unknown();
107
+ const method = op.execution!.create?.receipt?.paymentMethodId;
108
+ if (phase) {
109
+ if (args.phase === "create" || (args.phase === "attach" && !method))
110
+ return unknown();
111
+ return {
112
+ status: "claimed" as const,
113
+ mode: "reconcile" as const,
114
+ ...(method ? { paymentMethodId: method } : {}),
115
+ };
116
+ }
117
+ if (op.cancelRequested || op.state === "unknown") return unknown();
118
+ if (preparation.startsPaused) return conflict("scope_busy");
119
+ if (args.phase === "attach") requireWorkflow(method, unknown());
120
+ await ctx.db.patch("balanceFundingOperations", op._id, {
121
+ state: "running",
122
+ execution: {
123
+ ...op.execution!,
124
+ [args.phase]: { state: "running" as const },
125
+ },
126
+ });
127
+ return {
128
+ status: "claimed" as const,
129
+ mode: "execute" as const,
130
+ ...(method ? { paymentMethodId: method } : {}),
131
+ };
132
+ }
133
+ export async function recordProviderReceiptHandler(
134
+ ctx: MutationCtx,
135
+ args: FundingPhaseRef & { receipt: ProvisioningReceipt },
136
+ ) {
137
+ const context = await readWorkflowContext(ctx, args);
138
+ const { operation: op } = context;
139
+ requireWorkflow(
140
+ phaseKey(op, args.phase) === args.providerKey,
141
+ conflict("identity_changed"),
142
+ );
143
+ const receipt = args.receipt;
144
+ requireWorkflow(
145
+ receipt.phase === args.phase &&
146
+ receipt.customerAccount === args.accountId &&
147
+ receipt.stripeSubscriptionId === args.stripeSubscriptionId &&
148
+ receipt.providerApiVersion === args.providerApiVersion &&
149
+ (args.phase === "apply" || !!receipt.paymentMethodId?.trim()),
150
+ conflict("identity_changed"),
151
+ );
152
+ if (args.phase === "attach")
153
+ requireWorkflow(
154
+ op.execution!.create?.receipt?.paymentMethodId ===
155
+ receipt.paymentMethodId,
156
+ conflict("identity_changed"),
157
+ );
158
+ if (args.phase === "apply") {
159
+ requireWorkflow(
160
+ receipt.enabled === op.enabled &&
161
+ receipt.paymentMethodId ===
162
+ (op.enabled
163
+ ? context.preparation.preparation.paymentMethodId
164
+ : context.preparation.preparation.previousPaymentMethodId) &&
165
+ same(
166
+ receipt.paymentMethodTypes,
167
+ op.enabled
168
+ ? ["stripe_balance"]
169
+ : context.preparation.preparation.previousPaymentMethodTypes,
170
+ ),
171
+ conflict("identity_changed"),
172
+ );
173
+ }
174
+ const phase = op.execution![args.phase];
175
+ requireWorkflow(phase, unknown());
176
+ if (phase.receipt) {
177
+ requireWorkflow(same(phase.receipt, receipt), conflict("identity_changed"));
178
+ return null;
179
+ }
180
+ active(context);
181
+ requireWorkflow(
182
+ op.state !== "canceled" && op.state !== "failed",
183
+ conflict("revision_changed"),
184
+ );
185
+ await ctx.db.patch("balanceFundingOperations", op._id, {
186
+ state: op.cancelRequested ? op.state : "running",
187
+ execution: {
188
+ ...op.execution!,
189
+ [args.phase]: { state: "succeeded" as const, receipt },
190
+ },
191
+ });
192
+ return null;
193
+ }
194
+ export async function markProviderUnknownHandler(
195
+ ctx: MutationCtx,
196
+ args: FundingPhaseRef,
197
+ ) {
198
+ const context = await readWorkflowContext(ctx, args);
199
+ const { operation: op } = context;
200
+ requireWorkflow(
201
+ phaseKey(op, args.phase) === args.providerKey,
202
+ conflict("identity_changed"),
203
+ );
204
+ if (["succeeded", "canceled", "failed"].includes(op.state)) return null;
205
+ active(context);
206
+ const phase = op.execution![args.phase];
207
+ if (phase?.receipt) return null;
208
+ await ctx.db.patch("balanceFundingOperations", op._id, {
209
+ state: "unknown",
210
+ execution: {
211
+ ...op.execution!,
212
+ [args.phase]: { state: "unknown" as const },
213
+ },
214
+ });
215
+ return null;
216
+ }
217
+ export async function finishFromReceiptsHandler(
218
+ ctx: MutationCtx,
219
+ args: FundingWorkflowRef,
220
+ ) {
221
+ const context = await readWorkflowContext(ctx, args);
222
+ const { operation: op, preparation } = context;
223
+ if (op.state === "succeeded") return null;
224
+ if (op.kind === "apply") {
225
+ const receipt = op.execution!.apply?.receipt;
226
+ requireWorkflow(
227
+ receipt &&
228
+ op.execution!.apply?.state === "succeeded" &&
229
+ receipt.enabled === op.enabled &&
230
+ receipt.paymentMethodTypes !== undefined,
231
+ unknown(),
232
+ );
233
+ await finishHandler(ctx, {
234
+ ...ref(op),
235
+ enabled: op.enabled,
236
+ receipt: {
237
+ customerAccount: receipt.customerAccount,
238
+ stripeSubscriptionId: receipt.stripeSubscriptionId,
239
+ paymentMethodId: receipt.paymentMethodId,
240
+ paymentMethodTypes: receipt.paymentMethodTypes,
241
+ providerApiVersion: receipt.providerApiVersion,
242
+ },
243
+ });
244
+ return null;
245
+ }
246
+ const created = op.execution!.create?.receipt;
247
+ const attached = op.execution!.attach?.receipt;
248
+ requireWorkflow(
249
+ created &&
250
+ attached &&
251
+ created.paymentMethodId === attached.paymentMethodId &&
252
+ op.execution!.create?.state === "succeeded" &&
253
+ op.execution!.attach?.state === "succeeded",
254
+ unknown(),
255
+ );
256
+ await finishPreparationHandler(ctx, {
257
+ ...ref(op),
258
+ preparation: {
259
+ ...preparation.preparation,
260
+ paymentMethodId: attached.paymentMethodId!,
261
+ },
262
+ providerApiVersion: args.providerApiVersion,
263
+ });
264
+ return null;
265
+ }
266
+
267
+ export function phaseKey(
268
+ op: {
269
+ providerKey: string;
270
+ enabled: boolean;
271
+ providerKeys: {
272
+ create?: string;
273
+ attach?: string;
274
+ enable: string;
275
+ disable: string;
276
+ };
277
+ },
278
+ phase: "create" | "attach" | "apply",
279
+ ) {
280
+ return phase === "apply"
281
+ ? op.enabled
282
+ ? op.providerKeys.enable
283
+ : op.providerKeys.disable
284
+ : op.providerKeys[phase];
285
+ }
@@ -0,0 +1,40 @@
1
+ import { v, type Infer } from "convex/values";
2
+ import { operationRefFields, operationRef } from "./schema.js";
3
+ import {
4
+ providerPhase,
5
+ provisioningReceipt,
6
+ workflowUnavailable,
7
+ } from "./workflowSchema.js";
8
+ export const workflowRefFields = {
9
+ ...operationRefFields,
10
+ stripeSubscriptionId: v.string(),
11
+ providerApiVersion: v.string(),
12
+ definitionVersion: v.string(),
13
+ };
14
+ export const workflowRef = v.object(workflowRefFields);
15
+ export type FundingWorkflowRef = Infer<typeof workflowRef>;
16
+ export const phaseRefFields = {
17
+ ...workflowRefFields,
18
+ phase: providerPhase,
19
+ providerKey: v.string(),
20
+ };
21
+ export const phaseRef = v.object(phaseRefFields);
22
+ export type FundingPhaseRef = Infer<typeof phaseRef>;
23
+ export const workflowStartResult = v.union(
24
+ v.object({
25
+ status: v.literal("accepted"),
26
+ operation: operationRef,
27
+ workflowId: v.optional(v.string()),
28
+ }),
29
+ v.object({ status: v.literal("canceled"), operation: operationRef }),
30
+ workflowUnavailable,
31
+ );
32
+ export const phaseClaimResult = v.union(
33
+ v.object({
34
+ status: v.literal("claimed"),
35
+ mode: v.union(v.literal("execute"), v.literal("reconcile")),
36
+ paymentMethodId: v.optional(v.string()),
37
+ }),
38
+ v.object({ status: v.literal("ready"), value: provisioningReceipt }),
39
+ workflowUnavailable,
40
+ );