@owlmeans/server-payment 0.1.21 → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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,5 +1,6 @@
|
|
|
1
1
|
import type { AmountPolicyView } from '@owlmeans/payment'
|
|
2
2
|
import type { CheckoutPlugin } from '../../types.js'
|
|
3
|
+
import type { PaygateFeatures } from '../../paygate/types.js'
|
|
3
4
|
|
|
4
5
|
/** What a narrowed amount policy and the plugins' declarations allow a checkout — pure. */
|
|
5
6
|
export interface CheckoutPolicyHelper {
|
|
@@ -11,8 +12,9 @@ export interface CheckoutPolicyHelper {
|
|
|
11
12
|
*/
|
|
12
13
|
assertAmountAllowed: (view: AmountPolicyView, amountMinor: number) => void
|
|
13
14
|
/**
|
|
14
|
-
* The session lifetime: the smallest `sessionTtlSeconds` any plugin declares, clamped
|
|
15
|
-
*
|
|
15
|
+
* The session lifetime: the smallest `sessionTtlSeconds` any plugin declares, clamped into the
|
|
16
|
+
* paygate's `bounds` (`features.sessionTtl`); `undefined` when none declares one, or the paygate
|
|
17
|
+
* takes no lifetime (no bounds) — the paygate's own default.
|
|
16
18
|
*/
|
|
17
|
-
sessionTtlOf: (plugins: readonly CheckoutPlugin[]) => number | undefined
|
|
19
|
+
sessionTtlOf: (plugins: readonly CheckoutPlugin[], bounds?: PaygateFeatures['sessionTtl']) => number | undefined
|
|
18
20
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CheckoutLimitExceeded, type AmountPolicyView } from '@owlmeans/payment'
|
|
2
|
-
import { STRIPE_SESSION_TTL_MAX_SECONDS, STRIPE_SESSION_TTL_MIN_SECONDS } from '../consts.js'
|
|
3
2
|
import type { CheckoutPlugin } from '../types.js'
|
|
3
|
+
import type { PaygateFeatures } from '../paygate/types.js'
|
|
4
4
|
import type { CheckoutPolicyHelper } from './checkout-policy/types.js'
|
|
5
5
|
|
|
6
6
|
export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
|
|
@@ -15,7 +15,10 @@ export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
|
|
|
15
15
|
})
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const sessionTtlOf = (plugins: readonly CheckoutPlugin[]): number | undefined => {
|
|
18
|
+
const sessionTtlOf = (plugins: readonly CheckoutPlugin[], bounds?: PaygateFeatures['sessionTtl']): number | undefined => {
|
|
19
|
+
if (bounds == null) {
|
|
20
|
+
return undefined
|
|
21
|
+
}
|
|
19
22
|
const declared = plugins
|
|
20
23
|
.map(plugin => plugin.sessionTtlSeconds)
|
|
21
24
|
.filter((ttl): ttl is number => typeof ttl === 'number' && Number.isFinite(ttl))
|
|
@@ -23,9 +26,7 @@ export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
|
|
|
23
26
|
return undefined
|
|
24
27
|
}
|
|
25
28
|
|
|
26
|
-
return Math.min(
|
|
27
|
-
STRIPE_SESSION_TTL_MAX_SECONDS, Math.max(STRIPE_SESSION_TTL_MIN_SECONDS, Math.floor(Math.min(...declared))),
|
|
28
|
-
)
|
|
29
|
+
return Math.min(bounds.maxSeconds, Math.max(bounds.minSeconds, Math.floor(Math.min(...declared))))
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
return { assertAmountAllowed, sessionTtlOf }
|
|
@@ -1,30 +1,6 @@
|
|
|
1
|
-
import { TaxType } from '@owlmeans/payment'
|
|
2
|
-
import type { DisputePhase } from '../types.js'
|
|
3
|
-
|
|
4
|
-
export const NON_SCALABLE_REASONS = new Set([
|
|
5
|
-
'portion_product_exempt', 'portion_reduced_rated', 'portion_standard_rated', 'taxable_basis_reduced',
|
|
6
|
-
'proportionally_rated',
|
|
7
|
-
])
|
|
8
|
-
|
|
9
|
-
export const TAX_TYPE_MAP: Readonly<Record<string, TaxType>> = Object.freeze({
|
|
10
|
-
vat: TaxType.Vat, gst: TaxType.Gst, sales_tax: TaxType.SalesTax,
|
|
11
|
-
})
|
|
12
|
-
|
|
13
1
|
export const RESYNC_PAGE = 200
|
|
14
2
|
|
|
15
|
-
export const DISPUTE_PHASES: Record<string, DisputePhase> = {
|
|
16
|
-
'charge.dispute.created': 'opened',
|
|
17
|
-
'charge.dispute.funds_withdrawn': 'funds-withdrawn',
|
|
18
|
-
'charge.dispute.funds_reinstated': 'funds-reinstated',
|
|
19
|
-
'charge.dispute.closed': 'closed',
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Stripe's limit on every `custom_text` message. */
|
|
23
|
-
export const CUSTOM_TEXT_MAX = 1200
|
|
24
|
-
|
|
25
3
|
export const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
26
4
|
|
|
27
|
-
/**
|
|
28
|
-
export const
|
|
29
|
-
|
|
30
|
-
export const NEEDS_POSTAL_CODE_OR_STATE = new Set(['CA', 'IN'])
|
|
5
|
+
/** The highest-ranked entitling subscription first, the newest on a tie. */
|
|
6
|
+
export const ENTITLING_SORT = [{ field: 'rank', order: 'desc' }, { field: 'createdAt', order: 'desc' }] as const
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Serialized work per paygate customer, within this process. */
|
|
2
2
|
export interface CustomerLockHelper {
|
|
3
|
-
/** Serialize the work on one paygate
|
|
4
|
-
withCustomerLock: <T>(customerId: string | undefined, fn: () => Promise<T>) => Promise<T>
|
|
3
|
+
/** Serialize the work on one customer of one paygate within this process (key `<paygate>:<customer id>`). */
|
|
4
|
+
withCustomerLock: <T>(paygate: string, customerId: string | undefined, fn: () => Promise<T>) => Promise<T>
|
|
5
5
|
}
|
|
@@ -4,8 +4,8 @@ import type { CustomerLockHelper } from './customer-lock/types.js'
|
|
|
4
4
|
export const createCustomerLockHelper = (): CustomerLockHelper => {
|
|
5
5
|
const customerMutex: Record<string, Mutex> = {}
|
|
6
6
|
|
|
7
|
-
const withCustomerLock = async <T>(customerId: string | undefined, fn: () => Promise<T>): Promise<T> => {
|
|
8
|
-
const key = customerId ?? ''
|
|
7
|
+
const withCustomerLock = async <T>(paygate: string, customerId: string | undefined, fn: () => Promise<T>): Promise<T> => {
|
|
8
|
+
const key = `${paygate}:${customerId ?? ''}`
|
|
9
9
|
const mutex = customerMutex[key] = customerMutex[key] ?? new Mutex()
|
|
10
10
|
const release = await mutex.acquire()
|
|
11
11
|
try {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EstimateCache } from './types.js'
|
|
2
2
|
|
|
3
3
|
// One instance per gateway service, never module-level (a test builds many contexts in one process,
|
|
4
|
-
// and a module-level cache would make "no
|
|
4
|
+
// and a module-level cache would make "no paygate call" assertions order-dependent).
|
|
5
5
|
|
|
6
6
|
/** @param taxTtlMs default 24h; @param fxTtlMs default 1h; @param customerTtlMs default 5min. */
|
|
7
7
|
export const makeEstimateCache = (
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import type { PriceEstimate } from '@owlmeans/payment'
|
|
3
2
|
import type { PriceEstimateParams } from '../../types.js'
|
|
3
|
+
import type { PaygateCustomer } from '../../paygate/types.js'
|
|
4
4
|
import type { CacheEntry, FxOutcome, TaxOutcome } from '../types.local.js'
|
|
5
5
|
|
|
6
6
|
export interface EstimateCache {
|
|
@@ -9,20 +9,20 @@ export interface EstimateCache {
|
|
|
9
9
|
customerTtlMs: number
|
|
10
10
|
tax: Map<string, CacheEntry<TaxOutcome>>
|
|
11
11
|
fx: Map<string, CacheEntry<FxOutcome>>
|
|
12
|
-
customer: Map<string, CacheEntry<
|
|
12
|
+
customer: Map<string, CacheEntry<PaygateCustomer | null>>
|
|
13
13
|
inflight: Map<string, Promise<unknown>>
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
/** Price estimates of a context:
|
|
16
|
+
/** Price estimates of a context: the paygate's tax calculation and the local-currency line. */
|
|
17
17
|
export interface EstimateHelper {
|
|
18
18
|
/**
|
|
19
|
-
* A
|
|
20
|
-
*
|
|
19
|
+
* A tax estimate (and, when the pricing policy asks for it, a local-currency conversion) for one
|
|
20
|
+
* product/plan, at a billing country the request names or the entity's paygate customer does —
|
|
21
|
+
* through `params.paygate`, else the first registered paygate the plan is for sale through.
|
|
21
22
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* never cached.
|
|
23
|
+
* One tax calculation per distinct (paygate, currency, country, amount, tax code, behavior,
|
|
24
|
+
* matching tax ids) within `cache`'s TTL, and one FX quote per distinct (currency, local currency)
|
|
25
|
+
* — never more; a failed call is never cached. A paygate without `tax` answers `at-checkout`.
|
|
26
26
|
*/
|
|
27
|
-
|
|
27
|
+
estimatePrice: (params: PriceEstimateParams, cache: EstimateCache) => Promise<PriceEstimate>
|
|
28
28
|
}
|
package/src/plugins/estimate.ts
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { CheckoutPricingMode, currencyOfCountry, ProductError, TaxBehavior, TaxEstimateStatus, TaxType, UnknownProduct, type PriceEstimate, type TaxEstimate, type TaxRateEstimate, checkoutPricingHelper, consumerRegionHelper, priceEstimateHelper } from '@owlmeans/payment'
|
|
1
|
+
import { CheckoutPricingMode, currencyOfCountry, ProductError, TaxBehavior, TaxEstimateStatus, UnknownProduct, type PriceEstimate, type TaxEstimate, checkoutPricingHelper, consumerRegionHelper } from '@owlmeans/payment'
|
|
3
2
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
4
3
|
import { memoHelper } from '@owlmeans/context'
|
|
5
|
-
import { STRIPE_FX_QUOTES_API_VERSION, STRIPE_PAYGATE_ALIAS } from '../consts.js'
|
|
6
4
|
import type { PaymentPlan, PaymentProduct, PriceEstimateParams } from '../types.js'
|
|
7
|
-
import { NON_SCALABLE_REASONS, TAX_TYPE_MAP } from './consts.local.js'
|
|
8
5
|
import type { CacheEntry, FxOutcome, TaxOutcome } from './types.local.js'
|
|
9
6
|
import type { EstimateCache, EstimateHelper } from './estimate/types.js'
|
|
10
|
-
import {
|
|
7
|
+
import type { Paygate, PaygateCustomer } from '../paygate/types.js'
|
|
11
8
|
import { paymentAccessOf } from '../access.js'
|
|
12
|
-
import { paymentUtils } from '../utils.js'
|
|
13
9
|
import { catalogueOf } from '../catalogue.js'
|
|
14
|
-
import {
|
|
10
|
+
import { paygatesOf } from '../paygate/registry.js'
|
|
15
11
|
|
|
16
12
|
/**
|
|
17
13
|
* A keyed value cached for `ttlMs`, with in-flight requests shared across concurrent callers. Only
|
|
@@ -43,54 +39,6 @@ const cached = async <T>(
|
|
|
43
39
|
return promise
|
|
44
40
|
}
|
|
45
41
|
|
|
46
|
-
// -------------------------------------------------------------------------------------------
|
|
47
|
-
// Tax
|
|
48
|
-
// -------------------------------------------------------------------------------------------
|
|
49
|
-
|
|
50
|
-
/** A duck-typed check, matching `isMissingObject` above: the installed SDK's own error classes. */
|
|
51
|
-
const isInvalidRequest = (error: unknown): error is { code?: string } =>
|
|
52
|
-
(error as { type?: unknown } | null)?.type === 'StripeInvalidRequestError'
|
|
53
|
-
|
|
54
|
-
/** A linear percentage rate scales with the amount; a flat fee, a partial exemption, or several inclusive rates do not. */
|
|
55
|
-
const scalableOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[], behavior: TaxBehavior): boolean => {
|
|
56
|
-
if (breakdown.some(row => row.tax_rate_details?.rate_type === 'flat_amount')) return false
|
|
57
|
-
if (breakdown.some(row => NON_SCALABLE_REASONS.has(row.taxability_reason))) return false
|
|
58
|
-
if (behavior === TaxBehavior.Inclusive && breakdown.length > 1) return false
|
|
59
|
-
return true
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const statusOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[], taxMinor: number): TaxEstimateStatus => {
|
|
63
|
-
if (breakdown.some(row => row.taxability_reason === 'reverse_charge')) return TaxEstimateStatus.ReverseCharge
|
|
64
|
-
if (taxMinor > 0) return TaxEstimateStatus.Taxed
|
|
65
|
-
if (breakdown.some(row => row.taxability_reason === 'not_supported')) return TaxEstimateStatus.AtCheckout
|
|
66
|
-
return TaxEstimateStatus.None
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const taxTypeOf = (raw: string | null | undefined): TaxType => raw != null && raw in TAX_TYPE_MAP ? TAX_TYPE_MAP[raw] : TaxType.Tax
|
|
70
|
-
|
|
71
|
-
const ratesOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[]): TaxRateEstimate[] => breakdown
|
|
72
|
-
.filter((row): row is Stripe.Tax.Calculation.TaxBreakdown & {
|
|
73
|
-
tax_rate_details: NonNullable<Stripe.Tax.Calculation.TaxBreakdown['tax_rate_details']>
|
|
74
|
-
} => row.tax_rate_details != null)
|
|
75
|
-
.map(row => ({
|
|
76
|
-
type: taxTypeOf(row.tax_rate_details.tax_type),
|
|
77
|
-
percentage: row.tax_rate_details.percentage_decimal,
|
|
78
|
-
ratePpm: priceEstimateHelper.ratePpmOf(row.tax_rate_details.percentage_decimal),
|
|
79
|
-
...(row.tax_rate_details.country != null ? { country: row.tax_rate_details.country } : {}),
|
|
80
|
-
...(row.tax_rate_details.state != null ? { state: row.tax_rate_details.state } : {}),
|
|
81
|
-
}))
|
|
82
|
-
|
|
83
|
-
const taxEstimateOf = (calculation: Stripe.Tax.Calculation, behavior: TaxBehavior, subtotalMinor: number): TaxEstimate => {
|
|
84
|
-
const breakdown = calculation.tax_breakdown ?? []
|
|
85
|
-
const taxMinor = calculation.tax_amount_exclusive + calculation.tax_amount_inclusive
|
|
86
|
-
const status = statusOf(breakdown, taxMinor)
|
|
87
|
-
|
|
88
|
-
return {
|
|
89
|
-
status, subtotalMinor, taxMinor, totalMinor: calculation.amount_total,
|
|
90
|
-
scalable: scalableOf(breakdown, behavior), rates: ratesOf(breakdown),
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
42
|
/** The reference amount and currency of the estimate: an amount plan's default preset, else the plan's own price. */
|
|
95
43
|
const referenceOf = (plan: PaymentPlan): { subtotalMinor: number; currency: string } => {
|
|
96
44
|
if (plan.pricingMode === CheckoutPricingMode.Amount) {
|
|
@@ -113,19 +61,14 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
113
61
|
|
|
114
62
|
// Customer lookup — the fallback country and the tax ids a request-given country still checks.
|
|
115
63
|
const cachedCustomer = async (
|
|
116
|
-
|
|
117
|
-
): Promise<
|
|
118
|
-
const record = await access.paygateCustomers().byEntity(entityId,
|
|
64
|
+
paygate: Paygate, entityId: string, cache: EstimateCache,
|
|
65
|
+
): Promise<PaygateCustomer | null> => cached(cache.customer, cache.inflight, `customer:${paygate.id}:${entityId}`, cache.customerTtlMs, async () => {
|
|
66
|
+
const record = await access.paygateCustomers().byEntity(entityId, paygate.id)
|
|
119
67
|
if (record == null || record.deletedAt != null) {
|
|
120
68
|
return null
|
|
121
69
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return (retrieved as Stripe.DeletedCustomer).deleted ? null : retrieved as Stripe.Customer
|
|
125
|
-
} catch (error) {
|
|
126
|
-
if (paymentUtils.isMissingObject(error)) return null
|
|
127
|
-
throw error
|
|
128
|
-
}
|
|
70
|
+
|
|
71
|
+
return await paygate.customers.retrieve(record.externalId, { taxIds: true })
|
|
129
72
|
})
|
|
130
73
|
|
|
131
74
|
/**
|
|
@@ -152,24 +95,25 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
152
95
|
return option != null ? { subtotalMinor: option.unitAmount, currency: chargeCurrency } : reference
|
|
153
96
|
}
|
|
154
97
|
|
|
155
|
-
// Currency:
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
// the way Checkout prices it, one without keeps the quote's rate.
|
|
98
|
+
// Currency: the paygate's FX quotes. A buyer's local currency is priced at the BASE rate plus the
|
|
99
|
+
// paygate's own conversion fee (`price × (1 + fee)`), which a quote's fee-inclusive `exchangeRate`
|
|
100
|
+
// understates; a policy declaring `adaptiveFeeRate` is estimated the way checkout prices it, one
|
|
101
|
+
// without keeps the quote's rate.
|
|
160
102
|
const fetchFxRate = async (
|
|
161
|
-
|
|
103
|
+
paygate: Paygate, currency: string, localCurrency: string,
|
|
162
104
|
settlementCurrency: string = currency, adaptiveFeeRate?: number,
|
|
163
105
|
): Promise<FxOutcome> => {
|
|
106
|
+
const fx = paygate.fx
|
|
107
|
+
if (fx == null) return null
|
|
164
108
|
const settlement = settlementCurrency.toLowerCase()
|
|
165
109
|
const sourceRate = settlement === currency
|
|
166
110
|
? { referenceRate: 1 }
|
|
167
|
-
: await
|
|
111
|
+
: await fx.quote(currency, settlement)
|
|
168
112
|
if (sourceRate == null) return null
|
|
169
113
|
if (localCurrency === settlement) {
|
|
170
114
|
return { currency: localCurrency, exchangeRate: 1 / sourceRate.referenceRate }
|
|
171
115
|
}
|
|
172
|
-
const localRate = await
|
|
116
|
+
const localRate = await fx.quote(localCurrency, settlement)
|
|
173
117
|
if (localRate == null) return null
|
|
174
118
|
const settlementPerLocal = adaptiveFeeRate != null ? localRate.baseRate / (1 + adaptiveFeeRate) : localRate.exchangeRate
|
|
175
119
|
const feeRate = adaptiveFeeRate ?? localRate.fxFeeRate
|
|
@@ -179,17 +123,17 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
179
123
|
}
|
|
180
124
|
}
|
|
181
125
|
|
|
182
|
-
const
|
|
183
|
-
stripe: Stripe, params: PriceEstimateParams, cache: EstimateCache,
|
|
184
|
-
): Promise<PriceEstimate> => {
|
|
126
|
+
const estimatePrice = async (params: PriceEstimateParams, cache: EstimateCache): Promise<PriceEstimate> => {
|
|
185
127
|
const product = await catalogueOf(ctx).findProduct(params.productSku) as PaymentProduct | null
|
|
186
128
|
if (product == null) throw new UnknownProduct(params.productSku)
|
|
129
|
+
const paygates = paygatesOf(ctx)
|
|
187
130
|
const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
|
|
188
|
-
.filter(plan =>
|
|
131
|
+
.filter(plan => paygates.forSale(product, plan, params.paygate).length > 0)
|
|
189
132
|
const plan = params.planSku != null
|
|
190
133
|
? plans.find(item => item.sku === params.planSku)
|
|
191
134
|
: plans.find(item => item.recurring != null) ?? plans[0]
|
|
192
135
|
if (plan == null) throw new ProductError(params.planSku != null ? `plan:${params.planSku}` : 'plan')
|
|
136
|
+
const paygate = paygates.forSale(product, plan, params.paygate)[0]
|
|
193
137
|
|
|
194
138
|
const pricing = await access.payment().pricingPolicy()
|
|
195
139
|
const behavior = pricing.tax.behavior ?? TaxBehavior.Exclusive
|
|
@@ -201,25 +145,25 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
201
145
|
let country = locked ? profile.country as string : params.country?.toUpperCase()
|
|
202
146
|
let source: 'request' | 'customer' | 'profile' | undefined = locked ? 'profile' : country != null ? 'request' : undefined
|
|
203
147
|
let matchingTaxIds: Array<{ type: string; value: string }> = []
|
|
204
|
-
let
|
|
148
|
+
let exemption: 'exempt' | 'reverse' | undefined
|
|
205
149
|
|
|
206
|
-
const customer = await cachedCustomer(
|
|
150
|
+
const customer = await cachedCustomer(paygate, params.entityId, cache)
|
|
207
151
|
if (customer != null) {
|
|
208
|
-
if (country == null && customer.
|
|
209
|
-
country = customer.
|
|
152
|
+
if (country == null && customer.country != null) {
|
|
153
|
+
country = customer.country
|
|
210
154
|
source = 'customer'
|
|
211
155
|
}
|
|
212
156
|
if (country != null) {
|
|
213
|
-
matchingTaxIds = (customer.
|
|
157
|
+
matchingTaxIds = (customer.taxIds ?? [])
|
|
214
158
|
.filter(taxId => taxId.country === country)
|
|
215
159
|
.map(taxId => ({ type: taxId.type, value: taxId.value }))
|
|
216
|
-
if (customer.
|
|
217
|
-
else if (customer.
|
|
160
|
+
if (customer.taxExempt === 'exempt') exemption = 'exempt'
|
|
161
|
+
else if (customer.taxExempt === 'reverse') exemption = 'reverse'
|
|
218
162
|
}
|
|
219
163
|
}
|
|
220
164
|
|
|
221
165
|
const region = rights != null ? consumerRegionHelper.regionOf(country, rights) : null
|
|
222
|
-
const settlementCurrency = (await
|
|
166
|
+
const settlementCurrency = (await paygate.settlementCurrency())?.toLowerCase()
|
|
223
167
|
// The currency the checkout session charges: the region's (or the locked profile's) under a policy
|
|
224
168
|
// with region currencies, else none forced.
|
|
225
169
|
const chargeCurrency = rights != null && rights.currencies != null && Object.keys(rights.currencies).length > 0
|
|
@@ -232,44 +176,26 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
232
176
|
return { currency, behavior, tax: unresolvedEstimate(TaxEstimateStatus.LocationRequired, subtotalMinor), ...where }
|
|
233
177
|
}
|
|
234
178
|
|
|
179
|
+
if (paygate.tax == null) {
|
|
180
|
+
return { country, source, currency, behavior, tax: unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor), ...where } as PriceEstimate
|
|
181
|
+
}
|
|
182
|
+
const tax = paygate.tax
|
|
235
183
|
const cacheKey = JSON.stringify([
|
|
236
|
-
currency, country, subtotalMinor, product.taxCode ?? null, behavior,
|
|
237
|
-
matchingTaxIds.map(id => `${id.type}:${id.value}`).sort(),
|
|
184
|
+
paygate.id, currency, country, subtotalMinor, product.taxCode ?? null, behavior,
|
|
185
|
+
matchingTaxIds.map(id => `${id.type}:${id.value}`).sort(), exemption ?? null,
|
|
238
186
|
])
|
|
239
|
-
const outcome = await cached(cache.tax, cache.inflight, `tax:${cacheKey}`, cache.taxTtlMs, async (): Promise<TaxOutcome> =>
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
// parameter's own tax-id-type enum are independently generated from Stripe's OpenAPI
|
|
252
|
-
// spec and can drift apart in this pinned SDK; every value here still came from a real
|
|
253
|
-
// Stripe `TaxId` record, so it is valid at the API even where the two types disagree.
|
|
254
|
-
...(matchingTaxIds.length > 0
|
|
255
|
-
? { tax_ids: matchingTaxIds as Stripe.Tax.CalculationCreateParams.CustomerDetails['tax_ids'] }
|
|
256
|
-
: {}),
|
|
257
|
-
...(taxabilityOverride != null ? { taxability_override: taxabilityOverride } : {}),
|
|
258
|
-
},
|
|
259
|
-
})
|
|
260
|
-
return { ok: true, calculation }
|
|
261
|
-
} catch (error) {
|
|
262
|
-
if (isInvalidRequest(error)) return { ok: false, code: error.code }
|
|
263
|
-
throw error
|
|
264
|
-
}
|
|
265
|
-
})
|
|
266
|
-
|
|
267
|
-
const tax = outcome.ok
|
|
268
|
-
? taxEstimateOf(outcome.calculation, behavior, subtotalMinor)
|
|
269
|
-
: unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor)
|
|
270
|
-
|
|
271
|
-
const result: PriceEstimate = { country, source, currency, behavior, tax, ...where }
|
|
272
|
-
// Adaptive Pricing — and so a local-currency line — applies only to a session CHARGED in the
|
|
187
|
+
const outcome = await cached(cache.tax, cache.inflight, `tax:${cacheKey}`, cache.taxTtlMs, async (): Promise<TaxOutcome> =>
|
|
188
|
+
await tax.calculate({
|
|
189
|
+
currency, amountMinor: subtotalMinor, reference: plan.sku, taxBehavior: behavior,
|
|
190
|
+
...(product.taxCode != null ? { taxCode: product.taxCode } : {}),
|
|
191
|
+
country: country as string, taxIds: matchingTaxIds,
|
|
192
|
+
...(exemption != null ? { exemption } : {}),
|
|
193
|
+
}))
|
|
194
|
+
|
|
195
|
+
const estimated: TaxEstimate = outcome ?? unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor)
|
|
196
|
+
|
|
197
|
+
const result: PriceEstimate = { country, source, currency, behavior, tax: estimated, ...where }
|
|
198
|
+
// Local-currency pricing — and so a local-currency line — applies only to a session CHARGED in the
|
|
273
199
|
// settlement currency; a forced region currency (exact USD) is shown as it is. An amount plan is
|
|
274
200
|
// estimated in its policy currency but charged in the region's currency (converted per session,
|
|
275
201
|
// `chargeAmount`), so the session's currency decides, never the reference's: a EUR-charged top-up
|
|
@@ -280,14 +206,12 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
280
206
|
if (pricing.currency.estimate && pricing.currency.adaptive === true && adaptive) {
|
|
281
207
|
const localCurrency = currencyOfCountry(country)
|
|
282
208
|
if (localCurrency != null && localCurrency !== currency) {
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
const settlementCurrency = stripePricing?.settlementCurrency?.toLowerCase() ?? currency
|
|
286
|
-
// A preview endpoint: unreachable or erroring never fails the estimate, it only drops `local`.
|
|
209
|
+
const settlement = settlementCurrency ?? currency
|
|
210
|
+
// A rate that cannot be read never fails the estimate, it only drops `local`.
|
|
287
211
|
const feeRate = pricing.currency.adaptiveFeeRate
|
|
288
212
|
const fx = await cached(
|
|
289
|
-
cache.fx, cache.inflight, `fx:${
|
|
290
|
-
() => fetchFxRate(
|
|
213
|
+
cache.fx, cache.inflight, `fx:${paygate.id}:${currency}:${settlement}:${localCurrency}:${feeRate ?? ''}`, cache.fxTtlMs,
|
|
214
|
+
() => fetchFxRate(paygate, currency, localCurrency, settlement, feeRate),
|
|
291
215
|
).catch(() => null)
|
|
292
216
|
if (fx != null) {
|
|
293
217
|
result.local = { currency: fx.currency, exchangeRate: fx.exchangeRate, ...(fx.fxFeeRate != null ? { fxFeeRate: fx.fxFeeRate } : {}) }
|
|
@@ -298,7 +222,7 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
|
|
|
298
222
|
return result
|
|
299
223
|
}
|
|
300
224
|
|
|
301
|
-
return {
|
|
225
|
+
return { estimatePrice }
|
|
302
226
|
}
|
|
303
227
|
|
|
304
228
|
/** The price estimates of a context — one per context. */
|
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import type { Paygate, PaygateEvent } from '../../paygate/types.js'
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
3
|
+
/** The paygate events of a context, applied to the stores and told to the observers. */
|
|
4
|
+
export interface PaymentEventsHelper {
|
|
5
|
+
/**
|
|
6
|
+
* Apply one event a paygate's webhook produced. A throw escapes so the paygate delivers again:
|
|
7
|
+
*
|
|
8
|
+
* - `customer` — the customer row upserted (`country`, `currency`) or marked deleted;
|
|
9
|
+
* - `checkout` `completed` — a paid one-time checkout fulfilled (purchase, lock, confirmation mail,
|
|
10
|
+
* fulfillment, `onTopUp`), a subscription checkout completed; `failed` — `onPaymentFailed`;
|
|
11
|
+
* `expired` — the unfulfilled row purged; the checkout plugins hear `settled`;
|
|
12
|
+
* - `subscription` — applied to its row (`onSubscription`), a deleted one as canceled;
|
|
13
|
+
* - `invoice` — a renewal re-reads and applies its subscription, a failed payment tells
|
|
14
|
+
* `onPaymentFailed`, others keep the row's latest invoice;
|
|
15
|
+
* - `refund` (succeeded) and `dispute` — resolved to their fulfillment or subscription, recorded,
|
|
16
|
+
* told to `onRefund` / `onDispute`.
|
|
17
|
+
*/
|
|
18
|
+
apply: (paygate: Paygate, event: PaygateEvent) => Promise<void>
|
|
11
19
|
}
|