@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,81 @@
1
+ import type Stripe from "stripe";
2
+ import type { WebhookContext } from "./helpers.js";
3
+ import { componentRef } from "./helpers.js";
4
+ import type { RunCtx } from "../helpers.js";
5
+ import type { Doc } from "../../component/_generated/dataModel.js";
6
+ import {
7
+ refreshManagedSubscription,
8
+ observeManagedInvoice,
9
+ } from "../usage/subscriptionLifecycle.js";
10
+ /** Re-read native state: an old signed webhook payload cannot rewind the mirror. */
11
+ export async function syncManagedUsageEvent(
12
+ whCtx: WebhookContext,
13
+ event: Stripe.Event,
14
+ ) {
15
+ const object = event.data.object;
16
+ const subscriptionEvent = event.type.startsWith("customer.subscription.");
17
+ const invoiceEvent = event.type.startsWith("invoice.");
18
+ if (!subscriptionEvent && !invoiceEvent) return;
19
+ const sub = subscriptionEvent ? (object as Stripe.Subscription) : null;
20
+ const invoice = invoiceEvent ? (object as Stripe.Invoice) : null;
21
+ const nativeId =
22
+ sub?.id ??
23
+ (typeof invoice?.parent?.subscription_details?.subscription === "string"
24
+ ? invoice.parent.subscription_details.subscription
25
+ : invoice?.parent?.subscription_details?.subscription?.id);
26
+ if (!nativeId) return;
27
+ const key =
28
+ sub?.metadata?.bsUsageIntent ??
29
+ invoice?.parent?.subscription_details?.metadata?.bsUsageIntent;
30
+ if (!key || !/^[a-f0-9]{64}$/.test(key)) return;
31
+ const row = (await whCtx.ctx.runQuery(
32
+ componentRef(whCtx.component, "usageSubscriptions/queries/lookup"),
33
+ { key },
34
+ )) as Doc<"usageSubscriptionIntents"> | null;
35
+ const rows = row ? [row] : [];
36
+ if (!rows.length) return;
37
+ try {
38
+ if (
39
+ rows.length !== 1 ||
40
+ (rows[0].providerId && rows[0].providerId !== nativeId)
41
+ )
42
+ throw new Error("Ambiguous managed subscription");
43
+ const row = rows[0],
44
+ terms = JSON.parse(row.termsJson);
45
+ if (
46
+ event.livemode !== terms.meters[0].scope.livemode ||
47
+ (event.account && event.account !== terms.meters[0].scope.stripeAccountId)
48
+ )
49
+ throw new Error("Managed event realm mismatch");
50
+ const ctx = whCtx.ctx as RunCtx;
51
+ if (sub) {
52
+ // Metadata discovers a Checkout subscription even before its completion webhook.
53
+ await refreshManagedSubscription(whCtx.stripe, whCtx.component, ctx, {
54
+ ...row,
55
+ providerId: nativeId,
56
+ });
57
+ } else if (invoice) {
58
+ const source = row.providerId ? row : { ...row, providerId: nativeId };
59
+ if (!source.viewJson)
60
+ await refreshManagedSubscription(
61
+ whCtx.stripe,
62
+ whCtx.component,
63
+ ctx,
64
+ source,
65
+ );
66
+ const fresh = (await whCtx.ctx.runQuery(
67
+ componentRef(whCtx.component, "usageSubscriptions/queries/lookup"),
68
+ { key: row.key },
69
+ )) as Doc<"usageSubscriptionIntents">;
70
+ await observeManagedInvoice(
71
+ whCtx.stripe,
72
+ whCtx.component,
73
+ ctx,
74
+ fresh,
75
+ invoice.id,
76
+ );
77
+ }
78
+ } catch {
79
+ throw new Error("Native usage lifecycle observation unavailable");
80
+ }
81
+ }
@@ -178,6 +178,13 @@ import type * as usageObservations_helpers from "../usageObservations/helpers.js
178
178
  import type * as usageObservations_history from "../usageObservations/history.js";
