@owlmeans/server-payment 0.1.18 → 0.1.19

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 (141) hide show
  1. package/README.md +1 -1
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +74 -6
  4. package/build/access/types.d.ts +8 -1
  5. package/build/access/types.d.ts.map +1 -1
  6. package/build/access.d.ts.map +1 -1
  7. package/build/access.js +8 -2
  8. package/build/access.js.map +1 -1
  9. package/build/catalogue/types.d.ts +3 -1
  10. package/build/catalogue/types.d.ts.map +1 -1
  11. package/build/catalogue.d.ts.map +1 -1
  12. package/build/catalogue.js +15 -10
  13. package/build/catalogue.js.map +1 -1
  14. package/build/commit/types.d.ts +17 -2
  15. package/build/commit/types.d.ts.map +1 -1
  16. package/build/commit.d.ts.map +1 -1
  17. package/build/commit.js +40 -5
  18. package/build/commit.js.map +1 -1
  19. package/build/consts.d.ts +17 -0
  20. package/build/consts.d.ts.map +1 -1
  21. package/build/consts.js +19 -0
  22. package/build/consts.js.map +1 -1
  23. package/build/consumer/capture.d.ts.map +1 -1
  24. package/build/consumer/capture.js +2 -1
  25. package/build/consumer/capture.js.map +1 -1
  26. package/build/consumer/reconcile.d.ts.map +1 -1
  27. package/build/consumer/reconcile.js +2 -1
  28. package/build/consumer/reconcile.js.map +1 -1
  29. package/build/entitlement.d.ts.map +1 -1
  30. package/build/entitlement.js +7 -1
  31. package/build/entitlement.js.map +1 -1
  32. package/build/grant-fold/types.d.ts +41 -0
  33. package/build/grant-fold/types.d.ts.map +1 -0
  34. package/build/grant-fold/types.js +2 -0
  35. package/build/grant-fold/types.js.map +1 -0
  36. package/build/grant-fold.d.ts +4 -0
  37. package/build/grant-fold.d.ts.map +1 -0
  38. package/build/grant-fold.js +64 -0
  39. package/build/grant-fold.js.map +1 -0
  40. package/build/grants/types.d.ts +39 -0
  41. package/build/grants/types.d.ts.map +1 -0
  42. package/build/grants/types.js +2 -0
  43. package/build/grants/types.js.map +1 -0
  44. package/build/grants.d.ts +6 -0
  45. package/build/grants.d.ts.map +1 -0
  46. package/build/grants.js +141 -0
  47. package/build/grants.js.map +1 -0
  48. package/build/index.d.ts +4 -0
  49. package/build/index.d.ts.map +1 -1
  50. package/build/index.js +2 -0
  51. package/build/index.js.map +1 -1
  52. package/build/observer.d.ts +3 -0
  53. package/build/observer.d.ts.map +1 -1
  54. package/build/observer.js +6 -0
  55. package/build/observer.js.map +1 -1
  56. package/build/plugins/events.d.ts.map +1 -1
  57. package/build/plugins/events.js +5 -2
  58. package/build/plugins/events.js.map +1 -1
  59. package/build/plugins/session/types.d.ts +2 -0
  60. package/build/plugins/session/types.d.ts.map +1 -1
  61. package/build/plugins/session.d.ts.map +1 -1
  62. package/build/plugins/session.js +15 -2
  63. package/build/plugins/session.js.map +1 -1
  64. package/build/plugins/stripe.js +3 -3
  65. package/build/plugins/stripe.js.map +1 -1
  66. package/build/reconcile/types.d.ts +4 -2
  67. package/build/reconcile/types.d.ts.map +1 -1
  68. package/build/reconcile.d.ts.map +1 -1
  69. package/build/reconcile.js +3 -1
  70. package/build/reconcile.js.map +1 -1
  71. package/build/resource.d.ts +2 -1
  72. package/build/resource.d.ts.map +1 -1
  73. package/build/resource.js +10 -2
  74. package/build/resource.js.map +1 -1
  75. package/build/schemas.d.ts +2 -1
  76. package/build/schemas.d.ts.map +1 -1
  77. package/build/schemas.js +16 -2
  78. package/build/schemas.js.map +1 -1
  79. package/build/service.d.ts +3 -3
  80. package/build/service.d.ts.map +1 -1
  81. package/build/service.js +7 -5
  82. package/build/service.js.map +1 -1
  83. package/build/subscription/types.d.ts +12 -2
  84. package/build/subscription/types.d.ts.map +1 -1
  85. package/build/subscription.d.ts.map +1 -1
  86. package/build/subscription.js +14 -3
  87. package/build/subscription.js.map +1 -1
  88. package/build/types.d.ts +129 -0
  89. package/build/types.d.ts.map +1 -1
  90. package/build/usage/types.d.ts +25 -8
  91. package/build/usage/types.d.ts.map +1 -1
  92. package/build/usage.d.ts.map +1 -1
  93. package/build/usage.js +201 -46
  94. package/build/usage.js.map +1 -1
  95. package/build/utils/types.d.ts +5 -0
  96. package/build/utils/types.d.ts.map +1 -1
  97. package/build/utils.d.ts.map +1 -1
  98. package/build/utils.js +4 -2
  99. package/build/utils.js.map +1 -1
  100. package/package.json +22 -22
  101. package/src/access/types.ts +8 -1
  102. package/src/access.ts +12 -3
  103. package/src/catalogue/types.ts +3 -1
  104. package/src/catalogue.ts +17 -13
  105. package/src/commit/types.ts +17 -2
  106. package/src/commit.ts +47 -6
  107. package/src/consts.ts +20 -0
  108. package/src/consumer/capture.ts +2 -1
  109. package/src/consumer/reconcile.ts +2 -1
  110. package/src/entitlement.ts +8 -1
  111. package/src/grant-fold/types.ts +42 -0
  112. package/src/grant-fold.ts +89 -0
  113. package/src/grants/types.ts +42 -0
  114. package/src/grants.ts +171 -0
  115. package/src/index.ts +4 -0
  116. package/src/observer.ts +8 -1
  117. package/src/plugins/events.ts +5 -2
  118. package/src/plugins/session/types.ts +2 -0
  119. package/src/plugins/session.ts +15 -2
  120. package/src/plugins/stripe.ts +3 -3
  121. package/src/reconcile/types.ts +4 -2
  122. package/src/reconcile.ts +3 -1
  123. package/src/resource.ts +20 -7
  124. package/src/schemas.ts +20 -5
  125. package/src/service.ts +9 -6
  126. package/src/subscription/types.ts +12 -2
  127. package/src/subscription.ts +15 -2
  128. package/src/types.ts +133 -0
  129. package/src/usage/types.ts +25 -8
  130. package/src/usage.ts +235 -48
  131. package/src/utils/types.ts +5 -0
  132. package/src/utils.ts +6 -2
  133. package/tests/checkout.spec.ts +62 -0
  134. package/tests/consumer-fixtures.ts +7 -0
  135. package/tests/consumer-ops.spec.ts +12 -1
  136. package/tests/consumer-rights.spec.ts +35 -1
  137. package/tests/events.spec.ts +10 -0
  138. package/tests/fake-stripe.ts +35 -12
  139. package/tests/grants.spec.ts +276 -0
  140. package/tests/internal-plan.spec.ts +112 -0
  141. package/tests/usage.integration.spec.ts +32 -0
