@pithy-sh/payments 0.4.0 → 0.5.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 (177) 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 +1 -0
  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 +93 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/entitlement/allowance.d.ts +100 -0
  49. package/dist/entitlement/allowance.d.ts.map +1 -0
  50. package/dist/entitlement/allowance.js +171 -0
  51. package/dist/entitlement/manual.d.ts +5 -5
  52. package/dist/entitlement/manual.js +3 -3
  53. package/dist/entitlement/meter.d.ts +98 -0
  54. package/dist/entitlement/meter.d.ts.map +1 -0
  55. package/dist/entitlement/meter.js +177 -0
  56. package/dist/entitlement/override.d.ts +119 -0
  57. package/dist/entitlement/override.d.ts.map +1 -0
  58. package/dist/entitlement/override.js +256 -0
  59. package/dist/entitlement/resolver.d.ts +2 -1
  60. package/dist/entitlement/resolver.d.ts.map +1 -1
  61. package/dist/entitlement/resolver.js +32 -1
  62. package/dist/error/errors.d.ts +19 -0
  63. package/dist/error/errors.d.ts.map +1 -1
  64. package/dist/error/errors.js +35 -2
  65. package/dist/http/responses.d.ts +367 -0
  66. package/dist/http/responses.d.ts.map +1 -1
  67. package/dist/http/responses.js +146 -7
  68. package/dist/http/routes.d.ts.map +1 -1
  69. package/dist/http/routes.js +270 -16
  70. package/dist/http/schemas.d.ts +54 -0
  71. package/dist/http/schemas.d.ts.map +1 -1
  72. package/dist/http/schemas.js +61 -2
  73. package/dist/http/scopes.d.ts +25 -0
  74. package/dist/http/scopes.d.ts.map +1 -1
  75. package/dist/http/scopes.js +60 -1
  76. package/dist/http/view.d.ts +22 -4
  77. package/dist/http/view.d.ts.map +1 -1
  78. package/dist/http/view.js +88 -7
  79. package/dist/index.d.ts +2 -1
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +3 -2
  82. package/dist/migrations/0002_allowances.d.ts +26 -0
  83. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  84. package/dist/migrations/0002_allowances.js +62 -0
  85. package/dist/peer.d.ts +1 -0
  86. package/dist/peer.d.ts.map +1 -1
  87. package/dist/projection/event.d.ts +1 -0
  88. package/dist/projection/event.d.ts.map +1 -1
  89. package/dist/projection/event.js +1 -0
  90. package/dist/projection/writer.d.ts.map +1 -1
  91. package/dist/projection/writer.js +3 -1
  92. package/dist/rails/contract.d.ts +6 -0
  93. package/dist/rails/contract.d.ts.map +1 -1
  94. package/dist/rails/google/playApi.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.js +2 -0
  96. package/dist/rails/paddle/objects.d.ts +2 -0
  97. package/dist/rails/paddle/objects.d.ts.map +1 -1
  98. package/dist/rails/paddle/objects.js +7 -2
  99. package/dist/rails/paddle/usage.d.ts +11 -0
  100. package/dist/rails/paddle/usage.d.ts.map +1 -0
  101. package/dist/rails/paddle/usage.js +49 -0
  102. package/dist/rails/quantity.d.ts +12 -0
  103. package/dist/rails/quantity.d.ts.map +1 -0
  104. package/dist/rails/quantity.js +16 -0
  105. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  106. package/dist/rails/stripe/checkout.js +1 -1
  107. package/dist/rails/stripe/objects.d.ts.map +1 -1
  108. package/dist/rails/stripe/objects.js +3 -0
  109. package/dist/rails/stripe/usage.d.ts +10 -0
  110. package/dist/rails/stripe/usage.d.ts.map +1 -0
  111. package/dist/rails/stripe/usage.js +49 -0
  112. package/dist/usage/pass.d.ts +120 -0
  113. package/dist/usage/pass.d.ts.map +1 -0
  114. package/dist/usage/pass.js +363 -0
  115. package/dist/usage/reporter.d.ts +36 -0
  116. package/dist/usage/reporter.d.ts.map +1 -0
  117. package/dist/usage/reporter.js +2 -0
  118. package/dist/version.generated.d.ts +1 -1
  119. package/dist/version.generated.js +1 -1
  120. package/dist/workflows/specs.d.ts +28 -0
  121. package/dist/workflows/specs.d.ts.map +1 -1
  122. package/dist/workflows/specs.js +26 -1
  123. package/dist/workflows/usage.d.ts +38 -0
  124. package/dist/workflows/usage.d.ts.map +1 -0
  125. package/dist/workflows/usage.js +77 -0
  126. package/dist/workflows/worker.js +2 -2
  127. package/docs/entitlements.md +249 -0
  128. package/docs/lemon-squeezy.md +1 -0
  129. package/docs/paddle.md +1 -0
  130. package/package.json +5 -5
  131. package/pithy.manifest.json +3 -8
  132. package/src/admin/coverage.ts +28 -0
  133. package/src/admin/read.ts +173 -1
  134. package/src/audit/actions.ts +13 -0
  135. package/src/capability.ts +87 -9
  136. package/src/client/api.ts +44 -0
  137. package/src/client/hooks.ts +44 -0
  138. package/src/client/projection.ts +31 -0
  139. package/src/config/allowances.ts +211 -0
  140. package/src/config/config.ts +283 -15
  141. package/src/data/meterCounter.ts +38 -0
  142. package/src/data/override.ts +74 -0
  143. package/src/data/period.ts +53 -0
  144. package/src/data/purchase.ts +9 -0
  145. package/src/data/tables.ts +25 -1
  146. package/src/data/usageReport.ts +64 -0
  147. package/src/data/usageRun.ts +66 -0
  148. package/src/entitlement/allowance.ts +213 -0
  149. package/src/entitlement/manual.ts +6 -6
  150. package/src/entitlement/meter.ts +252 -0
  151. package/src/entitlement/override.ts +381 -0
  152. package/src/entitlement/resolver.ts +43 -2
  153. package/src/error/errors.ts +44 -1
  154. package/src/http/responses.ts +305 -4
  155. package/src/http/routes.ts +365 -11
  156. package/src/http/schemas.ts +139 -1
  157. package/src/http/scopes.ts +68 -0
  158. package/src/http/view.ts +112 -7
  159. package/src/index.ts +18 -0
  160. package/src/migrations/0002_allowances.ts +149 -0
  161. package/src/projection/event.ts +9 -0
  162. package/src/projection/writer.ts +4 -0
  163. package/src/rails/contract.ts +6 -0
  164. package/src/rails/google/playApi.ts +2 -0
  165. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  166. package/src/rails/paddle/objects.ts +6 -0
  167. package/src/rails/paddle/usage.ts +66 -0
  168. package/src/rails/quantity.ts +14 -0
  169. package/src/rails/stripe/checkout.ts +3 -1
  170. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  171. package/src/rails/stripe/objects.ts +4 -0
  172. package/src/rails/stripe/usage.ts +61 -0
  173. package/src/usage/pass.ts +539 -0
  174. package/src/usage/reporter.ts +38 -0
  175. package/src/version.generated.ts +1 -1
  176. package/src/workflows/specs.ts +34 -0
  177. package/src/workflows/usage.ts +97 -0