179
179
  import type * as usageObservations_mutations from "../usageObservations/mutations.js";
180
180
  import type * as usageObservations_queries from "../usageObservations/queries.js";
181
+ import type * as usageSubscriptions_abandonment from "../usageSubscriptions/abandonment.js";
182
+ import type * as usageSubscriptions_acceptance from "../usageSubscriptions/acceptance.js";
183
+ import type * as usageSubscriptions_helpers from "../usageSubscriptions/helpers.js";
184
+ import type * as usageSubscriptions_history from "../usageSubscriptions/history.js";
185
+ import type * as usageSubscriptions_mutations from "../usageSubscriptions/mutations.js";
186
+ import type * as usageSubscriptions_queries from "../usageSubscriptions/queries.js";
187
+ import type * as usageSubscriptions_retirement from "../usageSubscriptions/retirement.js";
181
188
  import type * as webhooks_mutations from "../webhooks/mutations.js";
182
189
  import type * as webhooks_queries from "../webhooks/queries.js";
183
190
  import type * as webhooks_validators from "../webhooks/validators.js";
@@ -360,6 +367,13 @@ const fullApi: ApiFromModules<{
360
367
  "usageObservations/history": typeof usageObservations_history;
361
368
  "usageObservations/mutations": typeof usageObservations_mutations;
362
369
  "usageObservations/queries": typeof usageObservations_queries;
370
+ "usageSubscriptions/abandonment": typeof usageSubscriptions_abandonment;
371
+ "usageSubscriptions/acceptance": typeof usageSubscriptions_acceptance;
372
+ "usageSubscriptions/helpers": typeof usageSubscriptions_helpers;
373
+ "usageSubscriptions/history": typeof usageSubscriptions_history;
374
+ "usageSubscriptions/mutations": typeof usageSubscriptions_mutations;
375
+ "usageSubscriptions/queries": typeof usageSubscriptions_queries;
376
+ "usageSubscriptions/retirement": typeof usageSubscriptions_retirement;
363
377
  "webhooks/mutations": typeof webhooks_mutations;
364
378
  "webhooks/queries": typeof webhooks_queries;
365
379
  "webhooks/validators": typeof webhooks_validators;
@@ -8321,6 +8321,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8321
8321
  recordJson: string;
8322
8322
  reservationId?: string;
8323
8323
  scopeKey: string;
8324
+ subscriptionId?: string;
8324
8325
  subscriptionJson: string;
8325
8326
  };
8326
8327
  } | null,
@@ -8366,6 +8367,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8366
8367
  recordJson: string;
8367
8368
  reservationId?: string;
8368
8369
  scopeKey: string;
8370
+ subscriptionId?: string;
8369
8371
  subscriptionJson: string;
8370
8372
  };
8371
8373
  }>;
@@ -8474,6 +8476,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8474
8476
  held: boolean;
8475
8477
  providerIdentifier: string;
8476
8478
  reason?:
8479
+ | "billing_period_closed"
8477
8480
  | "rate_limited"
8478
8481
  | "provider_unavailable"
8479
8482
  | "provider_outcome_unknown"
@@ -8552,6 +8555,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8552
8555
  held: boolean;
8553
8556
  providerIdentifier: string;
8554
8557
  reason?:
8558
+ | "billing_period_closed"
8555
8559
  | "rate_limited"
8556
8560
  | "provider_unavailable"
8557
8561
  | "provider_outcome_unknown"
@@ -8606,6 +8610,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8606
8610
  held: boolean;
8607
8611
  providerIdentifier: string;
8608
8612
  reason?:
8613
+ | "billing_period_closed"
8609
8614
  | "rate_limited"
8610
8615
  | "provider_unavailable"
8611
8616
  | "provider_outcome_unknown"
@@ -8660,6 +8665,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8660
8665
  held: boolean;
8661
8666
  providerIdentifier: string;
8662
8667
  reason?:
8668
+ | "billing_period_closed"
8663
8669
  | "rate_limited"
