@fantastic.dev/better-stripe 0.38.0 → 0.40.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 (167) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +21 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +3 -5
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +18 -0
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +4 -0
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/index.d.ts +4 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +3 -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/processingCostDeficit/index.d.ts +27 -0
  48. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  49. package/dist/client/processingCostDeficit/index.js +54 -0
  50. package/dist/client/processingCostDeficit/index.js.map +1 -0
  51. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  52. package/dist/client/settlement/verifiedSale.js +4 -6
  53. package/dist/client/settlement/verifiedSale.js.map +1 -1
  54. package/dist/component/_generated/api.d.ts +284 -0
  55. package/dist/component/_generated/api.d.ts.map +1 -0
  56. package/dist/component/_generated/api.js +31 -0
  57. package/dist/component/_generated/api.js.map +1 -0
  58. package/dist/component/_generated/component.d.ts +527 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  61. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  62. package/dist/component/balanceFunding/helpers.js +68 -0
  63. package/dist/component/balanceFunding/helpers.js.map +1 -0
  64. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  65. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  66. package/dist/component/balanceFunding/importHandler.js +130 -0
  67. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  68. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  69. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  70. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  71. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  72. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  73. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  74. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  75. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  76. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  77. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  78. package/dist/component/balanceFunding/mutations.js +106 -0
  79. package/dist/component/balanceFunding/mutations.js.map +1 -0
  80. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  81. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  82. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  83. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  84. package/dist/component/balanceFunding/queries.d.ts +151 -0
  85. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  86. package/dist/component/balanceFunding/queries.js +180 -0
  87. package/dist/component/balanceFunding/queries.js.map +1 -0
  88. package/dist/component/balanceFunding/schema.d.ts +748 -0
  89. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  90. package/dist/component/balanceFunding/schema.js +124 -0
  91. package/dist/component/balanceFunding/schema.js.map +1 -0
  92. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  93. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  94. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  95. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  96. package/dist/component/convex.config.d.ts.map +1 -1
  97. package/dist/component/convex.config.js +2 -0
  98. package/dist/component/convex.config.js.map +1 -1
  99. package/dist/component/costRecovery/completion.d.ts +1 -0
  100. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  101. package/dist/component/costRecovery/helpers.d.ts +1 -0
  102. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  103. package/dist/component/costRecovery/mutations.d.ts +5 -0
  104. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  105. package/dist/component/costRecovery/preparation.d.ts +50 -0
  106. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  107. package/dist/component/costRecovery/preparation.js +108 -0
  108. package/dist/component/costRecovery/preparation.js.map +1 -0
  109. package/dist/component/costRecovery/queries.d.ts +1 -0
  110. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  111. package/dist/component/costRecovery/reservations.d.ts +2 -0
  112. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  113. package/dist/component/costRecovery/schema.d.ts +7 -2
  114. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  115. package/dist/component/costRecovery/schema.js +1 -0
  116. package/dist/component/costRecovery/schema.js.map +1 -1
  117. package/dist/component/durableExecution/runtime.d.ts +3 -0
  118. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  119. package/dist/component/durableExecution/runtime.js +12 -0
  120. package/dist/component/durableExecution/runtime.js.map +1 -0
  121. package/dist/component/earnings/triggers.d.ts +242 -2
  122. package/dist/component/earnings/triggers.d.ts.map +1 -1
  123. package/dist/component/schema.d.ts +253 -1
  124. package/dist/component/schema.js +4 -0
  125. package/dist/component/schema.js.map +1 -1
  126. package/docs/settlement.md +48 -0
  127. package/package.json +4 -2
  128. package/src/client/costRecovery-invoices.ts +3 -7
  129. package/src/client/costRecovery.test.ts +34 -0
  130. package/src/client/costRecovery.ts +21 -0
  131. package/src/client/index.ts +7 -2
  132. package/src/client/paymentSource/client.ts +13 -0
  133. package/src/client/paymentSource/contracts.ts +33 -0
  134. package/src/client/paymentSource/economics.ts +20 -0
  135. package/src/client/paymentSource/funding.ts +23 -0
  136. package/src/client/paymentSource/history.ts +48 -0
  137. package/src/client/paymentSource/resolver.test.ts +582 -0
  138. package/src/client/paymentSource/resolver.ts +350 -0
  139. package/src/client/processingCostDeficit/README.md +35 -0
  140. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  141. package/src/client/processingCostDeficit/index.ts +91 -0
  142. package/src/client/settlement/verifiedSale.ts +4 -10
  143. package/src/component/_generated/api.ts +23 -1
  144. package/src/component/_generated/component.ts +693 -0
  145. package/src/component/balanceFunding/failure.test.ts +116 -0
  146. package/src/component/balanceFunding/helpers.ts +102 -0
  147. package/src/component/balanceFunding/import.test.ts +221 -0
  148. package/src/component/balanceFunding/importHandler.ts +146 -0
  149. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  150. package/src/component/balanceFunding/lookup.test.ts +113 -0
  151. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  152. package/src/component/balanceFunding/mutations.ts +136 -0
  153. package/src/component/balanceFunding/preparation.test.ts +146 -0
  154. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  155. package/src/component/balanceFunding/queries.ts +221 -0
  156. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  157. package/src/component/balanceFunding/schema.ts +169 -0
  158. package/src/component/balanceFunding/state.test.ts +352 -0
  159. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  160. package/src/component/balanceFunding/validation.test.ts +100 -0
  161. package/src/component/convex.config.ts +2 -0
  162. package/src/component/costRecovery/preparation.test.ts +355 -0
  163. package/src/component/costRecovery/preparation.ts +124 -0
  164. package/src/component/costRecovery/schema.ts +1 -0
  165. package/src/component/durableExecution/composition.test.ts +568 -0
  166. package/src/component/durableExecution/runtime.ts +12 -0
  167. package/src/component/schema.ts +8 -0