@@ -69,7 +69,11 @@ const PaymentsPurchaseResponse = z.object({
69
69
  entitlements: z.array(PaymentsEntitlementView).describe("What that purchase grants, resolved now.")
70
70
  }).describe("A verified purchase and the entitlements it produced.");
71
71
  /** `GET {base}/entitlements` — always the caller's own. */
72
- const PaymentsEntitlementsResponse = z.object({ entitlements: z.array(PaymentsEntitlementView).describe("The caller's entitlements, resolved now.") }).describe("Every entitlement the caller holds.");
72
+ const PaymentsEntitlementsResponse = z.object({
73
+ entitlements: z.array(PaymentsEntitlementView).describe("The caller's entitlements, resolved now."),
74
+ quotas: z.record(z.string(), z.number().int().nonnegative().nullable().describe("A whole number, or null for unlimited.")).optional().describe("Every declared quota, resolved for the caller's holder now — what `quota(c, name)` answers on the server, for a paywall screen to show. A UX affordance, never a security boundary: the server enforces. Absent from a Worker that predates declarations."),
75
+ features: z.record(z.string(), z.boolean().describe("Whether it is on.")).optional().describe("Every declared feature, resolved for the caller's holder now. A UX affordance, never a security boundary. Absent from a Worker that predates declarations.")
76
+ }).describe("Every entitlement the caller holds, and the allowances they resolve to.");
73
77
  /** `POST {base}/restore`. */
