@fantastic.dev/better-stripe 0.54.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 (282) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +264 -8
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +132 -4
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +264 -8
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +132 -4
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +9 -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 +9 -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/invoiceObservation.d.ts +38 -0
  31. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  32. package/dist/client/usage/invoiceObservation.js +157 -0
  33. package/dist/client/usage/invoiceObservation.js.map +1 -0
  34. package/dist/client/usage/observationClient.d.ts +83 -0
  35. package/dist/client/usage/observationClient.d.ts.map +1 -0
  36. package/dist/client/usage/observationClient.js +157 -0
  37. package/dist/client/usage/observationClient.js.map +1 -0
  38. package/dist/client/usage/observationTypes.d.ts +63 -0
  39. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  40. package/dist/client/usage/observationTypes.js +59 -0
  41. package/dist/client/usage/observationTypes.js.map +1 -0
  42. package/dist/client/usage/providerObservation.d.ts +4 -0
  43. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  44. package/dist/client/usage/providerObservation.js +96 -0
  45. package/dist/client/usage/providerObservation.js.map +1 -0
  46. package/dist/client/usage/reconciliation.d.ts +12 -0
  47. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  48. package/dist/client/usage/reconciliation.js +48 -0
  49. package/dist/client/usage/reconciliation.js.map +1 -0
  50. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  51. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  52. package/dist/client/usage/subscription.fixtures.js +84 -0
  53. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  54. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  55. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  57. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  58. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  59. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionCancellation.js +39 -0
  61. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  62. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  63. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionCheckout.js +94 -0
  65. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  66. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  67. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionClient.js +93 -0
  69. package/dist/client/usage/subscriptionClient.js.map +1 -0
  70. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  71. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionErrors.js +9 -0
  73. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  74. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  75. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  76. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  77. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  78. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  79. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  80. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  81. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  82. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  83. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  84. package/dist/client/usage/subscriptionProvider.js +147 -0
  85. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  86. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  87. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  88. package/dist/client/usage/subscriptionTerms.js +242 -0
  89. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  90. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  91. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  92. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  93. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  94. package/dist/client/usage/summary.d.ts +50 -0
  95. package/dist/client/usage/summary.d.ts.map +1 -0
  96. package/dist/client/usage/summary.js +110 -0
  97. package/dist/client/usage/summary.js.map +1 -0
  98. package/dist/client/webhooks/processors.d.ts.map +1 -1
  99. package/dist/client/webhooks/processors.js +2 -0
  100. package/dist/client/webhooks/processors.js.map +1 -1
  101. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  102. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  103. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  104. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  105. package/dist/component/_generated/api.d.ts +22 -0
  106. package/dist/component/_generated/api.d.ts.map +1 -1
  107. package/dist/component/_generated/api.js.map +1 -1
  108. package/dist/component/_generated/component.d.ts +255 -5
  109. package/dist/component/_generated/component.d.ts.map +1 -1
  110. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  111. package/dist/component/accountClosure/mutations.js +10 -0
  112. package/dist/component/accountClosure/mutations.js.map +1 -1
  113. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  114. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  115. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  116. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  117. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  118. package/dist/component/earnings/triggers.d.ts +296 -22
  119. package/dist/component/earnings/triggers.d.ts.map +1 -1
  120. package/dist/component/payoutRelease/queries.d.ts +2 -2
  121. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  122. package/dist/component/refundHistory/queries.d.ts +1 -1
  123. package/dist/component/schema.d.ts +132 -4
  124. package/dist/component/schema.js +8 -0
  125. package/dist/component/schema.js.map +1 -1
  126. package/dist/component/usage/mutations.d.ts.map +1 -1
  127. package/dist/component/usage/mutations.js +5 -0
  128. package/dist/component/usage/mutations.js.map +1 -1
  129. package/dist/component/usage/queries.d.ts +2 -0
  130. package/dist/component/usage/queries.d.ts.map +1 -1
  131. package/dist/component/usage/schema.d.ts +21 -9
  132. package/dist/component/usage/schema.d.ts.map +1 -1
  133. package/dist/component/usage/schema.js +5 -1
  134. package/dist/component/usage/schema.js.map +1 -1
  135. package/dist/component/usageDelivery/fields.d.ts +4 -2
  136. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  137. package/dist/component/usageDelivery/fields.js +3 -1
  138. package/dist/component/usageDelivery/fields.js.map +1 -1
  139. package/dist/component/usageDelivery/helpers.d.ts +5 -3
  140. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  141. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  142. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  143. package/dist/component/usageDelivery/mutations.js +8 -1
  144. package/dist/component/usageDelivery/mutations.js.map +1 -1
  145. package/dist/component/usageDelivery/queries.d.ts +19 -3
  146. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  147. package/dist/component/usageDelivery/queries.js +20 -3
  148. package/dist/component/usageDelivery/queries.js.map +1 -1
  149. package/dist/component/usageDelivery/schema.d.ts +2 -2
  150. package/dist/component/usageDelivery/steps.d.ts +1 -1
  151. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  152. package/dist/component/usageDelivery/steps.js +20 -2
  153. package/dist/component/usageDelivery/steps.js.map +1 -1
  154. package/dist/component/usageObservations/helpers.d.ts +38 -0
  155. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  156. package/dist/component/usageObservations/helpers.js +80 -0
  157. package/dist/component/usageObservations/helpers.js.map +1 -0
  158. package/dist/component/usageObservations/history.d.ts +6 -0
  159. package/dist/component/usageObservations/history.d.ts.map +1 -0
  160. package/dist/component/usageObservations/history.js +29 -0
  161. package/dist/component/usageObservations/history.js.map +1 -0
  162. package/dist/component/usageObservations/mutations.d.ts +6 -0
  163. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  164. package/dist/component/usageObservations/mutations.js +39 -0
  165. package/dist/component/usageObservations/mutations.js.map +1 -0
  166. package/dist/component/usageObservations/queries.d.ts +78 -0
  167. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  168. package/dist/component/usageObservations/queries.js +131 -0
  169. package/dist/component/usageObservations/queries.js.map +1 -0
  170. package/dist/component/usageObservations/schema.d.ts +72 -0
  171. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  172. package/dist/component/usageObservations/schema.js +29 -0
  173. package/dist/component/usageObservations/schema.js.map +1 -0
  174. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  175. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  176. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  177. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  178. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  179. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  180. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  181. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  182. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  183. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  184. package/dist/component/usageSubscriptions/helpers.js +28 -0
  185. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  186. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  187. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  188. package/dist/component/usageSubscriptions/history.js +46 -0
  189. package/dist/component/usageSubscriptions/history.js.map +1 -0
  190. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  191. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  192. package/dist/component/usageSubscriptions/mutations.js +252 -0
  193. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  194. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  195. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  196. package/dist/component/usageSubscriptions/queries.js +70 -0
  197. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  198. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  199. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  200. package/dist/component/usageSubscriptions/retirement.js +80 -0
  201. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  202. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  203. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  204. package/dist/component/usageSubscriptions/schema.js +69 -0
  205. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  206. package/dist/test.d.ts +6 -0
  207. package/dist/test.d.ts.map +1 -0
  208. package/dist/test.js +15 -0
  209. package/dist/test.js.map +1 -0
  210. package/docs/README.md +4 -0
  211. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  212. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  213. package/docs/evidence/native-metering/paid-run.json +107 -0
  214. package/docs/evidence/native-metering/promotional-run.json +103 -0
  215. package/docs/metered-usage.md +14 -0
  216. package/docs/metering-setup.md +7 -1
  217. package/docs/usage-observations.md +152 -0
  218. package/docs/usage-subscriptions.md +278 -0
  219. package/package.json +5 -2
  220. package/src/client/index.ts +26 -0
  221. package/src/client/usage/catalogPrices.ts +21 -0
  222. package/src/client/usage/client.ts +2 -2
  223. package/src/client/usage/deliveryProvider.test.ts +70 -1
  224. package/src/client/usage/deliveryProvider.ts +43 -2
  225. package/src/client/usage/index.ts +27 -0
  226. package/src/client/usage/invoiceObservation.test.ts +195 -0
  227. package/src/client/usage/invoiceObservation.ts +203 -0
  228. package/src/client/usage/observationClient.ts +233 -0
  229. package/src/client/usage/observationTypes.ts +101 -0
  230. package/src/client/usage/providerObservation.test.ts +207 -0
  231. package/src/client/usage/providerObservation.ts +124 -0
  232. package/src/client/usage/reconciliation.test.ts +117 -0
  233. package/src/client/usage/reconciliation.ts +86 -0
  234. package/src/client/usage/subscription.fixtures.ts +84 -0
  235. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  236. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  237. package/src/client/usage/subscriptionCancellation.ts +90 -0
  238. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  239. package/src/client/usage/subscriptionCheckout.ts +152 -0
  240. package/src/client/usage/subscriptionClient.test.ts +316 -0
  241. package/src/client/usage/subscriptionClient.ts +204 -0
  242. package/src/client/usage/subscriptionErrors.ts +14 -0
  243. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  244. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  245. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  246. package/src/client/usage/subscriptionProvider.ts +247 -0
  247. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  248. package/src/client/usage/subscriptionTerms.ts +294 -0
  249. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  250. package/src/client/usage/summary.test.ts +222 -0
  251. package/src/client/usage/summary.ts +188 -0
  252. package/src/client/webhooks/processors.ts +2 -0
  253. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  254. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  255. package/src/component/_generated/api.ts +22 -0
  256. package/src/component/_generated/component.ts +335 -0
  257. package/src/component/accountClosure/mutations.ts +12 -0
  258. package/src/component/schema.ts +16 -0
  259. package/src/component/usage/mutations.ts +5 -0
  260. package/src/component/usage/schema.ts +5 -1
  261. package/src/component/usageDelivery/fields.ts +3 -0
  262. package/src/component/usageDelivery/mutations.ts +26 -1
  263. package/src/component/usageDelivery/queries.ts +30 -3
  264. package/src/component/usageDelivery/steps.ts +61 -2
  265. package/src/component/usageObservations/helpers.ts +95 -0
  266. package/src/component/usageObservations/history.test.ts +87 -0
  267. package/src/component/usageObservations/history.ts +39 -0
  268. package/src/component/usageObservations/mutations.ts +39 -0
  269. package/src/component/usageObservations/queries.test.ts +162 -0
  270. package/src/component/usageObservations/queries.ts +145 -0
  271. package/src/component/usageObservations/schema.ts +40 -0
  272. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  273. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  274. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  275. package/src/component/usageSubscriptions/helpers.ts +33 -0
  276. package/src/component/usageSubscriptions/history.test.ts +69 -0
  277. package/src/component/usageSubscriptions/history.ts +68 -0
  278. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  279. package/src/component/usageSubscriptions/mutations.ts +275 -0
  280. package/src/component/usageSubscriptions/queries.ts +78 -0
  281. package/src/component/usageSubscriptions/retirement.ts +105 -0
  282. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,275 @@
