@fantastic.dev/better-stripe 0.57.0 → 0.59.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 (230) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +356 -50
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +162 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +356 -50
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +162 -9
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/allowanceClient.d.ts +51 -0
  12. package/dist/client/usage/allowanceClient.d.ts.map +1 -0
  13. package/dist/client/usage/allowanceClient.js +64 -0
  14. package/dist/client/usage/allowanceClient.js.map +1 -0
  15. package/dist/client/usage/allowanceTerms.d.ts +64 -0
  16. package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
  17. package/dist/client/usage/allowanceTerms.js +101 -0
  18. package/dist/client/usage/allowanceTerms.js.map +1 -0
  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/correctionClient.d.ts +33 -0
  24. package/dist/client/usage/correctionClient.d.ts.map +1 -0
  25. package/dist/client/usage/correctionClient.js +27 -0
  26. package/dist/client/usage/correctionClient.js.map +1 -0
  27. package/dist/client/usage/correctionEligibility.d.ts +4 -0
  28. package/dist/client/usage/correctionEligibility.d.ts.map +1 -0
  29. package/dist/client/usage/correctionEligibility.js +7 -0
  30. package/dist/client/usage/correctionEligibility.js.map +1 -0
  31. package/dist/client/usage/correctionInvoice.d.ts +9 -0
  32. package/dist/client/usage/correctionInvoice.d.ts.map +1 -0
  33. package/dist/client/usage/correctionInvoice.js +218 -0
  34. package/dist/client/usage/correctionInvoice.js.map +1 -0
  35. package/dist/client/usage/correctionInvoiceProof.d.ts +29 -0
  36. package/dist/client/usage/correctionInvoiceProof.d.ts.map +1 -0
  37. package/dist/client/usage/correctionInvoiceProof.js +41 -0
  38. package/dist/client/usage/correctionInvoiceProof.js.map +1 -0
  39. package/dist/client/usage/correctionProofs.d.ts +36 -0
  40. package/dist/client/usage/correctionProofs.d.ts.map +1 -0
  41. package/dist/client/usage/correctionProofs.js +41 -0
  42. package/dist/client/usage/correctionProofs.js.map +1 -0
  43. package/dist/client/usage/correctionProvider.d.ts +6 -0
  44. package/dist/client/usage/correctionProvider.d.ts.map +1 -0
  45. package/dist/client/usage/correctionProvider.js +243 -0
  46. package/dist/client/usage/correctionProvider.js.map +1 -0
  47. package/dist/client/usage/correctionRead.d.ts +27 -0
  48. package/dist/client/usage/correctionRead.d.ts.map +1 -0
  49. package/dist/client/usage/correctionRead.js +36 -0
  50. package/dist/client/usage/correctionRead.js.map +1 -0
  51. package/dist/client/usage/correctionTerms.d.ts +64 -0
  52. package/dist/client/usage/correctionTerms.d.ts.map +1 -0
  53. package/dist/client/usage/correctionTerms.js +65 -0
  54. package/dist/client/usage/correctionTerms.js.map +1 -0
  55. package/dist/client/usage/correctionTransport.fixtures.d.ts +37 -0
  56. package/dist/client/usage/correctionTransport.fixtures.d.ts.map +1 -0
  57. package/dist/client/usage/correctionTransport.fixtures.js +322 -0
  58. package/dist/client/usage/correctionTransport.fixtures.js.map +1 -0
  59. package/dist/client/usage/creditClient.d.ts +1 -1
  60. package/dist/client/usage/index.d.ts +4 -0
  61. package/dist/client/usage/index.d.ts.map +1 -1
  62. package/dist/client/usage/observationClient.d.ts +20 -0
  63. package/dist/client/usage/observationClient.d.ts.map +1 -1
  64. package/dist/client/usage/observationClient.js +20 -6
  65. package/dist/client/usage/observationClient.js.map +1 -1
  66. package/dist/client/usage/records.d.ts +1 -1
  67. package/dist/client/usage/records.d.ts.map +1 -1
  68. package/dist/client/usage/records.js.map +1 -1
  69. package/dist/client/usage/summary.d.ts +3 -0
  70. package/dist/client/usage/summary.d.ts.map +1 -1
  71. package/dist/client/usage/summary.js +9 -4
  72. package/dist/client/usage/summary.js.map +1 -1
  73. package/dist/client/usageExports.d.ts +4 -0
  74. package/dist/client/usageExports.d.ts.map +1 -1
  75. package/dist/component/_generated/api.d.ts +20 -0
  76. package/dist/component/_generated/api.d.ts.map +1 -1
  77. package/dist/component/_generated/api.js.map +1 -1
  78. package/dist/component/_generated/component.d.ts +324 -13
  79. package/dist/component/_generated/component.d.ts.map +1 -1
  80. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  81. package/dist/component/accountClosure/mutations.js +13 -0
  82. package/dist/component/accountClosure/mutations.js.map +1 -1
  83. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  84. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  85. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  86. package/dist/component/earnings/triggers.d.ts +288 -10
  87. package/dist/component/earnings/triggers.d.ts.map +1 -1
  88. package/dist/component/schema.d.ts +162 -9
  89. package/dist/component/schema.js +7 -0
  90. package/dist/component/schema.js.map +1 -1
  91. package/dist/component/usage/mutations.d.ts.map +1 -1
  92. package/dist/component/usage/mutations.js +4 -0
  93. package/dist/component/usage/mutations.js.map +1 -1
  94. package/dist/component/usage/queries.d.ts +2 -2
  95. package/dist/component/usage/schema.d.ts +21 -15
  96. package/dist/component/usage/schema.d.ts.map +1 -1
  97. package/dist/component/usage/schema.js +4 -2
  98. package/dist/component/usage/schema.js.map +1 -1
  99. package/dist/component/usageAllowance/helpers.d.ts +78 -0
  100. package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
  101. package/dist/component/usageAllowance/helpers.js +99 -0
  102. package/dist/component/usageAllowance/helpers.js.map +1 -0
  103. package/dist/component/usageAllowance/mutations.d.ts +37 -0
  104. package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
  105. package/dist/component/usageAllowance/mutations.js +99 -0
  106. package/dist/component/usageAllowance/mutations.js.map +1 -0
  107. package/dist/component/usageAllowance/queries.d.ts +36 -0
  108. package/dist/component/usageAllowance/queries.d.ts.map +1 -0
  109. package/dist/component/usageAllowance/queries.js +122 -0
  110. package/dist/component/usageAllowance/queries.js.map +1 -0
  111. package/dist/component/usageAllowance/reservations.d.ts +25 -0
  112. package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
  113. package/dist/component/usageAllowance/reservations.js +150 -0
  114. package/dist/component/usageAllowance/reservations.js.map +1 -0
  115. package/dist/component/usageAllowance/schema.d.ts +77 -0
  116. package/dist/component/usageAllowance/schema.d.ts.map +1 -0
  117. package/dist/component/usageAllowance/schema.js +32 -0
  118. package/dist/component/usageAllowance/schema.js.map +1 -0
  119. package/dist/component/usageCorrections/accounting.d.ts +5 -0
  120. package/dist/component/usageCorrections/accounting.d.ts.map +1 -0
  121. package/dist/component/usageCorrections/accounting.js +55 -0
  122. package/dist/component/usageCorrections/accounting.js.map +1 -0
  123. package/dist/component/usageCorrections/cancellation.d.ts +6 -0
  124. package/dist/component/usageCorrections/cancellation.d.ts.map +1 -0
  125. package/dist/component/usageCorrections/cancellation.js +29 -0
  126. package/dist/component/usageCorrections/cancellation.js.map +1 -0
  127. package/dist/component/usageCorrections/helpers.d.ts +60 -0
  128. package/dist/component/usageCorrections/helpers.d.ts.map +1 -0
  129. package/dist/component/usageCorrections/helpers.js +52 -0
  130. package/dist/component/usageCorrections/helpers.js.map +1 -0
  131. package/dist/component/usageCorrections/invoice.d.ts +38 -0
  132. package/dist/component/usageCorrections/invoice.d.ts.map +1 -0
  133. package/dist/component/usageCorrections/invoice.js +82 -0
  134. package/dist/component/usageCorrections/invoice.js.map +1 -0
  135. package/dist/component/usageCorrections/mutations.d.ts +121 -0
  136. package/dist/component/usageCorrections/mutations.d.ts.map +1 -0
  137. package/dist/component/usageCorrections/mutations.js +256 -0
  138. package/dist/component/usageCorrections/mutations.js.map +1 -0
  139. package/dist/component/usageCorrections/queries.d.ts +115 -0
  140. package/dist/component/usageCorrections/queries.d.ts.map +1 -0
  141. package/dist/component/usageCorrections/queries.js +84 -0
  142. package/dist/component/usageCorrections/queries.js.map +1 -0
  143. package/dist/component/usageCorrections/schema.d.ts +248 -0
  144. package/dist/component/usageCorrections/schema.d.ts.map +1 -0
  145. package/dist/component/usageCorrections/schema.js +74 -0
  146. package/dist/component/usageCorrections/schema.js.map +1 -0
  147. package/dist/component/usageCredits/queries.d.ts +1 -1
  148. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  149. package/dist/component/usageCredits/queries.js +6 -0
  150. package/dist/component/usageCredits/queries.js.map +1 -1
  151. package/dist/component/usageCredits/schema.d.ts +5 -5
  152. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  153. package/dist/component/usageCredits/schema.js +1 -1
  154. package/dist/component/usageCredits/schema.js.map +1 -1
  155. package/dist/component/usageDelivery/fields.d.ts +2 -2
  156. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  157. package/dist/component/usageDelivery/fields.js +1 -1
  158. package/dist/component/usageDelivery/fields.js.map +1 -1
  159. package/dist/component/usageDelivery/helpers.d.ts +7 -6
  160. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  161. package/dist/component/usageDelivery/mutations.d.ts +6 -6
  162. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  163. package/dist/component/usageDelivery/mutations.js +9 -1
  164. package/dist/component/usageDelivery/mutations.js.map +1 -1
  165. package/dist/component/usageDelivery/queries.d.ts +8 -6
  166. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  167. package/dist/component/usageDelivery/schema.d.ts +4 -4
  168. package/dist/component/usageDelivery/steps.d.ts +2 -2
  169. package/dist/component/usageDelivery/steps.js +1 -1
  170. package/dist/component/usageDelivery/steps.js.map +1 -1
  171. package/dist/component/usageObservations/queries.d.ts.map +1 -1
  172. package/dist/component/usageObservations/queries.js +4 -2
  173. package/dist/component/usageObservations/queries.js.map +1 -1
  174. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -1
  175. package/dist/component/usageSubscriptions/retirement.js +24 -2
  176. package/dist/component/usageSubscriptions/retirement.js.map +1 -1
  177. package/docs/README.md +4 -0
  178. package/docs/usage-corrections.md +249 -0
  179. package/docs/usage-limits.md +217 -0
  180. package/package.json +3 -1
  181. package/src/client/usage/allowanceClient.test.ts +93 -0
  182. package/src/client/usage/allowanceClient.ts +134 -0
  183. package/src/client/usage/allowanceTerms.test.ts +131 -0
  184. package/src/client/usage/allowanceTerms.ts +172 -0
  185. package/src/client/usage/client.ts +2 -2
  186. package/src/client/usage/correctionClient.test.ts +153 -0
  187. package/src/client/usage/correctionClient.ts +62 -0
  188. package/src/client/usage/correctionCredits.test.ts +156 -0
  189. package/src/client/usage/correctionEligibility.ts +14 -0
  190. package/src/client/usage/correctionInvoice.test.ts +127 -0
  191. package/src/client/usage/correctionInvoice.ts +269 -0
  192. package/src/client/usage/correctionInvoiceProof.ts +40 -0
  193. package/src/client/usage/correctionProofs.ts +40 -0
  194. package/src/client/usage/correctionProvider.ts +326 -0
  195. package/src/client/usage/correctionRead.ts +73 -0
  196. package/src/client/usage/correctionRecovery.test.ts +113 -0
  197. package/src/client/usage/correctionTerms.ts +98 -0
  198. package/src/client/usage/correctionTransport.fixtures.ts +372 -0
  199. package/src/client/usage/index.ts +19 -0
  200. package/src/client/usage/observationClient.ts +20 -6
  201. package/src/client/usage/records.ts +7 -1
  202. package/src/client/usage/summary.ts +12 -4
  203. package/src/client/usageExports.ts +19 -0
  204. package/src/component/_generated/api.ts +20 -0
  205. package/src/component/_generated/component.ts +423 -1
  206. package/src/component/accountClosure/mutations.ts +17 -0
  207. package/src/component/schema.ts +14 -0
  208. package/src/component/usage/allowance.test.ts +435 -0
  209. package/src/component/usage/mutations.ts +13 -0
  210. package/src/component/usage/schema.ts +6 -1
  211. package/src/component/usageAllowance/helpers.ts +137 -0
  212. package/src/component/usageAllowance/mutations.ts +139 -0
  213. package/src/component/usageAllowance/queries.ts +140 -0
  214. package/src/component/usageAllowance/reservations.ts +220 -0
  215. package/src/component/usageAllowance/schema.ts +37 -0
  216. package/src/component/usageCorrections/accounting.ts +79 -0
  217. package/src/component/usageCorrections/cancellation.ts +32 -0
  218. package/src/component/usageCorrections/corrections.test.ts +389 -0
  219. package/src/component/usageCorrections/helpers.ts +57 -0
  220. package/src/component/usageCorrections/invoice.ts +103 -0
  221. package/src/component/usageCorrections/mutations.ts +278 -0
  222. package/src/component/usageCorrections/queries.ts +94 -0
  223. package/src/component/usageCorrections/schema.ts +90 -0
  224. package/src/component/usageCredits/queries.ts +4 -0
  225. package/src/component/usageCredits/schema.ts +1 -0
  226. package/src/component/usageDelivery/fields.ts +1 -0
  227. package/src/component/usageDelivery/mutations.ts +8 -3
  228. package/src/component/usageDelivery/steps.ts +1 -1
  229. package/src/component/usageObservations/queries.ts +5 -2
  230. package/src/component/usageSubscriptions/retirement.ts +31 -2
