@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,117 @@
1
+ import { expect, it } from "vitest";
2
+ import { compareUsageObservations } from "./reconciliation.js";
3
+ import { summarizeUsageRecords } from "./summary.js";
4
+ import { prepareUsageRecord } from "./records.js";
5
+ const period = { start: 600, end: 1200 },
6
+ scope = {
7
+ stripeAccountId: "acct_platform",
8
+ customerAccount: "acct_buyer",
9
+ meterId: "mtr_calls",
10
+ livemode: false,
11
+ };
12
+ const record = prepareUsageRecord({
13
+ scope,
14
+ binding: {
15
+ stripeCustomerId: "cus_buyer",
16
+ stripePriceId: "price_calls",
17
+ eventName: "calls",
18
+ plan: {
19
+ key: "calls",
20
+ version: "v1",
21
+ model: "pay_as_you_go",
22
+ unit: { name: "call", precision: 0 },
23
+ rate: { currency: "usd", unitAmountDecimal: "2" },
24
+ },
25
+ },
26
+ sourceEventId: "one",
27
+ quantity: "2",
28
+ occurredAt: 700,
29
+ });
30
+ const subscription = {
31
+ subscriptionId: "sub_calls",
32
+ subscriptionItemId: "si_calls",
33
+ stripePriceId: "price_calls",
34
+ period,
35
+ interval: "month" as const,
36
+ };
37
+ const local = summarizeUsageRecords(
38
+ [
39
+ {
40
+ record,
41
+ subscription,
42
+ delivery: "provider_accepted",
43
+ hasValidationError: false,
44
+ },
45
+ ],
46
+ { period, complete: true, observedAt: 1201 },
47
+ );
48
+ const aggregate = {
49
+ status: "available" as const,
50
+ observedAt: 1201,
51
+ value: {
52
+ period,
53
+ quantity: "2",
54
+ scaledQuantity: "2",
55
+ complete: true,
56
+ nextCursor: null,
57
+ aggregationLagPossible: true as const,
58
+ stale: false,
59
+ entries: [{ id: "mtrusg_one", start: 600, end: 1200, scaledQuantity: "2" }],
60
+ },
61
+ };
62
+ it("separates observed matches from mismatches without changing usage", () => {
63
+ expect(
64
+ compareUsageObservations(local, aggregate, record.binding),
65
+ ).toMatchObject({
66
+ status: "observed_match",
67
+ localAcceptedQuantity: "2",
68
+ providerAcceptedQuantity: "2",
69
+ providerAggregateQuantity: "2",
70
+ });
71
+ expect(
72
+ compareUsageObservations(
73
+ local,
74
+ {
75
+ ...aggregate,
76
+ value: { ...aggregate.value, quantity: "0", scaledQuantity: "0" },
77
+ },
78
+ record.binding,
79
+ ),
80
+ ).toMatchObject({
81
+ status: "mismatch",
82
+ reason: "aggregation_lag_or_external_usage",
83
+ });
84
+ expect(record.quantity).toBe("2");
85
+ });
86
+ it("cannot compare stale, incomplete, absent or differently routed observations", () => {
87
+ expect(
88
+ compareUsageObservations(
89
+ local,
90
+ { ...aggregate, value: { ...aggregate.value, stale: true } },
91
+ record.binding,
92
+ ),
93
+ ).toMatchObject({ status: "unavailable", reason: "aggregate_stale" });
94
+ expect(
95
+ compareUsageObservations(
96
+ { ...local, complete: false },
97
+ aggregate,
98
+ record.binding,
99
+ ),
100
+ ).toMatchObject({
101
+ status: "unavailable",
102
+ reason: "local_history_incomplete",
103
+ });
104
+ expect(
105
+ compareUsageObservations(
106
+ local,
107
+ { status: "unavailable", reason: "aggregation_pending", retryable: true },
108
+ record.binding,
109
+ ),
110
+ ).toMatchObject({ status: "unavailable", providerAggregateQuantity: null });
111
+ expect(
112
+ compareUsageObservations(local, aggregate, {
113
+ ...record.binding,
114
+ stripePriceId: "price_changed",
115
+ }),
116
+ ).toMatchObject({ status: "unavailable", reason: "ambiguous_local_terms" });
117
+ });
@@ -0,0 +1,86 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { UsageLocalSummary } from "./summary.js";
3
+ import { decimalFromScaled } from "./summary.js";
4
+ import type { UsageAggregateObservation } from "./observationTypes.js";
5
+ import type { PreparedUsageRecord } from "./records.js";
6
+ export type UsageComparison = {
7
+ status: "observed_match" | "mismatch" | "unavailable";
8
+ reason: string;
9
+ localAcceptedQuantity: string | null;
10
+ providerAcceptedQuantity: string | null;
11
+ providerAggregateQuantity: string | null;
12
+ };
13
+ export function compareUsageObservations(
14
+ local: UsageLocalSummary,
15
+ aggregate: UsageAggregateObservation,
16
+ binding: PreparedUsageRecord["binding"],
17
+ ): UsageComparison {
18
+ const value: UsageComparison = {
19
+ status: "unavailable",
20
+ reason: "provider_unavailable",
21
+ localAcceptedQuantity: null,
22
+ providerAcceptedQuantity: null,
23
+ providerAggregateQuantity:
24
+ aggregate.status === "available" ? aggregate.value.quantity : null,
25
+ };
26
+ const unavailable = (reason: string) => ({ ...value, reason });
27
+ if (!local.complete) return unavailable("local_history_incomplete");
28
+ if (
29
+ local.groups.some(
30
+ (group) =>
31
+ JSON.stringify(convexToJson(group.binding)) !==
32
+ JSON.stringify(convexToJson(binding)),
33
+ )
34
+ )
35
+ return unavailable("ambiguous_local_terms");
36
+ const accepted = local.groups.reduce(
37
+ (sum, group) => sum + BigInt(group.acceptedScaledQuantity),
38
+ 0n,
39
+ ),
40
+ provider = local.groups.reduce(
41
+ (sum, group) => sum + BigInt(group.providerAcceptedScaledQuantity),
42
+ 0n,
43
+ );
44
+ value.localAcceptedQuantity = decimalFromScaled(
45
+ accepted,
46
+ binding.plan.unit.precision,
47
+ );
48
+ value.providerAcceptedQuantity = decimalFromScaled(
49
+ provider,
50
+ binding.plan.unit.precision,
51
+ );
52
+ if (aggregate.status !== "available") return unavailable(aggregate.reason);
53
+ if (aggregate.value.stale) return unavailable("aggregate_stale");
54
+ if (!aggregate.value.complete)
55
+ return unavailable("provider_history_incomplete");
56
+ if (
57
+ local.period.start !== aggregate.value.period.start ||
58
+ local.period.end !== aggregate.value.period.end
59
+ )
60
+ return unavailable("period_mismatch");
61
+ if (
62
+ local.groups.some(
63
+ (g) =>
64
+ g.deliveryQuantities.unknown !== "0" ||
65
+ g.deliveryQuantities.sending !== "0",
66
+ )
67
+ )
68
+ return unavailable("delivery_unresolved");
69
+ if (local.groups.some((g) => g.validationErrorEventCount > 0))
70
+ return {
71
+ ...value,
72
+ status: "mismatch",
73
+ reason: "provider_validation_errors",
74
+ };
75
+ return {
76
+ ...value,
77
+ status:
78
+ provider === BigInt(aggregate.value.scaledQuantity)
79
+ ? "observed_match"
80
+ : "mismatch",
81
+ reason:
82
+ provider === BigInt(aggregate.value.scaledQuantity)
83
+ ? "observations_equal"
84
+ : "aggregation_lag_or_external_usage",
85
+ };
86
+ }
@@ -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
+ });