1
+ import { closureByStripeId } from "../accountClosure/helpers.js";
2
+ import { abandonEnrollment } from "./abandonment.js";
3
+ import { retireEnrollment } from "./retirement.js";
4
+ import { appendSnapshot, saveView } from "./history.js";
5
+ import { controlDoc } from "./schema.js";
6
+ import { managedInvoiceSchema } from "../../client/usage/subscriptionInvoiceSchema.js";
7
+ import { v } from "convex/values";
8
+ import { mutation } from "../_generated/server.js";
9
+ import { intentDoc, method } from "./schema.js";
10
+ import { intentKey, jsonTerms, observationStart } from "./helpers.js";
11
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
12
+ import { subscriptionScope } from "../../client/usage/subscriptionTerms.js";
13
+ export const prepare = mutation({
14
+ args: { termsJson: v.string(), method },
15
+ returns: intentDoc,
16
+ handler: async (ctx, args) => {
17
+ const parsed = jsonTerms(args.termsJson),
18
+ { terms } = parsed;
19
+ if (
20
+ (terms.collection.method === "checkout") !==
21
+ (args.method === "checkout")
22
+ )
23
+ throw new Error("Subscription creation method conflict");
24
+ for (const account of new Set([
25
+ terms.meters[0].scope.stripeAccountId,
26
+ terms.meters[0].scope.customerAccount,
27
+ ])) {
28
+ if (await closureByStripeId(ctx, account))
29
+ throw new Error("Account closure prevents managed usage enrollment");
30
+ }
31
+ const key = await intentKey(subscriptionScope(terms), terms.requestId);
32
+ const prior = await ctx.db
33
+ .query("usageSubscriptionIntents")
34
+ .withIndex("by_key", (q) => q.eq("key", key))
35
+ .unique();
36
+ if (prior) {
37
+ if (prior.termsJson !== parsed.termsJson || prior.method !== args.method)
38
+ throw new Error("Subscription intent replay conflict");
39
+ return prior;
40
+ }
41
+ for (const { scope, binding } of terms.meters) {
42
+ const lockKey = JSON.stringify([
43
+ scope.stripeAccountId,
44
+ scope.livemode,
45
+ binding.stripeCustomerId,
46
+ scope.meterId,
47
+ ]);
48
+ const lock = await ctx.db
49
+ .query("usageSubscriptionLocks")
50
+ .withIndex("by_key", (q) => q.eq("key", lockKey))
51
+ .unique();
52
+ if (lock)
53
+ throw new Error("Native customer/meter enrollment already reserved");
54
+ await ctx.db.insert("usageSubscriptionLocks", {
55
+ key: lockKey,
56
+ intentKey: key,
57
+ stripeAccountId: scope.stripeAccountId,
58
+ customerAccount: scope.customerAccount,
59
+ });
60
+ }
61
+ const id = await ctx.db.insert("usageSubscriptionIntents", {
62
+ key,
63
+ scopeKey: parsed.scopeKey,
64
+ termsJson: parsed.termsJson,
65
+ method: args.method,
66
+ firstAttemptAt: Math.floor(Date.now() / 1000),
67
+ });
68
+ return (await ctx.db.get("usageSubscriptionIntents", id))!;
69
+ },
70
+ });
71
+
72
+ export const save = mutation({
73
+ args: { key: v.string(), nativeJson: v.string(), startedAt: v.number() },
74
+ returns: v.null(),
75
+ handler: async (ctx, args) => {
76
+ observationStart(args.startedAt);
77
+ if (new TextEncoder().encode(args.nativeJson).length > 65536)
78
+ throw new Error("Subscription observation exceeds size limit");
79
+ const intent = await ctx.db
80
+ .query("usageSubscriptionIntents")
81
+ .withIndex("by_key", (q) => q.eq("key", args.key))
82
+ .unique();
83
+ if (!intent) throw new Error("Subscription intent not found");
84
+ await saveView(ctx, intent, args.nativeJson, args.startedAt);
85
+ return null;
86
+ },
87
+ });
88
+
89
+ export const linkCheckout = mutation({
90
+ args: { key: v.string(), checkoutId: v.string() },
91
+ returns: v.null(),
92
+ handler: async (ctx, args) => {
93
+ if (!/^cs_[a-zA-Z0-9_]{1,200}$/.test(args.checkoutId))
94
+ throw new Error("Invalid Checkout identity");
95
+ const intent = await ctx.db
96
+ .query("usageSubscriptionIntents")
97
+ .withIndex("by_key", (q) => q.eq("key", args.key))
98
+ .unique();
99
+ if (
100
+ !intent ||
101
+ intent.method !== "checkout" ||
102
+ (intent.checkoutId && intent.checkoutId !== args.checkoutId)
103
+ )
104
+ throw new Error("Checkout intent identity conflict");
105
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
106
+ checkoutId: args.checkoutId,
107
+ });
108
+ return null;
109
+ },
110
+ });
111
+
112
+ export const saveInvoice = mutation({
113
+ args: {
114
+ key: v.string(),
115
+ invoiceId: v.string(),
116
+ observationsJson: v.string(),
117
+ startedAt: v.number(),
118
+ },
119
+ returns: v.null(),
120
+ handler: async (ctx, args) => {
121
+ observationStart(args.startedAt);
122
+ if (
123
+ !/^in_[a-zA-Z0-9]{1,100}$/.test(args.invoiceId) ||
124
+ new TextEncoder().encode(args.observationsJson).length > 131072
125
+ )
126
+ throw new Error("Invalid managed invoice observation");
127
+ const intent = await ctx.db
128
+ .query("usageSubscriptionIntents")
129
+ .withIndex("by_key", (q) => q.eq("key", args.key))
130
+ .unique();
131
+ if (!intent?.providerId)
132
+ throw new Error("Managed subscription unavailable");
133
+ const { terms } = jsonTerms(intent.termsJson),
134
+ observations = managedInvoiceSchema.parse(
135
+ JSON.parse(args.observationsJson),
136
+ );
137
+ const seen = new Set<string>();
138
+ for (const entry of observations) {
139
+ const meter = terms.meters.find((m) => m.scope.meterId === entry.meterId);
140
+ if (!meter || seen.has(entry.meterId))
141
+ throw new Error("Managed invoice source mismatch");
142
+ seen.add(entry.meterId);
143
+ if (entry.observation.status !== "available") continue;
144
+ const { value, observedAt } = entry.observation;
145
+ if (
146
+ observedAt > Math.floor(Date.now() / 1000) + 300 ||
147
+ value.invoiceId !== args.invoiceId ||
148
+ value.currency !== meter.binding.plan.rate.currency ||
149
+ value.lines.some(
150
+ (line) =>
151
+ line.stripePriceId !== meter.binding.stripePriceId ||
152
+ line.subscriptionItemId !== entry.subscriptionItemId ||
153
+ line.currency !== value.currency ||
154
+ line.nativePeriod.end < line.nativePeriod.start,
155
+ ) ||
156
+ (value.finalized && value.status === "draft")
157
+ )
158
+ throw new Error("Managed invoice provenance mismatch");
159
+ }
160
+ if (seen.size !== terms.meters.length)
161
+ throw new Error("Incomplete managed invoice sources");
162
+ await appendSnapshot(
163
+ ctx,
164
+ intent,
165
+ "invoice",
166
+ args.invoiceId,
167
+ observations,
168
+ args.startedAt,
169
+ );
170
+ return null;
171
+ },
172
+ });
173
+
174
+ export const prepareCancellation = mutation({
175
+ args: {
176
+ key: v.string(),
177
+ operationId: v.string(),
178
+ cancelAtPeriodEnd: v.boolean(),
179
+ },
180
+ returns: controlDoc,
181
+ handler: async (ctx, args) => {
182
+ if (!args.operationId || args.operationId.length > 100)
183
+ throw new Error("Invalid cancellation operation identity");
184
+ const intent = await ctx.db
185
+ .query("usageSubscriptionIntents")
186
+ .withIndex("by_key", (q) => q.eq("key", args.key))
187
+ .unique();
188
+ if (!intent?.providerId)
189
+ throw new Error("Managed subscription unavailable");
190
+ const key = await canonicalFingerprint([intent.key, args.operationId]);
191
+ const prior = await ctx.db
192
+ .query("usageSubscriptionControls")
193
+ .withIndex("by_key", (q) => q.eq("key", key))
194
+ .unique();
195
+ if (prior) {
196
+ if (prior.cancelAtPeriodEnd !== args.cancelAtPeriodEnd)
197
+ throw new Error("Cancellation operation replay conflict");
198
+ return prior;
199
+ }
200
+ if (intent.controlKey)
201
+ throw new Error("A cancellation operation is pending reconciliation");
202
+ const id = await ctx.db.insert("usageSubscriptionControls", {
203
+ key,
204
+ intentKey: intent.key,
205
+ operationId: args.operationId,
206
+ cancelAtPeriodEnd: args.cancelAtPeriodEnd,
207
+ firstAttemptAt: Math.floor(Date.now() / 1000),
208
+ });
209
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
210
+ controlKey: key,
211
+ });
212
+ return (await ctx.db.get("usageSubscriptionControls", id))!;
213
+ },
214
+ });
215
+ export const completeCancellation = mutation({
216
+ args: { key: v.string(), nativeJson: v.string(), startedAt: v.number() },
217
+ returns: v.string(),
218
+ handler: async (ctx, args) => {
219
+ observationStart(args.startedAt);
220
+ const command = await ctx.db
221
+ .query("usageSubscriptionControls")
222
+ .withIndex("by_key", (q) => q.eq("key", args.key))
223
+ .unique();
224
+ if (!command) throw new Error("Cancellation command unavailable");
225
+ if (command.resultJson) return command.resultJson;
226
+ const intent = await ctx.db
227
+ .query("usageSubscriptionIntents")
228
+ .withIndex("by_key", (q) => q.eq("key", command.intentKey))
229
+ .unique();
230
+ if (!intent || intent.controlKey !== command.key)
231
+ throw new Error("Cancellation command ownership conflict");
232
+ const view = await saveView(ctx, intent, args.nativeJson, args.startedAt);
233
+ if (
234
+ view.cancelAtPeriodEnd !== command.cancelAtPeriodEnd &&
235
+ !["canceled", "incomplete_expired"].includes(view.status)
236
+ )
237
+ throw new Error("Cancellation outcome mismatch");
238
+ const resultJson = JSON.stringify(view);
239
+ await ctx.db.patch("usageSubscriptionControls", command._id, {
240
+ resultJson,
241
+ });
242
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
243
+ controlKey: undefined,
244
+ });
245
+ return resultJson;
246
+ },
247
+ });
248
+
249
+ export const retire = mutation({
250
+ args: { key: v.string(), proofJson: v.string() },
251
+ returns: v.null(),
252
+ handler: async (ctx, args) => {
253
+ const intent = await ctx.db
254
+ .query("usageSubscriptionIntents")
255
+ .withIndex("by_key", (q) => q.eq("key", args.key))
256
+ .unique();
257
+ if (!intent) throw new Error("Managed subscription unavailable");
258
+ await retireEnrollment(ctx, intent, args.proofJson);
259
+ return null;
260
+ },
261
+ });
262
+
263
+ export const abandon = mutation({
264
+ args: { key: v.string(), proofJson: v.string() },
265
+ returns: v.null(),
266
+ handler: async (ctx, args) => {
267
+ const intent = await ctx.db
268
+ .query("usageSubscriptionIntents")
269
+ .withIndex("by_key", (q) => q.eq("key", args.key))
270
+ .unique();
271
+ if (!intent) throw new Error("Managed signup unavailable");
272
+ await abandonEnrollment(ctx, intent, args.proofJson);
273
+ return null;
274
+ },
275
+ });
@@ -0,0 +1,78 @@
1
+ import {
2
+ paginationOptsValidator,
3
+ paginationResultValidator,
4
+ } from "convex/server";
5
+ import { paginator } from "convex-helpers/server/pagination";
6
+ import schema from "../schema.js";
7
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
8
+ import { historyDoc } from "./schema.js";
9
+ import { v } from "convex/values";
10
+ import { query } from "../_generated/server.js";
11
+ import { intentDoc } from "./schema.js";
12
+ import { intentKey } from "./helpers.js";
13
+ export const scope = v.object({
14
+ stripeAccountId: v.string(),
15
+ customerAccount: v.string(),
16
+ livemode: v.boolean(),
17
+ });
18
+ export const get = query({
19
+ args: { scope, requestId: v.string() },
20
+ returns: v.union(intentDoc, v.null()),
21
+ handler: async (ctx, args) => {
22
+ const key = await intentKey(args.scope, args.requestId);
23
+ return ctx.db
24
+ .query("usageSubscriptionIntents")
25
+ .withIndex("by_key", (q) => q.eq("key", key))
26
+ .unique();
27
+ },
28
+ });
29
+
30
+ export const lookup = query({
31
+ args: { key: v.string() },
32
+ returns: v.union(intentDoc, v.null()),
33
+ handler: async (ctx, args) => {
34
+ if (!/^[a-f0-9]{64}$/.test(args.key))
35
+ throw new Error("Invalid managed subscription key");
36
+ return ctx.db
37
+ .query("usageSubscriptionIntents")
38
+ .withIndex("by_key", (q) => q.eq("key", args.key))
39
+ .unique();
40
+ },
41
+ });
42
+ export const history = query({
43
+ args: {
44
+ scope,
45
+ requestId: v.string(),
46
+ kind: v.union(
47
+ v.literal("subscription"),
48
+ v.literal("invoice"),
49
+ v.literal("retirement"),
50
+ ),
51
+ paginationOpts: paginationOptsValidator,
52
+ },
53
+ returns: paginationResultValidator(historyDoc),
54
+ handler: async (ctx, args) => {
55
+ validateUsagePageRequest({
56
+ period: { start: 0, end: 1 },
57
+ limit: args.paginationOpts.numItems,
58
+ cursor: args.paginationOpts.cursor,
59
+ });
60
+ const key = await intentKey(args.scope, args.requestId);
61
+ const intent = await ctx.db
62
+ .query("usageSubscriptionIntents")
63
+ .withIndex("by_key", (q) => q.eq("key", key))
64
+ .unique();
65
+ if (!intent) throw new Error("Managed subscription scope unavailable");
66
+ return paginator(ctx.db, schema)
67
+ .query("usageSubscriptionHistory")
68
+ .withIndex("by_intent_kind", (q) =>
69
+ q.eq("intentKey", key).eq("kind", args.kind),
70
+ )
71
+ .order("desc")
72
+ .paginate({
73
+ ...args.paginationOpts,
74
+ maximumRowsRead: 200,
75
+ maximumBytesRead: 1000000,
76
+ });
77
+ },
78
+ });
@@ -0,0 +1,105 @@
1
+ import { retirementProof } from "../../client/usage/subscriptionInvoiceSchema.js";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import type { Doc } from "../_generated/dataModel.js";
4
+ import { scopeKey } from "../usage/helpers.js";
5
+ import { jsonTerms } from "./helpers.js";
6
+ import type { UsageSubscriptionView } from "../../client/usage/subscriptionTerms.js";
7
+ import { appendSnapshot } from "./history.js";
8
+ export async function retireEnrollment(
9
+ ctx: MutationCtx,
10
+ intent: Doc<"usageSubscriptionIntents">,
11
+ proofJson: string,
12
+ ) {
13
+ if (new TextEncoder().encode(proofJson).length > 4096)
14
+ throw new Error("Retirement evidence exceeds size limit");
15
+ const proof = retirementProof.parse(JSON.parse(proofJson)),
16
+ { terms } = jsonTerms(intent.termsJson),
17
+ first = terms.meters[0];
18
+ const view = intent.viewJson
19
+ ? (JSON.parse(intent.viewJson) as UsageSubscriptionView)
20
+ : null;
21
+ if (
22
+ !view ||
23
+ view.status !== "canceled" ||
24
+ proof.subscriptionId !== intent.providerId ||
25
+ proof.stripeAccountId !== first.scope.stripeAccountId ||
26
+ proof.customerAccount !== first.scope.customerAccount ||
27
+ proof.stripeCustomerId !== first.binding.stripeCustomerId ||
28
+ proof.livemode !== first.scope.livemode ||
29
+ proof.periodEnd < Math.max(...view.items.map((item) => item.period.end)) ||
30
+ proof.finalizedAt < proof.periodEnd
31
+ )
32
+ throw new Error(
33
+ "Enrollment retirement requires canceled subscription and finalized period-end invoice",
34
+ );
35
+ if (intent.retirementInvoiceId) {
36
+ if (intent.retirementInvoiceId !== proof.invoiceId)
37
+ throw new Error("Retirement invoice replay conflict");
38
+ return;
39
+ }
40
+ if (intent.controlKey)
41
+ throw new Error("Cancellation command is still pending");
42
+ for (const meter of terms.meters) {
43
+ const key = scopeKey(meter.scope);
44
+ for (const state of [
45
+ "queued",
46
+ "sending",
47
+ "unknown",
48
+ "held",
49
+ "rejected",
50
+ ] as const) {
51
+ const pending = await ctx.db
52
+ .query("usageOutbox")
53
+ .withIndex("by_scope_state", (q) =>
54
+ q.eq("scopeKey", key).eq("state", state),
55
+ )
56
+ .take(1);
57
+ if (pending.length)
58
+ throw new Error("Enrollment has unresolved usage delivery");
59
+ }
60
+ const reservations = await ctx.db
61
+ .query("usageReservations")
62
+ .withIndex("by_scope_state", (q) =>
63
+ q.eq("scopeKey", key).eq("state", "reserved"),
64
+ )
65
+ .take(1);
66
+ const errors = await ctx.db
67
+ .query("usageDeliveryErrors")
68
+ .withIndex("by_scope", (q) => q.eq("scopeKey", key))
69
+ .take(1);
70
+ if (reservations.length || errors.length)
71
+ throw new Error(
72
+ "Enrollment has pending reservations or validation errors",
73
+ );
74
+ }
75
+ await appendSnapshot(
76
+ ctx,
77
+ intent,
78
+ "retirement",
79
+ intent.providerId!,
80
+ {
81
+ proof,
82
+ creditTreatment: "retain_original_terms",
83
+ billingReconciliation: "required",
84
+ },
85
+ Date.now(),
86
+ );
87
+ for (const { scope, binding } of terms.meters) {
88
+ const key = JSON.stringify([
89
+ scope.stripeAccountId,
90
+ scope.livemode,
91
+ binding.stripeCustomerId,
92
+ scope.meterId,
93
+ ]);
94
+ const lock = await ctx.db
95
+ .query("usageSubscriptionLocks")
96
+ .withIndex("by_key", (q) => q.eq("key", key))
97
+ .unique();
98
+ if (lock?.intentKey === intent.key)
99
+ await ctx.db.delete("usageSubscriptionLocks", lock._id);
100
+ }
101
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
102
+ retiredAt: Math.floor(Date.now() / 1000),
103
+ retirementInvoiceId: proof.invoiceId,
104
+ });
105
+ }
@@ -0,0 +1,73 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const method = v.union(v.literal("direct"), v.literal("checkout"));
4
+ export const intentFields = {
5
+ key: v.string(),
6
+ scopeKey: v.string(),
7
+ termsJson: v.string(),
8
+ method,
9
+ firstAttemptAt: v.number(),
10
+ providerId: v.optional(v.string()),
11
+ checkoutId: v.optional(v.string()),
12
+ viewJson: v.optional(v.string()),
13
+ startedAt: v.optional(v.number()),
14
+ controlKey: v.optional(v.string()),
15
+ historyCount: v.optional(v.number()),
16
+ retiredAt: v.optional(v.number()),
17
+ abandonedId: v.optional(v.string()),
18
+ retirementInvoiceId: v.optional(v.string()),
19
+ };
20
+ export const intentDoc = v.object({
21
+ _id: v.id("usageSubscriptionIntents"),
22
+ _creationTime: v.number(),
23
+ ...intentFields,
24
+ });
25
+ export const intentsTable = defineTable(intentFields)
26
+ .index("by_key", ["key"])
27
+ .index("by_provider", ["providerId"]);
28
+ export const locksTable = defineTable({
29
+ key: v.string(),
30
+ intentKey: v.string(),
31
+ stripeAccountId: v.string(),
32
+ customerAccount: v.string(),
33
+ })
34
+ .index("by_key", ["key"])
35
+ .index("by_realm", ["stripeAccountId"])
36
+ .index("by_payer", ["customerAccount"]);
37
+ export const historyFields = {
38
+ intentKey: v.string(),
39
+ kind: v.union(
40
+ v.literal("subscription"),
41
+ v.literal("invoice"),
42
+ v.literal("retirement"),
43
+ ),
44
+ resourceId: v.string(),
45
+ fingerprint: v.string(),
46
+ observationJson: v.string(),
47
+ startedAt: v.number(),
48
+ };
49
+ export const historyDoc = v.object({
50
+ _id: v.id("usageSubscriptionHistory"),
51
+ _creationTime: v.number(),
52
+ ...historyFields,
53
+ });
54
+ export const historyTable = defineTable(historyFields)
55
+ .index("by_fingerprint", ["fingerprint"])
56
+ .index("by_intent_kind", ["intentKey", "kind"]);
57
+
58
+ export const controlFields = {
59
+ key: v.string(),
60
+ intentKey: v.string(),
61
+ operationId: v.string(),
62
+ cancelAtPeriodEnd: v.boolean(),
63
+ firstAttemptAt: v.number(),
64
+ resultJson: v.optional(v.string()),
65
+ };
66
+ export const controlDoc = v.object({
67
+ _id: v.id("usageSubscriptionControls"),
68
+ _creationTime: v.number(),
69
+ ...controlFields,
70
+ });
71
+ export const controlsTable = defineTable(controlFields).index("by_key", [
72
+ "key",
73
+ ]);