8664
8670
  | "provider_unavailable"
8665
8671
  | "provider_outcome_unknown"
@@ -8707,6 +8713,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8707
8713
  };
8708
8714
  },
8709
8715
  {
8716
+ billingCutoff: number | null;
8710
8717
  event: {
8711
8718
  _creationTime: number;
8712
8719
  _id: string;
@@ -8716,8 +8723,14 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8716
8723
  recordJson: string;
8717
8724
  reservationId?: string;
8718
8725
  scopeKey: string;
8726
+ subscriptionId?: string;
8719
8727
  subscriptionJson: string;
8720
8728
  };
8729
+ managedCollection: null | {
8730
+ daysUntilDue: number | null;
8731
+ defaultPaymentMethod: string | null;
8732
+ method: "send_invoice" | "charge_automatically";
8733
+ };
8721
8734
  outbox: {
8722
8735
  _creationTime: number;
8723
8736
  _id: string;
@@ -8733,6 +8746,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8733
8746
  provider?: string;
8734
8747
  providerIdentifier: string;
8735
8748
  reason?:
8749
+ | "billing_period_closed"
8736
8750
  | "rate_limited"
8737
8751
  | "provider_unavailable"
8738
8752
  | "provider_outcome_unknown"
@@ -8891,6 +8905,192 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8891
8905
  >;
8892
8906
  };
8893
8907
  };
