@zonastery/bursar 1.0.0 → 2.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 +189 -62
- package/dist/billing/auto-recharge-port.d.ts +3 -3
- 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 +5 -4
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +64 -34
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +5 -5
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +2 -2
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +10 -9
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +31 -31
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +49 -10
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +1 -0
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +37 -10
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +69 -72
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +2 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +5 -5
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +2 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/policy-window.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +205 -60
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/customer.js +19 -11
- package/dist/billing/postgres/repositories/customer.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js +3 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts +14 -7
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +21 -20
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +53 -11
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +20 -17
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +123 -57
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +23 -20
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +43 -37
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/preferences.js +45 -7
- package/dist/billing/postgres/repositories/preferences.js.map +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/refund.js +13 -9
- package/dist/billing/postgres/repositories/refund.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
- package/dist/billing/postgres/repositories/subscription-change.js +234 -0
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +199 -91
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +13 -15
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +65 -34
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +23 -14
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +265 -228
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +6 -5
- 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 +6 -4
- 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 +18 -35
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/common.d.ts +0 -1
- package/dist/billing/types/common.d.ts.map +1 -1
- package/dist/billing/types/common.js.map +1 -1
- package/dist/billing/types/documents.d.ts +38 -12
- 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 +238 -0
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/index.js.map +1 -1
- package/dist/billing/types/preferences.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +8 -8
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/bursar.d.ts +33 -11
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +58 -22
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +1 -0
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -0
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/errors.d.ts +4 -14
- package/dist/commerce/errors.d.ts.map +1 -1
- package/dist/commerce/errors.js +4 -21
- package/dist/commerce/errors.js.map +1 -1
- package/dist/commerce/index.d.ts +1 -0
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js.map +1 -1
- 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 +27 -2
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts +15 -7
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +130 -77
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +33 -13
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.js.map +1 -1
- 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 +30 -13
- 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 +16 -5
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +14 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +7 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +64 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +9 -8
- package/dist/credits/catalog-runtime.d.ts.map +1 -0
- package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
- package/dist/credits/catalog-runtime.js.map +1 -0
- package/dist/credits/events.d.ts +4 -4
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/events.js +1 -1
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +14 -14
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +18 -17
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -2
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +39 -35
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +55 -53
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts +28 -30
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +100 -59
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +22 -21
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
- package/dist/credits/postgres/repositories/catalog.js +90 -0
- package/dist/credits/postgres/repositories/catalog.js.map +1 -0
- package/dist/credits/postgres/repositories/deduction.d.ts +32 -21
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +171 -62
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +21 -18
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +157 -65
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +94 -42
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +134 -104
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +36 -27
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +96 -52
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +31 -21
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +325 -235
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +7 -9
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +42 -63
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/queries.d.ts +5 -5
- package/dist/credits/queries.d.ts.map +1 -1
- package/dist/credits/queries.js +4 -4
- package/dist/credits/queries.js.map +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +42 -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 +51 -58
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +178 -113
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +25 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +9 -5
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +50 -12
- 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 +17 -6
- package/dist/credits/types/admission.d.ts.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/analytics.d.ts +2 -2
- package/dist/credits/types/analytics.d.ts.map +1 -1
- package/dist/credits/types/analytics.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +21 -14
- 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 +22 -8
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/index.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +19 -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.js.map +1 -1
- package/dist/credits/types/teams.d.ts +18 -6
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +24 -10
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +105 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +137 -9
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +29 -17
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/language.js.map +1 -1
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +11 -4
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr/tokenizer.d.ts.map +1 -1
- package/dist/expr/tokenizer.js +17 -13
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.d.ts +2 -2
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +7 -9
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +30 -9
- package/dist/generated/pricing-config.types.d.ts +14 -3
- 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 +11 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/integrations/better-auth.d.ts +23 -0
- package/dist/integrations/better-auth.d.ts.map +1 -0
- package/dist/integrations/better-auth.js +54 -0
- package/dist/integrations/better-auth.js.map +1 -0
- package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
- package/dist/load-config-file.d.ts.map +1 -0
- package/dist/{load-pricing-file.js → load-config-file.js} +23 -14
- package/dist/load-config-file.js.map +1 -0
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +3 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +2 -2
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +5 -0
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +77 -14
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts +29 -0
- package/dist/providers/dodo/better-auth.d.ts.map +1 -0
- package/dist/providers/dodo/better-auth.js +23 -0
- package/dist/providers/dodo/better-auth.js.map +1 -0
- package/dist/providers/dodo/client-contract.d.ts +32 -70
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +3 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +219 -148
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/index.d.ts +5 -2
- package/dist/providers/dodo/index.d.ts.map +1 -1
- package/dist/providers/dodo/index.js +2 -1
- package/dist/providers/dodo/index.js.map +1 -1
- package/dist/providers/dodo/nextjs.d.ts +16 -0
- package/dist/providers/dodo/nextjs.d.ts.map +1 -0
- package/dist/providers/dodo/nextjs.js +16 -0
- package/dist/providers/dodo/nextjs.js.map +1 -0
- package/dist/providers/dodo/provider.d.ts +30 -11
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +192 -122
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/react-native.d.ts +56 -0
- package/dist/providers/dodo/react-native.d.ts.map +1 -0
- package/dist/providers/dodo/react-native.js +57 -0
- package/dist/providers/dodo/react-native.js.map +1 -0
- package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
- package/dist/providers/dodo/webhook-bridge.js +21 -0
- package/dist/providers/dodo/webhook-bridge.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/index.d.ts +1 -0
- package/dist/providers/mock/index.d.ts.map +1 -1
- package/dist/providers/mock/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +8 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +26 -19
- 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 +214 -173
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/index.d.ts +1 -0
- package/dist/providers/stripe/index.d.ts.map +1 -1
- package/dist/providers/stripe/index.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +13 -11
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +287 -107
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +1 -2
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts +26 -4
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +65 -23
- package/dist/retry.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +7 -0
- package/dist/shared/diagnostics.d.ts.map +1 -0
- package/dist/shared/diagnostics.js +18 -0
- package/dist/shared/diagnostics.js.map +1 -0
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +43 -5
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +282 -30
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts +11 -0
- package/dist/shared/postgres-errors.d.ts.map +1 -0
- package/dist/shared/postgres-errors.js +105 -0
- package/dist/shared/postgres-errors.js.map +1 -0
- package/dist/shared/postgres-types.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts +15 -3
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +58 -14
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +18 -3
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +0 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +0 -2
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts +2 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +17 -3
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +1 -1
- 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 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +13 -3
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +35 -7
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +166 -53
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +62 -7
- package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
- package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
- package/dist/credits/postgres/repositories/pricing.js +0 -70
- package/dist/credits/postgres/repositories/pricing.js.map +0 -1
- package/dist/credits/pricing-runtime.d.ts.map +0 -1
- package/dist/credits/pricing-runtime.js.map +0 -1
- package/dist/load-pricing-file.d.ts.map +0 -1
- package/dist/load-pricing-file.js.map +0 -1
package/dist/credits/service.js
CHANGED
|
@@ -1,27 +1,33 @@
|
|
|
1
1
|
import Decimal from "decimal.js";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError } from "../errors.js";
|
|
3
|
+
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
4
4
|
import { raiseDeductError } from "./service-errors.js";
|
|
5
5
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
6
|
import { CreditQueries } from "./queries.js";
|
|
7
|
-
import {
|
|
7
|
+
import { CatalogRuntime, toDecimal } from "./catalog-runtime.js";
|
|
8
8
|
import { CreditLeaseWorkflow } from "./lease-workflow.js";
|
|
9
9
|
/**
|
|
10
|
-
* Default lease TTL (seconds) for ``reserve
|
|
10
|
+
* Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
|
|
11
11
|
* Long batch/agentic jobs call the configured lease TTL before this elapses.
|
|
12
12
|
*/
|
|
13
13
|
const DEFAULT_LEASE_TTL_SECONDS = 600;
|
|
14
14
|
const POLICY_PRESETS = new Set(["strict_prepaid", "overdraft"]);
|
|
15
|
+
function positiveAmount(value, operation) {
|
|
16
|
+
const amount = toDecimal(value);
|
|
17
|
+
if (!amount.isFinite() || !amount.gt(0)) {
|
|
18
|
+
throw new RangeError(`${operation} amount must be finite and greater than zero`);
|
|
19
|
+
}
|
|
20
|
+
return amount;
|
|
21
|
+
}
|
|
15
22
|
import { normalizeLogger } from "../shared/logger.js";
|
|
16
23
|
/**
|
|
17
24
|
* Orchestrates credit operations.
|
|
18
25
|
*
|
|
19
26
|
* The deduction path is a single atomic, idempotency-keyed store call
|
|
20
27
|
* (``deductWithAllowance``) that consumes free allowance, enforces plan policy,
|
|
21
|
-
* and debits the net amount in one transaction
|
|
22
|
-
* (contract §2). The manager is a thin layer that calculates the cost, maps
|
|
28
|
+
* and debits the net amount in one transaction. The service calculates the cost, maps
|
|
23
29
|
* the store's typed ``error`` codes to exceptions, and emits lifecycle events
|
|
24
|
-
* **only after** the operation has succeeded
|
|
30
|
+
* **only after** the operation has succeeded.
|
|
25
31
|
*
|
|
26
32
|
* Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events
|
|
27
33
|
* (deducted, deduct_failed, added, refunded, refund_failed, expired,
|
|
@@ -30,7 +36,7 @@ import { normalizeLogger } from "../shared/logger.js";
|
|
|
30
36
|
export class CreditsService {
|
|
31
37
|
store;
|
|
32
38
|
queries;
|
|
33
|
-
|
|
39
|
+
catalogRuntime;
|
|
34
40
|
leases;
|
|
35
41
|
emitter = null;
|
|
36
42
|
balanceMonitor;
|
|
@@ -52,10 +58,10 @@ export class CreditsService {
|
|
|
52
58
|
this.logger = normalizeLogger(options?.logger);
|
|
53
59
|
if (options?.postDeduction)
|
|
54
60
|
this.postDeductionHooks.add(options.postDeduction);
|
|
55
|
-
this.
|
|
61
|
+
this.catalogRuntime = new CatalogRuntime(store, engine ?? null, this.logger, options?.catalogCacheTtlMs ?? 300_000);
|
|
56
62
|
this.balanceMonitor = new LowBalanceMonitor(options?.lowBalance, (type, userId, data) => this.emit(type, userId, data), this.logger);
|
|
57
63
|
this.lazyExpiry = options?.lazyExpiry ?? false;
|
|
58
|
-
this.leases = new CreditLeaseWorkflow(store, this.
|
|
64
|
+
this.leases = new CreditLeaseWorkflow(store, this.catalogRuntime, this.logger, this.balanceMonitor, policy, options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null, options?.maxConcurrent ?? null, options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS, (type, userId, data) => this.emit(type, userId, data), (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey), (userId) => this.maybeLazyExpire(userId), (userId, result) => this.afterDeduction(userId, "settle", result));
|
|
59
65
|
}
|
|
60
66
|
/**
|
|
61
67
|
* Register an awaited post-commit deduction hook. A failing hook is logged
|
|
@@ -79,8 +85,8 @@ export class CreditsService {
|
|
|
79
85
|
}
|
|
80
86
|
}
|
|
81
87
|
}
|
|
82
|
-
async
|
|
83
|
-
return this.queries.
|
|
88
|
+
async getActiveCatalog() {
|
|
89
|
+
return this.queries.getActiveCatalog();
|
|
84
90
|
}
|
|
85
91
|
async getUserPlan(userId) {
|
|
86
92
|
return this.queries.getUserPlan(userId);
|
|
@@ -101,7 +107,16 @@ export class CreditsService {
|
|
|
101
107
|
return this.queries.migratePlanBatch(migrationId, batchSize);
|
|
102
108
|
}
|
|
103
109
|
async revokeCreditsByEntryType(userId, entryType) {
|
|
104
|
-
|
|
110
|
+
const result = await this.queries.revokeCreditsByEntryType(userId, entryType);
|
|
111
|
+
if (result.revoked.gt(0)) {
|
|
112
|
+
this.emit("credits.revoked", userId, {
|
|
113
|
+
userId,
|
|
114
|
+
entryType,
|
|
115
|
+
amount: result.revoked,
|
|
116
|
+
balanceAfter: result.balanceAfter,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return result;
|
|
105
120
|
}
|
|
106
121
|
/** Execute an application-driven catalog grant program. */
|
|
107
122
|
async executeGrantProgram(request) {
|
|
@@ -163,62 +178,58 @@ export class CreditsService {
|
|
|
163
178
|
}
|
|
164
179
|
}
|
|
165
180
|
}
|
|
166
|
-
/** Load
|
|
167
|
-
async
|
|
168
|
-
await this.
|
|
169
|
-
}
|
|
170
|
-
/** Load the active pricing config from the store. */
|
|
171
|
-
async loadPricingFromStore() {
|
|
172
|
-
await this.pricing.loadFromStore();
|
|
181
|
+
/** Load the active catalog revision from the store. */
|
|
182
|
+
async loadCatalogFromStore() {
|
|
183
|
+
await this.catalogRuntime.loadFromStore();
|
|
173
184
|
}
|
|
174
185
|
/**
|
|
175
186
|
* If the cached PricingEngine is stale (TTL expired), reload it from the
|
|
176
187
|
* store. Concurrent callers are deduplicated via the underlying
|
|
177
|
-
* ``lru-cache.fetch()`` — only one ``
|
|
188
|
+
* ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all
|
|
178
189
|
* callers await the same result.
|
|
179
190
|
*
|
|
180
|
-
* When ``
|
|
181
|
-
* ``
|
|
191
|
+
* When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call
|
|
192
|
+
* ``loadCatalogFromStore`` manually).
|
|
182
193
|
*/
|
|
183
|
-
async
|
|
184
|
-
await this.
|
|
194
|
+
async refreshCatalogIfStale() {
|
|
195
|
+
await this.catalogRuntime.refreshIfStale();
|
|
185
196
|
}
|
|
186
197
|
/**
|
|
187
|
-
* Invalidate the
|
|
188
|
-
* reloads from the store. Useful after a manual ``
|
|
198
|
+
* Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call
|
|
199
|
+
* reloads from the store. Useful after a manual ``loadCatalogFromStore``
|
|
189
200
|
* that bypasses the cache, or when the consumer knows the remote config
|
|
190
201
|
* has changed.
|
|
191
202
|
*/
|
|
192
|
-
|
|
193
|
-
this.
|
|
203
|
+
invalidateCatalog() {
|
|
204
|
+
this.catalogRuntime.invalidate();
|
|
194
205
|
}
|
|
195
206
|
/**
|
|
196
|
-
* Publish
|
|
207
|
+
* Publish and activate a catalog revision, then update the local engine.
|
|
197
208
|
*
|
|
198
|
-
*
|
|
209
|
+
* The store write is awaited, so
|
|
199
210
|
* a persistence failure surfaces to the caller instead of becoming an
|
|
200
211
|
* unhandled promise rejection.
|
|
201
212
|
*/
|
|
202
|
-
async
|
|
203
|
-
|
|
213
|
+
async publishAndActivateCatalog(config, label, rollout) {
|
|
214
|
+
return this.catalogRuntime.publishAndActivate(config, label, rollout);
|
|
204
215
|
}
|
|
205
216
|
/** Publish a validated, inactive catalog draft. */
|
|
206
|
-
async
|
|
207
|
-
return this.
|
|
217
|
+
async publishCatalogDraft(config, label) {
|
|
218
|
+
return this.catalogRuntime.publishDraft(config, label);
|
|
208
219
|
}
|
|
209
220
|
/** Activate an existing catalog version and reload the local engine. */
|
|
210
|
-
async
|
|
211
|
-
return this.
|
|
221
|
+
async activateCatalogRevision(version, rollout) {
|
|
222
|
+
return this.catalogRuntime.activateRevision(version, rollout);
|
|
212
223
|
}
|
|
213
224
|
/** The current PricingEngine, or null if not loaded. */
|
|
214
225
|
get pricingEngine() {
|
|
215
|
-
return this.
|
|
226
|
+
return this.catalogRuntime.currentEngine;
|
|
216
227
|
}
|
|
217
228
|
/**
|
|
218
229
|
* Set a user's subscription plan and emit ``credits.plan_changed``.
|
|
219
230
|
*
|
|
220
231
|
* The store call is awaited so a persistence failure surfaces to the caller.
|
|
221
|
-
* The event is emitted only after the store write succeeds
|
|
232
|
+
* The event is emitted only after the store write succeeds.
|
|
222
233
|
*/
|
|
223
234
|
async setUserPlan(userId, planKey, planAssignedAt) {
|
|
224
235
|
this.logger.info("[CreditsService] setUserPlan", { planKey, planAssignedAt });
|
|
@@ -226,18 +237,29 @@ export class CreditsService {
|
|
|
226
237
|
this.emit("credits.plan_changed", userId, {
|
|
227
238
|
userId,
|
|
228
239
|
planKey,
|
|
229
|
-
planAssignedAt: result.planAssignedAt
|
|
240
|
+
planAssignedAt: result.planAssignedAt,
|
|
241
|
+
assignmentState: result.assignmentState,
|
|
230
242
|
timestamp: new Date().toISOString(),
|
|
231
243
|
});
|
|
244
|
+
return result;
|
|
232
245
|
}
|
|
233
246
|
/** Unset a user's subscription plan and emit the plan-change event. */
|
|
234
247
|
async unsetUserPlan(userId) {
|
|
235
|
-
await this.store.unsetUserPlan(userId);
|
|
248
|
+
const result = await this.store.unsetUserPlan(userId);
|
|
236
249
|
this.emit("credits.plan_changed", userId, {
|
|
237
250
|
userId,
|
|
238
251
|
planKey: null,
|
|
239
252
|
timestamp: new Date().toISOString(),
|
|
240
253
|
});
|
|
254
|
+
return result;
|
|
255
|
+
}
|
|
256
|
+
/** Pin or unpin the user's current assignment revision. */
|
|
257
|
+
async setPlanRevisionPin(userId, pinned) {
|
|
258
|
+
return this.store.setPlanRevisionPin(userId, pinned);
|
|
259
|
+
}
|
|
260
|
+
/** Apply one bounded batch of renewal-effective plan changes. */
|
|
261
|
+
async applyDuePlanChanges(limit = 100) {
|
|
262
|
+
return this.store.applyDuePlanChanges(limit);
|
|
241
263
|
}
|
|
242
264
|
/** Sweep this user's expired lots when lazy expiry is enabled. */
|
|
243
265
|
async maybeLazyExpire(userId) {
|
|
@@ -253,7 +275,7 @@ export class CreditsService {
|
|
|
253
275
|
async addCredits(userId, amount, options) {
|
|
254
276
|
const type = options?.type ?? "adjustment";
|
|
255
277
|
this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options?.bucket });
|
|
256
|
-
const result = await this.store.addCredits(userId,
|
|
278
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
|
|
257
279
|
this.emit("credits.added", userId, {
|
|
258
280
|
entryId: result.entryId,
|
|
259
281
|
amount: result.amount,
|
|
@@ -279,21 +301,27 @@ export class CreditsService {
|
|
|
279
301
|
entryType,
|
|
280
302
|
bucket: options?.bucket,
|
|
281
303
|
});
|
|
282
|
-
const result = await this.store.addCredits(userId,
|
|
304
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
|
|
283
305
|
this.emit("credits.deducted", userId, {
|
|
284
306
|
entryId: result.entryId,
|
|
285
307
|
amount: result.amount,
|
|
286
308
|
newBalance: result.newBalance,
|
|
287
309
|
entryType,
|
|
288
|
-
});
|
|
289
|
-
await this.afterDeduction(userId, "raw", {
|
|
290
|
-
entryId: result.entryId,
|
|
291
|
-
userId,
|
|
292
|
-
amount: result.amount.abs(),
|
|
293
|
-
allowanceConsumed: new Decimal(0),
|
|
294
|
-
balanceAfter: result.newBalance,
|
|
295
310
|
idempotent: result.idempotent ?? false,
|
|
296
311
|
});
|
|
312
|
+
if (!result.idempotent) {
|
|
313
|
+
await this.afterDeduction(userId, "raw", {
|
|
314
|
+
entryId: result.entryId,
|
|
315
|
+
userId,
|
|
316
|
+
amount: result.amount.abs(),
|
|
317
|
+
allowanceConsumed: new Decimal(0),
|
|
318
|
+
balanceAfter: result.newBalance,
|
|
319
|
+
idempotent: false,
|
|
320
|
+
usageChargeId: null,
|
|
321
|
+
error: null,
|
|
322
|
+
bucketBreakdown: null,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
297
325
|
return result;
|
|
298
326
|
}
|
|
299
327
|
/**
|
|
@@ -304,14 +332,12 @@ export class CreditsService {
|
|
|
304
332
|
* 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
|
|
305
333
|
* ``ConfigError`` otherwise).
|
|
306
334
|
* 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
|
|
307
|
-
* 3.
|
|
308
|
-
* ``bucket`` is expired immediately via a direct ``store.addCredits``
|
|
309
|
-
* negative adjustment — naturally idempotent (a replay finds the bucket
|
|
310
|
-
* already at zero and skips the call).
|
|
311
|
-
* 4. The new cycle is granted via a direct ``store.addCredits`` call
|
|
335
|
+
* 3. The new cycle is granted via a direct ``store.addCredits`` call
|
|
312
336
|
* (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
|
|
313
337
|
* not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
|
|
314
338
|
* redelivered webhook replays the prior grant instead of double-crediting.
|
|
339
|
+
* 4. Existing bucket credits are never removed here. Subscription renewal
|
|
340
|
+
* policies that replace prior lots run atomically through BillingService.
|
|
315
341
|
* 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
|
|
316
342
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
317
343
|
*/
|
|
@@ -325,32 +351,21 @@ export class CreditsService {
|
|
|
325
351
|
throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
|
|
326
352
|
}
|
|
327
353
|
const bucket = options?.bucket ?? "subscription";
|
|
328
|
-
const replacePrior = options?.replacePrior ?? true;
|
|
329
354
|
const expiresAt = options?.ttlDays != null
|
|
330
355
|
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
331
356
|
: options?.expiresAt;
|
|
332
|
-
const amountDec =
|
|
333
|
-
|
|
334
|
-
// webhook must skip the replace-prior wipe as well as the duplicate grant.
|
|
335
|
-
let priorLeftover = new Decimal(0);
|
|
336
|
-
if (replacePrior) {
|
|
337
|
-
const bucketsBefore = await this.getBucketBalances(userId);
|
|
338
|
-
const current = bucketsBefore.buckets.find((t) => t.bucketKey === bucket);
|
|
339
|
-
if (current)
|
|
340
|
-
priorLeftover = current.balance;
|
|
341
|
-
}
|
|
342
|
-
let result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
|
|
357
|
+
const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
|
|
358
|
+
const result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
|
|
343
359
|
// The store contract exposes the mutation's replay result directly, avoiding
|
|
344
360
|
// a racy lifetime-balance comparison and an extra database round trip.
|
|
345
361
|
const isFreshGrant = !result.idempotent;
|
|
346
|
-
if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
|
|
347
|
-
await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, bucket);
|
|
348
|
-
// Reflect the post-replace balance so the returned result is accurate
|
|
349
|
-
// (the grant call above only knows the pre-replace balance).
|
|
350
|
-
result = { ...result, newBalance: (await this.getBalance(userId)).balance };
|
|
351
|
-
}
|
|
352
362
|
if (options?.planKey) {
|
|
353
|
-
|
|
363
|
+
// A fresh cycle intentionally re-anchors plan-assignment windows. On a
|
|
364
|
+
// webhook replay, repair a previously interrupted grant->assignment saga
|
|
365
|
+
// without re-anchoring an assignment that already succeeded.
|
|
366
|
+
if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
|
|
367
|
+
await this.setUserPlan(userId, options.planKey);
|
|
368
|
+
}
|
|
354
369
|
}
|
|
355
370
|
this.emit("credits.cycle_renewed", userId, {
|
|
356
371
|
entryId: result.entryId,
|
|
@@ -359,10 +374,11 @@ export class CreditsService {
|
|
|
359
374
|
bucket,
|
|
360
375
|
planKey: options?.planKey ?? null,
|
|
361
376
|
idempotencyKey: options?.idempotencyKey ?? null,
|
|
377
|
+
idempotent: result.idempotent,
|
|
362
378
|
});
|
|
363
379
|
return result;
|
|
364
380
|
}
|
|
365
|
-
// ── Lease lifecycle: atomic admission
|
|
381
|
+
// ── Lease lifecycle: atomic admission ───────────────────────────────
|
|
366
382
|
async reserve(userId, metricsOrAmount, options) {
|
|
367
383
|
return this.leases.reserve(userId, metricsOrAmount, options);
|
|
368
384
|
}
|
|
@@ -391,7 +407,7 @@ export class CreditsService {
|
|
|
391
407
|
return this.leases.beginBilledOperation(userId, options);
|
|
392
408
|
}
|
|
393
409
|
/**
|
|
394
|
-
* Full deduction flow as one atomic store call
|
|
410
|
+
* Full deduction flow as one atomic store call.
|
|
395
411
|
*
|
|
396
412
|
* 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
|
|
397
413
|
* (exact `Decimal`, **no truncation**).
|
|
@@ -401,22 +417,23 @@ export class CreditsService {
|
|
|
401
417
|
* On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
|
|
402
418
|
* typed exception is thrown. No success event is emitted on error.
|
|
403
419
|
*/
|
|
404
|
-
async deduct(userId, metrics,
|
|
405
|
-
/** Entitlement feature required for this operation. */
|
|
406
|
-
feature) {
|
|
420
|
+
async deduct(userId, metrics, options) {
|
|
407
421
|
await this.maybeLazyExpire(userId);
|
|
408
|
-
this.logger.debug("[CreditsService] deduct", {
|
|
409
|
-
|
|
422
|
+
this.logger.debug("[CreditsService] deduct", {
|
|
423
|
+
model: metrics.dimensions?.model,
|
|
424
|
+
feature: options?.feature,
|
|
425
|
+
});
|
|
426
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
410
427
|
const plan = await this.store.getUserPlan(userId);
|
|
411
|
-
const effectiveIdempotencyKey = idempotencyKey ?? `usage:${randomUUID()}`;
|
|
412
|
-
// 1) Calculate cost
|
|
428
|
+
const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
|
|
429
|
+
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
413
430
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
414
431
|
const cost = breakdown.total;
|
|
415
432
|
// Build ledger metadata: caller fields FIRST, system fields LAST so the
|
|
416
|
-
// system fields win
|
|
433
|
+
// protected system fields win.
|
|
417
434
|
const meta = {};
|
|
418
|
-
if (metadata) {
|
|
419
|
-
for (const [k, v] of Object.entries(metadata)) {
|
|
435
|
+
if (options?.metadata) {
|
|
436
|
+
for (const [k, v] of Object.entries(options.metadata)) {
|
|
420
437
|
if (v != null)
|
|
421
438
|
meta[k] = v;
|
|
422
439
|
}
|
|
@@ -426,10 +443,10 @@ export class CreditsService {
|
|
|
426
443
|
meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
|
|
427
444
|
meta["breakdownTotal"] = breakdown.total.toString();
|
|
428
445
|
meta["idempotencyKey"] = effectiveIdempotencyKey;
|
|
429
|
-
const
|
|
446
|
+
const deductionOptions = {
|
|
430
447
|
idempotencyKey: effectiveIdempotencyKey,
|
|
431
448
|
operation: metrics.operation,
|
|
432
|
-
feature: feature ?? null,
|
|
449
|
+
feature: options?.feature ?? null,
|
|
433
450
|
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
434
451
|
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
435
452
|
measures: { ...(metrics.measures ?? {}) },
|
|
@@ -438,8 +455,8 @@ export class CreditsService {
|
|
|
438
455
|
};
|
|
439
456
|
// 2) Atomic charge. This records zero-cost usage too, so authorization,
|
|
440
457
|
// quotas, and usage history cannot be bypassed by a free rate.
|
|
441
|
-
const result = await this.store.deductWithAllowance(userId, cost,
|
|
442
|
-
if (result.error) {
|
|
458
|
+
const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);
|
|
459
|
+
if (result.error !== null) {
|
|
443
460
|
if (result.error === "quota_exceeded") {
|
|
444
461
|
await this.emitQuotaEvents(userId, effectiveIdempotencyKey);
|
|
445
462
|
}
|
|
@@ -447,7 +464,7 @@ export class CreditsService {
|
|
|
447
464
|
error: result.error,
|
|
448
465
|
amount: cost,
|
|
449
466
|
model: metrics.dimensions?.model,
|
|
450
|
-
feature,
|
|
467
|
+
feature: options?.feature,
|
|
451
468
|
});
|
|
452
469
|
this.emit("credits.deduct_failed", userId, {
|
|
453
470
|
error: result.error,
|
|
@@ -465,7 +482,7 @@ export class CreditsService {
|
|
|
465
482
|
model: metrics.dimensions?.model ?? null,
|
|
466
483
|
idempotent: result.idempotent,
|
|
467
484
|
});
|
|
468
|
-
// low_balance is
|
|
485
|
+
// low_balance is edge-triggered: only fire when this deduction crossed
|
|
469
486
|
// the threshold. A replayed (idempotent) result did not move the balance, so
|
|
470
487
|
// it never crosses. balanceBefore = balanceAfter + amount charged.
|
|
471
488
|
if (!result.idempotent) {
|
|
@@ -476,6 +493,43 @@ export class CreditsService {
|
|
|
476
493
|
}
|
|
477
494
|
return result;
|
|
478
495
|
}
|
|
496
|
+
/**
|
|
497
|
+
* Record priced usage for a workflow without debiting the account again.
|
|
498
|
+
*
|
|
499
|
+
* This supports priced usage receipts that should be retained without
|
|
500
|
+
* affecting the account balance, such as externally billed usage.
|
|
501
|
+
*/
|
|
502
|
+
async recordUsage(userId, metrics, options) {
|
|
503
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
504
|
+
const plan = await this.store.getUserPlan(userId);
|
|
505
|
+
const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
|
|
506
|
+
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
507
|
+
const meta = {};
|
|
508
|
+
if (options?.metadata) {
|
|
509
|
+
for (const [key, value] of Object.entries(options.metadata)) {
|
|
510
|
+
if (value != null)
|
|
511
|
+
meta[key] = value;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
meta.operation = metrics.operation;
|
|
515
|
+
meta.measures = { ...(metrics.measures ?? {}) };
|
|
516
|
+
meta.dimensions = { ...(metrics.dimensions ?? {}) };
|
|
517
|
+
meta.breakdownTotal = breakdown.total.toString();
|
|
518
|
+
meta.idempotencyKey = effectiveIdempotencyKey;
|
|
519
|
+
const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
|
|
520
|
+
idempotencyKey: effectiveIdempotencyKey,
|
|
521
|
+
operation: metrics.operation,
|
|
522
|
+
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
523
|
+
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
524
|
+
measures: { ...(metrics.measures ?? {}) },
|
|
525
|
+
dimensions: { ...(metrics.dimensions ?? {}) },
|
|
526
|
+
metadata: meta,
|
|
527
|
+
});
|
|
528
|
+
if (result.error !== null) {
|
|
529
|
+
throw new StoreError(`Usage record failed: ${result.error}`);
|
|
530
|
+
}
|
|
531
|
+
return result;
|
|
532
|
+
}
|
|
479
533
|
/**
|
|
480
534
|
* Refund a previous credit deduction.
|
|
481
535
|
*
|
|
@@ -485,23 +539,29 @@ export class CreditsService {
|
|
|
485
539
|
* refund).
|
|
486
540
|
*/
|
|
487
541
|
/** Deduct the configured fixed cost for one named job. */
|
|
488
|
-
async deductFlatJob(userId, jobName,
|
|
489
|
-
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } },
|
|
490
|
-
}
|
|
491
|
-
async refundCredits(entryId,
|
|
492
|
-
const refundAmount = amount != null ?
|
|
493
|
-
this.logger.info("[CreditsService] refundCredits", {
|
|
494
|
-
|
|
495
|
-
|
|
542
|
+
async deductFlatJob(userId, jobName, options) {
|
|
543
|
+
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
|
|
544
|
+
}
|
|
545
|
+
async refundCredits(entryId, options) {
|
|
546
|
+
const refundAmount = options?.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
|
|
547
|
+
this.logger.info("[CreditsService] refundCredits", {
|
|
548
|
+
entryId,
|
|
549
|
+
refundAmount,
|
|
550
|
+
reason: options?.reason,
|
|
551
|
+
});
|
|
552
|
+
const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
|
|
553
|
+
if (result.error !== null) {
|
|
496
554
|
this.logger.warn("[CreditsService] refundCredits failed", {
|
|
497
555
|
entryId,
|
|
498
556
|
error: result.error,
|
|
499
557
|
});
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
558
|
+
if (result.userId !== null) {
|
|
559
|
+
this.emit("credits.refund_failed", result.userId, {
|
|
560
|
+
entryId,
|
|
561
|
+
error: result.error,
|
|
562
|
+
reason: options?.reason ?? null,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
505
565
|
throw new RefundError(`Refund rejected: ${result.error}`);
|
|
506
566
|
}
|
|
507
567
|
this.emit("credits.refunded", result.userId, {
|
|
@@ -509,7 +569,7 @@ export class CreditsService {
|
|
|
509
569
|
refundEntryId: result.refundEntryId,
|
|
510
570
|
amount: result.amount,
|
|
511
571
|
newBalance: result.newBalance,
|
|
512
|
-
reason: reason ?? null,
|
|
572
|
+
reason: options?.reason ?? null,
|
|
513
573
|
});
|
|
514
574
|
return result;
|
|
515
575
|
}
|
|
@@ -518,38 +578,43 @@ export class CreditsService {
|
|
|
518
578
|
*
|
|
519
579
|
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
520
580
|
* then debits the team balance. Threads an optional ``idempotencyKey`` through
|
|
521
|
-
* to the store so retried team charges are not double-counted
|
|
581
|
+
* to the store so retried team charges are not double-counted.
|
|
522
582
|
*/
|
|
523
|
-
async deductTeam(teamId, userId, metrics,
|
|
583
|
+
async deductTeam(teamId, userId, metrics, options) {
|
|
524
584
|
await this.maybeLazyExpire(userId);
|
|
525
585
|
// Lazy expiry is scoped to the individual member's credits, not the team's
|
|
526
586
|
// shared pool — there's no per-team expiry concept.
|
|
527
|
-
const engine = await this.
|
|
587
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
528
588
|
const plan = await this.store.getUserPlan(userId);
|
|
529
589
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
530
590
|
const cost = breakdown.total;
|
|
531
591
|
if (cost.lte(0)) {
|
|
532
592
|
const teamBal = await this.store.getTeamBalance(teamId);
|
|
593
|
+
if (teamBal === null) {
|
|
594
|
+
throw new StoreError(`Team not found: ${teamId}`);
|
|
595
|
+
}
|
|
533
596
|
return {
|
|
534
|
-
entryId:
|
|
597
|
+
entryId: null,
|
|
535
598
|
teamId,
|
|
536
599
|
userId,
|
|
537
600
|
amount: new Decimal(0),
|
|
538
601
|
teamBalanceAfter: teamBal.balance,
|
|
602
|
+
idempotent: false,
|
|
603
|
+
error: null,
|
|
539
604
|
};
|
|
540
605
|
}
|
|
541
606
|
const teamMetadata = {
|
|
542
|
-
...(metadata ?? {}),
|
|
607
|
+
...(options?.metadata ?? {}),
|
|
543
608
|
operation: metrics.operation,
|
|
544
609
|
measures: { ...(metrics.measures ?? {}) },
|
|
545
610
|
dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
|
|
546
611
|
breakdownTotal: breakdown.total.toString(),
|
|
547
612
|
};
|
|
548
|
-
const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, idempotencyKey);
|
|
549
|
-
//
|
|
613
|
+
const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, options?.idempotencyKey);
|
|
614
|
+
// Surface store errors: emit credits.deduct_failed and throw,
|
|
550
615
|
// mirroring the Python credit service implementation. Previously returned a silent
|
|
551
616
|
// success-shaped object with an .error field, so failed charges looked OK.
|
|
552
|
-
if (result.error) {
|
|
617
|
+
if (result.error !== null) {
|
|
553
618
|
this.emit("credits.deduct_failed", userId, {
|
|
554
619
|
error: result.error,
|
|
555
620
|
amount: cost,
|