74
78
  const PaymentsRestoreResponse = z.object({
75
79
  purchases: z.array(PaymentsPurchaseView).describe("Every receipt in the batch, as the projection left it."),
@@ -399,7 +403,9 @@ const PaymentsSubscriptionView = z.object({
399
403
  currentPeriodEndsAt: z.iso.datetime().nullable().describe("When the period already paid for runs out, ISO-8601 — the day access lapses if nothing renews it. Null while trialing or paused, which are the states with no billing period."),
400
404
  nextBilledAt: z.iso.datetime().nullable().describe("When the next charge falls due, ISO-8601, or null when none is going to. **Null is not canceled and not broken:** the store blanks it the moment a cancellation is scheduled and leaves the status `active`. Render `nextEvent` instead of putting this beside the word 'renews'."),
401
405
  scheduledChange: PaymentsSubscriptionScheduledChange.nullable().describe("The change waiting to land, or null when nothing is. The only field that separates a subscription ending this period from one renewing."),
402
- nextEvent: PaymentsSubscriptionNextEvent.describe("What happens next and when, already resolved — the scheduled change ahead of the billing date. The sentence a screen prints.")
406
+ nextEvent: PaymentsSubscriptionNextEvent.describe("What happens next and when, already resolved — the scheduled change ahead of the billing date. The sentence a screen prints."),
407
+ reportedQuantity: z.number().int().nonnegative().nullable().optional().describe("For a quantity-billed product, the last count reported to the store — null when nothing has been reported yet. Absent from a Worker that predates reported billing."),
408
+ reportedAt: z.iso.datetime().nullable().optional().describe("When that count was reported, ISO-8601, or null when nothing has been. Absent from a Worker that predates reported billing.")
403
409
  }).describe("One subscription as the person paying for it reads it: which plan, where it stands, and what is next.");
404
410
  /**
405
411
  * `GET {base}/subscription` — the caller's own subscription, or that they have none.
@@ -582,6 +588,29 @@ const PaymentsAdminCatalogProduct = z.object({
582
588
  name: z.string().describe("The display name the adopter wrote — `Pro`, `Remove ads`. What a list renders."),
583
589
  entitlements: z.array(z.string()).describe("The entitlement keys this product grants. The whole reason this read exists: a comp names a key, so this is the list a grant control offers instead of a text box.")
584
590
  }).describe("One catalog product as a management client sees it: what it is, and what it grants.");
591
+ /** A quota's value on the wire: a whole number from 0, or null for unlimited. */
592
+ const WireQuota = z.number().int().nonnegative().nullable().describe("A whole number from 0, or null for unlimited.");
593
+ /**
594
+ * One declared entitlement key, as a management client sees it: what it is called, and what it buys.
595
+ *
596
+ * **What an override editor is built from.** An override names a quota or a feature, and without this a pane
597
+ * could not say which names exist, which are numbers and which are switches, what the plan's value is, or
598
+ * what ceiling an operator may type up to. `quotas` holds numbers and `features` holds booleans, so the map a
599
+ * name sits in *is* its kind.
600
+ */
601
+ const PaymentsAdminCatalogEntitlement = z.object({
602
+ key: z.string().describe("The entitlement key — what gating code names, and what a comp grants."),
603
+ name: z.string().describe("The tier's display name, as the adopter wrote it — `Growth`."),
604
+ quotas: z.record(z.string(), WireQuota).describe("What this key allows, by quota name. A whole number, or null for unlimited."),
605
+ features: z.record(z.string(), z.boolean().describe("Whether the switch is on.")).describe("Its switches, by name."),
606
+ overrideMax: z.record(z.string(), z.number().int().nonnegative().describe("The ceiling.")).describe("Per quota, the largest number an override may set. A quota absent here accepts any whole number. `unrestricted` is never bounded by it."),
607
+ sold: z.boolean().describe("Whether a product in this catalog grants the key. False is comp-only: grantable by hand, sold by nothing.")
608
+ }).describe("One declared entitlement key: its name, its quotas, its features, and the ceilings on overriding them.");
609
+ /** The free floor, as a management client sees it. */
610
+ const PaymentsAdminCatalogDefaults = z.object({
611
+ quotas: z.record(z.string(), WireQuota).describe("What a subject holding no key gets, by quota name."),
612
+ features: z.record(z.string(), z.boolean().describe("Whether the switch is on.")).describe("The switches a subject holding no key gets.")
613
+ }).describe("What a caller holding no key gets — the free floor.");
585
614
  /**
586
615
  * `GET {base}/admin/catalog` — what this project sells.
587
616
  *
@@ -595,10 +624,12 @@ const PaymentsAdminCatalogProduct = z.object({
595
624
  * answers and an optional array makes "empty" and "absent" indistinguishable at the exact moment a caller
596
625
  * needs them apart.
597
626
  */
598
- const PaymentsAdminCatalogResponse = z.discriminatedUnion("enabled", [z.object({ enabled: z.literal(false).describe("This project defines nothing — no product is configured and no key was declared grantable, so there is no entitlement a comp control could offer and no grant that would succeed.") }).describe("A project composing payments with an empty catalog. The same answer as not composing it at all."), z.object({
627
+ const PaymentsAdminCatalogResponse = z.discriminatedUnion("enabled", [z.object({ enabled: z.literal(false).describe("This project defines nothing — no product is configured and no key is declared, so there is no entitlement a comp control could offer and no grant that would succeed.") }).describe("A project composing payments with an empty catalog. The same answer as not composing it at all."), z.object({
599
628
  enabled: z.literal(true).describe("This project sells something."),
600
629
  products: z.array(PaymentsAdminCatalogProduct).describe("The catalog, in the order the adopter wrote it — which is the order a list should show."),
601
- manualEntitlements: z.array(z.string()).describe("Entitlement keys the adopter declared grantable with no product behind them. Offered beside the products because a comp control that omitted them would refuse the grants it then submitted.")
630
+ manualEntitlements: z.array(z.string()).describe("The comp-only keys — declared, and sold by no product. Offered beside the products because a comp control that omitted them would refuse the grants it then submitted. Kept under its first name so a client reading an older Worker and a newer one reads one field."),
631
+ entitlements: z.array(PaymentsAdminCatalogEntitlement).optional().describe("Every declared key and what it buys, in the order the adopter wrote them. Absent from a Worker that predates declarations. What an override editor is built from: every editable name, and whether it is a number or a switch."),
632
+ defaults: PaymentsAdminCatalogDefaults.nullable().optional().describe("The free floor, or null when none is declared. Absent from a Worker that predates declarations.")
602
633
  }).describe("The catalog, as a management client reads it.")]).describe("What this project sells, or that it sells nothing. Never a price, a SKU, or a rail's identifier.");
603
634
  /** Where a page resumes, or the end of the list. */
604
635
  const NextCursor = z.string().nullable().describe("Where the next page resumes. Null at the end of the list. Opaque — pass it back verbatim.");
@@ -616,6 +647,9 @@ const NextCursor = z.string().nullable().describe("Where the next page resumes.
616
647
  * replayed. The first is the whole point of the pane and the second never leaves the Worker.
617
648
  */
618
649
  const PaymentsAdminPurchaseView = z.object({
650
+ quantity: z.number().int().positive().nullable().optional().describe("How many were bought, as the store stated it, or null where it did not. Absent from a Worker that predates the column."),
651
+ reportedQuantity: z.number().int().nonnegative().nullable().optional().describe("For a quantity-billed subscription, the last count reported to the store, or null when none has been. Absent from a Worker that predates reported billing."),
652
+ reportedAt: z.iso.datetime().nullable().optional().describe("When that count was reported, ISO-8601, or null. Absent from a Worker that predates reported billing."),
619
653
  id: z.string().describe("The purchase's UUID — its stable identifier on this Worker."),
620
654
  subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization. Half the owner: read the two together or a row is attributed to whoever else holds that id."),
621
655
  subjectId: PaymentsSubject.shape.subjectId.describe("The subject that bought it — the opaque id the adopter's auth capability issued, or the one its own membership model did. The only identity payments stores, and the join key to `auth:users:read`, which is granted separately."),
@@ -653,8 +687,75 @@ const PaymentsAdminEntitlementView = z.object({
653
687
  granted: z.boolean().describe("Whether it grants access right now, resolved against `expiresAt` on this read exactly as the hot path resolves it. The stored flag is an optimization; this is the answer."),
654
688
  expiresAt: z.iso.datetime().nullable().describe("When it lapses, ISO-8601; null for one that does not."),
655
689
  manual: z.boolean().describe("Whether a human wrote this row through the control plane rather than a purchase producing it. A manual grant is held against the projection, so it survives the subject's next renewal."),
656
- source: z.string().nullable().describe("The purchase currently granting this entitlement, or null when nothing does — a comp, or a grant whose purchase has lapsed.")
690
+ source: z.string().nullable().describe("The purchase currently granting this entitlement, or null when nothing does — a comp, or a grant whose purchase has lapsed."),
691
+ unrestricted: z.boolean().optional().describe("Whether this row's subject is `unrestricted` — every quota unlimited and every feature on, whatever it holds. On every row, because a privilege this large must not be inferable only from a row nobody opens. Absent from a Worker that predates overrides.")
657
692
  }).describe("One entitlement as a management client sees it: whose it is, whether it grants, and why.");
693
+ /** Where an allowance's value came from. */
694
+ const PaymentsAllowanceSource = z.enum([
695
+ "unrestricted",
696
+ "override",
697
+ "plan",
698
+ "default",
699
+ "none"
700
+ ]).describe("Where the value came from: the subject's `unrestricted` override, a pin on its override, a key it holds (`key` names it), the free floor, or `none` — nothing declared spoke to it, so it is 0 or false.");
701
+ /**
702
+ * One quota for one subject: what applies now, where it came from, and what it would be with the override
703
+ * removed. **Three facts, because a pane that lets an operator pin one field needs all three** — projecting only
704
+ * the effective value loses the plan's number the instant an override exists, and the pane can no longer draw
705
+ * the row it is editing or offer to revert it.
706
+ */
707
+ const PaymentsAdminQuotaView = z.object({
708
+ name: z.string().describe("The quota name."),
709
+ effective: WireQuota.describe("What applies now. A whole number, or null for unlimited."),
710
+ source: PaymentsAllowanceSource,
711
+ key: z.string().nullable().describe("The entitlement key that supplied `effective`, when `source` is `plan`."),
712
+ inherited: WireQuota.describe("What it would be with the override removed — the plan's own number, to show beside a pin and to revert to."),
713
+ inheritedSource: PaymentsAllowanceSource.describe("Where `inherited` came from."),
714
+ inheritedKey: z.string().nullable().describe("The key that supplied `inherited`, when it is a plan's."),
715
+ overrideMax: z.number().int().nonnegative().nullable().describe("The largest number an override may set here for this subject, or null for no ceiling.")
716
+ }).describe("One quota for one subject: effective, provenance, and inherited.");
717
+ /** One feature for one subject, the same three facts. */
718
+ const PaymentsAdminFeatureView = z.object({
719
+ name: z.string().describe("The feature name."),
720
+ effective: z.boolean().describe("Whether it is on now."),
721
+ source: PaymentsAllowanceSource,
722
+ key: z.string().nullable().describe("The entitlement key that supplied `effective`, when `source` is `plan`."),
723
+ inherited: z.boolean().describe("Whether it would be on with the override removed."),
724
+ inheritedSource: PaymentsAllowanceSource.describe("Where `inherited` came from."),
725
+ inheritedKey: z.string().nullable().describe("The key that supplied `inherited`, when it is a plan's.")
726
+ }).describe("One feature for one subject: effective, provenance, and inherited.");
727
+ /** Every declared allowance for one subject. */
728
+ const PaymentsAdminAllowancesView = z.object({
729
+ quotas: z.array(PaymentsAdminQuotaView).describe("Every declared quota, by name."),
730
+ features: z.array(PaymentsAdminFeatureView).describe("Every declared feature, by name.")
731
+ }).describe("Every declared allowance for one subject, resolved now.");
732
+ /** One subject's override row, as a management client sees it. */
733
+ const PaymentsAdminOverrideView = z.object({
734
+ version: z.number().int().positive().describe("The version a set must send back. A set naming an older one is refused as stale."),
735
+ unrestricted: z.boolean().describe("Whether every quota is unlimited and every feature on, except the pins, for every name present and future."),
736
+ quotas: z.record(z.string(), WireQuota).describe("The pinned quotas."),
737
+ features: z.record(z.string(), z.boolean().describe("Whether the switch is on.")).describe("The pinned features."),
738
+ reason: z.string().describe("The reason the last write gave."),
739
+ updatedAt: z.iso.datetime().describe("When it last changed, ISO-8601.")
740
+ }).describe("One subject's override: its version, its mode, its pins, and why.");
741
+ /** One subject's override in the listing: whose it is, and the override. */
742
+ const PaymentsAdminOverrideListItem = z.object({
743
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
744
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject the override shades."),
745
+ override: PaymentsAdminOverrideView
746
+ }).describe("One subject's override, as the listing pages it.");
747
+ /** `GET {base}/admin/overrides`. */
748
+ const PaymentsAdminOverridesResponse = z.object({
749
+ overrides: z.array(PaymentsAdminOverrideListItem).describe("The page, most recently changed first."),
750
+ nextCursor: z.string().nullable().describe("Where the next page resumes. Null at the end of the list. Opaque — pass it back verbatim.")
751
+ }).describe("A page of every subject's override — the negotiated numbers, and who is unrestricted.");
752
+ /** What every override write answers: the subject, and its override as it now stands. */
753
+ const PaymentsOverrideResponse = z.object({
754
+ subjectType: PaymentsSubject.shape.subjectType.describe("Which kind of holder, echoed."),
755
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject, echoed."),
756
+ override: PaymentsAdminOverrideView.nullable().describe("The override after the write, or null when the subject now has none — a whole clear, or a clear of nothing."),
757
+ version: z.number().int().nonnegative().describe("The version the next write must name. 0 when the subject has never had an override; a cleared one keeps its version, so a stale writer stays stale.")
758
+ }).describe("An override write's result: the subject, its override now, and the version to write against next.");
658
759
  /**
659
760
  * One reconciliation pass, as a management client sees it.
660
761
  *
@@ -711,6 +812,40 @@ const PaymentsAdminReconcileRunStarted = z.object({
711
812
  started: z.boolean().describe("Whether this request began a pass. Always true today: a press that starts nothing is refused with an error instead."),
712
813
  runId: z.string().nullable().describe("The Workflow instance that was started, so a caller can find this pass in the run log once it finishes. Null when `started` is false — there is no instance of *this* request to name, and naming the one already running would attribute somebody else's pass to this press.")
713
814
  }).describe("What a press on the reconciliation trigger produced: whether a pass began, and which one.");
815
+ /** One subject a usage run did not report, and why. */
816
+ const PaymentsAdminUsageFindingView = z.object({
817
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
818
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject."),
819
+ productId: z.string().describe("The product whose count was not reported."),
820
+ reason: z.enum([
821
+ "unanswered",
822
+ "not_integer",
823
+ "negative",
824
+ "below_min",
825
+ "above_max",
826
+ "resolver_failed",
827
+ "report_failed"
828
+ ]).describe("Why: the resolver answered nothing, a non-integer, a negative, a count outside min or max, or threw — or the store refused the report.")
829
+ }).describe("One subject a usage run did not report.");
830
+ /** One usage-reporting pass, as a management client sees it. */
831
+ const PaymentsAdminUsageRunView = z.object({
832
+ id: z.string().describe("The run's id."),
833
+ startedAt: z.iso.datetime().describe("When the pass began, ISO-8601."),
834
+ finishedAt: z.iso.datetime().describe("When it finished, ISO-8601."),
835
+ scanned: z.number().int().describe("Subscriptions examined."),
836
+ reported: z.number().int().describe("Periods a store accepted."),
837
+ sampled: z.number().int().describe("Daily-peak samples taken for a day still open."),
838
+ alreadyReported: z.number().int().describe("Periods already reported, so nothing was sent."),
839
+ skipped: z.number().int().describe("Subjects whose resolver answered nothing. Never reported as zero."),
840
+ invalid: z.number().int().describe("Subjects whose resolver answered a number that may not be billed. Never clamped."),
841
+ failed: z.number().int().describe("Subjects whose resolver threw, or whose report a store refused."),
842
+ findings: z.array(PaymentsAdminUsageFindingView).describe("The subjects not reported and why, up to a hundred. The counts are whole either way.")
843
+ }).describe("One usage-reporting pass: when it ran, its tally, and who it did not report.");
844
+ /** `GET {base}/admin/usage-runs`. */
845
+ const PaymentsAdminUsageRunsResponse = z.object({
846
+ runs: z.array(PaymentsAdminUsageRunView).describe("The page, most recently started first."),
847
+ nextCursor: NextCursor
848
+ }).describe("A page of the usage-reporting run log.");
714
849
  /** `GET {base}/admin/purchases`. */
715
850
  const PaymentsAdminPurchasesResponse = z.object({
716
851
  purchases: z.array(PaymentsAdminPurchaseView).describe("The page, most recently purchased first."),
@@ -741,7 +876,11 @@ const PaymentsAdminEntitlementsResponse = z.object({
741
876
  const PaymentsAdminSubjectEntitlementsResponse = z.object({
742
877
  subjectType: PaymentsSubject.shape.subjectType.describe("Which kind of holder was asked after, echoed back. Half of the address — the id alone named nothing."),
743
878
  subjectId: PaymentsSubject.shape.subjectId.describe("The id asked after, echoed so a response stands on its own."),
744
- entitlements: z.array(PaymentsAdminEntitlementView).describe("Every entitlement this subject holds, by key. Empty when it holds none.")
879
+ entitlements: z.array(PaymentsAdminEntitlementView).describe("Every entitlement this subject holds, by key. Empty when it holds none."),
880
+ unrestricted: z.boolean().optional().describe("Whether the subject is `unrestricted`. Absent from a Worker that predates overrides."),
881
+ overrideVersion: z.number().int().nonnegative().optional().describe("The version an override write for this subject must name — 0 when it has none. Absent from a Worker that predates overrides."),
882
+ override: PaymentsAdminOverrideView.nullable().optional().describe("The subject's override, or null when it has none. Absent from a Worker that predates overrides."),
883
+ allowances: PaymentsAdminAllowancesView.optional().describe("Every declared quota and feature, resolved for this subject now — effective, provenance, inherited. Absent from a Worker that predates declarations.")
745
884
  }).describe("One subject's entitlements, resolved now.");
746
885
  //#endregion
747
- export { PaymentsAdminCatalogProduct, PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementView, PaymentsAdminEntitlementsResponse, PaymentsAdminPurchaseView, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunView, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsCheckoutHandoffResponse, PaymentsDeferredSubscriptionSettlement, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementView, PaymentsEntitlementsResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPricingResponse, PaymentsPurchaseResponse, PaymentsPurchaseView, PaymentsQuotedFrom, PaymentsQuotedMoney, PaymentsRefundOutcome, PaymentsRefundRequest, PaymentsRefundRequestStatus, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionNextEvent, PaymentsSubscriptionQuote, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionScheduledChange, PaymentsSubscriptionSettlement, PaymentsSubscriptionStandingResponse, PaymentsSubscriptionView, PaymentsWebhookAck };
886
+ export { PaymentsAdminAllowancesView, PaymentsAdminCatalogDefaults, PaymentsAdminCatalogEntitlement, PaymentsAdminCatalogProduct, PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementView, PaymentsAdminEntitlementsResponse, PaymentsAdminFeatureView, PaymentsAdminOverrideListItem, PaymentsAdminOverrideView, PaymentsAdminOverridesResponse, PaymentsAdminPurchaseView, PaymentsAdminPurchasesResponse, PaymentsAdminQuotaView, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunView, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsAdminUsageFindingView, PaymentsAdminUsageRunView, PaymentsAdminUsageRunsResponse, PaymentsAllowanceSource, PaymentsCheckoutHandoffResponse, PaymentsDeferredSubscriptionSettlement, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementView, PaymentsEntitlementsResponse, PaymentsOverrideResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPricingResponse, PaymentsPurchaseResponse, PaymentsPurchaseView, PaymentsQuotedFrom, PaymentsQuotedMoney, PaymentsRefundOutcome, PaymentsRefundRequest, PaymentsRefundRequestStatus, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionNextEvent, PaymentsSubscriptionQuote, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionScheduledChange, PaymentsSubscriptionSettlement, PaymentsSubscriptionStandingResponse, PaymentsSubscriptionView, PaymentsWebhookAck };
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAW7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAG1C,OAAO,EAEL,KAAK,cAAc,EAKpB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,OA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AY,CAAC,KAAK,IAAI,CA0jFxG"}
@@ -6,10 +6,13 @@ import { providerProductId, railEnabled, resolveProduct } from "../config/config
6
6
  import { PaymentsPurchase } from "../data/purchase.js";
7
7
  import { WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent.js";
8
8
  import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables.js";
9
- import { resolveEntitlements } from "../projection/resolve.js";
10
9
  import { PaymentsEntitlementNotInCatalogError, PaymentsProductNotFoundError, PaymentsRailNotConfiguredError, PaymentsReceiptAlreadyOwnedError, PaymentsReconcileNotProvisionedError, PaymentsSubscriptionChangeRefusedError } from "../error/errors.js";
10
+ import { resolveEntitlements } from "../projection/resolve.js";
11
+ import { resolveAllowances } from "../entitlement/allowance.js";
12
+ import { allowanceOverride, clearOverride, overrideCeiling, overrideVersion, readOverride, setOverride, setUnrestricted } from "../entitlement/override.js";
13
+ import { allowanceInputFor } from "../entitlement/meter.js";
11
14
  import { requirePaymentsSubject, resolvePaymentsSubject } from "../entitlement/subjectSeam.js";
12
- import { listEntitlements, listPurchases, listReconcileRuns, listSubscriptions, readEntitlements } from "../admin/read.js";
15
+ import { lastReports, listEntitlements, listOverrides, listPurchases, listReconcileRuns, listSubscriptions, listUsageRuns, readEntitlements, unrestrictedSubjects } from "../admin/read.js";
13
16
  import { PaymentsAuditActions } from "../audit/actions.js";
14
17
  import { nextSubscriptionEvent } from "../data/subscription.js";
15
18
  import { grantEntitlement, revokeEntitlement } from "../entitlement/manual.js";
@@ -22,12 +25,13 @@ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/reg
22
25
  import { resolveRailProvider } from "../rails/providers.js";
23
26
  import { PAYMENTS_CAPABILITY, paymentsWorkflows } from "../workflows/specs.js";
24
27
  import { requireAuth } from "./guards.js";
25
- import { PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementsResponse, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsCheckoutHandoffResponse, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementsResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPurchaseResponse, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionStandingResponse, PaymentsWebhookAck } from "./responses.js";
26
- import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
27
- import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE } from "./scopes.js";
28
- import { adminCatalogView, adminEntitlementView, adminPurchaseView, adminReconcileRunView, entitlementView, purchaseView } from "./view.js";
28
+ import { PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementsResponse, PaymentsAdminOverridesResponse, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsAdminUsageRunsResponse, PaymentsCheckoutHandoffResponse, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementsResponse, PaymentsOverrideResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPurchaseResponse, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionStandingResponse, PaymentsWebhookAck } from "./responses.js";
29
+ import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminOverridesQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AdminUsageRunsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, OverrideClearRequest, OverrideSetRequest, OverrideUnrestrictedRequest, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
30
+ import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_OVERRIDE_CLEAR_SCOPE, PAYMENTS_OVERRIDE_SET_SCOPE, PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE, PAYMENTS_USAGE_READ_SCOPE } from "./scopes.js";
31
+ import { adminAllowancesView, adminCatalogView, adminEntitlementView, adminOverrideView, adminPurchaseView, adminReconcileRunView, adminUsageRunView, entitlementView, overrideView, purchaseView } from "./view.js";
29
32
  import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhookGuard.js";
30
33
  import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
34
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
31
35
  import { safeEmit } from "@pithy-sh/core/src/controlPlane/audit/actions";
32
36
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
33
37
  import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
@@ -827,7 +831,7 @@ function registerPaymentsRoutes(options) {
827
831
  }
828
832
  });
829
833
  return c.json({
830
- purchases: page.items.map(adminPurchaseView),
834
+ purchases: page.items.map((row) => adminPurchaseView(row)),
831
835
  nextCursor: page.nextCursor
832
836
  }, 200);
833
837
  });
@@ -852,6 +856,10 @@ function registerPaymentsRoutes(options) {
852
856
  ...query,
853
857
  subject
854
858
  });
859
+ const reported = await lastReports(database(c), page.items.flatMap((row) => row.originalTransactionId === null ? [] : [{
860
+ rail: row.rail,
861
+ providerSubscriptionId: row.originalTransactionId
862
+ }]));
855
863
  await recordRead(c, PaymentsAuditActions.subscriptionsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
856
864
  returned: page.items.length,
857
865
  resumed: query.cursor !== void 0,
@@ -862,7 +870,7 @@ function registerPaymentsRoutes(options) {
862
870
  }
863
871
  });
864
872
  return c.json({
865
- subscriptions: page.items.map(adminPurchaseView),
873
+ subscriptions: page.items.map((row) => adminPurchaseView(row, reported.get(`${row.rail}:${row.originalTransactionId}`) ?? null)),
866
874
  nextCursor: page.nextCursor
867
875
  }, 200);
868
876
  });
@@ -886,6 +894,7 @@ function registerPaymentsRoutes(options) {
886
894
  ...query,
887
895
  subject
888
896
  });
897
+ const unrestricted = await unrestrictedSubjects(database(c), page.items);
889
898
  await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
890
899
  returned: page.items.length,
891
900
  resumed: query.cursor !== void 0,
@@ -896,7 +905,48 @@ function registerPaymentsRoutes(options) {
896
905
  }
897
906
  });
898
907
  return c.json({
899
- entitlements: page.items.map((row) => adminEntitlementView(row, now)),
908
+ entitlements: page.items.map((row) => adminEntitlementView(row, now, unrestricted.has(encodeSubjectReference(row)))),
909
+ nextCursor: page.nextCursor
910
+ }, 200);
911
+ });
912
+ /**
913
+ * CONTROL PLANE. Every subject's override, most recently changed first.
914
+ *
915
+ * The read the override writes are paired with, on the entitlement read's scope: what a subject may have
916
+ * is one question with its entitlements, and an operator who can see one can see the other. Filterable to
917
+ * `unrestricted=true`, because "who holds the whole product" must be a question anyone holding this scope
918
+ * can answer in one request.
919
+ */
920
+ app.get(`${base}/admin/overrides`, describeRoute({
921
+ summary: "Read every subject's override, page by page.",
922
+ verification: "control-plane",
923
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
924
+ responses: { 200: PaymentsAdminOverridesResponse }
925
+ }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("query", AdminOverridesQuery), async (c) => {
926
+ const query = c.req.valid("query");
927
+ const subject = subjectFilter(query);
928
+ const unrestricted = query.unrestricted === void 0 ? void 0 : query.unrestricted === "true";
929
+ const page = await listOverrides(database(c), {
930
+ ...subject ? { subject } : {},
931
+ ...unrestricted === void 0 ? {} : { unrestricted },
932
+ ...query.cursor ? { cursor: query.cursor } : {},
933
+ ...query.limit ? { limit: query.limit } : {}
934
+ });
935
+ await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
936
+ returned: page.items.length,
937
+ resumed: query.cursor !== void 0,
938
+ filters: {
939
+ subjectType: subject?.subjectType ?? null,
940
+ subjectId: subject?.subjectId ?? null,
941
+ unrestricted: unrestricted ?? null
942
+ }
943
+ });
944
+ return c.json({
945
+ overrides: page.items.map((row) => ({
946
+ subjectType: row.subjectType,
947
+ subjectId: row.subjectId,
948
+ override: overrideView(row)
949
+ })),
900
950
  nextCursor: page.nextCursor
901
951
  }, 200);
902
952
  });
