@pithy-sh/payments 0.3.10 → 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 +11 -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 +38 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +59 -1
- package/dist/client/hooks.d.ts +63 -1
- package/dist/client/hooks.d.ts.map +1 -1
- package/dist/client/hooks.js +96 -2
- package/dist/client/paddleLink.d.ts +31 -0
- package/dist/client/paddleLink.d.ts.map +1 -0
- package/dist/client/paddleLink.js +37 -0
- 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/paddleIds.d.ts +28 -0
- package/dist/data/paddleIds.d.ts.map +1 -0
- package/dist/data/paddleIds.js +73 -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/entitlement/unimplementedSubject.d.ts.map +1 -1
- package/dist/entitlement/unimplementedSubject.js +3 -2
- 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 +390 -5
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +169 -13
- package/dist/http/routes.d.ts +6 -2
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +478 -52
- package/dist/http/schemas.d.ts +75 -1
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +80 -3
- 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/http/webhookGuard.d.ts.map +1 -1
- package/dist/http/webhookGuard.js +1 -1
- 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/events.d.ts.map +1 -1
- package/dist/rails/paddle/events.js +2 -1
- 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/refresh.d.ts +10 -5
- package/dist/rails/paddle/refresh.d.ts.map +1 -1
- package/dist/rails/paddle/refresh.js +8 -5
- package/dist/rails/paddle/refund.d.ts.map +1 -1
- package/dist/rails/paddle/refund.js +10 -2
- package/dist/rails/paddle/subscription.d.ts.map +1 -1
- package/dist/rails/paddle/subscription.js +8 -3
- 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/paddle/verify.d.ts.map +1 -1
- package/dist/rails/paddle/verify.js +2 -3
- 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/secret/registry.d.ts.map +1 -1
- package/dist/secret/registry.js +3 -2
- 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.d.ts.map +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/dist/workflows/workerConfig.d.ts.map +1 -1
- package/dist/workflows/workerConfig.js +8 -2
- package/docs/entitlements.md +249 -0
- package/docs/lemon-squeezy.md +1 -0
- package/docs/paddle.md +18 -2
- package/package.json +7 -7
- 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 +79 -0
- package/src/client/hooks.ts +122 -0
- package/src/client/paddleLink.ts +41 -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/paddleIds.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/entitlement/unimplementedSubject.ts +3 -4
- package/src/error/errors.ts +44 -1
- package/src/http/responses.ts +338 -10
- package/src/http/routes.ts +1089 -460
- package/src/http/schemas.ts +171 -2
- package/src/http/scopes.ts +68 -0
- package/src/http/view.ts +112 -7
- package/src/http/webhookGuard.ts +3 -2
- 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/events.ts +2 -1
- package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
- package/src/rails/paddle/objects.ts +6 -0
- package/src/rails/paddle/refresh.ts +17 -10
- package/src/rails/paddle/refund.ts +10 -2
- package/src/rails/paddle/subscription.ts +8 -3
- package/src/rails/paddle/usage.ts +66 -0
- package/src/rails/paddle/verify.ts +6 -4
- 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/secret/registry.ts +3 -2
- 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/workflows/workerConfig.ts +9 -3
package/src/admin/read.ts
CHANGED
|
@@ -2,20 +2,27 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import { chunkByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
|
|
5
6
|
import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
|
|
6
7
|
import type { z } from "zod";
|
|
7
8
|
import { PaymentsEntitlement } from "../data/entitlement";
|
|
9
|
+
import { PaymentsOverride } from "../data/override";
|
|
8
10
|
import { PaymentsPurchase, type PurchaseEnvironment } from "../data/purchase";
|
|
9
11
|
import type { PaymentsRail } from "../data/rail";
|
|
10
12
|
import { PaymentsReconcileRun } from "../data/reconcileRun";
|
|
11
13
|
import type { PurchaseStatus } from "../data/status";
|
|
12
|
-
import type
|
|
14
|
+
import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
|
|
13
15
|
import {
|
|
14
16
|
PAYMENTS_ENTITLEMENTS_TABLE,
|
|
17
|
+
PAYMENTS_OVERRIDES_TABLE,
|
|
15
18
|
PAYMENTS_PURCHASES_TABLE,
|
|
16
19
|
PAYMENTS_RECONCILE_RUNS_TABLE,
|
|
20
|
+
PAYMENTS_USAGE_REPORTS_TABLE,
|
|
21
|
+
PAYMENTS_USAGE_RUNS_TABLE,
|
|
17
22
|
paymentsDatabase,
|
|
18
23
|
} from "../data/tables";
|
|
24
|
+
import { PaymentsUsageReport } from "../data/usageReport";
|
|
25
|
+
import { PaymentsUsageRun } from "../data/usageRun";
|
|
19
26
|
|
|
20
27
|
/**
|
|
21
28
|
* The management read model — the queries behind the control-plane reads, and nothing else.
|
|
@@ -94,6 +101,7 @@ export const PaymentsPurchaseRecord = PaymentsPurchase.pick({
|
|
|
94
101
|
environment: true,
|
|
95
102
|
amountMinor: true,
|
|
96
103
|
currency: true,
|
|
104
|
+
quantity: true,
|
|
97
105
|
purchasedAt: true,
|
|
98
106
|
expiresAt: true,
|
|
99
107
|
revokedAt: true,
|
|
@@ -306,6 +314,170 @@ export async function readEntitlements(d1: D1Database, subject: PaymentsSubject)
|
|
|
306
314
|
return rows.map((row) => PaymentsEntitlement.parse(row));
|
|
307
315
|
}
|
|
308
316
|
|
|
317
|
+
/**
|
|
318
|
+
* Which of `subjects` are `unrestricted` — what the entitlement listing marks on each row. One query for the
|
|
319
|
+
* page rather than one per row, on the override index that leads on `unrestricted`.
|
|
320
|
+
*/
|
|
321
|
+
export async function unrestrictedSubjects(d1: D1Database, subjects: readonly PaymentsSubject[]): Promise<Set<string>> {
|
|
322
|
+
if (subjects.length === 0) return new Set();
|
|
323
|
+
const db = paymentsDatabase(d1);
|
|
324
|
+
const found = new Set<string>();
|
|
325
|
+
// One fixed parameter beside the list — `unrestricted` — so a full page of 100 ids is two statements.
|
|
326
|
+
for (const ids of chunkByBoundParameters([...new Set(subjects.map((subject) => subject.subjectId))], 1)) {
|
|
327
|
+
const rows = await db
|
|
328
|
+
.selectFrom(PAYMENTS_OVERRIDES_TABLE)
|
|
329
|
+
.select(["subjectType", "subjectId"])
|
|
330
|
+
// biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
|
|
331
|
+
.where("unrestricted", "=", 1 as any)
|
|
332
|
+
.where("subjectId", "in", ids)
|
|
333
|
+
.execute();
|
|
334
|
+
for (const row of rows) found.add(encodeSubjectReference(row as PaymentsSubject));
|
|
335
|
+
}
|
|
336
|
+
return found;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** What {@link listOverrides} accepts. */
|
|
340
|
+
export interface OverridesQuery {
|
|
341
|
+
/** Narrow to one subject. */
|
|
342
|
+
subject?: PaymentsSubject;
|
|
343
|
+
/** Narrow to the subjects that are `unrestricted`. */
|
|
344
|
+
unrestricted?: boolean;
|
|
345
|
+
/** Where to resume. */
|
|
346
|
+
cursor?: string;
|
|
347
|
+
/** How many rows to return, clamped by `pageLimit`. */
|
|
348
|
+
limit?: number;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Every subject's override, most recently changed first. A row a clear emptied is kept only so its version
|
|
353
|
+
* never repeats, and overrides nothing, so it is not listed.
|
|
354
|
+
*/
|
|
355
|
+
export async function listOverrides(
|
|
356
|
+
d1: D1Database,
|
|
357
|
+
query: OverridesQuery = {},
|
|
358
|
+
): Promise<PaymentsPage<PaymentsOverride>> {
|
|
359
|
+
const limit = pageLimit(query.limit);
|
|
360
|
+
const after = resume(query.cursor);
|
|
361
|
+
let selection = paymentsDatabase(d1)
|
|
362
|
+
.selectFrom(PAYMENTS_OVERRIDES_TABLE)
|
|
363
|
+
.selectAll()
|
|
364
|
+
// The SQL side of `isEmptyOverride`: the encoded 0/1 and the encoded empty JSON objects the codec writes.
|
|
365
|
+
.where((eb) =>
|
|
366
|
+
eb.or([
|
|
367
|
+
// biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
|
|
368
|
+
eb("unrestricted", "=", 1 as any),
|
|
369
|
+
// biome-ignore lint/suspicious/noExplicitAny: the encoded JSON text the codec writes.
|
|
370
|
+
eb("quotas", "!=", "{}" as any),
|
|
371
|
+
// biome-ignore lint/suspicious/noExplicitAny: as above.
|
|
372
|
+
eb("features", "!=", "{}" as any),
|
|
373
|
+
]),
|
|
374
|
+
)
|
|
375
|
+
.orderBy("updatedAt", "desc")
|
|
376
|
+
.orderBy("id", "desc")
|
|
377
|
+
.limit(limit + 1);
|
|
378
|
+
if (query.subject !== undefined) {
|
|
379
|
+
selection = selection
|
|
380
|
+
.where("subjectType", "=", query.subject.subjectType)
|
|
381
|
+
.where("subjectId", "=", query.subject.subjectId);
|
|
382
|
+
}
|
|
383
|
+
if (query.unrestricted !== undefined) {
|
|
384
|
+
const flag = query.unrestricted ? 1 : 0;
|
|
385
|
+
// biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
|
|
386
|
+
selection = selection.where("unrestricted", "=", flag as any);
|
|
387
|
+
}
|
|
388
|
+
if (after) {
|
|
389
|
+
selection = selection.where((eb) =>
|
|
390
|
+
eb.or([eb("updatedAt", "<", after.sort), eb.and([eb("updatedAt", "=", after.sort), eb("id", "<", after.id)])]),
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
const rows = await selection.execute();
|
|
394
|
+
return toPage(
|
|
395
|
+
rows.map((row) => PaymentsOverride.parse(row)),
|
|
396
|
+
limit,
|
|
397
|
+
(override) => ({ sort: override.updatedAt.getTime(), id: override.id }),
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Every `unrestricted` subject this deployment holds — what `pithy doctor` names. */
|
|
402
|
+
export async function listUnrestrictedSubjects(d1: D1Database): Promise<PaymentsSubject[]> {
|
|
403
|
+
const rows = await paymentsDatabase(d1)
|
|
404
|
+
.selectFrom(PAYMENTS_OVERRIDES_TABLE)
|
|
405
|
+
.select(["subjectType", "subjectId"])
|
|
406
|
+
// biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
|
|
407
|
+
.where("unrestricted", "=", 1 as any)
|
|
408
|
+
.orderBy("subjectType")
|
|
409
|
+
.orderBy("subjectId")
|
|
410
|
+
.execute();
|
|
411
|
+
return rows.map((row) => ({ subjectType: row.subjectType, subjectId: row.subjectId }) as PaymentsSubject);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** What {@link listUsageRuns} accepts. */
|
|
415
|
+
export interface UsageRunsQuery {
|
|
416
|
+
/** Where to resume, from a previous page's `nextCursor`. A malformed one is a first page. */
|
|
417
|
+
cursor?: string;
|
|
418
|
+
/** How many rows to return, clamped by `pageLimit`. */
|
|
419
|
+
limit?: number;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** The usage-reporting passes this deployment has run, newest first — the same keyset the reconcile log uses. */
|
|
423
|
+
export async function listUsageRuns(
|
|
424
|
+
d1: D1Database,
|
|
425
|
+
query: UsageRunsQuery = {},
|
|
426
|
+
): Promise<PaymentsPage<PaymentsUsageRun>> {
|
|
427
|
+
const limit = pageLimit(query.limit);
|
|
428
|
+
const after = resume(query.cursor);
|
|
429
|
+
let selection = paymentsDatabase(d1)
|
|
430
|
+
.selectFrom(PAYMENTS_USAGE_RUNS_TABLE)
|
|
431
|
+
.selectAll()
|
|
432
|
+
.orderBy("startedAt", "desc")
|
|
433
|
+
.orderBy("id", "desc")
|
|
434
|
+
.limit(limit + 1);
|
|
435
|
+
if (after) {
|
|
436
|
+
selection = selection.where((eb) =>
|
|
437
|
+
eb.or([eb("startedAt", "<", after.sort), eb.and([eb("startedAt", "=", after.sort), eb("id", "<", after.id)])]),
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
const rows = await selection.execute();
|
|
441
|
+
return toPage(
|
|
442
|
+
rows.map((row) => PaymentsUsageRun.parse(row)),
|
|
443
|
+
limit,
|
|
444
|
+
(run) => ({ sort: run.startedAt.getTime(), id: run.id }),
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* The newest accepted report of each subscription, by its store id — what the subscription reads show as the
|
|
450
|
+
* last reported count. Keyed on the subscription rather than on one period's purchase row, because the report
|
|
451
|
+
* for a period lands at that period's end and the current row has none until then.
|
|
452
|
+
*/
|
|
453
|
+
export async function lastReports(
|
|
454
|
+
d1: D1Database,
|
|
455
|
+
subscriptions: readonly { rail: PaymentsRail; providerSubscriptionId: string }[],
|
|
456
|
+
): Promise<Map<string, { quantity: number; reportedAt: Date }>> {
|
|
457
|
+
const latest = new Map<string, { quantity: number; reportedAt: Date }>();
|
|
458
|
+
if (subscriptions.length === 0) return latest;
|
|
459
|
+
const db = paymentsDatabase(d1);
|
|
460
|
+
const ids = [...new Set(subscriptions.map((entry) => entry.providerSubscriptionId))];
|
|
461
|
+
// One fixed parameter beside the list — `status` — so a full page is two statements. A subscription's rows
|
|
462
|
+
// all fall in the chunk that carries its id, so newest-first within a chunk is newest-first for it.
|
|
463
|
+
for (const chunk of chunkByBoundParameters(ids, 1)) {
|
|
464
|
+
const rows = await db
|
|
465
|
+
.selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
|
|
466
|
+
.selectAll()
|
|
467
|
+
.where("providerSubscriptionId", "in", chunk)
|
|
468
|
+
.where("status", "=", "reported")
|
|
469
|
+
.orderBy("reportedAt", "desc")
|
|
470
|
+
.execute();
|
|
471
|
+
for (const row of rows) {
|
|
472
|
+
const report = PaymentsUsageReport.parse(row);
|
|
473
|
+
const key = `${report.rail}:${report.providerSubscriptionId}`;
|
|
474
|
+
if (report.reportedAt === null || latest.has(key)) continue;
|
|
475
|
+
latest.set(key, { quantity: report.quantity, reportedAt: report.reportedAt });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return latest;
|
|
479
|
+
}
|
|
480
|
+
|
|
309
481
|
/** What {@link listReconcileRuns} accepts. */
|
|
310
482
|
export interface ReconcileRunsQuery {
|
|
311
483
|
/** Restrict to the passes narrowed to one store. Never matches a pass that ran against every rail. */
|
package/src/audit/actions.ts
CHANGED
|
@@ -208,6 +208,19 @@ export const PaymentsAuditActions = {
|
|
|
208
208
|
* indistinguishable from the 04:00 cron, which is exactly the question somebody reading the trail is asking.
|
|
209
209
|
*/
|
|
210
210
|
reconcileRunStarted: "payments/reconcile_run_started",
|
|
211
|
+
/**
|
|
212
|
+
* A management client pinned allowances for one subject, or turned `unrestricted` on or off. The first
|
|
213
|
+
* runtime-writable input to an entitlement decision, so every write is recorded with the subject, the
|
|
214
|
+
* mode, the before and the after — and the **reason**, verbatim, because six months later the only
|
|
215
|
+
* question anybody asks about an override is why.
|
|
216
|
+
*/
|
|
217
|
+
overrideSet: "payments/override_set",
|
|
218
|
+
/** A management client unpinned allowances for one subject, or cleared its override. */
|
|
219
|
+
overrideCleared: "payments/override_cleared",
|
|
220
|
+
/**
|
|
221
|
+
* A management client read the usage-reporting run log. Counts and filters only, as every management read.
|
|
222
|
+
*/
|
|
223
|
+
usageRunsRead: "payments/usage_runs_read",
|
|
211
224
|
} as const;
|
|
212
225
|
|
|
213
226
|
/** One of the payments audit action codes. */
|
package/src/capability.ts
CHANGED
|
@@ -8,13 +8,15 @@ import {
|
|
|
8
8
|
defineCapability,
|
|
9
9
|
} from "@pithy-sh/core/src/capability/capability";
|
|
10
10
|
import type { DatabaseSpecMap } from "@pithy-sh/core/src/data/databases";
|
|
11
|
+
import type { UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
|
|
11
12
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
12
13
|
import type { KvNamespaceSpecMap } from "@pithy-sh/core/src/kv/namespaces";
|
|
13
14
|
import { workflowBindings } from "@pithy-sh/core/src/workflow/bindings";
|
|
14
15
|
import type { Migration } from "kysely/migration";
|
|
15
|
-
import type { PaymentsClientProduct, PaymentsClientProjection } from "./client/projection";
|
|
16
|
-
import { PaymentsConfig, type PaymentsConfigInput } from "./config/config";
|
|
16
|
+
import type { PaymentsClientEntitlement, PaymentsClientProduct, PaymentsClientProjection } from "./client/projection";
|
|
17
|
+
import { PaymentsConfig, type PaymentsConfigInput, reportedProducts } from "./config/config";
|
|
17
18
|
import { paymentsTables } from "./data/tables";
|
|
19
|
+
import { type PaymentsAllowances, paymentsUsageMeter } from "./entitlement/meter";
|
|
18
20
|
import { installEntitlementResolver } from "./entitlement/resolver";
|
|
19
21
|
import type { PaymentsSubjectResolver, PaymentsSubjectSeam } from "./entitlement/subjectSeam";
|
|
20
22
|
import { requireImplementedSubject } from "./entitlement/unimplementedSubject";
|
|
@@ -23,12 +25,14 @@ import { paymentsManifestConfig } from "./http/manifestConfig";
|
|
|
23
25
|
import { registerPaymentsRoutes } from "./http/routes";
|
|
24
26
|
import { paymentsAdminRoutes } from "./http/scopes";
|
|
25
27
|
import { payments_0001_purchases } from "./migrations/0001_purchases";
|
|
28
|
+
import { payments_0002_allowances } from "./migrations/0002_allowances";
|
|
26
29
|
import { type PaymentsPeer, paymentsPeer } from "./peer";
|
|
27
30
|
import { paymentsInapplicableSecrets, paymentsSecretBranches } from "./secret/branches";
|
|
28
31
|
import { paymentsSecretsRegistry } from "./secret/registry";
|
|
29
32
|
import { paymentsExampleSeed } from "./seeds/example";
|
|
33
|
+
import type { PaymentsQuantityResolver } from "./usage/pass";
|
|
30
34
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
|
|
31
|
-
import { paymentsWorkflows } from "./workflows/specs";
|
|
35
|
+
import { paymentsUsageWorkflows, paymentsWorkflows } from "./workflows/specs";
|
|
32
36
|
|
|
33
37
|
/**
|
|
34
38
|
* Where payments' migrations sort in the app database. Unique per database; the registry composes keys
|
|
@@ -66,6 +70,14 @@ export type PaymentsOptions = PaymentsConfigInput & {
|
|
|
66
70
|
* it is optional and the authenticated caller is the answer.
|
|
67
71
|
*/
|
|
68
72
|
resolveSubject?: PaymentsSubjectResolver;
|
|
73
|
+
/**
|
|
74
|
+
* How many of a quantity-billed product's units one subject has — students, coaches, seats. Required
|
|
75
|
+
* when any product declares `billing: { kind: "reported" }`, and refused at boot without one. Called by the
|
|
76
|
+
* usage-reporting pass on a schedule, with the env and no request; never by payments for anything else, and
|
|
77
|
+
* payments never counts members itself. Rides here rather than in config for the reason `resolveSubject`
|
|
78
|
+
* does: a function does not survive the config's round trip through JSON. See `usage/pass.ts`.
|
|
79
|
+
*/
|
|
80
|
+
resolveQuantity?: PaymentsQuantityResolver;
|
|
69
81
|
};
|
|
70
82
|
|
|
71
83
|
/**
|
|
@@ -208,6 +220,26 @@ function requireResolvableSubject(config: PaymentsConfig, resolveSubject: Paymen
|
|
|
208
220
|
});
|
|
209
221
|
}
|
|
210
222
|
|
|
223
|
+
/**
|
|
224
|
+
* Refuse a catalog that bills by a reported quantity and gives payments nothing to ask.
|
|
225
|
+
*
|
|
226
|
+
* The same shape as {@link requireResolvableSubject}, and the same reasoning: the fault is total and the
|
|
227
|
+
* evidence is in hand. A quantity-billed subscription with no resolver is a subscription that bills nothing
|
|
228
|
+
* for what the customer is using, every period, and nothing anywhere fails — the store simply never hears a
|
|
229
|
+
* number. So it is refused here, naming every product it would happen to.
|
|
230
|
+
*/
|
|
231
|
+
function requireQuantityResolver(config: PaymentsConfig, resolveQuantity: PaymentsQuantityResolver | undefined): void {
|
|
232
|
+
if (resolveQuantity !== undefined) return;
|
|
233
|
+
const reported = reportedProducts(config);
|
|
234
|
+
if (reported.length === 0) return;
|
|
235
|
+
throw new ValidationError({
|
|
236
|
+
message: `This catalog bills ${products(reported)} by a reported quantity, and nothing can say how many.`,
|
|
237
|
+
action:
|
|
238
|
+
"Pass `resolveQuantity` to `payments(...)` in this Worker's pithy.config.ts, or drop `billing` from those products.",
|
|
239
|
+
detail: `Products with \`billing.kind: "reported"\`: ${reported.map((entry) => entry.id).join(", ")}. Payments never counts members itself, so without a resolver no count is ever reported and the store bills nothing.`,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
211
243
|
/**
|
|
212
244
|
* What a browser may know about this project's payments — the `virtual:pithy/payments` module.
|
|
213
245
|
*
|
|
@@ -288,12 +320,30 @@ function clientProjection(config: PaymentsConfig, environment: string): Payments
|
|
|
288
320
|
// Catalog order, not sorted: the order an adopter wrote their products in is the order a paywall
|
|
289
321
|
// should list them, and it is stable for a given config either way.
|
|
290
322
|
products,
|
|
323
|
+
// What each tier buys, so a paywall can compare them. The names, the numbers and the switches — and
|
|
324
|
+
// not `overrideMax`, which bounds an operator and tells a buyer nothing.
|
|
325
|
+
entitlements: Object.fromEntries(
|
|
326
|
+
Object.entries(config.entitlements).map(([key, declaration]): [string, PaymentsClientEntitlement] => [
|
|
327
|
+
key,
|
|
328
|
+
{ name: declaration.name, quotas: { ...declaration.quotas }, features: { ...declaration.features } },
|
|
329
|
+
]),
|
|
330
|
+
),
|
|
331
|
+
defaults:
|
|
332
|
+
config.defaults === undefined
|
|
333
|
+
? null
|
|
334
|
+
: { quotas: { ...config.defaults.quotas }, features: { ...config.defaults.features } },
|
|
291
335
|
};
|
|
292
336
|
}
|
|
293
337
|
|
|
338
|
+
/**
|
|
339
|
+
* The Workflows payments contributes: reconciliation always, usage reporting when the catalog sells a reported
|
|
340
|
+
* product.
|
|
341
|
+
*/
|
|
342
|
+
type PaymentsWorkflowSpecs = typeof paymentsWorkflows & Partial<typeof paymentsUsageWorkflows>;
|
|
343
|
+
|
|
294
344
|
/** The payments capability, with its resolved catalog attached for other tooling to read. */
|
|
295
345
|
export interface PaymentsCapability
|
|
296
|
-
extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "payments",
|
|
346
|
+
extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "payments", PaymentsWorkflowSpecs> {
|
|
297
347
|
/** The resolved catalog. */
|
|
298
348
|
paymentsConfig: PaymentsConfig;
|
|
299
349
|
/**
|
|
@@ -302,6 +352,19 @@ export interface PaymentsCapability
|
|
|
302
352
|
* payments bundles it (#645). See `peer.ts`.
|
|
303
353
|
*/
|
|
304
354
|
paymentsPeer: PaymentsPeer;
|
|
355
|
+
/**
|
|
356
|
+
* The meter `@pithy-sh/email` charges at enqueue — found structurally through core's
|
|
357
|
+
* `composedUsageMeter`, so email imports nothing from this package. Charges nothing for a meter this
|
|
358
|
+
* config leaves advisory. See `entitlement/meter.ts`.
|
|
359
|
+
*/
|
|
360
|
+
usageMeter: UsageMeter;
|
|
361
|
+
/**
|
|
362
|
+
* What the usage-reporting Workflow reads off the composition: the adopter's `resolveQuantity`, when the
|
|
363
|
+
* catalog bills by a reported quantity, and undefined otherwise. On the capability rather than in the
|
|
364
|
+
* config, so it is never serialized and never reaches a browser. `reportPaymentsUsage` in
|
|
365
|
+
* `workflows/usage.ts` reads it.
|
|
366
|
+
*/
|
|
367
|
+
paymentsUsage: { resolveQuantity: PaymentsQuantityResolver } | undefined;
|
|
305
368
|
}
|
|
306
369
|
|
|
307
370
|
/**
|
|
@@ -335,13 +398,14 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
335
398
|
// whose whole hazard is being serialized by accident. Separated here, the config that reaches
|
|
336
399
|
// `JSON.stringify` in `provision/resolvePaymentsConfig.ts` provably holds no function, because no function
|
|
337
400
|
// was ever in it.
|
|
338
|
-
const { resolveSubject, ...catalog } = options;
|
|
401
|
+
const { resolveSubject, resolveQuantity, ...catalog } = options;
|
|
339
402
|
|
|
340
403
|
// Parse the catalog at assembly — a product naming a disabled rail, a duplicate provider SKU, or a
|
|
341
404
|
// ledger grant on a non-consumable fails on deploy, not on the first webhook. `billingSubject` is required
|
|
342
405
|
// and has no default: what a project bills is a decision, and a default would make it an accident.
|
|
343
406
|
const resolved = PaymentsConfig.parse(catalog);
|
|
344
407
|
requireResolvableSubject(resolved, resolveSubject);
|
|
408
|
+
requireQuantityResolver(resolved, resolveQuantity);
|
|
345
409
|
|
|
346
410
|
// The one seam, built once. Both halves come from different places by construction (see
|
|
347
411
|
// {@link PaymentsOptions}), and every asker — the entitlement gate through the middleware, the routes
|
|
@@ -357,13 +421,22 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
357
421
|
...(resolveSubject ? { resolveSubject } : {}),
|
|
358
422
|
};
|
|
359
423
|
|
|
424
|
+
// The declarations and the meters, once — the gate's readers, the routes, and the meter `@pithy-sh/email`
|
|
425
|
+
// charges all read this object, so they cannot disagree about what a name means.
|
|
426
|
+
const allowances: PaymentsAllowances = { declarations: resolved, meters: resolved.meters };
|
|
427
|
+
|
|
360
428
|
// The optional peers, filled once by `compose` — which runs after this factory, so the routes are handed
|
|
361
429
|
// the slot and read it per request rather than being handed a value that does not exist yet.
|
|
362
430
|
const peers: { ledger: PaymentsLedgerPeer | undefined } = { ledger: undefined };
|
|
363
431
|
|
|
364
432
|
const migrations: Record<string, Migration> = {
|
|
365
433
|
"0001_purchases": payments_0001_purchases,
|
|
434
|
+
"0002_allowances": payments_0002_allowances,
|
|
366
435
|
};
|
|
436
|
+
// Usage reporting only where something is billed by a reported quantity: a project that sells none binds
|
|
437
|
+
// nothing for it, and its `pithy doctor` has nothing to report about a Workflow it does not have.
|
|
438
|
+
const workflows: PaymentsWorkflowSpecs =
|
|
439
|
+
reportedProducts(resolved).length > 0 ? { ...paymentsWorkflows, ...paymentsUsageWorkflows } : paymentsWorkflows;
|
|
367
440
|
const requiredBindings: BindingSpecInput[] = [
|
|
368
441
|
// The app database — all four pithy_payments_* tables live here.
|
|
369
442
|
{ type: "d1", name: "DB" },
|
|
@@ -371,7 +444,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
371
444
|
// declaration, so a binding rename cannot leave the two disagreeing. `optional` because the binding
|
|
372
445
|
// exists only once `pithy payments provision` has deployed the host, and an unprovisioned project must
|
|
373
446
|
// still verify receipts, accept webhooks, and resolve entitlements.
|
|
374
|
-
...workflowBindings(
|
|
447
|
+
...workflowBindings(workflows),
|
|
375
448
|
];
|
|
376
449
|
|
|
377
450
|
const capability = defineCapability({
|
|
@@ -395,7 +468,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
395
468
|
inapplicableSecrets: paymentsInapplicableSecrets(resolved.rails),
|
|
396
469
|
// The one durable job: the nightly reconciliation pass. Declared here so `createBackend` derives its
|
|
397
470
|
// binding and types `c.var.workflows.trigger("payments/reconcile", …)` precisely.
|
|
398
|
-
workflows
|
|
471
|
+
workflows,
|
|
399
472
|
// The one thing this capability cannot check on its own: whether the ledger it credits agrees the
|
|
400
473
|
// currency exists. See `checkLedgerGrants` for why the failure is otherwise invisible. And the one place
|
|
401
474
|
// the ledger reaches payments at all: found among the composed capabilities, never imported (#645).
|
|
@@ -422,7 +495,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
422
495
|
},
|
|
423
496
|
// Replaces core's fail-closed `noEntitlementProvider` with the D1-backed resolver, over the seam that
|
|
424
497
|
// says who to resolve for.
|
|
425
|
-
middleware: [installEntitlementResolver(PAYMENTS_DATABASE_NAME, subject)],
|
|
498
|
+
middleware: [installEntitlementResolver(PAYMENTS_DATABASE_NAME, subject, allowances)],
|
|
426
499
|
// The management surface, described for `GET /control-plane/manifest`. Built from the resolved
|
|
427
500
|
// `basePath` rather than the default, so an adopter who mounted payments at `/billing` gets a
|
|
428
501
|
// manifest naming `/billing/entitlements/grant` — the whole point of describing rather than
|
|
@@ -438,7 +511,12 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
438
511
|
seeds: [paymentsExampleSeed],
|
|
439
512
|
});
|
|
440
513
|
|
|
441
|
-
return Object.assign(capability, {
|
|
514
|
+
return Object.assign(capability, {
|
|
515
|
+
paymentsConfig: resolved,
|
|
516
|
+
paymentsPeer,
|
|
517
|
+
usageMeter: paymentsUsageMeter(allowances, "DB"),
|
|
518
|
+
paymentsUsage: resolveQuantity === undefined ? undefined : { resolveQuantity },
|
|
519
|
+
});
|
|
442
520
|
}
|
|
443
521
|
|
|
444
522
|
/** Whether a capability is the payments capability — carries its resolved catalog. */
|
package/src/client/api.ts
CHANGED
|
@@ -542,6 +542,50 @@ function isEntitlementsBody(value: unknown): value is { entitlements: Entitlemen
|
|
|
542
542
|
return isRecord(value) && isArrayOf(value.entitlements, isEntitlementView);
|
|
543
543
|
}
|
|
544
544
|
|
|
545
|
+
/**
|
|
546
|
+
* What the caller's holder may have, as `GET /payments/entitlements` resolves it: every declared quota (a
|
|
547
|
+
* whole number, or null for unlimited) and every declared feature. **A UX affordance, never a security
|
|
548
|
+
* boundary** — a paywall shows "3 of 10 seats", and the server is what refuses the eleventh.
|
|
549
|
+
*/
|
|
550
|
+
export interface AllowancesView {
|
|
551
|
+
/** Quotas by name. `null` is unlimited. */
|
|
552
|
+
quotas: Readonly<Record<string, number | null>>;
|
|
553
|
+
/** Features by name. */
|
|
554
|
+
features: Readonly<Record<string, boolean>>;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Whether a value is a map whose every value passes `guard`. */
|
|
558
|
+
function isMapOf<T>(value: unknown, guard: (item: unknown) => item is T): value is Record<string, T> {
|
|
559
|
+
return isRecord(value) && Object.values(value).every(guard);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** A quota on the wire: a whole number from 0, or null. */
|
|
563
|
+
function isQuota(value: unknown): value is number | null {
|
|
564
|
+
return value === null || (typeof value === "number" && Number.isInteger(value) && value >= 0);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** A feature on the wire. */
|
|
568
|
+
function isSwitch(value: unknown): value is boolean {
|
|
569
|
+
return typeof value === "boolean";
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** Whether a value is the entitlements envelope from a Worker that resolves allowances. */
|
|
573
|
+
function isAllowancesBody(value: unknown): value is AllowancesView {
|
|
574
|
+
return isRecord(value) && isMapOf(value.quotas, isQuota) && isMapOf(value.features, isSwitch);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* The caller's resolved allowances. The client-side reading of `quota(c, name)` and `feature(c, name)`, for a
|
|
579
|
+
* paywall screen — never the enforcement, which the server does.
|
|
580
|
+
*
|
|
581
|
+
* A Worker that predates declarations answers no allowances, and that is a failure here rather than an empty
|
|
582
|
+
* map: an empty map reads as *zero of everything*, and a screen would tell a paying customer they have none.
|
|
583
|
+
*/
|
|
584
|
+
export async function getAllowances(options?: PaymentsClientOptions): Promise<PaymentsResult<AllowancesView>> {
|
|
585
|
+
const result = await callPayments("/entitlements", {}, options, isAllowancesBody);
|
|
586
|
+
return result.ok ? { ok: true, value: { quotas: result.value.quotas, features: result.value.features } } : result;
|
|
587
|
+
}
|
|
588
|
+
|
|
545
589
|
/** Whether a value is the purchase envelope both write routes' single-purchase form returns. */
|
|
546
590
|
function isPurchaseBody(value: unknown): value is { purchase: PurchaseView; entitlements: EntitlementView[] } {
|
|
547
591
|
return isRecord(value) && isPurchaseView(value.purchase) && isArrayOf(value.entitlements, isEntitlementView);
|
|
@@ -610,6 +654,41 @@ export function createCheckout(
|
|
|
610
654
|
return callPayments("/checkout", jsonPost(input), options, isCheckoutHandoff);
|
|
611
655
|
}
|
|
612
656
|
|
|
657
|
+
/** Whether a value is a Paddle handoff specifically — the only shape the resume read answers with. */
|
|
658
|
+
function isPaddleResumeHandoff(value: unknown): value is PaddleCheckoutHandoff {
|
|
659
|
+
return isCheckoutHandoff(value) && value.kind === "paddle";
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* What a page needs to open the transaction a Paddle payment link arrived for.
|
|
664
|
+
*
|
|
665
|
+
* **The transaction already exists, which is the whole difference from {@link createCheckout}.** Paddle
|
|
666
|
+
* created it before mailing the link — a past-due retry, a manually-collected invoice, a payment-method
|
|
667
|
+
* update — and appended `?_ptxn=<id>` to this project's Default payment link. So nothing is minted here;
|
|
668
|
+
* the id is read off the URL by `readPaddleLinkTransaction` in `./paddleLink` and this asks the server for
|
|
669
|
+
* the account and presentation that go with it.
|
|
670
|
+
*
|
|
671
|
+
* **Why a round trip at all, when the browser already holds the id.** Because `successUrl` is not the
|
|
672
|
+
* browser's to name. The handoff carries where a paying buyer is sent, and a page that could choose it
|
|
673
|
+
* could send a paying customer somewhere it controls — the same rule the minted path states on the field
|
|
674
|
+
* itself. The client token and the display mode travel with it for the same reason they do there: one
|
|
675
|
+
* source of truth for which Paddle account this project sells through.
|
|
676
|
+
*
|
|
677
|
+
* Sends no credentials of consequence and needs none: the route is unauthenticated, because the buyer
|
|
678
|
+
* following a dunning link days later is usually signed out.
|
|
679
|
+
*/
|
|
680
|
+
export function resumeCheckout(
|
|
681
|
+
transactionId: string,
|
|
682
|
+
options?: PaymentsClientOptions,
|
|
683
|
+
): Promise<PaymentsResult<PaddleCheckoutHandoff>> {
|
|
684
|
+
return callPayments(
|
|
685
|
+
`/checkout/resume?transaction=${encodeURIComponent(transactionId)}`,
|
|
686
|
+
{},
|
|
687
|
+
options,
|
|
688
|
+
isPaddleResumeHandoff,
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
|
|
613
692
|
/**
|
|
614
693
|
* Create a Billing Portal session for the caller's own store account.
|
|
615
694
|
*
|