@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,222 @@
1
+ import { expect, it } from "vitest";
2
+ import { summarizeUsageRecords } from "./summary.js";
3
+ import { prepareUsageRecord } from "./records.js";
4
+ const scope = {
5
+ stripeAccountId: "acct_platform",
6
+ customerAccount: "acct_buyer",
7
+ meterId: "mtr_calls",
8
+ livemode: false,
9
+ };
10
+ const period = { start: 600, end: 1200 };
11
+ const subscription = {
12
+ subscriptionId: "sub_calls",
13
+ subscriptionItemId: "si_calls",
14
+ stripePriceId: "price_calls",
15
+ period,
16
+ interval: "month" as const,
17
+ };
18
+ function view(model = "pay_as_you_go", quantity = "1.25", currency = "usd") {
19
+ const record = prepareUsageRecord({
20
+ scope,
21
+ binding: {
22
+ stripeCustomerId: "cus_buyer",
23
+ stripePriceId: "price_calls",
24
+ eventName: "calls",
25
+ plan: {
26
+ key: "calls",
27
+ version: "v1",
28
+ model,
29
+ unit: { name: "call", precision: 2 },
30
+ rate: { currency, unitAmountDecimal: "2" },
31
+ ...(model === "included_overage"
32
+ ? { includedQuantity: "1", reset: "billing_period" }
33
+ : model === "prepaid"
34
+ ? { insufficientBalance: "reject" }
35
+ : {}),
36
+ },
37
+ },
38
+ sourceEventId: "one",
39
+ quantity,
40
+ occurredAt: 700,
41
+ });
42
+ return {
43
+ record,
44
+ subscription,
45
+ delivery: "provider_accepted" as const,
46
+ hasValidationError: false,
47
+ };
48
+ }
49
+ it("keeps exact accepted and transport-accepted quantities and separate currencies", () => {
50
+ const local = summarizeUsageRecords(
51
+ [
52
+ view(),
53
+ {
54
+ ...view("pay_as_you_go", "2.5", "eur"),
55
+ record: {
56
+ ...view("pay_as_you_go", "2.5", "eur").record,
57
+ binding: {
58
+ ...view("pay_as_you_go", "2.5", "eur").record.binding,
59
+ stripeCustomerId: "cus_eur",
60
+ },
61
+ },
62
+ delivery: "queued",
63
+ },
64
+ ],
65
+ { period, complete: true, observedAt: 1201 },
66
+ );
67
+ expect(local).toMatchObject({
68
+ complete: true,
69
+ eventCount: 2,
70
+ groups: [
71
+ {
72
+ acceptedQuantity: "1.25",
73
+ providerAcceptedQuantity: "1.25",
74
+ estimate: {
75
+ status: "available",
76
+ value: { amountDecimal: "2.5", currency: "usd" },
77
+ },
78
+ },
79
+ {
80
+ acceptedQuantity: "2.5",
81
+ providerAcceptedQuantity: "0",
82
+ estimate: {
83
+ status: "available",
84
+ value: { amountDecimal: "5", currency: "eur" },
85
+ },
86
+ },
87
+ ],
88
+ });
89
+ });
90
+ it("applies included units only to a complete original billing period", () => {
91
+ expect(
92
+ summarizeUsageRecords([view("included_overage")], {
93
+ period,
94
+ complete: true,
95
+ observedAt: 1201,
96
+ }),
97
+ ).toMatchObject({
98
+ groups: [
99
+ {
100
+ included: {
101
+ status: "available",
102
+ value: { consumed: "1.25", remaining: "0", overage: "0.25" },
103
+ },
104
+ estimate: { status: "available", value: { amountDecimal: "0.5" } },
105
+ },
106
+ ],
107
+ });
108
+ expect(
109
+ summarizeUsageRecords([view("included_overage")], {
110
+ period: { start: 700, end: 900 },
111
+ complete: true,
112
+ observedAt: 1201,
113
+ }),
114
+ ).toMatchObject({
115
+ groups: [
116
+ {
117
+ included: { status: "unavailable", reason: "partial_billing_period" },
118
+ estimate: { status: "unavailable" },
119
+ },
120
+ ],
121
+ });
122
+ });
123
+ it("does not fabricate prepaid balances or complete estimates from incomplete history", () => {
124
+ expect(
125
+ summarizeUsageRecords([view("prepaid")], {
126
+ period,
127
+ complete: true,
128
+ observedAt: 1201,
129
+ }),
130
+ ).toMatchObject({
131
+ groups: [
132
+ {
133
+ credits: {
134
+ status: "unavailable",
135
+ reason: "credit_accounting_not_configured",
136
+ },
137
+ estimate: { status: "unavailable" },
138
+ },
139
+ ],
140
+ });
141
+ expect(
142
+ summarizeUsageRecords([view()], {
143
+ period,
144
+ complete: false,
145
+ observedAt: 1201,
146
+ }),
147
+ ).toMatchObject({
148
+ complete: false,
149
+ groups: [
150
+ {
151
+ estimate: { status: "unavailable", reason: "local_history_incomplete" },
152
+ },
153
+ ],
154
+ });
155
+ });
156
+
157
+ it("does not estimate invoice usage across overlapping native subscription items", () => {
158
+ const first = view(),
159
+ second = {
160
+ ...view(),
161
+ subscription: { ...subscription, subscriptionItemId: "si_other" },
162
+ };
163
+ const result = summarizeUsageRecords([first, second], {
164
+ period,
165
+ complete: true,
166
+ observedAt: 1201,
167
+ });
168
+ expect(
169
+ result.groups.every(
170
+ (group) =>
171
+ group.estimate.status === "unavailable" &&
172
+ group.estimate.reason === "ambiguous_subscription_binding",
173
+ ),
174
+ ).toBe(true);
175
+ });
176
+
177
+ it("withholds allowance estimates across same-item price transitions", () => {
178
+ const first = view("included_overage", "0.75");
179
+ const second = structuredClone(first);
180
+ second.record.binding.plan.version = "v2";
181
+ second.record.binding.stripePriceId = "price_v2";
182
+ second.subscription = { ...subscription, stripePriceId: "price_v2" };
183
+ const result = summarizeUsageRecords([first, second], {
184
+ period,
185
+ complete: true,
186
+ observedAt: 1201,
187
+ });
188
+ expect(result.groups).toHaveLength(2);
189
+ for (const group of result.groups) {
190
+ expect(group.acceptedQuantity).toBe("0.75");
191
+ expect(group.included).toMatchObject({
192
+ status: "unavailable",
193
+ reason: "ambiguous_subscription_binding",
194
+ });
195
+ expect(group.estimate).toMatchObject({
196
+ status: "unavailable",
197
+ reason: "ambiguous_subscription_binding",
198
+ });
199
+ }
200
+ });
201
+
202
+ it("combines semantically identical snapshots regardless of property order", () => {
203
+ const first = view("included_overage", "0.75");
204
+ const second = structuredClone(first);
205
+ second.subscription = {
206
+ interval: subscription.interval,
207
+ period: { end: period.end, start: period.start },
208
+ stripePriceId: subscription.stripePriceId,
209
+ subscriptionItemId: subscription.subscriptionItemId,
210
+ subscriptionId: subscription.subscriptionId,
211
+ };
212
+ const result = summarizeUsageRecords([first, second], {
213
+ period,
214
+ complete: true,
215
+ observedAt: 1201,
216
+ });
217
+ expect(result.groups).toHaveLength(1);
218
+ expect(result.groups[0].included).toMatchObject({
219
+ status: "available",
220
+ value: { consumed: "1.5", overage: "0.5" },
221
+ });
222
+ });
@@ -0,0 +1,188 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { PreparedUsageRecord, UsageDeliveryState } from "./records.js";
3
+ import { parseUsageQuantity } from "./contracts.js";
4
+ import type {
5
+ UsageAvailability,
6
+ UsagePeriod,
7
+ UsageSubscriptionBinding,
8
+ } from "./boundaries.js";
9
+ export type UsageSummaryEvent = {
10
+ record: PreparedUsageRecord;
11
+ subscription: UsageSubscriptionBinding;
12
+ delivery: UsageDeliveryState;
13
+ hasValidationError: boolean;
14
+ };
15
+ export type UsageCreditSummary = {
16
+ availableQuantity: string;
17
+ reservedQuantity: string;
18
+ consumedQuantity: string;
19
+ expiredQuantity: string;
20
+ };
21
+ export type UsageLocalGroup = {
22
+ binding: PreparedUsageRecord["binding"];
23
+ subscription: UsageSubscriptionBinding;
24
+ acceptedScaledQuantity: string;
25
+ providerAcceptedScaledQuantity: string;
26
+ acceptedQuantity: string;
27
+ providerAcceptedQuantity: string;
28
+ eventCount: number;
29
+ validationErrorEventCount: number;
30
+ deliveryQuantities: Record<UsageDeliveryState, string>;
31
+ estimate: UsageAvailability<{ amountDecimal: string; currency: string }>;
32
+ included: UsageAvailability<{
33
+ included: string;
34
+ consumed: string;
35
+ remaining: string;
36
+ overage: string;
37
+ }>;
38
+ credits: UsageAvailability<UsageCreditSummary>;
39
+ };
40
+ export type UsageLocalSummary = {
41
+ period: UsagePeriod;
42
+ observedAt: number;
43
+ complete: boolean;
44
+ eventCount: number;
45
+ groups: UsageLocalGroup[];
46
+ };
47
+ export function decimalFromScaled(value: bigint, precision: number): string {
48
+ if (precision === 0) return value.toString();
49
+ const digits = value.toString().padStart(precision + 1, "0"),
50
+ whole = digits.slice(0, -precision),
51
+ fraction = digits.slice(-precision).replace(/0+$/, "");
52
+ return fraction ? `${whole}.${fraction}` : whole;
53
+ }
54
+ function rateAmount(quantity: bigint, record: PreparedUsageRecord) {
55
+ const [whole, fraction = ""] =
56
+ record.binding.plan.rate.unitAmountDecimal.split(".");
57
+ return decimalFromScaled(
58
+ quantity * BigInt(whole + fraction),
59
+ record.binding.plan.unit.precision + fraction.length,
60
+ );
61
+ }
62
+ const unavailable = (reason: string) => ({
63
+ status: "unavailable" as const,
64
+ reason,
65
+ retryable: false,
66
+ });
67
+ const states: UsageDeliveryState[] = [
68
+ "queued",
69
+ "sending",
70
+ "provider_accepted",
71
+ "rejected",
72
+ "unknown",
73
+ "held",
74
+ ];
75
+ export function summarizeUsageRecords(
76
+ events: UsageSummaryEvent[],
77
+ options: { period: UsagePeriod; complete: boolean; observedAt: number },
78
+ ): UsageLocalSummary {
79
+ const grouped = new Map<string, UsageSummaryEvent[]>();
80
+ for (const event of events) {
81
+ const key = JSON.stringify(
82
+ convexToJson([event.record.binding, event.subscription]),
83
+ );
84
+ const group = grouped.get(key) ?? [];
85
+ group.push(event);
86
+ grouped.set(key, group);
87
+ }
88
+ const groups: UsageLocalGroup[] = [];
89
+ for (const values of grouped.values()) {
90
+ const { record, subscription } = values[0],
91
+ plan = record.binding.plan,
92
+ precision = plan.unit.precision;
93
+ const sums = Object.fromEntries(
94
+ states.map((state) => [state, 0n]),
95
+ ) as Record<UsageDeliveryState, bigint>;
96
+ for (const value of values)
97
+ sums[value.delivery] += BigInt(value.record.scaledQuantity);
98
+ const accepted = states.reduce((sum, state) => sum + sums[state], 0n);
99
+ const fullPeriod =
100
+ options.period.start === subscription.period.start &&
101
+ options.period.end === subscription.period.end;
102
+ const eligible =
103
+ options.complete && (plan.model !== "included_overage" || fullPeriod);
104
+ let chargeable = accepted;
105
+ let included: UsageLocalGroup["included"] = unavailable(
106
+ plan.model === "included_overage"
107
+ ? options.complete
108
+ ? "partial_billing_period"
109
+ : "local_history_incomplete"
110
+ : "not_included_model",
111
+ );
112
+ if (plan.model === "included_overage" && eligible) {
113
+ const allowance = BigInt(
114
+ parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
115
+ );
116
+ chargeable = accepted > allowance ? accepted - allowance : 0n;
117
+ included = {
118
+ status: "available",
119
+ observedAt: options.observedAt,
120
+ value: {
121
+ included: decimalFromScaled(allowance, precision),
122
+ consumed: decimalFromScaled(accepted, precision),
123
+ remaining: decimalFromScaled(
124
+ allowance > accepted ? allowance - accepted : 0n,
125
+ precision,
126
+ ),
127
+ overage: decimalFromScaled(chargeable, precision),
128
+ },
129
+ };
130
+ }
131
+ groups.push({
132
+ binding: record.binding,
133
+ subscription,
134
+ acceptedScaledQuantity: accepted.toString(),
135
+ providerAcceptedScaledQuantity: sums.provider_accepted.toString(),
136
+ acceptedQuantity: decimalFromScaled(accepted, precision),
137
+ providerAcceptedQuantity: decimalFromScaled(
138
+ sums.provider_accepted,
139
+ precision,
140
+ ),
141
+ eventCount: values.length,
142
+ validationErrorEventCount: values.filter((v) => v.hasValidationError)
143
+ .length,
144
+ deliveryQuantities: Object.fromEntries(
145
+ states.map((state) => [
146
+ state,
147
+ decimalFromScaled(sums[state], precision),
148
+ ]),
149
+ ) as Record<UsageDeliveryState, string>,
150
+ included,
151
+ estimate: !options.complete
152
+ ? unavailable("local_history_incomplete")
153
+ : plan.model === "prepaid"
154
+ ? unavailable("credit_accounting_not_configured")
155
+ : !eligible
156
+ ? unavailable("partial_billing_period")
157
+ : {
158
+ status: "available",
159
+ observedAt: options.observedAt,
160
+ value: {
161
+ amountDecimal: rateAmount(chargeable, record),
162
+ currency: plan.rate.currency,
163
+ },
164
+ },
165
+ credits: unavailable(
166
+ plan.model === "prepaid"
167
+ ? "credit_accounting_not_configured"
168
+ : "not_prepaid_model",
169
+ ),
170
+ });
171
+ }
172
+ for (const group of groups) {
173
+ if (
174
+ groups.some(
175
+ (other) =>
176
+ other !== group &&
177
+ other.binding.stripeCustomerId === group.binding.stripeCustomerId &&
178
+ other.subscription.period.start < group.subscription.period.end &&
179
+ other.subscription.period.end > group.subscription.period.start,
180
+ )
181
+ ) {
182
+ group.estimate = unavailable("ambiguous_subscription_binding");
183
+ if (group.binding.plan.model === "included_overage")
184
+ group.included = unavailable("ambiguous_subscription_binding");
185
+ }
186
+ }
187
+ return { ...options, eventCount: events.length, groups };
188
+ }
@@ -1,3 +1,4 @@
1
+ import { syncManagedUsageEvent } from "./usageSubscriptions.js";
1
2
  import { isFixedPrice } from "../products/fixedPrice.js";