@@ -923,15 +973,34 @@ function registerPaymentsRoutes(options) {
923
973
  }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("param", AdminSubjectParam), async (c) => {
924
974
  const subject = c.req.valid("param");
925
975
  const now = clock();
926
- const rows = await readEntitlements(database(c), subject);
976
+ const d1 = database(c);
977
+ const rows = await readEntitlements(d1, subject);
978
+ const override = await readOverride(paymentsDatabase(d1), subject);
979
+ const held = grantedEntitlementKeys(rows.map((row) => ({
980
+ key: row.entitlement,
981
+ active: row.active,
982
+ expiresAt: row.expiresAt,
983
+ source: null
984
+ })), now);
985
+ const resolved = resolveAllowances({
986
+ declarations: config,
987
+ held,
988
+ override: allowanceOverride(override)
989
+ });
990
+ const unrestricted = override?.unrestricted === true;
927
991
  await recordRead(c, PaymentsAuditActions.entitlementsRead, encodeSubjectReference(subject), {
928
992
  subjectType: subject.subjectType,
929
993
  subjectId: subject.subjectId,
930
- returned: rows.length
994
+ returned: rows.length,
995
+ unrestricted
931
996
  });
932
997
  return c.json({
933
998
  ...subject,
934
- entitlements: rows.map((row) => adminEntitlementView(row, now))
999
+ entitlements: rows.map((row) => adminEntitlementView(row, now, unrestricted)),
1000
+ unrestricted,
1001
+ overrideVersion: overrideVersion(override),
1002
+ override: adminOverrideView(override),
1003
+ allowances: adminAllowancesView(resolved, (name) => overrideCeiling(config, held, name))
935
1004
  }, 200);
936
1005
  });
