@zonastery/bursar 2.0.1 → 2.0.3
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 +22 -14
- package/dist/billing/auto-recharge-service.d.ts +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +9 -6
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +4 -1
- 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 +2 -1
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +2 -3
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +38 -49
- 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 +22 -10
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -2
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +7 -7
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +6 -2
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +21 -6
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +2 -15
- 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 +1 -1
- 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 -1
- 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 +1 -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 +11 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +2 -2
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +1 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts +21 -11
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +40 -4
- package/dist/bursar.js.map +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/index.d.ts +0 -1
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js +0 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +154 -106
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +9 -5
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +0 -6
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-utils.d.ts +1 -1
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +1 -6
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +8 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +8 -0
- package/dist/credits/amount.d.ts.map +1 -0
- package/dist/credits/amount.js +32 -0
- package/dist/credits/amount.js.map +1 -0
- package/dist/credits/catalog-runtime.d.ts +5 -7
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +4 -13
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +2 -2
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +24 -21
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +3 -4
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +18 -14
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +30 -18
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +1 -1
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +21 -16
- 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 +21 -17
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +81 -38
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +26 -23
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +4 -2
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +1 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.js +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -0
- 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 +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/parser.d.ts +1 -0
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +15 -3
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr.d.ts +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +1 -1
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +31 -29
- package/dist/generated/pricing-config.types.d.ts +6 -18
- 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 +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -3
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +14 -29
- 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 +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +3 -3
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +11 -6
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +8 -13
- 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 +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +23 -15
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +4 -6
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +44 -82
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js +0 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +6 -0
- package/dist/providers/environment.d.ts.map +1 -0
- package/dist/providers/environment.js +10 -0
- package/dist/providers/environment.js.map +1 -0
- package/dist/providers/index.d.ts +3 -7
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -5
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +6 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +18 -50
- 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 +82 -14
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +3 -3
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +37 -24
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +9 -20
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +8 -0
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +49 -0
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/idempotency.d.ts +9 -0
- package/dist/shared/idempotency.d.ts.map +1 -0
- package/dist/shared/idempotency.js +34 -0
- package/dist/shared/idempotency.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +7 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +21 -4
- 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.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +9 -2
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +142 -36
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +44 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +59 -21
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +227 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +266 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +20 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +172 -42
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +43 -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 +7 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +155 -54
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +30 -9
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +268 -37
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +37 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +115 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +62 -36
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/credits/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type Decimal from \"decimal.js\";\n\nimport type { UsageMetrics } from \"../metrics.js\";\nimport type { Logger } from \"../shared/logger.js\";\nimport type { CreditEvent } from \"./events.js\";\nimport type {\n BillingMode,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n UsageAnalyticsStore,\n UsageChargeStore,\n} from \"./types/index.js\";\n\nexport type PolicyPreset = \"strict_prepaid\" | \"overdraft\";\nexport type
|
|
1
|
+
{"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../src/credits/service-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nimport type { UsageMetrics } from \"../metrics.js\";\nimport type { Logger } from \"../shared/logger.js\";\nimport type { Instrumentation } from \"../telemetry/index.js\";\nimport type { CreditEvent } from \"./events.js\";\nimport type {\n BillingMode,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n UsageAnalyticsStore,\n UsageChargeStore,\n} from \"./types/index.js\";\n\nexport type PolicyPreset = \"strict_prepaid\" | \"overdraft\";\n/** Exact decimal credit input. Native numbers are intentionally excluded. */\nexport type ExactAmount = Decimal | string;\nexport type MetricsOrAmount = UsageMetrics | ExactAmount;\n\nexport interface PostDeductionContext {\n userId: string;\n source: \"deduct\" | \"settle\" | \"raw\";\n deduction: DeductionSuccess;\n}\n\nexport interface LowBalanceConfig {\n thresholds?: ExactAmount[] | null;\n onTrigger?: ((event: CreditEvent) => void | Promise<void>) | null;\n /**\n * Maximum number of subjects whose breached-threshold state is retained in\n * memory. Defaults to 100,000.\n */\n maxTrackedUsers?: number;\n}\n\nexport interface CreditsServiceOptions {\n logger?: Logger | null;\n /** Explicit telemetry implementation; falls back to Bursar's no-op registry. */\n instrumentation?: Instrumentation | null;\n /**\n * Optional read-only analytics backend. Defaults to the credit store, which\n * keeps PostgreSQL as the zero-infrastructure behavior.\n */\n analytics?: UsageAnalyticsStore | null;\n /** Optional usage-history backend. Defaults to the credit store. */\n usageStore?: UsageChargeStore | null;\n /** Fallback credit policy for subjects without a plan assignment. */\n policy?: PolicyPreset;\n /** Planless-subject floor used with the `overdraft` fallback. */\n overdraftFloor?: ExactAmount | null;\n /** Planless-subject admission limit fallback. */\n maxConcurrent?: number | null;\n /**\n * Edge-triggered low-balance thresholds and optional non-blocking handler.\n * Defaults to zero when omitted.\n */\n lowBalance?: LowBalanceConfig | null;\n /** Default lease TTL in seconds. Defaults to 600. */\n defaultTtlSeconds?: number;\n /** Sweep a subject's expired credits before balance-sensitive operations. */\n lazyExpiry?: boolean;\n /**\n * Catalog cache TTL in milliseconds. A value of 0 disables automatic\n * reloads. Concurrent reloads are deduplicated. Defaults to 300,000.\n */\n catalogCacheTtlMs?: number;\n /**\n * Awaited after a committed, non-replayed deduction. Hook failures are\n * isolated from the committed credit charge.\n */\n postDeduction?: ((context: PostDeductionContext) => void | Promise<void>) | null;\n}\n\nexport interface AddCreditsOptions {\n type?: string;\n metadata?: CreditMetadata | null;\n expiresAt?: Date | null;\n /** Target credit bucket; omitted resolves to the catalog's default bucket. */\n bucket?: string | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey: string;\n}\n\nexport interface DeductCreditsOptions {\n entryType?: string;\n bucket?: string | null;\n metadata?: CreditMetadata | null;\n /** Stable replay key for the ledger mutation. */\n idempotencyKey: string;\n}\n\nexport interface DeductOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n /** Entitlement feature required for this operation. */\n feature?: string | null;\n}\n\nexport type DeductFlatJobOptions = DeductOptions;\n\nexport interface RecordUsageOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RefundCreditsOptions {\n amount?: ExactAmount;\n reason?: string;\n metadata?: CreditMetadata | null;\n idempotencyKey: string;\n}\n\nexport interface DeductTeamOptions {\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface ReserveOptions {\n /** Caller-stable replay-safe acquisition key. */\n idempotencyKey: string;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n metadata?: CreditMetadata | null;\n feature?: string | null;\n /** Model tag used when reserving a raw amount instead of usage metrics. */\n model?: string | null;\n}\n\nexport interface SettleOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n /** Entitlement key supplied at reserve time. */\n feature?: string | null;\n}\n\nexport interface CanAffordOptions {\n feature?: string | null;\n billingMode?: BillingMode | null;\n operationType?: string;\n}\n\nexport interface GrantSubscriptionCycleOptions {\n bucket?: string;\n expiresAt?: Date;\n ttlDays?: number;\n planKey?: string;\n idempotencyKey: string;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RunBilledOptions<T> {\n estimate: MetricsOrAmount;\n doWork: () => Promise<{ result: T; actual: MetricsOrAmount }>;\n operationType?: string;\n billingMode?: BillingMode | null;\n /** Stable key for the complete reserve/work/settle operation. */\n operationKey: string;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n /** Settlement attempts for SDK-classified transient failures. Defaults to 3. */\n settlementAttempts?: number;\n}\n\nexport interface BeginBilledOperationOptions {\n estimate: MetricsOrAmount;\n /** Stable key for the complete reserve/settle operation. */\n operationKey: string;\n operationType?: string;\n billingMode?: BillingMode | null;\n ttl?: number | null;\n feature?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface BilledOperation {\n readonly leaseId: string;\n readonly operationKey: string;\n settle(actual: MetricsOrAmount, metadata?: CreditMetadata | null): Promise<DeductionResult>;\n renew(ttl?: number | null): Promise<void>;\n release(): Promise<void>;\n}\n"]}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
2
1
|
import type { PricingEngine } from "../engine.js";
|
|
3
|
-
import type { CatalogRollout } from "../config.js";
|
|
2
|
+
import type { BursarConfigData, CatalogRollout } from "../config.js";
|
|
4
3
|
import type { AddCreditsResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CatalogRevision, BucketBalancesResult, CanAffordResult, CheckFeatureResult, DailySpendRow, DeductionResult, ExecuteGrantProgramRequest, GetUserPlanResult, GrantProgramAwardResult, LedgerEntry, LedgerPage, LeaseSuccess, ListLedgerEntriesOptions, ListQuotaEventsOptions, ListUsageChargesOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, RefundSuccess, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, UnsetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamDeductionResult, TopUserRow, UsageChargePage, UsageRecordResult } from "./types/index.js";
|
|
5
4
|
import type { CreditStore } from "./store.js";
|
|
6
5
|
import type { CreditEventEmitter } from "./events.js";
|
|
7
6
|
import type { UsageMetrics } from "../metrics.js";
|
|
8
|
-
import type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, GrantSubscriptionCycleOptions, MetricsOrAmount, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
|
|
9
|
-
export type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, GrantSubscriptionCycleOptions, LowBalanceConfig, PolicyPreset, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions, } from "./service-types.js";
|
|
7
|
+
import type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, ExactAmount, GrantSubscriptionCycleOptions, MetricsOrAmount, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
|
|
8
|
+
export type { AddCreditsOptions, BeginBilledOperationOptions, BilledOperation, CanAffordOptions, CreditsServiceOptions, DeductCreditsOptions, DeductFlatJobOptions, DeductOptions, DeductTeamOptions, ExactAmount, GrantSubscriptionCycleOptions, LowBalanceConfig, PolicyPreset, PostDeductionContext, RecordUsageOptions, RefundCreditsOptions, ReserveOptions, RunBilledOptions, SettleOptions, } from "./service-types.js";
|
|
10
9
|
/**
|
|
11
10
|
* Orchestrates credit operations.
|
|
12
11
|
*
|
|
@@ -29,6 +28,7 @@ export declare class CreditsService {
|
|
|
29
28
|
private balanceMonitor;
|
|
30
29
|
private lazyExpiry;
|
|
31
30
|
private logger;
|
|
31
|
+
private readonly instrumentation;
|
|
32
32
|
private readonly postDeductionHooks;
|
|
33
33
|
constructor(store: CreditStore, engine?: PricingEngine | null, emitter?: CreditEventEmitter | null, options?: CreditsServiceOptions | null);
|
|
34
34
|
/**
|
|
@@ -86,11 +86,11 @@ export declare class CreditsService {
|
|
|
86
86
|
* a persistence failure surfaces to the caller instead of becoming an
|
|
87
87
|
* unhandled promise rejection.
|
|
88
88
|
*/
|
|
89
|
-
publishAndActivateCatalog(config:
|
|
89
|
+
publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
90
90
|
/** Publish a validated, inactive catalog draft. */
|
|
91
|
-
publishCatalogDraft(config:
|
|
91
|
+
publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
|
|
92
92
|
/** Activate an existing catalog version and reload the local engine. */
|
|
93
|
-
activateCatalogRevision(version: number, rollout?: CatalogRollout |
|
|
93
|
+
activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
|
|
94
94
|
/** The current PricingEngine, or null if not loaded. */
|
|
95
95
|
get pricingEngine(): PricingEngine | null;
|
|
96
96
|
/**
|
|
@@ -110,7 +110,8 @@ export declare class CreditsService {
|
|
|
110
110
|
private maybeLazyExpire;
|
|
111
111
|
getBalance(userId: string): Promise<BalanceResult>;
|
|
112
112
|
/** Add credits to a user's account. */
|
|
113
|
-
addCredits(userId: string, amount:
|
|
113
|
+
addCredits(userId: string, amount: ExactAmount, options: AddCreditsOptions): Promise<AddCreditsResult>;
|
|
114
|
+
private addCreditsUninstrumented;
|
|
114
115
|
/**
|
|
115
116
|
* Deduct a raw credit amount from a user's account.
|
|
116
117
|
*
|
|
@@ -119,7 +120,7 @@ export declare class CreditsService {
|
|
|
119
120
|
* Use this for refund clawbacks and other administrative deductions that
|
|
120
121
|
* bypass the usage-based `deduct()` flow.
|
|
121
122
|
*/
|
|
122
|
-
deductCredits(userId: string, amount:
|
|
123
|
+
deductCredits(userId: string, amount: ExactAmount, options: DeductCreditsOptions): Promise<AddCreditsResult>;
|
|
123
124
|
/**
|
|
124
125
|
* Grant one billing-cycle's worth of credits — idempotent-safe for a
|
|
125
126
|
* payment-provider webhook handler (Stripe, etc. — bursar stays
|
|
@@ -137,8 +138,9 @@ export declare class CreditsService {
|
|
|
137
138
|
* 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
|
|
138
139
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
139
140
|
*/
|
|
140
|
-
grantSubscriptionCycle(userId: string, amount:
|
|
141
|
-
|
|
141
|
+
grantSubscriptionCycle(userId: string, amount: ExactAmount, options: GrantSubscriptionCycleOptions): Promise<AddCreditsResult>;
|
|
142
|
+
private grantSubscriptionCycleUninstrumented;
|
|
143
|
+
reserve(userId: string, metricsOrAmount: MetricsOrAmount, options: ReserveOptions): Promise<LeaseSuccess>;
|
|
142
144
|
settle(userId: string, leaseId: string, metricsOrAmount: MetricsOrAmount, options?: SettleOptions): Promise<DeductionResult>;
|
|
143
145
|
release(userId: string, leaseId: string): Promise<ReleaseResult>;
|
|
144
146
|
renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess>;
|
|
@@ -161,14 +163,15 @@ export declare class CreditsService {
|
|
|
161
163
|
* On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
|
|
162
164
|
* typed exception is thrown. No success event is emitted on error.
|
|
163
165
|
*/
|
|
164
|
-
deduct(userId: string, metrics: UsageMetrics, options
|
|
166
|
+
deduct(userId: string, metrics: UsageMetrics, options: DeductOptions): Promise<DeductionResult>;
|
|
167
|
+
private deductUninstrumented;
|
|
165
168
|
/**
|
|
166
169
|
* Record priced usage for a workflow without debiting the account again.
|
|
167
170
|
*
|
|
168
171
|
* This supports priced usage receipts that should be retained without
|
|
169
172
|
* affecting the account balance, such as externally billed usage.
|
|
170
173
|
*/
|
|
171
|
-
recordUsage(userId: string, metrics: UsageMetrics, options
|
|
174
|
+
recordUsage(userId: string, metrics: UsageMetrics, options: RecordUsageOptions): Promise<UsageRecordResult>;
|
|
172
175
|
/**
|
|
173
176
|
* Refund a previous credit deduction.
|
|
174
177
|
*
|
|
@@ -178,16 +181,17 @@ export declare class CreditsService {
|
|
|
178
181
|
* refund).
|
|
179
182
|
*/
|
|
180
183
|
/** Deduct the configured fixed cost for one named job. */
|
|
181
|
-
deductFlatJob(userId: string, jobName: string, options
|
|
182
|
-
refundCredits(entryId: string, options
|
|
184
|
+
deductFlatJob(userId: string, jobName: string, options: DeductFlatJobOptions): Promise<DeductionResult>;
|
|
185
|
+
refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess>;
|
|
186
|
+
private refundCreditsUninstrumented;
|
|
183
187
|
/**
|
|
184
188
|
* Deduct from a team's shared balance pool.
|
|
185
189
|
*
|
|
186
190
|
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
187
|
-
* then debits the team balance. Threads
|
|
191
|
+
* then debits the team balance. Threads a required ``idempotencyKey`` through
|
|
188
192
|
* to the store so retried team charges are not double-counted.
|
|
189
193
|
*/
|
|
190
|
-
deductTeam(teamId: string, userId: string, metrics: UsageMetrics, options
|
|
194
|
+
deductTeam(teamId: string, userId: string, metrics: UsageMetrics, options: DeductTeamOptions): Promise<TeamDeductionResult>;
|
|
191
195
|
private runSweep;
|
|
192
196
|
/**
|
|
193
197
|
* Sweep expired credits from all users' balances.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,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,GAAG,OAAO,CAAC,WAAW,CAAC;CAGhE"}
|
package/dist/credits/service.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
3
2
|
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
4
3
|
import { raiseDeductError } from "./service-errors.js";
|
|
5
4
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
5
|
import { CreditQueries } from "./queries.js";
|
|
7
|
-
import { CatalogRuntime
|
|
6
|
+
import { CatalogRuntime } from "./catalog-runtime.js";
|
|
7
|
+
import { toDecimal } from "./amount.js";
|
|
8
8
|
import { CreditLeaseWorkflow } from "./lease-workflow.js";
|
|
9
|
+
import { requireStableKey } from "../shared/idempotency.js";
|
|
10
|
+
import { getDefaultInstrumentation } from "../telemetry/index.js";
|
|
9
11
|
/**
|
|
10
12
|
* Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
|
|
11
13
|
* Long batch/agentic jobs call the configured lease TTL before this elapses.
|
|
@@ -45,9 +47,11 @@ export class CreditsService {
|
|
|
45
47
|
// behaviour; explicit `sweepExpiredCredits`/cron remains required.
|
|
46
48
|
lazyExpiry;
|
|
47
49
|
logger;
|
|
50
|
+
instrumentation;
|
|
48
51
|
postDeductionHooks = new Set();
|
|
49
52
|
constructor(store, engine, emitter, options) {
|
|
50
53
|
this.store = store;
|
|
54
|
+
this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
|
|
51
55
|
this.queries = new CreditQueries(store, options?.analytics ?? store, options?.usageStore ?? store);
|
|
52
56
|
const policy = options?.policy ?? "strict_prepaid";
|
|
53
57
|
if (!POLICY_PRESETS.has(policy)) {
|
|
@@ -120,7 +124,7 @@ export class CreditsService {
|
|
|
120
124
|
}
|
|
121
125
|
/** Execute an application-driven catalog grant program. */
|
|
122
126
|
async executeGrantProgram(request) {
|
|
123
|
-
return this.store.executeGrantProgram(request);
|
|
127
|
+
return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
|
|
124
128
|
}
|
|
125
129
|
async getLedgerEntry(userId, entryId) {
|
|
126
130
|
return this.queries.getLedgerEntry(userId, entryId);
|
|
@@ -273,9 +277,17 @@ export class CreditsService {
|
|
|
273
277
|
}
|
|
274
278
|
/** Add credits to a user's account. */
|
|
275
279
|
async addCredits(userId, amount, options) {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
280
|
+
return this.instrumentation.run("credits.grant", undefined, () => this.addCreditsUninstrumented(userId, amount, options));
|
|
281
|
+
}
|
|
282
|
+
async addCreditsUninstrumented(userId, amount, options) {
|
|
283
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
284
|
+
const type = options.type ?? "adjustment";
|
|
285
|
+
this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
|
|
286
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
|
|
287
|
+
...options,
|
|
288
|
+
type,
|
|
289
|
+
idempotencyKey,
|
|
290
|
+
});
|
|
279
291
|
this.emit("credits.added", userId, {
|
|
280
292
|
entryId: result.entryId,
|
|
281
293
|
amount: result.amount,
|
|
@@ -295,13 +307,19 @@ export class CreditsService {
|
|
|
295
307
|
* bypass the usage-based `deduct()` flow.
|
|
296
308
|
*/
|
|
297
309
|
async deductCredits(userId, amount, options) {
|
|
298
|
-
const
|
|
310
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
311
|
+
const entryType = options.entryType ?? "adjustment";
|
|
299
312
|
this.logger.info("[CreditsService] deductCredits", {
|
|
300
313
|
amount,
|
|
301
314
|
entryType,
|
|
302
|
-
bucket: options
|
|
315
|
+
bucket: options.bucket,
|
|
316
|
+
});
|
|
317
|
+
const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), {
|
|
318
|
+
type: entryType,
|
|
319
|
+
metadata: options.metadata,
|
|
320
|
+
bucket: options.bucket,
|
|
321
|
+
idempotencyKey,
|
|
303
322
|
});
|
|
304
|
-
const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
|
|
305
323
|
this.emit("credits.deducted", userId, {
|
|
306
324
|
entryId: result.entryId,
|
|
307
325
|
amount: result.amount,
|
|
@@ -342,24 +360,34 @@ export class CreditsService {
|
|
|
342
360
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
343
361
|
*/
|
|
344
362
|
async grantSubscriptionCycle(userId, amount, options) {
|
|
363
|
+
return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
|
|
364
|
+
}
|
|
365
|
+
async grantSubscriptionCycleUninstrumented(userId, amount, options) {
|
|
366
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
345
367
|
this.logger.info("[CreditsService] grantSubscriptionCycle", {
|
|
346
368
|
amount,
|
|
347
|
-
bucket: options
|
|
348
|
-
planKey: options
|
|
369
|
+
bucket: options.bucket,
|
|
370
|
+
planKey: options.planKey,
|
|
349
371
|
});
|
|
350
|
-
if (options
|
|
372
|
+
if (options.expiresAt != null && options.ttlDays != null) {
|
|
351
373
|
throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
|
|
352
374
|
}
|
|
353
|
-
const bucket = options
|
|
354
|
-
const expiresAt = options
|
|
375
|
+
const bucket = options.bucket ?? "subscription";
|
|
376
|
+
const expiresAt = options.ttlDays != null
|
|
355
377
|
? new Date(Date.now() + options.ttlDays * 86_400_000)
|
|
356
|
-
: options
|
|
378
|
+
: options.expiresAt;
|
|
357
379
|
const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
|
|
358
|
-
const result = await this.store.addCredits(userId, amountDec,
|
|
380
|
+
const result = await this.store.addCredits(userId, amountDec, {
|
|
381
|
+
type: "purchase",
|
|
382
|
+
metadata: options.metadata,
|
|
383
|
+
expiresAt,
|
|
384
|
+
bucket,
|
|
385
|
+
idempotencyKey,
|
|
386
|
+
});
|
|
359
387
|
// The store contract exposes the mutation's replay result directly, avoiding
|
|
360
388
|
// a racy lifetime-balance comparison and an extra database round trip.
|
|
361
389
|
const isFreshGrant = !result.idempotent;
|
|
362
|
-
if (options
|
|
390
|
+
if (options.planKey) {
|
|
363
391
|
// A fresh cycle intentionally re-anchors plan-assignment windows. On a
|
|
364
392
|
// webhook replay, repair a previously interrupted grant->assignment saga
|
|
365
393
|
// without re-anchoring an assignment that already succeeded.
|
|
@@ -372,21 +400,21 @@ export class CreditsService {
|
|
|
372
400
|
amount: amountDec,
|
|
373
401
|
newBalance: result.newBalance,
|
|
374
402
|
bucket,
|
|
375
|
-
planKey: options
|
|
376
|
-
idempotencyKey
|
|
403
|
+
planKey: options.planKey ?? null,
|
|
404
|
+
idempotencyKey,
|
|
377
405
|
idempotent: result.idempotent,
|
|
378
406
|
});
|
|
379
407
|
return result;
|
|
380
408
|
}
|
|
381
409
|
// ── Lease lifecycle: atomic admission ───────────────────────────────
|
|
382
410
|
async reserve(userId, metricsOrAmount, options) {
|
|
383
|
-
return this.leases.reserve(userId, metricsOrAmount, options);
|
|
411
|
+
return this.instrumentation.run("credits.reserve", undefined, () => this.leases.reserve(userId, metricsOrAmount, options));
|
|
384
412
|
}
|
|
385
413
|
async settle(userId, leaseId, metricsOrAmount, options) {
|
|
386
|
-
return this.leases.settle(userId, leaseId, metricsOrAmount, options);
|
|
414
|
+
return this.instrumentation.run("credits.settle", undefined, () => this.leases.settle(userId, leaseId, metricsOrAmount, options));
|
|
387
415
|
}
|
|
388
416
|
async release(userId, leaseId) {
|
|
389
|
-
return this.leases.release(userId, leaseId);
|
|
417
|
+
return this.instrumentation.run("credits.release", undefined, () => this.leases.release(userId, leaseId));
|
|
390
418
|
}
|
|
391
419
|
async renew(userId, leaseId, ttl) {
|
|
392
420
|
return this.leases.renew(userId, leaseId, ttl);
|
|
@@ -418,21 +446,24 @@ export class CreditsService {
|
|
|
418
446
|
* typed exception is thrown. No success event is emitted on error.
|
|
419
447
|
*/
|
|
420
448
|
async deduct(userId, metrics, options) {
|
|
449
|
+
return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
|
|
450
|
+
}
|
|
451
|
+
async deductUninstrumented(userId, metrics, options) {
|
|
421
452
|
await this.maybeLazyExpire(userId);
|
|
422
453
|
this.logger.debug("[CreditsService] deduct", {
|
|
423
454
|
model: metrics.dimensions?.model,
|
|
424
|
-
feature: options
|
|
455
|
+
feature: options.feature,
|
|
425
456
|
});
|
|
426
457
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
427
458
|
const plan = await this.store.getUserPlan(userId);
|
|
428
|
-
const effectiveIdempotencyKey = options?.idempotencyKey
|
|
459
|
+
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
429
460
|
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
430
461
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
431
462
|
const cost = breakdown.total;
|
|
432
463
|
// Build ledger metadata: caller fields FIRST, system fields LAST so the
|
|
433
464
|
// protected system fields win.
|
|
434
465
|
const meta = {};
|
|
435
|
-
if (options
|
|
466
|
+
if (options.metadata) {
|
|
436
467
|
for (const [k, v] of Object.entries(options.metadata)) {
|
|
437
468
|
if (v != null)
|
|
438
469
|
meta[k] = v;
|
|
@@ -446,7 +477,7 @@ export class CreditsService {
|
|
|
446
477
|
const deductionOptions = {
|
|
447
478
|
idempotencyKey: effectiveIdempotencyKey,
|
|
448
479
|
operation: metrics.operation,
|
|
449
|
-
feature: options
|
|
480
|
+
feature: options.feature ?? null,
|
|
450
481
|
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
451
482
|
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
452
483
|
measures: { ...(metrics.measures ?? {}) },
|
|
@@ -464,7 +495,7 @@ export class CreditsService {
|
|
|
464
495
|
error: result.error,
|
|
465
496
|
amount: cost,
|
|
466
497
|
model: metrics.dimensions?.model,
|
|
467
|
-
feature: options
|
|
498
|
+
feature: options.feature,
|
|
468
499
|
});
|
|
469
500
|
this.emit("credits.deduct_failed", userId, {
|
|
470
501
|
error: result.error,
|
|
@@ -502,10 +533,10 @@ export class CreditsService {
|
|
|
502
533
|
async recordUsage(userId, metrics, options) {
|
|
503
534
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
504
535
|
const plan = await this.store.getUserPlan(userId);
|
|
505
|
-
const effectiveIdempotencyKey = options?.idempotencyKey
|
|
536
|
+
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
506
537
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
507
538
|
const meta = {};
|
|
508
|
-
if (options
|
|
539
|
+
if (options.metadata) {
|
|
509
540
|
for (const [key, value] of Object.entries(options.metadata)) {
|
|
510
541
|
if (value != null)
|
|
511
542
|
meta[key] = value;
|
|
@@ -543,13 +574,21 @@ export class CreditsService {
|
|
|
543
574
|
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
|
|
544
575
|
}
|
|
545
576
|
async refundCredits(entryId, options) {
|
|
546
|
-
|
|
577
|
+
return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
|
|
578
|
+
}
|
|
579
|
+
async refundCreditsUninstrumented(entryId, options) {
|
|
580
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
581
|
+
const refundAmount = options.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
|
|
547
582
|
this.logger.info("[CreditsService] refundCredits", {
|
|
548
583
|
entryId,
|
|
549
584
|
refundAmount,
|
|
550
|
-
reason: options
|
|
585
|
+
reason: options.reason,
|
|
586
|
+
});
|
|
587
|
+
const result = await this.store.refundCredits(entryId, {
|
|
588
|
+
...options,
|
|
589
|
+
amount: refundAmount,
|
|
590
|
+
idempotencyKey,
|
|
551
591
|
});
|
|
552
|
-
const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
|
|
553
592
|
if (result.error !== null) {
|
|
554
593
|
this.logger.warn("[CreditsService] refundCredits failed", {
|
|
555
594
|
entryId,
|
|
@@ -559,7 +598,7 @@ export class CreditsService {
|
|
|
559
598
|
this.emit("credits.refund_failed", result.userId, {
|
|
560
599
|
entryId,
|
|
561
600
|
error: result.error,
|
|
562
|
-
reason: options
|
|
601
|
+
reason: options.reason ?? null,
|
|
563
602
|
});
|
|
564
603
|
}
|
|
565
604
|
throw new RefundError(`Refund rejected: ${result.error}`);
|
|
@@ -569,7 +608,7 @@ export class CreditsService {
|
|
|
569
608
|
refundEntryId: result.refundEntryId,
|
|
570
609
|
amount: result.amount,
|
|
571
610
|
newBalance: result.newBalance,
|
|
572
|
-
reason: options
|
|
611
|
+
reason: options.reason ?? null,
|
|
573
612
|
});
|
|
574
613
|
return result;
|
|
575
614
|
}
|
|
@@ -577,10 +616,11 @@ export class CreditsService {
|
|
|
577
616
|
* Deduct from a team's shared balance pool.
|
|
578
617
|
*
|
|
579
618
|
* Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
|
|
580
|
-
* then debits the team balance. Threads
|
|
619
|
+
* then debits the team balance. Threads a required ``idempotencyKey`` through
|
|
581
620
|
* to the store so retried team charges are not double-counted.
|
|
582
621
|
*/
|
|
583
622
|
async deductTeam(teamId, userId, metrics, options) {
|
|
623
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
584
624
|
await this.maybeLazyExpire(userId);
|
|
585
625
|
// Lazy expiry is scoped to the individual member's credits, not the team's
|
|
586
626
|
// shared pool — there's no per-team expiry concept.
|
|
@@ -604,13 +644,16 @@ export class CreditsService {
|
|
|
604
644
|
};
|
|
605
645
|
}
|
|
606
646
|
const teamMetadata = {
|
|
607
|
-
...(options
|
|
647
|
+
...(options.metadata ?? {}),
|
|
608
648
|
operation: metrics.operation,
|
|
609
649
|
measures: { ...(metrics.measures ?? {}) },
|
|
610
650
|
dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
|
|
611
651
|
breakdownTotal: breakdown.total.toString(),
|
|
612
652
|
};
|
|
613
|
-
const result = await this.store.deductTeam(teamId, userId, cost,
|
|
653
|
+
const result = await this.store.deductTeam(teamId, userId, cost, {
|
|
654
|
+
metadata: teamMetadata,
|
|
655
|
+
idempotencyKey,
|
|
656
|
+
});
|
|
614
657
|
// Surface store errors: emit credits.deduct_failed and throw,
|
|
615
658
|
// mirroring the Python credit service implementation. Previously returned a silent
|
|
616
659
|
// success-shaped object with an .error field, so failed charges looked OK.
|