@pithy-sh/payments 0.4.0 → 0.6.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 (180) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +2 -1
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
@@ -0,0 +1,249 @@
1
+ # Tiers, allowances and reported usage
2
+
3
+ _This copy ships in the package because `packages/payments/src/workflows/usage.ts` sends an adopter to it by name for the Workflow stanza._
4
+
5
+ What a key buys, how much one customer may have, what the kit counts for you, and how to bill by a count your code owns. Four parts, each standing on the one before it.
6
+
7
+ ## Part one — declare each entitlement once
8
+
9
+ A key is declared in the top-level `entitlements` map: its display name, its numbered `quotas`, its `features`. A product goes on mentioning the keys it grants, as an array of strings. The declaration is top-level because a tier is sold by more than one product — `growth_monthly` and `growth_annual` are two SKUs for one tier, and the numbers belong to the tier.
10
+
11
+ ```ts
12
+ payments({
13
+ billingSubject: "organization",
14
+ resolveSubject,
15
+
16
+ entitlements: {
17
+ start: {
18
+ name: "Start",
19
+ quotas: { emails: 500, projects: 3, seats: 2 },
20
+ features: { sso: false, auditExport: false },
21
+ },
22
+ growth: {
23
+ name: "Growth",
24
+ quotas: { emails: 5000, projects: 10, seats: 10 },
25
+ features: { sso: true, auditExport: false },
26
+ overrideMax: { emails: 100_000 },
27
+ },
28
+ scale: {
29
+ name: "Scale",
30
+ quotas: { emails: null, projects: null, seats: 50 },
31
+ features: { sso: true, auditExport: true },
32
+ },
33
+ // Declared and sold by nothing: comp-only.
34
+ enterprise: {
35
+ name: "Enterprise",
36
+ quotas: { emails: null, projects: null, seats: null },
37
+ features: { sso: true, auditExport: true },
38
+ },
39
+ },
40
+
41
+ // What a caller holding no key gets.
42
+ defaults: {
43
+ quotas: { emails: 50, projects: 1, seats: 1 },
44
+ features: { sso: false, auditExport: false },
45
+ },
46
+
47
+ rails: { stripe: true },
48
+ stripe: { successUrl, cancelUrl, portalReturnUrl },
49
+ products: {
50
+ start_monthly: { type: "subscription", name: "Start", entitlements: ["start"], stripe: { priceId: START } },
51
+ growth_monthly: { type: "subscription", name: "Growth", entitlements: ["growth"], stripe: { priceId: GROWTH } },
52
+ growth_annual: { type: "subscription", name: "Growth, yearly", entitlements: ["growth"], stripe: { priceId: GROWTH_YEAR } },
53
+ scale_monthly: { type: "subscription", name: "Scale", entitlements: ["scale"], stripe: { priceId: SCALE } },
54
+ },
55
+ });
56
+ ```
57
+
58
+ **`quotas` holds whole numbers and `null`; `features` holds booleans.** `null` is unlimited, and it is written, never inferred. A quota that is a float, a negative or a string is refused at parse, naming the key and the name.
59
+
60
+ **A key a product mentions must be declared.** A mention with no declaration is refused at parse, naming the product and the key. The reverse is legal and means comp-only: `enterprise` above is grantable by hand and sold by no checkout. `manualEntitlements` is gone, and a config still passing it is refused with the declaration to write instead.
61
+
62
+ **`overrideMax` is optional, per quota.** It bounds what an operator may pin for a subject on that tier (part two). It must name a quota the key declares and must not sit below that quota's own value — a ceiling under the plan would refuse what the plan already grants.
63
+
64
+ ### Reading an allowance
65
+
66
+ ```ts
67
+ import { feature, quota } from "@pithy-sh/core/src/entitlement/allowance";
68
+
69
+ app.post("/projects", requireAuth(), validate("json", NewProject), async (c) => {
70
+ const projects = await quota(c, "projects"); // a whole number, or null for unlimited
71
+ if (projects !== null && (await countProjects(orgOf(c))) >= projects) throw new ProjectLimitReached();
72
+ if (await feature(c, "auditExport")) enableExport();
73
+ // …
74
+ });
75
+ ```
76
+
77
+ **Neither reader takes a key.** A route does not know which tier the caller is on, and during an upgrade overlap the caller holds two. `quota(c, name)` resolves across every key the subject holds:
78
+
79
+ 1. The subject's **override**, if it pins this name.
80
+ 2. **`unrestricted`**, if the override carries it: unlimited, and on.
81
+ 3. The **highest** value among every key the subject holds now — `null` beats every number, and a feature is on if any held key turns it on.
82
+ 4. **`defaults`**, for a name no held key speaks to.
83
+ 5. **`0` and `false`.** Never unlimited.
84
+
85
+ **A name nothing declares throws `core/internal`**, naming the name and listing the declared ones. `quota(c, "emals")` is a hard failure, never a zero and never unlimited.
86
+
87
+ **`requireEntitlement` still gates on the key alone.** A quota denies nothing by itself, and a feature set to `false` denies nothing either. What a number means for a request is your route's decision, because only your code can count what it owns. Payments never counts members.
88
+
89
+ **A paywall reads the same numbers.** `virtual:pithy/payments` carries what each tier buys, and `useAllowances()` reads what the caller resolves to. A UX affordance, never a security boundary — `docs/UI.md`.
90
+
91
+ ## Part two — one subject's allowance, overridden from the control plane
92
+
93
+ An override shades one subject's numbers without taking them off their plan. Keyed on the subject, never on a key, so it survives a tier change.
94
+
95
+ ```
96
+ growth plan: emails 5000, projects 10, seats 10, sso true
97
+ override: emails 20000
98
+
99
+ effective: emails 20000 override
100
+ projects 10 plan: growth
101
+ seats 10 plan: growth
102
+
103
+ later, upgraded to scale:
104
+ effective: emails 20000, projects unlimited, seats 50
105
+ ```
106
+
107
+ Three control-plane writes, three scopes:
108
+
109
+ | Route | Scope | What it does |
110
+ | --- | --- | --- |
111
+ | `POST {base}/entitlements/overrides` | `payments:overrides:set` | Pin quotas or features by name. A merge: only the names sent change |
112
+ | `POST {base}/entitlements/overrides/unrestricted` | `payments:overrides:unrestricted` | Every quota unlimited and every feature on, for every name declared now or later — or take it back |
113
+ | `POST {base}/entitlements/overrides/clear` | `payments:overrides:clear` | Unpin names, or clear the whole override. Clearing nothing answers 200. Unpinning on an unrestricted subject is refused |
114
+
115
+ ```json
116
+ {
117
+ "subjectType": "organization",
118
+ "subjectId": "acme",
119
+ "version": 0,
120
+ "reason": "MSA signed 2026-06-01, ticket 4471",
121
+ "quotas": { "emails": 20000 }
122
+ }
123
+ ```
124
+
125
+ - **Version-checked.** Every read carries the subject's `overrideVersion`; a set and an unrestricted write must send it back. A write behind the row is `payments/override_stale` (409), and nothing is written — so two operators setting one customer cannot silently overwrite each other. A clear never resets the version: a pane still holding the version it read before a clear stays stale.
126
+ - **A clear's version is optional.** Sent, it is checked the same way, and a clear behind the row is a 409. Left out, the clear is not checked: it removes whatever is pinned now, including a pin another operator wrote after your read. That is allowed because a clear only moves a subject back toward its plan. Send the version when the pane must not undo a change it has not seen.
127
+ - **A clear only narrows.** On an `unrestricted` subject a pin is all that holds a name below unlimited, so unpinning it is a 400: lifting a name to unlimited is the unrestricted scope's grant. Turn `unrestricted` off first, or clear the whole override, which takes `unrestricted` with it.
128
+ - **A reason is required on a set and an unrestricted write**, and the audit event carries it verbatim beside the subject, the mode, the before and the after. On a clear it is optional: sent, the event carries it; left out, the event's reason is `null`. A clear that removes nothing changes nothing and writes no audit event.
129
+ - **Bounded.** A number past the tier's `overrideMax` is a 400 naming the limit. Never clamped. A quota with no ceiling accepts any whole number.
130
+ - **Declared names only.** A name the declarations do not mention is a 400 naming it and listing what is declared.
131
+ - **It grants no key.** A subject with an override and no entitlement is refused at every gate. A comped key and a pinned number compose.
132
+ - **`unrestricted` is its own route and its own scope.** It is the largest grant the kit has, and the only one whose reach grows by itself as names are declared. It is never bounded by `overrideMax`. It is how an Enterprise contract is honored today, beside a comped `enterprise` key, and how an operator grants their own account the whole product.
133
+
134
+ **The reads.** `GET {base}/admin/entitlements/:subjectType/:subjectId` projects, per declared name, what applies now, where it came from — `unrestricted`, `override`, `plan` with the key, `default`, or `none` — and what it would be with the override removed. That last one is what a pane shows beside a pin and reverts to. `GET {base}/admin/overrides` pages every override, filterable to `unrestricted=true`. Every entitlement row says whether its holder is unrestricted, and `pithy doctor` names every unrestricted subject in every environment.
135
+
136
+ **The catalog read is the editor's input.** `GET {base}/admin/catalog` projects each declared key's name, quotas, features and `overrideMax`, plus the floor — every editable name, and whether it is a number or a switch, from one response. Its `manualEntitlements` field is the comp-only keys — declared, and sold by no product. It is not the config key of that name, which is gone; the field keeps its first name so a client reads an older Worker and a newer one the same way.
137
+
138
+ ## Part three — the kit counts what it owns
139
+
140
+ | Meter | Counted from | Enforced by |
141
+ | --- | --- | --- |
142
+ | `emails` | a per-period counter in `pithy_payments_meter_counters` | `@pithy-sh/email`, at enqueue |
143
+ | `storageBytes` | `pithy_storage_objects` | `@pithy-sh/storage`, as the subject's ceiling in place of `bytesPerOwner` |
144
+ | `mediaItems` | `pithy_media_assets` | `@pithy-sh/media`, at create |
145
+
146
+ ```ts
147
+ payments({
148
+ // …
149
+ meters: { emails: { enforce: true } },
150
+ });
151
+ ```
152
+
153
+ **Every meter is advisory until named here.** Declaring `quotas: { emails: 500 }` makes 500 readable; enforcing the `emails` meter makes it binding. Two steps, because the first is a pricing decision and the second is a production one. An enforced meter with no quota of its name is refused at parse — it would refuse everyone.
154
+
155
+ **A refusal is `payments/quota_exceeded` (402)** — nothing is written — from all three meters. `@pithy-sh/storage` refuses in those words wherever `storageBytes` is enforced, at init and again at completion. Where it is advisory, the ceiling is `bytesPerOwner` and the refusal stays `storage/quota_exceeded` (413), as it always was.
156
+
157
+ **`unrestricted` lifts only what is not pinned.** A meter never refuses an `unrestricted` subject on a name nothing pins. A number pinned beside `unrestricted` wins, as the resolution order above says, and an enforced meter holds the subject to it.
158
+
159
+ **An organization's quota is the organization's.** Under `billingSubject: "organization"`, `storageBytes` sums every member's bytes stored for the organization and `mediaItems` counts every member's records, against one number. Counted per member, a paid quota would grow with every invitation. A write held for a different organization than the one billed, or for none, is refused as `core/internal` — it would sit outside the sum it was checked against, so the payments subject resolver and the organization in force must agree.
160
+
161
+ **An email is counted when you say whose it is.** Pass `subject` on the enqueue for mail a customer's plan pays for; the kit's own mail — a magic link to somebody who has not signed up — names nobody and is never counted.
162
+
163
+ ```ts
164
+ await email.enqueue(c.env, {
165
+ to,
166
+ template: "operationalNotice",
167
+ payload,
168
+ subject: { subjectType: "organization", subjectId: org.id },
169
+ });
170
+ ```
171
+
172
+ **The period** is the subscription's billing period where payments knows one and the calendar month (UTC) where it does not. A new period is a new counter row, so it starts at zero with nothing to reset it. The check and the charge are one statement, so concurrent sends cannot race past the limit.
173
+
174
+ **A counter read that fails refuses, and logs.** Over-counting briefly is recoverable; under-counting is not. The cost is real — a bug of ours becomes a refused send — and enforcement being opt-in is what bounds it. Leave a meter advisory to keep the check in your own route instead.
175
+
176
+ **A meter refuses; it never bills.** Nothing a meter counts is reported to a store. The kit does not sell overage.
177
+
178
+ ## Part four — bill by a count your code owns
179
+
180
+ Payments asks your code how many and tells the store. It never counts your members.
181
+
182
+ ```ts
183
+ payments({
184
+ billingSubject: "organization",
185
+ resolveSubject,
186
+ entitlements: { pro: { name: "Pro", quotas: { seats: null } } },
187
+ rails: { stripe: true },
188
+ stripe: { successUrl, cancelUrl, portalReturnUrl },
189
+ products: {
190
+ academy_seats: {
191
+ type: "subscription",
192
+ name: "Academy",
193
+ entitlements: ["pro"],
194
+ stripe: { priceId: ACADEMY_METERED_PRICE },
195
+ billing: {
196
+ kind: "reported",
197
+ unit: "student",
198
+ cadence: "period-end", // or "daily-peak"
199
+ min: 1,
200
+ max: 500,
201
+ rails: ["stripe"],
202
+ stripe: { meterEventName: "academy_students" },
203
+ },
204
+ },
205
+ },
206
+ resolveQuantity: async (c, subject) => countActiveStudents(c.env, subject.subjectId),
207
+ });
208
+ ```
209
+
210
+ **`resolveQuantity` rides on the options, beside `resolveSubject`, and never in config** — the config crosses a var as JSON and a function does not survive it. A reported product with no resolver is refused at boot, naming the product.
211
+
212
+ **`cadence`, per product.** `period-end` (the default) sends one count per subscription per billing period, in the period's last day. `daily-peak` keeps each day's high-water mark — a lower later answer never lowers it — and in the period's last day sends the highest day once. Both stores add up what they are sent, so a report per day would bill the sum of the days; one report bills the peak. That report goes out at the first run inside the period's last day, and it bills the peak up to then. Sampling goes on until the period ends, so a higher answer later that day is recorded in its day row and never billed. The day rows stay behind as the audit, and a row above the reported count on the last day is that gap. Under-billing a few hours is the right way round.
213
+
214
+ **What is never reported:**
215
+
216
+ - an answer of `undefined` — nothing for that subject that period, logged and counted as skipped. Never `0`.
217
+ - a non-integer, a negative, or a count outside `min` and `max` — skipped and named in the run's tally. Never clamped.
218
+ - a period already reported. One row per `(rail, subscription, period)`, claimed before the store is called, and its id sent as the store's idempotency key.
219
+
220
+ A resolver that throws for one subject does not stop the run. Every run is kept in `pithy_payments_usage_runs` with its tally and the subjects it did not report, at `GET {base}/admin/usage-runs` behind `payments:usage:read`. The subscription reads show the last count reported and when.
221
+
222
+ **The rails.** Stripe gets one Billing Meter event per report — the meter's own aggregation decides what the invoice bills — and its checkout sends a metered line with no quantity, which Stripe requires. Paddle gets a one-time charge of `billing.paddle.priceId` at the reported quantity on the next bill; nothing rewrites the subscription's items. Apple and Google have no seats and are refused at boot. Lemon Squeezy is deferred: its usage records attach to a subscription item the projection does not store.
223
+
224
+ ### The Workflow is yours to export
225
+
226
+ The pass calls your `resolveQuantity`, which lives only in your Worker, so its class is exported from your own entry — five lines — and its body is the kit's:
227
+
228
+ ```ts
229
+ // apps/api/src/index.ts, beside createEntrypoint
230
+ import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
231
+ import { NonRetryableError } from "cloudflare:workflows";
232
+ import { reportPaymentsUsage } from "@pithy-sh/payments/src/workflows/usage";
233
+
234
+ export class PaymentsUsageWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
235
+ override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
236
+ return reportPaymentsUsage(this.env, event, step, NonRetryableError);
237
+ }
238
+ }
239
+ ```
240
+
241
+ ```jsonc
242
+ // apps/api/wrangler.jsonc, in each environment's stanza
243
+ "workflows": [
244
+ { "binding": "PAYMENTS_USAGE", "name": "acme-prod-payments-usage", "class_name": "PaymentsUsageWorkflow" }
245
+ ],
246
+ "triggers": { "crons": ["15 * * * *"] }
247
+ ```
248
+
249
+ Hourly, so a `daily-peak` day is sampled through the day and every period's report, under either cadence, lands in its last day whatever hour it ends at. `createEntrypoint` fires it on the cron, and `c.var.workflows.trigger("payments/usage", {})` runs it on demand.
@@ -22,6 +22,7 @@ payments({
22
22
  lemonSqueezy: {
23
23
  successUrl: `${PUBLIC_ORIGIN}/thanks`,
24
24
  },
25
+ entitlements: { pro: { name: "Pro" } },
25
26
  products: {
26
27
  pro_monthly: {
27
28
  type: "subscription",
package/docs/paddle.md CHANGED
@@ -31,6 +31,7 @@ payments({
31
31
  checkout: "overlay",
32
32
  successUrl: `${PUBLIC_ORIGIN}/thanks`,
33
33
  },
34
+ entitlements: { pro: { name: "Pro" } },
34
35
  products: {
35
36
  pro_monthly: {
36
37
  type: "subscription",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/payments",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "scripts": {
31
31
  "build": "tsdown && tsc -p tsconfig.build.json && bun ../../tooling/build/src/stampDeclarations.ts && bun scripts/buildPaddlePrices.ts",
32
- "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
32
+ "typecheck": "bun check -p tsconfig.json && bun check -p tsconfig.client.json",
33
33
  "test": "vitest run",
34
34
  "test:node": "vitest run --project=node",
35
35
  "test:workers": "vitest run --project=workers",
@@ -42,9 +42,9 @@
42
42
  "@paddle/paddle-js": "^1.6.4"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.10.0",
46
- "@pithy-sh/ledger": "^0.3.0",
47
- "@pithy-sh/secrets": "^0.4.0",
45
+ "@pithy-sh/core": "^0.12.0",
46
+ "@pithy-sh/ledger": "^0.5.0",
47
+ "@pithy-sh/secrets": "^0.6.0",
48
48
  "hono": "^4.13.2",
49
49
  "kysely": "^0.29.0",
50
50
  "react": "^19.0.0",
@@ -35,12 +35,12 @@
35
35
  "whenToEnable": "Four payment rails \u2014 Apple, Google, Stripe, Lemon Squeezy \u2014 resolving to one cross-rail entitlement, in your own Worker and your own D1. Buy Pro on iOS, be entitled on the web, with no hosted data plane holding your purchase history. A product is not an entitlement: `pro_monthly` and `pro_annual`, across four stores' catalogs, grant one key \u2014 `pro` \u2014 and gating code names the key, never a SKU. Every write converges on one idempotent projection keyed on (rail, provider transaction id), so a client submission, a provider webhook, and a reconciliation pass produce the identical row: a dropped client call costs nothing and a replayed webhook changes nothing. The projection is monotonic on the provider's own event time, because providers do not guarantee delivery order and a stale `expired` arriving after the `renewed` that superseded it would silently revoke a paying subscriber. Sandbox purchases are tracked as sandbox and never grant a production entitlement. A cron Workflow re-verifies what the webhooks missed, because webhook-only systems rot silently. Lemon Squeezy is the merchant of record \u2014 it owns the sales tax, the EU VAT registration, the invoicing and the chargebacks, which is what a solo developer reaches for when the alternative is registering for VAT in twenty-seven countries. Add auth \u2014 every route belongs to an authenticated purchaser or a machine proving authenticity, and there are no public routes. Add secrets: the four rails' credentials are read through it, so payments will not compose without it. Ledger fulfillment is opt-in per product; most products never touch a balance.",
36
36
  "scaffold": [
37
37
  "Add a `payments({ rails: {...}, products: {...} })` block to pithy.config.ts. The catalog lives in config, not in D1 \u2014 a product's entitlement mapping is policy, so it belongs in git rather than in a mutable table. A new SKU needs a deploy, which is the correct trade.",
38
- "Give every product a `type` (`consumable`, `non_consumable`, or `subscription`), a display `name`, the `entitlements` it grants, and one block per rail it ships on. Omit a rail to ship without it \u2014 `remove_ads` on mobile only is expressed by omission, not a flag.",
38
+ "Declare every entitlement key once in the top-level `entitlements` map \u2014 its display `name`, its numbered `quotas` and its `features` \u2014 and an optional `defaults` floor for a caller holding none. Then give every product a `type` (`consumable`, `non_consumable`, or `subscription`), a display `name`, the declared keys it grants, and one block per rail it ships on. Omit a rail to ship without it \u2014 `remove_ads` on mobile only is expressed by omission, not a flag. Read an allowance in a route with `quota(c, name)` and `feature(c, name)` from `@pithy-sh/core/src/entitlement/allowance`.",
39
39
  "Bind a D1 database named DB in wrangler.jsonc \u2014 the same app database your other capabilities use.",
40
- "Run `pithy migrate` to create pithy_payments_purchases, pithy_payments_entitlements, pithy_payments_provider_accounts, pithy_payments_webhook_events, and pithy_payments_reconcile_runs.",
40
+ "Run `pithy migrate` to create pithy_payments_purchases, pithy_payments_entitlements, pithy_payments_provider_accounts, pithy_payments_webhook_events, pithy_payments_reconcile_runs, pithy_payments_sync_cursors, pithy_payments_overrides, pithy_payments_meter_counters, pithy_payments_usage_reports and pithy_payments_usage_runs.",
41
41
  "Add `@pithy-sh/secrets` if it is not already installed, then supply each rail's credentials through it: Apple's App Store Connect key with its key and issuer ids, Google's service account, Stripe's secret key and webhook signing secret. Apple's root certificates are public and ship with the package.",
42
42
  "Add `@pithy-sh/auth` if it is not already installed. Purchases belong to an authenticated user; with no auth capability composed every route denies.",
43
- "Comping and revoking entitlements by hand is a `control-plane` surface, not an admin user, so /payments/entitlements/grant and /payments/entitlements/revoke are reached with a signed management credential rather than a session. A grant must name an entitlement key this project defines \u2014 one a product grants, or one declared in `manualEntitlements` \u2014 so a console cannot comp `pr` for `pro` and leave a customer locked out; `payments:catalog:read` is the separately-granted read that lets a console offer a list instead of a text box, and it discloses only each product's id, kind, name and keys. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection `payments:catalog:read`, `payments:entitlements:grant`, `payments:entitlements:revoke`, or only the one its tooling needs \u2014 a refund tool that cannot comp cannot be turned into one, and a comp tool cannot take paid access away from a live customer. With the seam not composed both routes answer `controlplane/not_connected`, and no app session opens either of them whatever scopes it carries.",
43
+ "Comping and revoking entitlements by hand is a `control-plane` surface, not an admin user, so /payments/entitlements/grant and /payments/entitlements/revoke are reached with a signed management credential rather than a session. A grant must name an entitlement key the `entitlements` map declares \u2014 a declared key no product sells is comp-only \u2014 so a console cannot comp `pr` for `pro` and leave a customer locked out; `payments:catalog:read` is the separately-granted read that lets a console offer a list instead of a text box, and it discloses each product's id, kind, name and keys, and what each declared key buys. Per-subject overrides \u2014 a negotiated number, or `unrestricted` for the whole product \u2014 are three more control-plane writes, each behind its own scope: `payments:overrides:set`, `payments:overrides:unrestricted`, `payments:overrides:clear`. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection `payments:catalog:read`, `payments:entitlements:grant`, `payments:entitlements:revoke`, or only the one its tooling needs \u2014 a refund tool that cannot comp cannot be turned into one, and a comp tool cannot take paid access away from a live customer. With the seam not composed both routes answer `controlplane/not_connected`, and no app session opens either of them whatever scopes it carries.",
44
44
  "Selling through Stripe also needs a `stripe` block naming where its hosted pages return to \u2014 `successUrl`, `cancelUrl`, `portalReturnUrl`. Required whenever the rail is on, and config rather than request input: a client that could name a return URL could send a paying customer to a page it controls. Put `{CHECKOUT_SESSION_ID}` in the success URL's query and the thank-you page can post it to /payments/purchases for an entitlement at once.",
45
45
  "Set the account link on every purchase your app starts \u2014 Apple's appAccountToken and Google's obfuscatedAccountId, in the app's own purchase flow. A webhook arrives carrying the provider's identifier and names no holder of ours, so a purchase made without one arrives orphaned. Stripe needs nothing from you here: /payments/checkout sets `client_reference_id` from the subject the caller acts for, which is the one hook a client must never be allowed to name.",
46
46
  "Run `pithy payments provision` to deploy the reconciliation Workflow and write its binding. Every pass it runs leaves a row in pithy_payments_reconcile_runs \u2014 started, finished, rail, environment and tally, kept ninety days \u2014 and `GET /payments/admin/reconcile-runs` reads them behind `payments:reconcile:read`, so an adopter can tell a healthy integration from one whose cron stopped firing without granting anybody the purchase log. `pithy add` touches no Cloudflare account; provisioning is the separate, explicit step. Skipping it costs nothing up front \u2014 the binding is optional and every route works without it \u2014 but webhook-only systems rot silently, so the nightly pass is what turns a dropped delivery into a repaired row rather than a support ticket.",
@@ -60,11 +60,6 @@
60
60
  "organization": "paymentsSubject"
61
61
  }
62
62
  },
63
- {
64
- "key": "manualEntitlements",
65
- "default": [],
66
- "describe": "Entitlement keys the control plane may grant that no product sells \u2014 a beta flag, an internal tier, a key that exists only to be comped. Declared, because the alternative to declaring is not checking: with this empty, a manual grant of any key outside the catalog is refused. Only grants are constrained; a revoke of a key the catalog has since dropped stays legal."
67
- },
68
63
  {
69
64
  "key": "graceGrantsAccess",
70
65
  "default": true,
@@ -8,6 +8,7 @@ import {
8
8
  PAYMENTS_PURCHASES_READ_SCOPE,
9
9
  PAYMENTS_RECONCILE_READ_SCOPE,
10
10
  PAYMENTS_SUBSCRIPTIONS_READ_SCOPE,
11
+ PAYMENTS_USAGE_READ_SCOPE,
11
12
  } from "../http/scopes";
12
13
 
13
14
  /**
@@ -104,4 +105,31 @@ export const PAYMENTS_TABLE_DISCLOSURE: Record<keyof PaymentsTables, PaymentsDis
104
105
  withheld:
105
106
  "A sweep's resume token is internal bookkeeping, not a fact about a customer. Reading it answers nothing a management client asks, and the write it invites would silently skip every event between two cursor values.",
106
107
  },
108
+ /**
109
+ * One subject's override, read on the subject's entitlement read — the version a set must send back, the
110
+ * pins, and whether the subject is `unrestricted`. Read where the entitlements are because the two answer
111
+ * one question together: what this subject may have, and why. `unrestricted` also surfaces on the
112
+ * entitlement listing, because a privilege this size must not be inferable only from a row nobody opens.
113
+ */
114
+ pithyPaymentsOverrides: { reads: [PAYMENTS_ENTITLEMENTS_READ_SCOPE] },
115
+ /**
116
+ * Withheld. A counter exists to refuse a write at a limit and for no other purpose, and the subject read
117
+ * already says what the limit is. A page of every subject's usage is a page of every customer's activity,
118
+ * and nothing a management client does needs it.
119
+ */
120
+ pithyPaymentsMeterCounters: {
121
+ withheld:
122
+ "A meter counts to refuse at a limit and for nothing else. The limit is on the subject's entitlement read; a page of every subject's usage is a page of every customer's activity, which no pane needs.",
123
+ },
124
+ /**
125
+ * The last count reported for a subscription, on the subscription read — what a quantity-billed customer
126
+ * was billed for, and when it was sent.
127
+ */
128
+ pithyPaymentsUsageReports: { reads: [PAYMENTS_SUBSCRIPTIONS_READ_SCOPE] },
129
+ /**
130
+ * The usage-reporting run log, on its own scope — the reporting pass's health, as the reconcile run log is
131
+ * reconciliation's. Unlike that log it names subjects, in the findings an operator acts on, so it is not
132
+ * the health monitor's scope: it is granted to whoever answers "why was this customer not billed".
133
+ */
134
+ pithyPaymentsUsageRuns: { reads: [PAYMENTS_USAGE_READ_SCOPE] },
107
135
  };
package/src/admin/read.ts CHANGED
@@ -2,20 +2,27 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import { chunkByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
5
6
  import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
6
7
  import type { z } from "zod";
7
8
  import { PaymentsEntitlement } from "../data/entitlement";
9
+ import { PaymentsOverride } from "../data/override";
8
10
  import { PaymentsPurchase, type PurchaseEnvironment } from "../data/purchase";
9
11
  import type { PaymentsRail } from "../data/rail";
10
12
  import { PaymentsReconcileRun } from "../data/reconcileRun";
11
13
  import type { PurchaseStatus } from "../data/status";
12
- import type { PaymentsSubject } from "../data/subject";
14
+ import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
13
15
  import {
14
16
  PAYMENTS_ENTITLEMENTS_TABLE,
17
+ PAYMENTS_OVERRIDES_TABLE,
15
18
  PAYMENTS_PURCHASES_TABLE,
16
19
  PAYMENTS_RECONCILE_RUNS_TABLE,
20
+ PAYMENTS_USAGE_REPORTS_TABLE,
21
+ PAYMENTS_USAGE_RUNS_TABLE,
17
22
  paymentsDatabase,
18
23
  } from "../data/tables";
24
+ import { PaymentsUsageReport } from "../data/usageReport";
25
+ import { PaymentsUsageRun } from "../data/usageRun";
19
26
 
20
27
  /**
21
28
  * The management read model — the queries behind the control-plane reads, and nothing else.
@@ -94,6 +101,7 @@ export const PaymentsPurchaseRecord = PaymentsPurchase.pick({
94
101
  environment: true,
95
102
  amountMinor: true,
96
103
  currency: true,
104
+ quantity: true,
97
105
  purchasedAt: true,
98
106
  expiresAt: true,
99
107
  revokedAt: true,
@@ -306,6 +314,170 @@ export async function readEntitlements(d1: D1Database, subject: PaymentsSubject)
306
314
  return rows.map((row) => PaymentsEntitlement.parse(row));
307
315
  }
308
316
 
317
+ /**
318
+ * Which of `subjects` are `unrestricted` — what the entitlement listing marks on each row. One query for the
319
+ * page rather than one per row, on the override index that leads on `unrestricted`.
320
+ */
321
+ export async function unrestrictedSubjects(d1: D1Database, subjects: readonly PaymentsSubject[]): Promise<Set<string>> {
322
+ if (subjects.length === 0) return new Set();
323
+ const db = paymentsDatabase(d1);
324
+ const found = new Set<string>();
325
+ // One fixed parameter beside the list — `unrestricted` — so a full page of 100 ids is two statements.
326
+ for (const ids of chunkByBoundParameters([...new Set(subjects.map((subject) => subject.subjectId))], 1)) {
327
+ const rows = await db
328
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
329
+ .select(["subjectType", "subjectId"])
330
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
331
+ .where("unrestricted", "=", 1 as any)
332
+ .where("subjectId", "in", ids)
333
+ .execute();
334
+ for (const row of rows) found.add(encodeSubjectReference(row as PaymentsSubject));
335
+ }
336
+ return found;
337
+ }
338
+
339
+ /** What {@link listOverrides} accepts. */
340
+ export interface OverridesQuery {
341
+ /** Narrow to one subject. */
342
+ subject?: PaymentsSubject;
343
+ /** Narrow to the subjects that are `unrestricted`. */
344
+ unrestricted?: boolean;
345
+ /** Where to resume. */
346
+ cursor?: string;
347
+ /** How many rows to return, clamped by `pageLimit`. */
348
+ limit?: number;
349
+ }
350
+
351
+ /**
352
+ * Every subject's override, most recently changed first. A row a clear emptied is kept only so its version
353
+ * never repeats, and overrides nothing, so it is not listed.
354
+ */
355
+ export async function listOverrides(
356
+ d1: D1Database,
357
+ query: OverridesQuery = {},
358
+ ): Promise<PaymentsPage<PaymentsOverride>> {
359
+ const limit = pageLimit(query.limit);
360
+ const after = resume(query.cursor);
361
+ let selection = paymentsDatabase(d1)
362
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
363
+ .selectAll()
364
+ // The SQL side of `isEmptyOverride`: the encoded 0/1 and the encoded empty JSON objects the codec writes.
365
+ .where((eb) =>
366
+ eb.or([
367
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
368
+ eb("unrestricted", "=", 1 as any),
369
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded JSON text the codec writes.
370
+ eb("quotas", "!=", "{}" as any),
371
+ // biome-ignore lint/suspicious/noExplicitAny: as above.
372
+ eb("features", "!=", "{}" as any),
373
+ ]),
374
+ )
375
+ .orderBy("updatedAt", "desc")
376
+ .orderBy("id", "desc")
377
+ .limit(limit + 1);
378
+ if (query.subject !== undefined) {
379
+ selection = selection
380
+ .where("subjectType", "=", query.subject.subjectType)
381
+ .where("subjectId", "=", query.subject.subjectId);
382
+ }
383
+ if (query.unrestricted !== undefined) {
384
+ const flag = query.unrestricted ? 1 : 0;
385
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
386
+ selection = selection.where("unrestricted", "=", flag as any);
387
+ }
388
+ if (after) {
389
+ selection = selection.where((eb) =>
390
+ eb.or([eb("updatedAt", "<", after.sort), eb.and([eb("updatedAt", "=", after.sort), eb("id", "<", after.id)])]),
391
+ );
392
+ }
393
+ const rows = await selection.execute();
394
+ return toPage(
395
+ rows.map((row) => PaymentsOverride.parse(row)),
396
+ limit,
397
+ (override) => ({ sort: override.updatedAt.getTime(), id: override.id }),
398
+ );
399
+ }
400
+
401
+ /** Every `unrestricted` subject this deployment holds — what `pithy doctor` names. */
402
+ export async function listUnrestrictedSubjects(d1: D1Database): Promise<PaymentsSubject[]> {
403
+ const rows = await paymentsDatabase(d1)
404
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
405
+ .select(["subjectType", "subjectId"])
406
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
407
+ .where("unrestricted", "=", 1 as any)
408
+ .orderBy("subjectType")
409
+ .orderBy("subjectId")
410
+ .execute();
411
+ return rows.map((row) => ({ subjectType: row.subjectType, subjectId: row.subjectId }) as PaymentsSubject);
412
+ }
413
+
414
+ /** What {@link listUsageRuns} accepts. */
415
+ export interface UsageRunsQuery {
416
+ /** Where to resume, from a previous page's `nextCursor`. A malformed one is a first page. */
417
+ cursor?: string;
418
+ /** How many rows to return, clamped by `pageLimit`. */
419
+ limit?: number;
420
+ }
421
+
422
+ /** The usage-reporting passes this deployment has run, newest first — the same keyset the reconcile log uses. */
423
+ export async function listUsageRuns(
424
+ d1: D1Database,
425
+ query: UsageRunsQuery = {},
426
+ ): Promise<PaymentsPage<PaymentsUsageRun>> {
427
+ const limit = pageLimit(query.limit);
428
+ const after = resume(query.cursor);
429
+ let selection = paymentsDatabase(d1)
430
+ .selectFrom(PAYMENTS_USAGE_RUNS_TABLE)
431
+ .selectAll()
432
+ .orderBy("startedAt", "desc")
433
+ .orderBy("id", "desc")
434
+ .limit(limit + 1);
435
+ if (after) {
436
+ selection = selection.where((eb) =>
437
+ eb.or([eb("startedAt", "<", after.sort), eb.and([eb("startedAt", "=", after.sort), eb("id", "<", after.id)])]),
438
+ );
439
+ }
440
+ const rows = await selection.execute();
441
+ return toPage(
442
+ rows.map((row) => PaymentsUsageRun.parse(row)),
443
+ limit,
444
+ (run) => ({ sort: run.startedAt.getTime(), id: run.id }),
445
+ );
446
+ }
447
+
448
+ /**
449
+ * The newest accepted report of each subscription, by its store id — what the subscription reads show as the
450
+ * last reported count. Keyed on the subscription rather than on one period's purchase row, because the report
451
+ * for a period lands at that period's end and the current row has none until then.
452
+ */
453
+ export async function lastReports(
454
+ d1: D1Database,
455
+ subscriptions: readonly { rail: PaymentsRail; providerSubscriptionId: string }[],
456
+ ): Promise<Map<string, { quantity: number; reportedAt: Date }>> {
457
+ const latest = new Map<string, { quantity: number; reportedAt: Date }>();
458
+ if (subscriptions.length === 0) return latest;
459
+ const db = paymentsDatabase(d1);
460
+ const ids = [...new Set(subscriptions.map((entry) => entry.providerSubscriptionId))];
461
+ // One fixed parameter beside the list — `status` — so a full page is two statements. A subscription's rows
462
+ // all fall in the chunk that carries its id, so newest-first within a chunk is newest-first for it.
463
+ for (const chunk of chunkByBoundParameters(ids, 1)) {
464
+ const rows = await db
465
+ .selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
466
+ .selectAll()
467
+ .where("providerSubscriptionId", "in", chunk)
468
+ .where("status", "=", "reported")
469
+ .orderBy("reportedAt", "desc")
470
+ .execute();
471
+ for (const row of rows) {
472
+ const report = PaymentsUsageReport.parse(row);
473
+ const key = `${report.rail}:${report.providerSubscriptionId}`;
474
+ if (report.reportedAt === null || latest.has(key)) continue;
475
+ latest.set(key, { quantity: report.quantity, reportedAt: report.reportedAt });
476
+ }
477
+ }
478
+ return latest;
479
+ }
480
+
309
481
  /** What {@link listReconcileRuns} accepts. */
310
482
  export interface ReconcileRunsQuery {
311
483
  /** Restrict to the passes narrowed to one store. Never matches a pass that ran against every rail. */
@@ -208,6 +208,19 @@ export const PaymentsAuditActions = {
208
208
  * indistinguishable from the 04:00 cron, which is exactly the question somebody reading the trail is asking.
209
209
  */
210
210
  reconcileRunStarted: "payments/reconcile_run_started",
211
+ /**
212
+ * A management client pinned allowances for one subject, or turned `unrestricted` on or off. The first
213
+ * runtime-writable input to an entitlement decision, so every write is recorded with the subject, the
214
+ * mode, the before and the after — and the **reason**, verbatim, because six months later the only
215
+ * question anybody asks about an override is why.
216
+ */
217
+ overrideSet: "payments/override_set",
218
+ /** A management client unpinned allowances for one subject, or cleared its override. */
219
+ overrideCleared: "payments/override_cleared",
220
+ /**
221
+ * A management client read the usage-reporting run log. Counts and filters only, as every management read.
222
+ */
223
+ usageRunsRead: "payments/usage_runs_read",
211
224
  } as const;
212
225
 
213
226
  /** One of the payments audit action codes. */