@owlmeans/server-payment 0.1.19-rc.0 → 0.1.20-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) 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 +47 -5
  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/entitlement.d.ts.map +1 -1
  24. package/build/entitlement.js +7 -1
  25. package/build/entitlement.js.map +1 -1
  26. package/build/grant-fold/types.d.ts +41 -0
  27. package/build/grant-fold/types.d.ts.map +1 -0
  28. package/build/grant-fold/types.js +2 -0
  29. package/build/grant-fold/types.js.map +1 -0
  30. package/build/grant-fold.d.ts +4 -0
  31. package/build/grant-fold.d.ts.map +1 -0
  32. package/build/grant-fold.js +64 -0
  33. package/build/grant-fold.js.map +1 -0
  34. package/build/grants/types.d.ts +39 -0
  35. package/build/grants/types.d.ts.map +1 -0
  36. package/build/grants/types.js +2 -0
  37. package/build/grants/types.js.map +1 -0
  38. package/build/grants.d.ts +6 -0
  39. package/build/grants.d.ts.map +1 -0
  40. package/build/grants.js +141 -0
  41. package/build/grants.js.map +1 -0
  42. package/build/index.d.ts +4 -0
  43. package/build/index.d.ts.map +1 -1
  44. package/build/index.js +2 -0
  45. package/build/index.js.map +1 -1
  46. package/build/observer.d.ts +3 -0
  47. package/build/observer.d.ts.map +1 -1
  48. package/build/observer.js +6 -0
  49. package/build/observer.js.map +1 -1
  50. package/build/reconcile/types.d.ts +4 -2
  51. package/build/reconcile/types.d.ts.map +1 -1
  52. package/build/reconcile.d.ts.map +1 -1
  53. package/build/reconcile.js +3 -1
  54. package/build/reconcile.js.map +1 -1
  55. package/build/resource.d.ts +2 -1
  56. package/build/resource.d.ts.map +1 -1
  57. package/build/resource.js +10 -2
  58. package/build/resource.js.map +1 -1
  59. package/build/schemas.d.ts +2 -1
  60. package/build/schemas.d.ts.map +1 -1
  61. package/build/schemas.js +16 -2
  62. package/build/schemas.js.map +1 -1
  63. package/build/service.d.ts +3 -3
  64. package/build/service.d.ts.map +1 -1
  65. package/build/service.js +7 -5
  66. package/build/service.js.map +1 -1
  67. package/build/subscription/types.d.ts +12 -2
  68. package/build/subscription/types.d.ts.map +1 -1
  69. package/build/subscription.d.ts.map +1 -1
  70. package/build/subscription.js +14 -3
  71. package/build/subscription.js.map +1 -1
  72. package/build/types.d.ts +125 -0
  73. package/build/types.d.ts.map +1 -1
  74. package/build/usage/types.d.ts +25 -8
  75. package/build/usage/types.d.ts.map +1 -1
  76. package/build/usage.d.ts.map +1 -1
  77. package/build/usage.js +201 -46
  78. package/build/usage.js.map +1 -1
  79. package/build/utils/types.d.ts +5 -0
  80. package/build/utils/types.d.ts.map +1 -1
  81. package/build/utils.d.ts.map +1 -1
  82. package/build/utils.js +4 -2
  83. package/build/utils.js.map +1 -1
  84. package/package.json +19 -19
  85. package/src/access/types.ts +8 -1
  86. package/src/access.ts +12 -3
  87. package/src/catalogue/types.ts +3 -1
  88. package/src/catalogue.ts +17 -13
  89. package/src/commit/types.ts +17 -2
  90. package/src/commit.ts +47 -6
  91. package/src/consts.ts +20 -0
  92. package/src/entitlement.ts +8 -1
  93. package/src/grant-fold/types.ts +42 -0
  94. package/src/grant-fold.ts +89 -0
  95. package/src/grants/types.ts +42 -0
  96. package/src/grants.ts +171 -0
  97. package/src/index.ts +4 -0
  98. package/src/observer.ts +8 -1
  99. package/src/reconcile/types.ts +4 -2
  100. package/src/reconcile.ts +3 -1
  101. package/src/resource.ts +20 -7
  102. package/src/schemas.ts +20 -5
  103. package/src/service.ts +9 -6
  104. package/src/subscription/types.ts +12 -2
  105. package/src/subscription.ts +15 -2
  106. package/src/types.ts +129 -0
  107. package/src/usage/types.ts +25 -8
  108. package/src/usage.ts +235 -48
  109. package/src/utils/types.ts +5 -0
  110. package/src/utils.ts +6 -2
  111. package/tests/fake-stripe.ts +24 -7
  112. package/tests/grants.spec.ts +276 -0
  113. package/tests/internal-plan.spec.ts +112 -0
  114. package/tests/usage.integration.spec.ts +32 -0
package/src/access.ts CHANGED
@@ -6,23 +6,27 @@ import type { Context as ApiContext } from '@owlmeans/server-api'
6
6
  import {
7
7
  CONSUMER_RIGHTS_MAIL_PLUGIN_CONFIG, CONSUMER_RIGHTS_SERVICE, ENTITLEMENT_SERVICE, GATEWAY_SERVICE,
8
8
  PAYMENT_OBSERVER, RES_BILLING_PROFILE, RES_CONSUMER_CONSENT, RES_CONSUMER_DECLARATION, RES_CONSUMER_EVENT,
9
- RES_PAYGATE_CUSTOMER, RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_PURCHASE,
9
+ RES_PAYGATE_CUSTOMER, RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_GRANT, RES_PAYMENT_PURCHASE,
10
10
  RES_PAYMENT_SUBSCRIPTION, RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
11
11
  STRIPE_PINNED_API_VERSION, STRIPE_PLUGIN_CONFIG, STRIPE_PORTAL_PLUGIN_CONFIG, STRIPE_PRICING_PLUGIN_CONFIG,
12
12
  } from './consts.js'
