@zonastery/bursar 2.0.6 → 2.2.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 +33 -4
- package/dist/billing/auto-recharge-port.d.ts +11 -0
- package/dist/billing/auto-recharge-port.d.ts.map +1 -1
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +53 -26
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +38 -3
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +51 -7
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +34 -9
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +35 -3
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +1 -2
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +69 -29
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +2 -2
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +82 -19
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +168 -44
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +16 -3
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +11 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +13 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +71 -12
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +33 -3
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +5 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +7 -10
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +6 -1
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +25 -16
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js +25 -4
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +3 -2
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +44 -48
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +6 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +27 -10
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +46 -34
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +152 -126
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +0 -1
- package/dist/billing/service-types.d.ts.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +2 -0
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -0
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +15 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +2 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +15 -0
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +12 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +2 -24
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -29
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts +13 -21
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +44 -50
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +21 -2
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +27 -4
- package/dist/catalog.js.map +1 -1
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +147 -0
- package/dist/cli.js.map +1 -0
- package/dist/commerce/plan-change.d.ts +3 -3
- package/dist/commerce/plan-change.d.ts.map +1 -1
- package/dist/commerce/plan-change.js +14 -7
- package/dist/commerce/plan-change.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js +8 -2
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts +2 -0
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +330 -76
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +12 -3
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/availability.d.ts +4 -0
- package/dist/config/availability.d.ts.map +1 -0
- package/dist/config/availability.js +10 -0
- package/dist/config/availability.js.map +1 -0
- package/dist/config/normalize.d.ts +7 -0
- package/dist/config/normalize.d.ts.map +1 -0
- package/dist/config/normalize.js +119 -0
- package/dist/config/normalize.js.map +1 -0
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +4 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts +5 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +79 -22
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +10 -7
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +31 -15
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +42 -27
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +4 -0
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +26 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +8 -4
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +5 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +118 -70
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +5 -4
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +15 -2
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +77 -21
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +3 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +47 -38
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -7
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +6 -57
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +25 -7
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts +28 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +33 -14
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +2 -2
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +2 -12
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +9 -2
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +3 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +46 -12
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +6 -1
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +13 -3
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +1 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +9 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +30 -20
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +335 -251
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +4 -4
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/rated-wire.d.ts +7 -0
- package/dist/credits/rated-wire.d.ts.map +1 -0
- package/dist/credits/rated-wire.js +70 -0
- package/dist/credits/rated-wire.js.map +1 -0
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +8 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +5 -7
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +12 -9
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +161 -138
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +11 -3
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +9 -0
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +9 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/admission.d.ts +1 -0
- package/dist/credits/types/admission.d.ts.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +1 -0
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.d.ts +12 -0
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +13 -0
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/quotas.d.ts +2 -1
- package/dist/credits/types/quotas.d.ts.map +1 -1
- package/dist/credits/types/quotas.js.map +1 -1
- package/dist/engine.d.ts +4 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +59 -36
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +12 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +29 -9
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/language.js +1 -1
- package/dist/expr/language.js.map +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +5 -6
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +272 -228
- package/dist/generated/pricing-config.types.d.ts +128 -79
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +5 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +56 -17
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +2 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -1
- package/dist/node.js.map +1 -1
- package/dist/pricing-decimal.d.ts +7 -0
- package/dist/pricing-decimal.d.ts.map +1 -0
- package/dist/pricing-decimal.js +43 -0
- package/dist/pricing-decimal.js.map +1 -0
- package/dist/providers/dodo/better-auth-core.d.ts +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth-core.js +2 -2
- package/dist/providers/dodo/better-auth-core.js.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -2
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +124 -18
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs-core.js +2 -2
- package/dist/providers/dodo/nextjs-core.js.map +1 -1
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +16 -6
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +5 -2
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +46 -7
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
- package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
- package/dist/providers/dodo/verified-payment-payload.js +42 -0
- package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +4 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +3 -1
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +51 -24
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +4 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +118 -34
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +16 -2
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +9 -0
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +5 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +72 -11
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js +6 -0
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/provider-rejection.d.ts +3 -0
- package/dist/shared/provider-rejection.d.ts.map +1 -0
- package/dist/shared/provider-rejection.js +17 -0
- package/dist/shared/provider-rejection.js.map +1 -0
- package/dist/shared/timestamp.d.ts +5 -0
- package/dist/shared/timestamp.d.ts.map +1 -0
- package/dist/shared/timestamp.js +21 -0
- package/dist/shared/timestamp.js.map +1 -0
- package/dist/starter.yaml +17 -0
- package/dist/storage/adapters/clickhouse.d.ts +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +42 -37
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +5 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +46 -14
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +3 -7
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js +6 -15
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +4 -3
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +8 -0
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +1 -3
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +34 -12
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/raw-json.d.ts +10 -0
- package/dist/storage/raw-json.d.ts.map +1 -0
- package/dist/storage/raw-json.js +19 -0
- package/dist/storage/raw-json.js.map +1 -0
- package/dist/storage/runtime.d.ts +15 -10
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +97 -68
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/package.json +78 -71
- package/dist/credits/queries.d.ts +0 -33
- package/dist/credits/queries.d.ts.map +0 -1
- package/dist/credits/queries.js +0 -71
- package/dist/credits/queries.js.map +0 -1
package/dist/commerce/service.js
CHANGED
|
@@ -2,9 +2,13 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { Decimal } from "decimal.js";
|
|
4
4
|
import { loadConfigFromDict } from "../config.js";
|
|
5
|
-
import {
|
|
5
|
+
import { offerIsAvailable } from "../config/availability.js";
|
|
6
|
+
import { resolveProviderId } from "../config/parse-commerce.js";
|
|
7
|
+
import { ProviderResponseError, StoreError } from "../errors.js";
|
|
8
|
+
import { ProviderOperationOutcomeUnknownError } from "../providers/types.js";
|
|
6
9
|
import { normalizeLogger } from "../shared/logger.js";
|
|
7
10
|
import { requireStableKey, scopedStableKey } from "../shared/idempotency.js";
|
|
11
|
+
import { isDefinitiveProviderRejection } from "../shared/provider-rejection.js";
|
|
8
12
|
import { normalizeProviderEnvironment } from "../providers/environment.js";
|
|
9
13
|
import { persistedDiagnosticSummary } from "../shared/diagnostics.js";
|
|
10
14
|
import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
|
|
@@ -27,6 +31,12 @@ function requireOptionalNonEmptyText(value, field) {
|
|
|
27
31
|
if (value !== null && value !== undefined)
|
|
28
32
|
requireNonEmptyText(value, field);
|
|
29
33
|
}
|
|
34
|
+
function assertTrustedRegion(region) {
|
|
35
|
+
if (region !== undefined &&
|
|
36
|
+
(typeof region !== "string" || !/^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/.test(region))) {
|
|
37
|
+
throw new TypeError("region must be an uppercase ISO region code");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
30
40
|
function assertCreateCheckoutInput(input) {
|
|
31
41
|
requireNonEmptyText(input.subjectId, "subjectId");
|
|
32
42
|
requireNonEmptyText(input.accountId, "accountId");
|
|
@@ -36,6 +46,7 @@ function assertCreateCheckoutInput(input) {
|
|
|
36
46
|
requireStableKey(input.operationKey, "operationKey");
|
|
37
47
|
requireOptionalNonEmptyText(input.email, "email");
|
|
38
48
|
requireOptionalNonEmptyText(input.provider, "provider");
|
|
49
|
+
assertTrustedRegion(input.region);
|
|
39
50
|
if (input.type !== undefined && input.type !== "subscription" && input.type !== "credit_pack") {
|
|
40
51
|
throw new TypeError("type must be 'subscription' or 'credit_pack'");
|
|
41
52
|
}
|
|
@@ -56,14 +67,14 @@ const TERMINAL_SUBSCRIPTION_STATUSES = new Set([
|
|
|
56
67
|
"incomplete_expired",
|
|
57
68
|
"expired",
|
|
58
69
|
]);
|
|
59
|
-
function externalId(reference) {
|
|
70
|
+
function externalId(reference, environment) {
|
|
60
71
|
switch (reference.type) {
|
|
61
72
|
case "stripe_price":
|
|
62
|
-
return reference.priceId;
|
|
73
|
+
return resolveProviderId(reference.priceId, environment);
|
|
63
74
|
case "dodo_product":
|
|
64
|
-
return reference.productId;
|
|
75
|
+
return resolveProviderId(reference.productId, environment);
|
|
65
76
|
case "custom_object":
|
|
66
|
-
return reference.externalId;
|
|
77
|
+
return resolveProviderId(reference.externalId, environment);
|
|
67
78
|
}
|
|
68
79
|
}
|
|
69
80
|
function checkoutRedirectUrl(template, intentId) {
|
|
@@ -183,12 +194,14 @@ class CommerceAutoRechargeService {
|
|
|
183
194
|
this.commerce.providerForAccount(input.accountId),
|
|
184
195
|
this.commerce.credits.getBalance(input.accountId),
|
|
185
196
|
]);
|
|
186
|
-
await this.commerce.billing.autoRecharge.retry({
|
|
197
|
+
const result = await this.commerce.billing.autoRecharge.retry({
|
|
187
198
|
userId: input.accountId,
|
|
188
199
|
provider,
|
|
189
200
|
balance: balance.balance,
|
|
190
201
|
returnUrl: input.returnUrl,
|
|
191
202
|
});
|
|
203
|
+
if (result.outcome === "not_configured")
|
|
204
|
+
return null;
|
|
192
205
|
return this.commerce.billing.autoRecharge.getStatus({
|
|
193
206
|
userId: input.accountId,
|
|
194
207
|
provider,
|
|
@@ -247,7 +260,7 @@ export class CommerceService {
|
|
|
247
260
|
throw new CoreBillingDataUnavailableError("The active commerce catalog is unavailable");
|
|
248
261
|
}
|
|
249
262
|
try {
|
|
250
|
-
return loadConfigFromDict(raw);
|
|
263
|
+
return loadConfigFromDict(raw, this.options.providerEnvironment);
|
|
251
264
|
}
|
|
252
265
|
catch (error) {
|
|
253
266
|
throw new CoreBillingDataUnavailableError("The active commerce catalog is invalid", error);
|
|
@@ -295,24 +308,81 @@ export class CommerceService {
|
|
|
295
308
|
}
|
|
296
309
|
async createCheckout(input) {
|
|
297
310
|
assertCreateCheckoutInput(input);
|
|
298
|
-
|
|
299
|
-
|
|
311
|
+
return this.createCheckoutAttempt(input, 0);
|
|
312
|
+
}
|
|
313
|
+
async createCheckoutAttempt(input, attempt) {
|
|
314
|
+
const findWinner = () => this.billing.findCheckoutIntent(input.subjectId, input.operationKey, input.provider);
|
|
315
|
+
const replay = await findWinner();
|
|
316
|
+
if (replay && input.provider && replay.intent.provider !== input.provider) {
|
|
317
|
+
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
318
|
+
}
|
|
319
|
+
let resolved;
|
|
320
|
+
let expectedRevisionId;
|
|
321
|
+
if (replay) {
|
|
322
|
+
const config = loadConfigFromDict(replay.catalog, this.options.providerEnvironment);
|
|
323
|
+
const offer = config.commerce.offers[input.offerKey];
|
|
324
|
+
if (!offer)
|
|
325
|
+
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
326
|
+
try {
|
|
327
|
+
this.assertOfferType(offer, input.type);
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
331
|
+
}
|
|
332
|
+
resolved = { config, offerKey: input.offerKey, offer };
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
const revision = await this.billing.getActiveCatalogRevision();
|
|
336
|
+
if (!revision)
|
|
337
|
+
throw new CoreBillingDataUnavailableError("The active commerce catalog is unavailable");
|
|
338
|
+
expectedRevisionId = revision.id;
|
|
339
|
+
const config = loadConfigFromDict(revision.config, this.options.providerEnvironment);
|
|
340
|
+
const offer = config.commerce.offers[input.offerKey];
|
|
341
|
+
if (!offer) {
|
|
342
|
+
if (attempt === 0 && (await findWinner()))
|
|
343
|
+
return this.createCheckoutAttempt(input, 1);
|
|
344
|
+
throw new UnknownOfferError(`Unknown offer '${input.offerKey}'`);
|
|
345
|
+
}
|
|
346
|
+
this.assertOfferType(offer, input.type);
|
|
347
|
+
resolved = { config, offerKey: input.offerKey, offer };
|
|
348
|
+
}
|
|
349
|
+
let quantity;
|
|
350
|
+
try {
|
|
351
|
+
quantity = this.quantity(resolved.offer, input.quantity);
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
if (replay)
|
|
355
|
+
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
356
|
+
if (attempt === 0 && (await findWinner()))
|
|
357
|
+
return this.createCheckoutAttempt(input, 1);
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
300
360
|
const accountState = await Promise.all([
|
|
301
361
|
this.billing.getBlockingSubscription(input.accountId),
|
|
302
362
|
this.billing.getCustomerByUserId(input.accountId),
|
|
303
363
|
]);
|
|
304
|
-
if (resolved.offer.type === "subscription" && accountState[0]) {
|
|
364
|
+
if (!replay && resolved.offer.type === "subscription" && accountState[0]) {
|
|
365
|
+
if (attempt === 0 && (await findWinner()))
|
|
366
|
+
return this.createCheckoutAttempt(input, 1);
|
|
305
367
|
throw new ActiveSubscriptionError();
|
|
306
368
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
369
|
+
let provider;
|
|
370
|
+
try {
|
|
371
|
+
provider = await this.providers.select({
|
|
372
|
+
requested: replay?.intent.provider ?? input.provider,
|
|
373
|
+
current: accountState[1]?.provider,
|
|
374
|
+
offer: resolved.offer,
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
if (!replay && attempt === 0 && (await findWinner()))
|
|
379
|
+
return this.createCheckoutAttempt(input, 1);
|
|
380
|
+
throw error;
|
|
381
|
+
}
|
|
312
382
|
const reference = resolved.offer.providers[provider.provider];
|
|
313
383
|
if (!reference)
|
|
314
384
|
throw new UnknownOfferError("Offer has no reference for the selected provider");
|
|
315
|
-
const productId = externalId(reference);
|
|
385
|
+
const productId = externalId(reference, this.options.providerEnvironment);
|
|
316
386
|
const customer = await this.billing.getCustomerByUserId(input.accountId, provider.provider);
|
|
317
387
|
const metadata = {
|
|
318
388
|
...(input.metadata ?? {}),
|
|
@@ -328,25 +398,54 @@ export class CommerceService {
|
|
|
328
398
|
}
|
|
329
399
|
const digestValue = {
|
|
330
400
|
accountId: input.accountId,
|
|
401
|
+
cancelUrl: input.cancelUrl,
|
|
331
402
|
checkoutKind: resolved.offer.type,
|
|
403
|
+
email: input.email ?? null,
|
|
404
|
+
metadata: Object.entries(metadata).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0),
|
|
332
405
|
offerKey: resolved.offerKey,
|
|
333
406
|
provider: provider.provider,
|
|
334
407
|
quantity,
|
|
408
|
+
returnUrl: input.returnUrl,
|
|
335
409
|
};
|
|
336
|
-
|
|
337
|
-
.
|
|
410
|
+
if (input.region !== undefined)
|
|
411
|
+
digestValue.region = input.region;
|
|
412
|
+
const digest = (value) => createHash("sha256")
|
|
413
|
+
.update(JSON.stringify(value, Object.keys(value).sort()))
|
|
338
414
|
.digest("hex");
|
|
415
|
+
const requestDigest = digest(digestValue);
|
|
339
416
|
const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
|
|
340
|
-
const createIntent = () =>
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
417
|
+
const createIntent = () => {
|
|
418
|
+
const request = {
|
|
419
|
+
subjectId: input.subjectId,
|
|
420
|
+
accountId: input.accountId,
|
|
421
|
+
provider: provider.provider,
|
|
422
|
+
operationKey: input.operationKey,
|
|
423
|
+
checkoutKind: resolved.offer.type === "subscription" ? "subscription" : "credit_topup",
|
|
424
|
+
productKey: resolved.offerKey,
|
|
425
|
+
requestDigest,
|
|
426
|
+
providerCustomerId: customer?.providerCustomerId ?? null,
|
|
427
|
+
expiresAt: expiresAt(),
|
|
428
|
+
};
|
|
429
|
+
if (input.region !== undefined)
|
|
430
|
+
request.region = input.region;
|
|
431
|
+
if (expectedRevisionId)
|
|
432
|
+
request.expectedRevisionId = expectedRevisionId;
|
|
433
|
+
return this.billing.createOrGetCheckoutIntent(request);
|
|
434
|
+
};
|
|
435
|
+
let intent;
|
|
436
|
+
try {
|
|
437
|
+
intent = replay?.intent ?? (await createIntent());
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
if (attempt === 0 &&
|
|
441
|
+
((error instanceof StoreError && error.details?.sqlState === "40001") ||
|
|
442
|
+
(await findWinner())))
|
|
443
|
+
return this.createCheckoutAttempt(input, 1);
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
if (intent.requestDigest !== requestDigest && !replay && attempt === 0) {
|
|
447
|
+
return this.createCheckoutAttempt(input, 1);
|
|
448
|
+
}
|
|
350
449
|
if (intent.requestDigest !== requestDigest) {
|
|
351
450
|
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
352
451
|
}
|
|
@@ -355,21 +454,24 @@ export class CommerceService {
|
|
|
355
454
|
if (intent.status !== "open") {
|
|
356
455
|
throw new CheckoutConflictError("This checkout operation is terminal; start a new checkout with a new operation key");
|
|
357
456
|
}
|
|
457
|
+
if (new Date(intent.expiresAt).getTime() <= Date.now()) {
|
|
458
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "expired" });
|
|
459
|
+
throw new CheckoutConflictError("This checkout operation expired; start a new checkout with a new operation key");
|
|
460
|
+
}
|
|
358
461
|
if (intent.checkoutUrl) {
|
|
359
|
-
const locallyExpired = new Date(intent.expiresAt).getTime() <= Date.now();
|
|
360
|
-
if (locallyExpired) {
|
|
361
|
-
await this.billing.updateCheckoutIntent(intent.id, { status: "expired" });
|
|
362
|
-
throw new CheckoutConflictError("This checkout operation expired; start a new checkout with a new operation key");
|
|
363
|
-
}
|
|
364
462
|
if (intent.providerSessionId && provider.getCheckoutSessionStatus) {
|
|
365
463
|
const providerState = await provider.getCheckoutSessionStatus(intent.providerSessionId);
|
|
366
464
|
if (providerState?.paymentStatus === "succeeded") {
|
|
367
|
-
await this.billing.updateCheckoutIntent(intent.id, {
|
|
465
|
+
await this.billing.updateCheckoutIntent(intent.id, {
|
|
466
|
+
status: "completed",
|
|
467
|
+
});
|
|
368
468
|
throw new CheckoutCompletedError();
|
|
369
469
|
}
|
|
370
470
|
if (providerState !== null &&
|
|
371
471
|
TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
|
|
372
|
-
await this.billing.updateCheckoutIntent(intent.id, {
|
|
472
|
+
await this.billing.updateCheckoutIntent(intent.id, {
|
|
473
|
+
status: "failed",
|
|
474
|
+
});
|
|
373
475
|
throw new CheckoutConflictError("This checkout operation is no longer active; start a new checkout with a new operation key");
|
|
374
476
|
}
|
|
375
477
|
}
|
|
@@ -388,10 +490,12 @@ export class CommerceService {
|
|
|
388
490
|
returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
|
|
389
491
|
cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
|
|
390
492
|
metadata: { ...metadata, checkout_intent_id: intent.id },
|
|
391
|
-
idempotencyKey:
|
|
493
|
+
idempotencyKey: `bursar:checkout:${intent.id}`,
|
|
392
494
|
};
|
|
393
|
-
if (
|
|
394
|
-
checkoutParams.
|
|
495
|
+
if (resolved.offer.type === "subscription" && resolved.offer.trial)
|
|
496
|
+
checkoutParams.trial = resolved.offer.trial;
|
|
497
|
+
if (intent.providerCustomerId)
|
|
498
|
+
checkoutParams.customerId = intent.providerCustomerId;
|
|
395
499
|
if (input.email)
|
|
396
500
|
checkoutParams.email = input.email;
|
|
397
501
|
const session = await provider.createCheckoutSession(checkoutParams);
|
|
@@ -441,7 +545,10 @@ export class CommerceService {
|
|
|
441
545
|
if (!provider.cancelSubscription) {
|
|
442
546
|
throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
|
|
443
547
|
}
|
|
444
|
-
await provider.cancelSubscription(subscription.providerSubscriptionId, input.operationKey
|
|
548
|
+
await provider.cancelSubscription(subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "cancel-subscription", [
|
|
549
|
+
subscription.provider,
|
|
550
|
+
subscription.providerSubscriptionId,
|
|
551
|
+
]));
|
|
445
552
|
await this.billing.ingestBillingEvent({
|
|
446
553
|
provider: subscription.provider,
|
|
447
554
|
eventId: `cancel_${input.accountId}_${input.operationKey}`,
|
|
@@ -470,7 +577,10 @@ export class CommerceService {
|
|
|
470
577
|
if (!provider.reactivateSubscription) {
|
|
471
578
|
throw new ProviderCapabilityNotSupportedError(provider.provider, "reactivateSubscription");
|
|
472
579
|
}
|
|
473
|
-
await provider.reactivateSubscription(subscription.providerSubscriptionId, input.operationKey
|
|
580
|
+
await provider.reactivateSubscription(subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "reactivate-subscription", [
|
|
581
|
+
subscription.provider,
|
|
582
|
+
subscription.providerSubscriptionId,
|
|
583
|
+
]));
|
|
474
584
|
await this.billing.ingestBillingEvent({
|
|
475
585
|
provider: subscription.provider,
|
|
476
586
|
eventId: `reactivate_${input.accountId}_${input.operationKey}`,
|
|
@@ -544,15 +654,20 @@ export class CommerceService {
|
|
|
544
654
|
const interval = pending.toOffer.interval;
|
|
545
655
|
if (!planKey ||
|
|
546
656
|
!config.plans[planKey] ||
|
|
547
|
-
(interval !== "
|
|
657
|
+
(interval !== "day" &&
|
|
658
|
+
interval !== "week" &&
|
|
659
|
+
interval !== "month" &&
|
|
660
|
+
interval !== "year") ||
|
|
548
661
|
!pending.effectiveAt) {
|
|
549
662
|
throw new CoreBillingDataUnavailableError("Pending subscription change has incomplete catalog context");
|
|
550
663
|
}
|
|
551
664
|
pendingChange = {
|
|
552
665
|
planKey,
|
|
553
666
|
interval,
|
|
667
|
+
intervalCount: pending.toOffer.intervalCount,
|
|
554
668
|
effectiveAt: pending.effectiveAt,
|
|
555
|
-
scheduled: pending.effective === "renewal",
|
|
669
|
+
scheduled: pending.effective === "renewal" && pending.errorMessage !== "provider_outcome_unknown",
|
|
670
|
+
providerOutcomeUnknown: pending.errorMessage === "provider_outcome_unknown",
|
|
556
671
|
providerOperationId: pending.providerOperationId ?? null,
|
|
557
672
|
};
|
|
558
673
|
}
|
|
@@ -608,6 +723,11 @@ export class CommerceService {
|
|
|
608
723
|
}
|
|
609
724
|
if (resolved.offer.type !== "subscription")
|
|
610
725
|
throw new UnknownOfferError();
|
|
726
|
+
assertTrustedRegion(input.region);
|
|
727
|
+
const region = input.region;
|
|
728
|
+
if (!offerIsAvailable(resolved.offer.availability, region)) {
|
|
729
|
+
throw new UnknownOfferError("Target offer is outside its availability");
|
|
730
|
+
}
|
|
611
731
|
const provider = await this.providers.select({
|
|
612
732
|
requested: subscription.provider,
|
|
613
733
|
current: subscription.provider,
|
|
@@ -617,24 +737,30 @@ export class CommerceService {
|
|
|
617
737
|
if (!reference)
|
|
618
738
|
throw new UnknownOfferError("Target offer is unavailable from the provider");
|
|
619
739
|
const persistedOffer = reference.type === "stripe_price"
|
|
620
|
-
? await this.billing.resolveOffer(provider.provider, null, reference.
|
|
740
|
+
? await this.billing.resolveOffer(provider.provider, null, externalId(reference, this.options.providerEnvironment))
|
|
621
741
|
: reference.type === "dodo_product"
|
|
622
|
-
? await this.billing.resolveOffer(provider.provider, reference.
|
|
623
|
-
: await this.billing.resolveOfferByLookup(provider.provider, reference.
|
|
742
|
+
? await this.billing.resolveOffer(provider.provider, externalId(reference, this.options.providerEnvironment), null)
|
|
743
|
+
: await this.billing.resolveOfferByLookup(provider.provider, externalId(reference, this.options.providerEnvironment));
|
|
624
744
|
if (!persistedOffer) {
|
|
625
745
|
throw new CommerceResourceNotFoundError("Target offer is not present in persisted billing state");
|
|
626
746
|
}
|
|
747
|
+
if (persistedOffer.offerKey !== input.offerKey) {
|
|
748
|
+
throw new CoreBillingDataUnavailableError("Target provider reference resolves to a different offer");
|
|
749
|
+
}
|
|
750
|
+
if (!subscription.offerKey) {
|
|
751
|
+
throw new CoreBillingDataUnavailableError("Current subscription offer is unknown");
|
|
752
|
+
}
|
|
627
753
|
const currentPlan = entitlement.planKey ?? subscription.plan;
|
|
628
754
|
if (!currentPlan) {
|
|
629
755
|
throw new CommerceResourceNotFoundError("Current subscription plan is unknown");
|
|
630
756
|
}
|
|
631
|
-
const { classification, targetInterval, policy } = classifySubscriptionChange(resolved.config, currentPlan, subscription.interval, resolved.offer);
|
|
757
|
+
const { classification, targetInterval, policy } = classifySubscriptionChange(resolved.config, currentPlan, subscription.interval, resolved.offer, subscription.intervalCount, subscription.offerKey === persistedOffer.offerKey);
|
|
632
758
|
return {
|
|
633
759
|
subscription,
|
|
634
760
|
provider,
|
|
635
761
|
targetOfferId: persistedOffer.offerId,
|
|
636
762
|
targetOffer: resolved.offer,
|
|
637
|
-
targetProductId: externalId(reference),
|
|
763
|
+
targetProductId: externalId(reference, this.options.providerEnvironment),
|
|
638
764
|
targetInterval,
|
|
639
765
|
classification,
|
|
640
766
|
policy,
|
|
@@ -660,6 +786,7 @@ export class CommerceService {
|
|
|
660
786
|
scheduled: false,
|
|
661
787
|
planId: context.targetOffer.plan,
|
|
662
788
|
interval: context.targetInterval,
|
|
789
|
+
intervalCount: context.targetOffer.billingInterval.count,
|
|
663
790
|
};
|
|
664
791
|
}
|
|
665
792
|
const preview = await this.refreshPlanPreview(context);
|
|
@@ -669,12 +796,42 @@ export class CommerceService {
|
|
|
669
796
|
scheduled: context.policy.effective === "renewal",
|
|
670
797
|
planId: context.targetOffer.plan,
|
|
671
798
|
interval: context.targetInterval,
|
|
799
|
+
intervalCount: context.targetOffer.billingInterval.count,
|
|
672
800
|
preview,
|
|
673
801
|
quoteFingerprint: quoteFingerprint(preview),
|
|
674
802
|
};
|
|
675
803
|
}
|
|
804
|
+
replayPlanChange(change, input) {
|
|
805
|
+
if (change.toOffer.offerKey !== input.offerKey ||
|
|
806
|
+
(change.region ?? null) !== (input.region?.trim().toUpperCase() ?? null) ||
|
|
807
|
+
change.quoteFingerprint !== input.quoteFingerprint) {
|
|
808
|
+
throw new CheckoutConflictError("Plan change operation key was reused with different parameters");
|
|
809
|
+
}
|
|
810
|
+
if (change.state === "failed" || change.state === "canceled") {
|
|
811
|
+
throw new CheckoutConflictError("Plan change operation is terminal; use a new operation key");
|
|
812
|
+
}
|
|
813
|
+
const applied = change.state === "applied";
|
|
814
|
+
const unknown = !applied && change.errorMessage === "provider_outcome_unknown";
|
|
815
|
+
return {
|
|
816
|
+
success: true,
|
|
817
|
+
pending: !applied,
|
|
818
|
+
unchanged: applied,
|
|
819
|
+
scheduled: !applied && change.effective === "renewal" && !unknown,
|
|
820
|
+
providerOutcomeUnknown: unknown,
|
|
821
|
+
effectiveAt: change.effectiveAt ?? undefined,
|
|
822
|
+
planId: change.toOffer.plan,
|
|
823
|
+
interval: change.toOffer.interval,
|
|
824
|
+
intervalCount: change.toOffer.intervalCount,
|
|
825
|
+
};
|
|
826
|
+
}
|
|
676
827
|
async confirmPlanChange(input) {
|
|
677
828
|
requireStableKey(input.operationKey, "operationKey");
|
|
829
|
+
const subscription = await this.billing.getActiveSubscription(input.accountId);
|
|
830
|
+
if (subscription) {
|
|
831
|
+
const prior = await this.billing.findBillingSubscriptionChange(subscription.provider, subscription.providerSubscriptionId, input.operationKey);
|
|
832
|
+
if (prior)
|
|
833
|
+
return this.replayPlanChange(prior, input);
|
|
834
|
+
}
|
|
678
835
|
const context = await this.planChangeContext(input);
|
|
679
836
|
if (context.classification === "unchanged") {
|
|
680
837
|
return {
|
|
@@ -682,8 +839,16 @@ export class CommerceService {
|
|
|
682
839
|
unchanged: true,
|
|
683
840
|
planId: context.targetOffer.plan,
|
|
684
841
|
interval: context.targetInterval,
|
|
842
|
+
intervalCount: context.targetOffer.billingInterval.count,
|
|
685
843
|
};
|
|
686
844
|
}
|
|
845
|
+
const existing = await this.billing.getOpenBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId);
|
|
846
|
+
if (existing) {
|
|
847
|
+
if (existing.idempotencyKey === input.operationKey) {
|
|
848
|
+
return this.replayPlanChange(existing, input);
|
|
849
|
+
}
|
|
850
|
+
throw new CheckoutConflictError("A plan change is already awaiting reconciliation");
|
|
851
|
+
}
|
|
687
852
|
const preview = await this.refreshPlanPreview(context);
|
|
688
853
|
const fingerprint = quoteFingerprint(preview);
|
|
689
854
|
const refreshed = {
|
|
@@ -692,6 +857,7 @@ export class CommerceService {
|
|
|
692
857
|
scheduled: context.policy.effective === "renewal",
|
|
693
858
|
planId: context.targetOffer.plan,
|
|
694
859
|
interval: context.targetInterval,
|
|
860
|
+
intervalCount: context.targetOffer.billingInterval.count,
|
|
695
861
|
preview,
|
|
696
862
|
quoteFingerprint: fingerprint,
|
|
697
863
|
};
|
|
@@ -701,28 +867,37 @@ export class CommerceService {
|
|
|
701
867
|
if (!context.provider.changePlan) {
|
|
702
868
|
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "changePlan");
|
|
703
869
|
}
|
|
704
|
-
const existing = await this.billing.getOpenBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId);
|
|
705
|
-
if (existing?.state === "scheduled" && existing.effective === "renewal") {
|
|
706
|
-
throw new CheckoutConflictError("Cancel the existing plan change before choosing another plan");
|
|
707
|
-
}
|
|
708
|
-
else if (existing) {
|
|
709
|
-
throw new CheckoutConflictError("A plan change is already awaiting payment");
|
|
710
|
-
}
|
|
711
870
|
const scheduled = context.policy.effective === "renewal";
|
|
712
871
|
const effectiveAt = scheduled ? preview.nextBillingDate : preview.effectiveAt;
|
|
713
872
|
if (!effectiveAt) {
|
|
714
873
|
throw new CoreBillingDataUnavailableError("The provider did not return the scheduled change date");
|
|
715
874
|
}
|
|
716
|
-
const
|
|
875
|
+
const changeInput = {
|
|
717
876
|
provider: context.subscription.provider,
|
|
718
877
|
providerSubscriptionId: context.subscription.providerSubscriptionId,
|
|
719
878
|
toOfferId: context.targetOfferId,
|
|
720
879
|
effectiveAt,
|
|
721
880
|
effective: context.policy.effective,
|
|
722
881
|
idempotencyKey: input.operationKey,
|
|
882
|
+
quoteFingerprint: input.quoteFingerprint,
|
|
723
883
|
prorationBehavior: context.policy.proration === "none" ? "none" : "invoice_immediately",
|
|
724
|
-
}
|
|
884
|
+
};
|
|
885
|
+
if (input.region !== undefined)
|
|
886
|
+
changeInput.region = input.region;
|
|
887
|
+
const change = await this.billing.createBillingSubscriptionChange(changeInput);
|
|
888
|
+
if (change.created === false)
|
|
889
|
+
return this.replayPlanChange(change, input);
|
|
890
|
+
if (change.created !== true)
|
|
891
|
+
throw new StoreError("Plan change creation did not establish ownership", {
|
|
892
|
+
indeterminate: true,
|
|
893
|
+
});
|
|
894
|
+
const providerChangeKey = scopedStableKey(change.id, "plan-change", [
|
|
895
|
+
context.subscription.provider,
|
|
896
|
+
context.subscription.providerSubscriptionId,
|
|
897
|
+
]);
|
|
725
898
|
let cancellationWasReactivated = false;
|
|
899
|
+
let providerOperationId = null;
|
|
900
|
+
let providerMutationStarted = false;
|
|
726
901
|
try {
|
|
727
902
|
if (context.subscription.cancelAtPeriodEnd) {
|
|
728
903
|
if (!context.provider.reactivateSubscription) {
|
|
@@ -731,9 +906,11 @@ export class CommerceService {
|
|
|
731
906
|
if (!context.provider.cancelSubscription) {
|
|
732
907
|
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "cancelSubscription");
|
|
733
908
|
}
|
|
734
|
-
|
|
909
|
+
providerMutationStarted = true;
|
|
910
|
+
await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, scopedStableKey(providerChangeKey, "keep"));
|
|
735
911
|
cancellationWasReactivated = true;
|
|
736
912
|
}
|
|
913
|
+
providerMutationStarted = true;
|
|
737
914
|
const result = await context.provider.changePlan({
|
|
738
915
|
providerSubscriptionId: context.subscription.providerSubscriptionId,
|
|
739
916
|
productId: context.targetProductId,
|
|
@@ -744,20 +921,52 @@ export class CommerceService {
|
|
|
744
921
|
plan_slug: context.targetOffer.plan,
|
|
745
922
|
billing_interval: context.targetInterval,
|
|
746
923
|
},
|
|
747
|
-
idempotencyKey:
|
|
748
|
-
});
|
|
749
|
-
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
750
|
-
providerOperationId: result && "providerOperationId" in result ? (result.providerOperationId ?? null) : null,
|
|
924
|
+
idempotencyKey: providerChangeKey,
|
|
751
925
|
});
|
|
926
|
+
providerOperationId =
|
|
927
|
+
result && "providerOperationId" in result ? (result.providerOperationId ?? null) : null;
|
|
752
928
|
}
|
|
753
929
|
catch (error) {
|
|
754
|
-
|
|
930
|
+
const settled = await this.billing.findBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId, input.operationKey);
|
|
931
|
+
if (settled?.state === "applied")
|
|
932
|
+
return this.replayPlanChange(settled, input);
|
|
933
|
+
if (error instanceof ProviderOperationOutcomeUnknownError) {
|
|
934
|
+
try {
|
|
935
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
936
|
+
state: scheduled ? "scheduled" : "awaiting_payment",
|
|
937
|
+
providerOperationId: error.providerOperationId,
|
|
938
|
+
errorMessage: "provider_outcome_unknown",
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
catch {
|
|
942
|
+
// A verified webhook may have settled the change concurrently.
|
|
943
|
+
}
|
|
944
|
+
throw error;
|
|
945
|
+
}
|
|
946
|
+
if (providerMutationStarted && !isDefinitiveProviderRejection(error)) {
|
|
947
|
+
// A webhook may already have settled the receipt. Never regress it.
|
|
948
|
+
try {
|
|
949
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
950
|
+
state: scheduled ? "scheduled" : "awaiting_payment",
|
|
951
|
+
errorMessage: "provider_outcome_unknown",
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
catch {
|
|
955
|
+
// Preserve the provider error; the original receipt remains the fence.
|
|
956
|
+
}
|
|
957
|
+
throw error;
|
|
958
|
+
}
|
|
959
|
+
const failure = error;
|
|
755
960
|
if (cancellationWasReactivated) {
|
|
756
961
|
try {
|
|
757
|
-
await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, scopedStableKey(
|
|
962
|
+
await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, scopedStableKey(providerChangeKey, "restore-cancellation"));
|
|
758
963
|
}
|
|
759
964
|
catch (compensationError) {
|
|
760
|
-
|
|
965
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
966
|
+
state: scheduled ? "scheduled" : "awaiting_payment",
|
|
967
|
+
errorMessage: "provider_outcome_unknown",
|
|
968
|
+
});
|
|
969
|
+
throw new AggregateError([error, compensationError], "Plan change failed and the original subscription cancellation could not be restored");
|
|
761
970
|
}
|
|
762
971
|
}
|
|
763
972
|
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
@@ -766,6 +975,20 @@ export class CommerceService {
|
|
|
766
975
|
});
|
|
767
976
|
throw failure;
|
|
768
977
|
}
|
|
978
|
+
// A local write failure after provider acceptance must leave the change
|
|
979
|
+
// open for webhook reconciliation rather than restoring cancellation.
|
|
980
|
+
try {
|
|
981
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
982
|
+
state: scheduled ? "scheduled" : "awaiting_payment",
|
|
983
|
+
providerOperationId,
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
catch (error) {
|
|
987
|
+
const settled = await this.billing.findBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId, input.operationKey);
|
|
988
|
+
if (settled?.state === "applied")
|
|
989
|
+
return this.replayPlanChange(settled, input);
|
|
990
|
+
throw error;
|
|
991
|
+
}
|
|
769
992
|
return {
|
|
770
993
|
success: true,
|
|
771
994
|
pending: true,
|
|
@@ -773,6 +996,7 @@ export class CommerceService {
|
|
|
773
996
|
effectiveAt,
|
|
774
997
|
planId: context.targetOffer.plan,
|
|
775
998
|
interval: context.targetInterval,
|
|
999
|
+
intervalCount: context.targetOffer.billingInterval.count,
|
|
776
1000
|
};
|
|
777
1001
|
}
|
|
778
1002
|
async cancelScheduledPlanChange(input) {
|
|
@@ -788,8 +1012,10 @@ export class CommerceService {
|
|
|
788
1012
|
if (!provider.cancelScheduledPlanChange) {
|
|
789
1013
|
throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelScheduledPlanChange");
|
|
790
1014
|
}
|
|
791
|
-
await provider.cancelScheduledPlanChange(subscription.providerSubscriptionId, change.providerOperationId, input.operationKey);
|
|
792
|
-
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
1015
|
+
await provider.cancelScheduledPlanChange(subscription.providerSubscriptionId, change.providerOperationId, scopedStableKey(input.operationKey, "cancel-plan-change", [subscription.provider, change.id]));
|
|
1016
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
1017
|
+
state: "canceled",
|
|
1018
|
+
});
|
|
793
1019
|
return { success: true };
|
|
794
1020
|
}
|
|
795
1021
|
async createPortalSession(input) {
|
|
@@ -837,7 +1063,10 @@ export class CommerceService {
|
|
|
837
1063
|
}
|
|
838
1064
|
async updatePreferences(input) {
|
|
839
1065
|
const current = await this.billing.getUserPreferences(input.accountId);
|
|
840
|
-
const next = {
|
|
1066
|
+
const next = {
|
|
1067
|
+
...this.preferences(input.accountId, current),
|
|
1068
|
+
...input.patch,
|
|
1069
|
+
};
|
|
841
1070
|
await this.billing.updateUserPreferences(next);
|
|
842
1071
|
return next;
|
|
843
1072
|
}
|
|
@@ -893,14 +1122,17 @@ export class CommerceService {
|
|
|
893
1122
|
const subscriptionSummary = this.accountSubscriptionSummary(accountId, core.subscription, core.entitlement, core.config, pendingChange);
|
|
894
1123
|
const [transactionsResult, usageResult, invoicesResult] = await Promise.allSettled([
|
|
895
1124
|
this.credits.listLedgerEntries(accountId, { limit: 50 }),
|
|
896
|
-
this.credits.listUsageCharges(accountId, {
|
|
897
|
-
|
|
1125
|
+
this.credits.listUsageCharges(accountId, {
|
|
1126
|
+
limit: 100,
|
|
1127
|
+
includeRecordOnly: false,
|
|
1128
|
+
}),
|
|
1129
|
+
this.billing.listBillingInvoices(accountId, { limit: 100 }),
|
|
898
1130
|
]);
|
|
899
1131
|
const transactions = transactionsResult.status === "fulfilled"
|
|
900
1132
|
? transactionsResult.value.items.filter((entry) => entry.entryType !== "usage")
|
|
901
1133
|
: [];
|
|
902
1134
|
const usage = usageResult.status === "fulfilled" ? usageResult.value.items : [];
|
|
903
|
-
const invoices = invoicesResult.status === "fulfilled" ? invoicesResult.value : [];
|
|
1135
|
+
const invoices = invoicesResult.status === "fulfilled" ? invoicesResult.value.items : [];
|
|
904
1136
|
const documents = [
|
|
905
1137
|
...invoices.flatMap((invoice) => {
|
|
906
1138
|
return [
|
|
@@ -1028,15 +1260,18 @@ export class CommerceService {
|
|
|
1028
1260
|
}
|
|
1029
1261
|
async getInvoiceLink(input) {
|
|
1030
1262
|
let providerName;
|
|
1031
|
-
let
|
|
1263
|
+
let providerInvoiceId = null;
|
|
1264
|
+
let payment = null;
|
|
1032
1265
|
if (input.document.kind === "provider_invoice") {
|
|
1033
1266
|
const document = input.document;
|
|
1034
|
-
const owned =
|
|
1035
|
-
invoice.providerInvoiceId === document.providerDocumentId);
|
|
1267
|
+
const owned = await this.billing.hasBillingInvoice(input.accountId, document.provider, document.providerDocumentId);
|
|
1036
1268
|
if (!owned)
|
|
1037
1269
|
throw new CommerceResourceNotFoundError("Invoice not found");
|
|
1038
1270
|
providerName = document.provider;
|
|
1039
|
-
|
|
1271
|
+
providerInvoiceId = document.providerDocumentId;
|
|
1272
|
+
if (document.provider === "dodo") {
|
|
1273
|
+
payment = await this.billing.getOwnedBillingPaymentDocument(input.accountId, document.provider, document.providerDocumentId, document.providerDocumentId, { requireInvoiceLink: true });
|
|
1274
|
+
}
|
|
1040
1275
|
}
|
|
1041
1276
|
else {
|
|
1042
1277
|
const entry = await this.credits.getLedgerEntry(input.accountId, input.document.ledgerEntryId);
|
|
@@ -1046,14 +1281,33 @@ export class CommerceService {
|
|
|
1046
1281
|
if (!owned?.provider || !owned.providerDocumentId) {
|
|
1047
1282
|
throw new CommerceResourceNotFoundError("No provider document is associated with the ledger entry");
|
|
1048
1283
|
}
|
|
1284
|
+
const metadataPaymentId = z
|
|
1285
|
+
.string()
|
|
1286
|
+
.min(1)
|
|
1287
|
+
.safeParse(entry.metadata?.provider_payment_id).data;
|
|
1288
|
+
const paymentId = metadataPaymentId ?? owned.providerDocumentId;
|
|
1289
|
+
const invoiceOwned = await this.billing.hasBillingInvoice(input.accountId, owned.provider, owned.providerDocumentId);
|
|
1290
|
+
if (invoiceOwned && owned.provider === "dodo") {
|
|
1291
|
+
payment = await this.billing.getOwnedBillingPaymentDocument(input.accountId, owned.provider, paymentId, owned.providerDocumentId, { requireInvoiceLink: true });
|
|
1292
|
+
}
|
|
1293
|
+
else if (!invoiceOwned || metadataPaymentId) {
|
|
1294
|
+
payment = await this.billing.getOwnedBillingPaymentDocument(input.accountId, owned.provider, paymentId, owned.providerDocumentId);
|
|
1295
|
+
}
|
|
1296
|
+
if (!invoiceOwned && !payment)
|
|
1297
|
+
throw new CommerceResourceNotFoundError("Invoice not found");
|
|
1049
1298
|
providerName = owned.provider;
|
|
1050
|
-
|
|
1299
|
+
providerInvoiceId = invoiceOwned
|
|
1300
|
+
? owned.providerDocumentId
|
|
1301
|
+
: (payment?.providerInvoiceId ?? null);
|
|
1051
1302
|
}
|
|
1052
1303
|
const provider = await this.providers.get(providerName);
|
|
1053
1304
|
if (!provider.getInvoiceUrl) {
|
|
1054
1305
|
throw new ProviderCapabilityNotSupportedError(provider.provider, "getInvoiceUrl");
|
|
1055
1306
|
}
|
|
1056
|
-
const result = await provider.getInvoiceUrl(
|
|
1307
|
+
const result = await provider.getInvoiceUrl({
|
|
1308
|
+
providerInvoiceId,
|
|
1309
|
+
providerPaymentId: payment?.providerPaymentId ?? null,
|
|
1310
|
+
});
|
|
1057
1311
|
if (!result)
|
|
1058
1312
|
throw new CommerceResourceNotFoundError("No invoice URL is available");
|
|
1059
1313
|
return result;
|