@zonastery/bursar 2.0.6 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -4
- package/dist/billing/auto-recharge-port.d.ts +11 -0
- package/dist/billing/auto-recharge-port.d.ts.map +1 -1
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +53 -26
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +38 -3
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +51 -7
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +34 -9
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +35 -3
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +1 -2
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +69 -29
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +2 -2
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +82 -19
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +168 -44
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +16 -3
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +11 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +13 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +71 -12
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +33 -3
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +5 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +7 -10
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +6 -1
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +25 -16
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js +25 -4
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +3 -2
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +44 -48
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +6 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +27 -10
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +46 -34
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +152 -126
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +0 -1
- package/dist/billing/service-types.d.ts.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +2 -0
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -0
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +15 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +2 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +15 -0
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +12 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +2 -24
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -29
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts +13 -21
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +44 -50
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +21 -2
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +27 -4
- package/dist/catalog.js.map +1 -1
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +147 -0
- package/dist/cli.js.map +1 -0
- package/dist/commerce/plan-change.d.ts +3 -3
- package/dist/commerce/plan-change.d.ts.map +1 -1
- package/dist/commerce/plan-change.js +14 -7
- package/dist/commerce/plan-change.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js +8 -2
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts +2 -0
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +330 -76
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +12 -3
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/availability.d.ts +4 -0
- package/dist/config/availability.d.ts.map +1 -0
- package/dist/config/availability.js +10 -0
- package/dist/config/availability.js.map +1 -0
- package/dist/config/normalize.d.ts +7 -0
- package/dist/config/normalize.d.ts.map +1 -0
- package/dist/config/normalize.js +119 -0
- package/dist/config/normalize.js.map +1 -0
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +4 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts +5 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +79 -22
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +10 -7
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +31 -15
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +42 -27
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +4 -0
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +26 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +8 -4
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +5 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +118 -70
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +5 -4
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +15 -2
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +77 -21
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +3 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +47 -38
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -7
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +6 -57
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +25 -7
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts +28 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +33 -14
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +2 -2
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +2 -12
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +9 -2
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +3 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +46 -12
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +6 -1
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +13 -3
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +1 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +9 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +30 -20
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +335 -251
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +4 -4
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/rated-wire.d.ts +7 -0
- package/dist/credits/rated-wire.d.ts.map +1 -0
- package/dist/credits/rated-wire.js +70 -0
- package/dist/credits/rated-wire.js.map +1 -0
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +8 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +5 -7
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +12 -9
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +161 -138
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +11 -3
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +9 -0
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +9 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/admission.d.ts +1 -0
- package/dist/credits/types/admission.d.ts.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +1 -0
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.d.ts +12 -0
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +13 -0
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/quotas.d.ts +2 -1
- package/dist/credits/types/quotas.d.ts.map +1 -1
- package/dist/credits/types/quotas.js.map +1 -1
- package/dist/engine.d.ts +4 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +59 -36
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +12 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +29 -9
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/language.js +1 -1
- package/dist/expr/language.js.map +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +5 -6
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +272 -228
- package/dist/generated/pricing-config.types.d.ts +128 -79
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +5 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +56 -17
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +2 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -1
- package/dist/node.js.map +1 -1
- package/dist/pricing-decimal.d.ts +7 -0
- package/dist/pricing-decimal.d.ts.map +1 -0
- package/dist/pricing-decimal.js +43 -0
- package/dist/pricing-decimal.js.map +1 -0
- package/dist/providers/dodo/better-auth-core.d.ts +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth-core.js +2 -2
- package/dist/providers/dodo/better-auth-core.js.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -2
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +124 -18
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs-core.js +2 -2
- package/dist/providers/dodo/nextjs-core.js.map +1 -1
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +16 -6
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +5 -2
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +46 -7
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
- package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
- package/dist/providers/dodo/verified-payment-payload.js +42 -0
- package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +4 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +3 -1
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +51 -24
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +4 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +118 -34
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +16 -2
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +9 -0
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +5 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +72 -11
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js +6 -0
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/provider-rejection.d.ts +3 -0
- package/dist/shared/provider-rejection.d.ts.map +1 -0
- package/dist/shared/provider-rejection.js +17 -0
- package/dist/shared/provider-rejection.js.map +1 -0
- package/dist/shared/timestamp.d.ts +5 -0
- package/dist/shared/timestamp.d.ts.map +1 -0
- package/dist/shared/timestamp.js +21 -0
- package/dist/shared/timestamp.js.map +1 -0
- package/dist/starter.yaml +17 -0
- package/dist/storage/adapters/clickhouse.d.ts +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +42 -37
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +5 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +46 -14
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +3 -7
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js +6 -15
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +4 -3
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +8 -0
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +1 -3
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +34 -12
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/raw-json.d.ts +10 -0
- package/dist/storage/raw-json.d.ts.map +1 -0
- package/dist/storage/raw-json.js +19 -0
- package/dist/storage/raw-json.js.map +1 -0
- package/dist/storage/runtime.d.ts +15 -10
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +97 -68
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/package.json +78 -71
- package/dist/credits/queries.d.ts +0 -33
- package/dist/credits/queries.d.ts.map +0 -1
- package/dist/credits/queries.js +0 -71
- package/dist/credits/queries.js.map +0 -1
package/dist/credits/service.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Decimal } from "decimal.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
3
|
+
import { CapReachedError, ConfigError, IdempotencyConflictError, InsufficientCreditsError, OperationNotAllowedError, RefundError, StoreError, } from "../errors.js";
|
|
4
4
|
import { raiseDeductError } from "./service-errors.js";
|
|
5
5
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
|
-
import { CreditQueries } from "./queries.js";
|
|
7
6
|
import { CatalogRuntime } from "./catalog-runtime.js";
|
|
8
7
|
import { toDecimal } from "./amount.js";
|
|
8
|
+
import { ratedMeasures, ratedDimensions, callerMetadata } from "./rated-wire.js";
|
|
9
9
|
import { CreditLeaseWorkflow } from "./lease-workflow.js";
|
|
10
10
|
import { requireStableKey } from "../shared/idempotency.js";
|
|
11
11
|
import { getDefaultInstrumentation } from "../telemetry/index.js";
|
|
@@ -37,8 +37,16 @@ import { normalizeLogger } from "../shared/logger.js";
|
|
|
37
37
|
* low_balance).
|
|
38
38
|
*/
|
|
39
39
|
export class CreditsService {
|
|
40
|
+
/** Look up a durable charge or lease after an ambiguous outcome. */
|
|
41
|
+
async getOperationReceipt(userId, key, kind) {
|
|
42
|
+
return this.store.getOperationReceipt(userId, requireStableKey(key), kind);
|
|
43
|
+
}
|
|
40
44
|
store;
|
|
41
|
-
|
|
45
|
+
get providerEnvironment() {
|
|
46
|
+
return this.store.providerEnvironment;
|
|
47
|
+
}
|
|
48
|
+
analytics;
|
|
49
|
+
usageStore;
|
|
42
50
|
catalogRuntime;
|
|
43
51
|
leases;
|
|
44
52
|
emitter = null;
|
|
@@ -53,7 +61,8 @@ export class CreditsService {
|
|
|
53
61
|
constructor(store, engine, emitter, options) {
|
|
54
62
|
this.store = store;
|
|
55
63
|
this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
|
|
56
|
-
this.
|
|
64
|
+
this.analytics = options?.analytics ?? store;
|
|
65
|
+
this.usageStore = options?.usageStore ?? store;
|
|
57
66
|
const policy = options?.policy ?? "strict_prepaid";
|
|
58
67
|
if (!POLICY_PRESETS.has(policy)) {
|
|
59
68
|
throw new ConfigError(`unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(", ")}`);
|
|
@@ -91,28 +100,28 @@ export class CreditsService {
|
|
|
91
100
|
}
|
|
92
101
|
}
|
|
93
102
|
async getActiveCatalog() {
|
|
94
|
-
return this.
|
|
103
|
+
return this.store.getActiveCatalog();
|
|
95
104
|
}
|
|
96
105
|
async getUserPlan(userId) {
|
|
97
|
-
return this.
|
|
106
|
+
return this.store.getUserPlan(userId);
|
|
98
107
|
}
|
|
99
108
|
async checkFeature(userId, feature) {
|
|
100
|
-
return this.
|
|
109
|
+
return this.store.checkFeature(userId, feature);
|
|
101
110
|
}
|
|
102
111
|
async getQuotaState(userId, quotaKey) {
|
|
103
|
-
return this.
|
|
112
|
+
return this.store.getQuotaState(userId, quotaKey);
|
|
104
113
|
}
|
|
105
114
|
async listQuotaEvents(userId, options) {
|
|
106
|
-
return this.
|
|
115
|
+
return this.store.listQuotaEvents(userId, options);
|
|
107
116
|
}
|
|
108
117
|
async startPlanMigration(fromPlanId, toPlanId) {
|
|
109
|
-
return this.
|
|
118
|
+
return this.store.startPlanMigration(fromPlanId, toPlanId);
|
|
110
119
|
}
|
|
111
120
|
async migratePlanBatch(migrationId, batchSize) {
|
|
112
|
-
return this.
|
|
121
|
+
return this.store.migratePlanBatch(migrationId, batchSize);
|
|
113
122
|
}
|
|
114
123
|
async revokeCreditsByEntryType(userId, entryType) {
|
|
115
|
-
const result = await this.
|
|
124
|
+
const result = await this.store.revokeCreditsByEntryType(userId, entryType);
|
|
116
125
|
if (result.revoked.gt(0)) {
|
|
117
126
|
this.emit("credits.revoked", userId, {
|
|
118
127
|
userId,
|
|
@@ -120,6 +129,7 @@ export class CreditsService {
|
|
|
120
129
|
amount: result.revoked,
|
|
121
130
|
balanceAfter: result.balanceAfter,
|
|
122
131
|
});
|
|
132
|
+
await this.balanceMonitor.signalCrossing(userId, result.balanceAfter.plus(result.revoked), result.balanceAfter);
|
|
123
133
|
}
|
|
124
134
|
return result;
|
|
125
135
|
}
|
|
@@ -128,44 +138,57 @@ export class CreditsService {
|
|
|
128
138
|
return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
|
|
129
139
|
}
|
|
130
140
|
async getLedgerEntry(userId, entryId) {
|
|
131
|
-
return this.
|
|
141
|
+
return this.store.getLedgerEntry(userId, entryId);
|
|
132
142
|
}
|
|
133
143
|
async getAvailable(userId) {
|
|
134
|
-
return this.
|
|
144
|
+
return this.store.getAvailable(userId);
|
|
135
145
|
}
|
|
136
146
|
async aggregateStats(start, end) {
|
|
137
|
-
return this.
|
|
147
|
+
return this.analytics.aggregateStats(start, end);
|
|
138
148
|
}
|
|
139
149
|
async spendByUser(start, end) {
|
|
140
|
-
return this.
|
|
150
|
+
return this.analytics.spendByUser(start, end);
|
|
141
151
|
}
|
|
142
152
|
async spendByModel(start, end) {
|
|
143
|
-
return this.
|
|
153
|
+
return this.analytics.spendByModel(start, end);
|
|
144
154
|
}
|
|
145
155
|
async listLedgerEntries(userId, options) {
|
|
146
|
-
return this.
|
|
156
|
+
return this.store.listLedgerEntries(userId, options);
|
|
147
157
|
}
|
|
148
158
|
async listUsageEntries(userId, options) {
|
|
149
|
-
return this.
|
|
159
|
+
return this.store.listUsageEntries(userId, options);
|
|
150
160
|
}
|
|
151
161
|
async listUsageCharges(userId, options) {
|
|
152
|
-
return this.
|
|
162
|
+
return this.usageStore.listUsageCharges(userId, options);
|
|
153
163
|
}
|
|
154
164
|
async topUsers(limit, start, end) {
|
|
155
|
-
return this.
|
|
165
|
+
return this.analytics.topUsers(limit, start, end);
|
|
156
166
|
}
|
|
157
167
|
async dailySpend(start, end) {
|
|
158
|
-
return this.
|
|
168
|
+
return this.analytics.dailySpend(start, end);
|
|
159
169
|
}
|
|
160
170
|
/** Emit a credit lifecycle event. No-op if no emitter is configured. */
|
|
161
171
|
emit(type, userId, data) {
|
|
162
172
|
this.emitter?.emit({ type, timestamp: new Date(), userId, data });
|
|
163
173
|
}
|
|
164
174
|
async emitQuotaEvents(userId, idempotencyKey) {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
175
|
+
if (!this.emitter)
|
|
176
|
+
return;
|
|
177
|
+
let events;
|
|
178
|
+
try {
|
|
179
|
+
events = await this.store.listQuotaEvents(userId, {
|
|
180
|
+
idempotencyKey,
|
|
181
|
+
limit: 100,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
this.logger.warn("[CreditsService] failed to fetch quota events", {
|
|
186
|
+
userId,
|
|
187
|
+
idempotencyKey,
|
|
188
|
+
error: error instanceof Error ? error.message : String(error),
|
|
189
|
+
});
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
169
192
|
for (const event of events) {
|
|
170
193
|
const data = {
|
|
171
194
|
quotaKey: event.quotaKey,
|
|
@@ -237,7 +260,10 @@ export class CreditsService {
|
|
|
237
260
|
* The event is emitted only after the store write succeeds.
|
|
238
261
|
*/
|
|
239
262
|
async setUserPlan(userId, planKey, planAssignedAt) {
|
|
240
|
-
this.logger.info("[CreditsService] setUserPlan", {
|
|
263
|
+
this.logger.info("[CreditsService] setUserPlan", {
|
|
264
|
+
planKey,
|
|
265
|
+
planAssignedAt,
|
|
266
|
+
});
|
|
241
267
|
const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);
|
|
242
268
|
this.emit("credits.plan_changed", userId, {
|
|
243
269
|
userId,
|
|
@@ -283,7 +309,11 @@ export class CreditsService {
|
|
|
283
309
|
async addCreditsUninstrumented(userId, amount, options) {
|
|
284
310
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
285
311
|
const type = options.type ?? "adjustment";
|
|
286
|
-
this.logger.info("[CreditsService] addCredits", {
|
|
312
|
+
this.logger.info("[CreditsService] addCredits", {
|
|
313
|
+
amount,
|
|
314
|
+
type,
|
|
315
|
+
bucket: options.bucket,
|
|
316
|
+
});
|
|
287
317
|
const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
|
|
288
318
|
...options,
|
|
289
319
|
type,
|
|
@@ -296,7 +326,6 @@ export class CreditsService {
|
|
|
296
326
|
type,
|
|
297
327
|
idempotent: result.idempotent ?? false,
|
|
298
328
|
});
|
|
299
|
-
this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);
|
|
300
329
|
return result;
|
|
301
330
|
}
|
|
302
331
|
/**
|
|
@@ -329,6 +358,7 @@ export class CreditsService {
|
|
|
329
358
|
idempotent: result.idempotent ?? false,
|
|
330
359
|
});
|
|
331
360
|
if (!result.idempotent) {
|
|
361
|
+
await this.balanceMonitor.signalCrossing(userId, result.newBalance.plus(result.amount.abs()), result.newBalance);
|
|
332
362
|
await this.afterDeduction(userId, "raw", {
|
|
333
363
|
entryId: result.entryId,
|
|
334
364
|
userId,
|
|
@@ -348,17 +378,15 @@ export class CreditsService {
|
|
|
348
378
|
* payment-provider webhook handler (Stripe, etc. — bursar stays
|
|
349
379
|
* provider-agnostic) to call even on webhook redelivery.
|
|
350
380
|
*
|
|
351
|
-
* 1.
|
|
352
|
-
*
|
|
353
|
-
* 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
|
|
354
|
-
* 3. The new cycle is granted via a direct ``store.addCredits`` call
|
|
381
|
+
* 1. Supply a stable absolute ``expiresAt`` across retries, if the grant expires.
|
|
382
|
+
* 2. The new cycle is granted via a direct ``store.addCredits`` call
|
|
355
383
|
* (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
|
|
356
384
|
* not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
|
|
357
385
|
* redelivered webhook replays the prior grant instead of double-crediting.
|
|
358
|
-
*
|
|
386
|
+
* 3. Existing bucket credits are never removed here. Subscription renewal
|
|
359
387
|
* policies that replace prior lots run atomically through BillingService.
|
|
360
|
-
*
|
|
361
|
-
*
|
|
388
|
+
* 4. Emits ``credits.cycle_renewed`` and returns the grant result. Plan
|
|
389
|
+
* assignment is a separate operation managed by the caller.
|
|
362
390
|
*/
|
|
363
391
|
async grantSubscriptionCycle(userId, amount, options) {
|
|
364
392
|
return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
|
|
@@ -368,15 +396,15 @@ export class CreditsService {
|
|
|
368
396
|
this.logger.info("[CreditsService] grantSubscriptionCycle", {
|
|
369
397
|
amount,
|
|
370
398
|
bucket: options.bucket,
|
|
371
|
-
planKey: options.planKey,
|
|
372
399
|
});
|
|
373
|
-
if (
|
|
374
|
-
throw new ConfigError("grantSubscriptionCycle:
|
|
400
|
+
if ("ttlDays" in options) {
|
|
401
|
+
throw new ConfigError("grantSubscriptionCycle: use a stable absolute expiresAt instead of ttlDays");
|
|
402
|
+
}
|
|
403
|
+
if ("planKey" in options) {
|
|
404
|
+
throw new ConfigError("grantSubscriptionCycle: assign plans separately with setUserPlan");
|
|
375
405
|
}
|
|
376
406
|
const bucket = options.bucket ?? "subscription";
|
|
377
|
-
const expiresAt = options.
|
|
378
|
-
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
379
|
-
: options.expiresAt;
|
|
407
|
+
const expiresAt = options.expiresAt;
|
|
380
408
|
const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
|
|
381
409
|
const result = await this.store.addCredits(userId, amountDec, {
|
|
382
410
|
type: "purchase",
|
|
@@ -385,23 +413,11 @@ export class CreditsService {
|
|
|
385
413
|
bucket,
|
|
386
414
|
idempotencyKey,
|
|
387
415
|
});
|
|
388
|
-
// The store contract exposes the mutation's replay result directly, avoiding
|
|
389
|
-
// a racy lifetime-balance comparison and an extra database round trip.
|
|
390
|
-
const isFreshGrant = !result.idempotent;
|
|
391
|
-
if (options.planKey) {
|
|
392
|
-
// A fresh cycle intentionally re-anchors plan-assignment windows. On a
|
|
393
|
-
// webhook replay, repair a previously interrupted grant->assignment saga
|
|
394
|
-
// without re-anchoring an assignment that already succeeded.
|
|
395
|
-
if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
|
|
396
|
-
await this.setUserPlan(userId, options.planKey);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
416
|
this.emit("credits.cycle_renewed", userId, {
|
|
400
417
|
entryId: result.entryId,
|
|
401
418
|
amount: amountDec,
|
|
402
419
|
newBalance: result.newBalance,
|
|
403
420
|
bucket,
|
|
404
|
-
planKey: options.planKey ?? null,
|
|
405
421
|
idempotencyKey,
|
|
406
422
|
idempotent: result.idempotent,
|
|
407
423
|
});
|
|
@@ -447,44 +463,46 @@ export class CreditsService {
|
|
|
447
463
|
* typed exception is thrown. No success event is emitted on error.
|
|
448
464
|
*/
|
|
449
465
|
async deduct(userId, metrics, options) {
|
|
450
|
-
return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
|
|
466
|
+
return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, metrics, options)));
|
|
451
467
|
}
|
|
452
|
-
async deductUninstrumented(userId, metrics, options) {
|
|
468
|
+
async deductUninstrumented(userId, metrics, options, flatJob = false) {
|
|
453
469
|
await this.maybeLazyExpire(userId);
|
|
454
470
|
this.logger.debug("[CreditsService] deduct", {
|
|
455
471
|
model: metrics.dimensions?.model,
|
|
456
472
|
feature: options.feature,
|
|
457
473
|
});
|
|
458
|
-
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
459
474
|
const plan = await this.store.getUserPlan(userId);
|
|
475
|
+
const engine = await this.catalogRuntime.engineForPlan(plan);
|
|
476
|
+
const quoteVersion = plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine);
|
|
477
|
+
if (flatJob && engine.hasMeasure(metrics.operation, "jobs"))
|
|
478
|
+
metrics = { ...metrics, measures: { jobs: 1 } };
|
|
460
479
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
461
480
|
const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
|
|
462
481
|
const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
|
|
463
482
|
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
464
|
-
const breakdown = engine.calculate(metrics, {
|
|
483
|
+
const breakdown = engine.calculate(metrics, {
|
|
484
|
+
rateCard: plan.rateCard ?? undefined,
|
|
485
|
+
});
|
|
465
486
|
const cost = breakdown.total;
|
|
487
|
+
const measures = ratedMeasures(metrics.measures);
|
|
488
|
+
const dimensions = ratedDimensions(metrics.dimensions);
|
|
466
489
|
// Build ledger metadata: caller fields FIRST, system fields LAST so the
|
|
467
490
|
// protected system fields win.
|
|
468
|
-
const meta =
|
|
469
|
-
if (options.metadata) {
|
|
470
|
-
for (const [k, v] of Object.entries(options.metadata)) {
|
|
471
|
-
if (v != null)
|
|
472
|
-
meta[k] = v;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
491
|
+
const meta = callerMetadata(options.metadata, true);
|
|
475
492
|
meta["operation"] = metrics.operation;
|
|
476
|
-
meta["measures"] =
|
|
477
|
-
meta["dimensions"] =
|
|
478
|
-
meta["breakdownTotal"] = breakdown.total.
|
|
479
|
-
meta["
|
|
493
|
+
meta["measures"] = measures;
|
|
494
|
+
meta["dimensions"] = dimensions;
|
|
495
|
+
meta["breakdownTotal"] = breakdown.total.toFixed(6);
|
|
496
|
+
meta["idempotency_key"] = effectiveIdempotencyKey;
|
|
480
497
|
const deductionOptions = {
|
|
481
498
|
idempotencyKey: effectiveIdempotencyKey,
|
|
499
|
+
expectedPricing: this.catalogRuntime.expectedPricing(plan, quoteVersion),
|
|
482
500
|
operation: metrics.operation,
|
|
483
501
|
feature: options.feature ?? null,
|
|
484
502
|
model,
|
|
485
503
|
region,
|
|
486
|
-
measures
|
|
487
|
-
dimensions
|
|
504
|
+
measures,
|
|
505
|
+
dimensions,
|
|
488
506
|
metadata: meta,
|
|
489
507
|
};
|
|
490
508
|
// 2) Atomic charge. This records zero-cost usage too, so authorization,
|
|
@@ -518,7 +536,7 @@ export class CreditsService {
|
|
|
518
536
|
});
|
|
519
537
|
// low_balance is edge-triggered: only fire when this deduction crossed
|
|
520
538
|
// the threshold. A replayed (idempotent) result did not move the balance, so
|
|
521
|
-
// it never crosses.
|
|
539
|
+
// it never crosses. The store's amount is already net of allowance.
|
|
522
540
|
if (!result.idempotent) {
|
|
523
541
|
const balanceBefore = result.balanceAfter.plus(result.amount);
|
|
524
542
|
await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);
|
|
@@ -534,34 +552,39 @@ export class CreditsService {
|
|
|
534
552
|
* affecting the account balance, such as externally billed usage.
|
|
535
553
|
*/
|
|
536
554
|
async recordUsage(userId, metrics, options) {
|
|
537
|
-
|
|
555
|
+
return this.catalogRuntime.withFreshQuote(() => this.recordUsageOnce(userId, metrics, options));
|
|
556
|
+
}
|
|
557
|
+
async recordUsageOnce(userId, metrics, options) {
|
|
538
558
|
const plan = await this.store.getUserPlan(userId);
|
|
559
|
+
const engine = await this.catalogRuntime.engineForPlan(plan);
|
|
539
560
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
540
561
|
const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
|
|
541
562
|
const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
|
|
542
|
-
const breakdown = engine.calculate(metrics, {
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
}
|
|
549
|
-
}
|
|
563
|
+
const breakdown = engine.calculate(metrics, {
|
|
564
|
+
rateCard: plan.rateCard ?? undefined,
|
|
565
|
+
});
|
|
566
|
+
const measures = ratedMeasures(metrics.measures);
|
|
567
|
+
const dimensions = ratedDimensions(metrics.dimensions);
|
|
568
|
+
const meta = callerMetadata(options.metadata, true);
|
|
550
569
|
meta.operation = metrics.operation;
|
|
551
|
-
meta.measures =
|
|
552
|
-
meta.dimensions =
|
|
553
|
-
meta.breakdownTotal = breakdown.total.
|
|
554
|
-
meta.
|
|
570
|
+
meta.measures = measures;
|
|
571
|
+
meta.dimensions = dimensions;
|
|
572
|
+
meta.breakdownTotal = breakdown.total.toFixed(6);
|
|
573
|
+
meta.idempotency_key = effectiveIdempotencyKey;
|
|
555
574
|
const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
|
|
556
575
|
idempotencyKey: effectiveIdempotencyKey,
|
|
576
|
+
expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
|
|
557
577
|
operation: metrics.operation,
|
|
558
578
|
model,
|
|
559
579
|
region,
|
|
560
|
-
measures
|
|
561
|
-
dimensions
|
|
580
|
+
measures,
|
|
581
|
+
dimensions,
|
|
562
582
|
metadata: meta,
|
|
563
583
|
});
|
|
564
584
|
if (result.error !== null) {
|
|
585
|
+
if (result.error === "idempotency_conflict") {
|
|
586
|
+
throw new IdempotencyConflictError(`Idempotency key conflicts with a prior request. user=${userId}`);
|
|
587
|
+
}
|
|
565
588
|
throw new StoreError(`Usage record failed: ${result.error}`);
|
|
566
589
|
}
|
|
567
590
|
return result;
|
|
@@ -576,7 +599,7 @@ export class CreditsService {
|
|
|
576
599
|
*/
|
|
577
600
|
/** Deduct the configured fixed cost for one named job. */
|
|
578
601
|
async deductFlatJob(userId, jobName, options) {
|
|
579
|
-
return this.deduct(userId, { operation: jobName
|
|
602
|
+
return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, { operation: jobName }, options, true)));
|
|
580
603
|
}
|
|
581
604
|
async refundCredits(entryId, options) {
|
|
582
605
|
return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
|
|
@@ -626,62 +649,62 @@ export class CreditsService {
|
|
|
626
649
|
*/
|
|
627
650
|
async deductTeam(teamId, userId, metrics, options) {
|
|
628
651
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
teamId,
|
|
644
|
-
userId,
|
|
645
|
-
amount: new Decimal(0),
|
|
646
|
-
teamBalanceAfter: teamBal.balance,
|
|
647
|
-
idempotent: false,
|
|
648
|
-
error: null,
|
|
652
|
+
return this.catalogRuntime.withFreshQuote(async () => {
|
|
653
|
+
await this.maybeLazyExpire(userId);
|
|
654
|
+
const plan = await this.store.getUserPlan(userId);
|
|
655
|
+
const engine = await this.catalogRuntime.engineForPlan(plan);
|
|
656
|
+
const breakdown = engine.calculate(metrics, {
|
|
657
|
+
rateCard: plan.rateCard ?? undefined,
|
|
658
|
+
});
|
|
659
|
+
const cost = breakdown.total;
|
|
660
|
+
const teamMetadata = {
|
|
661
|
+
...callerMetadata(options.metadata, true),
|
|
662
|
+
operation: metrics.operation,
|
|
663
|
+
measures: ratedMeasures(metrics.measures),
|
|
664
|
+
dimensions: ratedDimensions(metrics.dimensions),
|
|
665
|
+
breakdownTotal: breakdown.total.toFixed(6),
|
|
649
666
|
};
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
667
|
+
const result = await this.store.deductTeam(teamId, userId, cost, {
|
|
668
|
+
metadata: teamMetadata,
|
|
669
|
+
idempotencyKey,
|
|
670
|
+
expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
|
|
671
|
+
});
|
|
672
|
+
// Surface store errors: emit credits.deduct_failed and throw,
|
|
673
|
+
// mirroring the Python credit service implementation. Previously returned a silent
|
|
674
|
+
// success-shaped object with an .error field, so failed charges looked OK.
|
|
675
|
+
if (result.error !== null) {
|
|
676
|
+
this.emit("credits.deduct_failed", userId, {
|
|
677
|
+
error: result.error,
|
|
678
|
+
amount: cost,
|
|
679
|
+
teamId,
|
|
680
|
+
deductType: "team",
|
|
681
|
+
});
|
|
682
|
+
if (result.error === "member_spend_cap_exceeded") {
|
|
683
|
+
throw new CapReachedError(`Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`);
|
|
684
|
+
}
|
|
685
|
+
if (result.error === "idempotency_conflict") {
|
|
686
|
+
throw new IdempotencyConflictError(`Team idempotency key conflicts with a prior request. Team=${teamId}`);
|
|
687
|
+
}
|
|
688
|
+
if (result.error === "not_team_member") {
|
|
689
|
+
throw new OperationNotAllowedError(`Active team membership is required. Team=${teamId}, user=${userId}`);
|
|
690
|
+
}
|
|
691
|
+
if (result.error === "insufficient_credits" || result.error === "insufficient_headroom") {
|
|
692
|
+
throw new InsufficientCreditsError(`Insufficient team credits. Team=${teamId}, user=${userId}, requested=${cost}`);
|
|
693
|
+
}
|
|
694
|
+
throw new StoreError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}`);
|
|
695
|
+
}
|
|
696
|
+
this.emit("credits.deducted", userId, {
|
|
697
|
+
entryId: result.entryId,
|
|
698
|
+
amount: result.amount,
|
|
699
|
+
teamBalanceAfter: result.teamBalanceAfter,
|
|
669
700
|
teamId,
|
|
670
701
|
deductType: "team",
|
|
671
702
|
});
|
|
672
|
-
if (result.
|
|
673
|
-
|
|
703
|
+
if (!result.idempotent) {
|
|
704
|
+
await this.balanceMonitor.signalCrossing(userId, result.teamBalanceAfter.plus(result.amount), result.teamBalanceAfter, { teamId });
|
|
674
705
|
}
|
|
675
|
-
|
|
676
|
-
}
|
|
677
|
-
this.emit("credits.deducted", userId, {
|
|
678
|
-
entryId: result.entryId,
|
|
679
|
-
amount: result.amount,
|
|
680
|
-
teamBalanceAfter: result.teamBalanceAfter,
|
|
681
|
-
teamId,
|
|
682
|
-
deductType: "team",
|
|
706
|
+
return result;
|
|
683
707
|
});
|
|
684
|
-
return result;
|
|
685
708
|
}
|
|
686
709
|
async runSweep(dryRun, userId) {
|
|
687
710
|
const result = await this.store.sweepExpiredCredits(dryRun, userId);
|