@zonastery/bursar 2.0.2 → 2.0.4
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 +1 -0
- package/dist/billing/auto-recharge-port.d.ts +3 -2
- 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 +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +5 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +3 -2
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +2 -10
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +7 -7
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +10 -8
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +5 -9
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +191 -285
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +42 -21
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +3 -9
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +10 -12
- 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 +3 -2
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +59 -41
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +8 -12
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +6 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +1 -1
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js +1 -9
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +29 -30
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +7 -6
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +31 -19
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +3 -2
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -1
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +3 -2
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +11 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +73 -39
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +4 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +4 -3
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +4 -3
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +45 -42
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js +11 -6
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +70 -68
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +1 -1
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-access.d.ts +5 -2
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +60 -41
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts +2 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +49 -29
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts +2 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +39 -23
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts +7 -2
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +49 -22
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts +2 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +41 -31
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +16 -12
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +91 -28
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +6 -5
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +66 -36
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +2 -2
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +6 -5
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +3 -4
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/events.d.ts +12 -1
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/events.js +35 -21
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +3 -2
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +4 -3
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +3 -2
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +14 -6
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +7 -7
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +4 -3
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +2 -2
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +6 -5
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +23 -13
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +5 -4
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +11 -12
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +4 -1
- 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 +5 -0
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +30 -10
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +15 -5
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +1 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +5 -4
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +2 -1
- 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.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +3 -2
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.d.ts +2 -2
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +40 -11
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +10 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +50 -9
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/evaluator.d.ts +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr/tokenizer.d.ts.map +1 -1
- package/dist/expr/tokenizer.js +34 -12
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.d.ts +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +13 -7
- package/dist/expr.js.map +1 -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 +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/integrations/better-auth.d.ts +4 -1
- package/dist/integrations/better-auth.d.ts.map +1 -1
- package/dist/integrations/better-auth.js +7 -4
- package/dist/integrations/better-auth.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +19 -13
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +3 -2
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +11 -8
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +26 -17
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +32 -0
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
- package/dist/providers/dodo/better-auth-core.js +14 -0
- package/dist/providers/dodo/better-auth-core.js.map +1 -0
- package/dist/providers/dodo/better-auth.d.ts +5 -7
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -13
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +16 -22
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +7 -4
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +130 -106
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +22 -0
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
- package/dist/providers/dodo/nextjs-core.js +14 -0
- package/dist/providers/dodo/nextjs-core.js.map +1 -0
- package/dist/providers/dodo/nextjs.d.ts +5 -7
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +11 -10
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +3 -3
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +76 -58
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/react-native-core.d.ts +56 -0
- package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
- package/dist/providers/dodo/react-native-core.js +56 -0
- package/dist/providers/dodo/react-native-core.js.map +1 -0
- package/dist/providers/dodo/react-native.d.ts +6 -50
- package/dist/providers/dodo/react-native.d.ts.map +1 -1
- package/dist/providers/dodo/react-native.js +5 -49
- package/dist/providers/dodo/react-native.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +1 -1
- package/dist/providers/environment.d.ts.map +1 -1
- package/dist/providers/environment.js +4 -2
- package/dist/providers/environment.js.map +1 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +5 -10
- 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 +104 -12
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +100 -60
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +0 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +16 -9
- package/dist/retry.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +10 -2
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +65 -6
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/idempotency.d.ts +4 -3
- package/dist/shared/idempotency.d.ts.map +1 -1
- package/dist/shared/idempotency.js +21 -10
- package/dist/shared/idempotency.js.map +1 -1
- package/dist/shared/json.d.ts +28 -0
- package/dist/shared/json.d.ts.map +1 -0
- package/dist/shared/json.js +41 -0
- package/dist/shared/json.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -4
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +10 -5
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +80 -45
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js +32 -31
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/postgres-types.d.ts +3 -2
- package/dist/shared/postgres-types.d.ts.map +1 -1
- package/dist/shared/postgres-types.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts +7 -6
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +17 -10
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +20 -6
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +150 -42
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +67 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +79 -26
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +228 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +272 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +21 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +157 -28
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +52 -7
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +9 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +97 -11
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +20 -3
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +326 -156
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +41 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +118 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +24 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CA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AAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport Decimal from \"decimal.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (row.error_code === null && !new Decimal(row.settled_amount).equals(params.amount)) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE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CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
|
|
@@ -55,8 +55,8 @@ declare const SetUserPlanRowSchema: z.ZodObject<{
|
|
|
55
55
|
plan_key: z.ZodString;
|
|
56
56
|
plan_assigned_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>;
|
|
57
57
|
assignment_state: z.ZodEnum<{
|
|
58
|
-
scheduled: "scheduled";
|
|
59
58
|
applied: "applied";
|
|
59
|
+
scheduled: "scheduled";
|
|
60
60
|
}>;
|
|
61
61
|
}, z.core.$strict>;
|
|
62
62
|
declare const EntitlementRowSchema: z.ZodObject<{
|
|
@@ -5,6 +5,7 @@ declare const CreateTeamRowSchema: z.ZodObject<{
|
|
|
5
5
|
name: z.ZodNullable<z.ZodString>;
|
|
6
6
|
team_subject_id: z.ZodNullable<z.ZodString>;
|
|
7
7
|
account_id: z.ZodNullable<z.ZodString>;
|
|
8
|
+
idempotent: z.ZodBoolean;
|
|
8
9
|
error_code: z.ZodNullable<z.ZodString>;
|
|
9
10
|
}, z.core.$strict>;
|
|
10
11
|
declare const TeamBalanceRowSchema: z.ZodObject<{
|
|
@@ -56,7 +57,7 @@ export declare class TeamRepository {
|
|
|
56
57
|
private callproc;
|
|
57
58
|
constructor(callproc: CallProc);
|
|
58
59
|
/** Create a new team with an initial balance. */
|
|
59
|
-
createTeam(ownerSubjectId: string, name: string, initialBalance: string): Promise<CreateTeamRow>;
|
|
60
|
+
createTeam(ownerSubjectId: string, name: string, idempotencyKey: string, initialBalance: string): Promise<CreateTeamRow>;
|
|
60
61
|
/** Fetch a team's balance and member count. Returns null if the team does not exist. */
|
|
61
62
|
getTeamBalance(teamId: string): Promise<TeamBalanceRow | null>;
|
|
62
63
|
/** Add a member to a team with an optional spend cap. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAiBlE,QAAA,MAAM,mBAAmB;;;;;;;kBA8BrB,CAAC;AAEL,QAAA,MAAM,oBAAoB;;;;;kBAOf,CAAC;AAEZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAMjB,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAOd,CAAC;AAcZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAwBxB,CAAC;A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SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC;CAoC7B"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
5
6
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
6
7
|
const safeInteger = z
|
|
7
8
|
.union([z.number().int(), z.string().regex(/^\d+$/)])
|
|
@@ -14,6 +15,7 @@ const CreateTeamRowSchema = z
|
|
|
14
15
|
name: z.string().min(1).nullable(),
|
|
15
16
|
team_subject_id: postgresUuid.nullable(),
|
|
16
17
|
account_id: postgresUuid.nullable(),
|
|
18
|
+
idempotent: z.boolean(),
|
|
17
19
|
error_code: z.string().min(1).nullable(),
|
|
18
20
|
})
|
|
19
21
|
.strict()
|
|
@@ -31,6 +33,12 @@ const CreateTeamRowSchema = z
|
|
|
31
33
|
message: "failed team creation cannot expose identity fields",
|
|
32
34
|
});
|
|
33
35
|
}
|
|
36
|
+
if (row.error_code !== null && row.idempotent) {
|
|
37
|
+
context.addIssue({
|
|
38
|
+
code: "custom",
|
|
39
|
+
message: "failed team creation cannot be idempotent",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
34
42
|
});
|
|
35
43
|
const TeamBalanceRowSchema = z
|
|
36
44
|
.object({
|
|
@@ -103,8 +111,13 @@ export class TeamRepository {
|
|
|
103
111
|
this.callproc = callproc;
|
|
104
112
|
}
|
|
105
113
|
/** Create a new team with an initial balance. */
|
|
106
|
-
async createTeam(ownerSubjectId, name, initialBalance) {
|
|
107
|
-
const rows = await this.callproc("create_team", [
|
|
114
|
+
async createTeam(ownerSubjectId, name, idempotencyKey, initialBalance) {
|
|
115
|
+
const rows = await this.callproc("create_team", [
|
|
116
|
+
ownerSubjectId,
|
|
117
|
+
name,
|
|
118
|
+
idempotencyKey,
|
|
119
|
+
initialBalance,
|
|
120
|
+
]);
|
|
108
121
|
return safeParse(CreateTeamRowSchema, requireRow(rows, "TeamRepository.createTeam"), "TeamRepository.createTeam");
|
|
109
122
|
}
|
|
110
123
|
/** Fetch a team's balance and member count. Returns null if the team does not exist. */
|
|
@@ -145,7 +158,8 @@ export class TeamRepository {
|
|
|
145
158
|
metadata,
|
|
146
159
|
]);
|
|
147
160
|
const row = safeParse(TeamDeductionRpcRowSchema, requireRow(rows, "TeamRepository.deductTeam"), "TeamRepository.deductTeam");
|
|
148
|
-
if (row.error_code === null &&
|
|
161
|
+
if (row.error_code === null &&
|
|
162
|
+
!new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))) {
|
|
149
163
|
throw new StoreError("TeamRepository.deductTeam: committed amount differs from the request", {
|
|
150
164
|
indeterminate: true,
|
|
151
165
|
});
|
|
@@ -154,7 +168,7 @@ export class TeamRepository {
|
|
|
154
168
|
entry_id: row.entry_id,
|
|
155
169
|
team_id: row.team_id,
|
|
156
170
|
user_id: row.subject_id,
|
|
157
|
-
amount,
|
|
171
|
+
amount: row.error_code === null ? row.amount : amount,
|
|
158
172
|
team_balance_after: row.balance_after,
|
|
159
173
|
replayed: row.replayed,
|
|
160
174
|
error: row.error_code,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,MAAM,OAAO,GAAG,C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ACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM;YACN,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [ownerSubjectId, name, initialBalance]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (row.error_code === null && !new Decimal(row.amount).equals(amount)) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,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,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAU,CAAC;KAC7D,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AAC3D,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEtD,MAAM,mBAAmB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AAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { type BursarConfigData, type CatalogRollout } from "../../config.js";
|
|
3
3
|
import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
|
|
4
|
+
import type { JsonObject } from "../../shared/json.js";
|
|
4
5
|
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
|
|
5
6
|
import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "../service-types.js";
|
|
6
7
|
import { CreditStore } from "../store.js";
|
|
7
|
-
import type { CreateLeaseOptions, SettleLeaseOptions } from "../store.js";
|
|
8
|
+
import type { CreateLeaseOptions, CreateTeamOptions, SettleLeaseOptions } from "../store.js";
|
|
8
9
|
export type PgPool = PostgresPool;
|
|
9
10
|
export type PgPoolConstructor = PostgresPoolConstructor;
|
|
10
11
|
/** Construction options for the PostgreSQL credit store. */
|
|
@@ -57,8 +58,8 @@ export declare class PostgresStore extends CreditStore {
|
|
|
57
58
|
getAvailable(userId: string): Promise<AvailableResult>;
|
|
58
59
|
getActiveCatalog(): Promise<CatalogRevision | null>;
|
|
59
60
|
private loadActiveCatalog;
|
|
60
|
-
publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
61
|
-
publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
|
|
61
|
+
publishAndActivateCatalog(config: BursarConfigData | JsonObject, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
62
|
+
publishCatalogDraft(config: BursarConfigData | JsonObject, label?: string | null): Promise<string>;
|
|
62
63
|
getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
|
|
63
64
|
getCatalogRevision(version: number): Promise<CatalogRevision | null>;
|
|
64
65
|
activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
|
|
@@ -85,7 +86,7 @@ export declare class PostgresStore extends CreditStore {
|
|
|
85
86
|
listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage>;
|
|
86
87
|
listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;
|
|
87
88
|
listUsageCharges(userId: string, options?: ListUsageChargesOptions): Promise<UsageChargePage>;
|
|
88
|
-
createTeam(ownerSubjectId: string, name: string,
|
|
89
|
+
createTeam(ownerSubjectId: string, name: string, options: CreateTeamOptions): Promise<CreateTeamResult>;
|
|
89
90
|
getTeamBalance(teamId: string): Promise<TeamBalanceResult | null>;
|
|
90
91
|
addTeamMember(teamId: string, userId: string, role?: TeamRole, spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
|
|
91
92
|
getTeamMembers(teamId: string): Promise<TeamMember[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAIrC,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAAE,UAAU,EAAiC,MAAM,sBAAsB,CAAC;AACtF,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAElB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,QAAQ,EAER,oBAAoB,EACpB,UAAU,EACV,mBAAmB,EACnB,WAAW,EACZ,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK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mCzB,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAYvF,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAYhE,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC;CAiCtC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { StoreClosedError, StoreError } from "../../errors.js";
|
|
3
4
|
import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
|
|
4
5
|
import { PostgresClient, } from "../../shared/postgres-client.js";
|
|
@@ -17,10 +18,11 @@ const DEFAULT_LEASE_TTL_SECONDS = 600;
|
|
|
17
18
|
const DEFAULT_PAGE_SIZE = 50;
|
|
18
19
|
const MAX_PAGE_SIZE = 200;
|
|
19
20
|
function requireText(value, context) {
|
|
20
|
-
|
|
21
|
+
const parsed = z.string().min(1).safeParse(value);
|
|
22
|
+
if (!parsed.success) {
|
|
21
23
|
throw new StoreError(`${context} returned a missing or invalid identifier`);
|
|
22
24
|
}
|
|
23
|
-
return
|
|
25
|
+
return parsed.data;
|
|
24
26
|
}
|
|
25
27
|
export class PostgresStore extends CreditStore {
|
|
26
28
|
providerEnvironment;
|
|
@@ -83,10 +85,10 @@ export class PostgresStore extends CreditStore {
|
|
|
83
85
|
}
|
|
84
86
|
constructor(options) {
|
|
85
87
|
super();
|
|
86
|
-
if (
|
|
88
|
+
if (!z.object({}).safeParse(options).success) {
|
|
87
89
|
throw new TypeError("PostgresStore options are required");
|
|
88
90
|
}
|
|
89
|
-
if (
|
|
91
|
+
if (options.poolConstructor !== undefined && !z.string().safeParse(options.postgres).success) {
|
|
90
92
|
throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
|
|
91
93
|
}
|
|
92
94
|
this.providerEnvironment = options.providerEnvironment;
|
|
@@ -129,10 +131,14 @@ export class PostgresStore extends CreditStore {
|
|
|
129
131
|
const rows = await this.query(`SELECT * FROM bursar.${name}(${placeholders})`, params);
|
|
130
132
|
if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
|
|
131
133
|
const row = rows[0];
|
|
134
|
+
if (row === undefined)
|
|
135
|
+
return rows;
|
|
132
136
|
const keys = Object.keys(row);
|
|
133
137
|
const key = keys[0];
|
|
134
138
|
if (keys.length === 1 && key !== undefined) {
|
|
135
|
-
|
|
139
|
+
const value = row[key];
|
|
140
|
+
if (value !== undefined)
|
|
141
|
+
return [value];
|
|
136
142
|
}
|
|
137
143
|
}
|
|
138
144
|
return rows;
|
|
@@ -171,7 +177,8 @@ export class PostgresStore extends CreditStore {
|
|
|
171
177
|
async deductWithAllowance(userId, amount, options) {
|
|
172
178
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
173
179
|
const operation = options?.operation ??
|
|
174
|
-
(
|
|
180
|
+
z.string().min(1).safeParse(options?.metadata?.operation).data ??
|
|
181
|
+
"usage";
|
|
175
182
|
const model = options?.model ?? null;
|
|
176
183
|
const region = options?.region ?? null;
|
|
177
184
|
const metadata = options?.metadata ?? {};
|
|
@@ -707,7 +714,9 @@ export class PostgresStore extends CreditStore {
|
|
|
707
714
|
const cursor = options?.cursor ?? null;
|
|
708
715
|
const entryTypes = usageOnly
|
|
709
716
|
? ["usage"]
|
|
710
|
-
:
|
|
717
|
+
: options && "entryTypes" in options
|
|
718
|
+
? (options.entryTypes ?? null)
|
|
719
|
+
: null;
|
|
711
720
|
const rows = await this.analyticsRepo.listLedgerEntries(userId, entryTypes, options?.fromDate?.toISOString() ?? null, options?.toDate?.toISOString() ?? null, limit + 1, cursor?.createdAt ?? null, cursor?.entryId ?? null, usageOnly);
|
|
712
721
|
const hasMore = rows.length > limit;
|
|
713
722
|
const items = rows.slice(0, limit).map(mapLedgerEntry);
|
|
@@ -738,13 +747,16 @@ export class PostgresStore extends CreditStore {
|
|
|
738
747
|
nextCursor: hasMore && last ? { eventAt: last.eventAt, usageId: last.usageId } : null,
|
|
739
748
|
};
|
|
740
749
|
}
|
|
741
|
-
async createTeam(ownerSubjectId, name,
|
|
742
|
-
const
|
|
750
|
+
async createTeam(ownerSubjectId, name, options) {
|
|
751
|
+
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
752
|
+
const initialBalance = options?.initialBalance ?? ZERO;
|
|
753
|
+
const row = await this.teamRepo.createTeam(ownerSubjectId, name, idempotencyKey, decParam(initialBalance));
|
|
743
754
|
if (row.error_code !== null)
|
|
744
755
|
throw new StoreError(row.error_code);
|
|
745
756
|
return {
|
|
746
757
|
teamId: requireText(row.team_id, "create_team"),
|
|
747
758
|
name: requireText(row.name, "create_team"),
|
|
759
|
+
idempotent: row.idempotent,
|
|
748
760
|
};
|
|
749
761
|
}
|
|
750
762
|
async getTeamBalance(teamId) {
|
|
@@ -782,9 +794,7 @@ export class PostgresStore extends CreditStore {
|
|
|
782
794
|
const meta = { ...(options?.metadata ?? {}) };
|
|
783
795
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
784
796
|
meta.idempotency_key = effectiveIdempotencyKey;
|
|
785
|
-
const operation =
|
|
786
|
-
? meta.operation
|
|
787
|
-
: "team_usage";
|
|
797
|
+
const operation = z.string().min(1).safeParse(meta.operation).data ?? "team_usage";
|
|
788
798
|
const row = await this.teamRepo.deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta));
|
|
789
799
|
if (row.error !== null) {
|
|
790
800
|
return {
|