@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.
- package/README.md +1 -1
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-payment/SKILL.md +74 -6
- 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/consumer/capture.d.ts.map +1 -1
- package/build/consumer/capture.js +2 -1
- package/build/consumer/capture.js.map +1 -1
- package/build/consumer/reconcile.d.ts.map +1 -1
- package/build/consumer/reconcile.js +2 -1
- package/build/consumer/reconcile.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/plugins/events.d.ts.map +1 -1
- package/build/plugins/events.js +5 -2
- package/build/plugins/events.js.map +1 -1
- package/build/plugins/session/types.d.ts +2 -0
- package/build/plugins/session/types.d.ts.map +1 -1
- package/build/plugins/session.d.ts.map +1 -1
- package/build/plugins/session.js +15 -2
- package/build/plugins/session.js.map +1 -1
- package/build/plugins/stripe.js +3 -3
- package/build/plugins/stripe.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 +129 -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 +22 -22
- 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/consumer/capture.ts +2 -1
- package/src/consumer/reconcile.ts +2 -1
- 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/plugins/events.ts +5 -2
- package/src/plugins/session/types.ts +2 -0
- package/src/plugins/session.ts +15 -2
- package/src/plugins/stripe.ts +3 -3
- 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 +133 -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/checkout.spec.ts +62 -0
- package/tests/consumer-fixtures.ts +7 -0
- package/tests/consumer-ops.spec.ts +12 -1
- package/tests/consumer-rights.spec.ts +35 -1
- package/tests/events.spec.ts +10 -0
- package/tests/fake-stripe.ts +35 -12
- 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/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)
|
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/plugins/events.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { customerLockHelper } from './customer-lock.js'
|
|
|
19
19
|
import { stripeSubscriptionsOf } from './subscriptions.js'
|
|
20
20
|
import { consumerRecordsOf } from '../consumer/records.js'
|
|
21
21
|
import { captureOf } from '../consumer/capture.js'
|
|
22
|
+
import { stripeSessionHelper } from './session.js'
|
|
22
23
|
|
|
23
24
|
/** `invoice.subscription`, top-level on the pinned API version. */
|
|
24
25
|
const subscriptionIdOfInvoice = (invoice: Stripe.Invoice): string | undefined =>
|
|
@@ -93,7 +94,7 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
93
94
|
await completeSubscriptionCheckout(session)
|
|
94
95
|
return
|
|
95
96
|
}
|
|
96
|
-
if (
|
|
97
|
+
if (!stripeSessionHelper.canFulfillPayment(session)) return
|
|
97
98
|
const metadata = session.metadata ?? {}
|
|
98
99
|
if (metadata.entityId == null || metadata.service == null || metadata.productSku == null) {
|
|
99
100
|
throw new PaygateError('metadata:owner')
|
|
@@ -441,6 +442,8 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
441
442
|
log.warn('Dispute matches no fulfillment or subscription', { disputeId: dispute.id })
|
|
442
443
|
return
|
|
443
444
|
}
|
|
445
|
+
const chargeId = paymentUtils.idOf(dispute.charge)
|
|
446
|
+
const charge = target.charge ?? (chargeId != null ? await paymentTargetOf(ctx).retrieveCharge(stripe, chargeId) : null)
|
|
444
447
|
const marks = { disputedAt: target.record.disputedAt ?? new Date(), disputeStatus: dispute.status }
|
|
445
448
|
if (target.kind === 'fulfillment') {
|
|
446
449
|
await access.fulfillments().update({ ...target.record, ...marks })
|
|
@@ -449,7 +452,7 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
449
452
|
}
|
|
450
453
|
await access.observer().propagateDispute(paymentUtils.compact({
|
|
451
454
|
...targetFields(target), disputeId: dispute.id, phase, status: dispute.status,
|
|
452
|
-
amountMinor: dispute.amount, currency: dispute.currency, eventKey: `dispute:${dispute.id}:${phase}`,
|
|
455
|
+
amountMinor: dispute.amount, paidMinor: charge?.amount, currency: dispute.currency, eventKey: `dispute:${dispute.id}:${phase}`,
|
|
453
456
|
}) as DisputeEvent, ctx)
|
|
454
457
|
log.info('Dispute changed', paymentUtils.compact({
|
|
455
458
|
entityId: target.record.entityId, target: target.kind, externalId: target.record.externalId,
|
|
@@ -4,6 +4,8 @@ import type { PaymentPlan, PaymentProduct } from '../../types.js'
|
|
|
4
4
|
|
|
5
5
|
/** The parts of a Stripe Checkout Session read from a plan or an answer alone — pure. */
|
|
6
6
|
export interface StripeSessionHelper {
|
|
7
|
+
/** Paid payments, or completed amount checkouts fully discounted with promotion codes enabled. */
|
|
8
|
+
canFulfillPayment: (session: Stripe.Checkout.Session) => boolean
|
|
7
9
|
/** The line item of an amount checkout, its pre-tax charge and its currency. @throws ProductError */
|
|
8
10
|
amountCheckoutLineItem: (
|
|
9
11
|
product: PaymentProduct, plan: PaymentPlan, amountMinor: number, behavior?: TaxBehavior,
|
package/src/plugins/session.ts
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import type Stripe from 'stripe'
|
|
2
|
-
import { ProductError, TaxBehavior, checkoutPricingHelper } from '@owlmeans/payment'
|
|
2
|
+
import { CheckoutPricingMode, ProductError, TaxBehavior, checkoutPricingHelper } from '@owlmeans/payment'
|
|
3
3
|
import type { PaymentPlan, PaymentProduct } from '../types.js'
|
|
4
4
|
import { NEEDS_POSTAL_CODE, NEEDS_POSTAL_CODE_OR_STATE } from './consts.local.js'
|
|
5
5
|
import type { StripeErrorShape } from './types.local.js'
|
|
6
6
|
import type { StripeSessionHelper } from './session/types.js'
|
|
7
7
|
|
|
8
8
|
export const createStripeSessionHelper = (): StripeSessionHelper => {
|
|
9
|
+
const canFulfillPayment = (session: Stripe.Checkout.Session): boolean => {
|
|
10
|
+
if (session.mode !== 'payment') return false
|
|
11
|
+
if (session.payment_status === 'paid'
|
|
12
|
+
&& (session.amount_total !== 0 || session.metadata?.pricingMode !== CheckoutPricingMode.Amount)) return true
|
|
13
|
+
|
|
14
|
+
return (session.payment_status === 'no_payment_required' || session.payment_status === 'paid')
|
|
15
|
+
&& session.status === 'complete' && session.metadata?.pricingMode === CheckoutPricingMode.Amount
|
|
16
|
+
&& session.allow_promotion_codes === true && session.amount_total === 0
|
|
17
|
+
&& Number.isSafeInteger(session.amount_subtotal) && (session.amount_subtotal ?? 0) > 0
|
|
18
|
+
&& session.total_details?.amount_discount === session.amount_subtotal
|
|
19
|
+
&& session.total_details?.amount_tax === 0
|
|
20
|
+
}
|
|
21
|
+
|
|
9
22
|
const amountCheckoutLineItem = (
|
|
10
23
|
product: PaymentProduct, plan: PaymentPlan, amountMinor: number, behavior: TaxBehavior = TaxBehavior.Exclusive,
|
|
11
24
|
): { lineItem: Stripe.Checkout.SessionCreateParams.LineItem; chargeMinor: number; currency: string } => {
|
|
@@ -67,7 +80,7 @@ export const createStripeSessionHelper = (): StripeSessionHelper => {
|
|
|
67
80
|
return (onTermsParam && aboutTerms) || (aboutTerms && /\burl\b/i.test(message) && /dashboard/i.test(message))
|
|
68
81
|
}
|
|
69
82
|
|
|
70
|
-
return { amountCheckoutLineItem, quantityCheckoutLineItem, isTaxLocatable, isMissingTermsUrl }
|
|
83
|
+
return { canFulfillPayment, amountCheckoutLineItem, quantityCheckoutLineItem, isTaxLocatable, isMissingTermsUrl }
|
|
71
84
|
}
|
|
72
85
|
|
|
73
86
|
export const stripeSessionHelper = createStripeSessionHelper()
|
package/src/plugins/stripe.ts
CHANGED
|
@@ -410,7 +410,8 @@ export const makeStripeCheckoutHelper = (ctx: ApiContext): StripeCheckoutHelper
|
|
|
410
410
|
const catalogueCurrency = (plan.amountPolicy?.currency ?? plan.currency ?? 'usd').toLowerCase()
|
|
411
411
|
const { buyer, customer } = await buyerOf(stripe, params, catalogueCurrency)
|
|
412
412
|
const pricing = await access.payment().pricingPolicy()
|
|
413
|
-
const
|
|
413
|
+
const stripePricing = await access.stripePricingConfig()
|
|
414
|
+
const settlement = stripePricing?.settlementCurrency?.toLowerCase()
|
|
414
415
|
const ttl = checkoutPolicyHelper.sessionTtlOf(plugins)
|
|
415
416
|
const now = new Date()
|
|
416
417
|
const expiresAt = ttl != null ? new Date((Math.floor(now.getTime() / 1000) + ttl) * 1000) : undefined
|
|
@@ -459,7 +460,7 @@ export const makeStripeCheckoutHelper = (ctx: ApiContext): StripeCheckoutHelper
|
|
|
459
460
|
currency: charged.currency,
|
|
460
461
|
}, {
|
|
461
462
|
mode: 'payment', line_items: [lineItem], invoice_creation: { enabled: true },
|
|
462
|
-
...checkoutOptions(pricing,
|
|
463
|
+
...checkoutOptions(pricing, stripePricing?.amountPromotionCodes === true, { locked: buyer.addressLocked, adaptive }),
|
|
463
464
|
...termsParams,
|
|
464
465
|
...(Object.keys(customText).length > 0 ? { custom_text: customText } : {}),
|
|
465
466
|
...expiry,
|
|
@@ -518,7 +519,6 @@ export const makeStripeCheckoutHelper = (ctx: ApiContext): StripeCheckoutHelper
|
|
|
518
519
|
// A subscription starts services at once: in scope (or unknown and protected) it needs the
|
|
519
520
|
// consumer's express start request, fresh and bound to this organization and plan.
|
|
520
521
|
const start = buyer.policy != null ? await access.consumerRightsOf()?.assertStartRequest(params.entityId, plan.sku, params.startRequestId) ?? null : null
|
|
521
|
-
const stripePricing = await access.stripePricingConfig()
|
|
522
522
|
const subscriptionPaymentMethodTypes = (stripePricing?.subscriptionPaymentMethodTypesByCurrency?.[currency]
|
|
523
523
|
?? stripePricing?.subscriptionPaymentMethodTypes) as string[] | undefined
|
|
524
524
|
const unitAmount = forced.unitAmount ?? price.unit_amount ?? undefined
|
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()
|