@zonastery/bursar 0.0.1 → 1.0.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 +85 -344
- package/dist/billing/auto-recharge-port.d.ts +27 -0
- package/dist/billing/auto-recharge-port.d.ts.map +1 -0
- package/dist/billing/auto-recharge-port.js +2 -0
- package/dist/billing/auto-recharge-port.js.map +1 -0
- package/dist/billing/auto-recharge-service.d.ts +43 -0
- package/dist/billing/auto-recharge-service.d.ts.map +1 -0
- package/dist/billing/auto-recharge-service.js +218 -0
- package/dist/billing/auto-recharge-service.js.map +1 -0
- package/dist/billing/billing-service.d.ts +71 -0
- package/dist/billing/billing-service.d.ts.map +1 -0
- package/dist/billing/billing-service.js +172 -0
- package/dist/billing/billing-service.js.map +1 -0
- package/dist/billing/billing-store.d.ts +59 -0
- package/dist/billing/billing-store.d.ts.map +1 -0
- package/dist/billing/billing-store.js +9 -0
- package/dist/billing/billing-store.js.map +1 -0
- package/dist/billing/contracts.d.ts +149 -0
- package/dist/billing/contracts.d.ts.map +1 -0
- package/dist/billing/contracts.js +2 -0
- package/dist/billing/contracts.js.map +1 -0
- package/dist/billing/event-handlers.d.ts +57 -0
- package/dist/billing/event-handlers.d.ts.map +1 -0
- package/dist/billing/event-handlers.js +667 -0
- package/dist/billing/event-handlers.js.map +1 -0
- package/dist/billing/event-processor.d.ts +19 -0
- package/dist/billing/event-processor.d.ts.map +1 -0
- package/dist/billing/event-processor.js +105 -0
- package/dist/billing/event-processor.js.map +1 -0
- package/dist/billing/financial-event-handlers.d.ts +26 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -0
- package/dist/billing/financial-event-handlers.js +241 -0
- package/dist/billing/financial-event-handlers.js.map +1 -0
- package/dist/billing/index.d.ts +10 -0
- package/dist/billing/index.d.ts.map +1 -0
- package/dist/billing/index.js +6 -0
- package/dist/billing/index.js.map +1 -0
- package/dist/billing/management.d.ts +59 -0
- package/dist/billing/management.d.ts.map +1 -0
- package/dist/billing/management.js +113 -0
- package/dist/billing/management.js.map +1 -0
- package/dist/billing/policy-window.d.ts +24 -0
- package/dist/billing/policy-window.d.ts.map +1 -0
- package/dist/billing/policy-window.js +88 -0
- package/dist/billing/policy-window.js.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/auto-recharge.js +178 -0
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
- package/dist/billing/postgres/repositories/customer.d.ts +12 -0
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/customer.js +33 -0
- package/dist/billing/postgres/repositories/customer.js.map +1 -0
- package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/dispute.js +18 -0
- package/dist/billing/postgres/repositories/dispute.js.map +1 -0
- package/dist/billing/postgres/repositories/event.d.ts +21 -0
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/event.js +47 -0
- package/dist/billing/postgres/repositories/event.js.map +1 -0
- package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/invoice.js +36 -0
- package/dist/billing/postgres/repositories/invoice.js.map +1 -0
- package/dist/billing/postgres/repositories/offer.d.ts +26 -0
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/offer.js +73 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -0
- package/dist/billing/postgres/repositories/payment.d.ts +32 -0
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/payment.js +78 -0
- package/dist/billing/postgres/repositories/payment.js.map +1 -0
- package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/preferences.js +23 -0
- package/dist/billing/postgres/repositories/preferences.js.map +1 -0
- package/dist/billing/postgres/repositories/refund.d.ts +7 -0
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/refund.js +32 -0
- package/dist/billing/postgres/repositories/refund.js.map +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/subscription.js +187 -0
- package/dist/billing/postgres/repositories/subscription.js.map +1 -0
- package/dist/billing/postgres/repositories/topup.d.ts +27 -0
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/topup.js +51 -0
- package/dist/billing/postgres/repositories/topup.js.map +1 -0
- package/dist/billing/postgres/store.d.ts +87 -0
- package/dist/billing/postgres/store.d.ts.map +1 -0
- package/dist/billing/postgres/store.js +527 -0
- package/dist/billing/postgres/store.js.map +1 -0
- package/dist/billing/service-types.d.ts +37 -0
- package/dist/billing/service-types.d.ts.map +1 -0
- package/dist/billing/service-types.js +2 -0
- package/dist/billing/service-types.js.map +1 -0
- package/dist/billing/types/auto-recharge.d.ts +56 -0
- package/dist/billing/types/auto-recharge.d.ts.map +1 -0
- package/dist/billing/types/auto-recharge.js +2 -0
- package/dist/billing/types/auto-recharge.js.map +1 -0
- package/dist/billing/types/catalog.d.ts +47 -0
- package/dist/billing/types/catalog.d.ts.map +1 -0
- package/dist/billing/types/catalog.js +2 -0
- package/dist/billing/types/catalog.js.map +1 -0
- package/dist/billing/types/common.d.ts +16 -0
- package/dist/billing/types/common.d.ts.map +1 -0
- package/dist/billing/types/common.js +2 -0
- package/dist/billing/types/common.js.map +1 -0
- package/dist/billing/types/documents.d.ts +39 -0
- package/dist/billing/types/documents.d.ts.map +1 -0
- package/dist/billing/types/documents.js +2 -0
- package/dist/billing/types/documents.js.map +1 -0
- package/dist/billing/types/events.d.ts +75 -0
- package/dist/billing/types/events.d.ts.map +1 -0
- package/dist/billing/types/events.js +38 -0
- package/dist/billing/types/events.js.map +1 -0
- package/dist/billing/types/index.d.ts +8 -0
- package/dist/billing/types/index.d.ts.map +1 -0
- package/dist/billing/types/index.js +8 -0
- package/dist/billing/types/index.js.map +1 -0
- package/dist/billing/types/preferences.d.ts +13 -0
- package/dist/billing/types/preferences.d.ts.map +1 -0
- package/dist/billing/types/preferences.js +2 -0
- package/dist/billing/types/preferences.js.map +1 -0
- package/dist/billing/types/subscriptions.d.ts +97 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -0
- package/dist/billing/types/subscriptions.js +12 -0
- package/dist/billing/types/subscriptions.js.map +1 -0
- package/dist/breakdown.d.ts +3 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +4 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/browser.d.ts +8 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +7 -0
- package/dist/browser.js.map +1 -0
- package/dist/bursar.d.ts +80 -0
- package/dist/bursar.d.ts.map +1 -0
- package/dist/bursar.js +129 -0
- package/dist/bursar.js.map +1 -0
- package/dist/catalog.d.ts +61 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +95 -0
- package/dist/catalog.js.map +1 -0
- package/dist/commerce/errors.d.ts +69 -0
- package/dist/commerce/errors.d.ts.map +1 -0
- package/dist/commerce/errors.js +107 -0
- package/dist/commerce/errors.js.map +1 -0
- package/dist/commerce/index.d.ts +6 -0
- package/dist/commerce/index.d.ts.map +1 -0
- package/dist/commerce/index.js +6 -0
- package/dist/commerce/index.js.map +1 -0
- package/dist/commerce/plan-change.d.ts +10 -0
- package/dist/commerce/plan-change.d.ts.map +1 -0
- package/dist/commerce/plan-change.js +42 -0
- package/dist/commerce/plan-change.js.map +1 -0
- package/dist/commerce/provider-registry.d.ts +18 -0
- package/dist/commerce/provider-registry.d.ts.map +1 -0
- package/dist/commerce/provider-registry.js +70 -0
- package/dist/commerce/provider-registry.js.map +1 -0
- package/dist/commerce/service.d.ts +73 -0
- package/dist/commerce/service.d.ts.map +1 -0
- package/dist/commerce/service.js +981 -0
- package/dist/commerce/service.js.map +1 -0
- package/dist/commerce/types.d.ts +217 -0
- package/dist/commerce/types.d.ts.map +1 -0
- package/dist/commerce/types.js.map +1 -0
- package/dist/config/parse-access.d.ts +6 -0
- package/dist/config/parse-access.d.ts.map +1 -0
- package/dist/config/parse-access.js +72 -0
- package/dist/config/parse-access.js.map +1 -0
- package/dist/config/parse-commerce.d.ts +3 -0
- package/dist/config/parse-commerce.d.ts.map +1 -0
- package/dist/config/parse-commerce.js +236 -0
- package/dist/config/parse-commerce.js.map +1 -0
- package/dist/config/parse-credits.d.ts +3 -0
- package/dist/config/parse-credits.d.ts.map +1 -0
- package/dist/config/parse-credits.js +99 -0
- package/dist/config/parse-credits.js.map +1 -0
- package/dist/config/parse-plans.d.ts +5 -0
- package/dist/config/parse-plans.d.ts.map +1 -0
- package/dist/config/parse-plans.js +126 -0
- package/dist/config/parse-plans.js.map +1 -0
- package/dist/config/parse-pricing.d.ts +4 -0
- package/dist/config/parse-pricing.d.ts.map +1 -0
- package/dist/config/parse-pricing.js +252 -0
- package/dist/config/parse-pricing.js.map +1 -0
- package/dist/config/parse-utils.d.ts +18 -0
- package/dist/config/parse-utils.d.ts.map +1 -0
- package/dist/config/parse-utils.js +118 -0
- package/dist/config/parse-utils.js.map +1 -0
- package/dist/config/types.d.ts +327 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/types.js +2 -0
- package/dist/config/types.js.map +1 -0
- package/dist/config.d.ts +6 -22
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +82 -263
- package/dist/config.js.map +1 -1
- package/dist/{stores → credits}/events.d.ts +6 -6
- package/dist/credits/events.d.ts.map +1 -0
- package/dist/{stores → credits}/events.js +5 -5
- package/dist/credits/events.js.map +1 -0
- package/dist/credits/lease-workflow.d.ts +90 -0
- package/dist/credits/lease-workflow.d.ts.map +1 -0
- package/dist/credits/lease-workflow.js +378 -0
- package/dist/credits/lease-workflow.js.map +1 -0
- package/dist/credits/low-balance-monitor.d.ts +26 -0
- package/dist/credits/low-balance-monitor.d.ts.map +1 -0
- package/dist/credits/low-balance-monitor.js +110 -0
- package/dist/credits/low-balance-monitor.js.map +1 -0
- package/dist/credits/postgres/repositories/analytics.d.ts +77 -0
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/analytics.js +151 -0
- package/dist/credits/postgres/repositories/analytics.js.map +1 -0
- package/dist/credits/postgres/repositories/balance.d.ts +66 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/balance.js +139 -0
- package/dist/credits/postgres/repositories/balance.js.map +1 -0
- package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/bucket.js +52 -0
- package/dist/credits/postgres/repositories/bucket.js.map +1 -0
- package/dist/credits/postgres/repositories/deduction.d.ts +55 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/deduction.js +130 -0
- package/dist/credits/postgres/repositories/deduction.js.map +1 -0
- package/dist/credits/postgres/repositories/lease.d.ts +69 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/lease.js +148 -0
- package/dist/credits/postgres/repositories/lease.js.map +1 -0
- package/dist/credits/postgres/repositories/plan.d.ts +105 -0
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/plan.js +182 -0
- package/dist/credits/postgres/repositories/plan.js.map +1 -0
- package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
- package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/pricing.js +70 -0
- package/dist/credits/postgres/repositories/pricing.js.map +1 -0
- package/dist/credits/postgres/repositories/team.d.ts +63 -0
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/team.js +120 -0
- package/dist/credits/postgres/repositories/team.js.map +1 -0
- package/dist/credits/postgres/store.d.ts +84 -0
- package/dist/credits/postgres/store.d.ts.map +1 -0
- package/dist/credits/postgres/store.js +765 -0
- package/dist/credits/postgres/store.js.map +1 -0
- package/dist/credits/postgres/value-mappers.d.ts +17 -0
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
- package/dist/credits/postgres/value-mappers.js +98 -0
- package/dist/credits/postgres/value-mappers.js.map +1 -0
- package/dist/credits/pricing-runtime.d.ts +34 -0
- package/dist/credits/pricing-runtime.d.ts.map +1 -0
- package/dist/credits/pricing-runtime.js +141 -0
- package/dist/credits/pricing-runtime.js.map +1 -0
- package/dist/credits/queries.d.ts +33 -0
- package/dist/credits/queries.d.ts.map +1 -0
- package/dist/credits/queries.js +71 -0
- package/dist/credits/queries.js.map +1 -0
- package/dist/credits/service-errors.d.ts +4 -0
- package/dist/credits/service-errors.d.ts.map +1 -0
- package/dist/credits/service-errors.js +57 -0
- package/dist/credits/service-errors.js.map +1 -0
- package/dist/credits/service-types.d.ts +122 -0
- package/dist/credits/service-types.d.ts.map +1 -0
- package/dist/credits/service-types.js +2 -0
- package/dist/credits/service-types.js.map +1 -0
- package/dist/credits/service.d.ts +207 -0
- package/dist/credits/service.d.ts.map +1 -0
- package/dist/credits/service.js +594 -0
- package/dist/credits/service.js.map +1 -0
- package/dist/{stores/credit-store.d.ts → credits/store.d.ts} +67 -71
- package/dist/credits/store.d.ts.map +1 -0
- package/dist/{stores/credit-store.js → credits/store.js} +30 -6
- package/dist/credits/store.js.map +1 -0
- package/dist/credits/types/account.d.ts +82 -0
- package/dist/credits/types/account.d.ts.map +1 -0
- package/dist/credits/types/account.js +2 -0
- package/dist/credits/types/account.js.map +1 -0
- package/dist/credits/types/admission.d.ts +39 -0
- package/dist/credits/types/admission.d.ts.map +1 -0
- package/dist/credits/types/admission.js +2 -0
- package/dist/credits/types/admission.js.map +1 -0
- package/dist/credits/types/analytics.d.ts +52 -0
- package/dist/credits/types/analytics.d.ts.map +1 -0
- package/dist/credits/types/analytics.js +2 -0
- package/dist/credits/types/analytics.js.map +1 -0
- package/dist/credits/types/catalog.d.ts +69 -0
- package/dist/credits/types/catalog.d.ts.map +1 -0
- package/dist/credits/types/catalog.js +2 -0
- package/dist/credits/types/catalog.js.map +1 -0
- package/dist/credits/types/grants.d.ts +24 -0
- package/dist/credits/types/grants.d.ts.map +1 -0
- package/dist/credits/types/grants.js +2 -0
- package/dist/credits/types/grants.js.map +1 -0
- package/dist/credits/types/index.d.ts +9 -0
- package/dist/credits/types/index.d.ts.map +1 -0
- package/dist/credits/types/index.js +2 -0
- package/dist/credits/types/index.js.map +1 -0
- package/dist/credits/types/ledger.d.ts +77 -0
- package/dist/credits/types/ledger.d.ts.map +1 -0
- package/dist/credits/types/ledger.js +2 -0
- package/dist/credits/types/ledger.js.map +1 -0
- package/dist/credits/types/quotas.d.ts +40 -0
- package/dist/credits/types/quotas.d.ts.map +1 -0
- package/dist/credits/types/quotas.js +2 -0
- package/dist/credits/types/quotas.js.map +1 -0
- package/dist/credits/types/teams.d.ts +44 -0
- package/dist/credits/types/teams.d.ts.map +1 -0
- package/dist/credits/types/teams.js +2 -0
- package/dist/credits/types/teams.js.map +1 -0
- package/dist/engine.d.ts +18 -39
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +169 -145
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +84 -25
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +117 -24
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts +46 -0
- package/dist/expr/ast.d.ts.map +1 -0
- package/dist/expr/ast.js +18 -0
- package/dist/expr/ast.js.map +1 -0
- package/dist/expr/evaluator.d.ts +4 -0
- package/dist/expr/evaluator.d.ts.map +1 -0
- package/dist/expr/evaluator.js +144 -0
- package/dist/expr/evaluator.js.map +1 -0
- package/dist/expr/language.d.ts +5 -0
- package/dist/expr/language.d.ts.map +1 -0
- package/dist/expr/language.js +73 -0
- package/dist/expr/language.js.map +1 -0
- package/dist/expr/parser.d.ts +24 -0
- package/dist/expr/parser.d.ts.map +1 -0
- package/dist/expr/parser.js +175 -0
- package/dist/expr/parser.js.map +1 -0
- package/dist/expr/tokenizer.d.ts +7 -0
- package/dist/expr/tokenizer.d.ts.map +1 -0
- package/dist/expr/tokenizer.js +85 -0
- package/dist/expr/tokenizer.js.map +1 -0
- package/dist/expr.d.ts +7 -58
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +41 -640
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +2764 -0
- package/dist/generated/pricing-config.types.d.ts +674 -0
- package/dist/generated/pricing-config.types.d.ts.map +1 -0
- package/dist/generated/pricing-config.types.js +8 -0
- package/dist/generated/pricing-config.types.js.map +1 -0
- package/dist/index.d.ts +21 -15
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -9
- package/dist/index.js.map +1 -1
- package/dist/load-pricing-file.d.ts.map +1 -1
- package/dist/load-pricing-file.js +61 -6
- package/dist/load-pricing-file.js.map +1 -1
- package/dist/metrics.d.ts +6 -16
- package/dist/metrics.d.ts.map +1 -1
- package/dist/node.d.ts +9 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +6 -2
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +9 -0
- package/dist/providers/_shared.d.ts.map +1 -0
- package/dist/providers/_shared.js +25 -0
- package/dist/providers/_shared.js.map +1 -0
- package/dist/providers/dodo/client-contract.d.ts +106 -0
- package/dist/providers/dodo/client-contract.d.ts.map +1 -0
- package/dist/providers/dodo/client-contract.js +2 -0
- package/dist/providers/dodo/client-contract.js.map +1 -0
- package/dist/providers/dodo/event-mapper.d.ts +6 -0
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -0
- package/dist/providers/dodo/event-mapper.js +344 -0
- package/dist/providers/dodo/event-mapper.js.map +1 -0
- package/dist/providers/dodo/index.d.ts +4 -0
- package/dist/providers/dodo/index.d.ts.map +1 -0
- package/dist/providers/dodo/index.js +3 -0
- package/dist/providers/dodo/index.js.map +1 -0
- package/dist/providers/dodo/provider.d.ts +53 -0
- package/dist/providers/dodo/provider.d.ts.map +1 -0
- package/dist/providers/dodo/provider.js +353 -0
- package/dist/providers/dodo/provider.js.map +1 -0
- package/dist/providers/index.d.ts +9 -0
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/index.js +7 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/providers/mock/index.d.ts +2 -0
- package/dist/providers/mock/index.d.ts.map +1 -0
- package/dist/providers/mock/index.js +2 -0
- package/dist/providers/mock/index.js.map +1 -0
- package/dist/providers/mock/provider.d.ts +41 -0
- package/dist/providers/mock/provider.d.ts.map +1 -0
- package/dist/providers/mock/provider.js +124 -0
- package/dist/providers/mock/provider.js.map +1 -0
- package/dist/providers/stripe/event-mapper.d.ts +7 -0
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -0
- package/dist/providers/stripe/event-mapper.js +342 -0
- package/dist/providers/stripe/event-mapper.js.map +1 -0
- package/dist/providers/stripe/index.d.ts +3 -0
- package/dist/providers/stripe/index.d.ts.map +1 -0
- package/dist/providers/stripe/index.js +3 -0
- package/dist/providers/stripe/index.js.map +1 -0
- package/dist/providers/stripe/provider.d.ts +48 -0
- package/dist/providers/stripe/provider.d.ts.map +1 -0
- package/dist/providers/stripe/provider.js +289 -0
- package/dist/providers/stripe/provider.js.map +1 -0
- package/dist/providers/types.d.ts +175 -0
- package/dist/providers/types.d.ts.map +1 -0
- package/dist/providers/types.js +18 -0
- package/dist/providers/types.js.map +1 -0
- package/dist/retry.d.ts +13 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +28 -0
- package/dist/retry.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -0
- package/dist/shared/logger.d.ts.map +1 -0
- package/dist/shared/logger.js +15 -0
- package/dist/shared/logger.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +51 -0
- package/dist/shared/postgres-client.d.ts.map +1 -0
- package/dist/shared/postgres-client.js +101 -0
- package/dist/shared/postgres-client.js.map +1 -0
- package/dist/shared/postgres-types.d.ts +7 -0
- package/dist/shared/postgres-types.d.ts.map +1 -0
- package/dist/shared/postgres-types.js +2 -0
- package/dist/shared/postgres-types.js.map +1 -0
- package/dist/shared/postgres-validation.d.ts +8 -0
- package/dist/shared/postgres-validation.d.ts.map +1 -0
- package/dist/shared/postgres-validation.js +40 -0
- package/dist/shared/postgres-validation.js.map +1 -0
- package/dist/storage/adapters/clickhouse.d.ts +61 -0
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
- package/dist/storage/adapters/clickhouse.js +329 -0
- package/dist/storage/adapters/clickhouse.js.map +1 -0
- package/dist/storage/adapters/s3.d.ts +35 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -0
- package/dist/storage/adapters/s3.js +100 -0
- package/dist/storage/adapters/s3.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +40 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -0
- package/dist/storage/outbox-worker.js +132 -0
- package/dist/storage/outbox-worker.js.map +1 -0
- package/dist/storage/ports.d.ts +77 -0
- package/dist/storage/ports.d.ts.map +1 -0
- package/dist/storage/ports.js +2 -0
- package/dist/storage/ports.js.map +1 -0
- package/dist/storage/postgres-repository.d.ts +14 -0
- package/dist/storage/postgres-repository.d.ts.map +1 -0
- package/dist/storage/postgres-repository.js +130 -0
- package/dist/storage/postgres-repository.js.map +1 -0
- package/dist/storage/runtime.d.ts +67 -0
- package/dist/storage/runtime.d.ts.map +1 -0
- package/dist/storage/runtime.js +313 -0
- package/dist/storage/runtime.js.map +1 -0
- package/package.json +70 -12
- package/dist/allowance.d.ts +0 -48
- package/dist/allowance.d.ts.map +0 -1
- package/dist/allowance.js +0 -140
- package/dist/allowance.js.map +0 -1
- package/dist/manager.d.ts +0 -421
- package/dist/manager.d.ts.map +0 -1
- package/dist/manager.js +0 -1112
- package/dist/manager.js.map +0 -1
- package/dist/stores/credit-store.d.ts.map +0 -1
- package/dist/stores/credit-store.js.map +0 -1
- package/dist/stores/events.d.ts.map +0 -1
- package/dist/stores/events.js.map +0 -1
- package/dist/stores/memory-store.d.ts +0 -178
- package/dist/stores/memory-store.d.ts.map +0 -1
- package/dist/stores/memory-store.js +0 -1833
- package/dist/stores/memory-store.js.map +0 -1
- package/dist/stores/postgres-store.d.ts +0 -95
- package/dist/stores/postgres-store.d.ts.map +0 -1
- package/dist/stores/postgres-store.js +0 -872
- package/dist/stores/postgres-store.js.map +0 -1
- package/dist/stores/supabase-store.d.ts +0 -76
- package/dist/stores/supabase-store.d.ts.map +0 -1
- package/dist/stores/supabase-store.js +0 -865
- package/dist/stores/supabase-store.js.map +0 -1
- package/dist/types.d.ts +0 -462
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- /package/dist/{types.js → commerce/types.js} +0 -0
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import Decimal from "decimal.js";
|
|
3
|
+
import { loadConfigFromDict } from "../config.js";
|
|
4
|
+
import { ConfigError } from "../errors.js";
|
|
5
|
+
import { normalizeLogger } from "../shared/logger.js";
|
|
6
|
+
import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, MissingPaymentMethodError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
|
|
7
|
+
import { CommerceProviderRegistry } from "./provider-registry.js";
|
|
8
|
+
import { classifySubscriptionChange } from "./plan-change.js";
|
|
9
|
+
const DEFAULT_CHECKOUT_INTENT_TTL_MS = 24 * 60 * 60 * 1_000;
|
|
10
|
+
const DEFAULT_PREFERENCES = {
|
|
11
|
+
autoRecharge: false,
|
|
12
|
+
overageProtection: true,
|
|
13
|
+
emailNotifications: true,
|
|
14
|
+
usageAlerts: true,
|
|
15
|
+
invoiceReminders: false,
|
|
16
|
+
};
|
|
17
|
+
const TERMINAL_CHECKOUT_STATUSES = new Set(["failed", "cancelled", "requires_payment_method"]);
|
|
18
|
+
const CURRENT_SUBSCRIPTION_STATUSES = new Set(["active", "trialing", "past_due", "incomplete"]);
|
|
19
|
+
const BLOCKING_SUBSCRIPTION_STATUSES = new Set(["active", "trialing", "past_due", "incomplete"]);
|
|
20
|
+
const TERMINAL_SUBSCRIPTION_STATUSES = new Set([
|
|
21
|
+
"canceled",
|
|
22
|
+
"unpaid",
|
|
23
|
+
"paused",
|
|
24
|
+
"incomplete_expired",
|
|
25
|
+
"expired",
|
|
26
|
+
]);
|
|
27
|
+
function externalId(reference) {
|
|
28
|
+
switch (reference.type) {
|
|
29
|
+
case "stripe_price":
|
|
30
|
+
return reference.priceId;
|
|
31
|
+
case "dodo_product":
|
|
32
|
+
return reference.productId;
|
|
33
|
+
case "custom_object":
|
|
34
|
+
return reference.externalId;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function checkoutRedirectUrl(template, intentId) {
|
|
38
|
+
return template.replaceAll("{intentId}", encodeURIComponent(intentId));
|
|
39
|
+
}
|
|
40
|
+
function quoteFingerprint(preview) {
|
|
41
|
+
const amount = (value) => {
|
|
42
|
+
const numeric = Number(value);
|
|
43
|
+
return Number.isFinite(numeric) ? numeric : null;
|
|
44
|
+
};
|
|
45
|
+
const financialFields = {
|
|
46
|
+
totalAmount: amount(preview.totalAmount),
|
|
47
|
+
settlementAmount: amount(preview.settlementAmount),
|
|
48
|
+
currency: preview.currency.toUpperCase(),
|
|
49
|
+
recurringAmount: amount(preview.recurringAmount),
|
|
50
|
+
recurringCurrency: preview.recurringCurrency?.toUpperCase() ?? null,
|
|
51
|
+
taxAmount: amount(preview.taxAmount),
|
|
52
|
+
customerCredits: amount(preview.customerCredits),
|
|
53
|
+
lineItems: preview.lineItems.map((item) => ({
|
|
54
|
+
productId: item.productId,
|
|
55
|
+
unitPrice: amount(item.unitPrice),
|
|
56
|
+
quantity: amount(item.quantity),
|
|
57
|
+
prorationFactor: amount(item.prorationFactor),
|
|
58
|
+
currency: item.currency.toUpperCase(),
|
|
59
|
+
tax: amount(item.tax),
|
|
60
|
+
subtotal: amount(item.subtotal),
|
|
61
|
+
})),
|
|
62
|
+
};
|
|
63
|
+
return createHash("sha256").update(JSON.stringify(financialFields)).digest("hex");
|
|
64
|
+
}
|
|
65
|
+
function providerPlanChangeParams(policy) {
|
|
66
|
+
return {
|
|
67
|
+
effectiveAt: policy.effective === "renewal" ? "next_billing_date" : "immediately",
|
|
68
|
+
prorationBillingMode: policy.proration === "none" ? "do_not_bill" : "prorated_immediately",
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
class CommerceAutoRechargeService {
|
|
72
|
+
commerce;
|
|
73
|
+
constructor(commerce) {
|
|
74
|
+
this.commerce = commerce;
|
|
75
|
+
}
|
|
76
|
+
async getStatus(input) {
|
|
77
|
+
const provider = await this.commerce.providerForAccount(input.accountId);
|
|
78
|
+
return this.commerce.billing.autoRecharge.getStatus({
|
|
79
|
+
userId: input.accountId,
|
|
80
|
+
provider,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
async enable(input) {
|
|
84
|
+
const [provider, balance] = await Promise.all([
|
|
85
|
+
this.commerce.providerForAccount(input.accountId),
|
|
86
|
+
this.commerce.credits.getBalance(input.accountId),
|
|
87
|
+
]);
|
|
88
|
+
try {
|
|
89
|
+
return await this.commerce.billing.autoRecharge.enable({
|
|
90
|
+
userId: input.accountId,
|
|
91
|
+
provider,
|
|
92
|
+
balance: Number(balance.balance),
|
|
93
|
+
returnUrl: input.returnUrl,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error instanceof Error && error.message.includes("payment_method")) {
|
|
98
|
+
throw new MissingPaymentMethodError();
|
|
99
|
+
}
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async disable(input) {
|
|
104
|
+
await this.commerce.billing.autoRecharge.disable(input.accountId);
|
|
105
|
+
}
|
|
106
|
+
async retry(input) {
|
|
107
|
+
const [provider, balance] = await Promise.all([
|
|
108
|
+
this.commerce.providerForAccount(input.accountId),
|
|
109
|
+
this.commerce.credits.getBalance(input.accountId),
|
|
110
|
+
]);
|
|
111
|
+
try {
|
|
112
|
+
await this.commerce.billing.autoRecharge.retry({
|
|
113
|
+
userId: input.accountId,
|
|
114
|
+
provider,
|
|
115
|
+
balance: Number(balance.balance),
|
|
116
|
+
returnUrl: input.returnUrl,
|
|
117
|
+
});
|
|
118
|
+
return this.commerce.billing.autoRecharge.getStatus({
|
|
119
|
+
userId: input.accountId,
|
|
120
|
+
provider,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error instanceof Error && error.message.includes("payment_method")) {
|
|
125
|
+
throw new MissingPaymentMethodError();
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async processIfNeeded(input) {
|
|
131
|
+
const profile = await this.commerce.billing.getAutoRechargeProfile(input.accountId);
|
|
132
|
+
if (!profile?.enabled || profile.state !== "active") {
|
|
133
|
+
return { outcome: "disabled" };
|
|
134
|
+
}
|
|
135
|
+
const [provider, balance] = await Promise.all([
|
|
136
|
+
profile.provider
|
|
137
|
+
? this.commerce.providers.get(profile.provider)
|
|
138
|
+
: this.commerce.providerForAccount(input.accountId),
|
|
139
|
+
this.commerce.credits.getBalance(input.accountId),
|
|
140
|
+
]);
|
|
141
|
+
return this.commerce.billing.autoRecharge.processIfNeeded({
|
|
142
|
+
userId: input.accountId,
|
|
143
|
+
provider,
|
|
144
|
+
balance: Number(balance.balance),
|
|
145
|
+
returnUrl: input.returnUrl,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Framework-independent catalog, billing-state, and provider coordinator. */
|
|
150
|
+
export class CommerceService {
|
|
151
|
+
billing;
|
|
152
|
+
credits;
|
|
153
|
+
options;
|
|
154
|
+
autoRecharge;
|
|
155
|
+
providers;
|
|
156
|
+
logger;
|
|
157
|
+
constructor(billing, credits, eventSink, options) {
|
|
158
|
+
this.billing = billing;
|
|
159
|
+
this.credits = credits;
|
|
160
|
+
this.options = options;
|
|
161
|
+
this.logger = normalizeLogger(options.logger);
|
|
162
|
+
const identityResolver = options.identityResolver
|
|
163
|
+
? async (input) => {
|
|
164
|
+
const accountId = await options.identityResolver(input);
|
|
165
|
+
if (accountId && input.customerId) {
|
|
166
|
+
await this.billing.upsertCustomer(input.provider, input.customerId, accountId, input.email);
|
|
167
|
+
}
|
|
168
|
+
return accountId;
|
|
169
|
+
}
|
|
170
|
+
: undefined;
|
|
171
|
+
this.providers = new CommerceProviderRegistry(options, {
|
|
172
|
+
tenantId: options.tenantId,
|
|
173
|
+
eventSink,
|
|
174
|
+
identityResolver,
|
|
175
|
+
});
|
|
176
|
+
this.autoRecharge = new CommerceAutoRechargeService(this);
|
|
177
|
+
}
|
|
178
|
+
/** Exposed for application composition and compatibility, not provider selection policy. */
|
|
179
|
+
getProvider(providerName) {
|
|
180
|
+
return this.providers.get(providerName);
|
|
181
|
+
}
|
|
182
|
+
clearProviderCache() {
|
|
183
|
+
this.providers.clear();
|
|
184
|
+
}
|
|
185
|
+
async activeConfig() {
|
|
186
|
+
const raw = await this.billing.getActiveBursarConfig();
|
|
187
|
+
if (!raw) {
|
|
188
|
+
throw new CoreBillingDataUnavailableError("The active commerce catalog is unavailable");
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
return loadConfigFromDict(raw);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
throw new CoreBillingDataUnavailableError("The active commerce catalog is invalid", error);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async resolveOffer(input) {
|
|
198
|
+
const config = await this.activeConfig();
|
|
199
|
+
const offer = config.commerce.offers[input.offerKey];
|
|
200
|
+
if (!offer)
|
|
201
|
+
throw new UnknownOfferError(`Unknown offer '${input.offerKey}'`);
|
|
202
|
+
this.assertOfferType(offer, input.type);
|
|
203
|
+
return { config, offerKey: input.offerKey, offer };
|
|
204
|
+
}
|
|
205
|
+
assertOfferType(offer, type) {
|
|
206
|
+
if (!type)
|
|
207
|
+
return;
|
|
208
|
+
const expected = type === "credit_pack" ? "topup" : "subscription";
|
|
209
|
+
if (offer.type !== expected) {
|
|
210
|
+
throw new UnknownOfferError(`Offer is not a ${type} offer`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
quantity(offer, requested) {
|
|
214
|
+
if (offer.type === "subscription") {
|
|
215
|
+
if (requested != null && requested !== 1) {
|
|
216
|
+
throw new InvalidOfferQuantityError("Subscription quantity must be 1", 1, 1);
|
|
217
|
+
}
|
|
218
|
+
return 1;
|
|
219
|
+
}
|
|
220
|
+
const quantity = requested ?? offer.quantity.default;
|
|
221
|
+
if (!Number.isInteger(quantity) || quantity < offer.quantity.minimum) {
|
|
222
|
+
throw new InvalidOfferQuantityError(`Minimum quantity is ${offer.quantity.minimum}`, offer.quantity.minimum, offer.quantity.maximum);
|
|
223
|
+
}
|
|
224
|
+
if (quantity > offer.quantity.maximum) {
|
|
225
|
+
throw new InvalidOfferQuantityError(`Maximum quantity is ${offer.quantity.maximum}`, offer.quantity.minimum, offer.quantity.maximum);
|
|
226
|
+
}
|
|
227
|
+
return quantity;
|
|
228
|
+
}
|
|
229
|
+
async providerForAccount(accountId, offer) {
|
|
230
|
+
const subscription = await this.billing.getUserSubscription(accountId);
|
|
231
|
+
const customer = await this.billing.getCustomerByUserId(accountId, subscription?.provider);
|
|
232
|
+
return this.providers.select({
|
|
233
|
+
current: subscription?.provider ?? customer?.provider,
|
|
234
|
+
offer,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
async createCheckout(input) {
|
|
238
|
+
const resolved = await this.resolveOffer(input);
|
|
239
|
+
const quantity = this.quantity(resolved.offer, input.quantity);
|
|
240
|
+
const accountState = input.accountId
|
|
241
|
+
? await Promise.all([
|
|
242
|
+
this.billing.getBlockingSubscription(input.accountId),
|
|
243
|
+
this.billing.getCustomerByUserId(input.accountId),
|
|
244
|
+
])
|
|
245
|
+
: [null, null];
|
|
246
|
+
if (resolved.offer.type === "subscription" && accountState[0]) {
|
|
247
|
+
throw new ActiveSubscriptionError();
|
|
248
|
+
}
|
|
249
|
+
const provider = await this.providers.select({
|
|
250
|
+
requested: input.provider,
|
|
251
|
+
current: accountState[1]?.provider,
|
|
252
|
+
offer: resolved.offer,
|
|
253
|
+
});
|
|
254
|
+
const reference = resolved.offer.providers[provider.provider];
|
|
255
|
+
if (!reference)
|
|
256
|
+
throw new UnknownOfferError("Offer has no reference for the selected provider");
|
|
257
|
+
const productId = externalId(reference);
|
|
258
|
+
const customer = input.accountId
|
|
259
|
+
? await this.billing.getCustomerByUserId(input.accountId, provider.provider)
|
|
260
|
+
: null;
|
|
261
|
+
const metadata = {
|
|
262
|
+
...(input.metadata ?? {}),
|
|
263
|
+
...(input.accountId ? { userId: input.accountId } : {}),
|
|
264
|
+
};
|
|
265
|
+
if (resolved.offer.type === "subscription") {
|
|
266
|
+
metadata.plan_slug = resolved.offer.plan;
|
|
267
|
+
metadata.billing_interval = resolved.offer.billingInterval.unit;
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
metadata.credits = resolved.offer.creditsPerUnit.mul(quantity).toString();
|
|
271
|
+
metadata.quantity = String(quantity);
|
|
272
|
+
}
|
|
273
|
+
const requestDigest = createHash("sha256")
|
|
274
|
+
.update(JSON.stringify({
|
|
275
|
+
checkoutKind: resolved.offer.type,
|
|
276
|
+
offerKey: resolved.offerKey,
|
|
277
|
+
provider: provider.provider,
|
|
278
|
+
quantity,
|
|
279
|
+
}))
|
|
280
|
+
.digest("hex");
|
|
281
|
+
const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
|
|
282
|
+
const createIntent = () => this.billing.createOrGetCheckoutIntent({
|
|
283
|
+
subjectId: input.subjectId,
|
|
284
|
+
provider: provider.provider,
|
|
285
|
+
checkoutKind: resolved.offer.type === "subscription" ? "subscription" : "credit_topup",
|
|
286
|
+
productKey: resolved.offerKey,
|
|
287
|
+
requestDigest,
|
|
288
|
+
expiresAt: expiresAt(),
|
|
289
|
+
});
|
|
290
|
+
let intent = await createIntent();
|
|
291
|
+
if (intent.requestDigest !== requestDigest) {
|
|
292
|
+
throw new CheckoutConflictError("A checkout is already in progress for a different offer");
|
|
293
|
+
}
|
|
294
|
+
if (intent.checkoutUrl) {
|
|
295
|
+
const locallyExpired = new Date(intent.expiresAt).getTime() <= Date.now();
|
|
296
|
+
if (!locallyExpired && (!intent.providerSessionId || !provider.getCheckoutSessionStatus)) {
|
|
297
|
+
throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
|
|
298
|
+
}
|
|
299
|
+
const providerState = locallyExpired
|
|
300
|
+
? null
|
|
301
|
+
: await provider.getCheckoutSessionStatus(intent.providerSessionId);
|
|
302
|
+
if (providerState?.paymentStatus === "succeeded") {
|
|
303
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "completed" });
|
|
304
|
+
throw new CheckoutCompletedError();
|
|
305
|
+
}
|
|
306
|
+
if (!locallyExpired &&
|
|
307
|
+
providerState !== null &&
|
|
308
|
+
!TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
|
|
309
|
+
throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
|
|
310
|
+
}
|
|
311
|
+
await this.billing.updateCheckoutIntent(intent.id, {
|
|
312
|
+
status: providerState === null ? "expired" : "failed",
|
|
313
|
+
});
|
|
314
|
+
intent = await createIntent();
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
const session = await provider.createCheckoutSession({
|
|
318
|
+
...(input.accountId ? { userId: input.accountId } : {}),
|
|
319
|
+
...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
|
|
320
|
+
...(input.email ? { email: input.email } : {}),
|
|
321
|
+
productId,
|
|
322
|
+
type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
|
|
323
|
+
quantity,
|
|
324
|
+
returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
|
|
325
|
+
cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
|
|
326
|
+
metadata: { ...metadata, checkout_intent_id: intent.id },
|
|
327
|
+
idempotencyKey: input.operationKey,
|
|
328
|
+
});
|
|
329
|
+
await this.billing.updateCheckoutIntent(intent.id, {
|
|
330
|
+
providerSessionId: session.providerSessionId,
|
|
331
|
+
checkoutUrl: session.url,
|
|
332
|
+
});
|
|
333
|
+
if (input.accountId &&
|
|
334
|
+
session.customerId &&
|
|
335
|
+
session.customerId !== customer?.providerCustomerId) {
|
|
336
|
+
await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
intentId: intent.id,
|
|
340
|
+
url: session.url,
|
|
341
|
+
provider: provider.provider,
|
|
342
|
+
offerKey: resolved.offerKey,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "failed" });
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
async getCheckoutStatus(input) {
|
|
351
|
+
const intent = await this.billing.getCheckoutIntent(input.intentId, input.subjectId);
|
|
352
|
+
if (!intent)
|
|
353
|
+
throw new CommerceResourceNotFoundError("Checkout intent not found");
|
|
354
|
+
const expired = intent.status === "open" && new Date(intent.expiresAt).getTime() <= Date.now();
|
|
355
|
+
return {
|
|
356
|
+
intentId: intent.id,
|
|
357
|
+
status: expired
|
|
358
|
+
? "expired"
|
|
359
|
+
: intent.status === "open"
|
|
360
|
+
? "pending"
|
|
361
|
+
: intent.status === "completed"
|
|
362
|
+
? "succeeded"
|
|
363
|
+
: intent.status,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
async cancelSubscription(input) {
|
|
367
|
+
const subscription = await this.billing.getUserSubscription(input.accountId);
|
|
368
|
+
if (!subscription?.providerSubscriptionId) {
|
|
369
|
+
throw new CommerceResourceNotFoundError("No active subscription found");
|
|
370
|
+
}
|
|
371
|
+
if (!["active", "trialing", "past_due"].includes(subscription.status ?? "")) {
|
|
372
|
+
return { ok: true };
|
|
373
|
+
}
|
|
374
|
+
const provider = await this.providers.get(subscription.provider);
|
|
375
|
+
if (!provider.cancelSubscription) {
|
|
376
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
|
|
377
|
+
}
|
|
378
|
+
await provider.cancelSubscription(subscription.providerSubscriptionId, input.operationKey);
|
|
379
|
+
await this.billing.ingestBillingEvent({
|
|
380
|
+
provider: subscription.provider,
|
|
381
|
+
eventId: `cancel_${input.accountId}_${input.operationKey}`,
|
|
382
|
+
eventType: "subscription.cancellation_scheduled",
|
|
383
|
+
occurredAt: new Date().toISOString(),
|
|
384
|
+
userId: input.accountId,
|
|
385
|
+
customer: { providerCustomerId: subscription.providerCustomerId },
|
|
386
|
+
subscription: {
|
|
387
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
388
|
+
cancelAtPeriodEnd: true,
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
return { ok: true, pending: true };
|
|
392
|
+
}
|
|
393
|
+
async reactivateSubscription(input) {
|
|
394
|
+
const subscription = await this.billing.getUserSubscription(input.accountId);
|
|
395
|
+
if (!subscription?.providerSubscriptionId) {
|
|
396
|
+
throw new CommerceResourceNotFoundError("No subscription found");
|
|
397
|
+
}
|
|
398
|
+
if ((subscription.status === "active" && !subscription.cancelAtPeriodEnd) ||
|
|
399
|
+
(!subscription.cancelAtPeriodEnd && subscription.status !== "canceled")) {
|
|
400
|
+
return { ok: true };
|
|
401
|
+
}
|
|
402
|
+
const provider = await this.providers.get(subscription.provider);
|
|
403
|
+
if (!provider.reactivateSubscription) {
|
|
404
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "reactivateSubscription");
|
|
405
|
+
}
|
|
406
|
+
await provider.reactivateSubscription(subscription.providerSubscriptionId, input.operationKey);
|
|
407
|
+
await this.billing.ingestBillingEvent({
|
|
408
|
+
provider: subscription.provider,
|
|
409
|
+
eventId: `reactivate_${input.accountId}_${input.operationKey}`,
|
|
410
|
+
eventType: "subscription.cancellation_unscheduled",
|
|
411
|
+
occurredAt: new Date().toISOString(),
|
|
412
|
+
userId: input.accountId,
|
|
413
|
+
customer: { providerCustomerId: subscription.providerCustomerId },
|
|
414
|
+
subscription: {
|
|
415
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
416
|
+
cancelAtPeriodEnd: false,
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
return { ok: true, pending: true };
|
|
420
|
+
}
|
|
421
|
+
async cancelAllSubscriptions(input) {
|
|
422
|
+
if (!input.operationKey.trim()) {
|
|
423
|
+
throw new ConfigError("operationKey must not be empty");
|
|
424
|
+
}
|
|
425
|
+
const subscriptions = await this.billing.listCancellableSubscriptions(input.accountId);
|
|
426
|
+
const results = await Promise.all(subscriptions.map(async (subscription) => {
|
|
427
|
+
try {
|
|
428
|
+
const provider = await this.providers.get(subscription.provider);
|
|
429
|
+
if (!provider.cancelSubscription) {
|
|
430
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
|
|
431
|
+
}
|
|
432
|
+
const operationKey = `${input.operationKey}:${subscription.provider}:${subscription.providerSubscriptionId}`;
|
|
433
|
+
await provider.cancelSubscription(subscription.providerSubscriptionId, operationKey);
|
|
434
|
+
await this.billing.ingestBillingEvent({
|
|
435
|
+
provider: subscription.provider,
|
|
436
|
+
eventId: `cancel_all_${input.accountId}_${operationKey}`,
|
|
437
|
+
eventType: "subscription.cancellation_scheduled",
|
|
438
|
+
occurredAt: new Date().toISOString(),
|
|
439
|
+
userId: input.accountId,
|
|
440
|
+
customer: { providerCustomerId: subscription.providerCustomerId },
|
|
441
|
+
subscription: {
|
|
442
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
443
|
+
cancelAtPeriodEnd: true,
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
return {
|
|
447
|
+
provider: subscription.provider,
|
|
448
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
449
|
+
canceled: true,
|
|
450
|
+
error: null,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
return {
|
|
455
|
+
provider: subscription.provider,
|
|
456
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
457
|
+
canceled: false,
|
|
458
|
+
error: error instanceof Error ? error.message : String(error),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
}));
|
|
462
|
+
const failures = results.filter((result) => !result.canceled);
|
|
463
|
+
if (failures.length) {
|
|
464
|
+
throw new AggregateError(failures.map((failure) => new Error(failure.error ?? "Subscription cancellation failed")), "One or more subscriptions could not be cancelled");
|
|
465
|
+
}
|
|
466
|
+
return {
|
|
467
|
+
accountId: input.accountId,
|
|
468
|
+
canceledCount: results.length,
|
|
469
|
+
subscriptions: results,
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
accountSubscriptionSummary(accountId, subscription, entitlement, config, pending) {
|
|
473
|
+
let pendingChange = null;
|
|
474
|
+
if (pending) {
|
|
475
|
+
const planKey = pending.toOffer.plan;
|
|
476
|
+
const interval = pending.toOffer.interval;
|
|
477
|
+
if (!planKey ||
|
|
478
|
+
!config.plans[planKey] ||
|
|
479
|
+
(interval !== "month" && interval !== "year") ||
|
|
480
|
+
!pending.effectiveAt) {
|
|
481
|
+
throw new CoreBillingDataUnavailableError("Pending subscription change has incomplete catalog context");
|
|
482
|
+
}
|
|
483
|
+
pendingChange = {
|
|
484
|
+
planKey,
|
|
485
|
+
interval,
|
|
486
|
+
effectiveAt: pending.effectiveAt,
|
|
487
|
+
scheduled: pending.effective === "renewal",
|
|
488
|
+
providerOperationId: pending.providerOperationId ?? null,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
const status = subscription?.status ?? null;
|
|
492
|
+
const isCurrent = status != null && CURRENT_SUBSCRIPTION_STATUSES.has(status);
|
|
493
|
+
const isEntitled = entitlement.planKey != null;
|
|
494
|
+
if (entitlement.planKey && !config.plans[entitlement.planKey]) {
|
|
495
|
+
throw new CoreBillingDataUnavailableError("The account plan is not present in the catalog");
|
|
496
|
+
}
|
|
497
|
+
const inGrace = status === "past_due" &&
|
|
498
|
+
subscription?.graceEndsAt != null &&
|
|
499
|
+
Date.parse(subscription.graceEndsAt) > Date.now();
|
|
500
|
+
return {
|
|
501
|
+
accountId,
|
|
502
|
+
planKey: entitlement.planKey ?? (isCurrent ? (subscription?.plan ?? null) : null),
|
|
503
|
+
status,
|
|
504
|
+
lifecycleState: status ?? "none",
|
|
505
|
+
accessState: isEntitled ? (inGrace ? "grace" : "entitled") : status ? "blocked" : "none",
|
|
506
|
+
isCurrent,
|
|
507
|
+
isEntitled,
|
|
508
|
+
isBlockingCheckout: status != null && BLOCKING_SUBSCRIPTION_STATUSES.has(status),
|
|
509
|
+
isCancellable: status != null &&
|
|
510
|
+
["active", "trialing", "past_due"].includes(status) &&
|
|
511
|
+
!subscription?.cancelAtPeriodEnd,
|
|
512
|
+
isTerminal: status != null && TERMINAL_SUBSCRIPTION_STATUSES.has(status),
|
|
513
|
+
subscription,
|
|
514
|
+
pendingChange,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
async getAccountSubscriptionSummary(accountId) {
|
|
518
|
+
const [subscription, entitlement, config] = await Promise.all([
|
|
519
|
+
this.billing.getUserSubscription(accountId),
|
|
520
|
+
this.credits.getUserPlan(accountId),
|
|
521
|
+
this.activeConfig(),
|
|
522
|
+
]);
|
|
523
|
+
const pending = subscription
|
|
524
|
+
? await this.billing.getOpenBillingSubscriptionChange(subscription.provider, subscription.providerSubscriptionId)
|
|
525
|
+
: null;
|
|
526
|
+
return this.accountSubscriptionSummary(accountId, subscription, entitlement, config, pending);
|
|
527
|
+
}
|
|
528
|
+
async planChangeContext(input) {
|
|
529
|
+
const [subscription, entitlement, resolved] = await Promise.all([
|
|
530
|
+
this.billing.getActiveSubscription(input.accountId),
|
|
531
|
+
this.credits.getUserPlan(input.accountId),
|
|
532
|
+
this.resolveOffer({
|
|
533
|
+
offerKey: input.offerKey,
|
|
534
|
+
type: "subscription",
|
|
535
|
+
}),
|
|
536
|
+
]);
|
|
537
|
+
if (!subscription?.providerSubscriptionId) {
|
|
538
|
+
throw new CommerceResourceNotFoundError("No active subscription found");
|
|
539
|
+
}
|
|
540
|
+
if (resolved.offer.type !== "subscription")
|
|
541
|
+
throw new UnknownOfferError();
|
|
542
|
+
const provider = await this.providers.select({
|
|
543
|
+
requested: subscription.provider,
|
|
544
|
+
current: subscription.provider,
|
|
545
|
+
offer: resolved.offer,
|
|
546
|
+
});
|
|
547
|
+
const reference = resolved.offer.providers[provider.provider];
|
|
548
|
+
if (!reference)
|
|
549
|
+
throw new UnknownOfferError("Target offer is unavailable from the provider");
|
|
550
|
+
const persistedOffer = reference.type === "stripe_price"
|
|
551
|
+
? await this.billing.resolveOffer(provider.provider, null, reference.priceId)
|
|
552
|
+
: reference.type === "dodo_product"
|
|
553
|
+
? await this.billing.resolveOffer(provider.provider, reference.productId, null)
|
|
554
|
+
: await this.billing.resolveOfferByLookup(provider.provider, reference.externalId);
|
|
555
|
+
if (!persistedOffer) {
|
|
556
|
+
throw new CommerceResourceNotFoundError("Target offer is not present in persisted billing state");
|
|
557
|
+
}
|
|
558
|
+
const currentPlan = entitlement.planKey ?? subscription.plan;
|
|
559
|
+
if (!currentPlan) {
|
|
560
|
+
throw new CommerceResourceNotFoundError("Current subscription plan is unknown");
|
|
561
|
+
}
|
|
562
|
+
const { classification, targetInterval, policy } = classifySubscriptionChange(resolved.config, currentPlan, subscription.interval, resolved.offer);
|
|
563
|
+
return {
|
|
564
|
+
subscription,
|
|
565
|
+
provider,
|
|
566
|
+
targetOfferId: persistedOffer.offerId,
|
|
567
|
+
targetOffer: resolved.offer,
|
|
568
|
+
targetProductId: externalId(reference),
|
|
569
|
+
targetInterval,
|
|
570
|
+
classification,
|
|
571
|
+
policy,
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
async refreshPlanPreview(context) {
|
|
575
|
+
if (!context.provider.previewChangePlan) {
|
|
576
|
+
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "previewChangePlan");
|
|
577
|
+
}
|
|
578
|
+
return context.provider.previewChangePlan({
|
|
579
|
+
providerSubscriptionId: context.subscription.providerSubscriptionId,
|
|
580
|
+
productId: context.targetProductId,
|
|
581
|
+
...providerPlanChangeParams(context.policy),
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
async previewPlanChange(input) {
|
|
585
|
+
const context = await this.planChangeContext(input);
|
|
586
|
+
if (context.classification === "unchanged") {
|
|
587
|
+
return {
|
|
588
|
+
unchanged: true,
|
|
589
|
+
classification: "unchanged",
|
|
590
|
+
scheduled: false,
|
|
591
|
+
planId: context.targetOffer.plan,
|
|
592
|
+
interval: context.targetInterval,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
const preview = await this.refreshPlanPreview(context);
|
|
596
|
+
return {
|
|
597
|
+
unchanged: false,
|
|
598
|
+
classification: context.classification,
|
|
599
|
+
scheduled: context.policy.effective === "renewal",
|
|
600
|
+
planId: context.targetOffer.plan,
|
|
601
|
+
interval: context.targetInterval,
|
|
602
|
+
preview,
|
|
603
|
+
quoteFingerprint: quoteFingerprint(preview),
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
async confirmPlanChange(input) {
|
|
607
|
+
const context = await this.planChangeContext(input);
|
|
608
|
+
if (context.classification === "unchanged") {
|
|
609
|
+
return {
|
|
610
|
+
success: true,
|
|
611
|
+
unchanged: true,
|
|
612
|
+
planId: context.targetOffer.plan,
|
|
613
|
+
interval: context.targetInterval,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
const preview = await this.refreshPlanPreview(context);
|
|
617
|
+
const fingerprint = quoteFingerprint(preview);
|
|
618
|
+
const refreshed = {
|
|
619
|
+
unchanged: false,
|
|
620
|
+
classification: context.classification,
|
|
621
|
+
scheduled: context.policy.effective === "renewal",
|
|
622
|
+
planId: context.targetOffer.plan,
|
|
623
|
+
interval: context.targetInterval,
|
|
624
|
+
preview,
|
|
625
|
+
quoteFingerprint: fingerprint,
|
|
626
|
+
};
|
|
627
|
+
if (!input.quoteFingerprint || input.quoteFingerprint !== fingerprint) {
|
|
628
|
+
throw new QuoteChangedError(refreshed);
|
|
629
|
+
}
|
|
630
|
+
if (!context.provider.changePlan) {
|
|
631
|
+
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "changePlan");
|
|
632
|
+
}
|
|
633
|
+
const existing = await this.billing.getOpenBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId);
|
|
634
|
+
if (existing?.state === "scheduled" && existing.effective === "renewal") {
|
|
635
|
+
if (!context.provider.cancelScheduledPlanChange) {
|
|
636
|
+
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "cancelScheduledPlanChange");
|
|
637
|
+
}
|
|
638
|
+
await context.provider.cancelScheduledPlanChange(context.subscription.providerSubscriptionId, existing.providerOperationId, `${input.operationKey}:replace`);
|
|
639
|
+
await this.billing.updateBillingSubscriptionChange(existing.id, {
|
|
640
|
+
state: "canceled",
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
else if (existing) {
|
|
644
|
+
throw new CheckoutConflictError("A plan change is already awaiting payment");
|
|
645
|
+
}
|
|
646
|
+
const scheduled = context.policy.effective === "renewal";
|
|
647
|
+
const effectiveAt = scheduled
|
|
648
|
+
? preview.nextBillingDate
|
|
649
|
+
: Number.isFinite(Date.parse(preview.effectiveAt))
|
|
650
|
+
? preview.effectiveAt
|
|
651
|
+
: new Date().toISOString();
|
|
652
|
+
if (!effectiveAt) {
|
|
653
|
+
throw new CoreBillingDataUnavailableError("The provider did not return the scheduled change date");
|
|
654
|
+
}
|
|
655
|
+
const change = await this.billing.createBillingSubscriptionChange({
|
|
656
|
+
provider: context.subscription.provider,
|
|
657
|
+
providerSubscriptionId: context.subscription.providerSubscriptionId,
|
|
658
|
+
toOfferId: context.targetOfferId,
|
|
659
|
+
effectiveAt,
|
|
660
|
+
effective: context.policy.effective,
|
|
661
|
+
idempotencyKey: input.operationKey,
|
|
662
|
+
prorationBehavior: context.policy.proration === "none" ? "none" : "invoice_immediately",
|
|
663
|
+
});
|
|
664
|
+
try {
|
|
665
|
+
if (context.subscription.cancelAtPeriodEnd) {
|
|
666
|
+
if (!context.provider.reactivateSubscription) {
|
|
667
|
+
throw new ProviderCapabilityNotSupportedError(context.provider.provider, "reactivateSubscription");
|
|
668
|
+
}
|
|
669
|
+
await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:keep`);
|
|
670
|
+
}
|
|
671
|
+
const result = await context.provider.changePlan({
|
|
672
|
+
providerSubscriptionId: context.subscription.providerSubscriptionId,
|
|
673
|
+
productId: context.targetProductId,
|
|
674
|
+
...providerPlanChangeParams(context.policy),
|
|
675
|
+
onPaymentFailure: context.policy.paymentFailure,
|
|
676
|
+
metadata: {
|
|
677
|
+
userId: input.accountId,
|
|
678
|
+
plan_slug: context.targetOffer.plan,
|
|
679
|
+
billing_interval: context.targetInterval,
|
|
680
|
+
},
|
|
681
|
+
idempotencyKey: input.operationKey,
|
|
682
|
+
});
|
|
683
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
684
|
+
providerOperationId: result && "providerOperationId" in result ? (result.providerOperationId ?? null) : null,
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
catch (error) {
|
|
688
|
+
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
689
|
+
state: "failed",
|
|
690
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
691
|
+
});
|
|
692
|
+
throw error;
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
success: true,
|
|
696
|
+
pending: true,
|
|
697
|
+
scheduled,
|
|
698
|
+
effectiveAt,
|
|
699
|
+
planId: context.targetOffer.plan,
|
|
700
|
+
interval: context.targetInterval,
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
async cancelScheduledPlanChange(input) {
|
|
704
|
+
const subscription = await this.billing.getActiveSubscription(input.accountId);
|
|
705
|
+
if (!subscription)
|
|
706
|
+
throw new CommerceResourceNotFoundError("No active subscription found");
|
|
707
|
+
const change = await this.billing.getOpenBillingSubscriptionChange(subscription.provider, subscription.providerSubscriptionId);
|
|
708
|
+
if (!change || change.state !== "scheduled" || change.effective !== "renewal") {
|
|
709
|
+
throw new CommerceResourceNotFoundError("No scheduled plan change found");
|
|
710
|
+
}
|
|
711
|
+
const provider = await this.providers.get(subscription.provider);
|
|
712
|
+
if (!provider.cancelScheduledPlanChange) {
|
|
713
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelScheduledPlanChange");
|
|
714
|
+
}
|
|
715
|
+
await provider.cancelScheduledPlanChange(subscription.providerSubscriptionId, change.providerOperationId, input.operationKey);
|
|
716
|
+
await this.billing.updateBillingSubscriptionChange(change.id, { state: "canceled" });
|
|
717
|
+
return { success: true };
|
|
718
|
+
}
|
|
719
|
+
async createPortalSession(input) {
|
|
720
|
+
const subscription = await this.billing.getUserSubscription(input.accountId);
|
|
721
|
+
const customer = await this.billing.getCustomerByUserId(input.accountId, subscription?.provider);
|
|
722
|
+
if (!customer?.providerCustomerId) {
|
|
723
|
+
throw new CommerceResourceNotFoundError("No billing customer found");
|
|
724
|
+
}
|
|
725
|
+
const provider = await this.providers.get(customer.provider);
|
|
726
|
+
if (input.purpose === "payment-method") {
|
|
727
|
+
if (subscription?.providerSubscriptionId) {
|
|
728
|
+
if (!provider.createUpdatePaymentMethodSession) {
|
|
729
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "createUpdatePaymentMethodSession");
|
|
730
|
+
}
|
|
731
|
+
return provider.createUpdatePaymentMethodSession({
|
|
732
|
+
customerId: customer.providerCustomerId,
|
|
733
|
+
subscriptionId: subscription.providerSubscriptionId,
|
|
734
|
+
returnUrl: input.returnUrl,
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
if (!provider.createPaymentMethodSetupSession) {
|
|
738
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "createPaymentMethodSetupSession");
|
|
739
|
+
}
|
|
740
|
+
return provider.createPaymentMethodSetupSession({
|
|
741
|
+
customerId: customer.providerCustomerId,
|
|
742
|
+
returnUrl: input.returnUrl,
|
|
743
|
+
cancelUrl: input.cancelUrl,
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
if (!provider.createCustomerPortalSession) {
|
|
747
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "createCustomerPortalSession");
|
|
748
|
+
}
|
|
749
|
+
return provider.createCustomerPortalSession({
|
|
750
|
+
customerId: customer.providerCustomerId,
|
|
751
|
+
returnUrl: input.returnUrl,
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
preferences(accountId, current) {
|
|
755
|
+
return {
|
|
756
|
+
userId: accountId,
|
|
757
|
+
...DEFAULT_PREFERENCES,
|
|
758
|
+
...(this.options.preferenceDefaults ?? {}),
|
|
759
|
+
...(current ?? {}),
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
async updatePreferences(input) {
|
|
763
|
+
const current = await this.billing.getUserPreferences(input.accountId);
|
|
764
|
+
const next = { ...this.preferences(input.accountId, current), ...input.patch };
|
|
765
|
+
await this.billing.updateUserPreferences(next);
|
|
766
|
+
return next;
|
|
767
|
+
}
|
|
768
|
+
ledgerDocument(entry) {
|
|
769
|
+
const metadata = entry.metadata ?? {};
|
|
770
|
+
const normalizedProvider = typeof metadata.provider === "string" ? metadata.provider : undefined;
|
|
771
|
+
const normalizedDocumentId = typeof metadata.provider_document_id === "string"
|
|
772
|
+
? metadata.provider_document_id
|
|
773
|
+
: typeof metadata.provider_invoice_id === "string"
|
|
774
|
+
? metadata.provider_invoice_id
|
|
775
|
+
: typeof metadata.provider_payment_id === "string"
|
|
776
|
+
? metadata.provider_payment_id
|
|
777
|
+
: undefined;
|
|
778
|
+
if (!normalizedDocumentId)
|
|
779
|
+
return null;
|
|
780
|
+
return {
|
|
781
|
+
kind: "ledger_entry",
|
|
782
|
+
ledgerEntryId: entry.entryId,
|
|
783
|
+
provider: normalizedProvider ?? null,
|
|
784
|
+
providerDocumentId: normalizedDocumentId,
|
|
785
|
+
createdAt: entry.createdAt,
|
|
786
|
+
entryType: entry.entryType,
|
|
787
|
+
amount: entry.amount,
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
async getAccountOverview(accountId) {
|
|
791
|
+
let core;
|
|
792
|
+
try {
|
|
793
|
+
const [balance, available, bucketBalances, entitlement, allowance, subscription, prefs, config,] = await Promise.all([
|
|
794
|
+
this.credits.getBalance(accountId),
|
|
795
|
+
this.credits.getAvailable(accountId),
|
|
796
|
+
this.credits.getBucketBalances(accountId),
|
|
797
|
+
this.credits.getUserPlan(accountId),
|
|
798
|
+
this.credits.checkAllowance(accountId),
|
|
799
|
+
this.billing.getUserSubscription(accountId),
|
|
800
|
+
this.billing.getUserPreferences(accountId),
|
|
801
|
+
this.activeConfig(),
|
|
802
|
+
]);
|
|
803
|
+
core = {
|
|
804
|
+
balance,
|
|
805
|
+
available,
|
|
806
|
+
bucketBalances,
|
|
807
|
+
entitlement,
|
|
808
|
+
allowance,
|
|
809
|
+
subscription,
|
|
810
|
+
preferences: this.preferences(accountId, prefs),
|
|
811
|
+
config,
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
catch (error) {
|
|
815
|
+
throw new CoreBillingDataUnavailableError(undefined, error);
|
|
816
|
+
}
|
|
817
|
+
const pendingChange = core.subscription
|
|
818
|
+
? await this.billing.getOpenBillingSubscriptionChange(core.subscription.provider, core.subscription.providerSubscriptionId)
|
|
819
|
+
: null;
|
|
820
|
+
const subscriptionSummary = this.accountSubscriptionSummary(accountId, core.subscription, core.entitlement, core.config, pendingChange);
|
|
821
|
+
const [transactionsResult, usageResult, invoicesResult] = await Promise.allSettled([
|
|
822
|
+
this.credits.listLedgerEntries(accountId, { limit: 50 }),
|
|
823
|
+
this.credits.listUsageCharges(accountId, { limit: 100 }),
|
|
824
|
+
this.billing.listBillingInvoices(accountId),
|
|
825
|
+
]);
|
|
826
|
+
const transactions = transactionsResult.status === "fulfilled"
|
|
827
|
+
? transactionsResult.value.items.filter((entry) => entry.entryType !== "usage")
|
|
828
|
+
: [];
|
|
829
|
+
const usage = usageResult.status === "fulfilled" ? usageResult.value.items : [];
|
|
830
|
+
const invoices = invoicesResult.status === "fulfilled" ? invoicesResult.value : [];
|
|
831
|
+
const documents = [
|
|
832
|
+
...invoices.flatMap((invoice) => {
|
|
833
|
+
const provider = invoice.provider ?? core.subscription?.provider;
|
|
834
|
+
return provider
|
|
835
|
+
? [
|
|
836
|
+
{
|
|
837
|
+
kind: "provider_invoice",
|
|
838
|
+
provider,
|
|
839
|
+
providerDocumentId: invoice.providerInvoiceId,
|
|
840
|
+
status: invoice.status,
|
|
841
|
+
amountPaidMinor: invoice.amountPaidMinor,
|
|
842
|
+
amountDueMinor: invoice.amountDueMinor,
|
|
843
|
+
currency: invoice.currency,
|
|
844
|
+
periodStart: invoice.periodStart,
|
|
845
|
+
periodEnd: invoice.periodEnd,
|
|
846
|
+
},
|
|
847
|
+
]
|
|
848
|
+
: [];
|
|
849
|
+
}),
|
|
850
|
+
...transactions.flatMap((entry) => {
|
|
851
|
+
const document = this.ledgerDocument(entry);
|
|
852
|
+
return document ? [document] : [];
|
|
853
|
+
}),
|
|
854
|
+
];
|
|
855
|
+
let paymentMethods = [];
|
|
856
|
+
let paymentMethodsAvailable = true;
|
|
857
|
+
let autoRecharge = null;
|
|
858
|
+
let autoRechargeAvailable = true;
|
|
859
|
+
try {
|
|
860
|
+
const customer = await this.billing.getCustomerByUserId(accountId, core.subscription?.provider);
|
|
861
|
+
if (customer) {
|
|
862
|
+
const provider = await this.providers.get(customer.provider);
|
|
863
|
+
if (provider.listPaymentMethods) {
|
|
864
|
+
paymentMethods = await provider.listPaymentMethods(customer.providerCustomerId);
|
|
865
|
+
}
|
|
866
|
+
else {
|
|
867
|
+
paymentMethodsAvailable = false;
|
|
868
|
+
}
|
|
869
|
+
try {
|
|
870
|
+
autoRecharge = await this.billing.autoRecharge.getStatus({
|
|
871
|
+
userId: accountId,
|
|
872
|
+
provider,
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
catch (error) {
|
|
876
|
+
autoRechargeAvailable = false;
|
|
877
|
+
this.logger.warn("[CommerceService] auto-recharge overview unavailable", {
|
|
878
|
+
accountId,
|
|
879
|
+
error: error instanceof Error ? error.message : String(error),
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
catch (error) {
|
|
885
|
+
paymentMethodsAvailable = false;
|
|
886
|
+
autoRechargeAvailable = false;
|
|
887
|
+
this.logger.warn("[CommerceService] provider overview unavailable", {
|
|
888
|
+
accountId,
|
|
889
|
+
error: error instanceof Error ? error.message : String(error),
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
const floor = core.entitlement.creditPolicy?.type === "credit_line"
|
|
893
|
+
? (core.entitlement.creditPolicy.creditLimit ?? new Decimal(0)).negated()
|
|
894
|
+
: new Decimal(0);
|
|
895
|
+
return {
|
|
896
|
+
accountId,
|
|
897
|
+
credits: {
|
|
898
|
+
ledgerBalance: core.balance.balance,
|
|
899
|
+
effectiveSpendableBalance: core.available.available
|
|
900
|
+
.plus(core.allowance.allowanceRemaining)
|
|
901
|
+
.minus(floor),
|
|
902
|
+
lifetimePurchases: core.balance.lifetimePurchased,
|
|
903
|
+
allowance: {
|
|
904
|
+
remaining: core.allowance.allowanceRemaining,
|
|
905
|
+
limit: core.entitlement.allowance?.amount ?? null,
|
|
906
|
+
periodStart: core.allowance.periodStart ?? null,
|
|
907
|
+
periodEnd: core.allowance.periodEnd ?? null,
|
|
908
|
+
},
|
|
909
|
+
buckets: core.bucketBalances.buckets,
|
|
910
|
+
bucketsByKey: Object.fromEntries(core.bucketBalances.buckets.map((bucket) => [bucket.bucketKey, bucket.balance])),
|
|
911
|
+
display: core.config.credits.display ?? null,
|
|
912
|
+
},
|
|
913
|
+
entitlement: core.entitlement,
|
|
914
|
+
subscriptionSummary,
|
|
915
|
+
subscription: core.subscription,
|
|
916
|
+
pendingChange,
|
|
917
|
+
preferences: core.preferences,
|
|
918
|
+
paymentMethods,
|
|
919
|
+
documents,
|
|
920
|
+
providerInvoices: invoices,
|
|
921
|
+
transactions,
|
|
922
|
+
usage,
|
|
923
|
+
autoRecharge,
|
|
924
|
+
availability: {
|
|
925
|
+
paymentMethods: paymentMethodsAvailable,
|
|
926
|
+
documents: invoicesResult.status === "fulfilled" && transactionsResult.status === "fulfilled",
|
|
927
|
+
providerInvoices: invoicesResult.status === "fulfilled",
|
|
928
|
+
transactions: transactionsResult.status === "fulfilled",
|
|
929
|
+
usage: usageResult.status === "fulfilled",
|
|
930
|
+
autoRecharge: autoRechargeAvailable,
|
|
931
|
+
},
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
async getInvoiceLink(input) {
|
|
935
|
+
let providerName;
|
|
936
|
+
let providerDocumentId;
|
|
937
|
+
if (input.document.kind === "provider_invoice") {
|
|
938
|
+
const document = input.document;
|
|
939
|
+
const owned = (await this.billing.listBillingInvoices(input.accountId)).find((invoice) => (invoice.provider ?? document.provider) === document.provider &&
|
|
940
|
+
invoice.providerInvoiceId === document.providerDocumentId);
|
|
941
|
+
if (!owned)
|
|
942
|
+
throw new CommerceResourceNotFoundError("Invoice not found");
|
|
943
|
+
providerName = document.provider;
|
|
944
|
+
providerDocumentId = owned.providerInvoiceId;
|
|
945
|
+
}
|
|
946
|
+
else {
|
|
947
|
+
const entry = await this.credits.getLedgerEntry(input.accountId, input.document.ledgerEntryId);
|
|
948
|
+
if (!entry)
|
|
949
|
+
throw new CommerceResourceNotFoundError("Ledger entry not found");
|
|
950
|
+
const owned = this.ledgerDocument(entry);
|
|
951
|
+
if (!owned?.provider || !owned.providerDocumentId) {
|
|
952
|
+
throw new CommerceResourceNotFoundError("No provider document is associated with the ledger entry");
|
|
953
|
+
}
|
|
954
|
+
providerName = owned.provider;
|
|
955
|
+
providerDocumentId = owned.providerDocumentId;
|
|
956
|
+
}
|
|
957
|
+
const provider = await this.providers.get(providerName);
|
|
958
|
+
if (!provider.getInvoiceUrl) {
|
|
959
|
+
throw new ProviderCapabilityNotSupportedError(provider.provider, "getInvoiceUrl");
|
|
960
|
+
}
|
|
961
|
+
const result = await provider.getInvoiceUrl(providerDocumentId);
|
|
962
|
+
if (!result)
|
|
963
|
+
throw new CommerceResourceNotFoundError("No invoice URL is available");
|
|
964
|
+
return result;
|
|
965
|
+
}
|
|
966
|
+
async handleWebhook(input) {
|
|
967
|
+
const provider = await this.providers.select({ requested: input.provider });
|
|
968
|
+
const result = await provider.handleWebhook({
|
|
969
|
+
rawBody: input.rawBody,
|
|
970
|
+
headers: input.headers,
|
|
971
|
+
});
|
|
972
|
+
return {
|
|
973
|
+
received: result.received,
|
|
974
|
+
retryable: result.retryable,
|
|
975
|
+
provider: result.provider,
|
|
976
|
+
eventId: result.eventId,
|
|
977
|
+
eventType: result.eventType,
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
//# sourceMappingURL=service.js.map
|