package/src/types.ts CHANGED
@@ -17,6 +17,7 @@ import type {
17
17
  QuantityCheckoutPolicy, SubscriptionStartBody, SubscriptionStartResponse, SubscriptionStartView,
18
18
  SubscriptionStatus, WithdrawalBody, WithdrawalCandidateList, WithdrawalReceipt, WithdrawalStatus,
19
19
  } from '@owlmeans/payment'
20
+ import type { EntitlementGrantKind, EntitlementGrantStatus } from './consts.js'
20
21
 
21
22
 
22
23
  export interface Config extends ApiConfig {}
@@ -103,6 +104,8 @@ export interface StripePluginConfig extends PluginConfig { api: string; webhook?
103
104
 
104
105
  /** Stripe-only pricing settings — never a browser-visible field (see `PricingPolicy` for those). */
105
106
  export interface StripePricingDef {
107
+ /** Enable promotion-code entry on amount checkouts; absent/false keeps it disabled. */
108
+ amountPromotionCodes?: boolean
106
109
  /** Overrides `STRIPE_FX_QUOTES_API_VERSION`, when Stripe moves or renames the preview. */
107
110
  fxApiVersion?: string
108
111
  /**
@@ -366,9 +369,21 @@ export interface GatewayService extends InitializedService {
366
369
  portalLink: (ctx: ApiContext, entityId: string, opts: PortalLinkOptions) => Promise<string>
367
370
  /** @throws PaygateError('unmanaged') when `managed` is `false`. */
368
371
  estimatePrice: (ctx: ApiContext, params: PriceEstimateParams) => Promise<PriceEstimate>
372
+ /**
373
+ * Grant a plan without a paygate (`subscriptionCommitOf(ctx).grantInternalPlan`): the free plan, or
374
+ * any plan with `force`. A re-grant after a revoke or a lapse re-activates the row and observers
375
+ * hear `created` again; the row keeps its first `createdAt`.
376
+ */
369
377
  grantInternalPlan: (
370
378
  ctx: ApiContext, entityId: string, planSku: string, opts?: GrantInternalPlanOptions,
371
379
  ) => Promise<PaymentSubscriptionRecord>
380
+ /**
381
+ * End an internal grant now (`subscriptionCommitOf(ctx).revokeInternalPlan`): observers hear
382
+ * `canceled`. Idempotent. Mongo only — works unmanaged.
383
+ *
384
+ * @returns whether anything changed (`false`: no such row, or it had ended already)
385
+ */
386
+ revokeInternalPlan: (ctx: ApiContext, entityId: string, planSku: string) => Promise<boolean>
372
387
  /** @returns how many subscription rows changed */
373
388
  resyncSubscription: (ctx: ApiContext, ref: SubscriptionRef) => Promise<number>
374
389
  resyncAll: (ctx: ApiContext) => Promise<{ scanned: number; updated: number }>
@@ -543,6 +558,8 @@ export interface DisputeEvent {
543
558
  /** The paygate's dispute status (`needs_response`, `won`, `lost`, …). */
544
559
  status: string
545
560
  amountMinor: number
561
+ /** What the customer paid on the disputed charge, tax included, in the dispute currency. */
562
+ paidMinor?: number
546
563
  currency: string
547
564
  eventKey: string
548
565
  netAmountMinor?: number
@@ -619,6 +636,19 @@ export interface CancellationEvent {
619
636
  declaredAt: Date
620
637
  }
621
638
 
639
+ /** What happened to an entitlement grant. */
640
+ export type EntitlementGrantChange = 'granted' | 'revoked'
641
+
642
+ /** An entitlement grant given or revoked — `onEntitlementGrant`. */
643
+ export interface EntitlementGrantEvent {
644
+ entityId: string
645
+ /** The grant as stored after the change. */
646
+ grant: PaymentGrantRecord
647
+ change: EntitlementGrantChange
648
+ /** `grant:<grantId>:<change>`. */
649
+ eventKey: string
650
+ }
651
+
622
652
  export interface TopUpCallback { (completion: TopUpCompletion, ctx: ApiContext): Promise<void> }
623
653
  export interface SubscriptionCallback { (event: SubscriptionEvent, ctx: ApiContext): Promise<void> }
624
654
  export interface RefundCallback { (event: RefundEvent, ctx: ApiContext): Promise<void> }
@@ -627,6 +657,7 @@ export interface PaymentFailedCallback { (event: PaymentFailedEvent, ctx: ApiCon
627
657
  export interface ConsentCallback { (event: ConsentEvent, ctx: ApiContext): Promise<void> }
628
658
  export interface WithdrawalCallback { (event: WithdrawalEvent, ctx: ApiContext): Promise<void> }
629
659
  export interface CancellationCallback { (event: CancellationEvent, ctx: ApiContext): Promise<void> }
660
+ export interface EntitlementGrantCallback { (event: EntitlementGrantEvent, ctx: ApiContext): Promise<void> }
630
661
 
631
662
  /**
632
663
  * Callbacks run sequentially and are awaited. A paygate callback's throw escapes so the paygate
@@ -642,6 +673,12 @@ export interface CompletionObserver extends LazyService {
642
673
  onConsent: (cb: ConsentCallback) => void
643
674
  onWithdrawal: (cb: WithdrawalCallback) => void
644
675
  onCancellation: (cb: CancellationCallback) => void
676
+ /**
677
+ * An entitlement grant was given or revoked (`paymentAccessOf(ctx).grants()`). Runs in the process
678
+ * that wrote it, after the write; a throw is logged and never undoes the grant — the application's
679
+ * periodic reconciliation is the backstop. Idempotent by `eventKey`.
680
+ */
681
+ onEntitlementGrant: (cb: EntitlementGrantCallback) => void
645
682
  propagateTopUp: (completion: TopUpCompletion, ctx: ApiContext) => Promise<void>
646
683
  propagateSubscription: (event: SubscriptionEvent, ctx: ApiContext) => Promise<void>
647
684
  propagateRefund: (event: RefundEvent, ctx: ApiContext) => Promise<void>
@@ -650,6 +687,7 @@ export interface CompletionObserver extends LazyService {
650
687
  propagateConsent: (event: ConsentEvent, ctx: ApiContext) => Promise<void>
651
688
  propagateWithdrawal: (event: WithdrawalEvent, ctx: ApiContext) => Promise<void>
652
689
  propagateCancellation: (event: CancellationEvent, ctx: ApiContext) => Promise<void>
690
+ propagateEntitlementGrant: (event: EntitlementGrantEvent, ctx: ApiContext) => Promise<void>
653
691
  }
654
692
 
655
693
  // ---------------------------------------------------------------------------------------------
@@ -684,6 +722,8 @@ export interface PropagatedState {
684
722
  pausedAt?: Date
685
723
  /** The renewal invoice last reported as `renewed` — a renewal is reported once per invoice. */
686
724
  renewedInvoiceId?: string
725
+ /** The row's `restartedAt` when observers were last told — a restart they never heard is told again. */
726
+ restartedAt?: Date
687
727
  }
688
728
 
689
729
  /**
@@ -725,6 +765,11 @@ export interface PaymentSubscriptionRecord extends ResourceRecord {
725
765
  syncedAt?: Date
726
766
  lastEventId?: string
727
767
  initialPropagatedAt?: Date
768
+ /**
769
+ * When an internal grant last began entitling again after it had ended (a re-grant after a revoke
770
+ * or a lapse). It keys that `created` event apart from the first one; `createdAt` stays the first grant's.
771
+ */
772
+ restartedAt?: Date
728
773
  propagated?: PropagatedState
729
774
  /** The subscription's currency (lowercase). */
730
775
  currency?: string
@@ -833,6 +878,82 @@ export interface PaymentUsageCounterRecord extends ResourceRecord {
833
878
  }
834
879
  export interface PaymentUsageCounterResource extends MongoResource<PaymentUsageCounterRecord> {}
835
880
 
881
+ /**
882
+ * An organization's entitlement grant: extra units of one limit (`units`) or one capability
883
+ * (`capability`), beside whatever its plan grants. In force while `active`, from `startsAt`, until
884
+ * `endsAt` (absent: no end); a revoked or ended grant is ignored at read time.
885
+ */
886
+ export interface PaymentGrantRecord extends ResourceRecord {
887
+ entityId: string
888
+ kind: EntitlementGrantKind
889
+ /** `units`: the limit key whose ceiling it raises. */
890
+ limitKey?: string
891
+ /**
892
+ * The parameter it grants, exactly as the capability gate takes it (`feature:x`, `scope:x>=n`):
893
+ * what a `capability` grant is; on a `units` grant, the capability those units need (published
894
+ * sites need `feature:production--publish`), merged while the grant is in force.
895
+ */
896
+ capability?: string
897
+ /** `units`: how many units it adds. */
898
+ amount?: number
899
+ /**
900
+ * `units`: how many of them are held now — admitted by a conditional increment, returned by a
901
+ * release, rebuilt from the grant's usage events (`grant:<id>` window) by `reconcileCounters`.
902
+ */
903
+ used?: number
904
+ startsAt: Date
905
+ /** Exclusive; absent: the grant never ends. */
906
+ endsAt?: Date
907
+ status: EntitlementGrantStatus
908
+ /** The application's own reference (the operator action, a support ticket). */
909
+ ref?: string
910
+ note?: string
911
+ createdAt: Date
912
+ revokedAt?: Date
913
+ }
914
+ export interface PaymentGrantResource extends MongoResource<PaymentGrantRecord> {}
915
+
916
+ /** What `grants().grant` writes. */
917
+ export interface EntitlementGrantSpec {
918
+ kind: EntitlementGrantKind
919
+ /** Required for `units`: a limit key some declared plan has. */
920
+ limitKey?: string
921
+ /** Required for `units`: a positive safe integer. */
922
+ amount?: number
923
+ /**
924
+ * Required for `capability`, optional on `units` (the capability its units need):
925
+ * `scope:permission` or `scope:permission>=n`, never under the `limit` scope.
926
+ */
927
+ capability?: string
928
+ /** Default: now. */
929
+ startsAt?: Date
930
+ /** Exclusive, after `startsAt`; `null` or absent: never ends. */
931
+ endsAt?: Date | null
932
+ ref?: string
933
+ note?: string
934
+ }
935
+
936
+ export interface EntitlementGrantListOptions {
937
+ /** `true`: only the grants in force at `at`; `false`: only those that are not; absent: all. */
938
+ active?: boolean
939
+ /** Default: now. */
940
+ at?: Date
941
+ kind?: EntitlementGrantKind
942
+ limitKey?: string
943
+ }
944
+
945
+ export interface EntitlementGrantRevokeOptions {
946
+ /** Refuse (answer `null`) a grant of another organization. */
947
+ entityId?: string
948
+ }
949
+
950
+ export interface EntitlementGrantRevocation {
951
+ /** The grant as stored now; `null` when no grant has that id (for that organization). */
952
+ grant: PaymentGrantRecord | null
953
+ /** This call revoked it. */
954
+ changed: boolean
955
+ }
956
+
836
957
  /** One currency option of a synced price. */
837
958
  export interface SyncedPriceOption {
838
959
  currency: string
@@ -876,11 +997,18 @@ export interface FingerprintResource extends MongoResource<FingerprintRecord> {
876
997
  // ---------------------------------------------------------------------------------------------
877
998
 
878
999
  export interface EffectivePlan {
1000
+ /** The plan, with the row's `overrides` applied and the capability grants in force merged in. */
879
1001
  plan: PaymentPlan
880
1002
  /** The entitling row behind the plan; `null` when the entity falls back to the free plan. */
881
1003
  subscription: PaymentSubscriptionRecord | null
882
1004
  /** The declared free plan, when one exists. */
883
1005
  fallback: PaymentPlan | null
1006
+ /**
1007
+ * The entity's entitlement grants in force at resolution (both kinds); absent or empty without
1008
+ * any. Units grants are NOT folded into `plan.limits`: the plan's own ceiling stays what its
1009
+ * counter admits against, the grants are consumed after it.
1010
+ */
1011
+ grants?: PaymentGrantRecord[]
884
1012
  }
885
1013
 
886
1014
  export interface ConsumeRequest {
@@ -1480,6 +1608,11 @@ export interface CommitOptions {
1480
1608
  * observers are not told and the paygate retries.
1481
1609
  */
1482
1610
  beforePropagate?: (record: PaymentSubscriptionRecord, change: SubscriptionChange) => Promise<void>
1611
+ /**
1612
+ * The row starts entitling anew after it had ended — an internal re-grant after a revoke or a
1613
+ * lapse: classified `created` whatever was last propagated, with `previous: null`.
1614
+ */
1615
+ restart?: boolean
1483
1616
  }
1484
1617
 
1485
1618
  export interface CommitResult {
@@ -14,9 +14,20 @@ export interface LedgerSum { entityId: string; limitKey: string; window: string;
14
14
  * over-count, never over-admit.
15
15
  */
16
16
  export interface UsageHelper {
17
- /** @throws LimitExhausted | LimitUnknown */
17
+ /**
18
+ * Admit `amount` units under `eventKey`: from the plan's own counter while it has room, else from
19
+ * the first units grant of the limit in force (earliest end first, then oldest) with room for them
20
+ * and for whatever the plan counter holds over its ceiling — that event lives in the grant's window
21
+ * `grant:<grantId>`. A repeated key replays. The outcome folds the grants in force into
22
+ * `limit` / `used` / `remaining`; `window` is where the event lives.
23
+ *
24
+ * @throws LimitExhausted | LimitUnknown
25
+ */
18
26
  consumeLimit: (req: ConsumeRequest) => Promise<LimitOutcome>
19
- /** Idempotent: the release event is appended first, the counter decremented only by that append. */
27
+ /**
28
+ * Idempotent: the release event is appended first, then the unit goes back to where it was taken
29
+ * from — the counter of its window, or its grant (never below zero).
30
+ */
20
31
  releaseLimit: (req: ReleaseRequest) => Promise<LimitOutcome>
21
32
  /** The active consume event of a key, or `null` (never consumed, or released). */
22
33
  consumptionOf: (entityId: string, limitKey: string, eventKey: string) => Promise<PaymentUsageRecord | null>
@@ -26,15 +37,20 @@ export interface UsageHelper {
26
37
  * this answers "does the record hold a unit, and under which key".
27
38
  */
28
39
  consumptionByRefOf: (entityId: string, limitKey: string, ref: string) => Promise<PaymentUsageRecord | null>
29
- /** One limit of the effective plan, read against its current window. @throws LimitUnknown */
40
+ /**
41
+ * One limit of the effective plan, read against its current window, with the units grants in
42
+ * force folded in (`limit` + Σ amount, `used` + Σ used). @throws LimitUnknown
43
+ */
30
44
  limitStateOf: (entityId: string, limitKey: string) => Promise<LimitView>
31
45
  /** Sum of every event's `delta`, per (entity, limit, window). */
32
46
  ledgerSums: (match: Partial<CounterKey>) => Promise<LedgerSum[]>
33
47
  /**
34
- * Bring an occupancy limit's ledger and counter to the live count. Appends at most one adjusting
35
- * event per limit per UTC day (`reconcile:<key>:<YYYY-MM-DD>`), adjusted in place by a later run of
36
- * the same day, so the ledger sum always equals what was last observed. Flags `overSince` while the
37
- * count exceeds the limit. Never stops anything.
48
+ * Bring an occupancy limit's ledger and counter to the live count. The units grants in force hold
49
+ * what their `used` says; the plan's counter is brought to the rest (`actual - Σ used`, never below
50
+ * zero) — so a unit of a revoked or ended grant falls back on the plan counter. Appends at most one
51
+ * adjusting event per limit per UTC day (`reconcile:<key>:<YYYY-MM-DD>`), adjusted in place by a
52
+ * later run of the same day. Flags `overSince` while `actual` exceeds the limit plus the grants'
53
+ * units, and answers that folded `limit` beside the live `used`. Never stops anything.
38
54
  *
39
55
  * @throws LimitUnknown | LimitMisdeclared
40
56
  */
@@ -45,7 +61,8 @@ export interface UsageHelper {
45
61
  * Every (entity, limit, window) with events gets `used = max(0, sum)` and the limit of the
46
62
  * entity's current plan; a counter of a past day/month with no events is deleted (lifetime and
47
63
  * occupancy counters never are); a counter with no events otherwise reads `0`; and the current
48
- * window counter of every declared window limit exists.
64
+ * window counter of every declared window limit exists. Every units grant of the entity gets
65
+ * `used = max(0, sum of its grant:<id> events)` — those events never reach a counter window.
49
66
  */
50
67
  reconcileLedgerCounters: (entityId?: string) => Promise<CounterReconciliation>
51
68
  }