@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.
- package/README.md +10 -3
- package/dist/admin/coverage.d.ts.map +1 -1
- package/dist/admin/coverage.js +26 -2
- package/dist/admin/read.d.ts +48 -1
- package/dist/admin/read.d.ts.map +1 -1
- package/dist/admin/read.js +89 -2
- package/dist/audit/actions.d.ts +13 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +14 -1
- package/dist/capability.d.ts +33 -2
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +52 -9
- package/dist/client/api.d.ts +19 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +34 -1
- package/dist/client/hooks.d.ts +20 -1
- package/dist/client/hooks.d.ts.map +1 -1
- package/dist/client/hooks.js +40 -2
- package/dist/client/projection.d.ts +29 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/config/allowances.d.ts +71 -0
- package/dist/config/allowances.d.ts.map +1 -0
- package/dist/config/allowances.js +115 -0
- package/dist/config/config.d.ts +155 -9
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js +164 -14
- package/dist/data/meterCounter.d.ts +34 -0
- package/dist/data/meterCounter.d.ts.map +1 -0
- package/dist/data/meterCounter.js +33 -0
- package/dist/data/override.d.ts +56 -0
- package/dist/data/override.d.ts.map +1 -0
- package/dist/data/override.js +58 -0
- package/dist/data/period.d.ts +10 -0
- package/dist/data/period.d.ts.map +1 -0
- package/dist/data/period.js +37 -0
- package/dist/data/purchase.d.ts +1 -0
- package/dist/data/purchase.d.ts.map +1 -1
- package/dist/data/purchase.js +1 -0
- package/dist/data/tables.d.ts +17 -1
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +24 -4
- package/dist/data/usageReport.d.ts +68 -0
- package/dist/data/usageReport.d.ts.map +1 -0
- package/dist/data/usageReport.js +55 -0
- package/dist/data/usageRun.d.ts +93 -0
- package/dist/data/usageRun.d.ts.map +1 -0
- package/dist/data/usageRun.js +50 -0
- package/dist/entitlement/allowance.d.ts +100 -0
- package/dist/entitlement/allowance.d.ts.map +1 -0
- package/dist/entitlement/allowance.js +171 -0
- package/dist/entitlement/manual.d.ts +5 -5
- package/dist/entitlement/manual.js +3 -3
- package/dist/entitlement/meter.d.ts +98 -0
- package/dist/entitlement/meter.d.ts.map +1 -0
- package/dist/entitlement/meter.js +177 -0
- package/dist/entitlement/override.d.ts +119 -0
- package/dist/entitlement/override.d.ts.map +1 -0
- package/dist/entitlement/override.js +256 -0
- package/dist/entitlement/resolver.d.ts +2 -1
- package/dist/entitlement/resolver.d.ts.map +1 -1
- package/dist/entitlement/resolver.js +32 -1
- package/dist/error/errors.d.ts +19 -0
- package/dist/error/errors.d.ts.map +1 -1
- package/dist/error/errors.js +35 -2
- package/dist/http/responses.d.ts +367 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +146 -7
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +270 -16
- package/dist/http/schemas.d.ts +54 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +61 -2
- package/dist/http/scopes.d.ts +25 -0
- package/dist/http/scopes.d.ts.map +1 -1
- package/dist/http/scopes.js +60 -1
- package/dist/http/view.d.ts +22 -4
- package/dist/http/view.d.ts.map +1 -1
- package/dist/http/view.js +88 -7
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/migrations/0002_allowances.d.ts +26 -0
- package/dist/migrations/0002_allowances.d.ts.map +1 -0
- package/dist/migrations/0002_allowances.js +62 -0
- package/dist/peer.d.ts +1 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/projection/event.d.ts +1 -0
- package/dist/projection/event.d.ts.map +1 -1
- package/dist/projection/event.js +1 -0
- package/dist/projection/writer.d.ts.map +1 -1
- package/dist/projection/writer.js +3 -1
- package/dist/rails/contract.d.ts +6 -0
- package/dist/rails/contract.d.ts.map +1 -1
- package/dist/rails/google/playApi.d.ts.map +1 -1
- package/dist/rails/google/playApi.js +2 -0
- package/dist/rails/paddle/objects.d.ts +2 -0
- package/dist/rails/paddle/objects.d.ts.map +1 -1
- package/dist/rails/paddle/objects.js +7 -2
- package/dist/rails/paddle/usage.d.ts +11 -0
- package/dist/rails/paddle/usage.d.ts.map +1 -0
- package/dist/rails/paddle/usage.js +49 -0
- package/dist/rails/quantity.d.ts +12 -0
- package/dist/rails/quantity.d.ts.map +1 -0
- package/dist/rails/quantity.js +16 -0
- package/dist/rails/stripe/checkout.d.ts.map +1 -1
- package/dist/rails/stripe/checkout.js +1 -1
- package/dist/rails/stripe/objects.d.ts.map +1 -1
- package/dist/rails/stripe/objects.js +3 -0
- package/dist/rails/stripe/usage.d.ts +10 -0
- package/dist/rails/stripe/usage.d.ts.map +1 -0
- package/dist/rails/stripe/usage.js +49 -0
- package/dist/usage/pass.d.ts +120 -0
- package/dist/usage/pass.d.ts.map +1 -0
- package/dist/usage/pass.js +363 -0
- package/dist/usage/reporter.d.ts +36 -0
- package/dist/usage/reporter.d.ts.map +1 -0
- package/dist/usage/reporter.js +2 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/dist/workflows/specs.d.ts +28 -0
- package/dist/workflows/specs.d.ts.map +1 -1
- package/dist/workflows/specs.js +26 -1
- package/dist/workflows/usage.d.ts +38 -0
- package/dist/workflows/usage.d.ts.map +1 -0
- package/dist/workflows/usage.js +77 -0
- package/dist/workflows/worker.js +2 -2
- package/docs/entitlements.md +249 -0
- package/docs/lemon-squeezy.md +1 -0
- package/docs/paddle.md +1 -0
- package/package.json +5 -5
- package/pithy.manifest.json +3 -8
- package/src/admin/coverage.ts +28 -0
- package/src/admin/read.ts +173 -1
- package/src/audit/actions.ts +13 -0
- package/src/capability.ts +87 -9
- package/src/client/api.ts +44 -0
- package/src/client/hooks.ts +44 -0
- package/src/client/projection.ts +31 -0
- package/src/config/allowances.ts +211 -0
- package/src/config/config.ts +283 -15
- package/src/data/meterCounter.ts +38 -0
- package/src/data/override.ts +74 -0
- package/src/data/period.ts +53 -0
- package/src/data/purchase.ts +9 -0
- package/src/data/tables.ts +25 -1
- package/src/data/usageReport.ts +64 -0
- package/src/data/usageRun.ts +66 -0
- package/src/entitlement/allowance.ts +213 -0
- package/src/entitlement/manual.ts +6 -6
- package/src/entitlement/meter.ts +252 -0
- package/src/entitlement/override.ts +381 -0
- package/src/entitlement/resolver.ts +43 -2
- package/src/error/errors.ts +44 -1
- package/src/http/responses.ts +305 -4
- package/src/http/routes.ts +365 -11
- package/src/http/schemas.ts +139 -1
- package/src/http/scopes.ts +68 -0
- package/src/http/view.ts +112 -7
- package/src/index.ts +18 -0
- package/src/migrations/0002_allowances.ts +149 -0
- package/src/projection/event.ts +9 -0
- package/src/projection/writer.ts +4 -0
- package/src/rails/contract.ts +6 -0
- package/src/rails/google/playApi.ts +2 -0
- package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
- package/src/rails/paddle/objects.ts +6 -0
- package/src/rails/paddle/usage.ts +66 -0
- package/src/rails/quantity.ts +14 -0
- package/src/rails/stripe/checkout.ts +3 -1
- package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
- package/src/rails/stripe/objects.ts +4 -0
- package/src/rails/stripe/usage.ts +61 -0
- package/src/usage/pass.ts +539 -0
- package/src/usage/reporter.ts +38 -0
- package/src/version.generated.ts +1 -1
- package/src/workflows/specs.ts +34 -0
- package/src/workflows/usage.ts +97 -0
package/src/http/schemas.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
|
|
|
5
5
|
import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
|
|
6
6
|
import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
|
|
7
7
|
import { z } from "zod";
|
|
8
|
+
import { AllowanceName, QuotaValue } from "../config/allowances";
|
|
8
9
|
import { DiscountCode, DiscountTerms } from "../data/discount";
|
|
9
10
|
import { isPaddleTransactionId } from "../data/paddleIds";
|
|
10
11
|
import { PurchaseEnvironment } from "../data/purchase";
|
|
@@ -402,7 +403,7 @@ export const EntitlementGrantRequest = z
|
|
|
402
403
|
"The subject to grant. Support acts on somebody else's holding, so this is one of the two routes where the subject is a request field rather than the server's own answer.",
|
|
403
404
|
),
|
|
404
405
|
entitlement: EntitlementKey.describe(
|
|
405
|
-
"The entitlement key to grant, as gating code names it. Not a store SKU. It must be one
|
|
406
|
+
"The entitlement key to grant, as gating code names it. Not a store SKU. It must be one the `entitlements` map declares, and anything else is a 400 naming the key. Comping a key nothing sells is still the durable case; declaring it with no product behind it is how a project says so.",
|
|
406
407
|
),
|
|
407
408
|
expiresAt: JsonDate.optional().describe(
|
|
408
409
|
"When the grant lapses, as an ISO 8601 timestamp. Omit for a comp that never ends. A past timestamp writes a row that grants nothing, which is a slower way of revoking.",
|
|
@@ -431,6 +432,124 @@ export const EntitlementRevokeRequest = z
|
|
|
431
432
|
.describe("A control-plane request to revoke one entitlement from one subject, effective immediately.");
|
|
432
433
|
export type EntitlementRevokeRequest = z.output<typeof EntitlementRevokeRequest>;
|
|
433
434
|
|
|
435
|
+
/**
|
|
436
|
+
* ## The override writes
|
|
437
|
+
*
|
|
438
|
+
* Three routes, three scopes, and the split is the security core of them. **Set** pins numbers and switches;
|
|
439
|
+
* **unrestricted** hands a subject the whole product; **clear** removes pins. A credential that may raise one
|
|
440
|
+
* customer's email cap must not, by that fact, be able to hand anybody everything — so `unrestricted` is not a
|
|
441
|
+
* field on the set, and every one of these is a `strictObject`: a set body carrying `unrestricted: true` is a
|
|
442
|
+
* 400, never a field quietly dropped while the caller believes it took.
|
|
443
|
+
*
|
|
444
|
+
* **Both halves of the subject, a version, and on a set a reason.** The version is the one the caller read;
|
|
445
|
+
* a write behind the row is refused as stale. The reason is required because an override is a sentence about a
|
|
446
|
+
* commercial decision, and the audit event records it verbatim.
|
|
447
|
+
*
|
|
448
|
+
* Whether a name is declared, and whether a number is under its ceiling, are config-backed questions and stay
|
|
449
|
+
* in the handler: a schema constrains a value, it never replaces a lookup. What the schema does refuse is the
|
|
450
|
+
* shape — a float, a negative, a string where a quota belongs — as `validation/invalid_input`.
|
|
451
|
+
*/
|
|
452
|
+
|
|
453
|
+
/** The longest reason a write may carry. A sentence, a ticket number, a contract reference — not a document. */
|
|
454
|
+
const MAX_OVERRIDE_REASON_LENGTH = 500;
|
|
455
|
+
|
|
456
|
+
/** The most names one write may carry. Far past any real catalog; bounded because a verified client can still loop. */
|
|
457
|
+
const MAX_OVERRIDE_NAMES = 100;
|
|
458
|
+
|
|
459
|
+
const OverrideSubjectType = PaymentsSubject.shape.subjectType.describe(
|
|
460
|
+
"Which kind of holder the override is for. Named, never assumed — and refused when it is not the kind this project bills.",
|
|
461
|
+
);
|
|
462
|
+
const OverrideSubjectId = PaymentsSubject.shape.subjectId.describe("The subject whose allowances this shades.");
|
|
463
|
+
const OverrideVersion = z
|
|
464
|
+
.number()
|
|
465
|
+
.int()
|
|
466
|
+
.min(0)
|
|
467
|
+
.describe(
|
|
468
|
+
"The override version the caller read — `0` when the subject had none. A write naming a version behind the row is refused with `payments/override_stale` and changes nothing.",
|
|
469
|
+
);
|
|
470
|
+
const OverrideReason = z
|
|
471
|
+
.string()
|
|
472
|
+
.trim()
|
|
473
|
+
.min(1)
|
|
474
|
+
.max(MAX_OVERRIDE_REASON_LENGTH)
|
|
475
|
+
.describe("Why — a contract, a goodwill credit, a migration. Required, and recorded verbatim on the audit event.");
|
|
476
|
+
|
|
477
|
+
export const OverrideSetRequest = z
|
|
478
|
+
.strictObject({
|
|
479
|
+
subjectType: OverrideSubjectType,
|
|
480
|
+
subjectId: OverrideSubjectId,
|
|
481
|
+
version: OverrideVersion,
|
|
482
|
+
reason: OverrideReason,
|
|
483
|
+
quotas: z
|
|
484
|
+
.record(AllowanceName, QuotaValue)
|
|
485
|
+
.optional()
|
|
486
|
+
.describe(
|
|
487
|
+
"Quotas to pin, by name — a whole number from 0, or null for unlimited. Merged: a name absent here keeps whatever it had.",
|
|
488
|
+
),
|
|
489
|
+
features: z
|
|
490
|
+
.record(AllowanceName, z.boolean().describe("Whether the switch is on."))
|
|
491
|
+
.optional()
|
|
492
|
+
.describe("Features to pin, by name. Merged: a name absent here keeps whatever it had."),
|
|
493
|
+
})
|
|
494
|
+
.refine((body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length > 0, {
|
|
495
|
+
message: "Name at least one quota or feature to pin.",
|
|
496
|
+
})
|
|
497
|
+
.refine(
|
|
498
|
+
(body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length <= MAX_OVERRIDE_NAMES,
|
|
499
|
+
{
|
|
500
|
+
message: `Pin at most ${MAX_OVERRIDE_NAMES} names in one write.`,
|
|
501
|
+
},
|
|
502
|
+
)
|
|
503
|
+
.describe(
|
|
504
|
+
"A control-plane request to pin quotas and features for one subject. A merge by name, version-checked, with a reason.",
|
|
505
|
+
);
|
|
506
|
+
export type OverrideSetRequest = z.output<typeof OverrideSetRequest>;
|
|
507
|
+
|
|
508
|
+
export const OverrideUnrestrictedRequest = z
|
|
509
|
+
.strictObject({
|
|
510
|
+
subjectType: OverrideSubjectType,
|
|
511
|
+
subjectId: OverrideSubjectId,
|
|
512
|
+
version: OverrideVersion,
|
|
513
|
+
reason: OverrideReason,
|
|
514
|
+
unrestricted: z
|
|
515
|
+
.boolean()
|
|
516
|
+
.describe(
|
|
517
|
+
"True grants every quota unlimited and every feature on, for every name declared now and later, except the names the override pins. False takes it back and leaves the pins.",
|
|
518
|
+
),
|
|
519
|
+
})
|
|
520
|
+
.describe(
|
|
521
|
+
"A control-plane request to turn `unrestricted` on or off for one subject. Its own route, behind its own scope.",
|
|
522
|
+
);
|
|
523
|
+
export type OverrideUnrestrictedRequest = z.output<typeof OverrideUnrestrictedRequest>;
|
|
524
|
+
|
|
525
|
+
export const OverrideClearRequest = z
|
|
526
|
+
.strictObject({
|
|
527
|
+
subjectType: OverrideSubjectType,
|
|
528
|
+
subjectId: OverrideSubjectId,
|
|
529
|
+
version: OverrideVersion.optional().describe(
|
|
530
|
+
"The override version the caller read. Optional: sent, a clear behind the row is refused as stale; omitted, the clear is not checked, which is safe because a clear can only move a subject back toward its plan — unpinning a name on an unrestricted subject is refused.",
|
|
531
|
+
),
|
|
532
|
+
reason: OverrideReason.optional().describe("Why, when the caller says. Recorded on the audit event."),
|
|
533
|
+
quotas: z
|
|
534
|
+
.array(AllowanceName)
|
|
535
|
+
.max(MAX_OVERRIDE_NAMES)
|
|
536
|
+
.optional()
|
|
537
|
+
.describe(
|
|
538
|
+
"Quota pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to unlimited.",
|
|
539
|
+
),
|
|
540
|
+
features: z
|
|
541
|
+
.array(AllowanceName)
|
|
542
|
+
.max(MAX_OVERRIDE_NAMES)
|
|
543
|
+
.optional()
|
|
544
|
+
.describe(
|
|
545
|
+
"Feature pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to on.",
|
|
546
|
+
),
|
|
547
|
+
})
|
|
548
|
+
.describe(
|
|
549
|
+
"A control-plane request to unpin names, or — naming neither list — to clear the subject's override entirely, `unrestricted` included. Idempotent: clearing nothing answers 200. A clear never resets the version.",
|
|
550
|
+
);
|
|
551
|
+
export type OverrideClearRequest = z.output<typeof OverrideClearRequest>;
|
|
552
|
+
|
|
434
553
|
/**
|
|
435
554
|
* ## The management read queries
|
|
436
555
|
*
|
|
@@ -539,6 +658,20 @@ export const AdminEntitlementsQuery = z
|
|
|
539
658
|
.describe("The entitlement query: what to narrow it to, and where to resume.");
|
|
540
659
|
export type AdminEntitlementsQuery = z.output<typeof AdminEntitlementsQuery>;
|
|
541
660
|
|
|
661
|
+
export const AdminOverridesQuery = z
|
|
662
|
+
.object({
|
|
663
|
+
...SUBJECT_FILTER,
|
|
664
|
+
unrestricted: z
|
|
665
|
+
.enum(["true", "false"])
|
|
666
|
+
.optional()
|
|
667
|
+
.describe("`true` lists only the subjects that are `unrestricted` — the largest grant the kit has."),
|
|
668
|
+
cursor: Cursor,
|
|
669
|
+
limit: Limit,
|
|
670
|
+
})
|
|
671
|
+
.refine(subjectFilterIsWhole, SUBJECT_FILTER_RULE)
|
|
672
|
+
.describe("The override listing query: a holder, whether unrestricted, and where to resume.");
|
|
673
|
+
export type AdminOverridesQuery = z.output<typeof AdminOverridesQuery>;
|
|
674
|
+
|
|
542
675
|
export const AdminReconcileRunsQuery = z
|
|
543
676
|
.object({
|
|
544
677
|
rail: PaymentsRail.optional().describe(
|
|
@@ -553,6 +686,11 @@ export const AdminReconcileRunsQuery = z
|
|
|
553
686
|
.describe("The reconciliation-run query: what to narrow it to, and where to resume.");
|
|
554
687
|
export type AdminReconcileRunsQuery = z.output<typeof AdminReconcileRunsQuery>;
|
|
555
688
|
|
|
689
|
+
export const AdminUsageRunsQuery = z
|
|
690
|
+
.object({ cursor: Cursor, limit: Limit })
|
|
691
|
+
.describe("The usage-run query: where to resume, and how many.");
|
|
692
|
+
export type AdminUsageRunsQuery = z.output<typeof AdminUsageRunsQuery>;
|
|
693
|
+
|
|
556
694
|
/**
|
|
557
695
|
* The two path segments on the per-subject management read: `…/entitlements/:subjectType/:subjectId`.
|
|
558
696
|
*
|
package/src/http/scopes.ts
CHANGED
|
@@ -143,6 +143,35 @@ export const PAYMENTS_RECONCILE_READ_SCOPE: ControlPlaneScope = "payments:reconc
|
|
|
143
143
|
*/
|
|
144
144
|
export const PAYMENTS_RECONCILE_RUN_SCOPE: ControlPlaneScope = "payments:reconcile:run";
|
|
145
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Pin a number or a switch for one subject — a negotiated email allowance, a goodwill seat. A merge by name,
|
|
148
|
+
* version-checked, with a reason on the record and bounded by any `overrideMax` the catalog declares.
|
|
149
|
+
*
|
|
150
|
+
* **It does not confer `unrestricted`.** A credential that may raise one customer's email cap must not, by
|
|
151
|
+
* that fact, be able to hand anybody the entire product.
|
|
152
|
+
*/
|
|
153
|
+
export const PAYMENTS_OVERRIDE_SET_SCOPE: ControlPlaneScope = "payments:overrides:set";
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Turn `unrestricted` on or off for one subject: every quota unlimited and every feature on, for every name
|
|
157
|
+
* declared now and every name declared later. **The largest grant the kit has**, and the only one whose reach
|
|
158
|
+
* grows by itself, which is why it is its own scope and its own route — never a field on the set.
|
|
159
|
+
*/
|
|
160
|
+
export const PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE: ControlPlaneScope = "payments:overrides:unrestricted";
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Remove pins from one subject's override, or the whole override. Separate from setting, the way revoke is
|
|
164
|
+
* separate from grant: a tool that tidies up after a contract ends needs to clear and has no business
|
|
165
|
+
* pinning.
|
|
166
|
+
*/
|
|
167
|
+
export const PAYMENTS_OVERRIDE_CLEAR_SCOPE: ControlPlaneScope = "payments:overrides:clear";
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Read the usage-reporting run log — when each pass ran, what it reported, and which subjects it skipped and
|
|
171
|
+
* why. Its own scope, separate from the reconciliation log's: its findings name subjects.
|
|
172
|
+
*/
|
|
173
|
+
export const PAYMENTS_USAGE_READ_SCOPE: ControlPlaneScope = "payments:usage:read";
|
|
174
|
+
|
|
146
175
|
/**
|
|
147
176
|
* Every control-plane scope payments defines — what `pithy dashboard connect` offers for this capability, and
|
|
148
177
|
* the list a manifest or a doc quotes rather than re-typing. Core's `SEAM_SCOPES` is the same idea for the
|
|
@@ -158,8 +187,12 @@ export const PAYMENTS_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
|
158
187
|
PAYMENTS_ENTITLEMENTS_READ_SCOPE,
|
|
159
188
|
PAYMENTS_DISCOUNT_READ_SCOPE,
|
|
160
189
|
PAYMENTS_RECONCILE_READ_SCOPE,
|
|
190
|
+
PAYMENTS_USAGE_READ_SCOPE,
|
|
161
191
|
PAYMENTS_ENTITLEMENT_GRANT_SCOPE,
|
|
162
192
|
PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
|
|
193
|
+
PAYMENTS_OVERRIDE_SET_SCOPE,
|
|
194
|
+
PAYMENTS_OVERRIDE_CLEAR_SCOPE,
|
|
195
|
+
PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
|
|
163
196
|
PAYMENTS_DISCOUNT_CREATE_SCOPE,
|
|
164
197
|
PAYMENTS_RECONCILE_RUN_SCOPE,
|
|
165
198
|
];
|
|
@@ -256,5 +289,40 @@ export function paymentsAdminRoutes(basePath: string): AdminRoute[] {
|
|
|
256
289
|
scope: PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
|
|
257
290
|
summary: "Take an entitlement back, effective immediately.",
|
|
258
291
|
},
|
|
292
|
+
{
|
|
293
|
+
method: "GET",
|
|
294
|
+
path: `${basePath}/admin/usage-runs`,
|
|
295
|
+
scope: PAYMENTS_USAGE_READ_SCOPE,
|
|
296
|
+
summary:
|
|
297
|
+
"The usage-reporting passes this deployment has run — what each reported, and which subjects it skipped and why. The answer to why a quantity-billed customer was not billed.",
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
method: "GET",
|
|
301
|
+
path: `${basePath}/admin/overrides`,
|
|
302
|
+
scope: PAYMENTS_ENTITLEMENTS_READ_SCOPE,
|
|
303
|
+
summary:
|
|
304
|
+
"Page every subject's override — the numbers negotiated per customer, and which subjects are unrestricted.",
|
|
305
|
+
},
|
|
306
|
+
{
|
|
307
|
+
method: "POST",
|
|
308
|
+
path: `${basePath}/entitlements/overrides`,
|
|
309
|
+
scope: PAYMENTS_OVERRIDE_SET_SCOPE,
|
|
310
|
+
summary:
|
|
311
|
+
"Pin a negotiated number or switch for one subject, with a reason on the record. Merges by name; every other allowance keeps tracking the plan.",
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
method: "POST",
|
|
315
|
+
path: `${basePath}/entitlements/overrides/unrestricted`,
|
|
316
|
+
scope: PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
|
|
317
|
+
summary:
|
|
318
|
+
"Grant one subject the whole product — every quota unlimited and every feature on, including names declared later — or take it back.",
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
method: "POST",
|
|
322
|
+
path: `${basePath}/entitlements/overrides/clear`,
|
|
323
|
+
scope: PAYMENTS_OVERRIDE_CLEAR_SCOPE,
|
|
324
|
+
summary:
|
|
325
|
+
"Unpin allowances for one subject, or clear its override entirely. Unpinned names follow the plan again.",
|
|
326
|
+
},
|
|
259
327
|
];
|
|
260
328
|
}
|
package/src/http/view.ts
CHANGED
|
@@ -2,15 +2,21 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { PaymentsPurchaseRecord } from "../admin/read";
|
|
5
|
-
import type
|
|
5
|
+
import { compOnlyEntitlements, type PaymentsConfig } from "../config/config";
|
|
6
6
|
import type { PaymentsEntitlement } from "../data/entitlement";
|
|
7
|
+
import { isEmptyOverride, type PaymentsOverride } from "../data/override";
|
|
7
8
|
import type { PaymentsReconcileRun } from "../data/reconcileRun";
|
|
9
|
+
import type { PaymentsUsageRun } from "../data/usageRun";
|
|
10
|
+
import type { ResolvedAllowances } from "../entitlement/allowance";
|
|
8
11
|
import type { PurchaseProjection } from "../projection/writer";
|
|
9
12
|
import type {
|
|
13
|
+
PaymentsAdminAllowancesView,
|
|
10
14
|
PaymentsAdminCatalogResponse,
|
|
11
15
|
PaymentsAdminEntitlementView,
|
|
16
|
+
PaymentsAdminOverrideView,
|
|
12
17
|
PaymentsAdminPurchaseView,
|
|
13
18
|
PaymentsAdminReconcileRunView,
|
|
19
|
+
PaymentsAdminUsageRunView,
|
|
14
20
|
PaymentsEntitlementView,
|
|
15
21
|
PaymentsPurchaseView,
|
|
16
22
|
} from "./responses";
|
|
@@ -109,16 +115,43 @@ export function adminCatalogView(config: PaymentsConfig): PaymentsAdminCatalogRe
|
|
|
109
115
|
name: product.name,
|
|
110
116
|
entitlements: [...product.entitlements],
|
|
111
117
|
}));
|
|
112
|
-
const
|
|
113
|
-
|
|
118
|
+
const compOnly = compOnlyEntitlements(config);
|
|
119
|
+
const sold = new Set(products.flatMap((product) => product.entitlements));
|
|
120
|
+
const entitlements = Object.entries(config.entitlements).map(([key, declaration]) => ({
|
|
121
|
+
key,
|
|
122
|
+
name: declaration.name,
|
|
123
|
+
quotas: { ...declaration.quotas },
|
|
124
|
+
features: { ...declaration.features },
|
|
125
|
+
overrideMax: { ...(declaration.overrideMax ?? {}) },
|
|
126
|
+
sold: sold.has(key),
|
|
127
|
+
}));
|
|
128
|
+
if (products.length === 0 && entitlements.length === 0) return { enabled: false };
|
|
114
129
|
// Catalog order, not sorted: the order an adopter wrote their products in is the order a list should
|
|
115
|
-
// show them, exactly as the client projection argues.
|
|
116
|
-
|
|
130
|
+
// show them, exactly as the client projection argues. Declarations keep the order they were written in
|
|
131
|
+
// for the same reason.
|
|
132
|
+
return {
|
|
133
|
+
enabled: true,
|
|
134
|
+
products,
|
|
135
|
+
manualEntitlements: compOnly,
|
|
136
|
+
entitlements,
|
|
137
|
+
defaults:
|
|
138
|
+
config.defaults === undefined
|
|
139
|
+
? null
|
|
140
|
+
: { quotas: { ...config.defaults.quotas }, features: { ...config.defaults.features } },
|
|
141
|
+
};
|
|
117
142
|
}
|
|
118
143
|
|
|
119
144
|
/** Project one purchase for a management client. The record's columns, verbatim, with dates as strings. */
|
|
120
|
-
export function adminPurchaseView(
|
|
145
|
+
export function adminPurchaseView(
|
|
146
|
+
purchase: PaymentsPurchaseRecord,
|
|
147
|
+
reported?: { quantity: number; reportedAt: Date } | null,
|
|
148
|
+
): PaymentsAdminPurchaseView {
|
|
121
149
|
return {
|
|
150
|
+
quantity: purchase.quantity ?? null,
|
|
151
|
+
// Only a subscription read has asked; the purchase log leaves both absent rather than claiming none.
|
|
152
|
+
...(reported === undefined
|
|
153
|
+
? {}
|
|
154
|
+
: { reportedQuantity: reported?.quantity ?? null, reportedAt: reported?.reportedAt.toISOString() ?? null }),
|
|
122
155
|
id: purchase.id,
|
|
123
156
|
subjectType: purchase.subjectType,
|
|
124
157
|
subjectId: purchase.subjectId,
|
|
@@ -147,7 +180,11 @@ export function adminPurchaseView(purchase: PaymentsPurchaseRecord): PaymentsAdm
|
|
|
147
180
|
* and the gate the adopter's own app calls applies the timestamp on every request. A dashboard that
|
|
148
181
|
* rendered the flag would disagree with that gate, and the customer would believe the dashboard.
|
|
149
182
|
*/
|
|
150
|
-
export function adminEntitlementView(
|
|
183
|
+
export function adminEntitlementView(
|
|
184
|
+
row: PaymentsEntitlement,
|
|
185
|
+
now: Date,
|
|
186
|
+
unrestricted = false,
|
|
187
|
+
): PaymentsAdminEntitlementView {
|
|
151
188
|
const lapsed = row.expiresAt !== null && row.expiresAt.getTime() <= now.getTime();
|
|
152
189
|
return {
|
|
153
190
|
subjectType: row.subjectType,
|
|
@@ -157,6 +194,74 @@ export function adminEntitlementView(row: PaymentsEntitlement, now: Date): Payme
|
|
|
157
194
|
expiresAt: row.expiresAt?.toISOString() ?? null,
|
|
158
195
|
manual: row.manual,
|
|
159
196
|
source: row.sourcePurchaseId,
|
|
197
|
+
unrestricted,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Project one usage run for a management client. The row's columns, dates as ISO strings. */
|
|
202
|
+
export function adminUsageRunView(run: PaymentsUsageRun): PaymentsAdminUsageRunView {
|
|
203
|
+
return {
|
|
204
|
+
id: run.id,
|
|
205
|
+
startedAt: run.startedAt.toISOString(),
|
|
206
|
+
finishedAt: run.finishedAt.toISOString(),
|
|
207
|
+
scanned: run.scanned,
|
|
208
|
+
reported: run.reported,
|
|
209
|
+
sampled: run.sampled,
|
|
210
|
+
alreadyReported: run.alreadyReported,
|
|
211
|
+
skipped: run.skipped,
|
|
212
|
+
invalid: run.invalid,
|
|
213
|
+
failed: run.failed,
|
|
214
|
+
findings: run.findings.map((finding) => ({ ...finding })),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Project one subject's override for a management client, or null when it has none. */
|
|
219
|
+
export function adminOverrideView(row: PaymentsOverride | undefined): PaymentsAdminOverrideView | null {
|
|
220
|
+
// A cleared row is kept only for its version — it overrides nothing, so it shows as no override.
|
|
221
|
+
return row === undefined || isEmptyOverride(row) ? null : overrideView(row);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Project one override row for a management client. */
|
|
225
|
+
export function overrideView(row: PaymentsOverride): PaymentsAdminOverrideView {
|
|
226
|
+
return {
|
|
227
|
+
version: row.version,
|
|
228
|
+
unrestricted: row.unrestricted,
|
|
229
|
+
quotas: { ...row.quotas },
|
|
230
|
+
features: { ...row.features },
|
|
231
|
+
reason: row.reason,
|
|
232
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Project every declared allowance for one subject: effective, provenance and inherited per name, plus the
|
|
238
|
+
* ceiling an override of each quota is bounded by for this subject. What an override editor draws its rows
|
|
239
|
+
* from.
|
|
240
|
+
*/
|
|
241
|
+
export function adminAllowancesView(
|
|
242
|
+
resolved: ResolvedAllowances,
|
|
243
|
+
ceiling: (name: string) => number | undefined,
|
|
244
|
+
): PaymentsAdminAllowancesView {
|
|
245
|
+
return {
|
|
246
|
+
quotas: resolved.quotas.map((quota) => ({
|
|
247
|
+
name: quota.name,
|
|
248
|
+
effective: quota.effective.value,
|
|
249
|
+
source: quota.effective.source,
|
|
250
|
+
key: quota.effective.key,
|
|
251
|
+
inherited: quota.inherited.value,
|
|
252
|
+
inheritedSource: quota.inherited.source,
|
|
253
|
+
inheritedKey: quota.inherited.key,
|
|
254
|
+
overrideMax: ceiling(quota.name) ?? null,
|
|
255
|
+
})),
|
|
256
|
+
features: resolved.features.map((feature) => ({
|
|
257
|
+
name: feature.name,
|
|
258
|
+
effective: feature.effective.value,
|
|
259
|
+
source: feature.effective.source,
|
|
260
|
+
key: feature.effective.key,
|
|
261
|
+
inherited: feature.inherited.value,
|
|
262
|
+
inheritedSource: feature.inherited.source,
|
|
263
|
+
inheritedKey: feature.inherited.key,
|
|
264
|
+
})),
|
|
160
265
|
};
|
|
161
266
|
}
|
|
162
267
|
|
package/src/index.ts
CHANGED
|
@@ -30,8 +30,20 @@ export {
|
|
|
30
30
|
payments,
|
|
31
31
|
} from "./capability";
|
|
32
32
|
export {
|
|
33
|
+
AllowanceName,
|
|
34
|
+
declaredFeatureNames,
|
|
35
|
+
declaredQuotaNames,
|
|
36
|
+
PaymentsAllowanceDefaults,
|
|
37
|
+
PaymentsEntitlementDeclaration,
|
|
38
|
+
type PaymentsEntitlementDeclarationInput,
|
|
39
|
+
QuotaValue,
|
|
40
|
+
} from "./config/allowances";
|
|
41
|
+
export {
|
|
42
|
+
compOnlyEntitlements,
|
|
33
43
|
entitlementsForProduct,
|
|
34
44
|
grantableEntitlements,
|
|
45
|
+
KIT_METERS,
|
|
46
|
+
type KitMeter,
|
|
35
47
|
PaymentsAppleProduct,
|
|
36
48
|
type PaymentsCatalogEntry,
|
|
37
49
|
PaymentsConfig,
|
|
@@ -41,6 +53,7 @@ export {
|
|
|
41
53
|
PaymentsLedgerGrant,
|
|
42
54
|
PaymentsLemonSqueezyProduct,
|
|
43
55
|
PaymentsLemonSqueezySettings,
|
|
56
|
+
PaymentsMeters,
|
|
44
57
|
PaymentsPaddleProduct,
|
|
45
58
|
PaymentsPaddleSettings,
|
|
46
59
|
type PaymentsPaddleSettingsInput,
|
|
@@ -49,12 +62,17 @@ export {
|
|
|
49
62
|
PaymentsProductType,
|
|
50
63
|
PaymentsRailToggles,
|
|
51
64
|
type PaymentsRailTogglesInput,
|
|
65
|
+
PaymentsReportCadence,
|
|
66
|
+
PaymentsReportedBilling,
|
|
52
67
|
PaymentsStripeProduct,
|
|
53
68
|
PaymentsStripeSettings,
|
|
54
69
|
type PaymentsStripeSettingsInput,
|
|
55
70
|
productForProviderSku,
|
|
56
71
|
providerProductId,
|
|
72
|
+
REPORTED_BILLING_RAILS,
|
|
57
73
|
railEnabled,
|
|
74
|
+
reportedBillingProblems,
|
|
75
|
+
reportedProducts,
|
|
58
76
|
resolveProduct,
|
|
59
77
|
} from "./config/config";
|
|
60
78
|
export { PaymentsEntitlement } from "./data/entitlement";
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type Kysely, sql } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Allowances, meters and reported usage: four tables and one column.
|
|
9
|
+
*
|
|
10
|
+
* **A new migration, because `0001` is history.** Every payments chain has been running since 0.1.0, and
|
|
11
|
+
* reshaping `0001` would reshape a database somebody is already running. So everything lands here, with a
|
|
12
|
+
* tested `down`.
|
|
13
|
+
*
|
|
14
|
+
* - `pithy_payments_overrides` — one subject's override, `UNIQUE (subjectType, subjectId)`. Keyed on the
|
|
15
|
+
* subject rather than on an entitlement key, so it survives a tier change.
|
|
16
|
+
* - `pithy_payments_meter_counters` — one subject's use of one kit meter in one period,
|
|
17
|
+
* `UNIQUE (subjectType, subjectId, meter, periodStart)`. The period is half the key, which is what makes a
|
|
18
|
+
* new period start at zero with nothing to reset it.
|
|
19
|
+
* - `pithy_payments_usage_reports` — one reported period of one quantity-billed subscription,
|
|
20
|
+
* `UNIQUE (rail, providerSubscriptionId, period)`. The key is the idempotency: a replayed run finds the row.
|
|
21
|
+
* - `pithy_payments_usage_runs` — one reporting pass, its tally kept, the way reconcile runs are.
|
|
22
|
+
* - `pithy_payments_purchases.quantity` — how many were bought, as the store states it. Nullable, because
|
|
23
|
+
* rows written before this did not record one and no store is asked again to invent it.
|
|
24
|
+
*
|
|
25
|
+
* The subject kind is closed with a `CHECK` on every subject-bearing table, as `0001` closes it, and every
|
|
26
|
+
* count a row holds is checked non-negative: a negative usage is a bug in the writer, never a fact.
|
|
27
|
+
*/
|
|
28
|
+
export const payments_0002_allowances: Migration = {
|
|
29
|
+
up: async (db: Kysely<unknown>): Promise<void> => {
|
|
30
|
+
await db.schema.alterTable("pithyPaymentsPurchases").addColumn("quantity", "integer").execute();
|
|
31
|
+
|
|
32
|
+
await db.schema
|
|
33
|
+
.createTable("pithyPaymentsOverrides")
|
|
34
|
+
.addColumn("id", "text", (c) => c.primaryKey())
|
|
35
|
+
.addColumn("subjectType", "text", (c) => c.notNull())
|
|
36
|
+
.addColumn("subjectId", "text", (c) => c.notNull())
|
|
37
|
+
.addColumn("unrestricted", "integer", (c) => c.notNull().defaultTo(0))
|
|
38
|
+
.addColumn("quotas", "text", (c) => c.notNull())
|
|
39
|
+
.addColumn("features", "text", (c) => c.notNull())
|
|
40
|
+
.addColumn("version", "integer", (c) => c.notNull())
|
|
41
|
+
.addColumn("reason", "text", (c) => c.notNull())
|
|
42
|
+
.addColumn("createdAt", "integer", (c) => c.notNull())
|
|
43
|
+
.addColumn("updatedAt", "integer", (c) => c.notNull())
|
|
44
|
+
// One override per subject. The conflict target every write is checked against, and the reason a
|
|
45
|
+
// tier change cannot take an override with it: nothing about a key is in it.
|
|
46
|
+
.addUniqueConstraint("pithyPaymentsOverridesSubjectIdx", ["subjectType", "subjectId"])
|
|
47
|
+
.addCheckConstraint("pithyPaymentsOverridesSubjectType", sql`subject_type in ('user', 'organization')`)
|
|
48
|
+
.addCheckConstraint("pithyPaymentsOverridesUnrestricted", sql`unrestricted in (0, 1)`)
|
|
49
|
+
.addCheckConstraint("pithyPaymentsOverridesVersion", sql`version >= 1`)
|
|
50
|
+
.execute();
|
|
51
|
+
|
|
52
|
+
// `GET {base}/admin/overrides`, newest change first, keyset-paged on the id like every listing here.
|
|
53
|
+
await db.schema
|
|
54
|
+
.createIndex("pithyPaymentsOverridesUpdatedIdx")
|
|
55
|
+
.on("pithyPaymentsOverrides")
|
|
56
|
+
.columns(["updatedAt", "id"])
|
|
57
|
+
.execute();
|
|
58
|
+
|
|
59
|
+
// `pithy doctor` names every unrestricted subject. The largest grant the kit has must never be a row
|
|
60
|
+
// nobody can find, so the read that finds them is an index range rather than a scan.
|
|
61
|
+
await db.schema
|
|
62
|
+
.createIndex("pithyPaymentsOverridesUnrestrictedIdx")
|
|
63
|
+
.on("pithyPaymentsOverrides")
|
|
64
|
+
.columns(["unrestricted", "subjectType", "subjectId"])
|
|
65
|
+
.execute();
|
|
66
|
+
|
|
67
|
+
await db.schema
|
|
68
|
+
.createTable("pithyPaymentsMeterCounters")
|
|
69
|
+
.addColumn("id", "text", (c) => c.primaryKey())
|
|
70
|
+
.addColumn("subjectType", "text", (c) => c.notNull())
|
|
71
|
+
.addColumn("subjectId", "text", (c) => c.notNull())
|
|
72
|
+
.addColumn("meter", "text", (c) => c.notNull())
|
|
73
|
+
.addColumn("periodStart", "integer", (c) => c.notNull())
|
|
74
|
+
.addColumn("used", "integer", (c) => c.notNull().defaultTo(0))
|
|
75
|
+
.addColumn("createdAt", "integer", (c) => c.notNull())
|
|
76
|
+
.addColumn("updatedAt", "integer", (c) => c.notNull())
|
|
77
|
+
// The upsert conflict target the conditional charge is written against. One row per period: the
|
|
78
|
+
// charge and the limit check are one statement on it, so a concurrent burst is serialized by SQLite.
|
|
79
|
+
.addUniqueConstraint("pithyPaymentsMeterCountersPeriodIdx", ["subjectType", "subjectId", "meter", "periodStart"])
|
|
80
|
+
.addCheckConstraint("pithyPaymentsMeterCountersSubjectType", sql`subject_type in ('user', 'organization')`)
|
|
81
|
+
.addCheckConstraint("pithyPaymentsMeterCountersUsed", sql`used >= 0`)
|
|
82
|
+
.execute();
|
|
83
|
+
|
|
84
|
+
await db.schema
|
|
85
|
+
.createTable("pithyPaymentsUsageReports")
|
|
86
|
+
.addColumn("id", "text", (c) => c.primaryKey())
|
|
87
|
+
.addColumn("rail", "text", (c) => c.notNull())
|
|
88
|
+
.addColumn("providerSubscriptionId", "text", (c) => c.notNull())
|
|
89
|
+
.addColumn("purchaseId", "text", (c) => c.notNull())
|
|
90
|
+
.addColumn("productId", "text", (c) => c.notNull())
|
|
91
|
+
.addColumn("subjectType", "text", (c) => c.notNull())
|
|
92
|
+
.addColumn("subjectId", "text", (c) => c.notNull())
|
|
93
|
+
.addColumn("cadence", "text", (c) => c.notNull())
|
|
94
|
+
.addColumn("period", "text", (c) => c.notNull())
|
|
95
|
+
.addColumn("quantity", "integer", (c) => c.notNull())
|
|
96
|
+
.addColumn("status", "text", (c) => c.notNull())
|
|
97
|
+
.addColumn("sampledAt", "integer", (c) => c.notNull())
|
|
98
|
+
.addColumn("reportedAt", "integer")
|
|
99
|
+
.addColumn("createdAt", "integer", (c) => c.notNull())
|
|
100
|
+
.addColumn("updatedAt", "integer", (c) => c.notNull())
|
|
101
|
+
// The idempotency key: one row per period of one subscription on one store. Reporting a period twice
|
|
102
|
+
// is a second insert against this, and it is refused.
|
|
103
|
+
.addUniqueConstraint("pithyPaymentsUsageReportsPeriodIdx", ["rail", "providerSubscriptionId", "period"])
|
|
104
|
+
.addCheckConstraint("pithyPaymentsUsageReportsSubjectType", sql`subject_type in ('user', 'organization')`)
|
|
105
|
+
.addCheckConstraint("pithyPaymentsUsageReportsCadence", sql`cadence in ('period-end', 'daily-peak')`)
|
|
106
|
+
.addCheckConstraint("pithyPaymentsUsageReportsStatus", sql`status in ('sampling', 'claimed', 'reported')`)
|
|
107
|
+
.addCheckConstraint("pithyPaymentsUsageReportsQuantity", sql`quantity >= 0`)
|
|
108
|
+
.execute();
|
|
109
|
+
|
|
110
|
+
// The subscription reads' "last reported count" is a subscription's newest report, which the unique's
|
|
111
|
+
// leading `(rail, providerSubscriptionId)` already answers as one index range — so no index of its own.
|
|
112
|
+
|
|
113
|
+
await db.schema
|
|
114
|
+
.createTable("pithyPaymentsUsageRuns")
|
|
115
|
+
.addColumn("id", "text", (c) => c.primaryKey())
|
|
116
|
+
.addColumn("startedAt", "integer", (c) => c.notNull())
|
|
117
|
+
.addColumn("finishedAt", "integer", (c) => c.notNull())
|
|
118
|
+
.addColumn("scanned", "integer", (c) => c.notNull().defaultTo(0))
|
|
119
|
+
.addColumn("reported", "integer", (c) => c.notNull().defaultTo(0))
|
|
120
|
+
.addColumn("sampled", "integer", (c) => c.notNull().defaultTo(0))
|
|
121
|
+
.addColumn("alreadyReported", "integer", (c) => c.notNull().defaultTo(0))
|
|
122
|
+
.addColumn("skipped", "integer", (c) => c.notNull().defaultTo(0))
|
|
123
|
+
.addColumn("invalid", "integer", (c) => c.notNull().defaultTo(0))
|
|
124
|
+
.addColumn("failed", "integer", (c) => c.notNull().defaultTo(0))
|
|
125
|
+
.addColumn("findings", "text", (c) => c.notNull())
|
|
126
|
+
.addColumn("createdAt", "integer", (c) => c.notNull())
|
|
127
|
+
.addCheckConstraint(
|
|
128
|
+
"pithyPaymentsUsageRunsCounts",
|
|
129
|
+
sql`scanned >= 0 and reported >= 0 and sampled >= 0 and already_reported >= 0 and skipped >= 0 and invalid >= 0 and failed >= 0`,
|
|
130
|
+
)
|
|
131
|
+
.execute();
|
|
132
|
+
|
|
133
|
+
await db.schema
|
|
134
|
+
.createIndex("pithyPaymentsUsageRunsStartedIdx")
|
|
135
|
+
.on("pithyPaymentsUsageRuns")
|
|
136
|
+
.columns(["startedAt", "id"])
|
|
137
|
+
.execute();
|
|
138
|
+
},
|
|
139
|
+
down: async (db: Kysely<unknown>): Promise<void> => {
|
|
140
|
+
await db.schema.dropIndex("pithyPaymentsUsageRunsStartedIdx").execute();
|
|
141
|
+
await db.schema.dropTable("pithyPaymentsUsageRuns").execute();
|
|
142
|
+
await db.schema.dropTable("pithyPaymentsUsageReports").execute();
|
|
143
|
+
await db.schema.dropTable("pithyPaymentsMeterCounters").execute();
|
|
144
|
+
await db.schema.dropIndex("pithyPaymentsOverridesUnrestrictedIdx").execute();
|
|
145
|
+
await db.schema.dropIndex("pithyPaymentsOverridesUpdatedIdx").execute();
|
|
146
|
+
await db.schema.dropTable("pithyPaymentsOverrides").execute();
|
|
147
|
+
await db.schema.alterTable("pithyPaymentsPurchases").dropColumn("quantity").execute();
|
|
148
|
+
},
|
|
149
|
+
};
|
package/src/projection/event.ts
CHANGED
|
@@ -85,6 +85,15 @@ export const ProviderEvent = z
|
|
|
85
85
|
.nullable()
|
|
86
86
|
.default(null)
|
|
87
87
|
.describe("The ISO currency of `amountMinor`, or null when the rail did not report one."),
|
|
88
|
+
quantity: z
|
|
89
|
+
.number()
|
|
90
|
+
.int()
|
|
91
|
+
.positive()
|
|
92
|
+
.nullable()
|
|
93
|
+
.default(null)
|
|
94
|
+
.describe(
|
|
95
|
+
"How many were bought, as the store states it, or null where it does not say. Never invented: a rail that reads no quantity leaves this null rather than writing 1.",
|
|
96
|
+
),
|
|
88
97
|
providerEventAt: z
|
|
89
98
|
.date()
|
|
90
99
|
.describe(
|
package/src/projection/writer.ts
CHANGED
|
@@ -188,6 +188,7 @@ export async function projectPurchase(
|
|
|
188
188
|
originalTransactionId: event.originalTransactionId,
|
|
189
189
|
amountMinor: event.amountMinor,
|
|
190
190
|
currency: event.currency,
|
|
191
|
+
quantity: event.quantity,
|
|
191
192
|
providerEventAt: event.providerEventAt,
|
|
192
193
|
payload: event.payload,
|
|
193
194
|
createdAt: existing?.createdAt ?? now,
|
|
@@ -400,6 +401,9 @@ function upsertPurchase(db: PaymentsDatabase, row: PaymentsPurchaseRow) {
|
|
|
400
401
|
originalTransactionId: row.originalTransactionId,
|
|
401
402
|
amountMinor: row.amountMinor,
|
|
402
403
|
currency: row.currency,
|
|
404
|
+
// The newest event's statement, under the same monotonic rule as every column beside it — so a
|
|
405
|
+
// client submission, a webhook and a reconciliation pass converge on one quantity.
|
|
406
|
+
quantity: row.quantity,
|
|
403
407
|
providerEventAt: row.providerEventAt,
|
|
404
408
|
payload: row.payload,
|
|
405
409
|
updatedAt: row.updatedAt,
|
package/src/rails/contract.ts
CHANGED
|
@@ -368,6 +368,12 @@ export interface CheckoutSessionInput {
|
|
|
368
368
|
providerProductId: string;
|
|
369
369
|
/** Whether this buys a recurring subscription or a one-off. Decides the hosted flow the store presents. */
|
|
370
370
|
subscription: boolean;
|
|
371
|
+
/**
|
|
372
|
+
* Whether the product bills by a reported quantity (`billing.kind: "reported"`). Such a price is metered on
|
|
373
|
+
* Stripe, and Stripe refuses a line quantity on a metered price — so the line goes out with none, and the
|
|
374
|
+
* count arrives later as reported usage. Absent is a flat-priced product.
|
|
375
|
+
*/
|
|
376
|
+
reported?: boolean;
|
|
371
377
|
/**
|
|
372
378
|
* The subject the purchase is for — the authenticated caller, or the organization the project bills on
|
|
373
379
|
* their behalf, as the configured subject seam resolved it.
|