@@ -0,0 +1,116 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_failure", scopeKey: "failure" };
11
+ const original = {
12
+ customerAccount: scope.accountId,
13
+ stripeSubscriptionId: "sub_failure",
14
+ previousPaymentMethodId: null,
15
+ previousPaymentMethodTypes: null,
16
+ };
17
+ const args = {
18
+ ...scope,
19
+ preparation: original,
20
+ consent: true,
21
+ consentAt: 10,
22
+ consentReference: "consent",
23
+ providerApiVersion: "preview",
24
+ requestKey: "prepare",
25
+ };
26
+ it("records safe terminal failure only before execution and keeps failed lookup free of preparation data", async () => {
27
+ const t = convexTest(schema, modules);
28
+ const first = await t.mutation(m("prepare"), args);
29
+ await t.mutation(m("failBeforeStart"), {
30
+ ...first.operation,
31
+ failureCode: "policy_invalid",
32
+ });
33
+ const lookup = { ...first.operation, stripeSubscriptionId: "sub_failure" };
34
+ expect(await t.query(q("getOperation"), lookup)).toEqual({
35
+ ...first.operation,
36
+ state: "failed",
37
+ cancelRequested: false,
38
+ failureCode: "policy_invalid",
39
+ });
40
+ expect(await t.query(q("getPreparation"), lookup)).toEqual({
41
+ status: "failed",
42
+ operation: first.operation,
43
+ failureCode: "policy_invalid",
44
+ });
45
+ expect(await t.mutation(m("prepare"), args)).toEqual(first);
46
+ for (const name of ["start", "markUnknown", "requestCancel"])
47
+ expect((await t.mutation(m(name), first.operation)).state).toBe("failed");
48
+ await expect(
49
+ t.mutation(m("finishPreparation"), {
50
+ ...first.operation,
51
+ preparation: { ...original, paymentMethodId: "pm_balance" },
52
+ providerApiVersion: "preview",
53
+ }),
54
+ ).rejects.toThrow(/version|failed/i);
55
+ const next = await t.mutation(m("prepare"), { ...args, requestKey: "fresh" });
56
+ expect(next.operation.version).toBe(2);
57
+ const earlier = await t.query(q("inspectOperation"), {
58
+ ...first.operation,
59
+ stripeSubscriptionId: "sub_failure",
60
+ });
61
+ const newer = await t.query(q("inspectOperation"), {
62
+ ...next.operation,
63
+ stripeSubscriptionId: "sub_failure",
64
+ });
65
+ expect(newer.providerKeys.create).not.toBe(earlier.providerKeys.create);
66
+ await expect(
67
+ t.mutation(m("finishPreparation"), {
68
+ ...first.operation,
69
+ preparation: { ...original, paymentMethodId: "pm_balance" },
70
+ providerApiVersion: "preview",
71
+ }),
72
+ ).rejects.toThrow(/version|failed/i);
73
+ expect(
74
+ (
75
+ await t.query(q("getOperation"), {
76
+ ...next.operation,
77
+ stripeSubscriptionId: "sub_failure",
78
+ })
79
+ ).state,
80
+ ).toBe("pending");
81
+ });
82
+ it("never turns running or unknown provider work into terminal failure or releases its claim", async () => {
83
+ const t = convexTest(schema, modules);
84
+ const first = await t.mutation(m("prepare"), args);
85
+ await t.mutation(m("start"), first.operation);
86
+ await expect(
87
+ t.mutation(m("failBeforeStart"), {
88
+ ...first.operation,
89
+ failureCode: "unsupported_source",
90
+ }),
91
+ ).rejects.toThrow(/started|uncertain/i);
92
+ await t.mutation(m("markUnknown"), first.operation);
93
+ await expect(
94
+ t.mutation(m("failBeforeStart"), {
95
+ ...first.operation,
96
+ failureCode: "unsupported_source",
97
+ }),
98
+ ).rejects.toThrow(/started|uncertain/i);
99
+ expect(
100
+ (
101
+ await t.query(q("getOperation"), {
102
+ ...first.operation,
103
+ stripeSubscriptionId: "sub_failure",
104
+ })
105
+ ).state,
106
+ ).toBe("unknown");
107
+ expect(
108
+ await t.mutation(m("prepare"), { ...args, requestKey: "retry" }),
109
+ ).toEqual(first);
110
+ await expect(
111
+ t.mutation(m("failBeforeStart"), {
112
+ ...first.operation,
113
+ failureCode: "raw provider error with credential",
114
+ }),
115
+ ).rejects.toThrow();
116
+ });
@@ -0,0 +1,102 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
+ import type {
4
+ operationDoc,
5
+ preparationDoc,
6
+ operationRefFields,
7
+ } from "./schema.js";
8
+ type Scope = { accountId: string; scopeKey: string };
9
+ type Ref = {
10
+ [K in keyof typeof operationRefFields]: Infer<(typeof operationRefFields)[K]>;
11
+ };
12
+ function canonical(value: unknown): unknown {
13
+ if (Array.isArray(value)) return value.map(canonical);
14
+ if (value !== null && typeof value === "object")
15
+ return Object.fromEntries(
16
+ Object.entries(value)
17
+ .sort(([a], [b]) => a.localeCompare(b))
18
+ .map(([key, item]) => [key, canonical(item)]),
19
+ );
20
+ return value;
21
+ }
22
+ export const fingerprint = (value: unknown) => JSON.stringify(canonical(value));
23
+ export const same = (a: unknown, b: unknown) =>
24
+ fingerprint(a) === fingerprint(b);
25
+ export function text(value: string) {
26
+ if (!value.trim() || value.length > 200)
27
+ throw new Error("Invalid balance funding identity.");
28
+ }
29
+ export function validateScope(scope: Scope) {
30
+ text(scope.accountId);
31
+ text(scope.scopeKey);
32
+ }
33
+ export function integer(value: number, minimum = 0) {
34
+ if (!Number.isSafeInteger(value) || value < minimum)
35
+ throw new Error("Invalid balance funding version or time.");
36
+ }
37
+ export const unavailable = (
38
+ reason: "identity_changed" | "revision_changed" | "scope_busy",
39
+ ) => ({ status: "conflict" as const, reason, retryable: false as const });
40
+ export async function readPreparation(
41
+ ctx: QueryCtx | MutationCtx,
42
+ args: Scope & { preparationId: Infer<typeof preparationDoc>["_id"] },
43
+ ) {
44
+ validateScope(args);
45
+ const value = await ctx.db.get(
46
+ "balanceFundingPreparations",
47
+ args.preparationId,
48
+ );
49
+ if (
50
+ value &&
51
+ (value.accountId !== args.accountId || value.scopeKey !== args.scopeKey)
52
+ )
53
+ throw new Error("Balance funding scope identity does not match.");
54
+ return value;
55
+ }
56
+ export async function readOperation(ctx: QueryCtx | MutationCtx, args: Ref) {
57
+ validateScope(args);
58
+ integer(args.version, 1);
59
+ const value = await ctx.db.get("balanceFundingOperations", args.operationId);
60
+ if (
61
+ value &&
62
+ (value.accountId !== args.accountId ||
63
+ value.scopeKey !== args.scopeKey ||
64
+ value.version !== args.version)
65
+ )
66
+ throw new Error("Balance funding operation identity does not match.");
67
+ return value;
68
+ }
69
+ export function ref(value: Infer<typeof operationDoc>) {
70
+ return {
71
+ accountId: value.accountId,
72
+ scopeKey: value.scopeKey,
73
+ operationId: value._id,
74
+ version: value.version,
75
+ };
76
+ }
77
+ export function validateOriginal(value: {
78
+ customerAccount: string;
79
+ stripeSubscriptionId: string;
80
+ previousPaymentMethodId: string | null;
81
+ previousPaymentMethodTypes: string[] | null;
82
+ paymentMethodId?: string;
83
+ }) {
84
+ text(value.customerAccount);
85
+ text(value.stripeSubscriptionId);
86
+ if (
87
+ value.paymentMethodId !== undefined &&
88
+ value.previousPaymentMethodId === value.paymentMethodId
89
+ )
90
+ throw new Error("Invalid restoration balance payment method.");
91
+ if (value.previousPaymentMethodId !== null)
92
+ text(value.previousPaymentMethodId);
93
+ if (value.previousPaymentMethodTypes !== null) {
94
+ if (value.previousPaymentMethodTypes.includes("stripe_balance"))
95
+ throw new Error(
96
+ "Invalid restoration from an already-enabled subscription.",
97
+ );
98
+ if (value.previousPaymentMethodTypes.length > 50)
99
+ throw new Error("Invalid restoration payment method types.");
100
+ value.previousPaymentMethodTypes.forEach(text);
101
+ }
102
+ }
@@ -0,0 +1,221 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_owner", scopeKey: "legacy-owner" };
11
+ const record = {
12
+ ...scope,
13
+ sourceKey: "legacy-row-1",
14
+ preparation: {
15
+ customerAccount: scope.accountId,
16
+ stripeSubscriptionId: "sub_legacy",
17
+ paymentMethodId: "pm_balance",
18
+ previousPaymentMethodId: "pm_card",
19
+ previousPaymentMethodTypes: ["card"],
20
+ },
21
+ consentAt: 100,
22
+ consentReference: "legacy-consent",
23
+ providerApiVersion: "2026-06-30.preview",
24
+ enabled: true,
25
+ operationVersion: 7,
26
+ pending: {
27
+ enabled: false,
28
+ providerKey: "example_balance_sub_legacy_7",
29
+ requestKey: "legacy-disable",
30
+ },
31
+ };
32
+ it("imports pending legacy settings and exact provider keys once", async () => {
33
+ const t = convexTest(schema, modules);
34
+ const saved = await t.mutation(m("importPreparation"), record);
35
+ expect(await t.mutation(m("importPreparation"), record)).toEqual(saved);
36
+ const setting = await t.query(q("readPreparation"), {
37
+ ...{
38
+ ...scope,
39
+ preparationId: saved.preparationId,
40
+ },
41
+ stripeSubscriptionId: "sub_legacy",
42
+ });
43
+ expect(setting.preparation).toEqual(record.preparation);
44
+ expect(setting.enabled).toBe(true);
45
+ expect(setting.operationVersion).toBe(7);
46
+ const operation = await t.query(q("inspectOperation"), {
47
+ ...saved.operation,
48
+ stripeSubscriptionId: "sub_legacy",
49
+ });
50
+ expect(operation.state).toBe("unknown");
51
+ expect(operation.providerKeys).toEqual({
52
+ enable: "example_balance_sub_legacy_7:enable",
53
+ disable: "example_balance_sub_legacy_7:disable",
54
+ });
55
+ expect(
56
+ await t.mutation(m("begin"), {
57
+ ...scope,
58
+ preparationId: saved.preparationId,
59
+ enabled: false,
60
+ requestKey: "legacy-disable",
61
+ }),
62
+ ).toEqual({ status: "accepted", operation: saved.operation });
63
+ await t.mutation(m("finish"), {
64
+ ...saved.operation,
65
+ enabled: false,
66
+ receipt: {
67
+ customerAccount: scope.accountId,
68
+ stripeSubscriptionId: "sub_legacy",
69
+ paymentMethodId: "pm_card",
70
+ paymentMethodTypes: ["card"],
71
+ providerApiVersion: record.providerApiVersion,
72
+ },
73
+ });
74
+ expect(await t.mutation(m("importPreparation"), record)).toEqual(saved);
75
+ expect(
76
+ (
77
+ await t.query(q("readPreparation"), {
78
+ ...{
79
+ ...scope,
80
+ preparationId: saved.preparationId,
81
+ },
82
+ stripeSubscriptionId: "sub_legacy",
83
+ })
84
+ ).enabled,
85
+ ).toBe(false);
86
+ });
87
+ it("rejects conflicting import payloads and preserves saved restoration", async () => {
88
+ const t = convexTest(schema, modules);
89
+ const saved = await t.mutation(m("importPreparation"), record);
90
+ for (const changed of [
91
+ {
92
+ ...record,
93
+ preparation: {
94
+ ...record.preparation,
95
+ previousPaymentMethodId: "pm_other",
96
+ },
97
+ },
98
+ { ...record, pending: { ...record.pending, providerKey: "new-key" } },
99
+ { ...record, scopeKey: "other" },
100
+ { ...record, sourceKey: "other-source", operationVersion: 8 },
101
+ ])
102
+ await expect(t.mutation(m("importPreparation"), changed)).rejects.toThrow(
103
+ /conflict|identity|existing/i,
104
+ );
105
+ expect(
106
+ (
107
+ await t.query(q("readPreparation"), {
108
+ ...{
109
+ ...scope,
110
+ preparationId: saved.preparationId,
111
+ },
112
+ stripeSubscriptionId: "sub_legacy",
113
+ })
114
+ ).preparation.previousPaymentMethodId,
115
+ ).toBe("pm_card");
116
+ });
117
+ it("imports interrupted legacy preparation with its original create and attach keys", async () => {
118
+ const t = convexTest(schema, modules);
119
+ const { paymentMethodId: _paymentMethodId, ...original } = record.preparation;
120
+ const legacy = {
121
+ ...record,
122
+ preparation: original,
123
+ enabled: false,
124
+ pending: {
125
+ enabled: false,
126
+ kind: "prepare",
127
+ providerKey: "example_balance_prepare_sub_legacy",
128
+ requestKey: "legacy-prepare",
129
+ },
130
+ };
131
+ const saved = await t.mutation(m("importPreparation"), legacy);
132
+ const op = await t.query(q("inspectOperation"), {
133
+ ...saved.operation,
134
+ stripeSubscriptionId: "sub_legacy",
135
+ });
136
+ expect(op.kind).toBe("prepare");
137
+ expect(op.providerKeys.create).toBe(
138
+ "example_balance_prepare_sub_legacy:create",
139
+ );
140
+ expect(op.providerKeys.attach).toBe(
141
+ "example_balance_prepare_sub_legacy:attach",
142
+ );
143
+ expect(
144
+ await t.query(q("getPreparation"), {
145
+ ...saved.operation,
146
+ stripeSubscriptionId: "sub_legacy",
147
+ }),
148
+ ).toEqual({ status: "unknown", operation: saved.operation });
149
+ expect(
150
+ await t.mutation(m("prepare"), {
151
+ ...scope,
152
+ preparation: original,
153
+ consent: true,
154
+ consentAt: record.consentAt,
155
+ consentReference: record.consentReference,
156
+ providerApiVersion: record.providerApiVersion,
157
+ requestKey: "legacy-prepare",
158
+ }),
159
+ ).toEqual({ status: "accepted", operation: saved.operation });
160
+ await t.mutation(m("finishPreparation"), {
161
+ ...saved.operation,
162
+ preparation: record.preparation,
163
+ providerApiVersion: record.providerApiVersion,
164
+ });
165
+ expect(
166
+ (
167
+ await t.query(q("getPreparation"), {
168
+ ...saved.operation,
169
+ stripeSubscriptionId: "sub_legacy",
170
+ })
171
+ ).status,
172
+ ).toBe("prepared");
173
+ });
174
+ it("rolls back an import whose request identity already belongs to another scope", async () => {
175
+ const t = convexTest(schema, modules);
176
+ await t.mutation(m("importPreparation"), record);
177
+ await expect(
178
+ t.mutation(m("importPreparation"), {
179
+ ...record,
180
+ sourceKey: "row2",
181
+ scopeKey: "other",
182
+ preparation: { ...record.preparation, stripeSubscriptionId: "sub_other" },
183
+ }),
184
+ ).rejects.toThrow(/request identity/i);
185
+ expect(
186
+ (await t.run((ctx) => ctx.db.query("balanceFundingPreparations").take(10)))
187
+ .length,
188
+ ).toBe(1);
189
+ });
190
+ it("requires verification before applying an imported unresolved preparation", async () => {
191
+ const t = convexTest(schema, modules);
192
+ const legacy = {
193
+ ...record,
194
+ enabled: false,
195
+ pending: {
196
+ enabled: false,
197
+ kind: "prepare",
198
+ providerKey: "example_balance_prepare_sub_legacy",
199
+ requestKey: "legacy-prepare",
200
+ },
201
+ };
202
+ const saved = await t.mutation(m("importPreparation"), legacy);
203
+ await t.mutation(m("setStartsPaused"), {
204
+ ...scope,
205
+ preparationId: saved.preparationId,
206
+ stripeSubscriptionId: "sub_legacy",
207
+ paused: false,
208
+ });
209
+ expect(
210
+ await t.mutation(m("begin"), {
211
+ ...scope,
212
+ preparationId: saved.preparationId,
213
+ enabled: false,
214
+ requestKey: "disable",
215
+ }),
216
+ ).toEqual({
217
+ status: "not_ready",
218
+ reason: "provider_pending",
219
+ retryable: true,
220
+ });
221
+ });
@@ -0,0 +1,146 @@
1
+ import { validateOriginal } from "./helpers.js";
2
+ import type { Infer } from "convex/values";
3
+ import type { MutationCtx } from "../_generated/server.js";
4
+ import { text, integer, validateScope, fingerprint } from "./helpers.js";
5
+ import { importPreparationArgs } from "./mutationValidators.js";
6
+ export async function importPreparationHandler(
7
+ ctx: MutationCtx,
8
+ args: Infer<typeof importPreparationArgs>,
9
+ ) {
10
+ validateScope(args);
11
+ text(args.sourceKey);
12
+ text(args.consentReference);
13
+ text(args.providerApiVersion);
14
+ integer(args.consentAt);
15
+ integer(args.operationVersion, args.pending ? 1 : 0);
16
+ validateOriginal(args.preparation);
17
+ text(args.preparation.stripeSubscriptionId);
18
+ if (args.preparation.paymentMethodId) text(args.preparation.paymentMethodId);
19
+ else if (args.pending?.kind !== "prepare")
20
+ throw new Error("Invalid legacy preparation state.");
21
+ if (
22
+ args.pending?.kind === "prepare" &&
23
+ (args.enabled || args.pending.enabled)
24
+ )
25
+ throw new Error("Invalid legacy preparation target.");
26
+ if (args.accountId !== args.preparation.customerAccount)
27
+ throw new Error("Legacy preparation account identity conflict.");
28
+ const requestKey = `import:${args.sourceKey}`;
29
+ const payload = fingerprint(args);
30
+ const prior = await ctx.db
31
+ .query("balanceFundingRequests")
32
+ .withIndex("by_request", (q) => q.eq("requestKey", requestKey))
33
+ .unique();
34
+ if (prior) {
35
+ if (prior.payload !== payload || !prior.imported)
36
+ throw new Error("Legacy import identity conflict.");
37
+ return prior.imported;
38
+ }
39
+ const existing = await ctx.db
40
+ .query("balanceFundingPreparations")
41
+ .withIndex("by_account_subscription", (q) =>
42
+ q
43
+ .eq("accountId", args.accountId)
44
+ .eq(
45
+ "preparation.stripeSubscriptionId",
46
+ args.preparation.stripeSubscriptionId,
47
+ ),
48
+ )
49
+ .unique();
50
+ if (existing)
51
+ throw new Error("Existing preparation cannot be overwritten by import.");
52
+ const preparationId = await ctx.db.insert("balanceFundingPreparations", {
53
+ accountId: args.accountId,
54
+ scopeKey: args.scopeKey,
55
+ preparation: args.preparation,
56
+ consentAt: args.consentAt,
57
+ consentReference: args.consentReference,
58
+ providerApiVersion: args.providerApiVersion,
59
+ enabled: args.enabled,
60
+ operationVersion: args.operationVersion,
61
+ startsPaused: true,
62
+ verified: args.pending?.kind !== "prepare",
63
+ });
64
+ let operation;
65
+ if (args.pending) {
66
+ text(args.pending.providerKey);
67
+ text(args.pending.requestKey);
68
+ const collision = await ctx.db
69
+ .query("balanceFundingRequests")
70
+ .withIndex("by_request", (q) =>
71
+ q.eq("requestKey", args.pending!.requestKey),
72
+ )
73
+ .unique();
74
+ if (collision || args.pending.requestKey === requestKey)
75
+ throw new Error("Legacy operation request identity conflict.");
76
+ const operationId = await ctx.db.insert("balanceFundingOperations", {
77
+ accountId: args.accountId,
78
+ scopeKey: args.scopeKey,
79
+ preparationId,
80
+ enabled: args.pending.enabled,
81
+ version: args.operationVersion,
82
+ state: "unknown",
83
+ kind: args.pending.kind ?? "apply",
84
+ providerKey: args.pending.providerKey,
85
+ cancelRequested: false,
86
+ providerKeys: {
87
+ enable: `${args.pending.providerKey}:enable`,
88
+ disable: `${args.pending.providerKey}:disable`,
89
+ ...(args.pending.kind === "prepare"
90
+ ? {
91
+ create: `${args.pending.providerKey}:create`,
92
+ attach: `${args.pending.providerKey}:attach`,
93
+ }
94
+ : {}),
95
+ },
96
+ });
97
+ operation = {
98
+ accountId: args.accountId,
99
+ scopeKey: args.scopeKey,
100
+ operationId,
101
+ version: args.operationVersion,
102
+ };
103
+ await ctx.db.patch("balanceFundingPreparations", preparationId, {
104
+ activeOperationId: operationId,
105
+ });
106
+ await ctx.db.insert("balanceFundingRequests", {
107
+ requestKey: args.pending.requestKey,
108
+ preparationId,
109
+ payload:
110
+ args.pending.kind === "prepare"
111
+ ? fingerprint({
112
+ accountId: args.accountId,
113
+ scopeKey: args.scopeKey,
114
+ preparation: {
115
+ customerAccount: args.preparation.customerAccount,
116
+ stripeSubscriptionId: args.preparation.stripeSubscriptionId,
117
+ previousPaymentMethodId:
118
+ args.preparation.previousPaymentMethodId,
119
+ previousPaymentMethodTypes:
120
+ args.preparation.previousPaymentMethodTypes,
121
+ },
122
+ consent: true,
123
+ consentAt: args.consentAt,
124
+ consentReference: args.consentReference,
125
+ providerApiVersion: args.providerApiVersion,
126
+ requestKey: args.pending.requestKey,
127
+ })
128
+ : fingerprint({
129
+ accountId: args.accountId,
130
+ scopeKey: args.scopeKey,
131
+ preparationId,
132
+ enabled: args.pending.enabled,
133
+ consent: args.pending.enabled ? true : null,
134
+ }),
135
+ result: { status: "accepted", operation },
136
+ });
137
+ }
138
+ const imported = { preparationId, ...(operation ? { operation } : {}) };
139
+ await ctx.db.insert("balanceFundingRequests", {
140
+ requestKey,
141
+ payload,
142
+ preparationId,
143
+ imported,
144
+ });
145
+ return imported;
146
+ }
@@ -0,0 +1,90 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import { readOperation } from "./helpers.js";
4
+ import {
5
+ startArgs,
6
+ requestCancelArgs,
7
+ markUnknownArgs,
8
+ } from "./mutationValidators.js";
9
+ export async function startHandler(
10
+ ctx: MutationCtx,
11
+ args: Infer<typeof startArgs>,
12
+ ) {
13
+ const op = await readOperation(ctx, args);
14
+ if (!op) throw new Error("Balance funding operation is missing.");
15
+ if (op.state !== "pending") return op;
16
+ const setting = await ctx.db.get(
17
+ "balanceFundingPreparations",
18
+ op.preparationId,
19
+ );
20
+ if (
21
+ setting?.activeOperationId !== op._id ||
22
+ setting.operationVersion !== op.version
23
+ )
24
+ throw new Error("Balance funding operation version changed.");
25
+ if (setting.startsPaused)
26
+ throw new Error("Balance funding starts are paused.");
27
+ await ctx.db.patch("balanceFundingOperations", op._id, {
28
+ state: "running",
29
+ });
30
+ return { ...op, state: "running" as const };
31
+ }
32
+ export async function requestCancelHandler(
33
+ ctx: MutationCtx,
34
+ args: Infer<typeof requestCancelArgs>,
35
+ ) {
36
+ const op = await readOperation(ctx, args);
37
+ if (!op) throw new Error("Balance funding operation is missing.");
38
+ if (
39
+ op.state === "succeeded" ||
40
+ op.state === "canceled" ||
41
+ op.state === "failed"
42
+ )
43
+ return op;
44
+ const state = op.state === "pending" ? ("canceled" as const) : op.state;
45
+ await ctx.db.patch("balanceFundingOperations", op._id, {
46
+ state,
47
+ cancelRequested: true,
48
+ });
49
+ if (state === "canceled") {
50
+ const setting = await ctx.db.get(
51
+ "balanceFundingPreparations",
52
+ op.preparationId,
53
+ );
54
+ if (
55
+ setting?.activeOperationId !== op._id ||
56
+ setting.operationVersion !== op.version
57
+ )
58
+ throw new Error("Balance funding operation version changed.");
59
+ await ctx.db.patch("balanceFundingPreparations", setting._id, {
60
+ activeOperationId: undefined,
61
+ });
62
+ }
63
+ return { ...op, state, cancelRequested: true };
64
+ }
65
+ export async function markUnknownHandler(
66
+ ctx: MutationCtx,
67
+ args: Infer<typeof markUnknownArgs>,
68
+ ) {
69
+ const op = await readOperation(ctx, args);
70
+ if (!op) throw new Error("Balance funding operation is missing.");
71
+ if (
72
+ op.state === "succeeded" ||
73
+ op.state === "canceled" ||
74
+ op.state === "failed"
75
+ )
76
+ return op;
77
+ const setting = await ctx.db.get(
78
+ "balanceFundingPreparations",
79
+ op.preparationId,
80
+ );
81
+ if (
82
+ setting?.activeOperationId !== op._id ||
83
+ setting.operationVersion !== op.version
84
+ )
85
+ throw new Error("Balance funding operation version changed.");
86
+ await ctx.db.patch("balanceFundingOperations", op._id, {
87
+ state: "unknown",
88
+ });
89
+ return { ...op, state: "unknown" as const };
90
+ }