@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.
- package/README.md +1 -1
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-payment/SKILL.md +47 -5
- package/build/access/types.d.ts +8 -1
- package/build/access/types.d.ts.map +1 -1
- package/build/access.d.ts.map +1 -1
- package/build/access.js +8 -2
- package/build/access.js.map +1 -1
- package/build/catalogue/types.d.ts +3 -1
- package/build/catalogue/types.d.ts.map +1 -1
- package/build/catalogue.d.ts.map +1 -1
- package/build/catalogue.js +15 -10
- package/build/catalogue.js.map +1 -1
- package/build/commit/types.d.ts +17 -2
- package/build/commit/types.d.ts.map +1 -1
- package/build/commit.d.ts.map +1 -1
- package/build/commit.js +40 -5
- package/build/commit.js.map +1 -1
- package/build/consts.d.ts +17 -0
- package/build/consts.d.ts.map +1 -1
- package/build/consts.js +19 -0
- package/build/consts.js.map +1 -1
- package/build/entitlement.d.ts.map +1 -1
- package/build/entitlement.js +7 -1
- package/build/entitlement.js.map +1 -1
- package/build/grant-fold/types.d.ts +41 -0
- package/build/grant-fold/types.d.ts.map +1 -0
- package/build/grant-fold/types.js +2 -0
- package/build/grant-fold/types.js.map +1 -0
- package/build/grant-fold.d.ts +4 -0
- package/build/grant-fold.d.ts.map +1 -0
- package/build/grant-fold.js +64 -0
- package/build/grant-fold.js.map +1 -0
- package/build/grants/types.d.ts +39 -0
- package/build/grants/types.d.ts.map +1 -0
- package/build/grants/types.js +2 -0
- package/build/grants/types.js.map +1 -0
- package/build/grants.d.ts +6 -0
- package/build/grants.d.ts.map +1 -0
- package/build/grants.js +141 -0
- package/build/grants.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2 -0
- package/build/index.js.map +1 -1
- package/build/observer.d.ts +3 -0
- package/build/observer.d.ts.map +1 -1
- package/build/observer.js +6 -0
- package/build/observer.js.map +1 -1
- package/build/reconcile/types.d.ts +4 -2
- package/build/reconcile/types.d.ts.map +1 -1
- package/build/reconcile.d.ts.map +1 -1
- package/build/reconcile.js +3 -1
- package/build/reconcile.js.map +1 -1
- package/build/resource.d.ts +2 -1
- package/build/resource.d.ts.map +1 -1
- package/build/resource.js +10 -2
- package/build/resource.js.map +1 -1
- package/build/schemas.d.ts +2 -1
- package/build/schemas.d.ts.map +1 -1
- package/build/schemas.js +16 -2
- package/build/schemas.js.map +1 -1
- package/build/service.d.ts +3 -3
- package/build/service.d.ts.map +1 -1
- package/build/service.js +7 -5
- package/build/service.js.map +1 -1
- package/build/subscription/types.d.ts +12 -2
- package/build/subscription/types.d.ts.map +1 -1
- package/build/subscription.d.ts.map +1 -1
- package/build/subscription.js +14 -3
- package/build/subscription.js.map +1 -1
- package/build/types.d.ts +125 -0
- package/build/types.d.ts.map +1 -1
- package/build/usage/types.d.ts +25 -8
- package/build/usage/types.d.ts.map +1 -1
- package/build/usage.d.ts.map +1 -1
- package/build/usage.js +201 -46
- package/build/usage.js.map +1 -1
- package/build/utils/types.d.ts +5 -0
- package/build/utils/types.d.ts.map +1 -1
- package/build/utils.d.ts.map +1 -1
- package/build/utils.js +4 -2
- package/build/utils.js.map +1 -1
- package/package.json +19 -19
- package/src/access/types.ts +8 -1
- package/src/access.ts +12 -3
- package/src/catalogue/types.ts +3 -1
- package/src/catalogue.ts +17 -13
- package/src/commit/types.ts +17 -2
- package/src/commit.ts +47 -6
- package/src/consts.ts +20 -0
- package/src/entitlement.ts +8 -1
- package/src/grant-fold/types.ts +42 -0
- package/src/grant-fold.ts +89 -0
- package/src/grants/types.ts +42 -0
- package/src/grants.ts +171 -0
- package/src/index.ts +4 -0
- package/src/observer.ts +8 -1
- package/src/reconcile/types.ts +4 -2
- package/src/reconcile.ts +3 -1
- package/src/resource.ts +20 -7
- package/src/schemas.ts +20 -5
- package/src/service.ts +9 -6
- package/src/subscription/types.ts +12 -2
- package/src/subscription.ts +15 -2
- package/src/types.ts +129 -0
- package/src/usage/types.ts +25 -8
- package/src/usage.ts +235 -48
- package/src/utils/types.ts +5 -0
- package/src/utils.ts +6 -2
- package/tests/fake-stripe.ts +24 -7
- package/tests/grants.spec.ts +276 -0
- package/tests/internal-plan.spec.ts +112 -0
- package/tests/usage.integration.spec.ts +32 -0
package/src/index.ts
CHANGED
|
@@ -21,6 +21,10 @@ export type * from './catalogue/types.js'
|
|
|
21
21
|
export * from './catalogue.js'
|
|
22
22
|
export type * from './usage/types.js'
|
|
23
23
|
export * from './usage.js'
|
|
24
|
+
export type * from './grant-fold/types.js'
|
|
25
|
+
export * from './grant-fold.js'
|
|
26
|
+
export type * from './grants/types.js'
|
|
27
|
+
export * from './grants.js'
|
|
24
28
|
export type * from './subscription/types.js'
|
|
25
29
|
export * from './subscription.js'
|
|
26
30
|
export type * from './commit/types.js'
|
package/src/observer.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { createLazyService } from '@owlmeans/context'
|
|
|
2
2
|
import { PAYMENT_OBSERVER } from './consts.js'
|
|
3
3
|
import type {
|
|
4
4
|
CancellationCallback, CompletionObserver, Config, ConsentCallback, Context, DisputeCallback,
|
|
5
|
-
PaymentFailedCallback, RefundCallback, SubscriptionCallback, TopUpCallback,
|
|
5
|
+
EntitlementGrantCallback, PaymentFailedCallback, RefundCallback, SubscriptionCallback, TopUpCallback,
|
|
6
|
+
WithdrawalCallback,
|
|
6
7
|
} from './types.js'
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -13,6 +14,9 @@ import type {
|
|
|
13
14
|
* The consumer-rights callbacks (`onConsent`, `onWithdrawal`, `onCancellation`) run after the
|
|
14
15
|
* records and the paygate steps of their act; a throw is recorded as an `observers` event and
|
|
15
16
|
* retried by the consumer-rights `reconcile()` — they, too, are idempotent by `eventKey`.
|
|
17
|
+
*
|
|
18
|
+
* `onEntitlementGrant` runs in the process that gave or revoked the grant, right after the write;
|
|
19
|
+
* a throw is logged by the grant helper and never undoes the grant.
|
|
16
20
|
*/
|
|
17
21
|
export const makeCompletionObserverService = (
|
|
18
22
|
alias: string = PAYMENT_OBSERVER,
|
|
@@ -25,6 +29,7 @@ export const makeCompletionObserverService = (
|
|
|
25
29
|
const consent: ConsentCallback[] = []
|
|
26
30
|
const withdrawal: WithdrawalCallback[] = []
|
|
27
31
|
const cancellation: CancellationCallback[] = []
|
|
32
|
+
const entitlementGrant: EntitlementGrantCallback[] = []
|
|
28
33
|
|
|
29
34
|
const run = async <E>(callbacks: Array<(event: E, ctx: never) => Promise<void>>, event: E, ctx: unknown) => {
|
|
30
35
|
for (const callback of callbacks) {
|
|
@@ -41,6 +46,7 @@ export const makeCompletionObserverService = (
|
|
|
41
46
|
onConsent: cb => { consent.push(cb) },
|
|
42
47
|
onWithdrawal: cb => { withdrawal.push(cb) },
|
|
43
48
|
onCancellation: cb => { cancellation.push(cb) },
|
|
49
|
+
onEntitlementGrant: cb => { entitlementGrant.push(cb) },
|
|
44
50
|
propagateTopUp: async (completion, ctx) => { await run(topUp, completion, ctx) },
|
|
45
51
|
propagateSubscription: async (event, ctx) => { await run(subscription, event, ctx) },
|
|
46
52
|
propagateRefund: async (event, ctx) => { await run(refund, event, ctx) },
|
|
@@ -49,6 +55,7 @@ export const makeCompletionObserverService = (
|
|
|
49
55
|
propagateConsent: async (event, ctx) => { await run(consent, event, ctx) },
|
|
50
56
|
propagateWithdrawal: async (event, ctx) => { await run(withdrawal, event, ctx) },
|
|
51
57
|
propagateCancellation: async (event, ctx) => { await run(cancellation, event, ctx) },
|
|
58
|
+
propagateEntitlementGrant: async (event, ctx) => { await run(entitlementGrant, event, ctx) },
|
|
52
59
|
}, service => async () => { service.initialized = true })
|
|
53
60
|
}
|
|
54
61
|
|
package/src/reconcile/types.ts
CHANGED
|
@@ -5,11 +5,13 @@ import type { ReconcileAllOptions, ReconcileAllResult, ReconcileEntityOptions }
|
|
|
5
5
|
export interface ReconcileHelper {
|
|
6
6
|
/**
|
|
7
7
|
* Repair one entity: optionally re-read its paygate subscriptions, grant the free plan when it holds
|
|
8
|
-
* nothing entitling, recompute its limit counters from the ledger, and
|
|
8
|
+
* nothing entitling, recompute its limit counters and its units grants' `used` from the ledger, and
|
|
9
|
+
* return its view.
|
|
9
10
|
*/
|
|
10
11
|
reconcileEntity: (entityId: string, opts?: ReconcileEntityOptions) => Promise<EntitlementView>
|
|
11
12
|
/**
|
|
12
|
-
* Repair every entity the payment store knows
|
|
13
|
+
* Repair every entity the payment store knows (its subscriptions, usage events and entitlement
|
|
14
|
+
* grants), plus `entities`: counters — and each units grant's `used` — from the ledger in one
|
|
13
15
|
* pass, then per entity the optional resync and the free-plan backfill. A failing entity is counted
|
|
14
16
|
* and logged, never fatal.
|
|
15
17
|
*/
|
package/src/reconcile.ts
CHANGED
|
@@ -53,7 +53,9 @@ export const makeReconcileHelper = (ctx: ApiContext): ReconcileHelper => {
|
|
|
53
53
|
|
|
54
54
|
const knownEntities = async (): Promise<Set<string>> => {
|
|
55
55
|
const ids = new Set<string>()
|
|
56
|
-
|
|
56
|
+
const grants = access.grantRecordsOf()
|
|
57
|
+
const sources = [access.subscriptions(), access.usageEvents(), ...(grants != null ? [grants] : [])]
|
|
58
|
+
for (const resource of sources as unknown as Distinct[]) {
|
|
57
59
|
for (const id of await resource.collection.distinct('entityId', {})) {
|
|
58
60
|
if (typeof id === 'string' && id !== '') {
|
|
59
61
|
ids.add(id)
|
package/src/resource.ts
CHANGED
|
@@ -2,21 +2,21 @@ import type { ResourceMaker } from '@owlmeans/resource'
|
|
|
2
2
|
import { makeMongoResource } from '@owlmeans/mongo-resource'
|
|
3
3
|
import {
|
|
4
4
|
RES_BILLING_PROFILE, RES_CONSUMER_CONSENT, RES_CONSUMER_DECLARATION, RES_CONSUMER_EVENT, RES_PAYGATE_CUSTOMER,
|
|
5
|
-
RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT,
|
|
6
|
-
RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
|
|
5
|
+
RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_GRANT, RES_PAYMENT_PURCHASE,
|
|
6
|
+
RES_PAYMENT_SUBSCRIPTION, RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
|
|
7
7
|
} from './consts.js'
|
|
8
8
|
import {
|
|
9
9
|
BillingProfileSchema, ConsumerConsentSchema, ConsumerDeclarationSchema, PaygateCustomerSchema,
|
|
10
|
-
PaymentFulfillmentSchema, PaymentSubscriptionSchema, PaymentUsageCounterSchema,
|
|
11
|
-
PaymentWebhookSchema, PurchaseSchema, ConsumerEventSchema, FingerprintSchema,
|
|
10
|
+
PaymentFulfillmentSchema, PaymentGrantSchema, PaymentSubscriptionSchema, PaymentUsageCounterSchema,
|
|
11
|
+
PaymentUsageSchema, PaymentWebhookSchema, PurchaseSchema, ConsumerEventSchema, FingerprintSchema,
|
|
12
12
|
} from './schemas.js'
|
|
13
13
|
import type {
|
|
14
14
|
BillingProfileRecord, BillingProfileResource, ConsumerConsentRecord, ConsumerConsentResource,
|
|
15
15
|
ConsumerDeclarationRecord, ConsumerDeclarationResource, ConsumerEventRecord, ConsumerEventResource,
|
|
16
16
|
FingerprintRecord, FingerprintResource, PaygateCustomerRecord, PaygateCustomerResource, PaymentFulfillmentRecord,
|
|
17
|
-
PaymentFulfillmentResource,
|
|
18
|
-
|
|
19
|
-
PaymentWebhookResource, PurchaseRecord, PurchaseResource,
|
|
17
|
+
PaymentFulfillmentResource, PaymentGrantRecord, PaymentGrantResource, PaymentSubscriptionRecord,
|
|
18
|
+
PaymentSubscriptionResource, PaymentUsageCounterRecord, PaymentUsageCounterResource, PaymentUsageRecord,
|
|
19
|
+
PaymentUsageResource, PaymentWebhookRecord, PaymentWebhookResource, PurchaseRecord, PurchaseResource,
|
|
20
20
|
} from './types.js'
|
|
21
21
|
|
|
22
22
|
export const makePaygateCustomerResource: ResourceMaker<PaygateCustomerRecord, PaygateCustomerResource> = (
|
|
@@ -103,6 +103,19 @@ export const makeUsageCounterResource: ResourceMaker<PaymentUsageCounterRecord,
|
|
|
103
103
|
return resource
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
export const makeGrantResource: ResourceMaker<PaymentGrantRecord, PaymentGrantResource> = (
|
|
107
|
+
dbAlias, serviceAlias,
|
|
108
|
+
): PaymentGrantResource => {
|
|
109
|
+
const resource = makeMongoResource<PaymentGrantRecord, PaymentGrantResource>(
|
|
110
|
+
RES_PAYMENT_GRANT, dbAlias, serviceAlias,
|
|
111
|
+
)
|
|
112
|
+
resource.schema = PaymentGrantSchema
|
|
113
|
+
// What every resolution reads: the organization's active grants.
|
|
114
|
+
resource.index('entityStatus', { entityId: 1, status: 1, kind: 1, limitKey: 1 })
|
|
115
|
+
resource.index('entityCreated', { entityId: 1, createdAt: -1 })
|
|
116
|
+
return resource
|
|
117
|
+
}
|
|
118
|
+
|
|
106
119
|
export const makeFingerprintResource: ResourceMaker<FingerprintRecord, FingerprintResource> = (
|
|
107
120
|
dbAlias, serviceAlias,
|
|
108
121
|
): FingerprintResource => {
|
package/src/schemas.ts
CHANGED
|
@@ -5,11 +5,12 @@ import {
|
|
|
5
5
|
DeclarationChannelSchema, DeclarationKindSchema, PurchaseKindSchema, SubscriptionStatusSchema,
|
|
6
6
|
} from '@owlmeans/payment'
|
|
7
7
|
import { schema } from '@owlmeans/entrypoint'
|
|
8
|
+
import { EntitlementGrantKind, EntitlementGrantStatus } from './consts.js'
|
|
8
9
|
import type {
|
|
9
10
|
BillingProfileRecord, ConsumerConsentRecord, ConsumerDeclarationRecord, PaygateCustomerRecord,
|
|
10
|
-
PaymentFulfillmentRecord, PaymentSubscriptionRecord, PaymentUsageCounterRecord,
|
|
11
|
-
PaymentWebhookRecord, PurchaseRecord, ConsumerEventRecord, FingerprintRecord, PaygateParams,
|
|
12
|
-
ResyncSubscriptionsResult,
|
|
11
|
+
PaymentFulfillmentRecord, PaymentGrantRecord, PaymentSubscriptionRecord, PaymentUsageCounterRecord,
|
|
12
|
+
PaymentUsageRecord, PaymentWebhookRecord, PurchaseRecord, ConsumerEventRecord, FingerprintRecord, PaygateParams,
|
|
13
|
+
ResyncResult, ResyncSubscriptionsResult,
|
|
13
14
|
} from './types.js'
|
|
14
15
|
import { date, id, links, num, optBool, optNum, optStr, origin, str } from './consts.local.js'
|
|
15
16
|
|
|
@@ -40,7 +41,7 @@ export const PaymentSubscriptionSchema = {
|
|
|
40
41
|
periodStart: optDate, periodEnd: optDate, cancelAtPeriodEnd: optBool, canceledAt: optDate,
|
|
41
42
|
endedAt: optDate, pausedAt: optDate, trialEnd: optDate, latestInvoiceId: optStr, customerId: optStr,
|
|
42
43
|
disputedAt: optDate, disputeStatus: optStr, createdAt: date, updatedAt: optDate, syncedAt: optDate,
|
|
43
|
-
lastEventId: optStr, initialPropagatedAt: optDate, currency: optStr,
|
|
44
|
+
lastEventId: optStr, initialPropagatedAt: optDate, restartedAt: optDate, currency: optStr,
|
|
44
45
|
checkoutSessionId: optStr, purchaseId: optStr, firstInvoiceId: optStr, country: optStr, email: optStr,
|
|
45
46
|
amountTotalMinor: optNum, amountTaxMinor: optNum, termsAccepted: optBool, startRequestId: optStr,
|
|
46
47
|
withdrawnAt: optDate,
|
|
@@ -64,7 +65,7 @@ export const PaymentSubscriptionSchema = {
|
|
|
64
65
|
nullable: true,
|
|
65
66
|
properties: {
|
|
66
67
|
planSku: str, rank: num, status: SubscriptionStatusSchema, cancelAtPeriodEnd: optBool,
|
|
67
|
-
pausedAt: optDate, renewedInvoiceId: optStr,
|
|
68
|
+
pausedAt: optDate, renewedInvoiceId: optStr, restartedAt: optDate,
|
|
68
69
|
},
|
|
69
70
|
required: ['planSku', 'rank', 'status'],
|
|
70
71
|
additionalProperties: false,
|
|
@@ -124,6 +125,20 @@ export const PaymentUsageCounterSchema = {
|
|
|
124
125
|
additionalProperties: false,
|
|
125
126
|
} as unknown as JSONSchemaType<PaymentUsageCounterRecord>
|
|
126
127
|
|
|
128
|
+
export const PaymentGrantSchema = {
|
|
129
|
+
type: 'object',
|
|
130
|
+
properties: {
|
|
131
|
+
id, entityId: str,
|
|
132
|
+
kind: { type: 'string', enum: Object.values(EntitlementGrantKind) },
|
|
133
|
+
limitKey: optStr, capability: optStr, amount: optNum, used: optNum,
|
|
134
|
+
startsAt: date, endsAt: optDate,
|
|
135
|
+
status: { type: 'string', enum: Object.values(EntitlementGrantStatus) },
|
|
136
|
+
ref: optStr, note: optStr, createdAt: date, revokedAt: optDate,
|
|
137
|
+
},
|
|
138
|
+
required: ['entityId', 'kind', 'startsAt', 'status', 'createdAt'],
|
|
139
|
+
additionalProperties: false,
|
|
140
|
+
} as unknown as JSONSchemaType<PaymentGrantRecord>
|
|
141
|
+
|
|
127
142
|
/** An optional enum: `null` must be listed for a validator to accept it. */
|
|
128
143
|
const nullableEnum = (values: readonly unknown[]) => ({ type: 'string', enum: [...values, null], nullable: true })
|
|
129
144
|
|
package/src/service.ts
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
7
7
|
import {
|
|
8
8
|
ENTITLEMENT_SERVICE, GATEWAY_SERVICE, RES_PAYGATE_CUSTOMER, RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT,
|
|
9
|
-
RES_PAYMENT_SUBSCRIPTION, RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
|
|
9
|
+
RES_PAYMENT_GRANT, RES_PAYMENT_SUBSCRIPTION, RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
|
|
10
10
|
} from './consts.js'
|
|
11
11
|
import { registerConsumerRights } from './consumer/service.js'
|
|
12
12
|
import { makeEntitlementService } from './entitlement.js'
|
|
@@ -14,8 +14,8 @@ import { makeCapabilityGate } from './gate.js'
|
|
|
14
14
|
import { makeLimitGate } from './limit.js'
|
|
15
15
|
import { appendCompletionObserver } from './observer.js'
|
|
16
16
|
import {
|
|
17
|
-
makeFingerprintResource, makeFulfillmentResource,
|
|
18
|
-
makeUsageCounterResource, makeUsageResource, makeWebhookResource,
|
|
17
|
+
makeFingerprintResource, makeFulfillmentResource, makeGrantResource, makePaygateCustomerResource,
|
|
18
|
+
makeSubscriptionResource, makeUsageCounterResource, makeUsageResource, makeWebhookResource,
|
|
19
19
|
} from './resource.js'
|
|
20
20
|
import type {
|
|
21
21
|
Config, Context, GatewayService, PaymentGatewayOptions, PaymentPlan, GatewayServiceOptions, StripeBootstrapOptions,
|
|
@@ -99,6 +99,8 @@ export const makeGatewayService = (
|
|
|
99
99
|
? await portalOf(ctx).createPortalLink(await stripeOf(ctx), entityId, link) : unmanaged(),
|
|
100
100
|
grantInternalPlan: async (ctx, entityId, planSku, grant) =>
|
|
101
101
|
await subscriptionCommitOf(ctx).grantInternalPlan(entityId, planSku, grant),
|
|
102
|
+
revokeInternalPlan: async (ctx, entityId, planSku) =>
|
|
103
|
+
await subscriptionCommitOf(ctx).revokeInternalPlan(entityId, planSku),
|
|
102
104
|
resyncSubscription: async (ctx, ref) => managed
|
|
103
105
|
? await stripeSubscriptionsOf(ctx).resyncStripeSubscription(await stripeOf(ctx), ref) : unmanaged(),
|
|
104
106
|
resyncAll: async ctx => managed
|
|
@@ -127,9 +129,9 @@ export const makeGatewayService = (
|
|
|
127
129
|
}
|
|
128
130
|
|
|
129
131
|
/**
|
|
130
|
-
* Register the payment resources
|
|
131
|
-
*
|
|
132
|
-
* when not registered yet.
|
|
132
|
+
* Register the payment resources (the entitlement grants `payment-grant` included, on `dbAlias` like
|
|
133
|
+
* the others), the catalogue service, the completion observer, the gateway, both gate services, the
|
|
134
|
+
* entitlement service and the consumer-rights records and service — each only when not registered yet.
|
|
133
135
|
*
|
|
134
136
|
* `manage: false` registers the same surface for a process that reads entitlements but never talks
|
|
135
137
|
* to Stripe. Several managed processes of one deployment share the Stripe rows through one `owner`
|
|
@@ -146,6 +148,7 @@ export const appendPaymentGatewayService = <C extends Config, T extends Context<
|
|
|
146
148
|
[RES_PAYMENT_USAGE, makeUsageResource],
|
|
147
149
|
[RES_PAYMENT_USAGE_COUNTER, makeUsageCounterResource],
|
|
148
150
|
[RES_PAYMENT_FINGERPRINT, makeFingerprintResource],
|
|
151
|
+
[RES_PAYMENT_GRANT, makeGrantResource],
|
|
149
152
|
] as const
|
|
150
153
|
for (const [alias, maker] of makers) {
|
|
151
154
|
if (!ctx.hasResource(alias)) {
|
|
@@ -6,7 +6,8 @@ export interface SubscriptionHelper {
|
|
|
6
6
|
propagatedStateOf: (record: PaymentSubscriptionRecord, renewedInvoiceId?: string) => PropagatedState
|
|
7
7
|
/**
|
|
8
8
|
* What one subscription change means — the first rule that matches:
|
|
9
|
-
* `created` (first entitling state ever propagated
|
|
9
|
+
* `created` (first entitling state ever propagated, or an entitling state under `opts.restart`),
|
|
10
|
+
* `canceled`, `paused`, `resumed`,
|
|
10
11
|
* `upgraded`/`downgraded` (plan change by rank; equal rank reads as an upgrade),
|
|
11
12
|
* `cancel-scheduled`, `cancel-undone`, `renewed` (once per invoice), `past-due`, `suspended`,
|
|
12
13
|
* `trial-ending`; otherwise nothing an observer is told about.
|
|
@@ -14,10 +15,19 @@ export interface SubscriptionHelper {
|
|
|
14
15
|
classifySubscriptionChange: (
|
|
15
16
|
previous: PropagatedState | null, current: PaymentSubscriptionRecord, opts?: CommitOptions,
|
|
16
17
|
) => SubscriptionChange | null
|
|
17
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* The idempotency key a consumer keys the side effect of a change by. A `created` key is
|
|
20
|
+
* `subscription:<id>:created:<createdAt ISO>`, plus `:<restartedAt ISO>` for a row that began
|
|
21
|
+
* entitling again after it ended.
|
|
22
|
+
*/
|
|
18
23
|
subscriptionEventKey: (record: PaymentSubscriptionRecord, change: SubscriptionChange, opts?: CommitOptions) => string
|
|
19
24
|
/** Whether a row's stored state changed in a field that matters. */
|
|
20
25
|
materiallyDiffers: (previous: PaymentSubscriptionRecord, next: PaymentSubscriptionRecord) => boolean
|
|
26
|
+
/**
|
|
27
|
+
* Whether a row entitles at `at`: an entitling status and, for an internal grant, a period end
|
|
28
|
+
* still ahead (a paygate row's period end never stops it — its paygate does).
|
|
29
|
+
*/
|
|
30
|
+
entitlesAt: (record: PaymentSubscriptionRecord, at: Date) => boolean
|
|
21
31
|
/** Whether a row's classification inputs differ from what was last propagated. */
|
|
22
32
|
stateDiffers: (state: PropagatedState, record: PaymentSubscriptionRecord) => boolean
|
|
23
33
|
}
|
package/src/subscription.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ENTITLING_STATUSES, SubscriptionStatus } from '@owlmeans/payment'
|
|
1
|
+
import { ENTITLING_STATUSES, INTERNAL_PAYGATE, SubscriptionStatus } from '@owlmeans/payment'
|
|
2
2
|
import type { PaymentSubscriptionRecord, PropagatedState, SubscriptionChange, CommitOptions } from './types.js'
|
|
3
3
|
import { ENDED, MATERIAL } from './consts.local.js'
|
|
4
4
|
import { paymentUtils } from './utils.js'
|
|
@@ -16,6 +16,7 @@ export const createSubscriptionHelper = (): SubscriptionHelper => {
|
|
|
16
16
|
cancelAtPeriodEnd: record.cancelAtPeriodEnd === true,
|
|
17
17
|
pausedAt: record.pausedAt ?? undefined,
|
|
18
18
|
renewedInvoiceId: renewedInvoiceId ?? undefined,
|
|
19
|
+
restartedAt: record.restartedAt ?? undefined,
|
|
19
20
|
})
|
|
20
21
|
|
|
21
22
|
const classifySubscriptionChange = (
|
|
@@ -25,6 +26,10 @@ export const createSubscriptionHelper = (): SubscriptionHelper => {
|
|
|
25
26
|
if (previous == null) {
|
|
26
27
|
return active ? 'created' : null
|
|
27
28
|
}
|
|
29
|
+
// A row entitling again after it ended (an internal re-grant) starts anew, whatever was last told.
|
|
30
|
+
if (opts.restart === true && active) {
|
|
31
|
+
return 'created'
|
|
32
|
+
}
|
|
28
33
|
if (ENDED.includes(current.status) && !ENDED.includes(previous.status)) {
|
|
29
34
|
return 'canceled'
|
|
30
35
|
}
|
|
@@ -66,7 +71,9 @@ export const createSubscriptionHelper = (): SubscriptionHelper => {
|
|
|
66
71
|
const base = `subscription:${record.externalId}:${change}`
|
|
67
72
|
switch (change) {
|
|
68
73
|
case 'created':
|
|
74
|
+
// A row that began entitling again after it ended is keyed apart from its first start.
|
|
69
75
|
return `${base}:${new Date(record.createdAt).toISOString()}`
|
|
76
|
+
+ (record.restartedAt != null ? `:${new Date(record.restartedAt).toISOString()}` : '')
|
|
70
77
|
case 'renewed':
|
|
71
78
|
return `${base}:${opts.invoiceId ?? record.latestInvoiceId ?? 'unknown'}`
|
|
72
79
|
case 'upgraded':
|
|
@@ -93,12 +100,18 @@ export const createSubscriptionHelper = (): SubscriptionHelper => {
|
|
|
93
100
|
const materiallyDiffers = (previous: PaymentSubscriptionRecord, next: PaymentSubscriptionRecord): boolean =>
|
|
94
101
|
MATERIAL.some(field => !sameValue(previous[field], next[field]))
|
|
95
102
|
|
|
103
|
+
const entitlesAt = (record: PaymentSubscriptionRecord, at: Date): boolean =>
|
|
104
|
+
ENTITLING_STATUSES.includes(record.status) && (record.paygate !== INTERNAL_PAYGATE
|
|
105
|
+
|| record.periodEnd == null || new Date(record.periodEnd).getTime() > at.getTime())
|
|
106
|
+
|
|
96
107
|
const stateDiffers = (state: PropagatedState, record: PaymentSubscriptionRecord): boolean =>
|
|
97
108
|
state.planSku !== record.planSku || state.rank !== record.rank || state.status !== record.status
|
|
98
109
|
|| (state.cancelAtPeriodEnd === true) !== (record.cancelAtPeriodEnd === true)
|
|
99
110
|
|| timeOf(state.pausedAt) !== timeOf(record.pausedAt)
|
|
100
111
|
|
|
101
|
-
return {
|
|
112
|
+
return {
|
|
113
|
+
propagatedStateOf, classifySubscriptionChange, subscriptionEventKey, materiallyDiffers, entitlesAt, stateDiffers,
|
|
114
|
+
}
|
|
102
115
|
}
|
|
103
116
|
|
|
104
117
|
export const subscriptionHelper = createSubscriptionHelper()
|
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 {}
|
|
@@ -368,9 +369,21 @@ export interface GatewayService extends InitializedService {
|
|
|
368
369
|
portalLink: (ctx: ApiContext, entityId: string, opts: PortalLinkOptions) => Promise<string>
|
|
369
370
|
/** @throws PaygateError('unmanaged') when `managed` is `false`. */
|
|
370
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
|
+
*/
|
|
371
377
|
grantInternalPlan: (
|
|
372
378
|
ctx: ApiContext, entityId: string, planSku: string, opts?: GrantInternalPlanOptions,
|
|
373
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>
|
|
374
387
|
/** @returns how many subscription rows changed */
|
|
375
388
|
resyncSubscription: (ctx: ApiContext, ref: SubscriptionRef) => Promise<number>
|
|
376
389
|
resyncAll: (ctx: ApiContext) => Promise<{ scanned: number; updated: number }>
|
|
@@ -623,6 +636,19 @@ export interface CancellationEvent {
|
|
|
623
636
|
declaredAt: Date
|
|
624
637
|
}
|
|
625
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
|
+
|
|
626
652
|
export interface TopUpCallback { (completion: TopUpCompletion, ctx: ApiContext): Promise<void> }
|
|
627
653
|
export interface SubscriptionCallback { (event: SubscriptionEvent, ctx: ApiContext): Promise<void> }
|
|
628
654
|
export interface RefundCallback { (event: RefundEvent, ctx: ApiContext): Promise<void> }
|
|
@@ -631,6 +657,7 @@ export interface PaymentFailedCallback { (event: PaymentFailedEvent, ctx: ApiCon
|
|
|
631
657
|
export interface ConsentCallback { (event: ConsentEvent, ctx: ApiContext): Promise<void> }
|
|
632
658
|
export interface WithdrawalCallback { (event: WithdrawalEvent, ctx: ApiContext): Promise<void> }
|
|
633
659
|
export interface CancellationCallback { (event: CancellationEvent, ctx: ApiContext): Promise<void> }
|
|
660
|
+
export interface EntitlementGrantCallback { (event: EntitlementGrantEvent, ctx: ApiContext): Promise<void> }
|
|
634
661
|
|
|
635
662
|
/**
|
|
636
663
|
* Callbacks run sequentially and are awaited. A paygate callback's throw escapes so the paygate
|
|
@@ -646,6 +673,12 @@ export interface CompletionObserver extends LazyService {
|
|
|
646
673
|
onConsent: (cb: ConsentCallback) => void
|
|
647
674
|
onWithdrawal: (cb: WithdrawalCallback) => void
|
|
648
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
|
|
649
682
|
propagateTopUp: (completion: TopUpCompletion, ctx: ApiContext) => Promise<void>
|
|
650
683
|
propagateSubscription: (event: SubscriptionEvent, ctx: ApiContext) => Promise<void>
|
|
651
684
|
propagateRefund: (event: RefundEvent, ctx: ApiContext) => Promise<void>
|
|
@@ -654,6 +687,7 @@ export interface CompletionObserver extends LazyService {
|
|
|
654
687
|
propagateConsent: (event: ConsentEvent, ctx: ApiContext) => Promise<void>
|
|
655
688
|
propagateWithdrawal: (event: WithdrawalEvent, ctx: ApiContext) => Promise<void>
|
|
656
689
|
propagateCancellation: (event: CancellationEvent, ctx: ApiContext) => Promise<void>
|
|
690
|
+
propagateEntitlementGrant: (event: EntitlementGrantEvent, ctx: ApiContext) => Promise<void>
|
|
657
691
|
}
|
|
658
692
|
|
|
659
693
|
// ---------------------------------------------------------------------------------------------
|
|
@@ -688,6 +722,8 @@ export interface PropagatedState {
|
|
|
688
722
|
pausedAt?: Date
|
|
689
723
|
/** The renewal invoice last reported as `renewed` — a renewal is reported once per invoice. */
|
|
690
724
|
renewedInvoiceId?: string
|
|
725
|
+
/** The row's `restartedAt` when observers were last told — a restart they never heard is told again. */
|
|
726
|
+
restartedAt?: Date
|
|
691
727
|
}
|
|
692
728
|
|
|
693
729
|
/**
|
|
@@ -729,6 +765,11 @@ export interface PaymentSubscriptionRecord extends ResourceRecord {
|
|
|
729
765
|
syncedAt?: Date
|
|
730
766
|
lastEventId?: string
|
|
731
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
|
|
732
773
|
propagated?: PropagatedState
|
|
733
774
|
/** The subscription's currency (lowercase). */
|
|
734
775
|
currency?: string
|
|
@@ -837,6 +878,82 @@ export interface PaymentUsageCounterRecord extends ResourceRecord {
|
|
|
837
878
|
}
|
|
838
879
|
export interface PaymentUsageCounterResource extends MongoResource<PaymentUsageCounterRecord> {}
|
|
839
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
|
+
|
|
840
957
|
/** One currency option of a synced price. */
|
|
841
958
|
export interface SyncedPriceOption {
|
|
842
959
|
currency: string
|
|
@@ -880,11 +997,18 @@ export interface FingerprintResource extends MongoResource<FingerprintRecord> {
|
|
|
880
997
|
// ---------------------------------------------------------------------------------------------
|
|
881
998
|
|
|
882
999
|
export interface EffectivePlan {
|
|
1000
|
+
/** The plan, with the row's `overrides` applied and the capability grants in force merged in. */
|
|
883
1001
|
plan: PaymentPlan
|
|
884
1002
|
/** The entitling row behind the plan; `null` when the entity falls back to the free plan. */
|
|
885
1003
|
subscription: PaymentSubscriptionRecord | null
|
|
886
1004
|
/** The declared free plan, when one exists. */
|
|
887
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[]
|
|
888
1012
|
}
|
|
889
1013
|
|
|
890
1014
|
export interface ConsumeRequest {
|
|
@@ -1484,6 +1608,11 @@ export interface CommitOptions {
|
|
|
1484
1608
|
* observers are not told and the paygate retries.
|
|
1485
1609
|
*/
|
|
1486
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
|
|
1487
1616
|
}
|
|
1488
1617
|
|
|
1489
1618
|
export interface CommitResult {
|
package/src/usage/types.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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.
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
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
|
}
|