@@ -0,0 +1,134 @@
1
+ import { z } from "zod";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { UsageCreditClient } from "./creditClient.js";
6
+ import { prepareUsageRecord, scopeSchema, type UsageScope } from "./records.js";
7
+ import {
8
+ allowanceBinding,
9
+ limitPolicy,
10
+ type UsageAllowanceBinding,
11
+ type UsageAllowanceStatus,
12
+ type UsageAllowanceReconciliation,
13
+ type UsageLimitPolicy,
14
+ } from "./allowanceTerms.js";
15
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
16
+ import type { Doc, Id } from "../../component/_generated/dataModel.js";
17
+ export type UsageAllowanceReservation =
18
+ | { state: "denied"; reason: "not_entitled" | "hard_limit"; revision: number }
19
+ | {
20
+ state: "reserved" | "committed" | "released";
21
+ reservationId: Id<"usageReservations">;
22
+ revision: number;
23
+ };
24
+ const bindingJson = (input: UsageAllowanceBinding) =>
25
+ JSON.stringify(
26
+ allowanceBinding({
27
+ scope: input.scope,
28
+ binding: input.binding,
29
+ subscription: input.subscription,
30
+ }),
31
+ );
32
+ /** Trusted host authorizes policy management and the exact billable activity. */
33
+ export class UsageAllowanceClient extends UsageCreditClient {
34
+ configureAllowance(
35
+ ctx: RunCtx,
36
+ input: UsageAllowanceBinding & {
37
+ policy: UsageLimitPolicy;
38
+ expectedRevision: number;
39
+ },
40
+ ): Promise<{ revision: number }> {
41
+ const binding = allowanceBinding({
42
+ scope: input.scope,
43
+ binding: input.binding,
44
+ subscription: input.subscription,
45
+ });
46
+ return runMutationOrThrow(
47
+ ctx,
48
+ componentRef(this.component, "usageAllowance/mutations/configure"),
49
+ {
50
+ bindingJson: JSON.stringify(binding),
51
+ policyJson: JSON.stringify(limitPolicy(input.policy, binding)),
52
+ expectedRevision: input.expectedRevision,
53
+ },
54
+ );
55
+ }
56
+ async getAllowanceStatus(
57
+ ctx: RunCtx,
58
+ input: UsageAllowanceBinding,
59
+ ): Promise<UsageAllowanceStatus | null> {
60
+ const result = (await ctx.runQuery(
61
+ componentRef(this.component, "usageAllowance/queries/status"),
62
+ { bindingJson: bindingJson(input) },
63
+ )) as string | null;
64
+ return result === null
65
+ ? null
66
+ : (JSON.parse(result) as UsageAllowanceStatus);
67
+ }
68
+ reconcileAllowance(
69
+ ctx: RunCtx,
70
+ input: UsageAllowanceBinding,
71
+ ): Promise<UsageAllowanceReconciliation> {
72
+ return ctx.runQuery(
73
+ componentRef(this.component, "usageAllowance/queries/reconciliation"),
74
+ { bindingJson: bindingJson(input) },
75
+ );
76
+ }
77
+ reserveAllowance(
78
+ ctx: RunCtx,
79
+ input: { event: unknown; subscription: UsageSubscriptionBinding },
80
+ ): Promise<UsageAllowanceReservation> {
81
+ const event = prepareUsageRecord(input.event);
82
+ return runMutationOrThrow(
83
+ ctx,
84
+ componentRef(this.component, "usageAllowance/mutations/reserve"),
85
+ {
86
+ inputJson: JSON.stringify({
87
+ scope: event.scope,
88
+ binding: event.binding,
89
+ sourceEventId: event.sourceEventId,
90
+ occurredAt: event.occurredAt,
91
+ quantity: event.quantity,
92
+ }),
93
+ subscriptionJson: JSON.stringify(input.subscription),
94
+ },
95
+ );
96
+ }
97
+ releaseAllowance(
98
+ ctx: RunCtx,
99
+ input: {
100
+ scope: UsageScope;
101
+ reservationId: Id<"usageReservations">;
102
+ reason: "work_failed" | "abandoned_before_work";
103
+ },
104
+ ) {
105
+ return runMutationOrThrow(
106
+ ctx,
107
+ componentRef(this.component, "usageAllowance/mutations/release"),
108
+ { ...input, scope: scopeSchema.parse(input.scope) },
109
+ );
110
+ }
111
+ async readAllowanceHistory(
112
+ ctx: RunCtx,
113
+ input: UsageAllowanceBinding & { limit: number; cursor: string | null },
114
+ ) {
115
+ const limit = z.number().int().min(1).max(100).parse(input.limit),
116
+ cursor = z.string().min(1).max(2048).nullable().parse(input.cursor);
117
+ const result = (await ctx.runQuery(
118
+ componentRef(this.component, "usageAllowance/queries/readHistory"),
119
+ {
120
+ bindingJson: bindingJson(input),
121
+ paginationOpts: { numItems: limit, cursor },
122
+ },
123
+ )) as {
124
+ page: Doc<"usageAllowanceHistory">[];
125
+ continueCursor: string;
126
+ isDone: boolean;
127
+ };
128
+ return {
129
+ records: result.page,
130
+ cursor: result.isDone ? null : result.continueCursor,
131
+ isDone: result.isDone,
132
+ };
133
+ }
134
+ }
@@ -0,0 +1,131 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ allowanceBinding,
4
+ allowanceStatus,
5
+ limitPolicy,
6
+ } from "./allowanceTerms.js";
7
+ import { request } from "./subscription.fixtures.js";
8
+ const original = {
9
+ ...request.meters[0],
10
+ subscription: {
11
+ subscriptionId: "sub_calls",
12
+ subscriptionItemId: "si_calls",
13
+ stripePriceId: "price_calls",
14
+ period: { start: 600, end: 1200 },
15
+ interval: "month",
16
+ },
17
+ };
18
+ it("calculates fractional units and decimal minor-currency estimates without rounding", () => {
19
+ const binding = allowanceBinding({
20
+ ...original,
21
+ binding: {
22
+ ...original.binding,
23
+ plan: {
24
+ ...original.binding.plan,
25
+ unit: { name: "call", precision: 2 },
26
+ includedQuantity: "1.25",
27
+ rate: { currency: "usd", unitAmountDecimal: "0.025" },
28
+ },
29
+ },
30
+ });
31
+ const policy = limitPolicy(
32
+ {
33
+ reset: "billing_period",
34
+ rollover: "none",
35
+ entitled: true,
36
+ overage: "allow",
37
+ limit: { mode: "soft", quantity: "1.30" },
38
+ },
39
+ binding,
40
+ );
41
+ expect(
42
+ allowanceStatus(
43
+ binding,
44
+ policy,
45
+ { consumed: "130", reserved: "1", revision: 1 },
46
+ 700,
47
+ ),
48
+ ).toMatchObject({
49
+ consumedQuantity: "1.3",
50
+ reservedQuantity: "0.01",
51
+ billableOverageQuantity: "0.05",
52
+ softLimitReached: true,
53
+ committedEstimate: { amountDecimal: "0.00125", currency: "usd" },
54
+ projectedEstimate: { amountDecimal: "0.0015", currency: "usd" },
55
+ });
56
+ });
57
+ it("rejects unsupported rollover/reset, invalid precision and prepaid instead of minting allowance credit", () => {
58
+ const binding = allowanceBinding(original),
59
+ policy = {
60
+ reset: "billing_period",
61
+ rollover: "none",
62
+ entitled: true,
63
+ overage: "allow",
64
+ limit: { mode: "none" },
65
+ };
66
+ for (const changed of [
67
+ { ...policy, reset: "calendar_month" },
68
+ { ...policy, rollover: "carry" },
69
+ { ...policy, limit: { mode: "hard", quantity: "0.1" } },
70
+ { ...policy, limit: { mode: "hard", quantity: "1000000000000000000" } },
71
+ ])
72
+ expect(() => limitPolicy(changed, binding)).toThrow();
73
+ expect(() =>
74
+ allowanceBinding({
75
+ ...original,
76
+ binding: {
77
+ ...original.binding,
78
+ plan: {
79
+ key: "calls",
80
+ version: "v1",
81
+ model: "prepaid",
82
+ unit: { name: "call", precision: 0 },
83
+ rate: { currency: "usd", unitAmountDecimal: "2" },
84
+ insufficientBalance: "reject",
85
+ },
86
+ },
87
+ }),
88
+ ).toThrow(/payment-backed/i);
89
+ });
90
+ it("supports optional pay-as-you-go hard caps without inventing included units", () => {
91
+ const binding = allowanceBinding({
92
+ ...original,
93
+ binding: {
94
+ ...original.binding,
95
+ plan: {
96
+ key: "calls",
97
+ version: "v1",
98
+ model: "pay_as_you_go",
99
+ unit: { name: "call", precision: 0 },
100
+ rate: { currency: "usd", unitAmountDecimal: "2" },
101
+ },
102
+ },
103
+ });
104
+ const policy = limitPolicy(
105
+ {
106
+ reset: "billing_period",
107
+ rollover: "none",
108
+ entitled: true,
109
+ overage: "allow",
110
+ limit: { mode: "hard", quantity: "12" },
111
+ },
112
+ binding,
113
+ );
114
+ expect(
115
+ allowanceStatus(
116
+ binding,
117
+ policy,
118
+ { consumed: "6", reserved: "6", revision: 1 },
119
+ 700,
120
+ ),
121
+ ).toMatchObject({
122
+ includedQuantity: "0",
123
+ hardLimitRemainingQuantity: "0",
124
+ accepting: false,
125
+ committedEstimate: { amountDecimal: "12", currency: "usd" },
126
+ projectedEstimate: { amountDecimal: "24", currency: "usd" },
127
+ });
128
+ expect(() => limitPolicy({ ...policy, overage: "reject" }, binding)).toThrow(
129
+ /explicit usage cap/i,
130
+ );
131
+ });
@@ -0,0 +1,172 @@
1
+ import { z } from "zod";
2
+ import { prepareUsageRecord, type PreparedUsageRecord } from "./records.js";
3
+ import { parseUsageQuantity } from "./contracts.js";
4
+ import { decimalFromScaled } from "./summary.js";
5
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
6
+ export type UsageAllowanceBinding = Pick<
7
+ PreparedUsageRecord,
8
+ "scope" | "binding"
9
+ > & {
10
+ subscription: UsageSubscriptionBinding;
11
+ };
12
+ const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
13
+ const subscriptionSchema = z.strictObject({
14
+ subscriptionId: z.string().regex(/^sub_[a-zA-Z0-9]+$/),
15
+ subscriptionItemId: z.string().regex(/^si_[a-zA-Z0-9]+$/),
16
+ stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/),
17
+ period: z.strictObject({ start: seconds, end: seconds }),
18
+ interval: z.literal("month"),
19
+ });
20
+ export const usageLimitPolicySchema = z.strictObject({
21
+ reset: z.literal("billing_period"),
22
+ rollover: z.literal("none"),
23
+ entitled: z.boolean(),
24
+ overage: z.enum(["allow", "reject"]),
25
+ limit: z.discriminatedUnion("mode", [
26
+ z.strictObject({ mode: z.literal("none") }),
27
+ z.strictObject({ mode: z.enum(["soft", "hard"]), quantity: z.string() }),
28
+ ]),
29
+ });
30
+ export type UsageLimitPolicy = z.infer<typeof usageLimitPolicySchema>;
31
+ export type UsageAllowanceStatus = {
32
+ revision: number;
33
+ observedAt: number;
34
+ period: UsageSubscriptionBinding["period"];
35
+ accepting: boolean;
36
+ policy: UsageLimitPolicy;
37
+ consumedQuantity: string;
38
+ reservedQuantity: string;
39
+ includedQuantity: string;
40
+ remainingIncludedQuantity: string;
41
+ billableOverageQuantity: string;
42
+ softLimitReached: boolean;
43
+ hardLimitRemainingQuantity: string | null;
44
+ committedEstimate: { amountDecimal: string; currency: string };
45
+ projectedEstimate: { amountDecimal: string; currency: string };
46
+ cashCollection: "none";
47
+ };
48
+ export function allowanceBinding(input: unknown): UsageAllowanceBinding {
49
+ const raw = z
50
+ .strictObject({
51
+ scope: z.unknown(),
52
+ binding: z.unknown(),
53
+ subscription: subscriptionSchema,
54
+ })
55
+ .parse(input);
56
+ const event = prepareUsageRecord({
57
+ scope: raw.scope,
58
+ binding: raw.binding,
59
+ sourceEventId: "validation",
60
+ quantity: "0",
61
+ occurredAt: 0,
62
+ });
63
+ if (event.binding.plan.model === "prepaid")
64
+ throw new Error("Use payment-backed prepaid credit accounting");
65
+ if (
66
+ raw.subscription.period.end <= raw.subscription.period.start ||
67
+ raw.subscription.stripePriceId !== event.binding.stripePriceId
68
+ )
69
+ throw new Error("Allowance subscription period/price mismatch");
70
+ return {
71
+ scope: event.scope,
72
+ binding: event.binding,
73
+ subscription: raw.subscription,
74
+ };
75
+ }
76
+ export function limitPolicy(
77
+ input: unknown,
78
+ binding: UsageAllowanceBinding,
79
+ ): UsageLimitPolicy {
80
+ const policy = usageLimitPolicySchema.parse(input),
81
+ precision = binding.binding.plan.unit.precision;
82
+ if (policy.limit.mode !== "none")
83
+ policy.limit.quantity = parseUsageQuantity(
84
+ policy.limit.quantity,
85
+ precision,
86
+ ).quantity;
87
+ if (
88
+ binding.binding.plan.model === "pay_as_you_go" &&
89
+ policy.overage === "reject"
90
+ )
91
+ throw new Error(
92
+ "Pay-as-you-go requires an explicit usage cap instead of an included allowance",
93
+ );
94
+ return policy;
95
+ }
96
+ export function allowanceStatus(
97
+ binding: UsageAllowanceBinding,
98
+ policy: UsageLimitPolicy,
99
+ row: { consumed: string; reserved: string; revision: number },
100
+ observedAt: number,
101
+ ): UsageAllowanceStatus {
102
+ const plan = binding.binding.plan,
103
+ precision = plan.unit.precision;
104
+ const consumed = BigInt(row.consumed),
105
+ reserved = BigInt(row.reserved),
106
+ total = consumed + reserved;
107
+ const included =
108
+ plan.model === "included_overage"
109
+ ? BigInt(
110
+ parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
111
+ )
112
+ : 0n;
113
+ const overage = (quantity: bigint) =>
114
+ quantity > included ? quantity - included : 0n;
115
+ const quantity = (value: bigint) => decimalFromScaled(value, precision);
116
+ const cost = (value: bigint) => {
117
+ const [whole, fraction = ""] = plan.rate.unitAmountDecimal.split(".");
118
+ return {
119
+ amountDecimal: decimalFromScaled(
120
+ overage(value) * BigInt(whole + fraction),
121
+ precision + fraction.length,
122
+ ),
123
+ currency: plan.rate.currency,
124
+ };
125
+ };
126
+ let hard: bigint | null =
127
+ policy.limit.mode === "hard"
128
+ ? BigInt(
129
+ parseUsageQuantity(policy.limit.quantity, precision).scaledQuantity,
130
+ )
131
+ : null;
132
+ if (policy.overage === "reject")
133
+ hard = hard === null || included < hard ? included : hard;
134
+ return {
135
+ revision: row.revision,
136
+ observedAt,
137
+ period: binding.subscription.period,
138
+ accepting:
139
+ policy.entitled &&
140
+ observedAt >= binding.subscription.period.start &&
141
+ observedAt < binding.subscription.period.end - 60 &&
142
+ (hard === null || total < hard),
143
+ policy,
144
+ consumedQuantity: quantity(consumed),
145
+ reservedQuantity: quantity(reserved),
146
+ includedQuantity: quantity(included),
147
+ remainingIncludedQuantity: quantity(
148
+ included > total ? included - total : 0n,
149
+ ),
150
+ billableOverageQuantity: quantity(overage(consumed)),
151
+ softLimitReached:
152
+ policy.limit.mode === "soft" &&
153
+ total >=
154
+ BigInt(
155
+ parseUsageQuantity(policy.limit.quantity, precision).scaledQuantity,
156
+ ),
157
+ hardLimitRemainingQuantity:
158
+ hard === null ? null : quantity(hard > total ? hard - total : 0n),
159
+ committedEstimate: cost(consumed),
160
+ projectedEstimate: cost(total),
161
+ cashCollection: "none",
162
+ };
163
+ }
164
+
165
+ export type UsageAllowanceReconciliation = {
166
+ status: "matched" | "held";
167
+ reason: string;
168
+ consumedScaledQuantity: string;
169
+ reservedScaledQuantity: string;
170
+ acceptedScaledQuantity: string;
171
+ repaired: false;
172
+ };
@@ -1,4 +1,4 @@
1
- import { UsageCreditClient } from "./creditClient.js";
1
+ import { UsageCorrectionClient } from "./correctionClient.js";
2
2
  import type { Component, RunCtx } from "../helpers.js";
