@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
|
@@ -6,21 +6,16 @@ import type { DeductionSuccess } from "./types/index.js";
|
|
|
6
6
|
import type { LowBalanceConfig } from "./service-types.js";
|
|
7
7
|
type EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* Keeping this state outside CreditsService makes the event semantics
|
|
12
|
-
* independently testable and keeps the service focused on orchestration.
|
|
9
|
+
* Emits notifications from committed balance changes without per-user state.
|
|
13
10
|
*/
|
|
14
11
|
export declare class LowBalanceMonitor {
|
|
15
12
|
private readonly emit;
|
|
16
13
|
private readonly logger;
|
|
17
14
|
private readonly thresholds;
|
|
18
15
|
private readonly handler;
|
|
19
|
-
private readonly breachedByUser;
|
|
20
16
|
constructor(config: LowBalanceConfig | null | undefined, emit: EmitCreditEvent, logger: NormalizedLogger);
|
|
21
|
-
rearmAfterCredit(userId: string, balance: Decimal): void;
|
|
22
17
|
afterCharge(userId: string, result: DeductionSuccess): Promise<void>;
|
|
23
|
-
signalCrossing(userId: string, balanceBefore: Decimal, balanceAfter: Decimal): Promise<void>;
|
|
18
|
+
signalCrossing(userId: string, balanceBefore: Decimal, balanceAfter: Decimal, context?: StructuredObject): Promise<void>;
|
|
24
19
|
private fire;
|
|
25
20
|
}
|
|
26
21
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAG3D,KAAK,eAAe,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAEhG;;GAEG;AACH,qBAAa,iBAAiB;IAM1B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IANzB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAEhF,YACE,MAAM,EAAE,gBAAgB,GAAG,IAAI,GAAG,SAAS,EAC1B,IAAI,EAAE,eAAe,EACrB,MAAM,EAAE,gBAAgB,EAM1C;IAEK,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CASzE;IAEK,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,OAAO,EACtB,YAAY,EAAE,OAAO,EACrB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,IAAI,CAAC,CAUf;YAEa,IAAI;CAwBnB"}
|
|
@@ -1,19 +1,13 @@
|
|
|
1
1
|
import { Decimal } from "decimal.js";
|
|
2
|
-
import { LRUCache } from "lru-cache";
|
|
3
2
|
import { toDecimal } from "./amount.js";
|
|
4
|
-
const DEFAULT_MAX_TRACKED_USERS = 100_000;
|
|
5
3
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* Keeping this state outside CreditsService makes the event semantics
|
|
9
|
-
* independently testable and keeps the service focused on orchestration.
|
|
4
|
+
* Emits notifications from committed balance changes without per-user state.
|
|
10
5
|
*/
|
|
11
6
|
export class LowBalanceMonitor {
|
|
12
7
|
emit;
|
|
13
8
|
logger;
|
|
14
9
|
thresholds;
|
|
15
10
|
handler;
|
|
16
|
-
breachedByUser;
|
|
17
11
|
constructor(config, emit, logger) {
|
|
18
12
|
this.emit = emit;
|
|
19
13
|
this.logger = logger;
|
|
@@ -21,26 +15,6 @@ export class LowBalanceMonitor {
|
|
|
21
15
|
? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))
|
|
22
16
|
: null;
|
|
23
17
|
this.handler = config?.onTrigger ?? null;
|
|
24
|
-
const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;
|
|
25
|
-
if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {
|
|
26
|
-
throw new RangeError("lowBalance.maxTrackedUsers must be a positive safe integer");
|
|
27
|
-
}
|
|
28
|
-
this.breachedByUser = new LRUCache({ max: maxTrackedUsers });
|
|
29
|
-
}
|
|
30
|
-
rearmAfterCredit(userId, balance) {
|
|
31
|
-
if (!this.thresholds)
|
|
32
|
-
return;
|
|
33
|
-
const breached = this.breachedByUser.get(userId) ?? new Set();
|
|
34
|
-
for (const threshold of this.thresholds) {
|
|
35
|
-
if (balance.gt(threshold))
|
|
36
|
-
breached.delete(threshold.toString());
|
|
37
|
-
}
|
|
38
|
-
if (breached.size === 0) {
|
|
39
|
-
this.breachedByUser.delete(userId);
|
|
40
|
-
}
|
|
41
|
-
else {
|
|
42
|
-
this.breachedByUser.set(userId, breached);
|
|
43
|
-
}
|
|
44
18
|
}
|
|
45
19
|
async afterCharge(userId, result) {
|
|
46
20
|
if (result.idempotent)
|
|
@@ -53,40 +27,15 @@ export class LowBalanceMonitor {
|
|
|
53
27
|
}
|
|
54
28
|
await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);
|
|
55
29
|
}
|
|
56
|
-
async signalCrossing(userId, balanceBefore, balanceAfter) {
|
|
57
|
-
|
|
58
|
-
const threshold = new Decimal(0);
|
|
59
|
-
if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {
|
|
60
|
-
await this.fire(userId, balanceAfter, threshold);
|
|
61
|
-
}
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
const breached = this.breachedByUser.get(userId) ?? new Set();
|
|
65
|
-
const newlyCrossed = [];
|
|
66
|
-
for (const threshold of this.thresholds) {
|
|
67
|
-
if (balanceAfter.lte(threshold)) {
|
|
68
|
-
if (!breached.has(threshold.toString())) {
|
|
69
|
-
breached.add(threshold.toString());
|
|
70
|
-
newlyCrossed.push(threshold);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
else {
|
|
74
|
-
breached.delete(threshold.toString());
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
if (breached.size === 0) {
|
|
78
|
-
this.breachedByUser.delete(userId);
|
|
79
|
-
}
|
|
80
|
-
else {
|
|
81
|
-
this.breachedByUser.set(userId, breached);
|
|
82
|
-
}
|
|
30
|
+
async signalCrossing(userId, balanceBefore, balanceAfter, context) {
|
|
31
|
+
const newlyCrossed = (this.thresholds ?? [new Decimal(0)]).filter((threshold) => balanceBefore.gt(threshold) && balanceAfter.lte(threshold));
|
|
83
32
|
if (newlyCrossed.length > 0) {
|
|
84
33
|
const lowest = newlyCrossed.reduce((minimum, threshold) => threshold.lt(minimum) ? threshold : minimum);
|
|
85
|
-
await this.fire(userId, balanceAfter, lowest);
|
|
34
|
+
await this.fire(userId, balanceAfter, lowest, context);
|
|
86
35
|
}
|
|
87
36
|
}
|
|
88
|
-
async fire(userId, balance, threshold) {
|
|
89
|
-
const data = { balance, threshold };
|
|
37
|
+
async fire(userId, balance, threshold, context) {
|
|
38
|
+
const data = { ...context, balance, threshold };
|
|
90
39
|
this.emit("credits.low_balance", userId, data);
|
|
91
40
|
if (!this.handler)
|
|
92
41
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAOrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAIxC;;GAEG;AACH,MAAM,OAAO,iBAAiB;IAMT,IAAI;IACJ,MAAM;IANR,UAAU,CAAmB;IAC7B,OAAO,CAAwD;IAEhF,YACE,MAA2C,EAC1B,IAAqB,EACrB,MAAwB;oBADxB,IAAI;sBACJ,MAAM;QAEvB,IAAI,CAAC,UAAU,GAAG,MAAM,EAAE,UAAU,EAAE,MAAM;YAC1C,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChF,CAAC,CAAC,IAAI,CAAC;QACT,IAAI,CAAC,OAAO,GAAG,MAAM,EAAE,SAAS,IAAI,IAAI,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,MAAc,EAAE,MAAwB;QACxD,IAAI,MAAM,CAAC,UAAU;YAAE,OAAO;QAC9B,IAAI,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9B,IAAI,C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C,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\ntype EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;\n\n/**\n * Emits notifications from committed balance changes without per-user state.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n context?: StructuredObject,\n ): Promise<void> {\n const newlyCrossed = (this.thresholds ?? [new Decimal(0)]).filter(\n (threshold) => balanceBefore.gt(threshold) && balanceAfter.lte(threshold),\n );\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest, context);\n }\n }\n\n private async fire(\n userId: string,\n balance: Decimal,\n threshold: Decimal,\n context?: StructuredObject,\n ): Promise<void> {\n const data = { ...context, balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
|
|
@@ -36,7 +36,7 @@ declare const LedgerEntryRowSchema: z.ZodObject<{
|
|
|
36
36
|
reference_entry_id: z.ZodNullable<z.ZodString>;
|
|
37
37
|
idempotency_key: z.ZodNullable<z.ZodString>;
|
|
38
38
|
metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
|
|
39
|
-
created_at: z.ZodUnion<readonly [z.ZodString, z.
|
|
39
|
+
created_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<string, string | Date>>;
|
|
40
40
|
}, z.core.$strict>;
|
|
41
41
|
declare const UsageChargeRowSchema: z.ZodObject<{
|
|
42
42
|
usage_id: z.ZodString;
|
|
@@ -53,10 +53,10 @@ declare const UsageChargeRowSchema: z.ZodObject<{
|
|
|
53
53
|
feature: z.ZodNullable<z.ZodString>;
|
|
54
54
|
model: z.ZodNullable<z.ZodString>;
|
|
55
55
|
region: z.ZodNullable<z.ZodString>;
|
|
56
|
-
event_at: z.ZodUnion<readonly [z.ZodString, z.
|
|
56
|
+
event_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<string, string | Date>>;
|
|
57
57
|
idempotency_key: z.ZodString;
|
|
58
58
|
metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
|
|
59
|
-
created_at: z.ZodUnion<readonly [z.ZodString, z.
|
|
59
|
+
created_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<string, string | Date>>;
|
|
60
60
|
}, z.core.$strict>;
|
|
61
61
|
export type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;
|
|
62
62
|
export type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAuBlE,QAAA,MAAM,oBAAoB;;;;kBAMf,CAAC;AAEZ,QAAA,MAAM,qBAAqB;;;;kBAMhB,CAAC;AAEZ,QAAA,MAAM,gBAAgB;;;kBAA0E,CAAC;AAEjG,QAAA,MAAM,mBAAmB;;;;kBAMd,CAAC;AAEZ,QAAA,MAAM,uBAAuB;;;;;;kBAQlB,CAAC;AAEZ,QAAA,MAAM,oBAAoB;;;;;;;;;;;kBAaf,CAAC;AAEZ,QAAA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;kBAkBf,CAAC;AAEZ,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,C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AAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,EACb,eAAe,EAAE,MAAM,GAAG,IAAI,EAC9B,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,SAAS,UAAQ,GAChB,OAAO,CAAC,cAAc,EAAE,CAAC,CAiB3B;IAEK,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAMpF;IAEK,gBAAgB,CACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,iBAAiB,EAAE,OAAO,GACzB,OAAO,CAAC,cAAc,EAAE,CAAC,CAgB3B;CACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { StoreError } from "../../../errors.js";
|
|
3
|
+
import { utcTimestamp } from "../../../shared/timestamp.js";
|
|
3
4
|
import { isPostgresRow } from "../../../shared/json.js";
|
|
4
5
|
import { optionalRecordRow, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
5
6
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
@@ -7,10 +8,15 @@ const count = z.union([
|
|
|
7
8
|
z.number().int().nonnegative(),
|
|
8
9
|
z.string().regex(/^\d+$/).transform(Number),
|
|
9
10
|
]);
|
|
10
|
-
const timestamp = z
|
|
11
|
+
const timestamp = z
|
|
12
|
+
.union([z.string().min(1), z.date()])
|
|
13
|
+
.transform((value) => (value instanceof Date ? value.toISOString() : utcTimestamp(value)));
|
|
11
14
|
const calendarDate = z.union([
|
|
12
15
|
z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
13
|
-
|
|
16
|
+
// node-postgres parses DATE as local midnight, not as a UTC timestamp.
|
|
17
|
+
z
|
|
18
|
+
.date()
|
|
19
|
+
.transform((value) => `${String(value.getFullYear()).padStart(4, "0")}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`),
|
|
14
20
|
]);
|
|
15
21
|
const SpendByUserRowSchema = z
|
|
16
22
|
.object({
|
|
@@ -91,19 +97,27 @@ export class AnalyticsRepository {
|
|
|
91
97
|
const rows = await this.callproc("spend_by_user", [start, end]);
|
|
92
98
|
return (rows ?? []).map((raw) => {
|
|
93
99
|
const row = requireAnalyticsRow(raw, "AnalyticsRepository.spendByUser");
|
|
94
|
-
return safeParse(SpendByUserRowSchema, {
|
|
100
|
+
return safeParse(SpendByUserRowSchema, {
|
|
101
|
+
user_id: row.subject_id,
|
|
102
|
+
total_spend: row.total_spend,
|
|
103
|
+
entry_count: row.charge_count,
|
|
104
|
+
}, "AnalyticsRepository.spendByUser");
|
|
95
105
|
});
|
|
96
106
|
}
|
|
97
107
|
async spendByModel(start, end) {
|
|
98
108
|
const rows = await this.callproc("spend_by_model", [start, end]);
|
|
99
109
|
return (rows ?? []).map((raw) => {
|
|
100
110
|
const row = requireAnalyticsRow(raw, "AnalyticsRepository.spendByModel");
|
|
101
|
-
return safeParse(SpendByModelRowSchema, {
|
|
111
|
+
return safeParse(SpendByModelRowSchema, {
|
|
112
|
+
model: row.model,
|
|
113
|
+
total_spend: row.total_spend,
|
|
114
|
+
entry_count: row.charge_count,
|
|
115
|
+
}, "AnalyticsRepository.spendByModel");
|
|
102
116
|
});
|
|
103
117
|
}
|
|
104
118
|
async topUsers(limit, start, end) {
|
|
105
|
-
const rows = await this.callproc("spend_by_user", [start, end]);
|
|
106
|
-
return (rows ?? []).
|
|
119
|
+
const rows = await this.callproc("spend_by_user", [start, end, limit]);
|
|
120
|
+
return (rows ?? []).map((raw) => {
|
|
107
121
|
const row = requireAnalyticsRow(raw, "AnalyticsRepository.topUsers");
|
|
108
122
|
return safeParse(TopUserRowSchema, { user_id: row.subject_id, total_spend: row.total_spend }, "AnalyticsRepository.topUsers");
|
|
109
123
|
});
|
|
@@ -112,7 +126,11 @@ export class AnalyticsRepository {
|
|
|
112
126
|
const rows = await this.callproc("daily_spend", [start, end]);
|
|
113
127
|
return (rows ?? []).map((raw) => {
|
|
114
128
|
const row = requireAnalyticsRow(raw, "AnalyticsRepository.dailySpend");
|
|
115
|
-
return safeParse(DailySpendRowSchema, {
|
|
129
|
+
return safeParse(DailySpendRowSchema, {
|
|
130
|
+
date: row.day,
|
|
131
|
+
total_spend: row.total_spend,
|
|
132
|
+
entry_count: row.charge_count,
|
|
133
|
+
}, "AnalyticsRepository.dailySpend");
|
|
116
134
|
});
|
|
117
135
|
}
|
|
118
136
|
async aggregateStats(start, end) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,aAAa,EAAwC,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAElG,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;IACpB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE;IAC9B,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC;CAC5C,C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nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { isPostgresRow, type PostgresRow, type PostgresValue } from \"../../../shared/json.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z.union([z.string().min(1), z.date().transform((value) => value.toISOString())]);\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n z.date().transform((value) => value.toISOString().slice(0, 10)),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nfunction requireAnalyticsRow(value: PostgresValue, context: string): PostgresRow {\n if (!isPostgresRow(value)) {\n throw new StoreError(`${context}: expected an object result row`);\n }\n return value;\n}\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByUser\");\n return safeParse(\n SpendByUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByModel\");\n return safeParse(\n SpendByModelRowSchema,\n { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).slice(0, limit).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.topUsers\");\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.dailySpend\");\n return safeParse(\n DailySpendRowSchema,\n { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAwC,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAElG,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;IACpB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE;IAC9B,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC;CAC5C,CAAC,CAAC;AACH,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;KACpC,SAAS,CAAC,CAAC,KAAK,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AE,CAC9B,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,sCAAsC,CAAC,CAC7E,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport { utcTimestamp } from \"../../../shared/timestamp.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { isPostgresRow, type PostgresRow, type PostgresValue } from \"../../../shared/json.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z\n .union([z.string().min(1), z.date()])\n .transform((value) => (value instanceof Date ? value.toISOString() : utcTimestamp(value)));\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n // node-postgres parses DATE as local midnight, not as a UTC timestamp.\n z\n .date()\n .transform(\n (value) =>\n `${String(value.getFullYear()).padStart(4, \"0\")}-${String(value.getMonth() + 1).padStart(2, \"0\")}-${String(value.getDate()).padStart(2, \"0\")}`,\n ),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nfunction requireAnalyticsRow(value: PostgresValue, context: string): PostgresRow {\n if (!isPostgresRow(value)) {\n throw new StoreError(`${context}: expected an object result row`);\n }\n return value;\n}\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByUser\");\n return safeParse(\n SpendByUserRowSchema,\n {\n user_id: row.subject_id,\n total_spend: row.total_spend,\n entry_count: row.charge_count,\n },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByModel\");\n return safeParse(\n SpendByModelRowSchema,\n {\n model: row.model,\n total_spend: row.total_spend,\n entry_count: row.charge_count,\n },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end, limit]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.topUsers\");\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.dailySpend\");\n return safeParse(\n DailySpendRowSchema,\n {\n date: row.day,\n total_spend: row.total_spend,\n entry_count: row.charge_count,\n },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import type { CallProc } from "../../../shared/postgres-types.js";
|
|
3
|
+
import type { AccountCreatedInput } from "../../types/index.js";
|
|
3
4
|
declare const BalanceRowSchema: z.ZodObject<{
|
|
4
5
|
user_id: z.ZodString;
|
|
5
6
|
balance: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
@@ -49,6 +50,33 @@ export declare class BalanceRepository {
|
|
|
49
50
|
addCredits(userId: string, amount: string, type: string, metadata: string, expiresAt: string | null, bucket: string | null, idempotencyKey: string | null): Promise<AddCreditsRow>;
|
|
50
51
|
/** Fetch available balance (balance minus reserved holds). */
|
|
51
52
|
getAvailable(userId: string): Promise<AvailableRow | null>;
|
|
53
|
+
provisionAccount(input: AccountCreatedInput): Promise<{
|
|
54
|
+
plan_key: string;
|
|
55
|
+
plan_assigned: boolean;
|
|
56
|
+
grants: {
|
|
57
|
+
grant_event_id: string | null;
|
|
58
|
+
grant_award_id: string | null;
|
|
59
|
+
recipient_subject_id: string | null;
|
|
60
|
+
ledger_entry_id: string | null;
|
|
61
|
+
amount: string | number | null;
|
|
62
|
+
replayed: boolean;
|
|
63
|
+
error_code: string | null;
|
|
64
|
+
}[];
|
|
65
|
+
error_code: null;
|
|
66
|
+
} | {
|
|
67
|
+
plan_key: null;
|
|
68
|
+
plan_assigned: false;
|
|
69
|
+
grants: {
|
|
70
|
+
grant_event_id: string | null;
|
|
71
|
+
grant_award_id: string | null;
|
|
72
|
+
recipient_subject_id: string | null;
|
|
73
|
+
ledger_entry_id: string | null;
|
|
74
|
+
amount: string | number | null;
|
|
75
|
+
replayed: boolean;
|
|
76
|
+
error_code: string | null;
|
|
77
|
+
}[];
|
|
78
|
+
error_code: "missing_active_catalog" | "missing_default_plan";
|
|
79
|
+
}>;
|
|
52
80
|
/** Execute a configured grant-program event and return every award row. */
|
|
53
81
|
executeGrantProgram(params: {
|
|
54
82
|
trigger: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAUhE,QAAA,MAAM,gBAAgB;;;;kBAMX,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAgDrB,CAAC;AAEL,QAAA,MAAM,kBAAkB;;;;kBAMb,CAAC;AAEZ,QAAA,MAAM,0BAA0B;;;;;;;;kBA+B5B,CAAC;AAEL,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO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AAoB,EAAE,CAAC,CAalC;CACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { PricingDecimal } from "../../../pricing-decimal.js";
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
3
|
-
import { pgBoolean, postgresUuid, requireRecordRow,
|
|
3
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
4
|
+
import { pgBoolean, postgresUuid, requireRecordRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
5
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
6
|
const BalanceRowSchema = z
|
|
6
7
|
.object({
|
|
@@ -29,7 +30,7 @@ const AddCreditsRowSchema = z
|
|
|
29
30
|
message: "successful credit postings require entry and balance fields",
|
|
30
31
|
});
|
|
31
32
|
}
|
|
32
|
-
const amount = new
|
|
33
|
+
const amount = new PricingDecimal(row.amount);
|
|
33
34
|
if (row.error === null && amount.isPositive() && row.bucket === null) {
|
|
34
35
|
context.addIssue({
|
|
35
36
|
code: "custom",
|
|
@@ -93,6 +94,20 @@ const GrantProgramAwardRowSchema = z
|
|
|
93
94
|
});
|
|
94
95
|
}
|
|
95
96
|
});
|
|
97
|
+
const SignupRowSchema = z.discriminatedUnion("error_code", [
|
|
98
|
+
z.object({
|
|
99
|
+
plan_key: z.string().min(1),
|
|
100
|
+
plan_assigned: z.boolean(),
|
|
101
|
+
grants: z.array(GrantProgramAwardRowSchema),
|
|
102
|
+
error_code: z.null(),
|
|
103
|
+
}),
|
|
104
|
+
z.object({
|
|
105
|
+
plan_key: z.null(),
|
|
106
|
+
plan_assigned: z.literal(false),
|
|
107
|
+
grants: z.array(GrantProgramAwardRowSchema).length(0),
|
|
108
|
+
error_code: z.enum(["missing_active_catalog", "missing_default_plan"]),
|
|
109
|
+
}),
|
|
110
|
+
]);
|
|
96
111
|
/** Repository for user credit balance operations.
|
|
97
112
|
*
|
|
98
113
|
* All methods call Postgres RPCs via the callproc function.
|
|
@@ -119,7 +134,7 @@ export class BalanceRepository {
|
|
|
119
134
|
}
|
|
120
135
|
/** Add credits to a user's account. */
|
|
121
136
|
async addCredits(userId, amount, type, metadata, expiresAt, bucket, idempotencyKey) {
|
|
122
|
-
const decimalAmount = new
|
|
137
|
+
const decimalAmount = new PricingDecimal(amount);
|
|
123
138
|
const rows = await this.callproc("post_credit", [
|
|
124
139
|
userId,
|
|
125
140
|
decimalAmount.isNegative() ? "adjustment" : type === "purchase" ? "purchase" : "grant",
|
|
@@ -133,19 +148,13 @@ export class BalanceRepository {
|
|
|
133
148
|
"0",
|
|
134
149
|
]);
|
|
135
150
|
const row = requireRecordRow(rows, "BalanceRepository.addCredits");
|
|
136
|
-
const state = row.error_code == null
|
|
137
|
-
? optionalRecordRow(await this.callproc("get_credit_state", [userId]), "BalanceRepository.addCredits.state")
|
|
138
|
-
: undefined;
|
|
139
|
-
const grant = row.error_code == null && decimalAmount.isPositive() && row.entry_id != null
|
|
140
|
-
? optionalRecordRow(await this.callproc("get_credit_grant_details", [userId, row.entry_id]), "BalanceRepository.addCredits.grant")
|
|
141
|
-
: undefined;
|
|
142
151
|
return safeParse(AddCreditsRowSchema, {
|
|
143
152
|
entry_id: row.entry_id ?? null,
|
|
144
153
|
user_id: userId,
|
|
145
|
-
amount,
|
|
146
|
-
new_balance: row.balance_after ?? null,
|
|
147
|
-
lifetime_purchased:
|
|
148
|
-
bucket:
|
|
154
|
+
amount: row.error_code == null ? quantizeMoney(decimalAmount).toString() : amount,
|
|
155
|
+
new_balance: row.error_code == null ? (row.balance_after ?? null) : null,
|
|
156
|
+
lifetime_purchased: row.lifetime_purchased ?? null,
|
|
157
|
+
bucket: row.resolved_bucket_key ?? null,
|
|
149
158
|
idempotent: row.replayed,
|
|
150
159
|
error: row.error_code,
|
|
151
160
|
}, "BalanceRepository.addCredits");
|
|
@@ -163,6 +172,16 @@ export class BalanceRepository {
|
|
|
163
172
|
available: row.available,
|
|
164
173
|
}, "BalanceRepository.getAvailable");
|
|
165
174
|
}
|
|
175
|
+
async provisionAccount(input) {
|
|
176
|
+
const rows = await this.callproc("provision_subject_account", [
|
|
177
|
+
input.accountId,
|
|
178
|
+
input.eventKey,
|
|
179
|
+
input.region ?? null,
|
|
180
|
+
JSON.stringify(input.metadata ?? {}),
|
|
181
|
+
]);
|
|
182
|
+
const context = "BalanceRepository.provisionAccount";
|
|
183
|
+
return safeParse(SignupRowSchema, requireRecordRow(rows, context), context);
|
|
184
|
+
}
|
|
166
185
|
/** Execute a configured grant-program event and return every award row. */
|
|
167
186
|
async executeGrantProgram(params) {
|
|
168
187
|
const rows = await this.callproc("execute_grant_program", [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,OAAO,EAAE,OAAO;IAChB,kBAAkB,EAAE,OAAO;CAC5B,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG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\"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n optionalRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRecordRow(rows, \"BalanceRepository.getBalance\");\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRecordRow(rows, \"BalanceRepository.addCredits\");\n const state =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_state\", [userId]),\n \"BalanceRepository.addCredits.state\",\n )\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]),\n \"BalanceRepository.addCredits.grant\",\n )\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRecordRow(rows, \"BalanceRepository.getAvailable\");\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,C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C,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport { quantizeMoney } from \"../../../expr.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport type { AccountCreatedInput } from \"../../types/index.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new PricingDecimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\nconst SignupRowSchema = z.discriminatedUnion(\"error_code\", [\n z.object({\n plan_key: z.string().min(1),\n plan_assigned: z.boolean(),\n grants: z.array(GrantProgramAwardRowSchema),\n error_code: z.null(),\n }),\n z.object({\n plan_key: z.null(),\n plan_assigned: z.literal(false),\n grants: z.array(GrantProgramAwardRowSchema).length(0),\n error_code: z.enum([\"missing_active_catalog\", \"missing_default_plan\"]),\n }),\n]);\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRecordRow(rows, \"BalanceRepository.getBalance\");\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new PricingDecimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRecordRow(rows, \"BalanceRepository.addCredits\");\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount: row.error_code == null ? quantizeMoney(decimalAmount).toString() : amount,\n new_balance: row.error_code == null ? (row.balance_after ?? null) : null,\n lifetime_purchased: row.lifetime_purchased ?? null,\n bucket: row.resolved_bucket_key ?? null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRecordRow(rows, \"BalanceRepository.getAvailable\");\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n async provisionAccount(input: AccountCreatedInput) {\n const rows = await this.callproc(\"provision_subject_account\", [\n input.accountId,\n input.eventKey,\n input.region ?? null,\n JSON.stringify(input.metadata ?? {}),\n ]);\n const context = \"BalanceRepository.provisionAccount\";\n return safeParse(SignupRowSchema, requireRecordRow(rows, context), context);\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bucket.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"bucket.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAelE,QAAA,MAAM,uBAAuB;;;;;;;;;;kBAMlB,CAAC;AAEZ,QAAA,MAAM,cAAc;;;;kBAMT,CAAC;AAEZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD,+CAA+C;AAC/C,qBAAa,gBAAgB;IACf,OAAO,CAAC,QAAQ;IAA5B,YAAoB,QAAQ,EAAE,QAAQ,EAAI;IAE1C,mDAAmD;IAC7C,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiBlE;IAED,mCAAmC;IAC7B,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAOzF;CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { PricingDecimal } from "../../../pricing-decimal.js";
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
import { Decimal } from "decimal.js";
|
|
3
3
|
import { postgresUuid, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BucketRowSchema = z
|
|
@@ -36,7 +36,7 @@ export class BucketRepository {
|
|
|
36
36
|
const rows = await this.callproc("get_credit_bucket_balances", [userId]);
|
|
37
37
|
const buckets = (rows ?? []).map((row) => safeParse(BucketRowSchema, row, "BucketRepository.getBucketBalances"));
|
|
38
38
|
const totalBalance = buckets
|
|
39
|
-
.reduce((total, row) => total.plus(row.balance), new
|
|
39
|
+
.reduce((total, row) => total.plus(row.balance), new PricingDecimal(0))
|
|
40
40
|
.toString();
|
|
41
41
|
return safeParse(BucketEnvelopeRowSchema, {
|
|
42
42
|
user_id: userId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE7F,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,eAA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E,GAAG,EAAE,oCAAoC,CAAC,CACtE,CAAC;QACF,MAAM,YAAY,GAAG,OAAO;aACzB,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,cAAc,CAAC,CAAC,CAAC,CAAC;aACtE,QAAQ,EAAE,CAAC;QACd,OAAO,SAAS,CACd,uBAAuB,EACvB;YACE,OAAO,EAAE,MAAM;YACf,OAAO;YACP,aAAa,EAAE,YAAY;SAC5B,EACD,oCAAoC,CACrC,CAAC;IACJ,CAAC;IAED,mCAAmC;IACnC,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK,EAAE,MAAe,EAAE,KAAK,GAAG,GAAG;QACpE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QACxF,OAAO,SAAS,CACd,cAAc,EACd,UAAU,CAAC,IAAI,EAAE,sCAAsC,CAAC,EACxD,sCAAsC,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BucketRowSchema = z\n .object({\n bucket_key: z.string().min(1),\n label: z.string().min(1),\n priority: z.number().int().nonnegative(),\n expires: z.boolean(),\n balance: decimal,\n })\n .strict();\n\nconst BucketEnvelopeRowSchema = z\n .object({\n user_id: postgresUuid,\n buckets: z.array(BucketRowSchema),\n total_balance: decimal,\n })\n .strict();\n\nconst SweepRowSchema = z\n .object({\n expired_count: z.number().int().nonnegative(),\n expired_amount: decimal,\n expired_by_bucket: z.record(z.string().min(1), decimal),\n })\n .strict();\n\nexport type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;\nexport type SweepRow = z.infer<typeof SweepRowSchema>;\n\n/** Repository for credit bucket operations. */\nexport class BucketRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch per-bucket credit balances for a user. */\n async getBucketBalances(userId: string): Promise<BucketEnvelopeRow> {\n const rows = await this.callproc(\"get_credit_bucket_balances\", [userId]);\n const buckets = (rows ?? []).map((row) =>\n safeParse(BucketRowSchema, row, \"BucketRepository.getBucketBalances\"),\n );\n const totalBalance = buckets\n .reduce((total, row) => total.plus(row.balance), new PricingDecimal(0))\n .toString();\n return safeParse(\n BucketEnvelopeRowSchema,\n {\n user_id: userId,\n buckets,\n total_balance: totalBalance,\n },\n \"BucketRepository.getBucketBalances\",\n );\n }\n\n /** Sweep expired credit grants. */\n async sweepExpiredCredits(dryRun = false, userId?: string, limit = 100): Promise<SweepRow> {\n const rows = await this.callproc(\"sweep_expired_lots\", [limit, userId ?? null, dryRun]);\n return safeParse(\n SweepRowSchema,\n requireRow(rows, \"BucketRepository.sweepExpiredCredits\"),\n \"BucketRepository.sweepExpiredCredits\",\n );\n }\n}\n"]}
|
|
@@ -21,8 +21,8 @@ export declare class CatalogRepository {
|
|
|
21
21
|
constructor(callproc: CallProc);
|
|
22
22
|
private parseRevision;
|
|
23
23
|
getActiveCatalog(): Promise<CatalogRevisionRow | null>;
|
|
24
|
-
publishAndActivateCatalog(config:
|
|
25
|
-
publishCatalogDraft(config:
|
|
24
|
+
publishAndActivateCatalog(config: JsonObject, label: string | null, rollout: JsonObject): Promise<string>;
|
|
25
|
+
publishCatalogDraft(config: JsonObject, label: string | null): Promise<string>;
|
|
26
26
|
private publishRevision;
|
|
27
27
|
getCatalogHistory(): Promise<CatalogRevisionRow[]>;
|
|
28
28
|
getCatalogRevision(version: number): Promise<CatalogRevisionRow | null>;
|