2
3
  import { handleRefundEvent } from "./refundDelivery.js";
3
4
  import { handlePayoutEvent } from "./payoutReconciliation.js";
@@ -31,6 +32,7 @@ export async function processEvent(
31
32
  event: Stripe.Event,
32
33
  ): Promise<void> {
33
34
  // Stripe guarantees the object type matches event.type, so these casts are safe.
35
+ await syncManagedUsageEvent(whCtx, event);
34
36
  const obj = event.data.object;
35
37
 
36
38
  switch (event.type) {
@@ -0,0 +1,162 @@
1
+ import { expect, it } from "vitest";
2
+ import type Stripe from "stripe";
3
+ import { fixture } from "../usage/subscriptionTransport.fixtures.js";
4
+ import { request } from "../usage/subscription.fixtures.js";
5
+ import { BetterStripe } from "../index.js";
6
+ import type { RunCtx } from "../helpers.js";
7
+ import type { WebhookContext } from "./helpers.js";
8
+ import { syncManagedUsageEvent } from "./usageSubscriptions.js";
9
+ const ref = {
10
+ scope: {
11
+ stripeAccountId: "acct_platform",
12
+ customerAccount: "acct_buyer",
13
+ livemode: false,
14
+ },
15
+ requestId: "signup1",
16
+ };
17
+ it("refreshes managed native state rather than trusting an old subscription payload", async () => {
18
+ const f = fixture(),
19
+ client = new BetterStripe(f.component),
20
+ options = {
21
+ stripeSecretKey: "sk_test_subscription",
22
+ httpClient: f.httpClient,
23
+ };
24
+ await f.t.action((ctx) =>
25
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
26
+ );
27
+ const event = {
28
+ type: "customer.subscription.updated",
29
+ livemode: false,
30
+ data: { object: { ...f.state.native, status: "past_due" } },
31
+ } as unknown as Stripe.Event;
32
+ await f.t.action((ctx) =>
33
+ syncManagedUsageEvent(
34
+ {
35
+ ctx,
36
+ component: f.component,
37
+ stripe: f.stripe,
38
+ webhookSecret: "whsec_fixture",
39
+ } as WebhookContext,
40
+ event,
41
+ ),
42
+ );
43
+ expect(
44
+ await f.t.query((ctx) => client.usage.getSubscription(ctx as RunCtx, ref)),
45
+ ).toMatchObject({ status: "available", value: { status: "active" } });
46
+ f.state.missingNative = true;
47
+ await expect(
48
+ f.t.action((ctx) =>
49
+ syncManagedUsageEvent(
50
+ {
51
+ ctx,
52
+ component: f.component,
53
+ stripe: f.stripe,
54
+ webhookSecret: "whsec_fixture",
55
+ } as WebhookContext,
56
+ event,
57
+ ),
58
+ ),
59
+ ).rejects.toThrow("Native usage lifecycle observation unavailable");
60
+ });
61
+ it("records managed paid invoice observations without treating paid status as new cash", async () => {
62
+ const f = fixture(),
63
+ client = new BetterStripe(f.component),
64
+ options = {
65
+ stripeSecretKey: "sk_test_subscription",
66
+ httpClient: f.httpClient,
67
+ };
68
+ await f.t.action((ctx) =>
69
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
70
+ );
71
+ const event = {
72
+ type: "invoice.paid",
73
+ livemode: false,
74
+ data: {
75
+ object: {
76
+ id: "in_closeout",
77
+ parent: {
78
+ subscription_details: {
79
+ subscription: "sub_calls",
80
+ metadata: f.state.native!.metadata,
81
+ },
82
+ },
83
+ },
84
+ },
85
+ } as unknown as Stripe.Event;
86
+ await f.t.action((ctx) =>
87
+ syncManagedUsageEvent(
88
+ {
89
+ ctx,
90
+ component: f.component,
91
+ stripe: f.stripe,
92
+ webhookSecret: "whsec_fixture",
93
+ } as WebhookContext,
94
+ event,
95
+ ),
96
+ );
97
+ const history = await f.t.query((ctx) =>
98
+ client.usage.readSubscriptionHistory(ctx as RunCtx, {
99
+ ...ref,
100
+ kind: "invoice",
101
+ limit: 10,
102
+ cursor: null,
103
+ }),
104
+ );
105
+ expect(history.records[0].observation).toMatchObject([
106
+ {
107
+ observation: {
108
+ status: "available",
109
+ value: { status: "paid", paymentEvidence: "not_resolved" },
110
+ },
111
+ },
112
+ ]);
113
+ expect(
114
+ f.calls
115
+ .filter((call) => call.path.includes("/invoices/"))
116
+ .every((call) => call.method === "GET"),
117
+ ).toBe(true);
118
+ });
119
+ it("leaves existing fixed-price flows untouched and rejects foreign managed event context", async () => {
120
+ const f = fixture();
121
+ await f.t.action((ctx) =>
122
+ syncManagedUsageEvent(
123
+ {
124
+ ctx,
125
+ component: f.component,
126
+ stripe: f.stripe,
127
+ webhookSecret: "whsec_fixture",
128
+ } as WebhookContext,
129
+ {
130
+ type: "customer.subscription.updated",
131
+ livemode: false,
132
+ data: { object: { id: "sub_fixed", metadata: {} } },
133
+ } as unknown as Stripe.Event,
134
+ ),
135
+ );
136
+ expect(f.calls).toHaveLength(0);
137
+ const client = new BetterStripe(f.component);
138
+ await f.t.action((ctx) =>
139
+ client.usage.ensureSubscription(ctx as RunCtx, request, {
140
+ stripeSecretKey: "sk_test_subscription",
141
+ httpClient: f.httpClient,
142
+ }),
143
+ );
144
+ await expect(
145
+ f.t.action((ctx) =>
146
+ syncManagedUsageEvent(
147
+ {
148
+ ctx,
149
+ component: f.component,
150
+ stripe: f.stripe,
151
+ webhookSecret: "whsec_fixture",
152
+ } as WebhookContext,
153
+ {
154
+ type: "customer.subscription.updated",
155
+ account: "acct_foreign",
156
+ livemode: false,
157
+ data: { object: f.state.native },
158
+ } as unknown as Stripe.Event,
159
+ ),
160
+ ),
161
+ ).rejects.toThrow("Native usage lifecycle observation unavailable");
162
+ });
@@ -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
+ }
@@ -174,6 +174,17 @@ import type * as usageDelivery_mutations from "../usageDelivery/mutations.js";
174
174
  import type * as usageDelivery_queries from "../usageDelivery/queries.js";
175
175
  import type * as usageDelivery_steps from "../usageDelivery/steps.js";
176
176
  import type * as usageDelivery_workflow from "../usageDelivery/workflow.js";
177
+ import type * as usageObservations_helpers from "../usageObservations/helpers.js";
178
+ import type * as usageObservations_history from "../usageObservations/history.js";
179
+ import type * as usageObservations_mutations from "../usageObservations/mutations.js";
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";
177
188
  import type * as webhooks_mutations from "../webhooks/mutations.js";
178
189
  import type * as webhooks_queries from "../webhooks/queries.js";
179
190
  import type * as webhooks_validators from "../webhooks/validators.js";
@@ -352,6 +363,17 @@ const fullApi: ApiFromModules<{
352
363
  "usageDelivery/queries": typeof usageDelivery_queries;
353
364
  "usageDelivery/steps": typeof usageDelivery_steps;
354
365
  "usageDelivery/workflow": typeof usageDelivery_workflow;
366
+ "usageObservations/helpers": typeof usageObservations_helpers;
367
+ "usageObservations/history": typeof usageObservations_history;
368
+ "usageObservations/mutations": typeof usageObservations_mutations;
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;
355
377
  "webhooks/mutations": typeof webhooks_mutations;
356
378
  "webhooks/queries": typeof webhooks_queries;
357
379
  "webhooks/validators": typeof webhooks_validators;