@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":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,qBAAqB,GAAG,CAAC;KAC5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AAM,IAAI,CAAC,KAAK,CAC3B,kEAAkE,EAClE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,IAAI,IAAI,CAAC,CAC/C,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,6BAA6B,CAAC,CAAC;IACtE,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresValue } from \"../../../shared/json.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst BillingEventRowSchema = z\n .object({\n status: z.enum([\n \"claimed\",\n \"duplicate\",\n \"busy\",\n \"invalid_request\",\n \"idempotency_conflict\",\n \"max_retries_exceeded\",\n ]),\n event_id: postgresUuid.nullable(),\n claim_token: postgresUuid.nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.status === \"claimed\") {\n if (row.event_id === null || row.claim_token === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"claimed billing event requires event_id and claim_token\",\n });\n }\n return;\n }\n if (row.claim_token !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"unclaimed billing event cannot expose a claim_token\",\n });\n }\n if (row.status === \"invalid_request\") {\n if (row.event_id !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"invalid billing event request cannot identify a stored event\",\n });\n }\n return;\n }\n if (row.event_id === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"stored billing event outcome requires event_id\",\n });\n }\n });\n\nexport type BillingEventRow = z.infer<typeof BillingEventRowSchema>;\n\nfunction booleanResult(rows: PostgresValue[], key: string, context: string): boolean {\n return requireResultField(rows, key, pgBoolean, context);\n}\n\n/** Repository for billing event lifecycle operations. */\nexport class BillingEventRepository {\n constructor(private query: QueryFn) {}\n\n /** Claim a billing event for processing (idempotent claim). */\n async claim(\n provider: string,\n eventId: string,\n eventType: string,\n metadata: string,\n ): Promise<BillingEventRow> {\n const rows = await this.query(\"SELECT * FROM bursar.claim_billing_event($1, $2, $3, $4)\", [\n provider,\n eventId,\n eventType,\n metadata,\n ]);\n const row = requireRecordRow(rows, \"BillingEventRepository.claim\");\n return safeParse(\n BillingEventRowSchema,\n { event_id: row.event_id, status: row.result, claim_token: row.claim_token },\n \"BillingEventRepository.claim\",\n { indeterminate: true },\n );\n }\n\n /** Mark a billing event as completed. */\n async complete(provider: string, eventId: string, claimToken: string): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.complete_billing_event($1, $2, $3::uuid) AS completed\",\n [provider, eventId, claimToken],\n );\n return booleanResult(rows, \"completed\", \"BillingEventRepository.complete\");\n }\n\n /** Mark a billing event as failed. */\n async fail(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n const rows = await this.query(\n \"SELECT bursar.fail_billing_event($1, $2, $3::uuid, $4) AS failed\",\n [provider, eventId, claimToken, error ?? null],\n );\n return booleanResult(rows, \"failed\", \"BillingEventRepository.fail\");\n }\n}\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { QueryFn } from "../../../shared/postgres-types.js";
|
|
2
|
+
import type { JsonObject } from "../../../shared/json.js";
|
|
2
3
|
import type { BillingInvoiceRecord } from "../../types/index.js";
|
|
3
4
|
export declare class BillingInvoiceRepository {
|
|
4
5
|
private query;
|
|
5
6
|
constructor(query: QueryFn);
|
|
6
7
|
listForUser(userId: string): Promise<BillingInvoiceRecord[]>;
|
|
7
|
-
upsert(subjectId: string, provider: string, providerInvoiceId: string, subscriptionId: string | null, status: "draft" | "open" | "paid" | "void" | "uncollectible", amountPaidMinor: number, amountDueMinor: number, currency: string, periodStart: string | null, periodEnd: string | null, metadata:
|
|
8
|
+
upsert(subjectId: string, provider: string, providerInvoiceId: string, subscriptionId: string | null, status: "draft" | "open" | "paid" | "void" | "uncollectible", amountPaidMinor: number, amountDueMinor: number, currency: string, periodStart: string | null, periodEnd: string | null, metadata: JsonObject, providerUpdatedAt: string): Promise<void>;
|
|
8
9
|
}
|
|
9
10
|
//# sourceMappingURL=invoice.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"invoice.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;IA8B5D,MAAM,CACV,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,eAAe,EAC5D,eAAe,EAAE,MAAM,EACvB,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,GAAG,IAAI,EAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,UAAU,EACpB,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC;CAoBjB"}
|
|
@@ -31,19 +31,15 @@ export class BillingInvoiceRepository {
|
|
|
31
31
|
async listForUser(userId) {
|
|
32
32
|
const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);
|
|
33
33
|
return rows.map((row) => {
|
|
34
|
-
if (typeof row !== "object" || row === null || Array.isArray(row)) {
|
|
35
|
-
throw new TypeError("BillingInvoiceRepository.listForUser expected an object row");
|
|
36
|
-
}
|
|
37
|
-
const raw = row;
|
|
38
34
|
const parsed = safeParse(InvoiceRowSchema, {
|
|
39
|
-
provider:
|
|
40
|
-
provider_invoice_id:
|
|
41
|
-
status:
|
|
42
|
-
amount_paid_minor:
|
|
43
|
-
amount_due_minor:
|
|
44
|
-
currency:
|
|
45
|
-
period_start:
|
|
46
|
-
period_end:
|
|
35
|
+
provider: row.provider,
|
|
36
|
+
provider_invoice_id: row.provider_invoice_id,
|
|
37
|
+
status: row.status,
|
|
38
|
+
amount_paid_minor: row.amount_paid_minor,
|
|
39
|
+
amount_due_minor: row.amount_due_minor,
|
|
40
|
+
currency: row.currency,
|
|
41
|
+
period_start: row.period_start,
|
|
42
|
+
period_end: row.period_end,
|
|
47
43
|
}, "BillingInvoiceRepository.listForUser");
|
|
48
44
|
return {
|
|
49
45
|
provider: parsed.provider,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"invoice.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/invoice.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EAC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gB,EAChB,iBAAyB,EACzB,cAA6B,EAC7B,MAA4D,EAC5D,eAAuB,EACvB,cAAsB,EACtB,QAAgB,EAChB,WAA0B,EAC1B,SAAwB,EACxB,QAAoB,EACpB,iBAAyB;QAEzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,kHAAkH,EAClH;YACE,SAAS;YACT,QAAQ;YACR,iBAAiB;YACjB,cAAc;YACd,MAAM;YACN,cAAc;YACd,eAAe;YACf,QAAQ;YACR,WAAW;YACX,SAAS;YACT,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;YACxB,iBAAiB;SAClB,CACF,CAAC;QACF,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE,iCAAiC,CAAC,CAAC;IAClF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject } from \"../../../shared/json.js\";\nimport type { BillingInvoiceRecord } from \"../../types/index.js\";\nimport {\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeMinorUnits = z\n .union([z.number().int().nonnegative().safe(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\nconst optionalTimestamp = z\n .union([\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n z.string().datetime({ offset: true }),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value))\n .nullable();\n\nconst InvoiceRowSchema = z\n .object({\n provider: z.string().min(1),\n provider_invoice_id: z.string().min(1),\n status: z.enum([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]),\n amount_paid_minor: safeMinorUnits,\n amount_due_minor: safeMinorUnits,\n currency: z.string().regex(/^[A-Z]{3}$/),\n period_start: optionalTimestamp,\n period_end: optionalTimestamp,\n })\n .strict();\n\nexport class BillingInvoiceRepository {\n constructor(private query: QueryFn) {}\n\n async listForUser(userId: string): Promise<BillingInvoiceRecord[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_invoices($1::uuid)`, [userId]);\n return rows.map((row) => {\n const parsed = safeParse(\n InvoiceRowSchema,\n {\n provider: row.provider,\n provider_invoice_id: row.provider_invoice_id,\n status: row.status,\n amount_paid_minor: row.amount_paid_minor,\n amount_due_minor: row.amount_due_minor,\n currency: row.currency,\n period_start: row.period_start,\n period_end: row.period_end,\n },\n \"BillingInvoiceRepository.listForUser\",\n );\n return {\n provider: parsed.provider,\n providerInvoiceId: parsed.provider_invoice_id,\n status: parsed.status,\n amountPaidMinor: parsed.amount_paid_minor,\n amountDueMinor: parsed.amount_due_minor,\n currency: parsed.currency,\n periodStart: parsed.period_start,\n periodEnd: parsed.period_end,\n } satisfies BillingInvoiceRecord;\n });\n }\n\n async upsert(\n subjectId: string,\n provider: string,\n providerInvoiceId: string,\n subscriptionId: string | null,\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\",\n amountPaidMinor: number,\n amountDueMinor: number,\n currency: string,\n periodStart: string | null,\n periodEnd: string | null,\n metadata: JsonObject,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_invoice($1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::jsonb, $12) AS id`,\n [\n subjectId,\n provider,\n providerInvoiceId,\n subscriptionId,\n status,\n amountDueMinor,\n amountPaidMinor,\n currency,\n periodStart,\n periodEnd,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingInvoiceRepository.upsert\");\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"offer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAgDjE,UAAU,mBAAmB;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5C,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,eAAe,GAAG,mBAAmB,GAC/C,CACI;IACE,YAAY,EAAE,IAAI,CAAC;IACnB,WAAW,EAAE,IAAI,CAAC;IAClB,iBAAiB,EAAE,KAAK,CAAC;CAC1B,GACD;IACE,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CACJ,CAAC;AAEJ,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAK5B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;YAI7E,OAAO;CAuGtB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { StoreError } from "../../../errors.js";
|
|
4
4
|
import { postgresUuid, safeParse, unwrapJsonb } from "../../../shared/postgres-validation.js";
|
|
@@ -92,6 +92,11 @@ export class BillingOfferRepository {
|
|
|
92
92
|
});
|
|
93
93
|
}
|
|
94
94
|
const rawContext = contextRows[0];
|
|
95
|
+
if (rawContext === undefined) {
|
|
96
|
+
throw new StoreError("BillingOfferRepository: catalog plan context is missing", {
|
|
97
|
+
details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
95
100
|
const offerContext = safeParse(OfferContextRowSchema, {
|
|
96
101
|
offer_key: rawContext.offer_key,
|
|
97
102
|
plan_id: rawContext.plan_id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAC;AAE9F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;KACtD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,oCAAoC,CAAC,CAAC;AAE5F,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,mBAAmB,EAAE,YAAY;IACjC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,G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;gBAC/E,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QACD,OAAO;YACL,GAAG,aAAa;YAChB,YAAY,EAAE,KAAK,CAAC,kBAAkB;YACtC,WAAW,EAAE,KAAK,CAAC,sBAAsB;YACzC,iBAAiB,EAAE,KAAK,CAAC,mBAAmB,KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0] as Record<string, unknown>;\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAA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KAAK,kBAAkB;SACpE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, safeParse, unwrapJsonb } from \"../../../shared/postgres-validation.js\";\n\nconst PositiveDecimalSchema = z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && value.gt(0), \"expected a finite positive decimal\");\n\nconst CatalogOfferRowSchema = z\n .object({\n id: postgresUuid,\n catalog_revision_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n cycle_grant_amount: PositiveDecimalSchema.nullable(),\n cycle_grant_bucket_key: z.string().min(1).nullable(),\n cycle_grant_renewal: z.enum([\"replace_previous\", \"accumulate\"]).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const grantFields = [\n row.cycle_grant_amount,\n row.cycle_grant_bucket_key,\n row.cycle_grant_renewal,\n ];\n if (\n grantFields.some((value) => value !== null) &&\n grantFields.some((value) => value === null)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cycle grant fields must either all be set or all be null\",\n });\n }\n });\n\nconst OfferContextRowSchema = z\n .object({\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ninterface BillingOfferRowBase {\n id: string;\n planId: string;\n offerKey: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n}\n\nexport type BillingOfferRow = BillingOfferRowBase &\n (\n | {\n grantCredits: null;\n grantBucket: null;\n grantReplacePrior: false;\n }\n | {\n grantCredits: Decimal;\n grantBucket: string;\n grantReplacePrior: boolean;\n }\n );\n\n/** Repository for billing offer resolution. */\nexport class BillingOfferRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingOfferRow | null> {\n const lookupType = priceId !== null ? \"price_id\" : \"product_id\";\n return this.resolve(provider, lookupType, priceId ?? productId, \"resolveByPrice\");\n }\n\n async resolveByLookup(provider: string, lookupKey: string): Promise<BillingOfferRow | null> {\n return this.resolve(provider, \"external_id\", lookupKey, \"resolveByLookup\");\n }\n\n private async resolve(\n provider: string,\n lookupType: \"price_id\" | \"product_id\" | \"external_id\",\n lookupValue: string | null,\n operation: string,\n ): Promise<BillingOfferRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingOfferRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_offer($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one offer`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n const offer = safeParse(\n CatalogOfferRowSchema,\n {\n id: raw.id,\n catalog_revision_id: raw.catalog_revision_id,\n offer_key: raw.offer_key,\n plan_key: raw.plan_key,\n billing_unit: raw.billing_unit,\n billing_count: raw.billing_count,\n cycle_grant_amount: raw.cycle_grant_amount,\n cycle_grant_bucket_key: raw.cycle_grant_bucket_key,\n cycle_grant_renewal: raw.cycle_grant_renewal,\n },\n context,\n );\n\n const contextRows = await this.query(\n \"SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)\",\n [offer.id, offer.catalog_revision_id],\n );\n if (contextRows.length !== 1) {\n throw new StoreError(`${context}: catalog plan context is missing`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const rawContext = contextRows[0];\n if (rawContext === undefined) {\n throw new StoreError(\"BillingOfferRepository: catalog plan context is missing\", {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n const offerContext = safeParse(\n OfferContextRowSchema,\n {\n offer_key: rawContext.offer_key,\n plan_id: rawContext.plan_id,\n plan_key: rawContext.plan_key,\n billing_unit: rawContext.billing_unit,\n billing_count: rawContext.billing_count,\n },\n `${context}.context`,\n );\n if (\n offerContext.offer_key !== offer.offer_key ||\n offerContext.plan_key !== offer.plan_key ||\n offerContext.billing_unit !== offer.billing_unit ||\n offerContext.billing_count !== offer.billing_count\n ) {\n throw new StoreError(`${context}: catalog plan context does not match the resolved offer`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n\n const resolvedOffer: BillingOfferRowBase = {\n id: offer.id,\n planId: offerContext.plan_id,\n offerKey: offer.offer_key,\n plan: offer.plan_key,\n interval: offer.billing_unit,\n intervalCount: offer.billing_count,\n };\n if (offer.cycle_grant_amount === null) {\n return {\n ...resolvedOffer,\n grantCredits: null,\n grantBucket: null,\n grantReplacePrior: false,\n };\n }\n if (offer.cycle_grant_bucket_key === null || offer.cycle_grant_renewal === null) {\n throw new StoreError(`${context}: resolved offer has an incomplete cycle grant`, {\n details: { offerId: offer.id, catalogRevisionId: offer.catalog_revision_id },\n });\n }\n return {\n ...resolvedOffer,\n grantCredits: offer.cycle_grant_amount,\n grantBucket: offer.cycle_grant_bucket_key,\n grantReplacePrior: offer.cycle_grant_renewal === \"replace_previous\",\n };\n }\n}\n"]}
|
|
@@ -20,7 +20,7 @@ declare const BillingPaymentRowSchema: z.ZodObject<{
|
|
|
20
20
|
canceled: "canceled";
|
|
21
21
|
}>;
|
|
22
22
|
provider_updated_at: z.ZodUnion<readonly [z.ZodString, z.ZodDate]>;
|
|
23
|
-
metadata: z.ZodRecord<z.ZodString, z.
|
|
23
|
+
metadata: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
|
|
24
24
|
}, z.core.$strict>;
|
|
25
25
|
export type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;
|
|
26
26
|
export type ForRefundRow = BillingPaymentRow;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"payment.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAcjE,QAAA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;kBAelB,CAAC;AACZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,iBAAiB,CAAC;AAuB7C,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAC5B,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,iBAAiB,EAAE,MAAM,GAAG,IAAI,EAChC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,cAAc,GAAG,cAAc,EACxC,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,MAAM,EAAE,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,UAAU,EACvD,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,MAAM,CAAC;IAyBZ,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAQvF,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;CAQhG"}
|
|
@@ -17,7 +17,7 @@ const BillingPaymentRowSchema = z
|
|
|
17
17
|
purpose: z.enum(["subscription", "credit_topup"]),
|
|
18
18
|
status: z.enum(["pending", "succeeded", "failed", "canceled"]),
|
|
19
19
|
provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),
|
|
20
|
-
metadata: z.record(z.string(), z.
|
|
20
|
+
metadata: z.record(z.string(), z.json()),
|
|
21
21
|
})
|
|
22
22
|
.strict();
|
|
23
23
|
function parsePaymentRow(row, context) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/payment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC;IACrC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE;CACtC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;IACN,EAAE,EAAE,YAAY;IAChB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,mBAAmB,EAAE,CAAC,CAAC,MAAM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CAAC;IAC7F,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,QAAgB,EAAE,iBAAyB;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,6DAA6D,EAAE;YAC3F,QAAQ;YACR,iBAAiB;SAClB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,EAAE,oCAAoC,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst PgSafeMinorUnitsSchema = z.union([\n z.string().regex(/^\\d+$/),\n z.number().int().nonnegative().safe(),\n]);\n\nconst BillingPaymentRowSchema = z\n .object({\n id: postgresUuid,\n provider: z.string().min(1),\n provider_payment_id: z.string().min(1),\n provider_invoice_id: z.string().nullable(),\n subject_id: postgresUuid,\n amount_minor: PgSafeMinorUnitsSchema,\n tax_minor: PgSafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n purpose: z.enum([\"subscription\", \"credit_topup\"]),\n status: z.enum([\"pending\", \"succeeded\", \"failed\", \"canceled\"]),\n provider_updated_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nexport type BillingPaymentRow = z.infer<typeof BillingPaymentRowSchema>;\nexport type ForRefundRow = BillingPaymentRow;\n\nfunction parsePaymentRow(row: PostgresRow, context: string): BillingPaymentRow {\n return safeParse(\n BillingPaymentRowSchema,\n {\n id: row.id,\n provider: row.provider,\n provider_payment_id: row.provider_payment_id,\n provider_invoice_id: row.provider_invoice_id,\n subject_id: row.subject_id,\n amount_minor: row.amount_minor,\n tax_minor: row.tax_minor,\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n provider_updated_at: row.provider_updated_at,\n metadata: row.metadata,\n },\n context,\n );\n}\n\nexport class BillingPaymentRepository {\n constructor(private query: QueryFn) {}\n async upsert(\n provider: string,\n providerPaymentId: string,\n providerInvoiceId: string | null,\n userId: string,\n amountMinor: number,\n taxMinor: number,\n currency: string,\n purpose: \"subscription\" | \"credit_topup\",\n metadata: string | null,\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\",\n providerUpdatedAt: string,\n ): Promise<string> {\n if (!userId) throw new TypeError(\"billing payment requires a subject\");\n if (purpose !== \"subscription\" && purpose !== \"credit_topup\") {\n throw new TypeError(\"billing payment requires a known purpose\");\n }\n const rows = await this.query(\n `SELECT bursar.upsert_billing_payment(\n $1::uuid,$2,$3,$4,$5,$6,$7,$8::bursar.billing_payment_status,$9,$10,$11::jsonb\n ) AS id`,\n [\n userId,\n provider,\n providerPaymentId,\n amountMinor,\n taxMinor,\n currency,\n purpose,\n status,\n providerUpdatedAt,\n providerInvoiceId,\n metadata ?? \"{}\",\n ],\n );\n return requireResultField(rows, \"id\", postgresUuid, \"BillingPaymentRepository.upsert\");\n }\n async getForRefund(provider: string, providerPaymentId: string): Promise<ForRefundRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getForRefund\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getForRefund\");\n }\n async getDirect(provider: string, providerPaymentId: string): Promise<BillingPaymentRow | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_payment_by_provider($1,$2)\", [\n provider,\n providerPaymentId,\n ]);\n const row = optionalRecordRow(rows, \"BillingPaymentRepository.getDirect\");\n return row === null ? null : parsePaymentRow(row, \"BillingPaymentRepository.getDirect\");\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"subscription-change.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EACV,yBAAyB,EACzB,8BAA8B,EAE/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AA4HjE,uEAAuE;AACvE,qBAAa,mCAAmC;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAErC,MAAM,CACV,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,8BAA8B,GACpC,OAAO,CAAC,yBAAyB,CAAC;IAuC/B,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQ9D,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,sBAAsB,EAAE,MAAM,GAC7B,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAQtC,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC;YAoBlE,aAAa;YAyBb,gBAAgB;CA6C/B"}
|
|
@@ -206,15 +206,7 @@ export class BillingSubscriptionChangeRepository {
|
|
|
206
206
|
details: { subscriptionChangeId: row.id, rowCount: rows.length },
|
|
207
207
|
});
|
|
208
208
|
}
|
|
209
|
-
const parsed = rows.map((candidate,
|
|
210
|
-
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
|
|
211
|
-
throw new StoreError(`${context}: malformed subscription-change offer context`, {
|
|
212
|
-
details: { subscriptionChangeId: row.id, index },
|
|
213
|
-
});
|
|
214
|
-
}
|
|
215
|
-
const record = candidate;
|
|
216
|
-
return safeParse(OfferContextRowSchema, projectContext(record), `${context}.context`);
|
|
217
|
-
});
|
|
209
|
+
const parsed = rows.map((candidate) => safeParse(OfferContextRowSchema, projectContext(candidate), `${context}.context`));
|
|
218
210
|
const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));
|
|
219
211
|
const from = bySide.get("from");
|
|
220
212
|
const to = bySide.get("to");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription-change.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAElF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;CAC3D,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC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a,IAAI,EAAE,CAAC,QAAQ,KAAK,GAAG,CAAC,WAAW,EAAE,CAAC;YAC3E,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,oDAAoD,EAAE;gBACnF,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IACtB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { BillingSubscriptionChangeUpdate } from \"../../contracts.js\";\nimport type {\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionOfferContext,\n} from \"../../types/index.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = z\n .union([\n z.string().datetime({ offset: true }),\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value));\nconst positiveBigint = z\n .union([z.string().regex(/^[1-9]\\d*$/), z.number().int().positive().safe()])\n .transform(String);\nconst changeState = z.enum([\"awaiting_payment\", \"scheduled\", \"applied\", \"failed\", \"canceled\"]);\nconst effectiveBehavior = z.enum([\"immediate\", \"renewal\"]);\nconst prorationBehavior = z.enum([\"provider_default\", \"invoice_immediately\", \"none\"]);\n\nconst OpenChangeResultSchema = z\n .object({\n change_id: positiveBigint.nullable(),\n state: changeState.nullable(),\n error_code: z\n .enum([\n \"invalid_request\",\n \"missing_subscription\",\n \"invalid_target_offer\",\n \"idempotency_conflict\",\n \"open_change_exists\",\n ])\n .nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const succeeded = row.error_code === null;\n if (succeeded !== (row.change_id !== null && row.state !== null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"subscription-change result has inconsistent success fields\",\n });\n }\n });\n\nconst ChangeRowSchema = z\n .object({\n id: positiveBigint,\n subscription_id: postgresUuid,\n from_offer_id: postgresUuid,\n from_catalog_revision_id: postgresUuid,\n to_offer_id: postgresUuid,\n to_catalog_revision_id: postgresUuid,\n effective_at: timestamp.nullable(),\n effective_behavior: effectiveBehavior,\n state: changeState,\n proration_behavior: prorationBehavior,\n idempotency_key: z.string().min(1),\n provider_operation_id: z.string().min(1).nullable(),\n error_message: z.string().min(1).max(8192).nullable(),\n })\n .strict();\n\ntype ChangeRow = z.infer<typeof ChangeRowSchema>;\n\nconst OfferContextRowSchema = z\n .object({\n side: z.enum([\"from\", \"to\"]),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ntype OfferContextRow = z.infer<typeof OfferContextRowSchema>;\n\nfunction projectChange(row: Record<string, unknown>): Record<string, unknown> {\n return {\n id: row.id,\n subscription_id: row.subscription_id,\n from_offer_id: row.from_offer_id,\n from_catalog_revision_id: row.from_catalog_revision_id,\n to_offer_id: row.to_offer_id,\n to_catalog_revision_id: row.to_catalog_revision_id,\n effective_at: row.effective_at,\n effective_behavior: row.effective_behavior,\n state: row.state,\n proration_behavior: row.proration_behavior,\n idempotency_key: row.idempotency_key,\n provider_operation_id: row.provider_operation_id,\n error_message: row.error_message,\n };\n}\n\nfunction projectContext(row: Record<string, unknown>): Record<string, unknown> {\n return {\n side: row.side,\n offer_id: row.offer_id,\n offer_key: row.offer_key,\n plan_id: row.plan_id,\n plan_key: row.plan_key,\n billing_unit: row.billing_unit,\n billing_count: row.billing_count,\n };\n}\n\nfunction publicContext(row: OfferContextRow): BillingSubscriptionOfferContext {\n return {\n offerId: row.offer_id,\n offerKey: row.offer_key,\n planId: row.plan_id,\n plan: row.plan_key,\n interval: row.billing_unit,\n intervalCount: row.billing_count,\n };\n}\n\n/** Persistence boundary for durable subscription offer transitions. */\nexport class BillingSubscriptionChangeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async create(\n subscriptionId: string,\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const rows = await this.query(\n `SELECT * FROM bursar.open_subscription_change(\n $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6\n )`,\n [\n subscriptionId,\n input.toOfferId,\n input.effectiveAt,\n input.effective,\n input.idempotencyKey,\n input.prorationBehavior ?? \"provider_default\",\n ],\n );\n const raw = requireRecordRow(rows, \"BillingSubscriptionChangeRepository.create\");\n const result = safeParse(\n OpenChangeResultSchema,\n { change_id: raw.change_id, state: raw.state, error_code: raw.error_code },\n \"BillingSubscriptionChangeRepository.create\",\n { indeterminate: true },\n );\n if (result.error_code !== null) {\n throw new StoreError(`subscription change rejected: ${result.error_code}`, {\n details: { errorCode: result.error_code },\n });\n }\n if (result.change_id === null) {\n throw new StoreError(\"subscription change returned no identifier\", { indeterminate: true });\n }\n const change = await this.getById(result.change_id);\n if (change === null) {\n throw new StoreError(\"subscription change could not be read after creation\", {\n indeterminate: true,\n details: { subscriptionChangeId: result.change_id },\n });\n }\n return change;\n }\n\n async getById(id: string): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_billing_subscription_change($1::bigint)\",\n [id],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getById\");\n }\n\n async getOpen(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)\",\n [provider, providerSubscriptionId],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getOpen\");\n }\n\n async update(id: string, update: BillingSubscriptionChangeUpdate): Promise<void> {\n if (update.state === undefined) return;\n const rows = await this.query(\n \"SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced\",\n [\n id,\n update.state,\n update.providerOperationId ?? null,\n optionalBoundedDiagnosticMessage(update.errorMessage),\n ],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"BillingSubscriptionChangeRepository.update\")\n ) {\n throw new StoreError(`subscription change transition rejected: ${id}`, {\n details: { subscriptionChangeId: id },\n });\n }\n }\n\n private async parseOptional(\n rows: readonly unknown[],\n context: string,\n ): Promise<BillingSubscriptionChange | null> {\n const raw = optionalRecordRow(rows, context);\n if (raw === null) return null;\n const row = safeParse(ChangeRowSchema, projectChange(raw), context);\n const contexts = await this.getOfferContexts(row, context);\n return {\n id: row.id,\n subscriptionId: row.subscription_id,\n fromOfferId: row.from_offer_id,\n toOfferId: row.to_offer_id,\n fromOffer: publicContext(contexts.from),\n toOffer: publicContext(contexts.to),\n effectiveAt: row.effective_at,\n effective: row.effective_behavior,\n state: row.state,\n prorationBehavior: row.proration_behavior,\n idempotencyKey: row.idempotency_key,\n providerOperationId: row.provider_operation_id,\n errorMessage: row.error_message,\n };\n }\n\n private async getOfferContexts(\n row: ChangeRow,\n context: string,\n ): Promise<{ from: OfferContextRow; to: OfferContextRow }> {\n const rows = await this.query(\n `SELECT requested.side, requested.offer_id, offer_context.*\n FROM (\n VALUES\n ('from', $1::uuid, $2::uuid),\n ('to', $3::uuid, $4::uuid)\n ) AS requested(side, offer_id, catalog_revision_id)\n CROSS JOIN LATERAL bursar.get_catalog_offer_context(\n requested.offer_id,\n requested.catalog_revision_id\n ) AS offer_context`,\n [\n row.from_offer_id,\n row.from_catalog_revision_id,\n row.to_offer_id,\n row.to_catalog_revision_id,\n ],\n );\n if (rows.length !== 2) {\n throw new StoreError(`${context}: expected both subscription-change offer contexts`, {\n details: { subscriptionChangeId: row.id, rowCount: rows.length },\n });\n }\n const parsed = rows.map((candidate, index) => {\n if (typeof candidate !== \"object\" || candidate === null || Array.isArray(candidate)) {\n throw new StoreError(`${context}: malformed subscription-change offer context`, {\n details: { subscriptionChangeId: row.id, index },\n });\n }\n const record = candidate as Record<string, unknown>;\n return safeParse(OfferContextRowSchema, projectContext(record), `${context}.context`);\n });\n const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));\n const from = bySide.get(\"from\");\n const to = bySide.get(\"to\");\n if (bySide.size !== 2 || from === undefined || to === undefined) {\n throw new StoreError(`${context}: duplicate or missing subscription-change offer context`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n if (from.offer_id !== row.from_offer_id || to.offer_id !== row.to_offer_id) {\n throw new StoreError(`${context}: subscription-change offer context does not match`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n return { from, to };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subscription-change.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAGlF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;CAC3D,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,C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CAAC,MAAM,EAAE;aACjE,CAAC,CAAC;QACL,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CACpC,SAAS,CAAC,qBAAqB,EAAE,cAAc,CAAC,SAAS,CAAC,EAAE,GAAG,OAAO,UAAU,CAAC,CAClF,CAAC;QACF,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;QAC/E,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAChC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;YAChE,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,0DAA0D,EAAE;gBACzF,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,KAAK,GAAG,CAAC,aAAa,IAAI,EAAE,CAAC,QAAQ,KAAK,GAAG,CAAC,WAAW,EAAE,CAAC;YAC3E,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,oDAAoD,EAAE;gBACnF,OAAO,EAAE,EAAE,oBAAoB,EAAE,GAAG,CAAC,EAAE,EAAE;aAC1C,CAAC,CAAC;QACL,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IACtB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { BillingSubscriptionChangeUpdate } from \"../../contracts.js\";\nimport type {\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionOfferContext,\n} from \"../../types/index.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { PostgresRow } from \"../../../shared/json.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = z\n .union([\n z.string().datetime({ offset: true }),\n z.date().refine((value) => !Number.isNaN(value.getTime())),\n ])\n .transform((value) => (value instanceof Date ? value.toISOString() : value));\nconst positiveBigint = z\n .union([z.string().regex(/^[1-9]\\d*$/), z.number().int().positive().safe()])\n .transform(String);\nconst changeState = z.enum([\"awaiting_payment\", \"scheduled\", \"applied\", \"failed\", \"canceled\"]);\nconst effectiveBehavior = z.enum([\"immediate\", \"renewal\"]);\nconst prorationBehavior = z.enum([\"provider_default\", \"invoice_immediately\", \"none\"]);\n\nconst OpenChangeResultSchema = z\n .object({\n change_id: positiveBigint.nullable(),\n state: changeState.nullable(),\n error_code: z\n .enum([\n \"invalid_request\",\n \"missing_subscription\",\n \"invalid_target_offer\",\n \"idempotency_conflict\",\n \"open_change_exists\",\n ])\n .nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n const succeeded = row.error_code === null;\n if (succeeded !== (row.change_id !== null && row.state !== null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"subscription-change result has inconsistent success fields\",\n });\n }\n });\n\nconst ChangeRowSchema = z\n .object({\n id: positiveBigint,\n subscription_id: postgresUuid,\n from_offer_id: postgresUuid,\n from_catalog_revision_id: postgresUuid,\n to_offer_id: postgresUuid,\n to_catalog_revision_id: postgresUuid,\n effective_at: timestamp.nullable(),\n effective_behavior: effectiveBehavior,\n state: changeState,\n proration_behavior: prorationBehavior,\n idempotency_key: z.string().min(1),\n provider_operation_id: z.string().min(1).nullable(),\n error_message: z.string().min(1).max(8192).nullable(),\n })\n .strict();\n\ntype ChangeRow = z.infer<typeof ChangeRowSchema>;\n\nconst OfferContextRowSchema = z\n .object({\n side: z.enum([\"from\", \"to\"]),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n billing_unit: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n billing_count: z.number().int().positive(),\n })\n .strict();\n\ntype OfferContextRow = z.infer<typeof OfferContextRowSchema>;\n\nfunction projectChange(row: PostgresRow) {\n return {\n id: row.id,\n subscription_id: row.subscription_id,\n from_offer_id: row.from_offer_id,\n from_catalog_revision_id: row.from_catalog_revision_id,\n to_offer_id: row.to_offer_id,\n to_catalog_revision_id: row.to_catalog_revision_id,\n effective_at: row.effective_at,\n effective_behavior: row.effective_behavior,\n state: row.state,\n proration_behavior: row.proration_behavior,\n idempotency_key: row.idempotency_key,\n provider_operation_id: row.provider_operation_id,\n error_message: row.error_message,\n };\n}\n\nfunction projectContext(row: PostgresRow) {\n return {\n side: row.side,\n offer_id: row.offer_id,\n offer_key: row.offer_key,\n plan_id: row.plan_id,\n plan_key: row.plan_key,\n billing_unit: row.billing_unit,\n billing_count: row.billing_count,\n };\n}\n\nfunction publicContext(row: OfferContextRow): BillingSubscriptionOfferContext {\n return {\n offerId: row.offer_id,\n offerKey: row.offer_key,\n planId: row.plan_id,\n plan: row.plan_key,\n interval: row.billing_unit,\n intervalCount: row.billing_count,\n };\n}\n\n/** Persistence boundary for durable subscription offer transitions. */\nexport class BillingSubscriptionChangeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async create(\n subscriptionId: string,\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const rows = await this.query(\n `SELECT * FROM bursar.open_subscription_change(\n $1::uuid, $2::uuid, $3::timestamptz, $4, $5, $6\n )`,\n [\n subscriptionId,\n input.toOfferId,\n input.effectiveAt,\n input.effective,\n input.idempotencyKey,\n input.prorationBehavior ?? \"provider_default\",\n ],\n );\n const raw = requireRecordRow(rows, \"BillingSubscriptionChangeRepository.create\");\n const result = safeParse(\n OpenChangeResultSchema,\n { change_id: raw.change_id, state: raw.state, error_code: raw.error_code },\n \"BillingSubscriptionChangeRepository.create\",\n { indeterminate: true },\n );\n if (result.error_code !== null) {\n throw new StoreError(`subscription change rejected: ${result.error_code}`, {\n details: { errorCode: result.error_code },\n });\n }\n if (result.change_id === null) {\n throw new StoreError(\"subscription change returned no identifier\", { indeterminate: true });\n }\n const change = await this.getById(result.change_id);\n if (change === null) {\n throw new StoreError(\"subscription change could not be read after creation\", {\n indeterminate: true,\n details: { subscriptionChangeId: result.change_id },\n });\n }\n return change;\n }\n\n async getById(id: string): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_billing_subscription_change($1::bigint)\",\n [id],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getById\");\n }\n\n async getOpen(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.get_open_billing_subscription_change($1, $2)\",\n [provider, providerSubscriptionId],\n );\n return this.parseOptional(rows, \"BillingSubscriptionChangeRepository.getOpen\");\n }\n\n async update(id: string, update: BillingSubscriptionChangeUpdate): Promise<void> {\n if (update.state === undefined) return;\n const rows = await this.query(\n \"SELECT bursar.advance_subscription_change($1::bigint, $2, $3, $4) AS advanced\",\n [\n id,\n update.state,\n update.providerOperationId ?? null,\n optionalBoundedDiagnosticMessage(update.errorMessage),\n ],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"BillingSubscriptionChangeRepository.update\")\n ) {\n throw new StoreError(`subscription change transition rejected: ${id}`, {\n details: { subscriptionChangeId: id },\n });\n }\n }\n\n private async parseOptional(\n rows: readonly PostgresRow[],\n context: string,\n ): Promise<BillingSubscriptionChange | null> {\n const raw = optionalRecordRow(rows, context);\n if (raw === null) return null;\n const row = safeParse(ChangeRowSchema, projectChange(raw), context);\n const contexts = await this.getOfferContexts(row, context);\n return {\n id: row.id,\n subscriptionId: row.subscription_id,\n fromOfferId: row.from_offer_id,\n toOfferId: row.to_offer_id,\n fromOffer: publicContext(contexts.from),\n toOffer: publicContext(contexts.to),\n effectiveAt: row.effective_at,\n effective: row.effective_behavior,\n state: row.state,\n prorationBehavior: row.proration_behavior,\n idempotencyKey: row.idempotency_key,\n providerOperationId: row.provider_operation_id,\n errorMessage: row.error_message,\n };\n }\n\n private async getOfferContexts(\n row: ChangeRow,\n context: string,\n ): Promise<{ from: OfferContextRow; to: OfferContextRow }> {\n const rows = await this.query(\n `SELECT requested.side, requested.offer_id, offer_context.*\n FROM (\n VALUES\n ('from', $1::uuid, $2::uuid),\n ('to', $3::uuid, $4::uuid)\n ) AS requested(side, offer_id, catalog_revision_id)\n CROSS JOIN LATERAL bursar.get_catalog_offer_context(\n requested.offer_id,\n requested.catalog_revision_id\n ) AS offer_context`,\n [\n row.from_offer_id,\n row.from_catalog_revision_id,\n row.to_offer_id,\n row.to_catalog_revision_id,\n ],\n );\n if (rows.length !== 2) {\n throw new StoreError(`${context}: expected both subscription-change offer contexts`, {\n details: { subscriptionChangeId: row.id, rowCount: rows.length },\n });\n }\n const parsed = rows.map((candidate) =>\n safeParse(OfferContextRowSchema, projectContext(candidate), `${context}.context`),\n );\n const bySide = new Map(parsed.map((candidate) => [candidate.side, candidate]));\n const from = bySide.get(\"from\");\n const to = bySide.get(\"to\");\n if (bySide.size !== 2 || from === undefined || to === undefined) {\n throw new StoreError(`${context}: duplicate or missing subscription-change offer context`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n if (from.offer_id !== row.from_offer_id || to.offer_id !== row.to_offer_id) {\n throw new StoreError(`${context}: subscription-change offer context does not match`, {\n details: { subscriptionChangeId: row.id },\n });\n }\n return { from, to };\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import type { BillingSubscriptionState } from "../../types/subscriptions.js";
|
|
2
|
+
import type { BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome } from "../../types/subscriptions.js";
|
|
3
3
|
import type { QueryFn } from "../../../shared/postgres-types.js";
|
|
4
|
+
import type { JsonObject } from "../../../shared/json.js";
|
|
4
5
|
declare const SubscriptionRowSchema: z.ZodObject<{
|
|
5
6
|
id: z.ZodString;
|
|
6
7
|
user_id: z.ZodString;
|
|
@@ -38,7 +39,7 @@ declare const SubscriptionRowSchema: z.ZodObject<{
|
|
|
38
39
|
year: "year";
|
|
39
40
|
}>;
|
|
40
41
|
interval_count: z.ZodNumber;
|
|
41
|
-
metadata: z.ZodRecord<z.ZodString, z.
|
|
42
|
+
metadata: z.ZodRecord<z.ZodString, z.ZodJSONSchema>;
|
|
42
43
|
}, z.core.$strict>;
|
|
43
44
|
export type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;
|
|
44
45
|
export declare class BillingSubscriptionRepository {
|
|
@@ -51,17 +52,16 @@ export declare class BillingSubscriptionRepository {
|
|
|
51
52
|
getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null>;
|
|
52
53
|
getUserSubscriptions(userId: string): Promise<SubscriptionRow[]>;
|
|
53
54
|
listExpiredGraceSubscriptions(now: string, limit?: number): Promise<SubscriptionRow[]>;
|
|
54
|
-
|
|
55
|
+
reconcileEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, terminalPlanKey: string | null, reason: string): Promise<SubscriptionEntitlementOutcome>;
|
|
56
|
+
expireGracePeriod(subjectId: string, subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string, terminalPlanKey: string | null): Promise<boolean>;
|
|
55
57
|
recordConflict(input: {
|
|
56
58
|
userId?: string | null;
|
|
57
59
|
provider: string;
|
|
58
60
|
duplicateSubscriptionId: string;
|
|
59
61
|
existingSubscriptionId?: string | null;
|
|
60
62
|
eventId?: string | null;
|
|
61
|
-
metadata?:
|
|
63
|
+
metadata?: JsonObject;
|
|
62
64
|
}): Promise<string>;
|
|
63
|
-
/** Select a provider subscription without modifying provider-reported state. */
|
|
64
|
-
selectEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
|
|
65
65
|
}
|
|
66
66
|
export {};
|
|
67
67
|
//# sourceMappingURL=subscription.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"subscription.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AAkEvE,QAAA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAyBhB,CAAC;AAEZ,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAyCpE,qBAAa,6BAA6B;IAC5B,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,OAAO;IAE5B,MAAM,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;IA+E5D,OAAO,CAAC,GAAG;YAgCG,gBAAgB;IA4CxB,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,sBAAsB,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IActF,mBAAmB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z.enum(["applied", "revoked", "preserved", "stale"]);
|
|
21
22
|
const PersistedSubscriptionRowSchema = z
|
|
22
23
|
.object({
|
|
23
24
|
id: postgresUuid,
|
|
@@ -37,7 +38,7 @@ const PersistedSubscriptionRowSchema = z
|
|
|
37
38
|
grace_expired_at: timestamp.nullable(),
|
|
38
39
|
provider_updated_at: timestamp,
|
|
39
40
|
cancel_at_period_end: pgBoolean,
|
|
40
|
-
metadata: z.record(z.string(), z.
|
|
41
|
+
metadata: z.record(z.string(), z.json()),
|
|
41
42
|
})
|
|
42
43
|
.strict();
|
|
43
44
|
const CatalogReferenceSchema = z
|
|
@@ -78,14 +79,11 @@ const SubscriptionRowSchema = z
|
|
|
78
79
|
cancel_at_period_end: pgBoolean,
|
|
79
80
|
interval: z.enum(["day", "week", "month", "year"]),
|
|
80
81
|
interval_count: z.number().int().positive(),
|
|
81
|
-
metadata: z.record(z.string(), z.
|
|
82
|
+
metadata: z.record(z.string(), z.json()),
|
|
82
83
|
})
|
|
83
84
|
.strict();
|
|
84
|
-
function record(value, context) {
|
|
85
|
-
return safeParse(z.record(z.string(), z.unknown()), value, context);
|
|
86
|
-
}
|
|
87
85
|
function persistedSubscription(row, context) {
|
|
88
|
-
const value =
|
|
86
|
+
const value = row;
|
|
89
87
|
return safeParse(PersistedSubscriptionRowSchema, {
|
|
90
88
|
id: value.id,
|
|
91
89
|
subject_id: value.subject_id,
|
|
@@ -165,7 +163,7 @@ export class BillingSubscriptionRepository {
|
|
|
165
163
|
requireResultField(rows, "id", postgresUuid, "BillingSubscriptionRepository.upsert");
|
|
166
164
|
}
|
|
167
165
|
map(row) {
|
|
168
|
-
const r =
|
|
166
|
+
const r = row;
|
|
169
167
|
return safeParse(SubscriptionRowSchema, {
|
|
170
168
|
id: r.id,
|
|
171
169
|
user_id: r.subject_id,
|
|
@@ -254,9 +252,30 @@ export class BillingSubscriptionRepository {
|
|
|
254
252
|
const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));
|
|
255
253
|
return enriched.map((row) => this.map(row));
|
|
256
254
|
}
|
|
257
|
-
async
|
|
258
|
-
const
|
|
259
|
-
|
|
255
|
+
async reconcileEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason) {
|
|
256
|
+
const expectedTimestamp = safeParse(timestamp, expectedProviderUpdatedAt, "BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt");
|
|
257
|
+
const assignmentTimestamp = planAssignedAt === null
|
|
258
|
+
? null
|
|
259
|
+
: safeParse(timestamp, planAssignedAt, "BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt");
|
|
260
|
+
const rows = await this.query(`SELECT bursar.reconcile_subscription_entitlement(
|
|
261
|
+
$1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,
|
|
262
|
+
$5::timestamptz, $6::timestamptz, $7, $8, $9
|
|
263
|
+
) AS outcome`, [
|
|
264
|
+
subjectId,
|
|
265
|
+
subscriptionId,
|
|
266
|
+
billingEventId,
|
|
267
|
+
expectedStatus,
|
|
268
|
+
expectedTimestamp,
|
|
269
|
+
assignmentTimestamp,
|
|
270
|
+
applyEntitlement,
|
|
271
|
+
terminalPlanKey,
|
|
272
|
+
reason,
|
|
273
|
+
]);
|
|
274
|
+
return requireResultField(rows, "outcome", SubscriptionEntitlementOutcomeSchema, "BillingSubscriptionRepository.reconcileEntitlement");
|
|
275
|
+
}
|
|
276
|
+
async expireGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey) {
|
|
277
|
+
const rows = await this.query(`SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4, $5) AS expired`, [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey]);
|
|
278
|
+
return requireResultField(rows, "expired", pgBoolean, "BillingSubscriptionRepository.expireGracePeriod");
|
|
260
279
|
}
|
|
261
280
|
async recordConflict(input) {
|
|
262
281
|
const rows = await this.query(`SELECT bursar.record_subscription_conflict(
|
|
@@ -271,25 +290,5 @@ export class BillingSubscriptionRepository {
|
|
|
271
290
|
]);
|
|
272
291
|
return requireResultField(rows, "id", z.union([z.string().min(1), z.number().int()]).transform(String), "BillingSubscriptionRepository.recordConflict");
|
|
273
292
|
}
|
|
274
|
-
/** Select a provider subscription without modifying provider-reported state. */
|
|
275
|
-
async selectEntitlementSource(userId, provider, providerSubscriptionId) {
|
|
276
|
-
const eligibleStatuses = new Set(["trialing", "active", "past_due", "paused"]);
|
|
277
|
-
const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [
|
|
278
|
-
userId,
|
|
279
|
-
]);
|
|
280
|
-
const replacement = rows
|
|
281
|
-
.map((row) => persistedSubscription(row, "BillingSubscriptionRepository.selectEntitlementSource"))
|
|
282
|
-
.filter((row) => row.provider === provider &&
|
|
283
|
-
eligibleStatuses.has(row.status) &&
|
|
284
|
-
(!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId))
|
|
285
|
-
.sort((left, right) => Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at))[0];
|
|
286
|
-
if (replacement?.id == null)
|
|
287
|
-
return false;
|
|
288
|
-
const selectedRows = await this.query(`SELECT bursar.select_entitlement_source($1::uuid, $2::uuid) AS selected`, [userId, replacement.id]);
|
|
289
|
-
if (!requireResultField(selectedRows, "selected", pgBoolean, "BillingSubscriptionRepository.selectEntitlementSource")) {
|
|
290
|
-
throw new StoreError("subscription entitlement source selection was rejected");
|
|
291
|
-
}
|
|
292
|
-
return true;
|
|
293
|
-
}
|
|
294
293
|
}
|
|
295
294
|
//# sourceMappingURL=subscription.js.map
|