@owlmeans/server-payment 0.1.22-rc.0 → 0.2.0-alpha.1
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 +52 -54
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-payment/SKILL.md +272 -330
- package/agent-meta/skills/server-payment/parts/reference.md +3 -3
- package/build/access/types.d.ts +7 -16
- package/build/access/types.d.ts.map +1 -1
- package/build/access.d.ts.map +1 -1
- package/build/access.js +6 -8
- package/build/access.js.map +1 -1
- package/build/actions/resync.d.ts +3 -3
- package/build/actions/resync.js +5 -5
- package/build/actions/resync.js.map +1 -1
- package/build/actions/webhook.d.ts +4 -1
- package/build/actions/webhook.d.ts.map +1 -1
- package/build/actions/webhook.js +8 -4
- package/build/actions/webhook.js.map +1 -1
- package/build/bootstrap/types.d.ts +13 -7
- package/build/bootstrap/types.d.ts.map +1 -1
- package/build/bootstrap.d.ts +4 -4
- package/build/bootstrap.d.ts.map +1 -1
- package/build/bootstrap.js +19 -10
- package/build/bootstrap.js.map +1 -1
- package/build/catalogue/types.d.ts +3 -3
- package/build/catalogue/types.d.ts.map +1 -1
- package/build/catalogue.d.ts.map +1 -1
- package/build/catalogue.js +4 -8
- package/build/catalogue.js.map +1 -1
- package/build/checkout/types.d.ts +21 -0
- package/build/checkout/types.d.ts.map +1 -0
- package/build/{plugins/stripe → checkout}/types.js.map +1 -1
- package/build/checkout.d.ts +6 -0
- package/build/checkout.d.ts.map +1 -0
- package/build/checkout.js +374 -0
- package/build/checkout.js.map +1 -0
- package/build/config.d.ts +10 -16
- package/build/config.d.ts.map +1 -1
- package/build/config.js +18 -59
- package/build/config.js.map +1 -1
- package/build/consts.d.ts +3 -49
- package/build/consts.d.ts.map +1 -1
- package/build/consts.js +3 -61
- package/build/consts.js.map +1 -1
- package/build/consumer/cancellation/types.d.ts +6 -4
- package/build/consumer/cancellation/types.d.ts.map +1 -1
- package/build/consumer/cancellation.d.ts.map +1 -1
- package/build/consumer/cancellation.js +11 -5
- package/build/consumer/cancellation.js.map +1 -1
- package/build/consumer/capture/types.d.ts +8 -12
- package/build/consumer/capture/types.d.ts.map +1 -1
- package/build/consumer/capture.d.ts.map +1 -1
- package/build/consumer/capture.js +48 -53
- package/build/consumer/capture.js.map +1 -1
- package/build/consumer/index.d.ts +4 -0
- package/build/consumer/index.d.ts.map +1 -1
- package/build/consumer/index.js +2 -0
- package/build/consumer/index.js.map +1 -1
- package/build/consumer/reconcile.d.ts.map +1 -1
- package/build/consumer/reconcile.js +82 -72
- package/build/consumer/reconcile.js.map +1 -1
- package/build/consumer/records/types.d.ts +4 -4
- package/build/consumer/records/types.d.ts.map +1 -1
- package/build/consumer/records.d.ts.map +1 -1
- package/build/consumer/records.js +16 -13
- package/build/consumer/records.js.map +1 -1
- package/build/consumer/service.d.ts +2 -2
- package/build/consumer/service.d.ts.map +1 -1
- package/build/consumer/service.js +28 -21
- package/build/consumer/service.js.map +1 -1
- package/build/consumer/types.d.ts +1 -4
- package/build/consumer/types.d.ts.map +1 -1
- package/build/consumer/types.local.d.ts +1 -9
- package/build/consumer/types.local.d.ts.map +1 -1
- package/build/consumer/withdrawal/types.d.ts +14 -12
- package/build/consumer/withdrawal/types.d.ts.map +1 -1
- package/build/consumer/withdrawal.d.ts.map +1 -1
- package/build/consumer/withdrawal.js +55 -71
- package/build/consumer/withdrawal.js.map +1 -1
- package/build/index.d.ts +12 -6
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -4
- package/build/index.js.map +1 -1
- package/build/paygate/providers.d.ts +13 -0
- package/build/paygate/providers.d.ts.map +1 -0
- package/build/paygate/providers.js +38 -0
- package/build/paygate/providers.js.map +1 -0
- package/build/paygate/registry.d.ts +6 -0
- package/build/paygate/registry.d.ts.map +1 -0
- package/build/paygate/registry.js +37 -0
- package/build/paygate/registry.js.map +1 -0
- package/build/paygate/types.d.ts +577 -0
- package/build/paygate/types.d.ts.map +1 -0
- package/build/{plugins/session → paygate}/types.js.map +1 -1
- package/build/plan/types.d.ts +6 -1
- package/build/plan/types.d.ts.map +1 -1
- package/build/plan.d.ts.map +1 -1
- package/build/plan.js +16 -2
- package/build/plan.js.map +1 -1
- package/build/plugins/checkout-policy/types.d.ts +5 -3
- package/build/plugins/checkout-policy/types.d.ts.map +1 -1
- package/build/plugins/checkout-policy.d.ts.map +1 -1
- package/build/plugins/checkout-policy.js +5 -3
- package/build/plugins/checkout-policy.js.map +1 -1
- package/build/plugins/consts.local.d.ts +8 -10
- package/build/plugins/consts.local.d.ts.map +1 -1
- package/build/plugins/consts.local.js +2 -19
- package/build/plugins/consts.local.js.map +1 -1
- package/build/plugins/customer-lock/types.d.ts +2 -2
- package/build/plugins/customer-lock/types.d.ts.map +1 -1
- package/build/plugins/customer-lock.js +2 -2
- package/build/plugins/customer-lock.js.map +1 -1
- package/build/plugins/estimate/cache.js +1 -1
- package/build/plugins/estimate/cache.js.map +1 -1
- package/build/plugins/estimate/types.d.ts +10 -10
- package/build/plugins/estimate/types.d.ts.map +1 -1
- package/build/plugins/estimate.d.ts.map +1 -1
- package/build/plugins/estimate.js +48 -122
- package/build/plugins/estimate.js.map +1 -1
- package/build/plugins/events/types.d.ts +17 -10
- package/build/plugins/events/types.d.ts.map +1 -1
- package/build/plugins/events.d.ts +6 -5
- package/build/plugins/events.d.ts.map +1 -1
- package/build/plugins/events.js +162 -173
- package/build/plugins/events.js.map +1 -1
- package/build/plugins/fx/types.d.ts +10 -21
- package/build/plugins/fx/types.d.ts.map +1 -1
- package/build/plugins/fx.d.ts +1 -1
- package/build/plugins/fx.d.ts.map +1 -1
- package/build/plugins/fx.js +17 -54
- package/build/plugins/fx.js.map +1 -1
- package/build/plugins/portal/types.d.ts +8 -37
- package/build/plugins/portal/types.d.ts.map +1 -1
- package/build/plugins/portal.d.ts.map +1 -1
- package/build/plugins/portal.js +38 -208
- package/build/plugins/portal.js.map +1 -1
- package/build/plugins/refunds/types.d.ts +11 -11
- package/build/plugins/refunds/types.d.ts.map +1 -1
- package/build/plugins/refunds.d.ts.map +1 -1
- package/build/plugins/refunds.js +14 -39
- package/build/plugins/refunds.js.map +1 -1
- package/build/plugins/snapshot/types.d.ts +11 -0
- package/build/plugins/snapshot/types.d.ts.map +1 -0
- package/build/plugins/snapshot/types.js +2 -0
- package/build/plugins/snapshot/types.js.map +1 -0
- package/build/plugins/snapshot.d.ts +4 -0
- package/build/plugins/snapshot.d.ts.map +1 -0
- package/build/plugins/snapshot.js +19 -0
- package/build/plugins/snapshot.js.map +1 -0
- package/build/plugins/subscriptions/types.d.ts +17 -17
- package/build/plugins/subscriptions/types.d.ts.map +1 -1
- package/build/plugins/subscriptions.d.ts +4 -4
- package/build/plugins/subscriptions.d.ts.map +1 -1
- package/build/plugins/subscriptions.js +69 -77
- package/build/plugins/subscriptions.js.map +1 -1
- package/build/plugins/types.local.d.ts +9 -43
- package/build/plugins/types.local.d.ts.map +1 -1
- package/build/plugins/webhook-manager/types.d.ts +15 -43
- package/build/plugins/webhook-manager/types.d.ts.map +1 -1
- package/build/plugins/webhook-manager.d.ts +3 -3
- package/build/plugins/webhook-manager.d.ts.map +1 -1
- package/build/plugins/webhook-manager.js +21 -199
- package/build/plugins/webhook-manager.js.map +1 -1
- package/build/protocol.d.ts +1 -1
- package/build/protocol.d.ts.map +1 -1
- package/build/protocol.js +1 -1
- package/build/protocol.js.map +1 -1
- package/build/service.d.ts +11 -11
- package/build/service.d.ts.map +1 -1
- package/build/service.js +59 -23
- package/build/service.js.map +1 -1
- package/build/sync/types.d.ts +17 -13
- package/build/sync/types.d.ts.map +1 -1
- package/build/sync.d.ts.map +1 -1
- package/build/sync.js +22 -122
- package/build/sync.js.map +1 -1
- package/build/types.d.ts +46 -101
- package/build/types.d.ts.map +1 -1
- package/build/utils/types.d.ts +0 -8
- package/build/utils/types.d.ts.map +1 -1
- package/build/utils.d.ts +1 -4
- package/build/utils.d.ts.map +1 -1
- package/build/utils.js +1 -15
- package/build/utils.js.map +1 -1
- package/package.json +20 -22
- package/src/access/types.ts +7 -16
- package/src/access.ts +7 -15
- package/src/actions/resync.ts +5 -5
- package/src/actions/webhook.ts +8 -4
- package/src/bootstrap/types.ts +13 -7
- package/src/bootstrap.ts +23 -13
- package/src/catalogue/types.ts +3 -3
- package/src/catalogue.ts +4 -8
- package/src/checkout/types.ts +21 -0
- package/src/checkout.ts +414 -0
- package/src/config.ts +19 -66
- package/src/consts.ts +3 -69
- package/src/consumer/cancellation/types.ts +6 -4
- package/src/consumer/cancellation.ts +13 -7
- package/src/consumer/capture/types.ts +8 -12
- package/src/consumer/capture.ts +50 -59
- package/src/consumer/index.ts +4 -0
- package/src/consumer/reconcile.ts +69 -68
- package/src/consumer/records/types.ts +4 -4
- package/src/consumer/records.ts +19 -14
- package/src/consumer/service.ts +35 -22
- package/src/consumer/types.local.ts +1 -8
- package/src/consumer/types.ts +1 -4
- package/src/consumer/withdrawal/types.ts +14 -12
- package/src/consumer/withdrawal.ts +61 -77
- package/src/index.ts +12 -6
- package/src/paygate/providers.ts +48 -0
- package/src/paygate/registry.ts +53 -0
- package/src/paygate/types.ts +640 -0
- package/src/plan/types.ts +6 -1
- package/src/plan.ts +21 -3
- package/src/plugins/checkout-policy/types.ts +5 -3
- package/src/plugins/checkout-policy.ts +6 -5
- package/src/plugins/consts.local.ts +2 -26
- package/src/plugins/customer-lock/types.ts +2 -2
- package/src/plugins/customer-lock.ts +2 -2
- package/src/plugins/estimate/cache.ts +1 -1
- package/src/plugins/estimate/types.ts +10 -10
- package/src/plugins/estimate.ts +52 -128
- package/src/plugins/events/types.ts +17 -9
- package/src/plugins/events.ts +172 -190
- package/src/plugins/fx/types.ts +10 -23
- package/src/plugins/fx.ts +28 -64
- package/src/plugins/portal/types.ts +8 -38
- package/src/plugins/portal.ts +48 -229
- package/src/plugins/refunds/types.ts +11 -11
- package/src/plugins/refunds.ts +16 -40
- package/src/plugins/snapshot/types.ts +11 -0
- package/src/plugins/snapshot.ts +22 -0
- package/src/plugins/subscriptions/types.ts +17 -17
- package/src/plugins/subscriptions.ts +81 -81
- package/src/plugins/types.local.ts +9 -33
- package/src/plugins/webhook-manager/types.ts +15 -43
- package/src/plugins/webhook-manager.ts +24 -220
- package/src/protocol.ts +1 -1
- package/src/service.ts +66 -30
- package/src/sync/types.ts +17 -13
- package/src/sync.ts +25 -143
- package/src/types.ts +47 -97
- package/src/utils/types.ts +0 -9
- package/src/utils.ts +2 -20
- package/tests/capabilities.spec.ts +219 -0
- package/tests/entitlement.spec.ts +4 -4
- package/tests/gate-handlers.spec.ts +6 -6
- package/tests/gate.spec.ts +2 -2
- package/tests/grants.spec.ts +2 -2
- package/tests/internal-plan.spec.ts +2 -2
- package/tests/limit-gate.spec.ts +2 -2
- package/tests/paygates.spec.ts +132 -0
- package/tests/protocol.spec.ts +4 -5
- package/tests/usage.spec.ts +2 -2
- package/tests/webhook.spec.ts +137 -0
- package/build/plugins/session/types.d.ts +0 -34
- package/build/plugins/session/types.d.ts.map +0 -1
- package/build/plugins/session.d.ts +0 -4
- package/build/plugins/session.d.ts.map +0 -1
- package/build/plugins/session.js +0 -71
- package/build/plugins/session.js.map +0 -1
- package/build/plugins/status.d.ts +0 -8
- package/build/plugins/status.d.ts.map +0 -1
- package/build/plugins/status.js +0 -21
- package/build/plugins/status.js.map +0 -1
- package/build/plugins/stripe/types.d.ts +0 -20
- package/build/plugins/stripe/types.d.ts.map +0 -1
- package/build/plugins/stripe.d.ts +0 -6
- package/build/plugins/stripe.d.ts.map +0 -1
- package/build/plugins/stripe.js +0 -518
- package/build/plugins/stripe.js.map +0 -1
- package/src/plugins/session/types.ts +0 -30
- package/src/plugins/session.ts +0 -86
- package/src/plugins/status.ts +0 -22
- package/src/plugins/stripe/types.ts +0 -20
- package/src/plugins/stripe.ts +0 -571
- package/tests/checkout-consumer.spec.ts +0 -366
- package/tests/checkout-locks.spec.ts +0 -161
- package/tests/checkout-plugins.spec.ts +0 -164
- package/tests/checkout.spec.ts +0 -313
- package/tests/consumer-events.spec.ts +0 -215
- package/tests/consumer-fixtures.ts +0 -141
- package/tests/consumer-ops.spec.ts +0 -361
- package/tests/consumer-rights.integration.spec.ts +0 -147
- package/tests/consumer-rights.spec.ts +0 -606
- package/tests/context.ts +0 -110
- package/tests/estimate.spec.ts +0 -350
- package/tests/events.spec.ts +0 -367
- package/tests/fake-stripe.ts +0 -1004
- package/tests/gateway-options.spec.ts +0 -180
- package/tests/portal.spec.ts +0 -202
- package/tests/sync.spec.ts +0 -114
- package/tests/usage.integration.spec.ts +0 -165
- package/tests/webhook-manager.spec.ts +0 -149
- /package/build/{plugins/session → checkout}/types.js +0 -0
- /package/build/{plugins/stripe → paygate}/types.js +0 -0
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import { MAILER_SERVICE } from '@owlmeans/mailer'
|
|
3
2
|
import {
|
|
4
|
-
CancellationStatus, DeclarationKind, ENTITLING_STATUSES, PurchaseKind, WithdrawalStatus,
|
|
3
|
+
CancellationStatus, DeclarationKind, ENTITLING_STATUSES, INTERNAL_PAYGATE, PaygateError, PurchaseKind, WithdrawalStatus,
|
|
5
4
|
} from '@owlmeans/payment'
|
|
6
5
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
7
|
-
import { PURCHASE_BACKFILL_DAYS
|
|
6
|
+
import { PURCHASE_BACKFILL_DAYS } from '../consts.js'
|
|
8
7
|
import type { ConsumerRightsInternals, WithdrawalComputation } from './types.js'
|
|
9
8
|
import type {
|
|
10
9
|
ConsumerEventRecord, ConsumerMailKind, ConsumerReconcileOptions, ConsumerReconcileResult, UsageReading,
|
|
@@ -12,10 +11,10 @@ import type {
|
|
|
12
11
|
import { log } from '../log.js'
|
|
13
12
|
import { DAY_MS, MAX_ATTEMPTS } from './consts.local.js'
|
|
14
13
|
import { paymentAccessOf } from '../access.js'
|
|
15
|
-
import { paymentUtils } from '../utils.js'
|
|
16
14
|
import { consumerRecordsOf } from './records.js'
|
|
17
15
|
import { captureOf } from './capture.js'
|
|
18
|
-
import {
|
|
16
|
+
import { checkoutSnapshotHelper } from '../plugins/snapshot.js'
|
|
17
|
+
import { paygatesOf } from '../paygate/registry.js'
|
|
19
18
|
import { consumerMailOf } from './mail.js'
|
|
20
19
|
import { consumerObserversOf } from './observers.js'
|
|
21
20
|
import { cancellationOf } from './cancellation.js'
|
|
@@ -74,9 +73,7 @@ export const makeConsumerReconcileHelper = (
|
|
|
74
73
|
return pending
|
|
75
74
|
}
|
|
76
75
|
|
|
77
|
-
const retryWithdrawals = async (
|
|
78
|
-
stripe: Stripe, since: Date, limit: number, result: ConsumerReconcileResult,
|
|
79
|
-
): Promise<void> => {
|
|
76
|
+
const retryWithdrawals = async (since: Date, limit: number, result: ConsumerReconcileResult): Promise<void> => {
|
|
80
77
|
const { items } = await access.consumerDeclarations().list({
|
|
81
78
|
kind: DeclarationKind.Withdrawal, status: WithdrawalStatus.Processing, matched: true, receivedAt: { $gte: since },
|
|
82
79
|
}, { size: limit * 2, sort: [{ field: 'receivedAt', order: 'asc' }] })
|
|
@@ -87,6 +84,8 @@ export const makeConsumerReconcileHelper = (
|
|
|
87
84
|
const purchase = declaration.purchaseId != null ? await access.purchases().byPurchaseId(declaration.purchaseId) : null
|
|
88
85
|
// A declaration that lost the race for its purchase is a duplicate — never executed.
|
|
89
86
|
if (purchase == null || purchase.withdrawalId !== id) continue
|
|
87
|
+
const paygate = paygatesOf(ctx).find(purchase.paygate)
|
|
88
|
+
if (paygate == null) continue
|
|
90
89
|
const computed = await computedOf(id)
|
|
91
90
|
const refundDone = (declaration.refundMinor ?? 0) <= 0 || await records.hasEvent(id, 'refund', undefined, true)
|
|
92
91
|
const cancelDone = purchase.kind !== PurchaseKind.Subscription
|
|
@@ -100,7 +99,7 @@ export const makeConsumerReconcileHelper = (
|
|
|
100
99
|
if (attempt < MAX_ATTEMPTS) {
|
|
101
100
|
handled++
|
|
102
101
|
result.retried++
|
|
103
|
-
if (!await withdrawalOf(ctx).retryCreditNote(
|
|
102
|
+
if (!await withdrawalOf(ctx).retryCreditNote(paygate, declaration, purchase, computed.netMinor, refundEvent.externalId, attempt)) {
|
|
104
103
|
result.failed++
|
|
105
104
|
}
|
|
106
105
|
}
|
|
@@ -112,7 +111,7 @@ export const makeConsumerReconcileHelper = (
|
|
|
112
111
|
handled++
|
|
113
112
|
result.retried++
|
|
114
113
|
try {
|
|
115
|
-
const execution = await withdrawalOf(ctx).executeWithdrawal(
|
|
114
|
+
const execution = await withdrawalOf(ctx).executeWithdrawal(paygate, declaration, purchase, {
|
|
116
115
|
refundMinor: declaration.refundMinor ?? computed?.refundMinor ?? 0, netMinor: computed?.netMinor ?? 0,
|
|
117
116
|
}, { attempt })
|
|
118
117
|
if (!execution.ok) {
|
|
@@ -129,9 +128,7 @@ export const makeConsumerReconcileHelper = (
|
|
|
129
128
|
}
|
|
130
129
|
}
|
|
131
130
|
|
|
132
|
-
const retryCancellations = async (
|
|
133
|
-
stripe: Stripe, since: Date, limit: number, result: ConsumerReconcileResult,
|
|
134
|
-
): Promise<void> => {
|
|
131
|
+
const retryCancellations = async (since: Date, limit: number, result: ConsumerReconcileResult): Promise<void> => {
|
|
135
132
|
const { items } = await access.consumerDeclarations().list({
|
|
136
133
|
kind: DeclarationKind.Cancellation, status: CancellationStatus.Scheduled, matched: true, receivedAt: { $gte: since },
|
|
137
134
|
}, { size: limit * 2, sort: [{ field: 'receivedAt', order: 'asc' }] })
|
|
@@ -142,11 +139,12 @@ export const makeConsumerReconcileHelper = (
|
|
|
142
139
|
if (declaration.subscriptionId == null
|
|
143
140
|
|| await records.hasEvent(id, 'cancel-scheduled', undefined, true)) continue
|
|
144
141
|
const attempt = await failures(id, 'cancel-scheduled')
|
|
145
|
-
const row = await access.subscriptions().
|
|
146
|
-
|
|
142
|
+
const row = await access.subscriptions().load({ externalId: declaration.subscriptionId, paygate: { $ne: INTERNAL_PAYGATE } })
|
|
143
|
+
const paygate = row != null ? paygatesOf(ctx).find(row.paygate) : null
|
|
144
|
+
if (row == null || paygate == null || attempt >= MAX_ATTEMPTS) continue
|
|
147
145
|
handled++
|
|
148
146
|
result.retried++
|
|
149
|
-
if (!await cancellationOf(ctx).scheduleCancellation(
|
|
147
|
+
if (!await cancellationOf(ctx).scheduleCancellation(paygate, declaration, row, attempt)) {
|
|
150
148
|
result.failed++
|
|
151
149
|
}
|
|
152
150
|
}
|
|
@@ -215,50 +213,52 @@ export const makeConsumerReconcileHelper = (
|
|
|
215
213
|
}
|
|
216
214
|
|
|
217
215
|
/** Completed checkouts of the last days that have no purchase row (records only — no mail). */
|
|
218
|
-
const backfillPurchases = async (
|
|
219
|
-
const from = Math.floor((Date.now() - PURCHASE_BACKFILL_DAYS * DAY_MS) / 1000)
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
216
|
+
const backfillPurchases = async (limit: number, result: ConsumerReconcileResult): Promise<void> => {
|
|
217
|
+
const from = new Date(Math.floor((Date.now() - PURCHASE_BACKFILL_DAYS * DAY_MS) / 1000) * 1000)
|
|
218
|
+
for (const paygate of paygatesOf(ctx).all()) {
|
|
219
|
+
const listCompleted = paygate.checkout.listCompleted
|
|
220
|
+
if (listCompleted == null) continue
|
|
221
|
+
let cursor: string | undefined
|
|
222
|
+
let scanned = 0
|
|
223
|
+
for (;;) {
|
|
224
|
+
const page = await listCompleted(from, cursor)
|
|
225
|
+
for (const session of page.items) {
|
|
226
|
+
scanned++
|
|
227
|
+
if (result.backfilled >= limit) return
|
|
228
|
+
const metadata = session.metadata ?? {}
|
|
229
|
+
if (metadata.entityId == null || metadata.productSku == null) continue
|
|
230
|
+
try {
|
|
231
|
+
if (checkoutSnapshotHelper.canFulfill(session)) {
|
|
232
|
+
if (await access.purchases().load({ sessionId: session.id }) != null) continue
|
|
233
|
+
const amount = Number(metadata.amountMinor)
|
|
234
|
+
const captured = await captureOf(ctx).capturePaymentPurchase(paygate, session, {
|
|
235
|
+
...(Number.isSafeInteger(amount) && amount > 0 ? { netAmountMinor: amount } : {}),
|
|
236
|
+
...(metadata.amountCurrency != null ? { amountCurrency: metadata.amountCurrency } : {}),
|
|
237
|
+
...(session.createdAt != null ? { at: session.createdAt } : {}),
|
|
238
|
+
}, { mail: false })
|
|
239
|
+
if (captured?.created === true) result.backfilled++
|
|
240
|
+
} else if (session.mode === 'subscription') {
|
|
241
|
+
const subscriptionId = session.subscriptionId
|
|
242
|
+
if (subscriptionId == null
|
|
243
|
+
|| await access.purchases().byPurchaseId(records.purchaseIdOf(paygate.id, subscriptionId)) != null) continue
|
|
244
|
+
const row = await access.subscriptions().byExternalId(subscriptionId, paygate.id)
|
|
245
|
+
if (row == null || !ENTITLING_STATUSES.includes(row.status)) continue
|
|
246
|
+
const subscription = paygate.subscriptions != null ? await paygate.subscriptions.retrieve(subscriptionId) : null
|
|
247
|
+
if (subscription == null) throw new PaygateError(`subscription:${subscriptionId}`)
|
|
248
|
+
const captured = await captureOf(ctx).captureSubscriptionPurchase(paygate, subscription, row)
|
|
249
|
+
if (captured != null) {
|
|
250
|
+
await captureOf(ctx).completeSubscriptionPurchase(paygate, session, captured.purchase, { mail: false })
|
|
251
|
+
if (captured.created) result.backfilled++
|
|
252
|
+
}
|
|
253
253
|
}
|
|
254
|
+
} catch (error) {
|
|
255
|
+
result.failed++
|
|
256
|
+
log.error('Reconcile: purchase backfill failed', { sessionId: session.id, paygate: paygate.id, error })
|
|
254
257
|
}
|
|
255
|
-
} catch (error) {
|
|
256
|
-
result.failed++
|
|
257
|
-
log.error('Reconcile: purchase backfill failed', { sessionId: session.id, error })
|
|
258
258
|
}
|
|
259
|
+
if (page.cursor == null || page.items.length === 0 || scanned >= limit * 20) break
|
|
260
|
+
cursor = page.cursor
|
|
259
261
|
}
|
|
260
|
-
if (!page.has_more || page.data.length === 0 || scanned >= limit * 20) return
|
|
261
|
-
startingAfter = page.data[page.data.length - 1].id
|
|
262
262
|
}
|
|
263
263
|
}
|
|
264
264
|
|
|
@@ -266,25 +266,26 @@ export const makeConsumerReconcileHelper = (
|
|
|
266
266
|
* Organizations that paid before countries were locked: locked from their paygate customer's
|
|
267
267
|
* address — never one an operator unlocked (its next completed purchase locks it).
|
|
268
268
|
*/
|
|
269
|
-
const lockLegacy = async (
|
|
269
|
+
const lockLegacy = async (limit: number, result: ConsumerReconcileResult): Promise<void> => {
|
|
270
270
|
const policy = await access.payment().consumerRightsPolicy()
|
|
271
271
|
if (policy?.mechanisms.countryLock !== true) {
|
|
272
272
|
return
|
|
273
273
|
}
|
|
274
|
-
const { items } = await access.paygateCustomers().list({ paygate:
|
|
274
|
+
const { items } = await access.paygateCustomers().list({ paygate: { $ne: INTERNAL_PAYGATE }, deletedAt: null }, { size: limit * 4 })
|
|
275
275
|
for (const customer of items) {
|
|
276
276
|
if (result.locked >= limit) return
|
|
277
277
|
if (customer.entityId == null || await access.billingProfiles().byEntity(customer.entityId) != null) continue
|
|
278
278
|
if (!await records.hasPaid(customer.entityId) || await records.wasUnlocked(customer.entityId)) continue
|
|
279
|
+
const paygate = paygatesOf(ctx).find(customer.paygate)
|
|
280
|
+
if (paygate == null) continue
|
|
279
281
|
try {
|
|
280
282
|
let country = customer.country
|
|
281
283
|
if (country == null) {
|
|
282
|
-
|
|
283
|
-
country = (retrieved as Stripe.DeletedCustomer).deleted ? undefined : (retrieved as Stripe.Customer).address?.country ?? undefined
|
|
284
|
+
country = (await paygate.customers.retrieve(customer.externalId))?.country ?? undefined
|
|
284
285
|
}
|
|
285
286
|
if (country == null) continue
|
|
286
287
|
const { created } = await records.lockProfile(policy, {
|
|
287
|
-
entityId: customer.entityId, country, source: 'customer', customerId: customer.externalId,
|
|
288
|
+
entityId: customer.entityId, country, source: 'customer', paygate: paygate.id, customerId: customer.externalId,
|
|
288
289
|
email: customer.email ?? undefined,
|
|
289
290
|
})
|
|
290
291
|
if (created) result.locked++
|
|
@@ -302,17 +303,17 @@ export const makeConsumerReconcileHelper = (
|
|
|
302
303
|
}
|
|
303
304
|
const limit = Math.max(1, opts.limit ?? 50)
|
|
304
305
|
const since = opts.since ?? new Date(Date.now() - 30 * DAY_MS)
|
|
305
|
-
const
|
|
306
|
+
const managed = internals.managed
|
|
306
307
|
const steps: Array<[string, () => Promise<void>]> = [
|
|
307
|
-
...(
|
|
308
|
-
['withdrawals', async () => { await retryWithdrawals(
|
|
309
|
-
['cancellations', async () => { await retryCancellations(
|
|
308
|
+
...(managed ? [
|
|
309
|
+
['withdrawals', async () => { await retryWithdrawals(since, limit, result) }],
|
|
310
|
+
['cancellations', async () => { await retryCancellations(since, limit, result) }],
|
|
310
311
|
] as Array<[string, () => Promise<void>]> : []),
|
|
311
312
|
['mails', async () => { await retryMails(since, limit, result) }],
|
|
312
313
|
['observers', async () => { await retryObservers(since, limit, result) }],
|
|
313
|
-
...(
|
|
314
|
-
['backfill', async () => { await backfillPurchases(
|
|
315
|
-
['legacy locks', async () => { await lockLegacy(
|
|
314
|
+
...(managed ? [
|
|
315
|
+
['backfill', async () => { await backfillPurchases(limit, result) }],
|
|
316
|
+
['legacy locks', async () => { await lockLegacy(limit, result) }],
|
|
316
317
|
] as Array<[string, () => Promise<void>]> : []),
|
|
317
318
|
]
|
|
318
319
|
for (const [name, step] of steps) {
|
|
@@ -9,8 +9,8 @@ export interface ConsumerEventDraft extends Omit<ConsumerEventRecord, 'at' | 'id
|
|
|
9
9
|
|
|
10
10
|
/** The consumer-rights records of a context: purchases, billing profiles and the audit trail. */
|
|
11
11
|
export interface ConsumerRecords {
|
|
12
|
-
/** The purchase id of a paygate checkout session or subscription:
|
|
13
|
-
purchaseIdOf: (externalId: string) => string
|
|
12
|
+
/** The purchase id of a paygate checkout session or subscription: `<paygate>:<id>`. */
|
|
13
|
+
purchaseIdOf: (paygate: string, externalId: string) => string
|
|
14
14
|
/** A locked profile as the wire sees it. */
|
|
15
15
|
profileViewOf: (record: BillingProfileRecord, policy: ConsumerRightsPolicy | null) => BillingProfileView
|
|
16
16
|
/** No profile yet: nothing locked, the default legal language, an unknown buyer (protected by default). */
|
|
@@ -22,8 +22,8 @@ export interface ConsumerRecords {
|
|
|
22
22
|
recordEvent: (event: ConsumerEventDraft) => Promise<void>
|
|
23
23
|
/** Whether a step already succeeded (or a mail was deliberately skipped) for a record. */
|
|
24
24
|
hasEvent: (recordId: string, action: ConsumerEventRecord['action'], step?: string, ok?: boolean) => Promise<boolean>
|
|
25
|
-
/** The entity's highest-ranked entitling
|
|
26
|
-
|
|
25
|
+
/** The entity's highest-ranked entitling paygate subscription (any paygate but the internal one), or `null`. */
|
|
26
|
+
entitlingPaygateSubscription: (entityId: string) => Promise<PaymentSubscriptionRecord | null>
|
|
27
27
|
/** Whether the entity ever paid through the paygate (a fulfilled checkout or a propagated subscription). */
|
|
28
28
|
hasPaid: (entityId: string) => Promise<boolean>
|
|
29
29
|
/**
|
package/src/consumer/records.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { ConsumerRegion, ConsumerRightsError, ENTITLING_STATUSES, PurchaseKind, type BillingProfileView, type ConsumerRightsPolicy, consumerRegionHelper } from '@owlmeans/payment'
|
|
1
|
+
import { ConsumerRegion, ConsumerRightsError, ENTITLING_STATUSES, INTERNAL_PAYGATE, PurchaseKind, type BillingProfileView, type ConsumerRightsPolicy, consumerRegionHelper } from '@owlmeans/payment'
|
|
2
2
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
3
3
|
import { memoHelper } from '@owlmeans/context'
|
|
4
|
-
import { PURCHASE_ID_PREFIX, STRIPE_PAYGATE_ALIAS } from '../consts.js'
|
|
5
4
|
import type {
|
|
6
5
|
BillingProfileRecord, ConsumerEventRecord, PaymentSubscriptionRecord, PurchaseRecord, UnlockOptions,
|
|
7
6
|
} from '../types.js'
|
|
@@ -11,12 +10,13 @@ import type { LockInput, LockResult, PurchaseDraft } from './types.js'
|
|
|
11
10
|
import { paymentAccessOf } from '../access.js'
|
|
12
11
|
import { paymentUtils } from '../utils.js'
|
|
13
12
|
import { consumerFormatHelper } from './format.js'
|
|
13
|
+
import { paygatesOf } from '../paygate/registry.js'
|
|
14
14
|
import type { ConsumerEventDraft, ConsumerRecords } from './records/types.js'
|
|
15
15
|
|
|
16
16
|
export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
17
17
|
const access = paymentAccessOf(ctx)
|
|
18
18
|
|
|
19
|
-
const purchaseIdOf = (externalId: string): string => `${
|
|
19
|
+
const purchaseIdOf = (paygate: string, externalId: string): string => `${paygate}:${externalId}`
|
|
20
20
|
|
|
21
21
|
const profileViewOf = (record: BillingProfileRecord, policy: ConsumerRightsPolicy | null): BillingProfileView => ({
|
|
22
22
|
country: record.country,
|
|
@@ -52,24 +52,28 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
|
52
52
|
recordId, action, ...(step != null ? { step } : {}), ...(ok != null ? { ok } : {}),
|
|
53
53
|
})) != null
|
|
54
54
|
|
|
55
|
-
/** The currency of the entity's entitling
|
|
55
|
+
/** The currency of the entity's entitling paygate subscription — two of one customer cannot differ. */
|
|
56
56
|
const activeSubscriptionCurrency = async (entityId: string): Promise<string | undefined> => {
|
|
57
|
-
const row = await
|
|
57
|
+
const row = await entitlingPaygateSubscription(entityId)
|
|
58
58
|
|
|
59
59
|
return row?.currency ?? undefined
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
const
|
|
62
|
+
const entitlingPaygateSubscription = async (
|
|
63
63
|
entityId: string,
|
|
64
64
|
): Promise<PaymentSubscriptionRecord | null> => await access.subscriptions().load(
|
|
65
|
-
{ entityId, paygate:
|
|
65
|
+
{ entityId, paygate: { $ne: INTERNAL_PAYGATE }, status: [...ENTITLING_STATUSES] },
|
|
66
66
|
{ sort: [{ field: 'rank', order: 'desc' }, { field: 'createdAt', order: 'desc' }] },
|
|
67
67
|
)
|
|
68
68
|
|
|
69
69
|
const hasPaid = async (entityId: string): Promise<boolean> =>
|
|
70
|
-
await access.fulfillments().load({ entityId, paygate:
|
|
70
|
+
await access.fulfillments().load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, fulfilledAt: { $exists: true } }) != null
|
|
71
71
|
|| await access.subscriptions()
|
|
72
|
-
.load({ entityId, paygate:
|
|
72
|
+
.load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, initialPropagatedAt: { $exists: true } }) != null
|
|
73
|
+
|
|
74
|
+
/** The paygate a lock is recorded for: the one named, else the first registered one. */
|
|
75
|
+
const lockPaygateOf = (paygate: string | undefined): string =>
|
|
76
|
+
paygate ?? paygatesOf(ctx).all()[0]?.id ?? INTERNAL_PAYGATE
|
|
73
77
|
|
|
74
78
|
const lockProfile = async (policy: ConsumerRightsPolicy | null, input: LockInput): Promise<LockResult> => {
|
|
75
79
|
const country = input.country.trim().toUpperCase()
|
|
@@ -84,7 +88,8 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
|
84
88
|
}
|
|
85
89
|
|
|
86
90
|
const region = consumerRegionHelper.regionOf(country, policy) ?? ConsumerRegion.Other
|
|
87
|
-
const
|
|
91
|
+
const paygate = lockPaygateOf(input.paygate)
|
|
92
|
+
const settlement = (await paygatesOf(ctx).find(paygate)?.settlementCurrency())?.toLowerCase()
|
|
88
93
|
const currency = (await activeSubscriptionCurrency(input.entityId))
|
|
89
94
|
?? (policy?.currencies != null && Object.keys(policy.currencies).length > 0
|
|
90
95
|
? consumerRegionHelper.chargeCurrencyOf(region, policy, input.currency ?? settlement ?? 'usd')
|
|
@@ -96,7 +101,7 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
|
96
101
|
currency: currency.toLowerCase(),
|
|
97
102
|
language: input.language ?? consumerRegionHelper.billingLanguageOf(country, policy),
|
|
98
103
|
source: input.source,
|
|
99
|
-
paygate
|
|
104
|
+
paygate,
|
|
100
105
|
customerId: input.customerId,
|
|
101
106
|
sessionId: input.sessionId,
|
|
102
107
|
ipCountry: input.ipCountry?.toUpperCase(),
|
|
@@ -255,7 +260,7 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
|
255
260
|
if (latest?.email != null && latest.email !== '') {
|
|
256
261
|
return latest.email
|
|
257
262
|
}
|
|
258
|
-
const customer = await access.paygateCustomers().
|
|
263
|
+
const customer = await access.paygateCustomers().load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, email: { $exists: true } })
|
|
259
264
|
|
|
260
265
|
return customer?.email ?? undefined
|
|
261
266
|
}
|
|
@@ -272,13 +277,13 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
|
|
|
272
277
|
if (consumerFormatHelper.normalizeEmail(profile?.email) === wanted) {
|
|
273
278
|
return true
|
|
274
279
|
}
|
|
275
|
-
const customer = await access.paygateCustomers().byEntity(purchase.entityId,
|
|
280
|
+
const customer = await access.paygateCustomers().byEntity(purchase.entityId, purchase.paygate)
|
|
276
281
|
|
|
277
282
|
return consumerFormatHelper.normalizeEmail(customer?.email) === wanted
|
|
278
283
|
}
|
|
279
284
|
|
|
280
285
|
return {
|
|
281
|
-
purchaseIdOf, profileViewOf, unlockedProfileView, recordEvent, hasEvent,
|
|
286
|
+
purchaseIdOf, profileViewOf, unlockedProfileView, recordEvent, hasEvent, entitlingPaygateSubscription, hasPaid,
|
|
282
287
|
lockProfile, unlockProfile, wasUnlocked, unconsentedWindows, createPurchase, patchPurchase, contactEmailOf,
|
|
283
288
|
emailMatches,
|
|
284
289
|
}
|
package/src/consumer/service.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import { createLazyService } from '@owlmeans/context'
|
|
3
2
|
import { MAILER_SERVICE } from '@owlmeans/mailer'
|
|
4
|
-
import { cancellationEffectiveAt, CancellationKind, CancellationStatus, CancellationUnavailable, CancellationUnavailableReason, ConsentKind, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, DeclarationChannel, DeclarationKind, ENTITLING_STATUSES, PaygateError, PerformanceConsentRequired, PurchaseKind, SubscriptionStartRequired, TERMINAL_STATUSES, UnknownPlan, WithdrawalStatus, WithdrawalUnavailable, WithdrawalUnavailableReason, type CancellationReceipt, type ConsumerRightsPolicy, type DeclarationReceipt, type PerformanceConsentView, type PurchaseView, type SubscriptionStartView, type WithdrawalCandidate, type WithdrawalReceipt, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment'
|
|
3
|
+
import { cancellationEffectiveAt, CancellationKind, CancellationStatus, CancellationUnavailable, CancellationUnavailableReason, ConsentKind, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, DeclarationChannel, DeclarationKind, ENTITLING_STATUSES, INTERNAL_PAYGATE, PaygateError, PerformanceConsentRequired, PurchaseKind, SubscriptionStartRequired, TERMINAL_STATUSES, UnknownPlan, WithdrawalStatus, WithdrawalUnavailable, WithdrawalUnavailableReason, type CancellationReceipt, type ConsumerRightsPolicy, type DeclarationReceipt, type PerformanceConsentView, type PurchaseView, type SubscriptionStartView, type WithdrawalCandidate, type WithdrawalReceipt, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment'
|
|
5
4
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
6
|
-
import { CONSUMER_RIGHTS_SERVICE
|
|
5
|
+
import { CONSUMER_RIGHTS_SERVICE } from '../consts.js'
|
|
7
6
|
import { CONSUMER_RIGHTS_RESOURCE_MAKERS } from '../resource.js'
|
|
8
7
|
import { makeConsumerReconcileHelper } from './reconcile.js'
|
|
9
8
|
import type {
|
|
@@ -26,6 +25,8 @@ import { consumerMailOf } from './mail.js'
|
|
|
26
25
|
import { consumerObserversOf } from './observers.js'
|
|
27
26
|
import { cancellationOf } from './cancellation.js'
|
|
28
27
|
import { withdrawalOf } from './withdrawal.js'
|
|
28
|
+
import { paygatesOf } from '../paygate/registry.js'
|
|
29
|
+
import type { Paygate } from '../paygate/types.js'
|
|
29
30
|
|
|
30
31
|
const latestDeadline = (items: Array<{ deadline?: Date | null }>): Date | undefined => {
|
|
31
32
|
const times = items.map(item => item.deadline != null ? new Date(item.deadline).getTime() : Number.NaN)
|
|
@@ -34,6 +35,14 @@ const latestDeadline = (items: Array<{ deadline?: Date | null }>): Date | undefi
|
|
|
34
35
|
return times.length > 0 ? new Date(Math.max(...times)) : undefined
|
|
35
36
|
}
|
|
36
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Whether a withdrawal of the purchase can be executed at its paygate: a registered paygate with
|
|
40
|
+
* `payments`, and with `subscriptions` for a subscription purchase — otherwise it is left to an
|
|
41
|
+
* operator (`review`).
|
|
42
|
+
*/
|
|
43
|
+
const executable = (paygate: Paygate | null, purchase: PurchaseRecord): boolean =>
|
|
44
|
+
paygate?.payments != null && (purchase.kind !== PurchaseKind.Subscription || paygate.subscriptions != null)
|
|
45
|
+
|
|
37
46
|
/** Only what a person typed, echoed as the receipt's content — never enriched with a match. */
|
|
38
47
|
const contentOf = (fields: Record<string, string | undefined | null>): Record<string, string> =>
|
|
39
48
|
Object.fromEntries(Object.entries(fields).filter((entry): entry is [string, string] =>
|
|
@@ -81,14 +90,19 @@ export const makeConsumerRightsService = (
|
|
|
81
90
|
let manageGateway: boolean | undefined
|
|
82
91
|
const isManaged = (): boolean => (manageOwn ?? manageGateway) !== false
|
|
83
92
|
let meter: UsageMeter | null = opts.usage ?? null
|
|
84
|
-
let stripeFactory = opts.stripe
|
|
85
93
|
let renderer: ConsumerMailRenderer | null = null
|
|
86
|
-
const stripeOf = async (ctx: ApiContext): Promise<Stripe> =>
|
|
87
|
-
stripeFactory != null ? await stripeFactory(ctx) : await paymentAccessOf(ctx).stripeClient()
|
|
88
94
|
const internals: ConsumerRightsInternals = {
|
|
89
|
-
get managed() { return isManaged() }, meter: () => meter,
|
|
95
|
+
get managed() { return isManaged() }, meter: () => meter,
|
|
90
96
|
}
|
|
91
97
|
|
|
98
|
+
/** The registered paygate of a record, or `null`. */
|
|
99
|
+
const paygateOf = (ctx: ApiContext, id: string | undefined): Paygate | null =>
|
|
100
|
+
id != null ? paygatesOf(ctx).find(id) : null
|
|
101
|
+
|
|
102
|
+
/** A paygate subscription row by its id, whichever paygate it is of. */
|
|
103
|
+
const subscriptionRow = async (ctx: ApiContext, externalId: string): Promise<PaymentSubscriptionRecord | null> =>
|
|
104
|
+
await paymentAccessOf(ctx).subscriptions().load({ externalId, paygate: { $ne: INTERNAL_PAYGATE } })
|
|
105
|
+
|
|
92
106
|
const requirePolicy = async (ctx: ApiContext): Promise<ConsumerRightsPolicy> => {
|
|
93
107
|
const policy = await paymentAccessOf(ctx).payment().consumerRightsPolicy()
|
|
94
108
|
if (policy == null) {
|
|
@@ -126,7 +140,7 @@ export const makeConsumerRightsService = (
|
|
|
126
140
|
}
|
|
127
141
|
// Case-insensitive (`$ilike`, its `%`/`_`/`\` wildcards escaped): a paygate keeps the e-mail as typed.
|
|
128
142
|
const pattern = wanted.replace(/[\\%_]/g, match => `\\${match}`)
|
|
129
|
-
const { items } = await paymentAccessOf(ctx).paygateCustomers().list({ paygate:
|
|
143
|
+
const { items } = await paymentAccessOf(ctx).paygateCustomers().list({ paygate: { $ne: INTERNAL_PAYGATE }, email: { $ilike: pattern } }, { size: 20 })
|
|
130
144
|
const entities = [...new Set(items.filter(item => item.deletedAt == null && item.entityId != null).map(item => item.entityId as string))]
|
|
131
145
|
|
|
132
146
|
return entities.length === 1 ? entities[0] : null
|
|
@@ -522,7 +536,7 @@ export const makeConsumerRightsService = (
|
|
|
522
536
|
status = WithdrawalStatus.Received
|
|
523
537
|
} else if (purchase.deadline == null || at.getTime() >= new Date(purchase.deadline).getTime()) {
|
|
524
538
|
status = WithdrawalStatus.Expired
|
|
525
|
-
} else if (meter != null && policy.mechanisms.automaticRefunds) {
|
|
539
|
+
} else if (meter != null && policy.mechanisms.automaticRefunds && executable(paygateOf(ctx, purchase.paygate), purchase)) {
|
|
526
540
|
try {
|
|
527
541
|
computation = await withdrawalOf(ctx).computeWithdrawal(meter, purchase, at)
|
|
528
542
|
} catch (error) {
|
|
@@ -583,7 +597,7 @@ export const makeConsumerRightsService = (
|
|
|
583
597
|
let final: WithdrawalStatus = status
|
|
584
598
|
let execution: WithdrawalExecution | null = null
|
|
585
599
|
if (status === WithdrawalStatus.Processing && purchase != null && computation != null) {
|
|
586
|
-
execution = await withdrawalOf(ctx).executeWithdrawal(
|
|
600
|
+
execution = await withdrawalOf(ctx).executeWithdrawal(paygateOf(ctx, purchase.paygate) as Paygate, declaration, purchase, computation)
|
|
587
601
|
final = execution.needsReview ? WithdrawalStatus.Review : execution.ok ? WithdrawalStatus.Refunded : WithdrawalStatus.Failed
|
|
588
602
|
}
|
|
589
603
|
if (purchase != null && (final === WithdrawalStatus.Refunded || final === WithdrawalStatus.Review)
|
|
@@ -620,22 +634,22 @@ export const makeConsumerRightsService = (
|
|
|
620
634
|
let row: PaymentSubscriptionRecord | null = null
|
|
621
635
|
if (subject != null) {
|
|
622
636
|
if (body.subscriptionId != null) {
|
|
623
|
-
row = await
|
|
637
|
+
row = await subscriptionRow(ctx, body.subscriptionId)
|
|
624
638
|
} else if (body.contractRef != null) {
|
|
625
639
|
purchase = await purchaseByContract(ctx, body.contractRef)
|
|
626
640
|
if (purchase != null && purchase.entityId === subject.entityId && purchase.subscriptionId != null) {
|
|
627
|
-
row = await access.subscriptions().byExternalId(purchase.subscriptionId,
|
|
641
|
+
row = await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate)
|
|
628
642
|
}
|
|
629
643
|
}
|
|
630
644
|
row = row != null && row.entityId === subject.entityId
|
|
631
|
-
? row : await consumerRecordsOf(ctx).
|
|
645
|
+
? row : await consumerRecordsOf(ctx).entitlingPaygateSubscription(subject.entityId)
|
|
632
646
|
} else {
|
|
633
647
|
purchase = await matchPublicPurchase(ctx, body.contractRef, body.email)
|
|
634
648
|
if (purchase?.subscriptionId != null) {
|
|
635
|
-
row = await access.subscriptions().byExternalId(purchase.subscriptionId,
|
|
649
|
+
row = await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate)
|
|
636
650
|
} else if (purchase == null) {
|
|
637
651
|
const entityId = await entityByEmail(ctx, body.email)
|
|
638
|
-
row = entityId != null ? await consumerRecordsOf(ctx).
|
|
652
|
+
row = entityId != null ? await consumerRecordsOf(ctx).entitlingPaygateSubscription(entityId) : null
|
|
639
653
|
}
|
|
640
654
|
}
|
|
641
655
|
const live = row != null && !TERMINAL_STATUSES.includes(row.status) && ENTITLING_STATUSES.includes(row.status)
|
|
@@ -652,7 +666,7 @@ export const makeConsumerRightsService = (
|
|
|
652
666
|
if (body.kind === CancellationKind.Extraordinary) {
|
|
653
667
|
// For cause: recorded and left to an operator — the paygate is not touched.
|
|
654
668
|
status = CancellationStatus.Review
|
|
655
|
-
} else if (row != null && live && row.periodEnd != null) {
|
|
669
|
+
} else if (row != null && live && row.periodEnd != null && paygateOf(ctx, row.paygate)?.subscriptions != null) {
|
|
656
670
|
effectiveAt = cancellationEffectiveAt(new Date(row.periodEnd), plan?.recurring?.interval ?? 'month',
|
|
657
671
|
requested != null && !Number.isNaN(requested.getTime()) ? requested : null)
|
|
658
672
|
status = row.cancelAtPeriodEnd === true && effectiveAt.getTime() === new Date(row.periodEnd).getTime()
|
|
@@ -676,7 +690,7 @@ export const makeConsumerRightsService = (
|
|
|
676
690
|
}) as ConsumerDeclarationRecord)
|
|
677
691
|
let final = status
|
|
678
692
|
if (status === CancellationStatus.Scheduled && row != null) {
|
|
679
|
-
final = await cancellationOf(ctx).scheduleCancellation(
|
|
693
|
+
final = await cancellationOf(ctx).scheduleCancellation(paygateOf(ctx, row.paygate) as Paygate, declaration, row)
|
|
680
694
|
? CancellationStatus.Scheduled : CancellationStatus.Received
|
|
681
695
|
}
|
|
682
696
|
if (purchase != null && effectiveAt != null) {
|
|
@@ -719,7 +733,6 @@ export const makeConsumerRightsService = (
|
|
|
719
733
|
else manageGateway = plumbing.manage
|
|
720
734
|
}
|
|
721
735
|
if (plumbing.usage != null) meter = plumbing.usage
|
|
722
|
-
if (plumbing.stripe != null) stripeFactory = plumbing.stripe
|
|
723
736
|
})
|
|
724
737
|
|
|
725
738
|
return service
|
|
@@ -728,7 +741,7 @@ export const makeConsumerRightsService = (
|
|
|
728
741
|
/**
|
|
729
742
|
* Register the consumer-rights resources and service (each only when absent), or configure the
|
|
730
743
|
* service already registered — `from` says who asks. The order of the application's call and the
|
|
731
|
-
* gateway's is free: `usage`
|
|
744
|
+
* gateway's is free: `usage` is installed whenever it comes, and the application's
|
|
732
745
|
* explicit `manage` wins over the gateway's. The resources keep the first registration's aliases.
|
|
733
746
|
*/
|
|
734
747
|
export const registerConsumerRights = <C extends Config, T extends Context<C>>(
|
|
@@ -743,12 +756,12 @@ export const registerConsumerRights = <C extends Config, T extends Context<C>>(
|
|
|
743
756
|
// A lazy service: reachable before the context initializes.
|
|
744
757
|
let service = ctx.hasService(alias) ? ctx.service<ConsumerRightsService>(alias) : null
|
|
745
758
|
if (service == null) {
|
|
746
|
-
service = makeConsumerRightsService(alias, { ...opts, manage: undefined, usage: undefined
|
|
759
|
+
service = makeConsumerRightsService(alias, { ...opts, manage: undefined, usage: undefined })
|
|
747
760
|
ctx.registerService(service)
|
|
748
761
|
}
|
|
749
762
|
const plumb = plumbers.get(service)
|
|
750
763
|
if (plumb != null) {
|
|
751
|
-
plumb(paymentUtils.compact({ manage: opts.manage, usage: opts.usage
|
|
764
|
+
plumb(paymentUtils.compact({ manage: opts.manage, usage: opts.usage }), from)
|
|
752
765
|
} else if (opts.usage != null) {
|
|
753
766
|
// A service made elsewhere: only its public seam.
|
|
754
767
|
service.useMeter(opts.usage)
|
|
@@ -759,7 +772,7 @@ export const registerConsumerRights = <C extends Config, T extends Context<C>>(
|
|
|
759
772
|
|
|
760
773
|
/**
|
|
761
774
|
* Register the consumer-rights resources and service, each only when absent — the gateway
|
|
762
|
-
* registration does too. Called before or after the gateway, it installs `usage`
|
|
775
|
+
* registration does too. Called before or after the gateway, it installs `usage` on
|
|
763
776
|
* the service and its explicit `manage` wins over the gateway's; `useMeter` and `useMailRenderer`
|
|
764
777
|
* work on the service at any time.
|
|
765
778
|
*/
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import type { AbstractRequest } from '@owlmeans/entrypoint'
|
|
3
2
|
import type { ConsumerRightsOptions } from '../types.js'
|
|
4
3
|
|
|
@@ -13,10 +12,4 @@ export interface Rendered {
|
|
|
13
12
|
export type Headers = AbstractRequest['headers']
|
|
14
13
|
|
|
15
14
|
/** What a later registration applies to a service already registered. */
|
|
16
|
-
export interface Plumbing extends Pick<ConsumerRightsOptions, 'manage' | 'usage'
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* A credit note's creation parameters in the API version the client is pinned to: the refund it corrects
|
|
20
|
-
* is named by `refund` there, where the installed SDK's types (a newer version) list `refunds`.
|
|
21
|
-
*/
|
|
22
|
-
export interface PinnedCreditNoteParams extends Stripe.CreditNoteCreateParams { refund?: string }
|
|
15
|
+
export interface Plumbing extends Pick<ConsumerRightsOptions, 'manage' | 'usage'> {}
|
package/src/consumer/types.ts
CHANGED
|
@@ -3,13 +3,11 @@ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
|
|
|
3
3
|
import type {
|
|
4
4
|
ConsumerRightsAccountProtocols, ConsumerRightsPublicProtocols, WithdrawalEstimate,
|
|
5
5
|
} from '@owlmeans/payment'
|
|
6
|
-
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
7
|
-
import type Stripe from 'stripe'
|
|
8
6
|
import type {
|
|
9
7
|
PurchaseRecord, BillingProfileRecord, BillingProfileSource, LockOptions, UsageMeter, UsageReading,
|
|
10
8
|
} from '../types.js'
|
|
11
9
|
|
|
12
|
-
/** What a completed
|
|
10
|
+
/** What a completed checkout session says about its buyer and totals. */
|
|
13
11
|
export interface SessionEvidence {
|
|
14
12
|
country?: string
|
|
15
13
|
email?: string
|
|
@@ -64,7 +62,6 @@ export interface PurchaseDraft extends Omit<PurchaseRecord, 'id' | 'contractRef'
|
|
|
64
62
|
export interface ConsumerRightsInternals {
|
|
65
63
|
readonly managed: boolean
|
|
66
64
|
meter: () => UsageMeter | null
|
|
67
|
-
stripe: (ctx: ApiContext) => Promise<Stripe>
|
|
68
65
|
}
|
|
69
66
|
|
|
70
67
|
/** Who hands a registration its options: the application itself, or the gateway on its behalf. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import type { ConsumerDeclarationRecord, PurchaseRecord, UsageMeter } from '../../types.js'
|
|
3
2
|
import type { WithdrawalComputation, WithdrawalExecution } from '../types.js'
|
|
3
|
+
import type { Paygate } from '../../paygate/types.js'
|
|
4
4
|
|
|
5
5
|
/** Withdrawals of a context: what they reimburse and their paygate steps. */
|
|
6
6
|
export interface WithdrawalHelper {
|
|
@@ -13,25 +13,27 @@ export interface WithdrawalHelper {
|
|
|
13
13
|
*/
|
|
14
14
|
computeWithdrawal: (meter: UsageMeter, purchase: PurchaseRecord, at: Date) => Promise<WithdrawalComputation>
|
|
15
15
|
/**
|
|
16
|
-
* Execute a withdrawal at the paygate, the first attempt of every call under the
|
|
17
|
-
* `withdrawal:<id>:<step>` (a retry by `reconcile`
|
|
16
|
+
* Execute a withdrawal at the purchase's paygate, the first attempt of every call under the
|
|
17
|
+
* idempotency key `withdrawal:<id>:<step>` (a retry by `reconcile` uses `…:<attempt>` and adopts
|
|
18
|
+
* what an earlier attempt made):
|
|
18
19
|
*
|
|
19
|
-
* 1. a subscription purchase: `subscriptions.
|
|
20
|
-
* 2. an invoice-backed purchase
|
|
21
|
-
*
|
|
22
|
-
* tells observers not to claw back), then
|
|
23
|
-
* corrective tax document; a failed credit note keeps the plain
|
|
24
|
-
*
|
|
20
|
+
* 1. a subscription purchase: `subscriptions.cancelNow`, without proration or a final invoice;
|
|
21
|
+
* 2. an invoice-backed purchase (a paygate with `payments.creditNotes`): a credit-note preview of
|
|
22
|
+
* the invoice line at the net refund, then OUR refund for the previewed total (metadata
|
|
23
|
+
* `withdrawalId` — the refund webhook then tells observers not to claw back), then a credit note
|
|
24
|
+
* documenting that refund — the corrective tax document; a failed credit note keeps the plain
|
|
25
|
+
* refund and is recorded;
|
|
26
|
+
* 3. otherwise: a plain proportional refund on the payment.
|
|
25
27
|
*
|
|
26
28
|
* Steps that already succeeded (a recorded `ok` event) are skipped. Every step is an event.
|
|
27
29
|
*/
|
|
28
30
|
executeWithdrawal: (
|
|
29
|
-
|
|
31
|
+
paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
|
|
30
32
|
computation: { refundMinor: number, netMinor: number }, opts?: { attempt?: number },
|
|
31
33
|
) => Promise<WithdrawalExecution>
|
|
32
|
-
/** Retry a credit note that failed after its refund succeeded. */
|
|
34
|
+
/** Retry a credit note that failed after its refund succeeded (`false` without `payments.creditNotes`). */
|
|
33
35
|
retryCreditNote: (
|
|
34
|
-
|
|
36
|
+
paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
|
|
35
37
|
netMinor: number, refundId: string, attempt: number,
|
|
36
38
|
) => Promise<boolean>
|
|
37
39
|
}
|