13
13
  import type {
14
14
  BillingProfileResource, CompletionObserver, ConsumerConsentResource, ConsumerDeclarationResource,
15
15
  ConsumerEventResource, ConsumerMailPluginConfig, ConsumerRightsService, EntitlementService, FingerprintResource,
16
- GatewayService, PaygateCustomerResource, PaymentFulfillmentResource, PaymentSubscriptionRecord,
16
+ GatewayService, PaygateCustomerResource, PaymentFulfillmentResource, PaymentGrantResource, PaymentSubscriptionRecord,
17
17
  PaymentSubscriptionResource, PaymentUsageCounterResource, PaymentUsageResource, PaymentWebhookResource,
18
18
  PortalBrandingConfig, PurchaseResource, StripePluginConfig, StripePricingPluginConfig,
19
19
  } from './types.js'
20
20
  import type { PluginReader } from './types.local.js'
21
21
  import type { PaymentAccess } from './access/types.js'
22
+ import type { EntitlementGrantHelper } from './grants/types.js'
23
+ import { entitlementGrantsOf } from './grants.js'
22
24
 
23
25
  export const makePaymentAccess = (ctx: ApiContext): PaymentAccess => {
24
26
  const hasService = (alias: string): boolean =>
25
27
  (ctx as unknown as { hasService?: (alias: string) => boolean }).hasService?.(alias) === true
28
+ const hasResource = (alias: string): boolean =>
29
+ (ctx as unknown as { hasResource?: (alias: string) => boolean }).hasResource?.(alias) === true
26
30
  const plugins = () => (ctx as never as PluginReader).getConfigResource(PLUGINS)
27
31
 
28
32
  const payment = (): PaymentService => ctx.service<PaymentService>(PAYMENT_SERVICE)
@@ -40,6 +44,10 @@ export const makePaymentAccess = (ctx: ApiContext): PaymentAccess => {
40
44
  const usageCounters = (): PaymentUsageCounterResource =>
41
45
  ctx.resource<PaymentUsageCounterResource>(RES_PAYMENT_USAGE_COUNTER)
42
46
  const fingerprints = (): FingerprintResource => ctx.resource<FingerprintResource>(RES_PAYMENT_FINGERPRINT)
47
+ const grantRecords = (): PaymentGrantResource => ctx.resource<PaymentGrantResource>(RES_PAYMENT_GRANT)
48
+ const grantRecordsOf = (): PaymentGrantResource | null =>
49
+ hasResource(RES_PAYMENT_GRANT) ? grantRecords() : null
50
+ const grants = (): EntitlementGrantHelper => entitlementGrantsOf(ctx)
43
51
  const billingProfiles = (): BillingProfileResource => ctx.resource<BillingProfileResource>(RES_BILLING_PROFILE)
44
52
  const purchases = (): PurchaseResource => ctx.resource<PurchaseResource>(RES_PAYMENT_PURCHASE)
45
53
  const consumerConsents = (): ConsumerConsentResource => ctx.resource<ConsumerConsentResource>(RES_CONSUMER_CONSENT)
@@ -76,7 +84,8 @@ export const makePaymentAccess = (ctx: ApiContext): PaymentAccess => {
76
84
 
77
85
  return {
78
86
  payment, gateway, gatewayOf, observer, entitlements, paygateCustomers, subscriptions, fulfillments,
79
- paymentWebhooks, usageEvents, usageCounters, fingerprints, billingProfiles, purchases, consumerConsents,
87
+ paymentWebhooks, usageEvents, usageCounters, fingerprints, grantRecords, grantRecordsOf, grants, billingProfiles,
88
+ purchases, consumerConsents,
80
89
  consumerDeclarations, consumerEvents, consumerRights, consumerRightsOf, stripeConfig, portalBrandingConfig,
81
90
  consumerMailConfig, stripePricingConfig, stripeClient, activeSubscription,
82
91
  }
@@ -15,7 +15,9 @@ export interface CatalogueHelper {
15
15
  * The plan an entity holds: its highest-ranked subscription in an entitling status (the catalogue
16
16
  * rank, the stored one for a plan the catalogue no longer declares; the newest first on a tie),
17
17
  * else the declared free plan. The plan answered carries the winning row's `overrides`
18
- * (`overriddenPlan`), so every reader — ceilings, the view, the gates — sees one answer.
18
+ * (`overriddenPlan`) and the capability grants in force (`withCapabilities`), so every reader —
19
+ * ceilings, the view, the gates — sees one answer. The grants in force ride along as `grants`
20
+ * (units grants are not folded into `plan.limits`: the usage ledger consumes them after the plan).
19
21
  *
20
22
  * @throws PlanRequired when there is neither.
21
23
  */
package/src/catalogue.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { PermissionSet } from '@owlmeans/auth'
2
- import { ENTITLING_STATUSES, INTERNAL_PAYGATE, PlanRequired, ProductError, promoHelper } from '@owlmeans/payment'
2
+ import { ENTITLING_STATUSES, PlanRequired, ProductError, promoHelper } from '@owlmeans/payment'
3
3
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
4
  import { memoHelper } from '@owlmeans/context'
5
5
  import { STRIPE_PAYGATE_ALIAS } from './consts.js'
6
6
  import { paymentAccessOf } from './access.js'
7
7
  import { planHelper } from './plan.js'
8
+ import { subscriptionHelper } from './subscription.js'
9
+ import { grantFoldHelper } from './grant-fold.js'
10
+ import { entitlementGrantsOf } from './grants.js'
8
11
  import type { EffectivePlan, PaymentPlan, PaymentProduct, PaymentSubscriptionRecord } from './types.js'
9
12
  import { log } from './log.js'
10
13
  import type { CatalogueHelper } from './catalogue/types.js'
@@ -12,10 +15,6 @@ import type { CatalogueHelper } from './catalogue/types.js'
12
15
  /** The plan skus already reported unknown — process-wide, so each is warned about once. */
13
16
  const unknownPlans = new Set<string>()
14
17
 
15
- /** An internal grant with a period end stops entitling at that instant; a paygate row never does. */
16
- const stillEntitles = (row: PaymentSubscriptionRecord, at: Date): boolean =>
17
- row.paygate !== INTERNAL_PAYGATE || row.periodEnd == null || new Date(row.periodEnd).getTime() > at.getTime()
18
-
19
18
  export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
20
19
  const access = paymentAccessOf(ctx)
21
20
 
@@ -56,7 +55,8 @@ export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
56
55
  { entityId, status: [...ENTITLING_STATUSES] }, { size: 0 },
57
56
  )
58
57
  const candidates: Array<{ plan: PaymentPlan, row: PaymentSubscriptionRecord, rank: number }> = []
59
- for (const row of items.filter(item => stillEntitles(item, at))) {
58
+ // An internal grant with a period end stops entitling at that instant; a paygate row never does.
59
+ for (const row of items.filter(item => subscriptionHelper.entitlesAt(item, at))) {
60
60
  const plan = await findPlan(row.planSku)
61
61
  if (plan == null) {
62
62
  if (!unknownPlans.has(row.planSku)) {
@@ -71,14 +71,18 @@ export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
71
71
  || new Date(b.row.createdAt).getTime() - new Date(a.row.createdAt).getTime())
72
72
 
73
73
  const best = candidates[0]
74
- if (best != null) {
75
- return { plan: planHelper.overriddenPlan(best.plan, best.row), subscription: best.row, fallback }
76
- }
77
- if (fallback != null) {
78
- return { plan: fallback, subscription: null, fallback }
74
+ if (best == null && fallback == null) {
75
+ throw new PlanRequired(entityId)
79
76
  }
80
-
81
- throw new PlanRequired(entityId)
77
+ const grants = await entitlementGrantsOf(ctx).inForce(entityId, at)
78
+ const effective = (plan: PaymentPlan, subscription: PaymentSubscriptionRecord | null): EffectivePlan =>
79
+ grants.length === 0
80
+ ? { plan, subscription, fallback }
81
+ : { plan: grantFoldHelper.withCapabilities(plan, grants), subscription, fallback, grants }
82
+
83
+ return best != null
84
+ ? effective(planHelper.overriddenPlan(best.plan, best.row), best.row)
85
+ : effective(fallback!, null)
82
86
  }
83
87
 
84
88
  const entitlementsOf = async (entityId: string, productSkus?: string[]): Promise<PermissionSet[]> => {
@@ -20,8 +20,23 @@ export interface SubscriptionCommitHelper {
20
20
  ) => Promise<CommitResult>
21
21
  /**
22
22
  * Grant a plan without a paygate — the free plan every entity holds, or a complimentary one
23
- * (`force`). One row per grant (`free:<entityId>` / `internal:<planSku>:<entityId>`), upserted: its
24
- * `createdAt` survives a re-grant, and observers hear `created` once.
23
+ * (`force`). One row per grant (`free:<entityId>` / `internal:<planSku>:<entityId>`), upserted.
24
+ *
25
+ * Observers hear `created` when the row first entitles, and again (`previous: null`, the key
26
+ * suffixed with the row's new `restartedAt`) when a re-grant re-activates a row that had stopped
27
+ * entitling — revoked, or past its period end. A re-grant of an entitling row only moves its
28
+ * period end and tells nobody. `createdAt` is always the FIRST grant's: subscription-week windows,
29
+ * credit frames and grandfathered promos keep their anchor, so a revoke and a re-grant inside one
30
+ * window never open a second allowance in it.
25
31
  */
26
32
  grantInternalPlan: (entityId: string, planSku: string, opts?: GrantInternalPlanOptions) => Promise<PaymentSubscriptionRecord>
33
+ /**
34
+ * End an internal grant now: `status: canceled`, `periodEnd` / `endedAt` = now (a grant already
35
+ * past its period end keeps that instant), `canceledAt` = now. Observers hear `canceled` — the
36
+ * event a paygate cancellation delivers. Idempotent: no row, or a row ended already, changes
37
+ * nothing and tells nobody.
38
+ *
39
+ * @returns whether anything changed
40
+ */
41
+ revokeInternalPlan: (entityId: string, planSku: string) => Promise<boolean>
27
42
  }
package/src/commit.ts CHANGED
@@ -2,11 +2,11 @@ import { ENTITLING_STATUSES, INTERNAL_PAYGATE, ProductError, SubscriptionStatus,
2
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
3
3
  import { memoHelper } from '@owlmeans/context'
4
4
  import type {
5
- CommitOptions, CommitResult, GrantInternalPlanOptions, PaymentSubscriptionRecord, PropagatedState,
5
+ CommitOptions, CommitResult, GrantInternalPlanOptions, PaymentPlan, PaymentSubscriptionRecord, PropagatedState,
6
6
  SubscriptionSnapshot,
7
7
  } from './types.js'
8
8
  import { log } from './log.js'
9
- import { SUBSCRIPTION_LOG_EVENTS } from './consts.local.js'
9
+ import { ENDED, SUBSCRIPTION_LOG_EVENTS } from './consts.local.js'
10
10
  import { paymentAccessOf } from './access.js'
11
11
  import { paymentUtils } from './utils.js'
12
12
  import { catalogueOf } from './catalogue.js'
@@ -17,6 +17,12 @@ import type { SubscriptionCommitHelper } from './commit/types.js'
17
17
  export const makeSubscriptionCommitHelper = (ctx: ApiContext): SubscriptionCommitHelper => {
18
18
  const access = paymentAccessOf(ctx)
19
19
 
20
+ const timeOf = (value: Date | null | undefined): number | null => value == null ? null : new Date(value).getTime()
21
+
22
+ /** An internal grant's row: `free:<entityId>` for a free plan, `internal:<planSku>:<entityId>` otherwise. */
23
+ const internalIdOf = (entityId: string, planSku: string, plan: PaymentPlan | null): string =>
24
+ plan?.free === true ? `free:${entityId}` : `internal:${planSku}:${entityId}`
25
+
20
26
  const snapshotOf = async (
21
27
  record: PaymentSubscriptionRecord, state?: PropagatedState,
22
28
  ): Promise<SubscriptionSnapshot> => {
@@ -92,7 +98,8 @@ export const makeSubscriptionCommitHelper = (ctx: ApiContext): SubscriptionCommi
92
98
  await opts.beforePropagate?.(stored, change)
93
99
  await access.observer().propagateSubscription({
94
100
  change,
95
- previous: prior != null && previous != null ? await snapshotOf(previous, prior) : null,
101
+ // `created` has nothing before it — a row that starts entitling again starts anew too.
102
+ previous: change !== 'created' && prior != null && previous != null ? await snapshotOf(previous, prior) : null,
96
103
  current: await snapshotOf(stored),
97
104
  active: ENTITLING_STATUSES.includes(stored.status),
98
105
  eventKey: subscriptionHelper.subscriptionEventKey(stored, change, opts),
@@ -121,10 +128,17 @@ export const makeSubscriptionCommitHelper = (ctx: ApiContext): SubscriptionCommi
121
128
  throw new ProductError(`internal-grant:${planSku}`)
122
129
  }
123
130
  const product = await catalogueOf(ctx).findProduct(plan.productSku)
124
- const externalId = plan.free === true ? `free:${entityId}` : `internal:${planSku}:${entityId}`
131
+ const externalId = internalIdOf(entityId, planSku, plan)
125
132
  const previous = await access.subscriptions().byExternalId(externalId, INTERNAL_PAYGATE)
126
133
  const now = new Date()
127
134
  const { periodEnd: _periodEnd, endedAt: _endedAt, canceledAt: _canceledAt, ...kept } = previous ?? {}
135
+ // A row that stopped entitling (revoked, or past its period end) starts anew. So does one an
136
+ // earlier call re-activated while its observers failed: they never heard that restart, and the
137
+ // retry tells them under the same key.
138
+ const ended = previous != null && !subscriptionHelper.entitlesAt(previous, now)
139
+ const untold = previous?.restartedAt != null && !ended
140
+ && timeOf(previous.propagated?.restartedAt) !== timeOf(previous.restartedAt)
141
+ const restartedAt = ended ? now : previous?.restartedAt
128
142
 
129
143
  const next = {
130
144
  ...kept,
@@ -137,15 +151,42 @@ export const makeSubscriptionCommitHelper = (ctx: ApiContext): SubscriptionCommi
137
151
  status: SubscriptionStatus.Active,
138
152
  rank: planHelper.planRank(plan),
139
153
  ...(opts.periodEnd != null ? { periodEnd: opts.periodEnd } : {}),
154
+ // The first grant's: subscription-week windows, credit frames and grandfathered promos keep
155
+ // their anchor through a revoke and a re-grant, so no window opens twice.
140
156
  createdAt: previous?.createdAt ?? now,
157
+ ...(restartedAt != null ? { restartedAt } : {}),
141
158
  updatedAt: now,
142
159
  } as PaymentSubscriptionRecord
143
- const { record } = await commitSubscription(previous, next)
160
+ const { record } = await commitSubscription(previous, next, ended || untold ? { restart: true } : {})
144
161
 
145
162
  return record ?? next
146
163
  }
147
164
 
148
- return { snapshotOf, commitSubscription, grantInternalPlan }
165
+ const revokeInternalPlan = async (entityId: string, planSku: string): Promise<boolean> => {
166
+ const plan = await catalogueOf(ctx).findPlan(planSku)
167
+ const previous = await access.subscriptions().byExternalId(internalIdOf(entityId, planSku, plan), INTERNAL_PAYGATE)
168
+ if (previous == null || ENDED.includes(previous.status)) {
169
+ return false
170
+ }
171
+ const now = new Date()
172
+ // A grant already past its period end ended then, not now.
173
+ const endedAt = previous.periodEnd != null && new Date(previous.periodEnd).getTime() < now.getTime()
174
+ ? new Date(previous.periodEnd) : now
175
+
176
+ const next: PaymentSubscriptionRecord = {
177
+ ...previous,
178
+ status: SubscriptionStatus.Canceled,
179
+ periodEnd: endedAt,
180
+ canceledAt: now,
181
+ endedAt,
182
+ updatedAt: now,
183
+ }
184
+ const { change, updated } = await commitSubscription(previous, next)
185
+
186
+ return change != null || updated
187
+ }
188
+
189
+ return { snapshotOf, commitSubscription, grantInternalPlan, revokeInternalPlan }
149
190
  }
150
191
 
151
192
  /** The subscription store of a context — one per context. */
package/src/consts.ts CHANGED
@@ -34,6 +34,26 @@ export const RES_PAYMENT_WEBHOOK = 'payment-webhook'
34
34
  export const RES_PAYMENT_USAGE = 'payment-usage'
35
35
  export const RES_PAYMENT_USAGE_COUNTER = 'payment-usage-counter'
36
36
  export const RES_PAYMENT_FINGERPRINT = 'payment-fingerprint'
37
+ /** An organization's entitlement grants: extra units of a limit, or a capability, beside its plan. */
38
+ export const RES_PAYMENT_GRANT = 'payment-grant'
39
+
40
+ /** What an entitlement grant gives: counted units of one limit, or one capability. */
41
+ export enum EntitlementGrantKind {
42
+ Units = 'units',
43
+ Capability = 'capability',
44
+ }
45
+
46
+ /**
47
+ * An entitlement grant's lifecycle. A grant is `active` until it is revoked; its `startsAt` /
48
+ * `endsAt` are read at read time, so an expired grant stays `active` and is simply out of force.
49
+ */
50
+ export enum EntitlementGrantStatus {
51
+ Active = 'active',
52
+ Revoked = 'revoked',
53
+ }
54
+
55
+ /** The usage window of a unit held on an entitlement grant: `grant:<grantId>` — never a counter window. */
56
+ export const GRANT_WINDOW_PREFIX = 'grant:'
37
57
 
38
58
  /** One per organization: the billing country fixed at the first purchase. */
39
59
  export const RES_BILLING_PROFILE = 'payment-billing-profile'
@@ -9,6 +9,7 @@ import { paymentUtils } from './utils.js'
9
9
  import { catalogueOf } from './catalogue.js'
10
10
  import { planHelper } from './plan.js'
11
11
  import { usageOf } from './usage.js'
12
+ import { grantFoldHelper } from './grant-fold.js'
12
13
 
13
14
  const dateOrUndefined = (value: Date | null | undefined): Date | undefined =>
14
15
  value == null ? undefined : new Date(value)
@@ -61,7 +62,13 @@ export const makeEntitlementService = (alias: string = ENTITLEMENT_SERVICE): Ent
61
62
  }
62
63
  }
63
64
 
64
- return entitlementViewHelper.entitlementViewOf(effective.plan, planViewOf(effective), usage, at)
65
+ const view = entitlementViewHelper.entitlementViewOf(effective.plan, planViewOf(effective), usage, at)
66
+ const grants = effective.grants ?? []
67
+
68
+ // Units grants in force fold into their limit's numbers; capability grants are in the plan already.
69
+ return grants.length === 0
70
+ ? view
71
+ : { ...view, limits: view.limits.map(limit => grantFoldHelper.foldLimitView(limit, grants)) }
65
72
  }
66
73
 
67
74
  const service: EntitlementService = createService<EntitlementService>(alias, {
@@ -0,0 +1,42 @@
1
+ import type { LimitView } from '@owlmeans/payment'
2
+ import type { PaymentGrantRecord, PaymentPlan } from '../types.js'
3
+
4
+ /** The units of a limit's grants, summed. */
5
+ export interface GrantUnits {
6
+ /** Σ `amount`. */
7
+ amount: number
8
+ /** Σ `used`. */
9
+ used: number
10
+ }
11
+
12
+ /**
13
+ * How entitlement grants fold into what a plan answers — pure, no store. Every member takes the
14
+ * grants IN FORCE (read through `inForceAt`); a revoked or ended grant must not reach them.
15
+ */
16
+ export interface GrantFoldHelper {
17
+ /** Whether a grant is in force at `at`: `active`, started (`startsAt <= at`), not ended (`endsAt > at`, or none). */
18
+ inForceAt: (grant: PaymentGrantRecord, at: Date) => boolean
19
+ /**
20
+ * The units grants of one limit among `grants`, in the order they are consumed: the earliest end
21
+ * first (a grant without an end last), then the oldest.
22
+ */
23
+ unitsOf: (grants: readonly PaymentGrantRecord[], limitKey: string) => PaymentGrantRecord[]
24
+ /** Σ amount and Σ used of units grants (already narrowed to one limit). */
25
+ unitsFold: (units: readonly PaymentGrantRecord[]) => GrantUnits
26
+ /**
27
+ * One limit's view with the units grants of its key folded into its numbers: `limit` + Σ amount,
28
+ * `used` + Σ used, `remaining = max(0, limit - used)`. The same view when none applies.
29
+ */
30
+ foldLimitView: (view: LimitView, grants: readonly PaymentGrantRecord[]) => LimitView
31
+ /**
32
+ * A plan with the granted capabilities merged into its capabilities — those of `capability`
33
+ * grants and the one a `units` grant may carry: each granted parameter becomes
34
+ * a set of its own, without a promo, replacing the plan's entry of the same permission unless the
35
+ * plan already grants it unconditionally. The same plan when none applies.
36
+ */
37
+ withCapabilities: (plan: PaymentPlan, grants: readonly PaymentGrantRecord[]) => PaymentPlan
38
+ /** The usage window a unit held on a grant is written under: `grant:<grantId>`. */
39
+ windowOf: (grantId: string) => string
40
+ /** The grant id of a `grant:<id>` window; `null` for any other window. */
41
+ grantIdOf: (window: string | null | undefined) => string | null
42
+ }
@@ -0,0 +1,89 @@
1
+ import type { LimitView, PlanCapability } from '@owlmeans/payment'
2
+ import { CAPABILITY_LIMIT_SCOPE, entitlementParamHelper } from '@owlmeans/payment'
3
+ import { EntitlementGrantKind, EntitlementGrantStatus, GRANT_WINDOW_PREFIX } from './consts.js'
4
+ import type { PaymentGrantRecord, PaymentPlan } from './types.js'
5
+ import type { GrantFoldHelper, GrantUnits } from './grant-fold/types.js'
6
+
7
+ const timeOf = (value: Date | string | null | undefined): number | null =>
8
+ value == null ? null : new Date(value).getTime()
9
+
10
+ const count = (value: number | null | undefined): number =>
11
+ typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0
12
+
13
+ export const createGrantFoldHelper = (): GrantFoldHelper => {
14
+ const inForceAt = (grant: PaymentGrantRecord, at: Date): boolean => {
15
+ if (grant.status !== EntitlementGrantStatus.Active) {
16
+ return false
17
+ }
18
+ const now = at.getTime()
19
+ const starts = timeOf(grant.startsAt)
20
+ const ends = timeOf(grant.endsAt)
21
+
22
+ return (starts == null || starts <= now) && (ends == null || ends > now)
23
+ }
24
+
25
+ const unitsOf = (grants: readonly PaymentGrantRecord[], limitKey: string): PaymentGrantRecord[] =>
26
+ grants.filter(grant => grant.kind === EntitlementGrantKind.Units && grant.limitKey === limitKey
27
+ && count(grant.amount) > 0)
28
+ .sort((a, b) => (timeOf(a.endsAt) ?? Number.POSITIVE_INFINITY) - (timeOf(b.endsAt) ?? Number.POSITIVE_INFINITY)
29
+ || (timeOf(a.createdAt) ?? 0) - (timeOf(b.createdAt) ?? 0))
30
+
31
+ const unitsFold = (units: readonly PaymentGrantRecord[]): GrantUnits => units.reduce<GrantUnits>(
32
+ (sum, grant) => ({ amount: sum.amount + count(grant.amount), used: sum.used + count(grant.used) }),
33
+ { amount: 0, used: 0 },
34
+ )
35
+
36
+ const foldLimitView = (view: LimitView, grants: readonly PaymentGrantRecord[]): LimitView => {
37
+ const units = unitsOf(grants, view.key)
38
+ if (units.length === 0) {
39
+ return view
40
+ }
41
+ const fold = unitsFold(units)
42
+ const limit = view.limit + fold.amount
43
+ const used = view.used + fold.used
44
+
45
+ return { ...view, limit, used, remaining: Math.max(0, limit - used) }
46
+ }
47
+
48
+ /** Whether a held capability value answers a granted one: any flag for `true`, at least as much for a number. */
49
+ const covers = (held: unknown, value: true | number): boolean =>
50
+ value === true ? held != null && held !== false : typeof held === 'number' && held >= value
51
+
52
+ const withCapabilities = (plan: PaymentPlan, grants: readonly PaymentGrantRecord[]): PaymentPlan => {
53
+ // A capability grant, or a units grant carrying the capability its units need.
54
+ const granted = grants.filter(grant => typeof grant.capability === 'string' && grant.capability !== '')
55
+ if (granted.length === 0) {
56
+ return plan
57
+ }
58
+ let capabilities: PlanCapability[] = [...(plan.capabilities ?? [])]
59
+ for (const grant of granted) {
60
+ const { scope, permission, atLeast } = entitlementParamHelper.parseEntitlementParam(grant.capability!)
61
+ if (scope == null || scope === '' || permission === '' || scope === CAPABILITY_LIMIT_SCOPE) {
62
+ continue
63
+ }
64
+ const value: true | number = atLeast ?? true
65
+ const covered = capabilities.some(set => set.scope === scope && set.promo == null
66
+ && covers(set.permissions?.[permission], value))
67
+ if (covered) {
68
+ continue
69
+ }
70
+ // The grant's row replaces the plan's (a promo's, or a smaller magnitude): one row per permission.
71
+ capabilities = capabilities.map(set => set.scope !== scope || set.permissions?.[permission] == null ? set : {
72
+ ...set, permissions: Object.fromEntries(Object.entries(set.permissions).filter(([key]) => key !== permission)),
73
+ })
74
+ capabilities.push({ scope, permissions: { [permission]: value } })
75
+ }
76
+
77
+ return { ...plan, capabilities }
78
+ }
79
+
80
+ const windowOf = (grantId: string): string => `${GRANT_WINDOW_PREFIX}${grantId}`
81
+
82
+ const grantIdOf = (window: string | null | undefined): string | null =>
83
+ typeof window === 'string' && window.startsWith(GRANT_WINDOW_PREFIX) && window.length > GRANT_WINDOW_PREFIX.length
84
+ ? window.slice(GRANT_WINDOW_PREFIX.length) : null
85
+
86
+ return { inForceAt, unitsOf, unitsFold, foldLimitView, withCapabilities, windowOf, grantIdOf }
87
+ }
88
+
89
+ export const grantFoldHelper = createGrantFoldHelper()
@@ -0,0 +1,42 @@
1
+ import type {
2
+ EntitlementGrantListOptions, EntitlementGrantRevocation, EntitlementGrantRevokeOptions, EntitlementGrantSpec,
3
+ PaymentGrantRecord,
4
+ } from '../types.js'
5
+
6
+ /**
7
+ * A context's entitlement grants (`payment-grant`): extra units of a limit or a capability, given to
8
+ * one organization beside its plan — Mongo only, so it works in an unmanaged process too.
9
+ *
10
+ * - `units` are consumed only after the plan's own allowance is exhausted (`consume`), returned by a
11
+ * release, folded into the limit's `limit` / `used` / `remaining` everywhere a limit is read, and
12
+ * rebuilt from their usage events by `reconcileCounters`.
13
+ * - `capability` grants — and the capability a `units` grant may carry — are merged into the
14
+ * effective plan's capabilities while in force.
15
+ * - A grant is in force while `active`, from `startsAt` until `endsAt`; a revoked or ended grant is
16
+ * ignored at read time — its used units stay consumed, its unused ones are gone.
17
+ */
18
+ export interface EntitlementGrantHelper {
19
+ /**
20
+ * Give an organization a grant, then tell `onEntitlementGrant` (`granted`). A `units` grant starts
21
+ * with nothing used.
22
+ *
23
+ * @throws UnsupportedArgumentError — `entityId`, `kind`, `limitKey`, `amount`, `capability`, `startsAt`, `endsAt`
24
+ * @throws LimitUnknown when no declared plan has the limit key
25
+ */
26
+ grant: (entityId: string, spec: EntitlementGrantSpec) => Promise<PaymentGrantRecord>
27
+ /**
28
+ * Revoke a grant now (`status: revoked`, `revokedAt`), then tell `onEntitlementGrant` (`revoked`).
29
+ * Idempotent: a revoked grant answers `changed: false` and nobody is told again. Used units stay
30
+ * consumed (their events keep their records' units); the unused ones are gone with the grant.
31
+ */
32
+ revoke: (grantId: string, opts?: EntitlementGrantRevokeOptions) => Promise<EntitlementGrantRevocation>
33
+ /** One grant by id, or `null`. */
34
+ get: (grantId: string) => Promise<PaymentGrantRecord | null>
35
+ /** An organization's grants, the newest first; `active` narrows to those (not) in force at `at`. */
36
+ list: (entityId: string, opts?: EntitlementGrantListOptions) => Promise<PaymentGrantRecord[]>
37
+ /**
38
+ * The grants in force at `at` (default now) — what plan resolution, the limit numbers and the
39
+ * entitlement view fold in. Empty in a context without the `payment-grant` resource.
40
+ */
41
+ inForce: (entityId: string, at?: Date) => Promise<PaymentGrantRecord[]>
42
+ }
package/src/grants.ts ADDED
@@ -0,0 +1,171 @@
1
+ import { CAPABILITY_LIMIT_SCOPE, LimitUnknown, entitlementParamHelper } from '@owlmeans/payment'
2
+ import { UnsupportedArgumentError, type Criteria } from '@owlmeans/resource'
3
+ import type { Context as ApiContext } from '@owlmeans/server-api'
4
+ import { memoHelper } from '@owlmeans/context'
5
+ import { EntitlementGrantKind, EntitlementGrantStatus } from './consts.js'
6
+ import type {
7
+ EntitlementGrantChange, EntitlementGrantListOptions, EntitlementGrantRevocation, EntitlementGrantRevokeOptions,
8
+ EntitlementGrantSpec, PaymentGrantRecord,
9
+ } from './types.js'
10
+ import { log } from './log.js'
11
+ import { paymentAccessOf } from './access.js'
12
+ import { paymentUtils } from './utils.js'
13
+ import { catalogueOf } from './catalogue.js'
14
+ import { grantFoldHelper } from './grant-fold.js'
15
+ import type { EntitlementGrantHelper } from './grants/types.js'
16
+
17
+ const isDate = (value: unknown): value is Date => value instanceof Date && Number.isFinite(value.getTime())
18
+
19
+ export const makeEntitlementGrantHelper = (ctx: ApiContext): EntitlementGrantHelper => {
20
+ const access = paymentAccessOf(ctx)
21
+
22
+ const newestFirst = (a: PaymentGrantRecord, b: PaymentGrantRecord): number =>
23
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
24
+
25
+ /** Observers hear a grant after it is stored; their throw is logged, the grant stands. */
26
+ const tell = async (grant: PaymentGrantRecord, change: EntitlementGrantChange): Promise<void> => {
27
+ try {
28
+ await access.observer().propagateEntitlementGrant({
29
+ entityId: grant.entityId, grant, change, eventKey: `grant:${grant.id}:${change}`,
30
+ }, ctx)
31
+ } catch (error) {
32
+ log.error('Entitlement grant observer failed', { entityId: grant.entityId, grantId: grant.id, change, error })
33
+ }
34
+ }
35
+
36
+ const assertUnits = async (spec: EntitlementGrantSpec): Promise<void> => {
37
+ if (typeof spec.limitKey !== 'string' || spec.limitKey === '') {
38
+ throw new UnsupportedArgumentError('limitKey')
39
+ }
40
+ if (typeof spec.amount !== 'number' || !Number.isSafeInteger(spec.amount) || spec.amount < 1) {
41
+ throw new UnsupportedArgumentError('amount')
42
+ }
43
+ const limitKey = spec.limitKey
44
+ if (!(await catalogueOf(ctx).catalogPlans()).some(plan => plan.limits?.[limitKey] != null)) {
45
+ throw new LimitUnknown(limitKey)
46
+ }
47
+ }
48
+
49
+ const assertCapability = (spec: Pick<EntitlementGrantSpec, 'capability'>): void => {
50
+ if (typeof spec.capability !== 'string' || spec.capability === '') {
51
+ throw new UnsupportedArgumentError('capability')
52
+ }
53
+ const { scope, permission } = entitlementParamHelper.parseEntitlementParam(spec.capability)
54
+ if (scope == null || scope === '' || permission === '' || scope === CAPABILITY_LIMIT_SCOPE) {
55
+ throw new UnsupportedArgumentError('capability')
56
+ }
57
+ }
58
+
59
+ const grant = async (entityId: string, spec: EntitlementGrantSpec): Promise<PaymentGrantRecord> => {
60
+ if (typeof entityId !== 'string' || entityId === '') {
61
+ throw new UnsupportedArgumentError('entityId')
62
+ }
63
+ const now = new Date()
64
+ const startsAt = spec.startsAt ?? now
65
+ if (!isDate(startsAt)) {
66
+ throw new UnsupportedArgumentError('startsAt')
67
+ }
68
+ if (spec.endsAt != null && (!isDate(spec.endsAt) || spec.endsAt.getTime() <= startsAt.getTime())) {
69
+ throw new UnsupportedArgumentError('endsAt')
70
+ }
71
+ switch (spec.kind) {
72
+ case EntitlementGrantKind.Units:
73
+ await assertUnits(spec)
74
+ if (spec.capability != null) {
75
+ assertCapability(spec)
76
+ }
77
+ break
78
+ case EntitlementGrantKind.Capability:
79
+ assertCapability(spec)
80
+ break
81
+ default:
82
+ throw new UnsupportedArgumentError('kind')
83
+ }
84
+
85
+ const units = spec.kind === EntitlementGrantKind.Units
86
+ const stored = await access.grantRecords().create(paymentUtils.compact<PaymentGrantRecord>({
87
+ entityId,
88
+ kind: spec.kind,
89
+ ...(units ? { limitKey: spec.limitKey, amount: spec.amount, used: 0 } : {}),
90
+ capability: spec.capability,
91
+ startsAt,
92
+ endsAt: spec.endsAt ?? undefined,
93
+ status: EntitlementGrantStatus.Active,
94
+ ref: spec.ref,
95
+ note: spec.note,
96
+ createdAt: now,
97
+ }))
98
+ log.info('Entitlement granted', paymentUtils.compact({
99
+ entityId, grantId: stored.id, kind: stored.kind, limitKey: stored.limitKey, amount: stored.amount,
100
+ capability: stored.capability, endsAt: stored.endsAt ?? undefined, ref: stored.ref,
101
+ }), { event: 'entitlement.granted' })
102
+ await tell(stored, 'granted')
103
+
104
+ return stored
105
+ }
106
+
107
+ const revoke = async (
108
+ grantId: string, opts: EntitlementGrantRevokeOptions = {},
109
+ ): Promise<EntitlementGrantRevocation> => {
110
+ const records = access.grantRecordsOf()
111
+ const found = records != null && typeof grantId === 'string' && grantId !== '' ? await records.load(grantId) : null
112
+ if (records == null || found == null || (opts.entityId != null && found.entityId !== opts.entityId)) {
113
+ return { grant: null, changed: false }
114
+ }
115
+ if (found.status === EntitlementGrantStatus.Revoked) {
116
+ return { grant: found, changed: false }
117
+ }
118
+
119
+ const at = new Date()
120
+ // A raw `$set` guarded by the status: a replace would clobber a unit held concurrently.
121
+ const won = await paymentUtils.conditionalSet(
122
+ records, paymentUtils.idCriteria(grantId, { status: EntitlementGrantStatus.Active }),
123
+ { status: EntitlementGrantStatus.Revoked, revokedAt: at },
124
+ )
125
+ const stored = await records.load(grantId) ?? { ...found, status: EntitlementGrantStatus.Revoked, revokedAt: at }
126
+ if (!won) {
127
+ return { grant: stored, changed: false }
128
+ }
129
+ log.info('Entitlement revoked', paymentUtils.compact({
130
+ entityId: stored.entityId, grantId, kind: stored.kind, limitKey: stored.limitKey, used: stored.used,
131
+ capability: stored.capability,
132
+ }), { event: 'entitlement.revoked' })
133
+ await tell(stored, 'revoked')
134
+
135
+ return { grant: stored, changed: true }
136
+ }
137
+
138
+ const get = async (grantId: string): Promise<PaymentGrantRecord | null> => {
139
+ const records = access.grantRecordsOf()
140
+
141
+ return records != null && typeof grantId === 'string' && grantId !== '' ? await records.load(grantId) : null
142
+ }
143
+
144
+ const list = async (entityId: string, opts: EntitlementGrantListOptions = {}): Promise<PaymentGrantRecord[]> => {
145
+ const records = access.grantRecordsOf()
146
+ if (records == null) {
147
+ return []
148
+ }
149
+ const at = opts.at ?? new Date()
150
+ const where = paymentUtils.compact({ entityId, kind: opts.kind, limitKey: opts.limitKey })
151
+ const { items } = await records.list(where as Criteria<PaymentGrantRecord>, { size: 0 })
152
+
153
+ return items.filter(item => opts.active == null || grantFoldHelper.inForceAt(item, at) === opts.active)
154
+ .sort(newestFirst)
155
+ }
156
+
157
+ const inForce = async (entityId: string, at: Date = new Date()): Promise<PaymentGrantRecord[]> => {
158
+ const records = access.grantRecordsOf()
159
+ if (records == null) {
160
+ return []
161
+ }
162
+ const { items } = await records.list({ entityId, status: EntitlementGrantStatus.Active }, { size: 0 })
163
+
164
+ return items.filter(item => grantFoldHelper.inForceAt(item, at))
165
+ }
166
+
167
+ return { grant, revoke, get, list, inForce }
168
+ }
169
+
170
+ /** The entitlement grants of a context — one per context; also `paymentAccessOf(ctx).grants()`. */
171
+ export const entitlementGrantsOf = memoHelper.oncePer(makeEntitlementGrantHelper)