@zonastery/bursar 2.1.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -3
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +6 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +19 -3
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +34 -5
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +12 -6
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +20 -3
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +1 -0
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +40 -13
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +2 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +82 -16
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -0
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +160 -48
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +6 -3
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js +5 -2
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +33 -3
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +2 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +6 -1
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +25 -17
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js +24 -4
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +40 -43
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +6 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +9 -5
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +24 -31
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +110 -113
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -0
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +15 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +2 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +15 -0
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +10 -0
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +2 -24
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -29
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts +5 -17
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +26 -44
- package/dist/bursar.js.map +1 -1
- package/dist/cli.js +0 -6
- package/dist/cli.js.map +1 -1
- package/dist/commerce/service.d.ts +1 -0
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +162 -38
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +2 -0
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/normalize.d.ts +3 -1
- package/dist/config/normalize.d.ts.map +1 -1
- package/dist/config/normalize.js +12 -5
- package/dist/config/normalize.js.map +1 -1
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +4 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +32 -17
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +5 -5
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +13 -9
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +7 -5
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +2 -0
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +11 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config.d.ts +2 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +94 -86
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +5 -4
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +15 -2
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +74 -18
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +3 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +47 -38
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -7
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +6 -57
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +25 -7
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts +28 -0
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +33 -14
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +2 -2
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +2 -12
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +9 -2
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +3 -0
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +46 -12
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +4 -1
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +1 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +9 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +29 -20
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +329 -250
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +4 -4
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/rated-wire.d.ts +7 -0
- package/dist/credits/rated-wire.d.ts.map +1 -0
- package/dist/credits/rated-wire.js +70 -0
- package/dist/credits/rated-wire.js.map +1 -0
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +8 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +5 -7
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +11 -9
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +156 -138
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +11 -3
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +9 -0
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +9 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/admission.d.ts +1 -0
- package/dist/credits/types/admission.d.ts.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/grants.d.ts +12 -0
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +13 -0
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/quotas.d.ts +2 -1
- package/dist/credits/types/quotas.d.ts.map +1 -1
- package/dist/credits/types/quotas.js.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +51 -34
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +12 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +29 -9
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/language.js +1 -1
- package/dist/expr/language.js.map +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +5 -6
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +102 -202
- package/dist/generated/pricing-config.types.d.ts +7 -1
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +38 -12
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js.map +1 -1
- package/dist/pricing-decimal.d.ts +7 -0
- package/dist/pricing-decimal.d.ts.map +1 -0
- package/dist/pricing-decimal.js +43 -0
- package/dist/pricing-decimal.js.map +1 -0
- package/dist/providers/dodo/better-auth-core.d.ts +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth-core.js +2 -2
- package/dist/providers/dodo/better-auth-core.js.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -2
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +120 -18
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs-core.js +2 -2
- package/dist/providers/dodo/nextjs-core.js.map +1 -1
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +16 -6
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +5 -2
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +33 -6
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
- package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
- package/dist/providers/dodo/verified-payment-payload.js +42 -0
- package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +4 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +3 -1
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +48 -20
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +4 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +64 -23
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +11 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +9 -0
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +3 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +61 -49
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/provider-rejection.d.ts +3 -0
- package/dist/shared/provider-rejection.d.ts.map +1 -0
- package/dist/shared/provider-rejection.js +17 -0
- package/dist/shared/provider-rejection.js.map +1 -0
- package/dist/shared/timestamp.d.ts +2 -0
- package/dist/shared/timestamp.d.ts.map +1 -1
- package/dist/shared/timestamp.js +7 -0
- package/dist/shared/timestamp.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +18 -17
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +5 -0
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +46 -14
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +3 -7
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js +6 -15
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +4 -3
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +3 -0
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +1 -3
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +10 -4
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +15 -10
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +74 -68
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/package.json +73 -71
- package/dist/credits/queries.d.ts +0 -33
- package/dist/credits/queries.d.ts.map +0 -1
- package/dist/credits/queries.js +0 -71
- package/dist/credits/queries.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,MAAM,OAAO,GAAG,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,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC;YACf,IAAI,EAAE,QAAQ;YACd,OAAO,EAAE,4BAA4B;SACtC,CAAC,CAAC;QACH,OAAO,CAAC,CAAC,KAAK,CAAC;IACj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I,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,mBAAmB,EAAE,GAAG,EAAE,8BAA8B,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,MAAc,EACd,KAAoB,EACpB,KAAa,EACb,cAA6B,EAC7B,OAAsB;QAEtB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,EAAE;YAC5D,MAAM;YACN,KAAK;YACL,KAAK;YACL,cAAc;YACd,OAAO;SACR,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,mBAAmB,EAAE,GAAG,EAAE,gCAAgC,CAAC,CACtE,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,MAAc;QACjC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,+BAA+B,CAAC,CAAC;QACrE,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,kBAAkB,EAAE,GAAG,EAAE,+BAA+B,CAAC,CAAC;IAC1E,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\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({\n code: \"custom\",\n message: \"expected a valid timestamp\",\n });\n return z.NEVER;\n }\n return parsed;\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst entitlementValue = z.object({ value: z.json() }).strict();\nconst admissionOperation = z\n .object({ max_in_flight: z.number().int().positive().nullable() })\n .strict();\n\nconst UserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_assigned_at: timestamp,\n plan_assignment_ends_at: timestamp.nullable(),\n assignment_source_type: z.enum([\"manual\", \"subscription\", \"migration\", \"system\"]),\n assignment_source_id: postgresUuid.nullable(),\n catalog_revision_pinned: z.boolean(),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_label: z.string().min(1),\n rate_card: z.string().min(1).nullable(),\n allowed_operations: z.array(z.string().min(1)),\n operation_access: z.enum([\"all\", \"none\", \"listed\"]),\n credit_allowance_amount: decimal.nullable(),\n credit_allowance_priority: z.number().int().nonnegative().nullable(),\n credit_allowance_reset_unit: z\n .enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"])\n .nullable(),\n credit_allowance_reset_count: z.number().int().positive().nullable(),\n credit_allowance_reset_anchor: z.enum([\"calendar\", \"plan_assignment\", \"rolling\"]).nullable(),\n credit_allowance_reset_timezone: z.string().min(1).nullable(),\n entitlements: z.record(z.string().min(1), entitlementValue),\n credit_policy_type: z.enum([\"prepaid\", \"credit_line\"]).nullable(),\n credit_limit: decimal.nullable(),\n admission_max_in_flight: z.number().int().positive().nullable(),\n operation_admission: z.record(z.string().min(1), admissionOperation),\n catalog_revision_no: safeInteger,\n })\n .strict()\n .superRefine((row, context) => {\n const allowance = [\n row.credit_allowance_amount,\n row.credit_allowance_priority,\n row.credit_allowance_reset_unit,\n row.credit_allowance_reset_count,\n row.credit_allowance_reset_anchor,\n row.credit_allowance_reset_timezone,\n ];\n const populated = allowance.filter((value) => value !== null).length;\n if (populated !== 0 && populated !== allowance.length) {\n context.addIssue({\n code: \"custom\",\n message: \"allowance policy fields must be all set or all null\",\n });\n }\n if (\n (row.credit_policy_type === null && row.credit_limit !== null) ||\n (row.credit_policy_type === \"prepaid\" && row.credit_limit !== null) ||\n (row.credit_policy_type === \"credit_line\" && row.credit_limit === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"credit policy fields are inconsistent\",\n });\n }\n });\n\nconst SetUserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_assigned_at: timestamp,\n assignment_state: z.enum([\"applied\", \"scheduled\"]),\n })\n .strict();\n\nconst EntitlementRowSchema = z\n .object({\n feature_key: z.string().min(1),\n feature_type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n feature_value: z.json(),\n catalog_revision_id: postgresUuid,\n plan_key: z.string().min(1).nullable(),\n value_source: z.enum([\"default\", \"plan\"]),\n })\n .strict();\n\nconst AllowanceRowSchema = z\n .object({\n plan_id: postgresUuid,\n allowance_remaining: decimal,\n period_start: timestamp.transform((value) => value.toISOString()),\n period_end: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nconst UnsetPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n })\n .strict();\n\nconst PlanMigrationStartRowSchema = postgresUuid;\nconst PlanMigrationBatchRowSchema = z\n .object({\n migrated: z.number().int().nonnegative(),\n done: z.boolean(),\n next_cursor: postgresUuid.nullable(),\n })\n .strict();\nconst QuotaStateRowSchema = z\n .object({\n user_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n quota_limit: decimal,\n consumed: decimal,\n reserved: decimal,\n remaining: decimal,\n overage: decimal,\n enforcement: z.enum([\"block\", \"allow\"]),\n window_start: timestamp.transform((value) => value.toISOString()),\n window_end: timestamp.transform((value) => value.toISOString()),\n emit_at_percent: z.array(z.number().finite().min(0).max(100)),\n })\n .strict();\nconst QuotaEventRowSchema = z\n .object({\n event_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n event_type: z.enum([\"threshold\", \"blocked\"]),\n threshold_percent: z.number().finite().min(0).max(100).nullable(),\n idempotency_key: z.string().min(1),\n usage_charge_id: postgresUuid.nullable(),\n created_at: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nexport type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;\nexport type UserPlanRow = z.infer<typeof UserPlanRowSchema>;\nexport type SetUserPlanRow = z.infer<typeof SetUserPlanRowSchema>;\nexport type EntitlementRow = z.infer<typeof EntitlementRowSchema>;\nexport type AllowanceRow = z.infer<typeof AllowanceRowSchema>;\nexport type PlanMigrationStartRow = z.infer<typeof PlanMigrationStartRowSchema>;\nexport type PlanMigrationBatchRow = z.infer<typeof PlanMigrationBatchRowSchema>;\nexport type QuotaStateRow = z.infer<typeof QuotaStateRowSchema>;\nexport type QuotaEventRow = z.infer<typeof QuotaEventRowSchema>;\n\n/** Repository for plan management operations. */\nexport class PlanRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's current plan. Returns null if user has no plan. */\n async getUserPlan(userId: string): Promise<UserPlanRow | null> {\n const rows = await this.callproc(\"get_subject_plan\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.getUserPlan\");\n return row === null ? null : safeParse(UserPlanRowSchema, row, \"PlanRepository.getUserPlan\");\n }\n\n async getEntitlement(userId: string, feature: string): Promise<EntitlementRow | null> {\n const rows = await this.callproc(\"get_subject_entitlements\", [userId]);\n const entitlements = (rows ?? []).map((row) =>\n safeParse(EntitlementRowSchema, row, \"PlanRepository.getEntitlement\"),\n );\n return entitlements.find((candidate) => candidate.feature_key === feature) ?? null;\n }\n\n /** Assign a plan to a user. */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt: string | null,\n ): Promise<SetUserPlanRow> {\n return safeParse(\n SetUserPlanRowSchema,\n requireRow(\n await this.callproc(\"set_subject_plan\", [userId, planKey, planAssignedAt]),\n \"PlanRepository.setUserPlan\",\n ),\n \"PlanRepository.setUserPlan\",\n );\n }\n\n /** Remove a user's plan assignment. */\n async unsetUserPlan(userId: string): Promise<UnsetPlanRow> {\n const rows = await this.callproc(\"unassign_plan\", [userId, \"sdk_unassignment\"]);\n if (\n !safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.unsetUserPlan\"),\n \"PlanRepository.unsetUserPlan\",\n )\n ) {\n throw new StoreError(\"PlanRepository.unsetUserPlan: unassign_plan returned false\");\n }\n return safeParse(UnsetPlanRowSchema, { user_id: userId }, \"PlanRepository.unsetUserPlan\");\n }\n\n /** Pin or unpin the user's current assignment to its catalog revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n const rows = await this.callproc(\"set_plan_revision_pin\", [userId, pinned]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.setPlanRevisionPin\"),\n \"PlanRepository.setPlanRevisionPin\",\n );\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit: number): Promise<number> {\n const rows = await this.callproc(\"apply_due_plan_assignment_changes\", [limit]);\n return safeParse(\n z.number().int().nonnegative(),\n requireRow(rows, \"PlanRepository.applyDuePlanChanges\"),\n \"PlanRepository.applyDuePlanChanges\",\n );\n }\n\n /** Check a user's remaining free allowance. */\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartRow> {\n const rows = await this.callproc(\"start_plan_migration\", [fromPlanId, toPlanId]);\n return safeParse(\n PlanMigrationStartRowSchema,\n requireRow(rows, \"PlanRepository.startPlanMigration\"),\n \"PlanRepository.startPlanMigration\",\n );\n }\n\n async migratePlanBatch(migrationId: string, batchSize?: number): Promise<PlanMigrationBatchRow> {\n const rows = await this.callproc(\"migrate_plan_batch\", [migrationId, batchSize ?? 100]);\n return safeParse(\n PlanMigrationBatchRowSchema,\n requireRow(rows, \"PlanRepository.migratePlanBatch\"),\n \"PlanRepository.migratePlanBatch\",\n );\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaStateRow[]> {\n const rows = await this.callproc(\"get_subject_quota_state\", [userId, quotaKey ?? null]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaStateRowSchema, row, \"PlanRepository.getQuotaState\"),\n );\n }\n\n async listQuotaEvents(\n userId: string,\n after: string | null,\n limit: number,\n idempotencyKey: string | null,\n afterId: string | null,\n ): Promise<QuotaEventRow[]> {\n const rows = await this.callproc(\"list_subject_quota_events\", [\n userId,\n after,\n limit,\n idempotencyKey,\n afterId,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaEventRowSchema, row, \"PlanRepository.listQuotaEvents\"),\n );\n }\n\n async checkAllowance(userId: string): Promise<AllowanceRow | null> {\n const rows = await this.callproc(\"get_subject_allowance\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.checkAllowance\");\n return row === null\n ? null\n : safeParse(AllowanceRowSchema, row, \"PlanRepository.checkAllowance\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plan.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,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,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE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AAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,+BAA+B,CAAC,CAAC;QACrE,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,kBAAkB,EAAE,GAAG,EAAE,+BAA+B,CAAC,CAAC;IAC1E,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\";\nimport { StoreError } from \"../../../errors.js\";\nimport { utcTimestamp } from \"../../../shared/timestamp.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({\n code: \"custom\",\n message: \"expected a valid timestamp\",\n });\n return z.NEVER;\n }\n return parsed;\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst entitlementValue = z.object({ value: z.json() }).strict();\nconst admissionOperation = z\n .object({ max_in_flight: z.number().int().positive().nullable() })\n .strict();\n\nconst UserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_assigned_at: timestamp,\n plan_assignment_ends_at: timestamp.nullable(),\n assignment_source_type: z.enum([\"manual\", \"subscription\", \"migration\", \"system\"]),\n assignment_source_id: postgresUuid.nullable(),\n catalog_revision_pinned: z.boolean(),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_label: z.string().min(1),\n rate_card: z.string().min(1).nullable(),\n allowed_operations: z.array(z.string().min(1)),\n operation_access: z.enum([\"all\", \"none\", \"listed\"]),\n credit_allowance_amount: decimal.nullable(),\n credit_allowance_priority: z.number().int().nonnegative().nullable(),\n credit_allowance_reset_unit: z\n .enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"])\n .nullable(),\n credit_allowance_reset_count: z.number().int().positive().nullable(),\n credit_allowance_reset_anchor: z.enum([\"calendar\", \"plan_assignment\", \"rolling\"]).nullable(),\n credit_allowance_reset_timezone: z.string().min(1).nullable(),\n entitlements: z.record(z.string().min(1), entitlementValue),\n credit_policy_type: z.enum([\"prepaid\", \"credit_line\"]).nullable(),\n credit_limit: decimal.nullable(),\n admission_max_in_flight: z.number().int().positive().nullable(),\n operation_admission: z.record(z.string().min(1), admissionOperation),\n catalog_revision_no: safeInteger,\n })\n .strict()\n .superRefine((row, context) => {\n const allowance = [\n row.credit_allowance_amount,\n row.credit_allowance_priority,\n row.credit_allowance_reset_unit,\n row.credit_allowance_reset_count,\n row.credit_allowance_reset_anchor,\n row.credit_allowance_reset_timezone,\n ];\n const populated = allowance.filter((value) => value !== null).length;\n if (populated !== 0 && populated !== allowance.length) {\n context.addIssue({\n code: \"custom\",\n message: \"allowance policy fields must be all set or all null\",\n });\n }\n if (\n (row.credit_policy_type === null && row.credit_limit !== null) ||\n (row.credit_policy_type === \"prepaid\" && row.credit_limit !== null) ||\n (row.credit_policy_type === \"credit_line\" && row.credit_limit === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"credit policy fields are inconsistent\",\n });\n }\n });\n\nconst SetUserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_assigned_at: timestamp,\n assignment_state: z.enum([\"applied\", \"scheduled\"]),\n })\n .strict();\n\nconst EntitlementRowSchema = z\n .object({\n feature_key: z.string().min(1),\n feature_type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n feature_value: z.json(),\n catalog_revision_id: postgresUuid,\n plan_key: z.string().min(1).nullable(),\n value_source: z.enum([\"default\", \"plan\"]),\n })\n .strict();\n\nconst AllowanceRowSchema = z\n .object({\n plan_id: postgresUuid,\n allowance_remaining: decimal,\n period_start: timestamp.transform((value) => value.toISOString()),\n period_end: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nconst UnsetPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n })\n .strict();\n\nconst PlanMigrationStartRowSchema = postgresUuid;\nconst PlanMigrationBatchRowSchema = z\n .object({\n migrated: z.number().int().nonnegative(),\n done: z.boolean(),\n next_cursor: postgresUuid.nullable(),\n })\n .strict();\nconst QuotaStateRowSchema = z\n .object({\n user_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n quota_limit: decimal,\n consumed: decimal,\n reserved: decimal,\n remaining: decimal,\n overage: decimal,\n enforcement: z.enum([\"block\", \"allow\"]),\n window_start: timestamp.transform((value) => value.toISOString()),\n window_end: timestamp.transform((value) => value.toISOString()),\n emit_at_percent: z.array(z.number().finite().min(0).max(100)),\n })\n .strict();\nconst QuotaEventRowSchema = z\n .object({\n event_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n event_type: z.enum([\"threshold\", \"blocked\"]),\n threshold_percent: z.number().finite().min(0).max(100).nullable(),\n idempotency_key: z.string().min(1),\n usage_charge_id: postgresUuid.nullable(),\n created_at: z\n .union([z.string().min(1), z.date()])\n .transform((value) => (value instanceof Date ? value.toISOString() : utcTimestamp(value))),\n })\n .strict();\n\nexport type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;\nexport type UserPlanRow = z.infer<typeof UserPlanRowSchema>;\nexport type SetUserPlanRow = z.infer<typeof SetUserPlanRowSchema>;\nexport type EntitlementRow = z.infer<typeof EntitlementRowSchema>;\nexport type AllowanceRow = z.infer<typeof AllowanceRowSchema>;\nexport type PlanMigrationStartRow = z.infer<typeof PlanMigrationStartRowSchema>;\nexport type PlanMigrationBatchRow = z.infer<typeof PlanMigrationBatchRowSchema>;\nexport type QuotaStateRow = z.infer<typeof QuotaStateRowSchema>;\nexport type QuotaEventRow = z.infer<typeof QuotaEventRowSchema>;\n\n/** Repository for plan management operations. */\nexport class PlanRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's current plan. Returns null if user has no plan. */\n async getUserPlan(userId: string): Promise<UserPlanRow | null> {\n const rows = await this.callproc(\"get_subject_plan\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.getUserPlan\");\n return row === null ? null : safeParse(UserPlanRowSchema, row, \"PlanRepository.getUserPlan\");\n }\n\n async getEntitlement(userId: string, feature: string): Promise<EntitlementRow | null> {\n const rows = await this.callproc(\"get_subject_entitlements\", [userId]);\n const entitlements = (rows ?? []).map((row) =>\n safeParse(EntitlementRowSchema, row, \"PlanRepository.getEntitlement\"),\n );\n return entitlements.find((candidate) => candidate.feature_key === feature) ?? null;\n }\n\n /** Assign a plan to a user. */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt: string | null,\n ): Promise<SetUserPlanRow> {\n return safeParse(\n SetUserPlanRowSchema,\n requireRow(\n await this.callproc(\"set_subject_plan\", [userId, planKey, planAssignedAt]),\n \"PlanRepository.setUserPlan\",\n ),\n \"PlanRepository.setUserPlan\",\n );\n }\n\n /** Remove a user's plan assignment. */\n async unsetUserPlan(userId: string): Promise<UnsetPlanRow> {\n const rows = await this.callproc(\"unassign_plan\", [userId, \"sdk_unassignment\"]);\n if (\n !safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.unsetUserPlan\"),\n \"PlanRepository.unsetUserPlan\",\n )\n ) {\n throw new StoreError(\"PlanRepository.unsetUserPlan: unassign_plan returned false\");\n }\n return safeParse(UnsetPlanRowSchema, { user_id: userId }, \"PlanRepository.unsetUserPlan\");\n }\n\n /** Pin or unpin the user's current assignment to its catalog revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n const rows = await this.callproc(\"set_plan_revision_pin\", [userId, pinned]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.setPlanRevisionPin\"),\n \"PlanRepository.setPlanRevisionPin\",\n );\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit: number): Promise<number> {\n const rows = await this.callproc(\"apply_due_plan_assignment_changes\", [limit]);\n return safeParse(\n z.number().int().nonnegative(),\n requireRow(rows, \"PlanRepository.applyDuePlanChanges\"),\n \"PlanRepository.applyDuePlanChanges\",\n );\n }\n\n /** Check a user's remaining free allowance. */\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartRow> {\n const rows = await this.callproc(\"start_plan_migration\", [fromPlanId, toPlanId]);\n return safeParse(\n PlanMigrationStartRowSchema,\n requireRow(rows, \"PlanRepository.startPlanMigration\"),\n \"PlanRepository.startPlanMigration\",\n );\n }\n\n async migratePlanBatch(migrationId: string, batchSize?: number): Promise<PlanMigrationBatchRow> {\n const rows = await this.callproc(\"migrate_plan_batch\", [migrationId, batchSize ?? 100]);\n return safeParse(\n PlanMigrationBatchRowSchema,\n requireRow(rows, \"PlanRepository.migratePlanBatch\"),\n \"PlanRepository.migratePlanBatch\",\n );\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaStateRow[]> {\n const rows = await this.callproc(\"get_subject_quota_state\", [userId, quotaKey ?? null]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaStateRowSchema, row, \"PlanRepository.getQuotaState\"),\n );\n }\n\n async listQuotaEvents(\n userId: string,\n after: string | null,\n limit: number,\n idempotencyKey: string | null,\n afterId: string | null,\n ): Promise<QuotaEventRow[]> {\n const rows = await this.callproc(\"list_subject_quota_events\", [\n userId,\n after,\n limit,\n idempotencyKey,\n afterId,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaEventRowSchema, row, \"PlanRepository.listQuotaEvents\"),\n );\n }\n\n async checkAllowance(userId: string): Promise<AllowanceRow | null> {\n const rows = await this.callproc(\"get_subject_allowance\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.checkAllowance\");\n return row === null\n ? null\n : safeParse(AllowanceRowSchema, row, \"PlanRepository.checkAllowance\");\n }\n}\n"]}
|
|
@@ -67,7 +67,7 @@ export declare class TeamRepository {
|
|
|
67
67
|
/** Remove a team member, returning false when absent or the final owner. */
|
|
68
68
|
removeTeamMember(teamId: string, userId: string): Promise<boolean>;
|
|
69
69
|
/** Deduct credits from a team's balance on behalf of a user. */
|
|
70
|
-
deductTeam(teamId: string, userId: string, amount: string, idempotencyKey: string, operation: string, metadata: string): Promise<TeamDeductionRow>;
|
|
70
|
+
deductTeam(teamId: string, userId: string, amount: string, idempotencyKey: string, operation: string, metadata: string, expectedPlanId?: string | null, expectedRevisionNo?: number | null): Promise<TeamDeductionRow>;
|
|
71
71
|
}
|
|
72
72
|
export {};
|
|
73
73
|
//# sourceMappingURL=team.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAiBlE,QAAA,MAAM,mBAAmB;;;;;;;kBA8BrB,CAAC;AAEL,QAAA,MAAM,oBAAoB;;;;;kBAOf,CAAC;AAEZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAMjB,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAOd,CAAC;AAcZ,QAAA,MAAM,sBAAsB;;;;;;;;kBA4BxB,CAAC;AAEL,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAA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,GAAE,MAAM,GAAG,IAAW,GACvC,OAAO,CAAC,gBAAgB,CAAC,CAqC3B;CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { PricingDecimal } from "../../../pricing-decimal.js";
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
import { Decimal } from "decimal.js";
|
|
3
3
|
import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
|
|
4
4
|
import { StoreError } from "../../../errors.js";
|
|
5
5
|
import { quantizeMoney } from "../../../expr.js";
|
|
@@ -86,10 +86,12 @@ const TeamDeductionRowSchema = z
|
|
|
86
86
|
})
|
|
87
87
|
.strict()
|
|
88
88
|
.superRefine((row, context) => {
|
|
89
|
-
if (row.error === null &&
|
|
89
|
+
if (row.error === null &&
|
|
90
|
+
((row.entry_id == null) !== new PricingDecimal(row.amount).isZero() ||
|
|
91
|
+
row.team_balance_after === null)) {
|
|
90
92
|
context.addIssue({
|
|
91
93
|
code: "custom",
|
|
92
|
-
message: "successful team deductions require entry and balance
|
|
94
|
+
message: "successful team deductions require a matching entry and balance",
|
|
93
95
|
});
|
|
94
96
|
}
|
|
95
97
|
if (row.error !== null && (row.entry_id !== null || row.replayed)) {
|
|
@@ -148,7 +150,7 @@ export class TeamRepository {
|
|
|
148
150
|
return safeParse(z.boolean(), requireRow(rows, "TeamRepository.removeTeamMember"), "TeamRepository.removeTeamMember");
|
|
149
151
|
}
|
|
150
152
|
/** Deduct credits from a team's balance on behalf of a user. */
|
|
151
|
-
async deductTeam(teamId, userId, amount, idempotencyKey, operation, metadata) {
|
|
153
|
+
async deductTeam(teamId, userId, amount, idempotencyKey, operation, metadata, expectedPlanId = null, expectedRevisionNo = null) {
|
|
152
154
|
const rows = await this.callproc("deduct_team", [
|
|
153
155
|
teamId,
|
|
154
156
|
userId,
|
|
@@ -156,10 +158,12 @@ export class TeamRepository {
|
|
|
156
158
|
idempotencyKey,
|
|
157
159
|
operation,
|
|
158
160
|
metadata,
|
|
161
|
+
expectedPlanId,
|
|
162
|
+
expectedRevisionNo,
|
|
159
163
|
]);
|
|
160
164
|
const row = safeParse(TeamDeductionRpcRowSchema, requireRow(rows, "TeamRepository.deductTeam"), "TeamRepository.deductTeam");
|
|
161
165
|
if (row.error_code === null &&
|
|
162
|
-
!new
|
|
166
|
+
!new PricingDecimal(row.amount).equals(quantizeMoney(new PricingDecimal(amount)))) {
|
|
163
167
|
throw new StoreError("TeamRepository.deductTeam: committed amount differs from the request", {
|
|
164
168
|
indeterminate: true,
|
|
165
169
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAU,CAAC;KAC7D,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AAC3D,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,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AAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAU,CAAC;KAC7D,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AA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C,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CACd,sBAAsB,EACtB;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,OAAO,EAAE,GAAG,CAAC,UAAU;YACvB,MAAM,EAAE,GAAG,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { PricingDecimal } from \"../../../pricing-decimal.js\";\nimport { 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\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n ((row.entry_id == null) !== new PricingDecimal(row.amount).isZero() ||\n row.team_balance_after === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require a matching entry and balance\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n expectedPlanId: string | null = null,\n expectedRevisionNo: number | null = null,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n expectedPlanId,\n expectedRevisionNo,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new PricingDecimal(row.amount).equals(quantizeMoney(new PricingDecimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
|
|
@@ -2,10 +2,10 @@ import { Decimal } from "decimal.js";
|
|
|
2
2
|
import { type BursarConfigData, type CatalogRollout } from "../../config.js";
|
|
3
3
|
import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
|
|
4
4
|
import type { JsonObject } from "../../shared/json.js";
|
|
5
|
-
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
|
|
6
|
-
import type { AddCreditsOptions,
|
|
5
|
+
import type { AccountCreatedInput, AccountCreatedResult, AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
|
|
6
|
+
import type { AddCreditsOptions, RefundCreditsOptions } from "../service-types.js";
|
|
7
7
|
import { CreditStore } from "../store.js";
|
|
8
|
-
import type { CreateLeaseOptions, CreateTeamOptions, SettleLeaseOptions } from "../store.js";
|
|
8
|
+
import type { CreateLeaseOptions, CreateTeamOptions, DeductTeamStoreOptions, SettleLeaseOptions } from "../store.js";
|
|
9
9
|
export type PgPool = PostgresPool;
|
|
10
10
|
export type PgPoolConstructor = PostgresPoolConstructor;
|
|
11
11
|
/** Construction options for the PostgreSQL credit store. */
|
|
@@ -21,29 +21,37 @@ export interface PostgresStoreOptions extends PostgresConnectionOptions {
|
|
|
21
21
|
usageBackend?: "postgres" | "clickhouse";
|
|
22
22
|
}
|
|
23
23
|
export declare class PostgresStore extends CreditStore {
|
|
24
|
+
getOperationReceipt(userId: string, key: string, kind: "charge" | "lease"): Promise<{
|
|
25
|
+
kind: "charge" | "lease";
|
|
26
|
+
receiptId: string;
|
|
27
|
+
operation: string;
|
|
28
|
+
requested: Decimal;
|
|
29
|
+
charged: Decimal | null;
|
|
30
|
+
allowanceAmount: Decimal;
|
|
31
|
+
status: string;
|
|
32
|
+
expiresAt: string | null;
|
|
33
|
+
ledgerEntryId: string | null;
|
|
34
|
+
usageChargeId: string | null;
|
|
35
|
+
} | null>;
|
|
36
|
+
readonly tenantId: string;
|
|
24
37
|
readonly providerEnvironment: NonNullable<PostgresConnectionOptions["providerEnvironment"]>;
|
|
25
38
|
private readonly postgres;
|
|
26
|
-
private
|
|
27
|
-
private
|
|
28
|
-
private
|
|
29
|
-
private
|
|
30
|
-
private
|
|
31
|
-
private
|
|
32
|
-
private
|
|
33
|
-
private
|
|
34
|
-
private get balanceRepo();
|
|
35
|
-
private get deductionRepo();
|
|
36
|
-
private get leaseRepo();
|
|
37
|
-
private get catalogRepo();
|
|
38
|
-
private get planRepo();
|
|
39
|
-
private get analyticsRepo();
|
|
40
|
-
private get teamRepo();
|
|
41
|
-
private get bucketRepo();
|
|
39
|
+
private readonly balanceRepo;
|
|
40
|
+
private readonly deductionRepo;
|
|
41
|
+
private readonly leaseRepo;
|
|
42
|
+
private readonly catalogRepo;
|
|
43
|
+
private readonly planRepo;
|
|
44
|
+
private readonly analyticsRepo;
|
|
45
|
+
private readonly teamRepo;
|
|
46
|
+
private readonly bucketRepo;
|
|
42
47
|
constructor(options: PostgresStoreOptions);
|
|
43
48
|
private query;
|
|
49
|
+
/** Check the same tenant-scoped connection used by financial operations. */
|
|
50
|
+
checkReachability(): Promise<void>;
|
|
44
51
|
withUsageBackend<T>(expected: "postgres" | "clickhouse", action: () => Promise<T>): Promise<T>;
|
|
45
52
|
close(): Promise<void>;
|
|
46
53
|
private static readonly RPC_NAME_RE;
|
|
54
|
+
private static readonly CURSOR_PROJECTIONS;
|
|
47
55
|
private static readonly SCALAR_RPC_NAMES;
|
|
48
56
|
private callproc;
|
|
49
57
|
getBalance(userId: string): Promise<BalanceResult>;
|
|
@@ -92,9 +100,10 @@ export declare class PostgresStore extends CreditStore {
|
|
|
92
100
|
addTeamMember(teamId: string, userId: string, role?: TeamRole, spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
|
|
93
101
|
getTeamMembers(teamId: string): Promise<TeamMember[]>;
|
|
94
102
|
removeTeamMember(teamId: string, userId: string): Promise<boolean>;
|
|
95
|
-
deductTeam(teamId: string, userId: string, amount: Decimal, options:
|
|
103
|
+
deductTeam(teamId: string, userId: string, amount: Decimal, options: DeductTeamStoreOptions): Promise<TeamDeductionResult>;
|
|
96
104
|
sweepExpiredCredits(dryRun?: boolean, userId?: string, limit?: number): Promise<SweepResult>;
|
|
97
105
|
getBucketBalances(userId: string): Promise<BucketBalancesResult>;
|
|
98
106
|
executeGrantProgram(request: ExecuteGrantProgramRequest): Promise<GrantProgramAwardResult[]>;
|
|
107
|
+
provisionAccount(input: AccountCreatedInput): Promise<AccountCreatedResult>;
|
|
99
108
|
}
|
|
100
109
|
//# sourceMappingURL=store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAUrC,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAGL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AAEzC,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