937
1006
  /**
@@ -966,6 +1035,30 @@ function registerPaymentsRoutes(options) {
966
1035
  }, 200);
967
1036
  });
968
1037
  /**
1038
+ * CONTROL PLANE. What usage reporting has done — the passes this Worker has run, newest first.
1039
+ *
1040
+ * Its own scope, separate from the reconciliation log's: a run's findings name the subjects it did not
1041
+ * report and why, which is what an operator answering "why was this customer not billed" needs and what a
1042
+ * health monitor does not.
1043
+ */
1044
+ app.get(`${base}/admin/usage-runs`, describeRoute({
1045
+ summary: "Read the usage-reporting passes this deployment has run.",
1046
+ verification: "control-plane",
1047
+ scopes: [PAYMENTS_USAGE_READ_SCOPE],
1048
+ responses: { 200: PaymentsAdminUsageRunsResponse }
1049
+ }), requireControlPlane(PAYMENTS_USAGE_READ_SCOPE), validate("query", AdminUsageRunsQuery), async (c) => {
1050
+ const query = c.req.valid("query");
1051
+ const page = await listUsageRuns(database(c), query);
1052
+ await recordRead(c, PaymentsAuditActions.usageRunsRead, null, {
1053
+ returned: page.items.length,
1054
+ resumed: query.cursor !== void 0
1055
+ });
1056
+ return c.json({
1057
+ runs: page.items.map(adminUsageRunView),
1058
+ nextCursor: page.nextCursor
1059
+ }, 200);
1060
+ });
1061
+ /**
969
1062
  * CONTROL PLANE WRITE. Start a reconciliation pass now.
970
1063
  *
971
1064
  * **The counterpart to the read above, and a different power.** Reading the log says whether the nightly
@@ -1090,9 +1183,23 @@ function registerPaymentsRoutes(options) {
1090
1183
  responses: { 200: PaymentsEntitlementsResponse }
1091
1184
  }), requireAuth(), async (c) => {
1092
1185
  const subject = await resolvePaymentsSubject(c, seam);
1093
- if (subject === void 0) return c.json({ entitlements: [] }, 200);
1094
- const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1095
- return c.json({ entitlements: entitlements.map(entitlementView) }, 200);
1186
+ const now = clock();
1187
+ const db = subject === void 0 ? void 0 : paymentsDatabase(database(c));
1188
+ const input = await allowanceInputFor(db, config, subject, now);
1189
+ const resolved = resolveAllowances(input);
1190
+ const allowances = {
1191
+ quotas: Object.fromEntries(resolved.quotas.map((entry) => [entry.name, entry.effective.value])),
1192
+ features: Object.fromEntries(resolved.features.map((entry) => [entry.name, entry.effective.value]))
1193
+ };
1194
+ if (subject === void 0 || db === void 0) return c.json({
1195
+ entitlements: [],
1196
+ ...allowances
1197
+ }, 200);
1198
+ const entitlements = await resolveEntitlements(db, subject, now);
1199
+ return c.json({
1200
+ entitlements: entitlements.map(entitlementView),
1201
+ ...allowances
1202
+ }, 200);
1096
1203
  });
1097
1204
  /**
1098
1205
  * AUTHED WRITE. Restore Purchases, client-driven because only the device can enumerate what its store
@@ -1250,6 +1357,7 @@ function registerPaymentsRoutes(options) {
1250
1357
  const handoff = await (await checkoutRail(c, rail)).createCheckoutSession({
1251
1358
  providerProductId: sku,
1252
1359
  subscription: entry.product.type === "subscription",
1360
+ reported: entry.product.billing?.kind === "reported",
1253
1361
  subject,
1254
1362
  providerAccountId: await accountFor(c, rail, subject),
1255
1363
  successUrl: settings.successUrl,
@@ -1500,7 +1608,16 @@ function registerPaymentsRoutes(options) {
1500
1608
  deployment: deploymentName(c)
1501
1609
  });
1502
1610
  if (standing === void 0) return c.json({ subscription: null }, 200);
1503
- return c.json({ subscription: subscriptionView(target.purchase.productId, standing) }, 200);
1611
+ const subscriptionId = target.purchase.originalTransactionId;
1612
+ const last = subscriptionId === null ? void 0 : (await lastReports(database(c), [{
1613
+ rail: target.purchase.rail,
1614
+ providerSubscriptionId: subscriptionId
1615
+ }])).get(`${target.purchase.rail}:${subscriptionId}`);
1616
+ return c.json({ subscription: {
1617
+ ...subscriptionView(target.purchase.productId, standing),
1618
+ reportedQuantity: last?.quantity ?? null,
1619
+ reportedAt: last?.reportedAt.toISOString() ?? null
1620
+ } }, 200);
1504
1621
  });
1505
1622
  /**
1506
1623
  * AUTHED READ — what moving to one catalog product would cost, as the store previews it.
@@ -1974,6 +2091,143 @@ function registerPaymentsRoutes(options) {
1974
2091
  expiresAt: revoked.expiresAt
1975
2092
  }) }, 200);
1976
2093
  });
2094
+ /**
2095
+ * The billing-kind check every override write shares, refused exactly as a grant refuses it. An override
2096
+ * keyed on a kind no read path resolves would shade nobody's numbers and answer 200.
2097
+ */
2098
+ function requireBilledKind(subjectType) {
2099
+ if (subjectType === config.billingSubject) return;
2100
+ throw new ValidationError({
2101
+ message: `This project bills ${config.billingSubject}s, not ${subjectType}s.`,
2102
+ action: "Send `subjectType` as the kind this project bills, or change `billingSubject` in pithy.config.ts.",
2103
+ detail: `An override for a ${subjectType} here writes a row keyed on a kind no read path resolves, so it would shade nobody's allowances and the table would say otherwise.`
2104
+ });
2105
+ }
2106
+ /** What every override write answers. */
2107
+ function overrideResponse(subject, change) {
2108
+ return {
2109
+ ...subject,
2110
+ override: adminOverrideView(change.after),
2111
+ version: overrideVersion(change.after)
2112
+ };
2113
+ }
2114
+ /**
2115
+ * The audit event every override write emits — the subject, the mode, the before and the after, and the
2116
+ * reason verbatim. Severity `warning`, as a comp is: nothing else here changes what a customer may have
2117
+ * with no money moving.
2118
+ */
2119
+ async function emitOverride(c, action, subject, mode, reason, change) {
2120
+ const caller = controlPlaneCaller(c);
2121
+ await c.var.emit({
2122
+ action,
2123
+ outcome: "success",
2124
+ severity: "warning",
2125
+ actorType: "control-plane",
2126
+ actorId: caller.subject,
2127
+ resourceType: "entitlement_override",
2128
+ resourceId: encodeSubjectReference(subject),
2129
+ metadata: {
2130
+ connectionId: caller.connectionId,
2131
+ subjectType: subject.subjectType,
2132
+ subjectId: subject.subjectId,
2133
+ mode,
2134
+ reason,
2135
+ before: adminOverrideView(change.before),
2136
+ after: adminOverrideView(change.after)
2137
+ }
2138
+ });
2139
+ }
2140
+ /**
2141
+ * CONTROL PLANE. Pin a negotiated number or switch for one subject.
2142
+ *
2143
+ * **A merge by name, never a replace.** Only the names sent change; every other pin stands and every name
2144
+ * never pinned keeps tracking the plan, so an upgrade still reaches a customer whose email allowance was
2145
+ * negotiated. **Version-checked**: the body names the version it read, and a set behind the row is
2146
+ * `payments/override_stale` with nothing written. **Bounded**: a number past a declared `overrideMax` is a
2147
+ * 400 naming the limit. **Explained**: `reason` is required and the audit event carries it.
2148
+ *
2149
+ * It does not set `unrestricted`, and a body that tries is a 400 rather than a field quietly dropped:
2150
+ * that is the other route, behind its own scope.
2151
+ */
2152
+ app.post(`${base}/entitlements/overrides`, describeRoute({
2153
+ summary: "Pin quotas and features for one subject.",
2154
+ verification: "control-plane",
2155
+ scopes: [PAYMENTS_OVERRIDE_SET_SCOPE],
2156
+ responses: { 200: PaymentsOverrideResponse }
2157
+ }), requireControlPlane(PAYMENTS_OVERRIDE_SET_SCOPE), validate("json", OverrideSetRequest), async (c) => {
2158
+ const input = c.req.valid("json");
2159
+ requireBilledKind(input.subjectType);
2160
+ const subject = {
2161
+ subjectType: input.subjectType,
2162
+ subjectId: input.subjectId
2163
+ };
2164
+ const change = await setOverride(database(c), config, {
2165
+ subject,
2166
+ version: input.version,
2167
+ reason: input.reason,
2168
+ ...input.quotas ? { quotas: input.quotas } : {},
2169
+ ...input.features ? { features: input.features } : {}
2170
+ }, { now: clock() });
2171
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "patch", input.reason, change);
2172
+ return c.json(overrideResponse(subject, change), 200);
2173
+ });
2174
+ /**
2175
+ * CONTROL PLANE. Grant one subject the whole product, or take it back.
2176
+ *
2177
+ * **Its own route and its own scope**, because it is the largest grant the kit has and the only one whose
2178
+ * reach grows by itself as names are declared: a credential that may raise one email cap must not be able
2179
+ * to do this. Never bounded by `overrideMax` — being unbounded is the point. It grants no entitlement key:
2180
+ * a subject holding nothing is still refused at every gate.
2181
+ */
2182
+ app.post(`${base}/entitlements/overrides/unrestricted`, describeRoute({
2183
+ summary: "Turn unrestricted on or off for one subject.",
2184
+ verification: "control-plane",
2185
+ scopes: [PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE],
2186
+ responses: { 200: PaymentsOverrideResponse }
2187
+ }), requireControlPlane(PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE), validate("json", OverrideUnrestrictedRequest), async (c) => {
2188
+ const input = c.req.valid("json");
2189
+ requireBilledKind(input.subjectType);
2190
+ const subject = {
2191
+ subjectType: input.subjectType,
2192
+ subjectId: input.subjectId
2193
+ };
2194
+ const change = await setUnrestricted(database(c), {
2195
+ subject,
2196
+ version: input.version,
2197
+ reason: input.reason,
2198
+ unrestricted: input.unrestricted
2199
+ }, { now: clock() });
2200
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "unrestricted", input.reason, change);
2201
+ return c.json(overrideResponse(subject, change), 200);
2202
+ });
2203
+ /**
2204
+ * CONTROL PLANE. Unpin names for one subject, or clear its override.
2205
+ *
2206
+ * **Idempotent**: a subject with no override answers 200 with nothing changed — the state the caller asked
2207
+ * for — and writes no audit row, because nothing moved. A name unpinned resolves from the plan again.
2208
+ */
2209
+ app.post(`${base}/entitlements/overrides/clear`, describeRoute({
2210
+ summary: "Unpin allowances for one subject, or clear its override.",
2211
+ verification: "control-plane",
2212
+ scopes: [PAYMENTS_OVERRIDE_CLEAR_SCOPE],
2213
+ responses: { 200: PaymentsOverrideResponse }
2214
+ }), requireControlPlane(PAYMENTS_OVERRIDE_CLEAR_SCOPE), validate("json", OverrideClearRequest), async (c) => {
2215
+ const input = c.req.valid("json");
2216
+ requireBilledKind(input.subjectType);
2217
+ const subject = {
2218
+ subjectType: input.subjectType,
2219
+ subjectId: input.subjectId
2220
+ };
2221
+ const change = await clearOverride(database(c), {
2222
+ subject,
2223
+ ...input.version !== void 0 ? { version: input.version } : {},
2224
+ ...input.quotas ? { quotas: input.quotas } : {},
2225
+ ...input.features ? { features: input.features } : {},
2226
+ ...input.reason ? { reason: input.reason } : {}
2227
+ }, { now: clock() });
2228
+ if (change.before !== void 0) await emitOverride(c, PaymentsAuditActions.overrideCleared, subject, "clear", input.reason ?? null, change);
2229
+ return c.json(overrideResponse(subject, change), 200);
2230
+ });
1977
2231
  };
1978
2232
  /**
1979
2233
  * The webhook handler, once, for every rail.