@zonastery/bursar 1.0.1 → 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 +86 -3
- 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 +8 -7
- 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 +31 -9
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +2 -1
- 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 +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 +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/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 +202 -59
- 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 +12 -5
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +18 -15
- 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 +18 -11
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +260 -238
- 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/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/bursar.d.ts +27 -9
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +48 -20
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/errors.d.ts +1 -10
- package/dist/commerce/errors.d.ts.map +1 -1
- package/dist/commerce/errors.js +1 -16
- 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/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 +85 -67
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +27 -15
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +16 -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 +16 -5
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/types.d.ts +2 -2
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -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 +34 -34
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +52 -52
- 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 +28 -26
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +153 -68
- 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 +90 -43
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +126 -108
- 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 +23 -18
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +282 -265
- 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 +36 -61
- 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-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 +42 -62
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +140 -121
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +20 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +5 -5
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +49 -11
- 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 +20 -15
- 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/ledger.d.ts +12 -3
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.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 +52 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +76 -4
- 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/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 +5 -7
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +5 -12
- package/dist/generated/pricing-config.types.d.ts +3 -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 +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- 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} +15 -10
- package/dist/load-config-file.js.map +1 -0
- 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 +36 -0
- 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/shared/postgres-client.d.ts +5 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +23 -7
- package/dist/shared/postgres-client.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 +2 -5
- 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/ports.d.ts +0 -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 +2 -2
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +24 -6
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +87 -30
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +56 -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 -76
- 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
|
@@ -4,24 +4,30 @@ import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, St
|
|
|
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,21 @@ 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;
|
|
241
255
|
}
|
|
242
256
|
/** Pin or unpin the user's current assignment revision. */
|
|
243
257
|
async setPlanRevisionPin(userId, pinned) {
|
|
@@ -261,7 +275,7 @@ export class CreditsService {
|
|
|
261
275
|
async addCredits(userId, amount, options) {
|
|
262
276
|
const type = options?.type ?? "adjustment";
|
|
263
277
|
this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options?.bucket });
|
|
264
|
-
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);
|
|
265
279
|
this.emit("credits.added", userId, {
|
|
266
280
|
entryId: result.entryId,
|
|
267
281
|
amount: result.amount,
|
|
@@ -287,21 +301,27 @@ export class CreditsService {
|
|
|
287
301
|
entryType,
|
|
288
302
|
bucket: options?.bucket,
|
|
289
303
|
});
|
|
290
|
-
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);
|
|
291
305
|
this.emit("credits.deducted", userId, {
|
|
292
306
|
entryId: result.entryId,
|
|
293
307
|
amount: result.amount,
|
|
294
308
|
newBalance: result.newBalance,
|
|
295
309
|
entryType,
|
|
296
|
-
});
|
|
297
|
-
await this.afterDeduction(userId, "raw", {
|
|
298
|
-
entryId: result.entryId,
|
|
299
|
-
userId,
|
|
300
|
-
amount: result.amount.abs(),
|
|
301
|
-
allowanceConsumed: new Decimal(0),
|
|
302
|
-
balanceAfter: result.newBalance,
|
|
303
310
|
idempotent: result.idempotent ?? false,
|
|
304
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
|
+
}
|
|
305
325
|
return result;
|
|
306
326
|
}
|
|
307
327
|
/**
|
|
@@ -312,14 +332,12 @@ export class CreditsService {
|
|
|
312
332
|
* 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
|
|
313
333
|
* ``ConfigError`` otherwise).
|
|
314
334
|
* 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
|
|
315
|
-
* 3.
|
|
316
|
-
* ``bucket`` is expired immediately via a direct ``store.addCredits``
|
|
317
|
-
* negative adjustment — naturally idempotent (a replay finds the bucket
|
|
318
|
-
* already at zero and skips the call).
|
|
319
|
-
* 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
|
|
320
336
|
* (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
|
|
321
337
|
* not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
|
|
322
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.
|
|
323
341
|
* 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
|
|
324
342
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
325
343
|
*/
|
|
@@ -333,32 +351,21 @@ export class CreditsService {
|
|
|
333
351
|
throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
|
|
334
352
|
}
|
|
335
353
|
const bucket = options?.bucket ?? "subscription";
|
|
336
|
-
const replacePrior = options?.replacePrior ?? true;
|
|
337
354
|
const expiresAt = options?.ttlDays != null
|
|
338
355
|
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
339
356
|
: options?.expiresAt;
|
|
340
|
-
const amountDec =
|
|
341
|
-
|
|
342
|
-
// webhook must skip the replace-prior wipe as well as the duplicate grant.
|
|
343
|
-
let priorLeftover = new Decimal(0);
|
|
344
|
-
if (replacePrior) {
|
|
345
|
-
const bucketsBefore = await this.getBucketBalances(userId);
|
|
346
|
-
const current = bucketsBefore.buckets.find((t) => t.bucketKey === bucket);
|
|
347
|
-
if (current)
|
|
348
|
-
priorLeftover = current.balance;
|
|
349
|
-
}
|
|
350
|
-
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);
|
|
351
359
|
// The store contract exposes the mutation's replay result directly, avoiding
|
|
352
360
|
// a racy lifetime-balance comparison and an extra database round trip.
|
|
353
361
|
const isFreshGrant = !result.idempotent;
|
|
354
|
-
if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
|
|
355
|
-
await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, bucket);
|
|
356
|
-
// Reflect the post-replace balance so the returned result is accurate
|
|
357
|
-
// (the grant call above only knows the pre-replace balance).
|
|
358
|
-
result = { ...result, newBalance: (await this.getBalance(userId)).balance };
|
|
359
|
-
}
|
|
360
362
|
if (options?.planKey) {
|
|
361
|
-
|
|
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
|
+
}
|
|
362
369
|
}
|
|
363
370
|
this.emit("credits.cycle_renewed", userId, {
|
|
364
371
|
entryId: result.entryId,
|
|
@@ -367,10 +374,11 @@ export class CreditsService {
|
|
|
367
374
|
bucket,
|
|
368
375
|
planKey: options?.planKey ?? null,
|
|
369
376
|
idempotencyKey: options?.idempotencyKey ?? null,
|
|
377
|
+
idempotent: result.idempotent,
|
|
370
378
|
});
|
|
371
379
|
return result;
|
|
372
380
|
}
|
|
373
|
-
// ── Lease lifecycle: atomic admission
|
|
381
|
+
// ── Lease lifecycle: atomic admission ───────────────────────────────
|
|
374
382
|
async reserve(userId, metricsOrAmount, options) {
|
|
375
383
|
return this.leases.reserve(userId, metricsOrAmount, options);
|
|
376
384
|
}
|
|
@@ -399,7 +407,7 @@ export class CreditsService {
|
|
|
399
407
|
return this.leases.beginBilledOperation(userId, options);
|
|
400
408
|
}
|
|
401
409
|
/**
|
|
402
|
-
* Full deduction flow as one atomic store call
|
|
410
|
+
* Full deduction flow as one atomic store call.
|
|
403
411
|
*
|
|
404
412
|
* 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
|
|
405
413
|
* (exact `Decimal`, **no truncation**).
|
|
@@ -409,22 +417,23 @@ export class CreditsService {
|
|
|
409
417
|
* On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
|
|
410
418
|
* typed exception is thrown. No success event is emitted on error.
|
|
411
419
|
*/
|
|
412
|
-
async deduct(userId, metrics,
|
|
413
|
-
/** Entitlement feature required for this operation. */
|
|
414
|
-
feature) {
|
|
420
|
+
async deduct(userId, metrics, options) {
|
|
415
421
|
await this.maybeLazyExpire(userId);
|
|
416
|
-
this.logger.debug("[CreditsService] deduct", {
|
|
417
|
-
|
|
422
|
+
this.logger.debug("[CreditsService] deduct", {
|
|
423
|
+
model: metrics.dimensions?.model,
|
|
424
|
+
feature: options?.feature,
|
|
425
|
+
});
|
|
426
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
418
427
|
const plan = await this.store.getUserPlan(userId);
|
|
419
|
-
const effectiveIdempotencyKey = idempotencyKey ?? `usage:${randomUUID()}`;
|
|
420
|
-
// 1) Calculate cost
|
|
428
|
+
const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
|
|
429
|
+
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
421
430
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
422
431
|
const cost = breakdown.total;
|
|
423
432
|
// Build ledger metadata: caller fields FIRST, system fields LAST so the
|
|
424
|
-
// system fields win
|
|
433
|
+
// protected system fields win.
|
|
425
434
|
const meta = {};
|
|
426
|
-
if (metadata) {
|
|
427
|
-
for (const [k, v] of Object.entries(metadata)) {
|
|
435
|
+
if (options?.metadata) {
|
|
436
|
+
for (const [k, v] of Object.entries(options.metadata)) {
|
|
428
437
|
if (v != null)
|
|
429
438
|
meta[k] = v;
|
|
430
439
|
}
|
|
@@ -434,10 +443,10 @@ export class CreditsService {
|
|
|
434
443
|
meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
|
|
435
444
|
meta["breakdownTotal"] = breakdown.total.toString();
|
|
436
445
|
meta["idempotencyKey"] = effectiveIdempotencyKey;
|
|
437
|
-
const
|
|
446
|
+
const deductionOptions = {
|
|
438
447
|
idempotencyKey: effectiveIdempotencyKey,
|
|
439
448
|
operation: metrics.operation,
|
|
440
|
-
feature: feature ?? null,
|
|
449
|
+
feature: options?.feature ?? null,
|
|
441
450
|
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
442
451
|
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
443
452
|
measures: { ...(metrics.measures ?? {}) },
|
|
@@ -446,8 +455,8 @@ export class CreditsService {
|
|
|
446
455
|
};
|
|
447
456
|
// 2) Atomic charge. This records zero-cost usage too, so authorization,
|
|
448
457
|
// quotas, and usage history cannot be bypassed by a free rate.
|
|
449
|
-
const result = await this.store.deductWithAllowance(userId, cost,
|
|
450
|
-
if (result.error) {
|
|
458
|
+
const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);
|
|
459
|
+
if (result.error !== null) {
|
|
451
460
|
if (result.error === "quota_exceeded") {
|
|
452
461
|
await this.emitQuotaEvents(userId, effectiveIdempotencyKey);
|
|
453
462
|
}
|
|
@@ -455,7 +464,7 @@ export class CreditsService {
|
|
|
455
464
|
error: result.error,
|
|
456
465
|
amount: cost,
|
|
457
466
|
model: metrics.dimensions?.model,
|
|
458
|
-
feature,
|
|
467
|
+
feature: options?.feature,
|
|
459
468
|
});
|
|
460
469
|
this.emit("credits.deduct_failed", userId, {
|
|
461
470
|
error: result.error,
|
|
@@ -473,7 +482,7 @@ export class CreditsService {
|
|
|
473
482
|
model: metrics.dimensions?.model ?? null,
|
|
474
483
|
idempotent: result.idempotent,
|
|
475
484
|
});
|
|
476
|
-
// low_balance is
|
|
485
|
+
// low_balance is edge-triggered: only fire when this deduction crossed
|
|
477
486
|
// the threshold. A replayed (idempotent) result did not move the balance, so
|
|
478
487
|
// it never crosses. balanceBefore = balanceAfter + amount charged.
|
|
479
488
|
if (!result.idempotent) {
|
|
@@ -487,18 +496,17 @@ export class CreditsService {
|
|
|
487
496
|
/**
|
|
488
497
|
* Record priced usage for a workflow without debiting the account again.
|
|
489
498
|
*
|
|
490
|
-
* This
|
|
491
|
-
*
|
|
492
|
-
* preserves the child cost and metadata in Bursar's usage journal.
|
|
499
|
+
* This supports priced usage receipts that should be retained without
|
|
500
|
+
* affecting the account balance, such as externally billed usage.
|
|
493
501
|
*/
|
|
494
|
-
async recordUsage(userId, metrics,
|
|
495
|
-
const engine = await this.
|
|
502
|
+
async recordUsage(userId, metrics, options) {
|
|
503
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
496
504
|
const plan = await this.store.getUserPlan(userId);
|
|
497
|
-
const effectiveIdempotencyKey = idempotencyKey ?? `usage-record:${randomUUID()}`;
|
|
505
|
+
const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
|
|
498
506
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
499
507
|
const meta = {};
|
|
500
|
-
if (metadata) {
|
|
501
|
-
for (const [key, value] of Object.entries(metadata)) {
|
|
508
|
+
if (options?.metadata) {
|
|
509
|
+
for (const [key, value] of Object.entries(options.metadata)) {
|
|
502
510
|
if (value != null)
|
|
503
511
|
meta[key] = value;
|
|
504
512
|
}
|
|
@@ -517,7 +525,7 @@ export class CreditsService {
|
|
|
517
525
|
dimensions: { ...(metrics.dimensions ?? {}) },
|
|
518
526
|
metadata: meta,
|
|
519
527
|
});
|
|
520
|
-
if (result.error) {
|
|
528
|
+
if (result.error !== null) {
|
|
521
529
|
throw new StoreError(`Usage record failed: ${result.error}`);
|
|
522
530
|
}
|
|
523
531
|
return result;
|
|
@@ -531,23 +539,29 @@ export class CreditsService {
|
|
|
531
539
|
* refund).
|
|
532
540
|
*/
|
|
533
541
|
/** Deduct the configured fixed cost for one named job. */
|
|
534
|
-
async deductFlatJob(userId, jobName,
|
|
535
|
-
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } },
|
|
536
|
-
}
|
|
537
|
-
async refundCredits(entryId,
|
|
538
|
-
const refundAmount = amount != null ?
|
|
539
|
-
this.logger.info("[CreditsService] refundCredits", {
|
|
540
|
-
|
|
541
|
-
|
|
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) {
|
|
542
554
|
this.logger.warn("[CreditsService] refundCredits failed", {
|
|
543
555
|
entryId,
|
|
544
556
|
error: result.error,
|
|
545
557
|
});
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
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
|
+
}
|
|
551
565
|
throw new RefundError(`Refund rejected: ${result.error}`);
|
|
552
566
|
}
|
|
553
567
|
this.emit("credits.refunded", result.userId, {
|
|
@@ -555,7 +569,7 @@ export class CreditsService {
|
|
|
555
569
|
refundEntryId: result.refundEntryId,
|
|
556
570
|
amount: result.amount,
|
|
557
571
|
newBalance: result.newBalance,
|
|
558
|
-
reason: reason ?? null,
|
|
572
|
+
reason: options?.reason ?? null,
|
|
559
573
|
});
|
|
560
574
|
return result;
|
|
561
575
|
}
|
|
@@ -564,38 +578,43 @@ export class CreditsService {
|
|
|
564
578
|
*
|
|
565
579
|
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
566
580
|
* then debits the team balance. Threads an optional ``idempotencyKey`` through
|
|
567
|
-
* to the store so retried team charges are not double-counted
|
|
581
|
+
* to the store so retried team charges are not double-counted.
|
|
568
582
|
*/
|
|
569
|
-
async deductTeam(teamId, userId, metrics,
|
|
583
|
+
async deductTeam(teamId, userId, metrics, options) {
|
|
570
584
|
await this.maybeLazyExpire(userId);
|
|
571
585
|
// Lazy expiry is scoped to the individual member's credits, not the team's
|
|
572
586
|
// shared pool — there's no per-team expiry concept.
|
|
573
|
-
const engine = await this.
|
|
587
|
+
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
574
588
|
const plan = await this.store.getUserPlan(userId);
|
|
575
589
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
576
590
|
const cost = breakdown.total;
|
|
577
591
|
if (cost.lte(0)) {
|
|
578
592
|
const teamBal = await this.store.getTeamBalance(teamId);
|
|
593
|
+
if (teamBal === null) {
|
|
594
|
+
throw new StoreError(`Team not found: ${teamId}`);
|
|
595
|
+
}
|
|
579
596
|
return {
|
|
580
|
-
entryId:
|
|
597
|
+
entryId: null,
|
|
581
598
|
teamId,
|
|
582
599
|
userId,
|
|
583
600
|
amount: new Decimal(0),
|
|
584
601
|
teamBalanceAfter: teamBal.balance,
|
|
602
|
+
idempotent: false,
|
|
603
|
+
error: null,
|
|
585
604
|
};
|
|
586
605
|
}
|
|
587
606
|
const teamMetadata = {
|
|
588
|
-
...(metadata ?? {}),
|
|
607
|
+
...(options?.metadata ?? {}),
|
|
589
608
|
operation: metrics.operation,
|
|
590
609
|
measures: { ...(metrics.measures ?? {}) },
|
|
591
610
|
dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
|
|
592
611
|
breakdownTotal: breakdown.total.toString(),
|
|
593
612
|
};
|
|
594
|
-
const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, idempotencyKey);
|
|
595
|
-
//
|
|
613
|
+
const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, options?.idempotencyKey);
|
|
614
|
+
// Surface store errors: emit credits.deduct_failed and throw,
|
|
596
615
|
// mirroring the Python credit service implementation. Previously returned a silent
|
|
597
616
|
// success-shaped object with an .error field, so failed charges looked OK.
|
|
598
|
-
if (result.error) {
|
|
617
|
+
if (result.error !== null) {
|
|
599
618
|
this.emit("credits.deduct_failed", userId, {
|
|
600
619
|
error: result.error,
|
|
601
620
|
amount: cost,
|