@fantastic.dev/better-stripe 0.55.0 → 0.56.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 (212) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +216 -38
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +92 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +216 -38
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +92 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/catalogPrices.d.ts +2 -0
  16. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  17. package/dist/client/usage/catalogPrices.js +15 -0
  18. package/dist/client/usage/catalogPrices.js.map +1 -1
  19. package/dist/client/usage/client.d.ts +2 -2
  20. package/dist/client/usage/client.d.ts.map +1 -1
  21. package/dist/client/usage/client.js +2 -2
  22. package/dist/client/usage/client.js.map +1 -1
  23. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  24. package/dist/client/usage/deliveryProvider.js +26 -1
  25. package/dist/client/usage/deliveryProvider.js.map +1 -1
  26. package/dist/client/usage/index.d.ts +4 -0
  27. package/dist/client/usage/index.d.ts.map +1 -1
  28. package/dist/client/usage/index.js +1 -0
  29. package/dist/client/usage/index.js.map +1 -1
  30. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  31. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  32. package/dist/client/usage/subscription.fixtures.js +84 -0
  33. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  34. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  35. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  36. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  37. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  38. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  39. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  40. package/dist/client/usage/subscriptionCancellation.js +39 -0
  41. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  42. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  43. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  44. package/dist/client/usage/subscriptionCheckout.js +94 -0
  45. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  46. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  47. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  48. package/dist/client/usage/subscriptionClient.js +93 -0
  49. package/dist/client/usage/subscriptionClient.js.map +1 -0
  50. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  51. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  52. package/dist/client/usage/subscriptionErrors.js +9 -0
  53. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  54. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  55. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  57. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  58. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  59. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  61. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  62. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  63. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionProvider.js +147 -0
  65. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  66. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  67. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionTerms.js +242 -0
  69. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  70. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  71. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  73. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  74. package/dist/client/webhooks/processors.d.ts.map +1 -1
  75. package/dist/client/webhooks/processors.js +2 -0
  76. package/dist/client/webhooks/processors.js.map +1 -1
  77. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  78. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  79. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  80. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  81. package/dist/component/_generated/api.d.ts +14 -0
  82. package/dist/component/_generated/api.d.ts.map +1 -1
  83. package/dist/component/_generated/api.js.map +1 -1
  84. package/dist/component/_generated/component.d.ts +160 -5
  85. package/dist/component/_generated/component.d.ts.map +1 -1
  86. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  87. package/dist/component/accountClosure/mutations.js +10 -0
  88. package/dist/component/accountClosure/mutations.js.map +1 -1
  89. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  90. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  91. package/dist/component/earnings/triggers.d.ts +192 -4
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/payoutRelease/queries.d.ts +2 -2
  94. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  95. package/dist/component/schema.d.ts +92 -3
  96. package/dist/component/schema.js +5 -0
  97. package/dist/component/schema.js.map +1 -1
  98. package/dist/component/usage/mutations.d.ts.map +1 -1
  99. package/dist/component/usage/mutations.js +5 -0
  100. package/dist/component/usage/mutations.js.map +1 -1
  101. package/dist/component/usage/queries.d.ts +2 -0
  102. package/dist/component/usage/queries.d.ts.map +1 -1
  103. package/dist/component/usage/schema.d.ts +14 -7
  104. package/dist/component/usage/schema.d.ts.map +1 -1
  105. package/dist/component/usage/schema.js +5 -1
  106. package/dist/component/usage/schema.js.map +1 -1
  107. package/dist/component/usageDelivery/fields.d.ts +3 -2
  108. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  109. package/dist/component/usageDelivery/fields.js +2 -1
  110. package/dist/component/usageDelivery/fields.js.map +1 -1
  111. package/dist/component/usageDelivery/helpers.d.ts +4 -3
  112. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  113. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  114. package/dist/component/usageDelivery/queries.d.ts +17 -3
  115. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  116. package/dist/component/usageDelivery/queries.js +20 -3
  117. package/dist/component/usageDelivery/queries.js.map +1 -1
  118. package/dist/component/usageDelivery/schema.d.ts +2 -2
  119. package/dist/component/usageDelivery/steps.d.ts +1 -1
  120. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  121. package/dist/component/usageDelivery/steps.js +12 -1
  122. package/dist/component/usageDelivery/steps.js.map +1 -1
  123. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  124. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  125. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  126. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  127. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  128. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  129. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  130. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  131. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  132. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  133. package/dist/component/usageSubscriptions/helpers.js +28 -0
  134. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  135. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  136. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  137. package/dist/component/usageSubscriptions/history.js +46 -0
  138. package/dist/component/usageSubscriptions/history.js.map +1 -0
  139. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  140. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  141. package/dist/component/usageSubscriptions/mutations.js +252 -0
  142. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  143. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  144. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  145. package/dist/component/usageSubscriptions/queries.js +70 -0
  146. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  147. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  148. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  149. package/dist/component/usageSubscriptions/retirement.js +80 -0
  150. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  151. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  152. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  153. package/dist/component/usageSubscriptions/schema.js +69 -0
  154. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  155. package/dist/test.d.ts +6 -0
  156. package/dist/test.d.ts.map +1 -0
  157. package/dist/test.js +15 -0
  158. package/dist/test.js.map +1 -0
  159. package/docs/README.md +2 -0
  160. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  161. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  162. package/docs/evidence/native-metering/paid-run.json +107 -0
  163. package/docs/evidence/native-metering/promotional-run.json +103 -0
  164. package/docs/metered-usage.md +14 -0
  165. package/docs/metering-setup.md +5 -1
  166. package/docs/usage-subscriptions.md +278 -0
  167. package/package.json +4 -2
  168. package/src/client/index.ts +8 -0
  169. package/src/client/usage/catalogPrices.ts +21 -0
  170. package/src/client/usage/client.ts +2 -2
  171. package/src/client/usage/deliveryProvider.test.ts +70 -1
  172. package/src/client/usage/deliveryProvider.ts +43 -2
  173. package/src/client/usage/index.ts +9 -0
  174. package/src/client/usage/subscription.fixtures.ts +84 -0
  175. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  176. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  177. package/src/client/usage/subscriptionCancellation.ts +90 -0
  178. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  179. package/src/client/usage/subscriptionCheckout.ts +152 -0
  180. package/src/client/usage/subscriptionClient.test.ts +316 -0
  181. package/src/client/usage/subscriptionClient.ts +204 -0
  182. package/src/client/usage/subscriptionErrors.ts +14 -0
  183. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  184. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  185. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  186. package/src/client/usage/subscriptionProvider.ts +247 -0
  187. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  188. package/src/client/usage/subscriptionTerms.ts +294 -0
  189. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  190. package/src/client/webhooks/processors.ts +2 -0
  191. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  192. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  193. package/src/component/_generated/api.ts +14 -0
  194. package/src/component/_generated/component.ts +200 -0
  195. package/src/component/accountClosure/mutations.ts +12 -0
  196. package/src/component/schema.ts +10 -0
  197. package/src/component/usage/mutations.ts +5 -0
  198. package/src/component/usage/schema.ts +5 -1
  199. package/src/component/usageDelivery/fields.ts +2 -0
  200. package/src/component/usageDelivery/queries.ts +30 -3
  201. package/src/component/usageDelivery/steps.ts +22 -1
  202. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  203. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  204. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  205. package/src/component/usageSubscriptions/helpers.ts +33 -0
  206. package/src/component/usageSubscriptions/history.test.ts +69 -0
  207. package/src/component/usageSubscriptions/history.ts +68 -0
  208. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  209. package/src/component/usageSubscriptions/mutations.ts +275 -0
  210. package/src/component/usageSubscriptions/queries.ts +78 -0
  211. package/src/component/usageSubscriptions/retirement.ts +105 -0
  212. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,84 @@
