@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":"analytics.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAelE,QAAA,MAAM,oBAAoB;;;;kBAMf,CAAC;AAEZ,QAAA,MAAM,qB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C,UAAU,EAAE,CAAC;IAY1E,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IAYhE,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAStE,iBAAiB,CACrB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,EAC3B,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,EACb,eAAe,EAAE,MAAM,GAAG,IAAI,EAC9B,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,SAAS,UAAQ,GAChB,OAAO,CAAC,cAAc,EAAE,CAAC;IAmBtB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAQ/E,gBAAgB,CACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,iBAAiB,EAAE,OAAO,GACzB,OAAO,CAAC,cAAc,EAAE,CAAC;CAiB7B"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { StoreError } from "../../../errors.js";
|
|
3
|
+
import { isPostgresRow } from "../../../shared/json.js";
|
|
2
4
|
import { optionalRecordRow, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
3
5
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
4
6
|
const count = z.union([
|
|
@@ -51,7 +53,7 @@ const LedgerEntryRowSchema = z
|
|
|
51
53
|
operation: z.string(),
|
|
52
54
|
reference_entry_id: z.string().nullable(),
|
|
53
55
|
idempotency_key: z.string().nullable(),
|
|
54
|
-
metadata: z.record(z.string(), z.
|
|
56
|
+
metadata: z.record(z.string(), z.json()).nullable(),
|
|
55
57
|
created_at: timestamp,
|
|
56
58
|
})
|
|
57
59
|
.strict();
|
|
@@ -70,10 +72,16 @@ const UsageChargeRowSchema = z
|
|
|
70
72
|
region: z.string().nullable(),
|
|
71
73
|
event_at: timestamp,
|
|
72
74
|
idempotency_key: z.string(),
|
|
73
|
-
metadata: z.record(z.string(), z.
|
|
75
|
+
metadata: z.record(z.string(), z.json()).nullable(),
|
|
74
76
|
created_at: timestamp,
|
|
75
77
|
})
|
|
76
78
|
.strict();
|
|
79
|
+
function requireAnalyticsRow(value, context) {
|
|
80
|
+
if (!isPostgresRow(value)) {
|
|
81
|
+
throw new StoreError(`${context}: expected an object result row`);
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
77
85
|
export class AnalyticsRepository {
|
|
78
86
|
callproc;
|
|
79
87
|
constructor(callproc) {
|
|
@@ -82,28 +90,28 @@ export class AnalyticsRepository {
|
|
|
82
90
|
async spendByUser(start, end) {
|
|
83
91
|
const rows = await this.callproc("spend_by_user", [start, end]);
|
|
84
92
|
return (rows ?? []).map((raw) => {
|
|
85
|
-
const row = raw;
|
|
93
|
+
const row = requireAnalyticsRow(raw, "AnalyticsRepository.spendByUser");
|
|
86
94
|
return safeParse(SpendByUserRowSchema, { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count }, "AnalyticsRepository.spendByUser");
|
|
87
95
|
});
|
|
88
96
|
}
|
|
89
97
|
async spendByModel(start, end) {
|
|
90
98
|
const rows = await this.callproc("spend_by_model", [start, end]);
|
|
91
99
|
return (rows ?? []).map((raw) => {
|
|
92
|
-
const row = raw;
|
|
100
|
+
const row = requireAnalyticsRow(raw, "AnalyticsRepository.spendByModel");
|
|
93
101
|
return safeParse(SpendByModelRowSchema, { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count }, "AnalyticsRepository.spendByModel");
|
|
94
102
|
});
|
|
95
103
|
}
|
|
96
104
|
async topUsers(limit, start, end) {
|
|
97
105
|
const rows = await this.callproc("spend_by_user", [start, end]);
|
|
98
106
|
return (rows ?? []).slice(0, limit).map((raw) => {
|
|
99
|
-
const row = raw;
|
|
107
|
+
const row = requireAnalyticsRow(raw, "AnalyticsRepository.topUsers");
|
|
100
108
|
return safeParse(TopUserRowSchema, { user_id: row.subject_id, total_spend: row.total_spend }, "AnalyticsRepository.topUsers");
|
|
101
109
|
});
|
|
102
110
|
}
|
|
103
111
|
async dailySpend(start, end) {
|
|
104
112
|
const rows = await this.callproc("daily_spend", [start, end]);
|
|
105
113
|
return (rows ?? []).map((raw) => {
|
|
106
|
-
const row = raw;
|
|
114
|
+
const row = requireAnalyticsRow(raw, "AnalyticsRepository.dailySpend");
|
|
107
115
|
return safeParse(DailySpendRowSchema, { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count }, "AnalyticsRepository.dailySpend");
|
|
108
116
|
});
|
|
109
117
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAElG,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;IACpB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE;IAC9B,CAAC,CAAC,MAAM,EAAE,CAAC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,OAAe;QAClD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;QACxE,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,oCAAoC,CAAC,CAAC;IACjF,CAAC;IAED,KAAK,CAAC,gBAAgB,CACpB,MAAc,EACd,QAAuB,EACvB,MAAqB,EACrB,KAAa,EACb,aAA4B,EAC5B,aAA4B,EAC5B,iBAA0B;QAE1B,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,IAAI,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC3E,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE;YACrD,MAAM;YACN,aAAa;YACb,aAAa;YACb,KAAK;YACL,QAAQ;YACR,MAAM;YACN,iBAAiB;SAClB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,sCAAsC,CAAC,CAC7E,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z.union([z.string().min(1), z.date().transform((value) => value.toISOString())]);\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n z.date().transform((value) => value.toISOString().slice(0, 10)),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.unknown()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = raw as Record<string, unknown>;\n return safeParse(\n SpendByUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = raw as Record<string, unknown>;\n return safeParse(\n SpendByModelRowSchema,\n { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).slice(0, limit).map((raw) => {\n const row = raw as Record<string, unknown>;\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = raw as Record<string, unknown>;\n return safeParse(\n DailySpendRowSchema,\n { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,aAAa,EAAwC,MAAM,yBAAyB,CAAC;AAC9F,OAAO,E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,aAAa,IAAI,IAAI,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC3E,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE;YACrD,MAAM;YACN,aAAa;YACb,aAAa;YACb,KAAK;YACL,QAAQ;YACR,MAAM;YACN,iBAAiB;SAClB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,sCAAsC,CAAC,CAC7E,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { isPostgresRow, type PostgresRow, type PostgresValue } from \"../../../shared/json.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z.union([z.string().min(1), z.date().transform((value) => value.toISOString())]);\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n z.date().transform((value) => value.toISOString().slice(0, 10)),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nfunction requireAnalyticsRow(value: PostgresValue, context: string): PostgresRow {\n if (!isPostgresRow(value)) {\n throw new StoreError(`${context}: expected an object result row`);\n }\n return value;\n}\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByUser\");\n return safeParse(\n SpendByUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByModel\");\n return safeParse(\n SpendByModelRowSchema,\n { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).slice(0, limit).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.topUsers\");\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.dailySpend\");\n return safeParse(\n DailySpendRowSchema,\n { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"balance.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAWlE,QAAA,MAAM,gBAAgB;;;;kBAMX,CAAC;AAEZ,QAAA,MAAM,mBA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AM,GAAG,IAAI,CAAC;QACtB,QAAQ,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;CAcpC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
3
|
-
import { pgBoolean, postgresUuid,
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
|
+
import { pgBoolean, postgresUuid, requireRecordRow, optionalRecordRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BalanceRowSchema = z
|
|
6
6
|
.object({
|
|
@@ -110,7 +110,7 @@ export class BalanceRepository {
|
|
|
110
110
|
const rows = await this.callproc("get_credit_state", [userId]);
|
|
111
111
|
if (!rows || rows.length === 0)
|
|
112
112
|
return null;
|
|
113
|
-
const row =
|
|
113
|
+
const row = requireRecordRow(rows, "BalanceRepository.getBalance");
|
|
114
114
|
return safeParse(BalanceRowSchema, {
|
|
115
115
|
user_id: userId,
|
|
116
116
|
balance: row.balance,
|
|
@@ -132,12 +132,12 @@ export class BalanceRepository {
|
|
|
132
132
|
expiresAt,
|
|
133
133
|
"0",
|
|
134
134
|
]);
|
|
135
|
-
const row =
|
|
135
|
+
const row = requireRecordRow(rows, "BalanceRepository.addCredits");
|
|
136
136
|
const state = row.error_code == null
|
|
137
|
-
? (await this.callproc("get_credit_state", [userId]))
|
|
137
|
+
? optionalRecordRow(await this.callproc("get_credit_state", [userId]), "BalanceRepository.addCredits.state")
|
|
138
138
|
: undefined;
|
|
139
139
|
const grant = row.error_code == null && decimalAmount.isPositive() && row.entry_id != null
|
|
140
|
-
? (await this.callproc("get_credit_grant_details", [userId, row.entry_id]))
|
|
140
|
+
? optionalRecordRow(await this.callproc("get_credit_grant_details", [userId, row.entry_id]), "BalanceRepository.addCredits.grant")
|
|
141
141
|
: undefined;
|
|
142
142
|
return safeParse(AddCreditsRowSchema, {
|
|
143
143
|
entry_id: row.entry_id ?? null,
|
|
@@ -156,7 +156,7 @@ export class BalanceRepository {
|
|
|
156
156
|
if (!rows || rows.length === 0) {
|
|
157
157
|
return null;
|
|
158
158
|
}
|
|
159
|
-
const row =
|
|
159
|
+
const row = requireRecordRow(rows, "BalanceRepository.getAvailable");
|
|
160
160
|
return safeParse(AvailableRowSchema, {
|
|
161
161
|
balance: row.balance,
|
|
162
162
|
reserved: row.reserved,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,OAAO,EAAE,OAAO;IAChB,kBAAkB,EAAE,OAAO;CAC5B,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,MAAM,EAAE,OAAO;IACf,WAAW,EAAE,OAAO,CAAC,QAAQ,EAAE;IAC/B,kBAAkB,EAAE,OAAO,C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ACxB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,8BAA8B,CAC/B,CAAC;IACJ,CAAC;IAED,8DAA8D;IAC9D,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,EAAE,gCAAgC,CAA4B,CAAC;QAC1F,OAAO,SAAS,CACd,kBAAkB,EAClB;YACE,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,SAAS,EAAE,GAAG,CAAC,SAAS;SACzB,EACD,gCAAgC,CACjC,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,KAAK,CAAC,mBAAmB,CAAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n Record<string, unknown> | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,M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EACD,gCAAgC,CACjC,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,KAAK,CAAC,mBAAmB,CAAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n optionalRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRecordRow(rows, \"BalanceRepository.getBalance\");\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRecordRow(rows, \"BalanceRepository.addCredits\");\n const state =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_state\", [userId]),\n \"BalanceRepository.addCredits.state\",\n )\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]),\n \"BalanceRepository.addCredits.grant\",\n )\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRecordRow(rows, \"BalanceRepository.getAvailable\");\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import Decimal from "decimal.js";
|
|
2
|
+
import { Decimal } from "decimal.js";
|
|
3
3
|
import { postgresUuid, requireRow, safeParse } from "../../../shared/postgres-validation.js";
|
|
4
4
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
5
5
|
const BucketRowSchema = z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE7F,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE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GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CACvC,SAAS,CAAC,eAAe,EAAE,GAAG,EAAE,oCAAoC,CAAC,CACtE,CAAC;QACF,MAAM,YAAY,GAAG,OAAO;aACzB,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;aAC/D,QAAQ,EAAE,CAAC;QACd,OAAO,SAAS,CACd,uBAAuB,EACvB;YACE,OAAO,EAAE,MAAM;YACf,OAAO;YACP,aAAa,EAAE,YAAY;SAC5B,EACD,oCAAoC,CACrC,CAAC;IACJ,CAAC;IAED,mCAAmC;IACnC,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK,EAAE,MAAe,EAAE,KAAK,GAAG,GAAG;QACpE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QACxF,OAAO,SAAS,CACd,cAAc,EACd,UAAU,CAAC,IAAI,EAAE,sCAAsC,CAAC,EACxD,sCAAsC,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BucketRowSchema = z\n .object({\n bucket_key: z.string().min(1),\n label: z.string().min(1),\n priority: z.number().int().nonnegative(),\n expires: z.boolean(),\n balance: decimal,\n })\n .strict();\n\nconst BucketEnvelopeRowSchema = z\n .object({\n user_id: postgresUuid,\n buckets: z.array(BucketRowSchema),\n total_balance: decimal,\n })\n .strict();\n\nconst SweepRowSchema = z\n .object({\n expired_count: z.number().int().nonnegative(),\n expired_amount: decimal,\n expired_by_bucket: z.record(z.string().min(1), decimal),\n })\n .strict();\n\nexport type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;\nexport type SweepRow = z.infer<typeof SweepRowSchema>;\n\n/** Repository for credit bucket operations. */\nexport class BucketRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch per-bucket credit balances for a user. */\n async getBucketBalances(userId: string): Promise<BucketEnvelopeRow> {\n const rows = await this.callproc(\"get_credit_bucket_balances\", [userId]);\n const buckets = (rows ?? []).map((row) =>\n safeParse(BucketRowSchema, row, \"BucketRepository.getBucketBalances\"),\n );\n const totalBalance = buckets\n .reduce((total, row) => total.plus(row.balance), new Decimal(0))\n .toString();\n return safeParse(\n BucketEnvelopeRowSchema,\n {\n user_id: userId,\n buckets,\n total_balance: totalBalance,\n },\n \"BucketRepository.getBucketBalances\",\n );\n }\n\n /** Sweep expired credit grants. */\n async sweepExpiredCredits(dryRun = false, userId?: string, limit = 100): Promise<SweepRow> {\n const rows = await this.callproc(\"sweep_expired_lots\", [limit, userId ?? null, dryRun]);\n return safeParse(\n SweepRowSchema,\n requireRow(rows, \"BucketRepository.sweepExpiredCredits\"),\n \"BucketRepository.sweepExpiredCredits\",\n );\n }\n}\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import type { CallProc } from "../../../shared/postgres-types.js";
|
|
3
|
+
import type { JsonObject } from "../../../shared/json.js";
|
|
3
4
|
declare const CatalogRevisionRowSchema: z.ZodObject<{
|
|
4
5
|
id: z.ZodString;
|
|
5
|
-
config: z.ZodRecord<z.ZodString, z.
|
|
6
|
+
config: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
|
|
6
7
|
version: z.ZodCoercedNumber<unknown>;
|
|
7
8
|
label: z.ZodNullable<z.ZodString>;
|
|
8
9
|
active: z.ZodBoolean;
|
|
@@ -20,12 +21,12 @@ export declare class CatalogRepository {
|
|
|
20
21
|
constructor(callproc: CallProc);
|
|
21
22
|
private parseRevision;
|
|
22
23
|
getActiveCatalog(): Promise<CatalogRevisionRow | null>;
|
|
23
|
-
publishAndActivateCatalog(config: string, label: string | null, rollout:
|
|
24
|
+
publishAndActivateCatalog(config: string, label: string | null, rollout: JsonObject): Promise<CatalogRevisionRow>;
|
|
24
25
|
publishCatalogDraft(config: string, label: string | null): Promise<CatalogRevisionRow>;
|
|
25
26
|
private publishRevision;
|
|
26
27
|
getCatalogHistory(): Promise<CatalogRevisionRow[]>;
|
|
27
28
|
getCatalogRevision(version: number): Promise<CatalogRevisionRow | null>;
|
|
28
|
-
activateCatalogRevision(version: number, rollout:
|
|
29
|
+
activateCatalogRevision(version: number, rollout: JsonObject): Promise<CatalogRevisionRow>;
|
|
29
30
|
}
|
|
30
31
|
export {};
|
|
31
32
|
//# sourceMappingURL=catalog.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AAQvE,QAAA,MAAM,wBAAwB;;;;;;;;;;;;;kBAUnB,CAAC;AAQZ,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE1E,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAE/C,OAAO,CAAC,aAAa;IAgBf,gBAAgB,IAAI,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAOtD,yBAAyB,CAC7B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,OAAO,EAAE,UAAU,GAClB,OAAO,CAAC,kBAAkB,CAAC;IAIxB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,kBAAkB,CAAC;YAI9E,eAAe;IA6BvB,iBAAiB,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAWlD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAOvE,uBAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAQjG"}
|
|
@@ -4,7 +4,7 @@ import { optionalRecordRow, pgBoolean, requireRecordRow, safeParse, } from "../.
|
|
|
4
4
|
const CatalogRevisionRowSchema = z
|
|
5
5
|
.object({
|
|
6
6
|
id: z.string().min(1),
|
|
7
|
-
config: z.record(z.string(), z.
|
|
7
|
+
config: z.record(z.string(), z.json()),
|
|
8
8
|
version: z.coerce.number().int().positive(),
|
|
9
9
|
label: z.string().nullable(),
|
|
10
10
|
active: pgBoolean,
|
|
@@ -65,10 +65,11 @@ export class CatalogRepository {
|
|
|
65
65
|
async getCatalogHistory() {
|
|
66
66
|
const rows = await this.callproc("list_catalog_revisions", [500]);
|
|
67
67
|
return (rows ?? []).map((row) => {
|
|
68
|
-
|
|
68
|
+
const parsedRow = optionalRecordRow([row], "CatalogRepository.getCatalogHistory");
|
|
69
|
+
if (parsedRow === null) {
|
|
69
70
|
throw new StoreError("CatalogRepository.getCatalogHistory returned a non-object row");
|
|
70
71
|
}
|
|
71
|
-
return this.parseRevision(
|
|
72
|
+
return this.parseRevision(parsedRow, "CatalogRepository.getCatalogHistory");
|
|
72
73
|
});
|
|
73
74
|
}
|
|
74
75
|
async getCatalogRevision(version) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGhD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,wBAAwB,GAAG,CAAC;KAC/B,MAAM,CAAC;IACN,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACrB,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACtC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IAC3C,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,MAAM,EAAE,SAAS;IACjB,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC3D,UAAU,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,C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BAAgB,CAAC,CAAC;QACpE,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,2CAA2C,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n requireRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst CatalogRevisionRowSchema = z\n .object({\n id: z.string().min(1),\n config: z.record(z.string(), z.json()),\n version: z.coerce.number().int().positive(),\n label: z.string().nullable(),\n active: pgBoolean,\n status: z.enum([\"draft\", \"published\", \"active\", \"retired\"]),\n created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]),\n })\n .strict();\nconst PublishedRevisionSchema = z\n .object({\n revision_id: z.string().min(1),\n revision_no: z.coerce.number().int().positive(),\n status: z.enum([\"published\", \"active\"]),\n })\n .strict();\nexport type CatalogRevisionRow = z.infer<typeof CatalogRevisionRowSchema>;\n\nexport class CatalogRepository {\n constructor(private readonly callproc: CallProc) {}\n\n private parseRevision(row: PostgresRow, context: string): CatalogRevisionRow {\n return safeParse(\n CatalogRevisionRowSchema,\n {\n id: row.id,\n config: row.source_document,\n version: row.revision_no,\n label: row.label,\n active: row.status === \"active\",\n status: row.status,\n created_at: row.created_at,\n },\n context,\n );\n }\n\n async getActiveCatalog(): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"active_catalog_revision\", []);\n const row = optionalRecordRow(rows, \"CatalogRepository.getActiveCatalog\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getActiveCatalog\");\n }\n\n async publishAndActivateCatalog(\n config: string,\n label: string | null,\n rollout: JsonObject,\n ): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, true, rollout);\n }\n\n async publishCatalogDraft(config: string, label: string | null): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, false, { plans: {} });\n }\n\n private async publishRevision(\n config: string,\n label: string | null,\n activate = false,\n rollout: JsonObject = { plans: {} },\n ): Promise<CatalogRevisionRow> {\n const published = safeParse(\n PublishedRevisionSchema,\n requireRecordRow(\n await this.callproc(\"publish_and_activate_catalog\", [\n 1,\n JSON.parse(config),\n label,\n activate,\n rollout,\n ]),\n \"CatalogRepository.publishRevision\",\n ),\n \"CatalogRepository.publishRevision\",\n );\n const revision = await this.getCatalogRevision(published.revision_no);\n if (!revision) {\n throw new StoreError(\n `Catalog revision ${published.revision_no} disappeared after publication`,\n );\n }\n return revision;\n }\n\n async getCatalogHistory(): Promise<CatalogRevisionRow[]> {\n const rows = await this.callproc(\"list_catalog_revisions\", [500]);\n return (rows ?? []).map((row) => {\n const parsedRow = optionalRecordRow([row], \"CatalogRepository.getCatalogHistory\");\n if (parsedRow === null) {\n throw new StoreError(\"CatalogRepository.getCatalogHistory returned a non-object row\");\n }\n return this.parseRevision(parsedRow, \"CatalogRepository.getCatalogHistory\");\n });\n }\n\n async getCatalogRevision(version: number): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"catalog_revision_by_number\", [version]);\n const row = optionalRecordRow(rows, \"CatalogRepository.getCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getCatalogRevision\");\n }\n\n async activateCatalogRevision(version: number, rollout: JsonObject): Promise<CatalogRevisionRow> {\n const rows = await this.callproc(\"activate_catalog_revision\", [version, rollout]);\n const row = optionalRecordRow(rows, \"CatalogRepository.activateCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) {\n throw new StoreError(`Catalog revision ${version} was not found`);\n }\n return this.parseRevision(row, \"CatalogRepository.activateCatalogRevision\");\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deduction.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"deduction.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAWlE,eAAO,MAAM,kBAAkB;;;;;;;;;;kBAgC3B,CAAC;AA2BL,QAAA,MAAM,eAAe;;;;;;;kBA6BjB,CAAC;AAaL,QAAA,MAAM,eAAe;;;;;;kBAgBjB,CAAC;AAEL,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AACxD,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAExD,QAAA,MAAM,oBAAoB;;;;;kBAqBtB,CAAC;AAcL,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAElE,2DAA2D;AAC3D,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,kDAAkD;AAClD,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,mGAAmG;IAC7F,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IA8CtE,0EAA0E;IACpE,WAAW,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC;IA8BhE,0CAA0C;IACpC,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,SAAS,CAAC;IA2BrB,0CAA0C;IACpC,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;CAetF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
2
|
+
import { optionalRecordRow, postgresUuid, requireRecordRow, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
3
3
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
4
4
|
export const DeductionRowSchema = z
|
|
5
5
|
.object({
|
|
@@ -226,7 +226,7 @@ export class DeductionRepository {
|
|
|
226
226
|
/** Revoke credits by transaction type. */
|
|
227
227
|
async revokeCreditsByEntryType(userId, entryType) {
|
|
228
228
|
const rows = await this.callproc("revoke_subject_credits_by_operation", [userId, entryType]);
|
|
229
|
-
const row =
|
|
229
|
+
const row = requireRecordRow(rows, "DeductionRepository.revokeCreditsByEntryType");
|
|
230
230
|
return safeParse(RevokeRowSchema, {
|
|
231
231
|
user_id: userId,
|
|
232
232
|
entry_type: entryType,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deduction.js","sourceRoot":"","s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,CAAC,MAAc,EAAE,SAAiB;QAC9D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,qCAAqC,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QAC7F,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,EAAE,8CAA8C,CAG1E,CAAC;QACF,OAAO,SAAS,CACd,eAAe,EACf;YACE,OAAO,EAAE,MAAM;YACf,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,EACD,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nexport const DeductionRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n entry_id: postgresUuid.nullable(),\n amount: decimal,\n balance_after: decimal.nullable(),\n allowance_consumed: decimal,\n idempotent: z.boolean(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n user_id: postgresUuid,\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.charge_id === null || row.balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage charges require a receipt and committed balance\",\n });\n }\n if (\n row.error !== null &&\n (row.charge_id !== null ||\n row.entry_id !== null ||\n row.balance_after !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst ChargeRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: 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({ code: \"custom\", message: \"successful usage charges require a receipt\" });\n }\n if (\n row.error_code !== null &&\n (row.charge_id !== null || row.ledger_entry_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRowSchema = z\n .object({\n refund_entry_id: postgresUuid.nullable(),\n user_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n new_balance: decimal.nullable(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.refund_entry_id === null ||\n row.user_id === null ||\n row.amount === null ||\n row.new_balance === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful refunds require identity and balance fields\",\n });\n }\n if (row.error !== null && (row.refund_entry_id !== null || row.bucket_breakdown !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed refunds cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n subject_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst RevokeRowSchema = z\n .object({\n user_id: postgresUuid,\n entry_type: z.string().min(1),\n revoked: decimal,\n balance_after: decimal.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.balance_after === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful revocations require a committed balance\",\n });\n }\n });\n\nexport type DeductionRow = z.infer<typeof DeductionRowSchema>;\nexport type RefundRow = z.infer<typeof RefundRowSchema>;\nexport type RevokeRow = z.infer<typeof RevokeRowSchema>;\n\nconst UsageRecordRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: 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 usage records require a charge receipt\",\n });\n }\n if (row.error_code !== null && (row.charge_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage records cannot expose committed fields\",\n });\n }\n });\n\nconst UsageRecordRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nexport type UsageRecordRow = z.infer<typeof UsageRecordRowSchema>;\n\n/** Typed input for the plan-aware operation charge RPC. */\nexport interface DeductParams {\n userId: string;\n operation: 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}\n\n/** Repository for credit deduction operations. */\nexport class DeductionRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically deduct credits with allowance, entitlement, quota, and credit-policy enforcement. */\n async deductWithAllowance(params: DeductParams): Promise<DeductionRow> {\n const rows = await this.callproc(\"charge_usage_for_operation\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n ChargeRpcRowSchema,\n requireRow(rows, \"DeductionRepository.deductWithAllowance\"),\n \"DeductionRepository.deductWithAllowance\",\n );\n const details =\n row.error_code != null\n ? 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 \"DeductionRepository.deductWithAllowance.details\",\n );\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.charged,\n allowance_consumed: row.allowance_covered,\n balance_after: row.error_code === null ? details?.balance_after : null,\n bucket_breakdown: row.error_code === null ? details?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"DeductionRepository.deductWithAllowance\",\n );\n }\n\n /** Append a priced usage event without creating another balance debit. */\n async recordUsage(params: DeductParams): Promise<UsageRecordRow> {\n const rows = await this.callproc(\"record_usage\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n UsageRecordRpcRowSchema,\n requireRow(rows, \"DeductionRepository.recordUsage\"),\n \"DeductionRepository.recordUsage\",\n );\n return safeParse(\n UsageRecordRowSchema,\n {\n charge_id: row.charge_id,\n requested: row.requested,\n replayed: row.replayed,\n error_code: row.error_code,\n },\n \"DeductionRepository.recordUsage\",\n );\n }\n\n /** Refund a previous credit deduction. */\n async refundCredits(\n entryId: string,\n amount: string | null,\n idempotencyKey: string,\n reason: string | null,\n metadata: string,\n ): Promise<RefundRow> {\n const rows = await this.callproc(\"refund_credit_by_entry\", [\n entryId,\n amount,\n idempotencyKey,\n reason,\n metadata,\n ]);\n const row = safeParse(\n RefundRpcRowSchema,\n requireRow(rows, \"DeductionRepository.refundCredits\"),\n \"DeductionRepository.refundCredits\",\n );\n return safeParse(\n RefundRowSchema,\n {\n refund_entry_id: row.entry_id,\n user_id: row.subject_id,\n amount: row.amount,\n new_balance: row.balance_after,\n bucket_breakdown: null,\n error: row.error_code,\n },\n \"DeductionRepository.refundCredits\",\n );\n }\n\n /** Revoke credits by transaction type. */\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeRow> {\n const rows = await this.callproc(\"revoke_subject_credits_by_operation\", [userId, entryType]);\n const row = requireRow(rows, \"DeductionRepository.revokeCreditsByEntryType\") as Record<\n string,\n unknown\n >;\n return safeParse(\n RevokeRowSchema,\n {\n user_id: userId,\n entry_type: entryType,\n revoked: row.revoked,\n balance_after: row.balance_after,\n error_code: row.error_code,\n },\n \"DeductionRepository.revokeCreditsByEntryType\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"deduction.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAE3E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC;KAChC,MAAM,CAAC;IACN,SAAS,EAAE,YAAY,CAAC,QAAQ,EAAE;IAClC,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,MAAM,EAAE,OAAO;IACf,aAAa,EAAE,OAAO,CAAC,QAAQ,EAAE;IACjC,kBAAkB,EAAE,OAAO;IAC3B,UAAU,EAAE,CAAC,CAAC,OAAO,EAAE;IACvB,gBAAgB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;IACjE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;IACnC,OAAO,EAAE,YAAY;CACtB,CAAC;KACD,MAAM,EAAE;KACR,WAAW,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;IAC5B,IAAI,GAAG,CAAC,KAAK,KAAK,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,KAAK,IAAI,IAAI,GAAG,CAAC,aAAa,K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AC9B,gBAAgB,EAAE,IAAI;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,mCAAmC,CACpC,CAAC;IACJ,CAAC;IAED,0CAA0C;IAC1C,KAAK,CAAC,wBAAwB,CAAC,MAAc,EAAE,SAAiB;QAC9D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,qCAAqC,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QAC7F,MAAM,GAAG,GAAG,gBAAgB,CAAC,IAAI,EAAE,8CAA8C,CAAC,CAAC;QACnF,OAAO,SAAS,CACd,eAAe,EACf;YACE,OAAO,EAAE,MAAM;YACf,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,EACD,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRecordRow,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nexport const DeductionRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n entry_id: postgresUuid.nullable(),\n amount: decimal,\n balance_after: decimal.nullable(),\n allowance_consumed: decimal,\n idempotent: z.boolean(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n user_id: postgresUuid,\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.charge_id === null || row.balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful usage charges require a receipt and committed balance\",\n });\n }\n if (\n row.error !== null &&\n (row.charge_id !== null ||\n row.entry_id !== null ||\n row.balance_after !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst ChargeRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: 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({ code: \"custom\", message: \"successful usage charges require a receipt\" });\n }\n if (\n row.error_code !== null &&\n (row.charge_id !== null || row.ledger_entry_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage charges cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRowSchema = z\n .object({\n refund_entry_id: postgresUuid.nullable(),\n user_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n new_balance: decimal.nullable(),\n bucket_breakdown: z.record(z.string().min(1), decimal).nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.refund_entry_id === null ||\n row.user_id === null ||\n row.amount === null ||\n row.new_balance === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful refunds require identity and balance fields\",\n });\n }\n if (row.error !== null && (row.refund_entry_id !== null || row.bucket_breakdown !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed refunds cannot expose committed fields\",\n });\n }\n });\n\nconst RefundRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n subject_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst RevokeRowSchema = z\n .object({\n user_id: postgresUuid,\n entry_type: z.string().min(1),\n revoked: decimal,\n balance_after: decimal.nullable(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.balance_after === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful revocations require a committed balance\",\n });\n }\n });\n\nexport type DeductionRow = z.infer<typeof DeductionRowSchema>;\nexport type RefundRow = z.infer<typeof RefundRowSchema>;\nexport type RevokeRow = z.infer<typeof RevokeRowSchema>;\n\nconst UsageRecordRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: 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 usage records require a charge receipt\",\n });\n }\n if (row.error_code !== null && (row.charge_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed usage records cannot expose committed fields\",\n });\n }\n });\n\nconst UsageRecordRpcRowSchema = z\n .object({\n charge_id: postgresUuid.nullable(),\n requested: decimal,\n ledger_entry_id: postgresUuid.nullable(),\n charged: decimal,\n allowance_covered: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nexport type UsageRecordRow = z.infer<typeof UsageRecordRowSchema>;\n\n/** Typed input for the plan-aware operation charge RPC. */\nexport interface DeductParams {\n userId: string;\n operation: 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}\n\n/** Repository for credit deduction operations. */\nexport class DeductionRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically deduct credits with allowance, entitlement, quota, and credit-policy enforcement. */\n async deductWithAllowance(params: DeductParams): Promise<DeductionRow> {\n const rows = await this.callproc(\"charge_usage_for_operation\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n ChargeRpcRowSchema,\n requireRow(rows, \"DeductionRepository.deductWithAllowance\"),\n \"DeductionRepository.deductWithAllowance\",\n );\n const details =\n row.error_code != null\n ? 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 \"DeductionRepository.deductWithAllowance.details\",\n );\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.charged,\n allowance_consumed: row.allowance_covered,\n balance_after: row.error_code === null ? details?.balance_after : null,\n bucket_breakdown: row.error_code === null ? details?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"DeductionRepository.deductWithAllowance\",\n );\n }\n\n /** Append a priced usage event without creating another balance debit. */\n async recordUsage(params: DeductParams): Promise<UsageRecordRow> {\n const rows = await this.callproc(\"record_usage\", [\n params.userId,\n params.operation,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.metadata,\n params.measures,\n params.dimensions,\n ]);\n const row = safeParse(\n UsageRecordRpcRowSchema,\n requireRow(rows, \"DeductionRepository.recordUsage\"),\n \"DeductionRepository.recordUsage\",\n );\n return safeParse(\n UsageRecordRowSchema,\n {\n charge_id: row.charge_id,\n requested: row.requested,\n replayed: row.replayed,\n error_code: row.error_code,\n },\n \"DeductionRepository.recordUsage\",\n );\n }\n\n /** Refund a previous credit deduction. */\n async refundCredits(\n entryId: string,\n amount: string | null,\n idempotencyKey: string,\n reason: string | null,\n metadata: string,\n ): Promise<RefundRow> {\n const rows = await this.callproc(\"refund_credit_by_entry\", [\n entryId,\n amount,\n idempotencyKey,\n reason,\n metadata,\n ]);\n const row = safeParse(\n RefundRpcRowSchema,\n requireRow(rows, \"DeductionRepository.refundCredits\"),\n \"DeductionRepository.refundCredits\",\n );\n return safeParse(\n RefundRowSchema,\n {\n refund_entry_id: row.entry_id,\n user_id: row.subject_id,\n amount: row.amount,\n new_balance: row.balance_after,\n bucket_breakdown: null,\n error: row.error_code,\n },\n \"DeductionRepository.refundCredits\",\n );\n }\n\n /** Revoke credits by transaction type. */\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeRow> {\n const rows = await this.callproc(\"revoke_subject_credits_by_operation\", [userId, entryType]);\n const row = requireRecordRow(rows, \"DeductionRepository.revokeCreditsByEntryType\");\n return safeParse(\n RevokeRowSchema,\n {\n user_id: userId,\n entry_type: entryType,\n revoked: row.revoked,\n balance_after: row.balance_after,\n error_code: row.error_code,\n },\n \"DeductionRepository.revokeCreditsByEntryType\",\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"lease.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAsEnD,QAAA,MAAM,cAAc;;;;;;;kBAmChB,CAAC;AAEL,QAAA,MAAM,gBAAgB;;;;;;;;;kBAKX,CAAC;AAEZ,QAAA,MAAM,4BAA4B;;;;;kBAY9B,CAAC;AAEL,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AACtD,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAC1D,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAElF,qEAAqE;AACrE,qBAAa,eAAe;IACd,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAA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,CAAC;IAuCxF,uEAAuE;IACjE,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CASnD"}
|
|
@@ -2,7 +2,8 @@ import { z } from "zod";
|
|
|
2
2
|
import { DeductionRowSchema } from "./deduction.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
|
-
import Decimal from "decimal.js";
|
|
5
|
+
import { Decimal } from "decimal.js";
|
|
6
|
+
import { quantizeMoney } from "../../../expr.js";
|
|
6
7
|
const decimal = z.union([z.string().min(1), z.number().finite()]);
|
|
7
8
|
const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
|
|
8
9
|
const parsed = value instanceof Date ? value : new Date(value);
|
|
@@ -165,7 +166,8 @@ export class LeaseRepository {
|
|
|
165
166
|
params.metadata,
|
|
166
167
|
]);
|
|
167
168
|
const row = safeParse(SettleLeaseRpcRowSchema, requireRow(rows, "LeaseRepository.settleLease"), "LeaseRepository.settleLease");
|
|
168
|
-
if (row.error_code === null &&
|
|
169
|
+
if (row.error_code === null &&
|
|
170
|
+
!new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))) {
|
|
169
171
|
throw new StoreError("LeaseRepository.settleLease: committed amount differs from the request", {
|
|
170
172
|
indeterminate: true,
|
|
171
173
|
});
|