@zonastery/bursar 2.1.1 → 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 +20 -3
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +6 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +19 -3
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +34 -5
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +12 -6
- 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 +20 -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 -0
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +40 -13
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +2 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +82 -16
- 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 +160 -48
- 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 +6 -3
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +5 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
- 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.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +2 -1
- 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 -17
- 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 +24 -4
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +40 -43
- 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 +9 -5
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +24 -31
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +110 -113
- package/dist/billing/postgres/store.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 +10 -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 +5 -17
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +26 -44
- package/dist/bursar.js.map +1 -1
- package/dist/cli.js +0 -6
- package/dist/cli.js.map +1 -1
- package/dist/commerce/service.d.ts +1 -0
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +162 -38
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +2 -0
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/normalize.d.ts +3 -1
- package/dist/config/normalize.d.ts.map +1 -1
- package/dist/config/normalize.js +12 -5
- package/dist/config/normalize.js.map +1 -1
- 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.map +1 -1
- package/dist/config/parse-commerce.js +32 -17
- 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 +5 -5
- 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 +13 -9
- 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 +7 -5
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +2 -0
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +11 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config.d.ts +2 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +94 -86
- 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 +74 -18
- 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 +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +4 -1
- 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 +29 -20
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +329 -250
- 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 +11 -9
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +156 -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/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.map +1 -1
- package/dist/engine.js +51 -34
- 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 +102 -202
- package/dist/generated/pricing-config.types.d.ts +7 -1
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +38 -12
- 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 +1 -1
- package/dist/node.d.ts.map +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 +120 -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 +33 -6
- 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 +48 -20
- 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 +64 -23
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +11 -1
- 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 +3 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +61 -49
- package/dist/shared/postgres-client.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 +2 -0
- package/dist/shared/timestamp.d.ts.map +1 -1
- package/dist/shared/timestamp.js +7 -0
- package/dist/shared/timestamp.js.map +1 -1
- 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 +18 -17
- 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 +3 -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 +10 -4
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +15 -10
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +74 -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 +73 -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
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import { PricingDecimal } from "../../pricing-decimal.js";
|
|
1
2
|
import { Decimal } from "decimal.js";
|
|
2
3
|
import { z } from "zod";
|
|
3
|
-
import { StoreClosedError, StoreError } from "../../errors.js";
|
|
4
|
-
import {
|
|
5
|
-
import { PostgresClient, } from "../../shared/postgres-client.js";
|
|
4
|
+
import { CatalogNotLoadedError, ConfigError, StaleQuoteError, StoreClosedError, StoreError, } from "../../errors.js";
|
|
5
|
+
import { canonicalParsedBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
|
|
6
|
+
import { PostgresClient, normalizeTenantId, } from "../../shared/postgres-client.js";
|
|
7
|
+
import { normalizeProviderEnvironment } from "../../providers/environment.js";
|
|
6
8
|
import { requireStableKey } from "../../shared/idempotency.js";
|
|
7
9
|
import { CreditStore } from "../store.js";
|
|
8
|
-
import { BalanceRepository } from "./repositories/balance.js";
|
|
10
|
+
import { BalanceRepository, } from "./repositories/balance.js";
|
|
9
11
|
import { DeductionRepository } from "./repositories/deduction.js";
|
|
10
12
|
import { LeaseRepository } from "./repositories/lease.js";
|
|
11
13
|
import { CatalogRepository } from "./repositories/catalog.js";
|
|
@@ -17,6 +19,11 @@ import { ZERO, decimalParameter as decParam, decimalRecord as decRecord, decimal
|
|
|
17
19
|
const DEFAULT_LEASE_TTL_SECONDS = 600;
|
|
18
20
|
const DEFAULT_PAGE_SIZE = 50;
|
|
19
21
|
const MAX_PAGE_SIZE = 200;
|
|
22
|
+
function validateAnalyticsRange(start, end) {
|
|
23
|
+
if (!(start instanceof Date) || !(end instanceof Date) || !(end > start)) {
|
|
24
|
+
throw new RangeError("analytics requires end after start");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
20
27
|
function requireText(value, context) {
|
|
21
28
|
const parsed = z.string().min(1).safeParse(value);
|
|
22
29
|
if (!parsed.success) {
|
|
@@ -24,65 +31,102 @@ function requireText(value, context) {
|
|
|
24
31
|
}
|
|
25
32
|
return parsed.data;
|
|
26
33
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
this._balanceRepo = new BalanceRepository(this.callproc.bind(this));
|
|
41
|
-
}
|
|
42
|
-
return this._balanceRepo;
|
|
43
|
-
}
|
|
44
|
-
get deductionRepo() {
|
|
45
|
-
if (!this._deductionRepo) {
|
|
46
|
-
this._deductionRepo = new DeductionRepository(this.callproc.bind(this));
|
|
47
|
-
}
|
|
48
|
-
return this._deductionRepo;
|
|
49
|
-
}
|
|
50
|
-
get leaseRepo() {
|
|
51
|
-
if (!this._leaseRepo) {
|
|
52
|
-
this._leaseRepo = new LeaseRepository(this.callproc.bind(this));
|
|
53
|
-
}
|
|
54
|
-
return this._leaseRepo;
|
|
55
|
-
}
|
|
56
|
-
get catalogRepo() {
|
|
57
|
-
if (!this._catalogRepo) {
|
|
58
|
-
this._catalogRepo = new CatalogRepository(this.callproc.bind(this));
|
|
59
|
-
}
|
|
60
|
-
return this._catalogRepo;
|
|
61
|
-
}
|
|
62
|
-
get planRepo() {
|
|
63
|
-
if (!this._planRepo) {
|
|
64
|
-
this._planRepo = new PlanRepository(this.callproc.bind(this));
|
|
65
|
-
}
|
|
66
|
-
return this._planRepo;
|
|
67
|
-
}
|
|
68
|
-
get analyticsRepo() {
|
|
69
|
-
if (!this._analyticsRepo) {
|
|
70
|
-
this._analyticsRepo = new AnalyticsRepository(this.callproc.bind(this));
|
|
71
|
-
}
|
|
72
|
-
return this._analyticsRepo;
|
|
34
|
+
function mapDeduction(row, userId, procedure) {
|
|
35
|
+
if (row.error !== null) {
|
|
36
|
+
return {
|
|
37
|
+
entryId: null,
|
|
38
|
+
usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
|
|
39
|
+
userId,
|
|
40
|
+
amount: dec(row.amount),
|
|
41
|
+
allowanceConsumed: dec(row.allowance_consumed),
|
|
42
|
+
balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
|
|
43
|
+
idempotent: false,
|
|
44
|
+
error: row.error,
|
|
45
|
+
bucketBreakdown: null,
|
|
46
|
+
};
|
|
73
47
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
48
|
+
return {
|
|
49
|
+
entryId: row.entry_id == null ? null : requireText(row.entry_id, procedure),
|
|
50
|
+
usageChargeId: requireText(row.charge_id, procedure),
|
|
51
|
+
userId,
|
|
52
|
+
amount: dec(row.amount),
|
|
53
|
+
allowanceConsumed: dec(row.allowance_consumed),
|
|
54
|
+
balanceAfter: dec(row.balance_after),
|
|
55
|
+
idempotent: row.idempotent,
|
|
56
|
+
error: null,
|
|
57
|
+
bucketBreakdown: decRecord(row.bucket_breakdown),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function mapAvailable(userId, row) {
|
|
61
|
+
if (row === null)
|
|
62
|
+
return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
|
|
63
|
+
return {
|
|
64
|
+
userId,
|
|
65
|
+
balance: dec(row.balance),
|
|
66
|
+
reserved: dec(row.reserved),
|
|
67
|
+
available: dec(row.available),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function mapStaleQuote(error) {
|
|
71
|
+
if (error instanceof StoreError && error.details?.sqlState === "PZ003") {
|
|
72
|
+
throw new StaleQuoteError("Pricing changed before admission", {
|
|
73
|
+
cause: error,
|
|
74
|
+
});
|
|
79
75
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
export class PostgresStore extends CreditStore {
|
|
79
|
+
async getOperationReceipt(userId, key, kind) {
|
|
80
|
+
if (kind !== "charge" && kind !== "lease")
|
|
81
|
+
throw new TypeError("kind must be charge or lease");
|
|
82
|
+
const rows = await this.callproc("get_operation_receipt", [
|
|
83
|
+
userId,
|
|
84
|
+
requireStableKey(key),
|
|
85
|
+
kind,
|
|
86
|
+
]);
|
|
87
|
+
if (rows.length === 0)
|
|
88
|
+
return null;
|
|
89
|
+
const schema = z.object({
|
|
90
|
+
kind: z.enum(["charge", "lease"]),
|
|
91
|
+
receipt_id: z.string(),
|
|
92
|
+
operation: z.string(),
|
|
93
|
+
requested: z.string(),
|
|
94
|
+
charged: z.string().nullable(),
|
|
95
|
+
allowance_amount: z.string(),
|
|
96
|
+
status: z.string(),
|
|
97
|
+
expires_at: z.union([z.string(), z.date()]).nullable(),
|
|
98
|
+
ledger_entry_id: z.string().nullable(),
|
|
99
|
+
usage_charge_id: z.string().nullable(),
|
|
100
|
+
});
|
|
101
|
+
const parsed = schema.safeParse(rows[0]);
|
|
102
|
+
if (rows.length !== 1 || !parsed.success || parsed.data.kind !== kind) {
|
|
103
|
+
throw new StoreError("get_operation_receipt returned a malformed result");
|
|
83
104
|
}
|
|
84
|
-
|
|
105
|
+
const row = parsed.data;
|
|
106
|
+
return {
|
|
107
|
+
kind: row.kind,
|
|
108
|
+
receiptId: row.receipt_id,
|
|
109
|
+
operation: row.operation,
|
|
110
|
+
requested: dec(row.requested),
|
|
111
|
+
charged: row.charged === null ? null : dec(row.charged),
|
|
112
|
+
allowanceAmount: dec(row.allowance_amount),
|
|
113
|
+
status: row.status,
|
|
114
|
+
expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,
|
|
115
|
+
ledgerEntryId: row.ledger_entry_id,
|
|
116
|
+
usageChargeId: row.usage_charge_id,
|
|
117
|
+
};
|
|
85
118
|
}
|
|
119
|
+
tenantId;
|
|
120
|
+
providerEnvironment;
|
|
121
|
+
postgres;
|
|
122
|
+
balanceRepo;
|
|
123
|
+
deductionRepo;
|
|
124
|
+
leaseRepo;
|
|
125
|
+
catalogRepo;
|
|
126
|
+
planRepo;
|
|
127
|
+
analyticsRepo;
|
|
128
|
+
teamRepo;
|
|
129
|
+
bucketRepo;
|
|
86
130
|
constructor(options) {
|
|
87
131
|
super();
|
|
88
132
|
if (!z.object({}).safeParse(options).success) {
|
|
@@ -91,10 +135,11 @@ export class PostgresStore extends CreditStore {
|
|
|
91
135
|
if (options.poolConstructor !== undefined && !z.string().safeParse(options.postgres).success) {
|
|
92
136
|
throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
|
|
93
137
|
}
|
|
94
|
-
this.
|
|
138
|
+
this.tenantId = normalizeTenantId(options.tenantId);
|
|
139
|
+
this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
|
|
95
140
|
this.postgres = new PostgresClient(options.postgres, {
|
|
96
|
-
tenantId:
|
|
97
|
-
providerEnvironment:
|
|
141
|
+
tenantId: this.tenantId,
|
|
142
|
+
providerEnvironment: this.providerEnvironment,
|
|
98
143
|
usageBackend: options.usageBackend,
|
|
99
144
|
poolConstructor: options.poolConstructor,
|
|
100
145
|
connectionTimeoutMs: options.connectionTimeoutMs,
|
|
@@ -104,12 +149,29 @@ export class PostgresStore extends CreditStore {
|
|
|
104
149
|
maxConnections: options.maxConnections,
|
|
105
150
|
applicationName: options.applicationName,
|
|
106
151
|
onPoolError: options.onPoolError,
|
|
152
|
+
instrumentation: options.instrumentation,
|
|
107
153
|
closedError: () => new StoreClosedError("Credit store has been closed"),
|
|
108
154
|
});
|
|
155
|
+
const callproc = this.callproc.bind(this);
|
|
156
|
+
this.balanceRepo = new BalanceRepository(callproc);
|
|
157
|
+
this.deductionRepo = new DeductionRepository(callproc);
|
|
158
|
+
this.leaseRepo = new LeaseRepository(callproc);
|
|
159
|
+
this.catalogRepo = new CatalogRepository(callproc);
|
|
160
|
+
this.planRepo = new PlanRepository(callproc);
|
|
161
|
+
this.analyticsRepo = new AnalyticsRepository(callproc);
|
|
162
|
+
this.teamRepo = new TeamRepository(callproc);
|
|
163
|
+
this.bucketRepo = new BucketRepository(callproc);
|
|
109
164
|
}
|
|
110
165
|
async query(text, params) {
|
|
111
166
|
return this.postgres.query(text, params);
|
|
112
167
|
}
|
|
168
|
+
/** Check the same tenant-scoped connection used by financial operations. */
|
|
169
|
+
async checkReachability() {
|
|
170
|
+
const rows = await this.query("SELECT 1 AS bursar_reachable");
|
|
171
|
+
if (rows.length !== 1 || rows[0]?.bursar_reachable !== 1) {
|
|
172
|
+
throw new Error("PostgreSQL reachability check returned an invalid result");
|
|
173
|
+
}
|
|
174
|
+
}
|
|
113
175
|
withUsageBackend(expected, action) {
|
|
114
176
|
return this.postgres.withUsageBackend(expected, action);
|
|
115
177
|
}
|
|
@@ -117,6 +179,25 @@ export class PostgresStore extends CreditStore {
|
|
|
117
179
|
await this.postgres.close();
|
|
118
180
|
}
|
|
119
181
|
static RPC_NAME_RE = /^[a-z_][a-z0-9_]*$/;
|
|
182
|
+
// Cast cursor timestamps to text before pg can truncate their microseconds.
|
|
183
|
+
static CURSOR_PROJECTIONS = new Map([
|
|
184
|
+
[
|
|
185
|
+
"list_ledger",
|
|
186
|
+
"entry_id, account_id, actor_user_id, amount, entry_type, operation, reference_entry_id, " +
|
|
187
|
+
"idempotency_key, metadata, created_at::text AS created_at",
|
|
188
|
+
],
|
|
189
|
+
[
|
|
190
|
+
"list_usage_charges",
|
|
191
|
+
"usage_id, account_id, operation, requested, charged, allowance_requested, allowance_covered, " +
|
|
192
|
+
"billing_disposition, feature, model, region, event_at::text AS event_at, " +
|
|
193
|
+
"idempotency_key, metadata, created_at",
|
|
194
|
+
],
|
|
195
|
+
[
|
|
196
|
+
"list_subject_quota_events",
|
|
197
|
+
"event_id, quota_key, operation_key, measure_key, event_type, threshold_percent, " +
|
|
198
|
+
"idempotency_key, usage_charge_id, created_at::text AS created_at",
|
|
199
|
+
],
|
|
200
|
+
]);
|
|
120
201
|
static SCALAR_RPC_NAMES = new Set([
|
|
121
202
|
"apply_due_plan_assignment_changes",
|
|
122
203
|
"release_lease",
|
|
@@ -126,12 +207,13 @@ export class PostgresStore extends CreditStore {
|
|
|
126
207
|
"start_plan_migration",
|
|
127
208
|
"unassign_plan",
|
|
128
209
|
]);
|
|
129
|
-
async callproc(name, params) {
|
|
210
|
+
async callproc(name, params, query = this.postgres.query) {
|
|
130
211
|
if (!PostgresStore.RPC_NAME_RE.test(name)) {
|
|
131
212
|
throw new StoreError(`Invalid RPC name: ${name}`);
|
|
132
213
|
}
|
|
133
214
|
const placeholders = params.map((_, i) => `$${i + 1}`).join(", ");
|
|
134
|
-
const
|
|
215
|
+
const sql = `SELECT ${PostgresStore.CURSOR_PROJECTIONS.get(name) ?? "*"} FROM bursar.${name}(${placeholders})`;
|
|
216
|
+
const rows = await query(sql, params);
|
|
135
217
|
if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
|
|
136
218
|
const row = rows[0];
|
|
137
219
|
if (row === undefined)
|
|
@@ -163,19 +245,22 @@ export class PostgresStore extends CreditStore {
|
|
|
163
245
|
if (options?.expiresAt) {
|
|
164
246
|
meta.expires_at = options.expiresAt.toISOString();
|
|
165
247
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
248
|
+
return this.postgres.withTransaction(async (query) => {
|
|
249
|
+
const repository = new BalanceRepository((name, params) => this.callproc(name, params, query));
|
|
250
|
+
const row = await repository.addCredits(userId, decParam(amount), options?.type ?? "adjustment", JSON.stringify(meta), options?.expiresAt?.toISOString() ?? null, options?.bucket ?? null, stableKey);
|
|
251
|
+
if (row.error !== null) {
|
|
252
|
+
throw new StoreError(`post_credit: ${row.error}`);
|
|
253
|
+
}
|
|
254
|
+
return {
|
|
255
|
+
entryId: requireText(row.entry_id, "post_credit"),
|
|
256
|
+
userId: row.user_id,
|
|
257
|
+
amount: dec(row.amount),
|
|
258
|
+
newBalance: dec(row.new_balance),
|
|
259
|
+
lifetimePurchased: dec(row.lifetime_purchased),
|
|
260
|
+
bucket: row.bucket,
|
|
261
|
+
idempotent: row.idempotent,
|
|
262
|
+
};
|
|
263
|
+
});
|
|
179
264
|
}
|
|
180
265
|
async deductWithAllowance(userId, amount, options) {
|
|
181
266
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
@@ -188,46 +273,31 @@ export class PostgresStore extends CreditStore {
|
|
|
188
273
|
const feature = options?.feature ?? null;
|
|
189
274
|
const measures = options?.measures ?? {};
|
|
190
275
|
const dimensions = options?.dimensions ?? {};
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
idempotencyKey,
|
|
196
|
-
feature,
|
|
197
|
-
model,
|
|
198
|
-
region,
|
|
199
|
-
measures: JSON.stringify(measures),
|
|
200
|
-
dimensions: JSON.stringify(dimensions),
|
|
201
|
-
metadata: JSON.stringify(metadata ?? {}),
|
|
202
|
-
});
|
|
203
|
-
if (row.error !== null) {
|
|
204
|
-
return {
|
|
205
|
-
entryId: null,
|
|
206
|
-
usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
|
|
276
|
+
return this.postgres.withTransaction(async (query) => {
|
|
277
|
+
const repository = new DeductionRepository((name, params) => this.callproc(name, params, query));
|
|
278
|
+
const row = await repository
|
|
279
|
+
.deductWithAllowance({
|
|
207
280
|
userId,
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
idempotent: row.idempotent,
|
|
224
|
-
error: null,
|
|
225
|
-
bucketBreakdown: decRecord(row.bucket_breakdown),
|
|
226
|
-
};
|
|
281
|
+
operation,
|
|
282
|
+
amount: decParam(amount),
|
|
283
|
+
idempotencyKey,
|
|
284
|
+
feature,
|
|
285
|
+
model,
|
|
286
|
+
region,
|
|
287
|
+
measures: JSON.stringify(measures),
|
|
288
|
+
dimensions: JSON.stringify(dimensions),
|
|
289
|
+
metadata: JSON.stringify(metadata ?? {}),
|
|
290
|
+
expectedPlanId: options.expectedPricing?.planId ?? null,
|
|
291
|
+
expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
|
|
292
|
+
})
|
|
293
|
+
.catch(mapStaleQuote);
|
|
294
|
+
return mapDeduction(row, userId, "charge_usage_for_operation");
|
|
295
|
+
});
|
|
227
296
|
}
|
|
228
297
|
async recordUsage(userId, operation, amount, options) {
|
|
229
298
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
230
|
-
const row = await this.deductionRepo
|
|
299
|
+
const row = await this.deductionRepo
|
|
300
|
+
.recordUsage({
|
|
231
301
|
userId,
|
|
232
302
|
operation,
|
|
233
303
|
amount: decParam(amount),
|
|
@@ -238,7 +308,10 @@ export class PostgresStore extends CreditStore {
|
|
|
238
308
|
measures: JSON.stringify(options?.measures ?? {}),
|
|
239
309
|
dimensions: JSON.stringify(options?.dimensions ?? {}),
|
|
240
310
|
metadata: JSON.stringify(options?.metadata ?? {}),
|
|
241
|
-
|
|
311
|
+
expectedPlanId: options.expectedPricing?.planId ?? null,
|
|
312
|
+
expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
|
|
313
|
+
})
|
|
314
|
+
.catch(mapStaleQuote);
|
|
242
315
|
if (row.error_code !== null) {
|
|
243
316
|
return {
|
|
244
317
|
usageId: null,
|
|
@@ -258,85 +331,73 @@ export class PostgresStore extends CreditStore {
|
|
|
258
331
|
}
|
|
259
332
|
async createLease(userId, amount, operationType, options) {
|
|
260
333
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
|
|
267
|
-
metadata: JSON.stringify(options?.metadata ?? {}),
|
|
268
|
-
feature: options?.feature ?? null,
|
|
269
|
-
measures: JSON.stringify(options?.measures ?? {}),
|
|
270
|
-
dimensions: JSON.stringify(options?.dimensions ?? {}),
|
|
271
|
-
minimumBalance: options?.floor == null ? null : decParam(options.floor),
|
|
272
|
-
maxConcurrent: options?.maxConcurrent ?? null,
|
|
273
|
-
});
|
|
274
|
-
const availability = await this.getAvailable(userId);
|
|
275
|
-
if (row.error !== null) {
|
|
276
|
-
return {
|
|
277
|
-
leaseId: null,
|
|
334
|
+
return this.postgres.withTransaction(async (query) => {
|
|
335
|
+
const callproc = (name, params) => this.callproc(name, params, query);
|
|
336
|
+
const repository = new LeaseRepository(callproc);
|
|
337
|
+
const row = await repository
|
|
338
|
+
.createLease({
|
|
278
339
|
userId,
|
|
279
|
-
amount:
|
|
340
|
+
amount: decParam(amount),
|
|
341
|
+
operationType,
|
|
342
|
+
idempotencyKey,
|
|
343
|
+
ttlSeconds: options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,
|
|
344
|
+
metadata: JSON.stringify(options?.metadata ?? {}),
|
|
345
|
+
feature: options?.feature ?? null,
|
|
346
|
+
measures: JSON.stringify(options?.measures ?? {}),
|
|
347
|
+
dimensions: JSON.stringify(options?.dimensions ?? {}),
|
|
348
|
+
minimumBalance: options?.floor == null ? null : decParam(options.floor),
|
|
349
|
+
maxConcurrent: options?.maxConcurrent ?? null,
|
|
350
|
+
expectedPlanId: options.expectedPricing?.planId ?? null,
|
|
351
|
+
expectedRevisionNo: options.expectedPricing?.catalogVersion ?? null,
|
|
352
|
+
})
|
|
353
|
+
.catch(mapStaleQuote);
|
|
354
|
+
const availability = mapAvailable(userId, await new BalanceRepository(callproc).getAvailable(userId));
|
|
355
|
+
if (row.error !== null) {
|
|
356
|
+
return {
|
|
357
|
+
leaseId: null,
|
|
358
|
+
userId,
|
|
359
|
+
amount: row.amount == null ? null : dec(row.amount),
|
|
360
|
+
available: availability.available,
|
|
361
|
+
reservedTotal: availability.reserved,
|
|
362
|
+
minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
|
|
363
|
+
billingMode: options?.billingMode ?? "strict",
|
|
364
|
+
expiresAt: null,
|
|
365
|
+
error: row.error,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
leaseId: requireText(row.lease_id, "create_lease_for_operation"),
|
|
370
|
+
userId: row.user_id,
|
|
371
|
+
amount: dec(row.amount),
|
|
280
372
|
available: availability.available,
|
|
281
373
|
reservedTotal: availability.reserved,
|
|
282
|
-
minimumBalance:
|
|
283
|
-
billingMode:
|
|
284
|
-
expiresAt:
|
|
285
|
-
error:
|
|
374
|
+
minimumBalance: dec(row.minimum_balance),
|
|
375
|
+
billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
|
|
376
|
+
expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
|
|
377
|
+
error: null,
|
|
286
378
|
};
|
|
287
|
-
}
|
|
288
|
-
return {
|
|
289
|
-
leaseId: requireText(row.lease_id, "create_lease_for_operation"),
|
|
290
|
-
userId: row.user_id,
|
|
291
|
-
amount: dec(row.amount),
|
|
292
|
-
available: availability.available,
|
|
293
|
-
reservedTotal: availability.reserved,
|
|
294
|
-
minimumBalance: dec(row.minimum_balance),
|
|
295
|
-
billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
|
|
296
|
-
expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
|
|
297
|
-
error: null,
|
|
298
|
-
};
|
|
379
|
+
});
|
|
299
380
|
}
|
|
300
381
|
async settleLease(userId, leaseId, amount, options) {
|
|
301
382
|
const idempotencyKey = options?.idempotencyKey === undefined
|
|
302
383
|
? `lease:${leaseId}:settle`
|
|
303
384
|
: requireStableKey(options.idempotencyKey);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
amount: decParam(amount),
|
|
308
|
-
idempotencyKey,
|
|
309
|
-
feature: options?.feature ?? null,
|
|
310
|
-
model: options?.model ?? null,
|
|
311
|
-
region: options?.region ?? null,
|
|
312
|
-
measures: JSON.stringify(options?.measures ?? {}),
|
|
313
|
-
dimensions: JSON.stringify(options?.dimensions ?? {}),
|
|
314
|
-
metadata: JSON.stringify(options?.metadata ?? {}),
|
|
315
|
-
});
|
|
316
|
-
if (row.error !== null) {
|
|
317
|
-
return {
|
|
318
|
-
entryId: null,
|
|
319
|
-
usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
|
|
385
|
+
return this.postgres.withTransaction(async (query) => {
|
|
386
|
+
const repository = new LeaseRepository((name, params) => this.callproc(name, params, query));
|
|
387
|
+
const row = await repository.settleLease({
|
|
320
388
|
userId,
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
amount: dec(row.amount),
|
|
334
|
-
allowanceConsumed: dec(row.allowance_consumed),
|
|
335
|
-
balanceAfter: dec(row.balance_after),
|
|
336
|
-
idempotent: row.idempotent,
|
|
337
|
-
error: null,
|
|
338
|
-
bucketBreakdown: decRecord(row.bucket_breakdown),
|
|
339
|
-
};
|
|
389
|
+
leaseId,
|
|
390
|
+
amount: decParam(amount),
|
|
391
|
+
idempotencyKey,
|
|
392
|
+
feature: options?.feature ?? null,
|
|
393
|
+
model: options?.model ?? null,
|
|
394
|
+
region: options?.region ?? null,
|
|
395
|
+
measures: JSON.stringify(options?.measures ?? {}),
|
|
396
|
+
dimensions: JSON.stringify(options?.dimensions ?? {}),
|
|
397
|
+
metadata: JSON.stringify(options?.metadata ?? {}),
|
|
398
|
+
});
|
|
399
|
+
return mapDeduction(row, userId, "settle_lease");
|
|
400
|
+
});
|
|
340
401
|
}
|
|
341
402
|
async getLeasePricingContext(userId, leaseId) {
|
|
342
403
|
const row = await this.leaseRepo.getPricingContext(userId, leaseId);
|
|
@@ -344,6 +405,7 @@ export class PostgresStore extends CreditStore {
|
|
|
344
405
|
return null;
|
|
345
406
|
return {
|
|
346
407
|
catalogVersion: row.catalog_revision_no,
|
|
408
|
+
operationType: row.operation,
|
|
347
409
|
planId: row.plan_id ?? null,
|
|
348
410
|
planKey: row.plan_key ?? null,
|
|
349
411
|
rateCard: row.rate_card ?? null,
|
|
@@ -362,33 +424,36 @@ export class PostgresStore extends CreditStore {
|
|
|
362
424
|
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
|
|
363
425
|
throw new RangeError("ttlSeconds must be a positive integer");
|
|
364
426
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
427
|
+
return this.postgres.withTransaction(async (query) => {
|
|
428
|
+
const callproc = (name, params) => this.callproc(name, params, query);
|
|
429
|
+
const row = await new LeaseRepository(callproc).renewLease(userId, leaseId, ttlSeconds);
|
|
430
|
+
const availability = mapAvailable(userId, await new BalanceRepository(callproc).getAvailable(userId));
|
|
431
|
+
if (row.error !== null) {
|
|
432
|
+
return {
|
|
433
|
+
leaseId: null,
|
|
434
|
+
userId,
|
|
435
|
+
amount: row.amount == null ? null : dec(row.amount),
|
|
436
|
+
available: availability.available,
|
|
437
|
+
reservedTotal: availability.reserved,
|
|
438
|
+
minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
|
|
439
|
+
billingMode: row.minimum_balance != null && dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
|
|
440
|
+
expiresAt: null,
|
|
441
|
+
error: row.error,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
const minimumBalance = dec(row.minimum_balance);
|
|
368
445
|
return {
|
|
369
|
-
leaseId:
|
|
446
|
+
leaseId: requireText(row.lease_id, "renew_lease"),
|
|
370
447
|
userId,
|
|
371
|
-
amount:
|
|
448
|
+
amount: dec(row.amount),
|
|
372
449
|
available: availability.available,
|
|
373
450
|
reservedTotal: availability.reserved,
|
|
374
|
-
minimumBalance
|
|
375
|
-
billingMode:
|
|
376
|
-
expiresAt:
|
|
377
|
-
error:
|
|
451
|
+
minimumBalance,
|
|
452
|
+
billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
|
|
453
|
+
expiresAt: requireText(row.expires_at, "renew_lease"),
|
|
454
|
+
error: null,
|
|
378
455
|
};
|
|
379
|
-
}
|
|
380
|
-
const minimumBalance = dec(row.minimum_balance);
|
|
381
|
-
return {
|
|
382
|
-
leaseId: requireText(row.lease_id, "renew_lease"),
|
|
383
|
-
userId,
|
|
384
|
-
amount: dec(row.amount),
|
|
385
|
-
available: availability.available,
|
|
386
|
-
reservedTotal: availability.reserved,
|
|
387
|
-
minimumBalance,
|
|
388
|
-
billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
|
|
389
|
-
expiresAt: requireText(row.expires_at, "renew_lease"),
|
|
390
|
-
error: null,
|
|
391
|
-
};
|
|
456
|
+
});
|
|
392
457
|
}
|
|
393
458
|
async expireLeases(limit = 100) {
|
|
394
459
|
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
|
|
@@ -397,16 +462,7 @@ export class PostgresStore extends CreditStore {
|
|
|
397
462
|
return this.leaseRepo.expireLeases(limit);
|
|
398
463
|
}
|
|
399
464
|
async getAvailable(userId) {
|
|
400
|
-
|
|
401
|
-
if (row === null) {
|
|
402
|
-
return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
|
|
403
|
-
}
|
|
404
|
-
return {
|
|
405
|
-
userId,
|
|
406
|
-
balance: dec(row.balance),
|
|
407
|
-
reserved: dec(row.reserved),
|
|
408
|
-
available: dec(row.available),
|
|
409
|
-
};
|
|
465
|
+
return mapAvailable(userId, await this.balanceRepo.getAvailable(userId));
|
|
410
466
|
}
|
|
411
467
|
async getActiveCatalog() {
|
|
412
468
|
return this.loadActiveCatalog();
|
|
@@ -416,16 +472,14 @@ export class PostgresStore extends CreditStore {
|
|
|
416
472
|
return row === null ? null : normalizeCatalogRevision(row);
|
|
417
473
|
}
|
|
418
474
|
async publishAndActivateCatalog(config, label, rollout) {
|
|
419
|
-
const
|
|
420
|
-
const
|
|
475
|
+
const parsed = loadConfigFromDict(config, this.providerEnvironment);
|
|
476
|
+
const canonical = canonicalParsedBursarConfigDict(parsed);
|
|
421
477
|
const rolloutDocument = canonicalCatalogRolloutDict(validateCatalogRollout(parsed, loadCatalogRollout(rollout ?? {})));
|
|
422
|
-
|
|
423
|
-
return row.id;
|
|
478
|
+
return this.catalogRepo.publishAndActivateCatalog(canonical, label ?? null, rolloutDocument);
|
|
424
479
|
}
|
|
425
480
|
async publishCatalogDraft(config, label) {
|
|
426
|
-
const canonical =
|
|
427
|
-
|
|
428
|
-
return row.id;
|
|
481
|
+
const canonical = canonicalParsedBursarConfigDict(loadConfigFromDict(config, this.providerEnvironment));
|
|
482
|
+
return this.catalogRepo.publishCatalogDraft(canonical, label ?? null);
|
|
429
483
|
}
|
|
430
484
|
async getCatalogHistory() {
|
|
431
485
|
const rows = await this.catalogRepo.getCatalogHistory();
|
|
@@ -601,7 +655,7 @@ export class PostgresStore extends CreditStore {
|
|
|
601
655
|
if (options?.afterId != null && options.after == null) {
|
|
602
656
|
throw new TypeError("afterId requires after");
|
|
603
657
|
}
|
|
604
|
-
const rows = await this.planRepo.listQuotaEvents(userId, options?.after
|
|
658
|
+
const rows = await this.planRepo.listQuotaEvents(userId, options?.after instanceof Date ? options.after.toISOString() : (options?.after ?? null), limit, options?.idempotencyKey ?? null, options?.afterId ?? null);
|
|
605
659
|
return rows.map((row) => ({
|
|
606
660
|
eventId: row.event_id,
|
|
607
661
|
quotaKey: row.quota_key,
|
|
@@ -639,7 +693,7 @@ export class PostgresStore extends CreditStore {
|
|
|
639
693
|
}
|
|
640
694
|
async refundCredits(entryId, options) {
|
|
641
695
|
const stableKey = requireStableKey(options?.idempotencyKey);
|
|
642
|
-
const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new
|
|
696
|
+
const row = await this.deductionRepo.refundCredits(entryId, options?.amount != null ? decParam(new PricingDecimal(options.amount)) : null, stableKey, options?.reason ?? null, JSON.stringify(options?.metadata ?? {}));
|
|
643
697
|
if (row.error !== null) {
|
|
644
698
|
return {
|
|
645
699
|
refundEntryId: null,
|
|
@@ -662,9 +716,7 @@ export class PostgresStore extends CreditStore {
|
|
|
662
716
|
};
|
|
663
717
|
}
|
|
664
718
|
async aggregateStats(start, end) {
|
|
665
|
-
|
|
666
|
-
throw new RangeError("aggregateStats requires end after start");
|
|
667
|
-
}
|
|
719
|
+
validateAnalyticsRange(start, end);
|
|
668
720
|
const row = await this.analyticsRepo.aggregateStats(start.toISOString(), end.toISOString());
|
|
669
721
|
return {
|
|
670
722
|
totalCreditsConsumed: dec(row.total_credits_consumed),
|
|
@@ -675,6 +727,7 @@ export class PostgresStore extends CreditStore {
|
|
|
675
727
|
};
|
|
676
728
|
}
|
|
677
729
|
async spendByUser(start, end) {
|
|
730
|
+
validateAnalyticsRange(start, end);
|
|
678
731
|
const rows = await this.analyticsRepo.spendByUser(start.toISOString(), end.toISOString());
|
|
679
732
|
return (rows ?? []).map((r) => ({
|
|
680
733
|
userId: r.user_id,
|
|
@@ -683,6 +736,7 @@ export class PostgresStore extends CreditStore {
|
|
|
683
736
|
}));
|
|
684
737
|
}
|
|
685
738
|
async spendByModel(start, end) {
|
|
739
|
+
validateAnalyticsRange(start, end);
|
|
686
740
|
const rows = await this.analyticsRepo.spendByModel(start.toISOString(), end.toISOString());
|
|
687
741
|
return (rows ?? []).map((r) => ({
|
|
688
742
|
model: r.model,
|
|
@@ -691,6 +745,10 @@ export class PostgresStore extends CreditStore {
|
|
|
691
745
|
}));
|
|
692
746
|
}
|
|
693
747
|
async topUsers(limit, start, end) {
|
|
748
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 10_000) {
|
|
749
|
+
throw new RangeError("topUsers limit must be between 1 and 10000");
|
|
750
|
+
}
|
|
751
|
+
validateAnalyticsRange(start, end);
|
|
694
752
|
const rows = await this.analyticsRepo.topUsers(limit, start.toISOString(), end.toISOString());
|
|
695
753
|
return (rows ?? []).map((r) => ({
|
|
696
754
|
userId: r.user_id,
|
|
@@ -698,6 +756,7 @@ export class PostgresStore extends CreditStore {
|
|
|
698
756
|
}));
|
|
699
757
|
}
|
|
700
758
|
async dailySpend(start, end) {
|
|
759
|
+
validateAnalyticsRange(start, end);
|
|
701
760
|
const rows = await this.analyticsRepo.dailySpend(start.toISOString(), end.toISOString());
|
|
702
761
|
return (rows ?? []).map((r) => ({
|
|
703
762
|
date: r.date,
|
|
@@ -796,11 +855,15 @@ export class PostgresStore extends CreditStore {
|
|
|
796
855
|
return this.teamRepo.removeTeamMember(teamId, userId);
|
|
797
856
|
}
|
|
798
857
|
async deductTeam(teamId, userId, amount, options) {
|
|
858
|
+
if (amount.isNegative() && !amount.isZero())
|
|
859
|
+
throw new RangeError("team deduction amount must be non-negative");
|
|
799
860
|
const meta = { ...(options?.metadata ?? {}) };
|
|
800
861
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
801
862
|
meta.idempotency_key = effectiveIdempotencyKey;
|
|
802
863
|
const operation = z.string().min(1).safeParse(meta.operation).data ?? "team_usage";
|
|
803
|
-
const row = await this.teamRepo
|
|
864
|
+
const row = await this.teamRepo
|
|
865
|
+
.deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta), options.expectedPricing?.planId ?? null, options.expectedPricing?.catalogVersion ?? null)
|
|
866
|
+
.catch(mapStaleQuote);
|
|
804
867
|
if (row.error !== null) {
|
|
805
868
|
return {
|
|
806
869
|
entryId: null,
|
|
@@ -813,7 +876,7 @@ export class PostgresStore extends CreditStore {
|
|
|
813
876
|
};
|
|
814
877
|
}
|
|
815
878
|
return {
|
|
816
|
-
entryId:
|
|
879
|
+
entryId: row.entry_id,
|
|
817
880
|
teamId: row.team_id,
|
|
818
881
|
userId: row.user_id,
|
|
819
882
|
amount: dec(row.amount),
|
|
@@ -852,28 +915,44 @@ export class PostgresStore extends CreditStore {
|
|
|
852
915
|
region: request.region ?? null,
|
|
853
916
|
metadata: JSON.stringify(request.metadata ?? {}),
|
|
854
917
|
});
|
|
855
|
-
return rows.map(
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
amount: null,
|
|
863
|
-
replayed: false,
|
|
864
|
-
error: row.error_code,
|
|
865
|
-
};
|
|
918
|
+
return rows.map(grantProgramAward);
|
|
919
|
+
}
|
|
920
|
+
async provisionAccount(input) {
|
|
921
|
+
const row = await this.balanceRepo.provisionAccount(input);
|
|
922
|
+
if (row.error_code !== null) {
|
|
923
|
+
if (row.error_code === "missing_active_catalog") {
|
|
924
|
+
throw new CatalogNotLoadedError("No active Bursar catalog is available");
|
|
866
925
|
}
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
926
|
+
throw new ConfigError("The active catalog has no default account plan");
|
|
927
|
+
}
|
|
928
|
+
return {
|
|
929
|
+
accountId: input.accountId,
|
|
930
|
+
planKey: row.plan_key,
|
|
931
|
+
planAssigned: row.plan_assigned,
|
|
932
|
+
grants: row.grants.map(grantProgramAward),
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
function grantProgramAward(row) {
|
|
937
|
+
if (row.error_code !== null) {
|
|
938
|
+
return {
|
|
939
|
+
grantEventId: null,
|
|
940
|
+
grantAwardId: null,
|
|
941
|
+
recipientSubjectId: null,
|
|
942
|
+
ledgerEntryId: null,
|
|
943
|
+
amount: null,
|
|
944
|
+
replayed: false,
|
|
945
|
+
error: row.error_code,
|
|
946
|
+
};
|
|
877
947
|
}
|
|
948
|
+
return {
|
|
949
|
+
grantEventId: requireText(row.grant_event_id, "execute_grant_program"),
|
|
950
|
+
grantAwardId: requireText(row.grant_award_id, "execute_grant_program"),
|
|
951
|
+
recipientSubjectId: requireText(row.recipient_subject_id, "execute_grant_program"),
|
|
952
|
+
ledgerEntryId: requireText(row.ledger_entry_id, "execute_grant_program"),
|
|
953
|
+
amount: dec(row.amount),
|
|
954
|
+
replayed: row.replayed,
|
|
955
|
+
error: null,
|
|
956
|
+
};
|
|
878
957
|
}
|
|
879
958
|
//# sourceMappingURL=store.js.map
|