8908
+ usageSubscriptions: {
8909
+ mutations: {
8910
+ abandon: FunctionReference<
8911
+ "mutation",
8912
+ "internal",
8913
+ { key: string; proofJson: string },
8914
+ null,
8915
+ Name
8916
+ >;
8917
+ completeCancellation: FunctionReference<
8918
+ "mutation",
8919
+ "internal",
8920
+ { key: string; nativeJson: string; startedAt: number },
8921
+ string,
8922
+ Name
8923
+ >;
8924
+ linkCheckout: FunctionReference<
8925
+ "mutation",
8926
+ "internal",
8927
+ { checkoutId: string; key: string },
8928
+ null,
8929
+ Name
8930
+ >;
8931
+ prepare: FunctionReference<
8932
+ "mutation",
8933
+ "internal",
8934
+ { method: "direct" | "checkout"; termsJson: string },
8935
+ {
8936
+ _creationTime: number;
8937
+ _id: string;
8938
+ abandonedId?: string;
8939
+ checkoutId?: string;
8940
+ controlKey?: string;
8941
+ firstAttemptAt: number;
8942
+ historyCount?: number;
8943
+ key: string;
8944
+ method: "direct" | "checkout";
8945
+ providerId?: string;
8946
+ retiredAt?: number;
8947
+ retirementInvoiceId?: string;
8948
+ scopeKey: string;
8949
+ startedAt?: number;
8950
+ termsJson: string;
8951
+ viewJson?: string;
8952
+ },
8953
+ Name
8954
+ >;
8955
+ prepareCancellation: FunctionReference<
8956
+ "mutation",
8957
+ "internal",
8958
+ { cancelAtPeriodEnd: boolean; key: string; operationId: string },
8959
+ {
8960
+ _creationTime: number;
8961
+ _id: string;
8962
+ cancelAtPeriodEnd: boolean;
8963
+ firstAttemptAt: number;
8964
+ intentKey: string;
8965
+ key: string;
8966
+ operationId: string;
8967
+ resultJson?: string;
8968
+ },
8969
+ Name
8970
+ >;
8971
+ retire: FunctionReference<
8972
+ "mutation",
8973
+ "internal",
8974
+ { key: string; proofJson: string },
8975
+ null,
8976
+ Name
8977
+ >;
8978
+ save: FunctionReference<
8979
+ "mutation",
8980
+ "internal",
8981
+ { key: string; nativeJson: string; startedAt: number },
8982
+ null,
8983
+ Name
8984
+ >;
8985
+ saveInvoice: FunctionReference<
8986
+ "mutation",
8987
+ "internal",
8988
+ {
8989
+ invoiceId: string;
8990
+ key: string;
8991
+ observationsJson: string;
8992
+ startedAt: number;
8993
+ },
8994
+ null,
8995
+ Name
8996
+ >;
8997
+ };
8998
+ queries: {
8999
+ get: FunctionReference<
9000
+ "query",
9001
+ "internal",
9002
+ {
9003
+ requestId: string;
9004
+ scope: {
9005
+ customerAccount: string;
9006
+ livemode: boolean;
9007
+ stripeAccountId: string;
9008
+ };
9009
+ },
9010
+ {
9011
+ _creationTime: number;
9012
+ _id: string;
9013
+ abandonedId?: string;
9014
+ checkoutId?: string;
9015
+ controlKey?: string;
9016
+ firstAttemptAt: number;
9017
+ historyCount?: number;
9018
+ key: string;
9019
+ method: "direct" | "checkout";
9020
+ providerId?: string;
9021
+ retiredAt?: number;
9022
+ retirementInvoiceId?: string;
9023
+ scopeKey: string;
9024
+ startedAt?: number;
9025
+ termsJson: string;
9026
+ viewJson?: string;
9027
+ } | null,
9028
+ Name
9029
+ >;
9030
+ history: FunctionReference<
9031
+ "query",
9032
+ "internal",
9033
+ {
9034
+ kind: "subscription" | "invoice" | "retirement";
9035
+ paginationOpts: {
9036
+ cursor: string | null;
9037
+ endCursor?: string | null;
9038
+ id?: number;
9039
+ maximumBytesRead?: number;
9040
+ maximumRowsRead?: number;
9041
+ numItems: number;
9042
+ };
9043
+ requestId: string;
9044
+ scope: {
9045
+ customerAccount: string;
9046
+ livemode: boolean;
9047
+ stripeAccountId: string;
9048
+ };
9049
+ },
9050
+ {
9051
+ continueCursor: string;
9052
+ isDone: boolean;
9053
+ page: Array<{
9054
+ _creationTime: number;
9055
+ _id: string;
9056
+ fingerprint: string;
9057
+ intentKey: string;
9058
+ kind: "subscription" | "invoice" | "retirement";
9059
+ observationJson: string;
9060
+ resourceId: string;
9061
+ startedAt: number;
9062
+ }>;
9063
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
9064
+ splitCursor?: string | null;
9065
+ },
9066
+ Name
9067
+ >;
9068
+ lookup: FunctionReference<
9069
+ "query",
9070
+ "internal",
9071
+ { key: string },
9072
+ {
9073
+ _creationTime: number;
9074
+ _id: string;
9075
+ abandonedId?: string;
9076
+ checkoutId?: string;
9077
+ controlKey?: string;
9078
+ firstAttemptAt: number;
9079
+ historyCount?: number;
9080
+ key: string;
9081
+ method: "direct" | "checkout";
9082
+ providerId?: string;
9083
+ retiredAt?: number;
9084
+ retirementInvoiceId?: string;
9085
+ scopeKey: string;
9086
+ startedAt?: number;
9087
+ termsJson: string;
9088
+ viewJson?: string;
9089
+ } | null,
9090
+ Name
9091
+ >;
9092
+ };
9093
+ };
8894
9094
  webhooks: {
8895
9095
  mutations: {
8896
9096
  insertWebhookEvent: FunctionReference<
@@ -7,6 +7,18 @@ export const prepare = mutation({
7
7
  args: { stripeAccountId: v.string() },
8
8
  returns: v.object({ closure: closureDoc, isRetry: v.boolean() }),
9
9
  handler: async (ctx, { stripeAccountId }) => {
10
+ const payerLock = await ctx.db
11
+ .query("usageSubscriptionLocks")
12
+ .withIndex("by_payer", (q) => q.eq("customerAccount", stripeAccountId))
13
+ .first();
14
+ const realmLock = await ctx.db
15
+ .query("usageSubscriptionLocks")
16
+ .withIndex("by_realm", (q) => q.eq("stripeAccountId", stripeAccountId))
17
+ .first();
18
+ if (payerLock || realmLock)
19
+ throw new Error(
20
+ "Close out managed usage enrollment before account closure",
21
+ );
10
22
  const existing = await closureByStripeId(ctx, stripeAccountId);
11
23
  if (existing) return { closure: existing, isRetry: true };
12
24
  const account = await ctx.db
@@ -1,3 +1,9 @@
1
+ import {
2
+ controlsTable as usageSubscriptionControls,
3
+ intentsTable as usageSubscriptionIntents,
4
+ locksTable as usageSubscriptionLocks,
5
+ historyTable as usageSubscriptionHistory,
6
+ } from "./usageSubscriptions/schema.js";
1
7
  import {
2
8
  historyTable as usageDeliveryHistory,
3
9
  observationsTable as usageProviderObservations,
@@ -104,6 +110,10 @@ import { pricesTable, productsTable } from "./products/schema";
104
110
  import { webhookEventsTable } from "./webhooks/schema";
105
111
 
106
112
  export default defineSchema({
113
+ usageSubscriptionControls,
114
+ usageSubscriptionIntents,
115
+ usageSubscriptionLocks,
116
+ usageSubscriptionHistory,
107
117
  usageProviderObservations,
108
118
  usageDeliveryHistory,
109
119
  usageDeliveryLocks,
@@ -1,3 +1,4 @@
1
+ import { managedBillingCutoff } from "../usageSubscriptions/acceptance.js";
1
2
  import { v } from "convex/values";
2
3
  import type { FunctionHandle } from "convex/server";
3
4
  import { mutation } from "../_generated/server.js";
@@ -61,6 +62,9 @@ export const record = mutation({
61
62
  };
62
63
  }
63
64
  const now = Math.floor(Date.now() / 1000);
65
+ const cutoff = await managedBillingCutoff(ctx, event, subscription);
66
+ if (cutoff !== null && now >= cutoff)
67
+ throw new Error("Managed usage billing period is closing or closed");
64
68
  if (event.occurredAt < now - 35 * 86400 || event.occurredAt > now + 300)
65
69
  throw new Error("Usage occurrence is outside the native delivery window");
66
70
  if (
@@ -96,6 +100,7 @@ export const record = mutation({
96
100
  )
97
101
  throw new Error("Usage reservation does not match event");
98
102
  const eventId = await ctx.db.insert("usageEvents", {
103
+ subscriptionId: subscription.subscriptionId,
99
104
  reservationId: args.reservationId,
100
105
  scopeKey: key,
101
106
  identity: event.identity,
@@ -17,6 +17,7 @@ export const deliveryValidator = v.union(
17
17
  v.literal("held"),
18
18
  );
19
19
  export const eventFields = {
20
+ subscriptionId: v.optional(v.string()),
20
21
  reservationId: v.optional(v.id("usageReservations")),
21
22
  scopeKey: v.string(),
22
23
  identity: v.string(),
@@ -32,6 +33,7 @@ export const eventDoc = v.object({
32
33
  });
33
34
  export const usageEventsTable = defineTable(eventFields)
34
35
  .index("by_identity", ["identity"])
36
+ .index("by_scope_subscription", ["scopeKey", "subscriptionId"])
35
37
  .index("by_scope_time", ["scopeKey", "occurredAt"]);
36
38
  export const outboxFields = {
37
39
  ...deliveryFields,
@@ -71,4 +73,6 @@ export const usageReservationsTable = defineTable({
71
73
  v.literal("released"),
72
74
  ),
73
75
  eventId: v.optional(v.id("usageEvents")),
74
- }).index("by_scope_source", ["scopeKey", "sourceEventId"]);
76
+ })
77
+ .index("by_scope_source", ["scopeKey", "sourceEventId"])
78
+ .index("by_scope_state", ["scopeKey", "state"]);
@@ -1,6 +1,7 @@
1
1
  import { defineTable } from "convex/server";
2
2
  import { v } from "convex/values";
3
3
  export const reason = v.union(
4
+ v.literal("billing_period_closed"),
4
5
  v.literal("rate_limited"),
5
6
  v.literal("provider_unavailable"),
6
7
  v.literal("provider_outcome_unknown"),
@@ -57,4 +58,5 @@ export const errorDoc = v.object({
57
58
  });
58
59
  export const errorsTable = defineTable(errorFields)
59
60
  .index("by_dedupe", ["dedupe"])
61
+ .index("by_scope", ["scopeKey"])
60
62
  .index("by_event", ["eventId"]);
@@ -1,3 +1,5 @@
1
+ import { managedBillingPolicy } from "../usageSubscriptions/acceptance.js";
2
+ import { subscriptionSnapshot } from "../usage/helpers.js";
1
3
  import { query, internalQuery } from "../_generated/server.js";
2
4
  import { refFields, status } from "./schema.js";
3
5
  import { read, currentStatus } from "./helpers.js";
@@ -11,13 +13,38 @@ export const get = query({
11
13
  });
12
14
  const snapshotDefinition = {
13
15
  args: refFields,
14
- returns: v.object({ event: eventDoc, outbox: outboxDoc }),
16
+ returns: v.object({
17
+ event: eventDoc,
18
+ outbox: outboxDoc,
19
+ billingCutoff: v.union(v.number(), v.null()),
20
+ managedCollection: v.union(
21
+ v.null(),
22
+ v.object({
23
+ method: v.union(
24
+ v.literal("send_invoice"),
25
+ v.literal("charge_automatically"),
26
+ ),
27
+ daysUntilDue: v.union(v.number(), v.null()),
28
+ defaultPaymentMethod: v.union(v.string(), v.null()),
29
+ }),
30
+ ),
31
+ }),
15
32
  handler: async (
16
33
  ctx: import("../_generated/server.js").QueryCtx,
17
34
  args: import("convex/values").Infer<typeof _refValidator>,
18
35
  ) => {
19
- const { event, outbox } = await read(ctx, args);
20
- return { event, outbox };
36
+ const { event, outbox, record } = await read(ctx, args);
37
+ const policy = await managedBillingPolicy(
38
+ ctx,
39
+ record,
40
+ subscriptionSnapshot(event.subscriptionJson),
41
+ );
42
+ return {
43
+ event,
44
+ outbox,
45
+ billingCutoff: policy?.cutoff ?? null,
46
+ managedCollection: policy?.collection ?? null,
47
+ };
21
48
  },
22
49
  };
23
50
  const _refValidator = v.object(refFields);
@@ -1,3 +1,5 @@
1
+ import { managedBillingCutoff } from "../usageSubscriptions/acceptance.js";
2
+ import { subscriptionSnapshot } from "../usage/helpers.js";
1
3
  import { appendDeliveryHistory } from "../usageObservations/history.js";
2
4
  import { internalMutation } from "../_generated/server.js";
3
5
  import { v } from "convex/values";
@@ -12,7 +14,7 @@ export const claim = internalMutation({
12
14
  v.object({ kind: v.literal("done") }),
13
15
  ),
14
16
  handler: async (ctx, args) => {
15
- const { outbox, record } = await read(ctx, args),
17
+ const { event, outbox, record } = await read(ctx, args),
16
18
  now = Math.floor(Date.now() / 1000);
17
19
  if (
18
20
  outbox.held ||
@@ -62,6 +64,25 @@ export const claim = internalMutation({
62
64
  );
63
65
  return { kind: "done" as const };
64
66
  }
67
+ const cutoff = await managedBillingCutoff(
68
+ ctx,
69
+ record,
70
+ subscriptionSnapshot(event.subscriptionJson),
71
+ );
72
+ if (cutoff !== null && now >= cutoff) {
73
+ await ctx.db.patch("usageOutbox", outbox._id, {
74
+ state: "held",
75
+ reason: "billing_period_closed",
76
+ });
77
+ await appendDeliveryHistory(
78
+ ctx,
79
+ args.eventId,
80
+ "held",
81
+ outbox.attempts,
82
+ `billing-period:${outbox.attempts}`,
83
+ );
84
+ return { kind: "done" as const };
85
+ }
65
86
  const keys = lockKeys(record);
66
87
  const realm = await ctx.db
67
88
  .query("usageDeliveryLocks")
@@ -0,0 +1,80 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ import { abandonmentProof } from "../../client/usage/subscriptionInvoiceSchema.js";
4
+ import { jsonTerms } from "./helpers.js";
5
+ import { scopeKey } from "../usage/helpers.js";
6
+ import { appendSnapshot } from "./history.js";
7
+ export async function abandonEnrollment(
8
+ ctx: MutationCtx,
9
+ intent: Doc<"usageSubscriptionIntents">,
10
+ proofJson: string,
11
+ ) {
12
+ if (new TextEncoder().encode(proofJson).length > 4096)
13
+ throw new Error("Abandonment evidence exceeds size limit");
14
+ const proof = abandonmentProof.parse(JSON.parse(proofJson)),
15
+ { terms } = jsonTerms(intent.termsJson),
16
+ first = terms.meters[0];
17
+ if (
18
+ proof.stripeAccountId !== first.scope.stripeAccountId ||
19
+ proof.customerAccount !== first.scope.customerAccount ||
20
+ proof.stripeCustomerId !== first.binding.stripeCustomerId ||
21
+ proof.livemode !== first.scope.livemode ||
22
+ (proof.kind === "checkout"
23
+ ? intent.checkoutId !== proof.nativeId || intent.providerId !== undefined
24
+ : intent.providerId !== proof.nativeId)
25
+ )
26
+ throw new Error("Abandoned signup binding mismatch");
27
+ if (intent.retiredAt !== undefined) {
28
+ if (intent.abandonedId !== proof.nativeId)
29
+ throw new Error("Abandonment replay conflict");
30
+ return;
31
+ }
32
+ if (intent.controlKey)
33
+ throw new Error("Cancellation command is still pending");
34
+ for (const meter of terms.meters) {
35
+ const key = scopeKey(meter.scope);
36
+ const events =
37
+ proof.kind === "subscription"
38
+ ? await ctx.db
39
+ .query("usageEvents")
40
+ .withIndex("by_scope_subscription", (q) =>
41
+ q.eq("scopeKey", key).eq("subscriptionId", proof.nativeId),
42
+ )
43
+ .take(1)
44
+ : [];
45
+ const reservations = await ctx.db
46
+ .query("usageReservations")
47
+ .withIndex("by_scope_state", (q) =>
48
+ q.eq("scopeKey", key).eq("state", "reserved"),
49
+ )
50
+ .take(1);
51
+ if (events.length || reservations.length)
52
+ throw new Error("Signup has usage or pending reservations");
53
+ }
54
+ await appendSnapshot(
55
+ ctx,
56
+ intent,
57
+ "retirement",
58
+ proof.nativeId,
59
+ { abandonment: proof, creditTreatment: "retain_original_terms" },
60
+ Date.now(),
61
+ );
62
+ for (const { scope, binding } of terms.meters) {
63
+ const key = JSON.stringify([
64
+ scope.stripeAccountId,
65
+ scope.livemode,
66
+ binding.stripeCustomerId,
67
+ scope.meterId,
68
+ ]);
69
+ const lock = await ctx.db
70
+ .query("usageSubscriptionLocks")
71
+ .withIndex("by_key", (q) => q.eq("key", key))
72
+ .unique();
73
+ if (lock?.intentKey === intent.key)
74
+ await ctx.db.delete("usageSubscriptionLocks", lock._id);
75
+ }
76
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
77
+ retiredAt: Math.floor(Date.now() / 1000),
78
+ abandonedId: proof.nativeId,
79
+ });
80
+ }