1
+ export const meter = {
2
+ scope: {
3
+ stripeAccountId: "acct_platform",
4
+ customerAccount: "acct_buyer",
5
+ meterId: "mtr_calls",
6
+ livemode: false,
7
+ },
8
+ binding: {
9
+ stripeCustomerId: "cus_buyer",
10
+ stripePriceId: "price_calls",
11
+ eventName: "calls",
12
+ plan: {
13
+ key: "calls",
14
+ version: "v1",
15
+ model: "included_overage" as const,
16
+ unit: { name: "call", precision: 0 },
17
+ rate: { currency: "usd", unitAmountDecimal: "2" },
18
+ includedQuantity: "10",
19
+ reset: "billing_period" as const,
20
+ },
21
+ },
22
+ };
23
+ export const request = {
24
+ requestId: "signup1",
25
+ meters: [meter],
26
+ fixedPriceIds: ["price_base"],
27
+ collection: { method: "send_invoice" as const, daysUntilDue: 30 },
28
+ };
29
+ export function nativeSubscription() {
30
+ return {
31
+ id: "sub_calls",
32
+ latest_invoice: "in_initial",
33
+ livemode: false,
34
+ customer_account: "acct_buyer",
35
+ customer: "cus_buyer",
36
+ status: "active",
37
+ currency: "usd",
38
+ collection_method: "send_invoice" as
39
+ "send_invoice" | "charge_automatically",
40
+ days_until_due: 30 as number | null,
41
+ default_payment_method: null as string | null,
42
+ billing_mode: { type: "flexible" },
43
+ cancel_at_period_end: false,
44
+ cancel_at: null,
45
+ items: {
46
+ data: [
47
+ {
48
+ id: "si_calls",
49
+ current_period_start: 600,
50
+ current_period_end: 1200,
51
+ quantity: null,
52
+ price: {
53
+ id: "price_calls",
54
+ currency: "usd",
55
+ recurring: {
56
+ interval: "month",
57
+ interval_count: 1,
58
+ usage_type: "metered",
59
+ meter: "mtr_calls",
60
+ },
61
+ unit_amount_decimal: null,
62
+ },
63
+ },
64
+ {
65
+ id: "si_base",
66
+ current_period_start: 600,
67
+ current_period_end: 1200,
68
+ quantity: 1,
69
+ price: {
70
+ id: "price_base",
71
+ currency: "usd",
72
+ recurring: {
73
+ interval: "month",
74
+ interval_count: 1,
75
+ usage_type: "licensed",
76
+ },
77
+ unit_amount_decimal: "1000",
78
+ },
79
+ },
80
+ ],
81
+ has_more: false,
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,124 @@
1
+ import { expect, it } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { fixture } from "./subscriptionTransport.fixtures.js";
5
+ import { request } from "./subscription.fixtures.js";
6
+ const ref = {
7
+ scope: {
8
+ stripeAccountId: "acct_platform",
9
+ customerAccount: "acct_buyer",
10
+ livemode: false,
11
+ },
12
+ requestId: "signup1",
13
+ };
14
+ it("releases a verified expired unpaid Checkout with no subscription or payment references", async () => {
15
+ const f = fixture(),
16
+ client = new BetterStripe(f.component),
17
+ options = {
18
+ stripeSecretKey: "sk_test_subscription",
19
+ httpClient: f.httpClient,
20
+ };
21
+ const input = {
22
+ ...request,
23
+ collection: {
24
+ method: "checkout" as const,
25
+ successUrl: "https://example.test/success",
26
+ cancelUrl: "https://example.test/cancel",
27
+ },
28
+ };
29
+ await f.t.action((ctx) =>
30
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
31
+ );
32
+ Object.assign(f.state.session!, {
33
+ status: "expired",
34
+ payment_status: "unpaid",
35
+ payment_intent: null,
36
+ setup_intent: null,
37
+ });
38
+ expect(
39
+ await f.t.action((ctx) =>
40
+ client.usage.abandonSignup(ctx as RunCtx, ref, options),
41
+ ),
42
+ ).toMatchObject({
43
+ abandoned: true,
44
+ creditTreatment: "retain_original_terms",
45
+ });
46
+ await f.t.action((ctx) =>
47
+ client.usage.abandonSignup(ctx as RunCtx, ref, options),
48
+ );
49
+ expect(
50
+ await f.t.action((ctx) =>
51
+ client.usage.ensureCheckout(
52
+ ctx as RunCtx,
53
+ { ...input, requestId: "retry2" },
54
+ options,
55
+ ),
56
+ ),
57
+ ).toMatchObject({ status: "open" });
58
+ });
59
+ it("does not unlock an expired session with unresolved financial references", async () => {
60
+ const f = fixture(),
61
+ client = new BetterStripe(f.component),
62
+ options = {
63
+ stripeSecretKey: "sk_test_subscription",
64
+ httpClient: f.httpClient,
65
+ };
66
+ const input = {
67
+ ...request,
68
+ collection: {
69
+ method: "checkout" as const,
70
+ successUrl: "https://example.test/success",
71
+ cancelUrl: "https://example.test/cancel",
72
+ },
73
+ };
74
+ await f.t.action((ctx) =>
75
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
76
+ );
77
+ Object.assign(f.state.session!, {
78
+ status: "expired",
79
+ payment_status: "unpaid",
80
+ payment_intent: "pi_pending",
81
+ setup_intent: null,
82
+ });
83
+ await expect(
84
+ f.t.action((ctx) =>
85
+ client.usage.abandonSignup(ctx as RunCtx, ref, options),
86
+ ),
87
+ ).rejects.toThrow();
88
+ await expect(
89
+ f.t.action((ctx) =>
90
+ client.usage.ensureCheckout(
91
+ ctx as RunCtx,
92
+ { ...input, requestId: "retry2" },
93
+ options,
94
+ ),
95
+ ),
96
+ ).rejects.toThrow();
97
+ });
98
+
99
+ it("permits a new request after a verified incomplete-expired subscription with a void unpaid initial invoice", async () => {
100
+ const f = fixture(),
101
+ client = new BetterStripe(f.component),
102
+ options = {
103
+ stripeSecretKey: "sk_test_subscription",
104
+ httpClient: f.httpClient,
105
+ };
106
+ await f.t.action((ctx) =>
107
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
108
+ );
109
+ f.state.native!.status = "incomplete_expired";
110
+ expect(
111
+ await f.t.action((ctx) =>
112
+ client.usage.abandonSignup(ctx as RunCtx, ref, options),
113
+ ),
114
+ ).toMatchObject({ abandoned: true });
115
+ expect(
116
+ await f.t.action((ctx) =>
117
+ client.usage.ensureSubscription(
118
+ ctx as RunCtx,
119
+ { ...request, requestId: "retry2" },
120
+ options,
121
+ ),
122
+ ),
123
+ ).toMatchObject({ subscriptionId: "sub_calls2" });
124
+ });
@@ -0,0 +1,116 @@
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 type { Doc } from "../../component/_generated/dataModel.js";
6
+ import { subscriptionTerms } from "./subscriptionTerms.js";
7
+ import { abandonmentProof } from "./subscriptionInvoiceSchema.js";
8
+ import {
9
+ subscriptionCall,
10
+ UsageSubscriptionError,
11
+ verifySubscriptionRealm,
12
+ } from "./subscriptionProvider.js";
13
+ export async function abandonManagedSignup(
14
+ stripe: Stripe,
15
+ component: Component,
16
+ ctx: RunCtx,
17
+ row: Doc<"usageSubscriptionIntents">,
18
+ ) {
19
+ const terms = subscriptionTerms(JSON.parse(row.termsJson)),
20
+ first = terms.meters[0];
21
+ return subscriptionCall(async () => {
22
+ await verifySubscriptionRealm(stripe, terms);
23
+ const base = {
24
+ stripeAccountId: first.scope.stripeAccountId,
25
+ customerAccount: first.scope.customerAccount,
26
+ stripeCustomerId: first.binding.stripeCustomerId,
27
+ livemode: first.scope.livemode,
28
+ };
29
+ let proof;
30
+ if (row.providerId) {
31
+ const sub = await stripe.subscriptions.retrieve(row.providerId);
32
+ const invoiceId =
33
+ typeof sub.latest_invoice === "string"
34
+ ? sub.latest_invoice
35
+ : sub.latest_invoice?.id;
36
+ if (
37
+ sub.id !== row.providerId ||
38
+ sub.status !== "incomplete_expired" ||
39
+ sub.customer_account !== base.customerAccount ||
40
+ sub.livemode !== base.livemode ||
41
+ (typeof sub.customer === "string" ? sub.customer : sub.customer?.id) !==
42
+ base.stripeCustomerId ||
43
+ !invoiceId
44
+ )
45
+ throw new UsageSubscriptionError(
46
+ "incompatible_terms",
47
+ "Signup is not a verified expired unpaid subscription",
48
+ );
49
+ const invoice = await stripe.invoices.retrieve(invoiceId);
50
+ const parent = invoice.parent?.subscription_details?.subscription;
51
+ if (
52
+ invoice.id !== invoiceId ||
53
+ (typeof parent === "string" ? parent : parent?.id) !== sub.id ||
54
+ invoice.customer_account !== base.customerAccount ||
55
+ invoice.livemode !== base.livemode ||
56
+ (typeof invoice.customer === "string"
57
+ ? invoice.customer
58
+ : invoice.customer?.id) !== base.stripeCustomerId
59
+ )
60
+ throw new UsageSubscriptionError(
61
+ "incompatible_terms",
62
+ "Expired signup invoice binding mismatch",
63
+ );
64
+ proof = abandonmentProof.parse({
65
+ ...base,
66
+ kind: "subscription",
67
+ nativeId: sub.id,
68
+ status: sub.status,
69
+ invoiceId,
70
+ invoiceStatus: invoice.status,
71
+ invoiceAmountPaid: String(invoice.amount_paid),
72
+ billingReason: invoice.billing_reason,
73
+ });
74
+ } else {
75
+ if (!row.checkoutId)
76
+ throw new UsageSubscriptionError(
77
+ "unknown_create_outcome",
78
+ "Unknown signup must be reconciled before abandonment",
79
+ );
80
+ const session = await stripe.checkout.sessions.retrieve(row.checkoutId);
81
+ if (
82
+ session.id !== row.checkoutId ||
83
+ session.mode !== "subscription" ||
84
+ session.metadata?.bsUsageIntent !== row.key ||
85
+ session.customer_account !== base.customerAccount ||
86
+ session.livemode !== base.livemode ||
87
+ (typeof session.customer === "string"
88
+ ? session.customer
89
+ : session.customer?.id) !== base.stripeCustomerId
90
+ )
91
+ throw new UsageSubscriptionError(
92
+ "incompatible_terms",
93
+ "Expired Checkout binding mismatch",
94
+ );
95
+ proof = abandonmentProof.parse({
96
+ ...base,
97
+ kind: "checkout",
98
+ nativeId: session.id,
99
+ status: session.status,
100
+ subscription: session.subscription,
101
+ paymentIntent: session.payment_intent,
102
+ setupIntent: session.setup_intent,
103
+ paymentStatus: session.payment_status,
104
+ });
105
+ }
106
+ await runMutationOrThrow(
107
+ ctx,
108
+ componentRef(component, "usageSubscriptions/mutations/abandon"),
109
+ { key: row.key, proofJson: JSON.stringify(proof) },
110
+ );
111
+ return {
112
+ abandoned: true as const,
113
+ creditTreatment: "retain_original_terms" as const,
114
+ };
115
+ });
116
+ }
@@ -0,0 +1,90 @@
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 type { Doc } from "../../component/_generated/dataModel.js";
6
+ import {
7
+ subscriptionTerms,
8
+ subscriptionEvidence,
9
+ subscriptionView,
10
+ type UsageSubscriptionView,
11
+ } from "./subscriptionTerms.js";
12
+ import {
13
+ subscriptionCall,
14
+ UsageSubscriptionError,
15
+ verifySubscriptionRealm,
16
+ } from "./subscriptionProvider.js";
17
+ export async function changeManagedCancellation(
18
+ stripe: Stripe,
19
+ component: Component,
20
+ ctx: RunCtx,
21
+ row: Doc<"usageSubscriptionIntents">,
22
+ input: { operationId: string; cancelAtPeriodEnd: boolean },
23
+ ): Promise<UsageSubscriptionView> {
24
+ const terms = subscriptionTerms(JSON.parse(row.termsJson)),
25
+ startedAt = Date.now();
26
+ return subscriptionCall(async () => {
27
+ if (!row.providerId)
28
+ throw new UsageSubscriptionError(
29
+ "incompatible_terms",
30
+ "Managed subscription not observed",
31
+ );
32
+ await verifySubscriptionRealm(stripe, terms);
33
+ const command = (await runMutationOrThrow(
34
+ ctx,
35
+ componentRef(
36
+ component,
37
+ "usageSubscriptions/mutations/prepareCancellation",
38
+ ),
39
+ { key: row.key, ...input },
40
+ )) as Doc<"usageSubscriptionControls">;
41
+ const resultView = (json: string) => {
42
+ const view = JSON.parse(json) as UsageSubscriptionView;
43
+ if (
44
+ !input.cancelAtPeriodEnd &&
45
+ ["canceled", "incomplete_expired"].includes(view.status)
46
+ )
47
+ throw new UsageSubscriptionError(
48
+ "incompatible_terms",
49
+ "A canceled native subscription cannot be reactivated",
50
+ );
51
+ return view;
52
+ };
53
+ if (command.resultJson) return resultView(command.resultJson);
54
+ let native = await stripe.subscriptions.retrieve(row.providerId);
55
+ if (native.id !== row.providerId)
56
+ throw new UsageSubscriptionError(
57
+ "incompatible_terms",
58
+ "Pinned subscription identity changed",
59
+ );
60
+ subscriptionView(native, terms);
61
+ if (
62
+ native.cancel_at_period_end !== input.cancelAtPeriodEnd &&
63
+ !["canceled", "incomplete_expired"].includes(native.status)
64
+ ) {
65
+ if (Date.now() / 1000 - command.firstAttemptAt >= 23 * 3600)
66
+ throw new UsageSubscriptionError(
67
+ "unknown_create_outcome",
68
+ "Cancellation requires reconciliation after its safe retry window",
69
+ );
70
+ native = await stripe.subscriptions.update(
71
+ row.providerId,
72
+ { cancel_at_period_end: input.cancelAtPeriodEnd },
73
+ { idempotencyKey: `bs_usage_cancel_${command.key}` },
74
+ );
75
+ }
76
+ const result = await runMutationOrThrow(
77
+ ctx,
78
+ componentRef(
79
+ component,
80
+ "usageSubscriptions/mutations/completeCancellation",
81
+ ),
82
+ {
83
+ key: command.key,
84
+ nativeJson: JSON.stringify(subscriptionEvidence(native)),
85
+ startedAt,
86
+ },
87
+ );
88
+ return resultView(result);
89
+ });
90
+ }
@@ -0,0 +1,31 @@
1
+ import { expect, it } from "vitest";
2
+ import { managedCheckoutParams } from "./subscriptionCheckout.js";
3
+ import { subscriptionTerms } from "./subscriptionTerms.js";
4
+ import { request } from "./subscription.fixtures.js";
5
+ it("creates redirect Checkout with flexible mixed items and no metered quantities", () => {
6
+ const terms = subscriptionTerms({
7
+ ...request,
8
+ collection: {
9
+ method: "checkout",
10
+ successUrl: "https://example.test/success",
11
+ cancelUrl: "https://example.test/cancel",
12
+ },
13
+ });
14
+ const params = managedCheckoutParams(terms, "intent");
15
+ expect(params).toMatchObject({
16
+ customer_account: "acct_buyer",
17
+ mode: "subscription",
18
+ subscription_data: {
19
+ billing_mode: { type: "flexible" },
20
+ metadata: { bsUsageIntent: "intent" },
21
+ },
22
+ line_items: [
23
+ { price: "price_calls" },
24
+ { price: "price_base", quantity: 1 },
25
+ ],
26
+ });
27
+ expect(params.line_items?.[0]).not.toHaveProperty("quantity");
28
+ expect(() =>
29
+ managedCheckoutParams(subscriptionTerms(request), "intent"),
30
+ ).toThrow();
31
+ });
@@ -0,0 +1,152 @@
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
+ subscriptionTerms,
7
+ type UsageSubscriptionOptions,
8
+ type UsageSubscriptionTerms,
9
+ } from "./subscriptionTerms.js";
10
+ import {
11
+ subscriptionCall,
12
+ UsageSubscriptionError,
13
+ prepareSubscription,
14
+ verifySubscriptionRealm,
15
+ verifySubscriptionPrices,
16
+ discoverSubscription,
17
+ saveSubscription,
18
+ } from "./subscriptionProvider.js";
19
+ export function managedCheckoutParams(
20
+ terms: UsageSubscriptionTerms,
21
+ key: string,
22
+ ): Stripe.Checkout.SessionCreateParams {
23
+ if (terms.collection.method !== "checkout")
24
+ throw new UsageSubscriptionError(
25
+ "incompatible_terms",
26
+ "Managed Checkout requires Checkout collection",
27
+ );
28
+ return {
29
+ mode: "subscription",
30
+ customer_account: terms.meters[0].scope.customerAccount,
31
+ success_url: terms.collection.successUrl,
32
+ cancel_url: terms.collection.cancelUrl,
33
+ line_items: [
34
+ ...terms.meters.map((m) => ({ price: m.binding.stripePriceId })),
35
+ ...terms.fixedPriceIds.map((price) => ({ price, quantity: 1 })),
36
+ ],
37
+ metadata: { bsUsageIntent: key },
38
+ subscription_data: {
39
+ billing_mode: { type: "flexible" },
40
+ metadata: { bsUsageIntent: key },
41
+ },
42
+ };
43
+ }
44
+ async function findCheckout(
45
+ stripe: Stripe,
46
+ terms: UsageSubscriptionTerms,
47
+ key: string,
48
+ ) {
49
+ let cursor: string | undefined, found: Stripe.Checkout.Session | undefined;
50
+ for (let page = 0; page < 10; page++) {
51
+ const result = await stripe.checkout.sessions.list({
52
+ customer_account: terms.meters[0].scope.customerAccount,
53
+ limit: 100,
54
+ ...(cursor ? { starting_after: cursor } : {}),
55
+ });
56
+ if (result.data.length > 100) break;
57
+ for (const session of result.data)
58
+ if (session.metadata?.bsUsageIntent === key) {
59
+ if (found)
60
+ throw new UsageSubscriptionError(
61
+ "overlapping_enrollment",
62
+ "Ambiguous native usage Checkout identity",
63
+ );
64
+ found = session;
65
+ }
66
+ if (!result.has_more) return found;
67
+ const next = result.data[result.data.length - 1]?.id;
68
+ if (!next || next === cursor) break;
69
+ cursor = next;
70
+ }
71
+ throw new UsageSubscriptionError(
72
+ "incompatible_terms",
73
+ "Native usage Checkout history is incomplete",
74
+ );
75
+ }
76
+ export async function ensureManagedCheckout(
77
+ stripe: Stripe,
78
+ component: Component,
79
+ ctx: RunCtx,
80
+ input: UsageSubscriptionOptions,
81
+ ) {
82
+ const terms = subscriptionTerms(input),
83
+ startedAt = Date.now();
84
+ const params = managedCheckoutParams(terms, "pending");
85
+ return subscriptionCall(async () => {
86
+ await verifySubscriptionRealm(stripe, terms);
87
+ const row = await prepareSubscription(component, ctx, terms, "checkout");
88
+ await discoverSubscription(stripe, terms, row.key);
89
+ let session = row.checkoutId
90
+ ? await stripe.checkout.sessions.retrieve(row.checkoutId)
91
+ : await findCheckout(stripe, terms, row.key);
92
+ if (!session) {
93
+ if (Date.now() / 1000 - row.firstAttemptAt >= 23 * 3600)
94
+ throw new UsageSubscriptionError(
95
+ "unknown_create_outcome",
96
+ "Native Checkout create requires reconciliation after safe retry window",
97
+ );
98
+ await verifySubscriptionPrices(stripe, terms);
99
+ session = await stripe.checkout.sessions.create(
100
+ { ...params, ...managedCheckoutParams(terms, row.key) },
101
+ { idempotencyKey: `bs_usage_checkout_${row.key}` },
102
+ );
103
+ }
104
+ if (
105
+ (row.checkoutId && session.id !== row.checkoutId) ||
106
+ session.customer_account !== terms.meters[0].scope.customerAccount ||
107
+ (typeof session.customer === "string"
108
+ ? session.customer
109
+ : session.customer?.id) !== terms.meters[0].binding.stripeCustomerId ||
110
+ session.livemode !== terms.meters[0].scope.livemode ||
111
+ session.mode !== "subscription" ||
112
+ session.metadata?.bsUsageIntent !== row.key ||
113
+ !["open", "complete", "expired"].includes(session.status ?? "")
114
+ )
115
+ throw new UsageSubscriptionError(
116
+ "incompatible_terms",
117
+ "Native usage Checkout binding mismatch",
118
+ );
119
+ await runMutationOrThrow(
120
+ ctx,
121
+ componentRef(component, "usageSubscriptions/mutations/linkCheckout"),
122
+ { key: row.key, checkoutId: session.id },
123
+ );
124
+ const subscriptionId =
125
+ typeof session.subscription === "string"
126
+ ? session.subscription
127
+ : session.subscription?.id;
128
+ let view = null;
129
+ if (subscriptionId) {
130
+ const native = await stripe.subscriptions.retrieve(subscriptionId);
131
+ if (native.id !== subscriptionId)
132
+ throw new UsageSubscriptionError(
133
+ "incompatible_terms",
134
+ "Native Checkout subscription identity mismatch",
135
+ );
136
+ view = await saveSubscription(
137
+ component,
138
+ ctx,
139
+ row.key,
140
+ native,
141
+ terms,
142
+ startedAt,
143
+ );
144
+ }
145
+ return {
146
+ checkoutId: session.id,
147
+ status: session.status as "open" | "complete" | "expired",
148
+ url: session.status === "open" ? session.url : null,
149
+ subscription: view,
150
+ };
151
+ });
152
+ }