3
3
  import { runMutationOrThrow } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
@@ -46,7 +46,7 @@ function decode({ event, delivery }: StoredView): UsageEventView {
46
46
  };
47
47
  }
48
48
  /** Trusted host facade. Authenticate and authorize each exact scope first. */
49
- export class UsageLedgerClient extends UsageCreditClient {
49
+ export class UsageLedgerClient extends UsageCorrectionClient {
50
50
  constructor(component: Component) {
51
51
  super(component);
52
52
  }
@@ -0,0 +1,153 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { setupCorrection } from "./correctionTransport.fixtures.js";
4
+ afterEach(() => vi.useRealTimers());
5
+ it("uses the original native identifier and stable operation key without claiming pending cancellation complete", async () => {
6
+ const { f, client, options, correction, receipt, calls } =
7
+ await setupCorrection();
8
+ const result = await f.t.action((ctx) =>
9
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
10
+ );
11
+ expect(result).toMatchObject({
12
+ state: "provider_accepted",
13
+ nativeStatus: "pending",
14
+ nativeAdjustmentId: null,
15
+ restoredQuantity: "0",
16
+ cashConsequence: "none",
17
+ });
18
+ expect(
19
+ await f.t.action((ctx) =>
20
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
21
+ ),
22
+ ).toEqual(result);
23
+ expect(calls).toHaveLength(1);
24
+ expect(calls[0].body.get("cancel[identifier]")).toBe(
25
+ `bs_usage_${receipt.eventId}`,
26
+ );
27
+ expect(calls[0].key).toMatch(/^bs_usage_correction_/);
28
+ });
29
+
30
+ it("retains units if an invoice finalizes while the native cancellation is processing", async () => {
31
+ const { f, client, options, correction, state } = await setupCorrection();
32
+ state.status = "complete";
33
+ state.finalizeOnAdjust = true;
34
+ expect(
35
+ await f.t.action((ctx) =>
36
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
37
+ ),
38
+ ).toMatchObject({
39
+ state: "invoice_adjustment_required",
40
+ nativeStatus: "complete",
41
+ invoiceId: "in_usage",
42
+ restoredQuantity: "0",
43
+ cashConsequence: "operator_resolution_required",
44
+ });
45
+ });
46
+
47
+ it("exposes bounded correction evidence beside original usage and preserves unknown legacy coverage", async () => {
48
+ const { f, client, options, correction, original } = await setupCorrection();
49
+ const before = await f.t.query((ctx) =>
50
+ client.usage.readCorrectionHistory(ctx as RunCtx, {
51
+ scope: correction.scope,
52
+ eventId: correction.eventId,
53
+ limit: 1,
54
+ cursor: null,
55
+ }),
56
+ );
57
+ expect(before).toMatchObject({ records: [], coverage: "not_recorded" });
58
+ await f.t.action((ctx) =>
59
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
60
+ );
61
+ const page = await f.t.query((ctx) =>
62
+ client.usage.readCorrectionHistory(ctx as RunCtx, {
63
+ scope: correction.scope,
64
+ eventId: correction.eventId,
65
+ limit: 1,
66
+ cursor: null,
67
+ }),
68
+ );
69
+ expect(page.records).toHaveLength(1);
70
+ expect(page.isDone).toBe(false);
71
+ expect(page.coverage).toBe("recorded");
72
+ const status = await f.t.query((ctx) =>
73
+ client.usage.getReconciliation(ctx as RunCtx, {
74
+ scope: original.scope,
75
+ binding: original.binding,
76
+ subscription: original.subscription,
77
+ period: original.subscription.period,
78
+ }),
79
+ );
80
+ expect(status.correctionHistory).toMatchObject({
81
+ status: "available",
82
+ value: { coverage: "recorded" },
83
+ });
84
+ });
85
+
86
+ it("adopts a verified partial native invoice credit without erasing valid usage or issuing another refund", async () => {
87
+ const { f, client, options, correction } = await setupCorrection();
88
+ const partial = { ...correction, quantity: "2" };
89
+ expect(
90
+ await f.t.action((ctx) =>
91
+ client.usage.requestCorrection(ctx as RunCtx, partial, options),
92
+ ),
93
+ ).toMatchObject({ state: "unsupported", restoredQuantity: "0" });
94
+ const input = {
95
+ scope: correction.scope,
96
+ eventId: correction.eventId,
97
+ correctionId: correction.correctionId,
98
+ invoiceId: "in_usage",
99
+ creditNoteId: "cn_fix",
100
+ amount: 4,
101
+ };
102
+ const adopted = await f.t.action((ctx) =>
103
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
104
+ );
105
+ expect(adopted).toMatchObject({
106
+ state: "confirmed",
107
+ resolution: "invoice_credit",
108
+ creditNoteId: "cn_fix",
109
+ restoredQuantity: "0",
110
+ cashConsequence: "verified_external_adjustment",
111
+ });
112
+ expect(
113
+ await f.t.action((ctx) =>
114
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
115
+ ),
116
+ ).toEqual(adopted);
117
+ expect(
118
+ (
119
+ await f.t.query((ctx) =>
120
+ client.usage.getDelivery(ctx as RunCtx, {
121
+ scope: correction.scope,
122
+ eventId: correction.eventId,
123
+ }),
124
+ )
125
+ ).state,
126
+ ).toBe("provider_accepted");
127
+ });
128
+
129
+ it("restores included units once after complete native cancellation and reconciles the retained original ledger", async () => {
130
+ const { f, client, options, correction, original, state } =
131
+ await setupCorrection(true);
132
+ state.status = "complete";
133
+ expect(
134
+ await f.t.action((ctx) =>
135
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
136
+ ),
137
+ ).toMatchObject({ state: "confirmed", restoredQuantity: "6" });
138
+ expect(
139
+ await f.t.action((ctx) =>
140
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
141
+ ),
142
+ ).toMatchObject({ restoredQuantity: "6" });
143
+ expect(
144
+ await f.t.query((ctx) =>
145
+ client.usage.getAllowanceStatus(ctx as RunCtx, original),
146
+ ),
147
+ ).toMatchObject({ consumedQuantity: "0", remainingIncludedQuantity: "10" });
148
+ expect(
149
+ await f.t.query((ctx) =>
150
+ client.usage.reconcileAllowance(ctx as RunCtx, original),
151
+ ),
152
+ ).toMatchObject({ status: "matched", acceptedScaledQuantity: "0" });
153
+ });
@@ -0,0 +1,62 @@
1
+ import { observeInvoiceCorrection } from "./correctionInvoice.js";
2
+ import type { UsageInvoiceCorrectionOptions } from "./correctionTerms.js";
3
+ import { readCorrectionEvidence } from "./correctionRead.js";
4
+ import { scopeSchema, type UsageScope } from "./records.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import { correctionView } from "./correctionTerms.js";
8
+ import type { UsagePeriod } from "./boundaries.js";
9
+ import { UsageAllowanceClient } from "./allowanceClient.js";
10
+ import type { RunCtx } from "../helpers.js";
11
+ import { requestUsageCorrection } from "./correctionProvider.js";
12
+ import type { UsageCorrectionOptions } from "./correctionTerms.js";
13
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
14
+ /** Host authenticates and authorizes the actor and original activity before calling. */
15
+ export class UsageCorrectionClient extends UsageAllowanceClient {
16
+ async getCorrection(
17
+ ctx: RunCtx,
18
+ input: { scope: UsageScope; eventId: string; correctionId: string },
19
+ ) {
20
+ const row = (await ctx.runQuery(
21
+ componentRef(this.component, "usageCorrections/queries/get"),
22
+ { ...input, scope: scopeSchema.parse(input.scope) },
23
+ )) as Doc<"usageCorrections"> | null;
24
+ return row ? correctionView(row) : null;
25
+ }
26
+ readCorrectionHistory(
27
+ ctx: RunCtx,
28
+ input: {
29
+ scope: UsageScope;
30
+ eventId: string;
31
+ limit: number;
32
+ cursor: string | null;
33
+ },
34
+ ) {
35
+ return readCorrectionEvidence(this.component, ctx, input);
36
+ }
37
+ readCorrectionPeriodHistory(
38
+ ctx: RunCtx,
39
+ input: {
40
+ scope: UsageScope;
41
+ period: UsagePeriod;
42
+ limit: number;
43
+ cursor: string | null;
44
+ },
45
+ ) {
46
+ return readCorrectionEvidence(this.component, ctx, input);
47
+ }
48
+ observeInvoiceCorrection(
49
+ ctx: RunCtx,
50
+ input: UsageInvoiceCorrectionOptions,
51
+ options: UsageDeliveryProviderOptions,
52
+ ) {
53
+ return observeInvoiceCorrection(this.component, ctx, input, options);
54
+ }
55
+ requestCorrection(
56
+ ctx: RunCtx,
57
+ input: UsageCorrectionOptions,
58
+ options: UsageDeliveryProviderOptions = {},
59
+ ) {
60
+ return requestUsageCorrection(this.component, ctx, input, options);
61
+ }
62
+ }