@zonastery/bursar 2.0.3 → 2.0.5
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 -1
- 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.map +1 -1
- package/dist/billing/auto-recharge-service.js +3 -3
- 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 +6 -6
- 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 +8 -7
- 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 +32 -23
- 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/policy-window.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 +58 -40
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/customer.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 +2 -2
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -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.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +5 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +4 -4
- 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/preferences.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/preferences.js.map +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/refund.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 +11 -11
- 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.map +1 -1
- package/dist/billing/postgres/store.d.ts +6 -5
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +15 -13
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +2 -1
- 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/documents.d.ts +2 -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 +3 -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 +3 -2
- package/dist/breakdown.d.ts.map +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/errors.d.ts.map +1 -1
- package/dist/commerce/errors.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 +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +16 -22
- package/dist/commerce/service.js.map +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 +15 -11
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +90 -27
- package/dist/config/parse-utils.js.map +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 +65 -35
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +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.map +1 -1
- package/dist/credits/catalog-runtime.js +2 -3
- 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 +2 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +3 -2
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -1
- package/dist/credits/low-balance-monitor.d.ts.map +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 +6 -6
- 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.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +5 -4
- 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 +2 -2
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +11 -11
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -2
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +3 -2
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +17 -10
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +4 -3
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +10 -11
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/queries.d.ts.map +1 -1
- package/dist/credits/queries.js.map +1 -1
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +10 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +5 -4
- package/dist/credits/store.d.ts.map +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/engine.d.ts +2 -2
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +39 -10
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +7 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +18 -11
- 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.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.map +1 -1
- package/dist/expr.js +12 -6
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +0 -12
- package/dist/generated/pricing-config.types.d.ts +2 -8
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.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 +2 -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/providers/_shared.d.ts +8 -5
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +15 -11
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +30 -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 -9
- 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 +12 -10
- 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 +121 -113
- 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 +42 -35
- 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 +33 -9
- 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 +101 -61
- package/dist/providers/stripe/provider.js.map +1 -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 +5 -5
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +32 -22
- 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 +28 -4
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +8 -6
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +69 -47
- 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 +11 -4
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +8 -6
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +28 -5
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +48 -33
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +1 -1
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js +13 -12
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/maintenance.d.ts.map +1 -1
- package/dist/storage/maintenance.js +31 -25
- package/dist/storage/maintenance.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +18 -18
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +10 -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 +3 -1
- 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 +1 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +165 -182
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +10 -6
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +26 -23
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/opentelemetry.d.ts.map +1 -1
- package/dist/telemetry/opentelemetry.js +3 -3
- package/dist/telemetry/opentelemetry.js.map +1 -1
- package/package.json +40 -40
|
@@ -18,6 +18,7 @@ const SubscriptionStatusSchema = z.enum([
|
|
|
18
18
|
"paused",
|
|
19
19
|
"expired",
|
|
20
20
|
]);
|
|
21
|
+
const SubscriptionEntitlementOutcomeSchema = 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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1D,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;CACtC,CAAC;KACD,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACzF,MAAM,wBAAwB,GAAG,CAAC,CAAC,IAAI,CAAC;IACtC,YAAY;IACZ,oBAAoB;IACpB,UAAU;IACV,QAAQ;IACR,UAAU;IACV,UAAU;IACV,QAAQ;I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YAChC,CAAC,CAAC,sBAAsB,IAAI,GAAG,CAAC,wBAAwB,KAAK,sBAAsB,CAAC,CACvF;aACA,IAAI,CACH,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACd,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,mBAAmB,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAC/E,CAAC,CAAC,CAAC,CAAC;QAEP,IAAI,WAAW,EAAE,EAAE,IAAI,IAAI;YAAE,OAAO,KAAK,CAAC;QAE1C,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,KAAK,CACnC,yEAAyE,EACzE,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,CAAC,CACzB,CAAC;QACF,IACE,CAAC,kBAAkB,CACjB,YAAY,EACZ,UAAU,EACV,SAAS,EACT,uDAAuD,CACxD,EACD,CAAC;YACD,MAAM,IAAI,UAAU,CAAC,wDAAwD,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { BillingSubscriptionState } from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = 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 : new Date(value)).toISOString());\nconst SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\nconst CatalogReferenceSchema = z\n .object({\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n })\n .strict();\nconst OfferContextSchema = 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\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n metadata: z.record(z.string(), z.unknown()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\n\nfunction record(value: unknown, context: string): Record<string, unknown> {\n return safeParse(z.record(z.string(), z.unknown()), value, context);\n}\n\nfunction persistedSubscription(row: unknown, context: string): PersistedSubscriptionRow {\n const value = record(row, context);\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: unknown): SubscriptionRow {\n const r = record(row, \"BillingSubscriptionRepository.map\");\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(\n value: PersistedSubscriptionRow,\n ): Promise<Record<string, unknown>> {\n const reference = safeParse(\n CatalogReferenceSchema,\n { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id },\n \"BillingSubscriptionRepository.withOfferContext.reference\",\n );\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [reference.offer_id, reference.catalog_revision_id],\n );\n const rawContext = optionalRecordRow(\n contextRows,\n \"BillingSubscriptionRepository.withOfferContext\",\n );\n if (rawContext === null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: reference.offer_id,\n catalogRevisionId: reference.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\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 \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null\n ? null\n : this.map(\n await this.withOfferContext(\n persistedSubscription(row, \"BillingSubscriptionRepository.get\"),\n ),\n );\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = new Set(\n safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n ),\n );\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const candidates = rows\n .map((row) => persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscription\"))\n .filter((row) => allowed.has(row.status))\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n );\n const selected = candidates[0];\n return selected === undefined ? null : this.map(await this.withOfferContext(selected));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [\n now,\n limit,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.listExpiredGraceSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async markGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.mark_subscription_grace_expired($1::uuid, $2, $3) AS marked`,\n [subscriptionId, expectedGraceEndsAt, expiredAt],\n );\n return requireResultField(\n rows,\n \"marked\",\n pgBoolean,\n \"BillingSubscriptionRepository.markGraceExpired\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n\n /** Select a provider subscription without modifying provider-reported state. */\n async selectEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n const eligibleStatuses = new Set([\"trialing\", \"active\", \"past_due\", \"paused\"]);\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const replacement = rows\n .map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.selectEntitlementSource\"),\n )\n .filter(\n (row) =>\n row.provider === provider &&\n eligibleStatuses.has(row.status) &&\n (!providerSubscriptionId || row.provider_subscription_id === providerSubscriptionId),\n )\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n )[0];\n\n if (replacement?.id == null) return false;\n\n const selectedRows = await this.query(\n `SELECT bursar.select_entitlement_source($1::uuid, $2::uuid) AS selected`,\n [userId, replacement.id],\n );\n if (\n !requireResultField(\n selectedRows,\n \"selected\",\n pgBoolean,\n \"BillingSubscriptionRepository.selectEntitlementSource\",\n )\n ) {\n throw new StoreError(\"subscription entitlement source selection was rejected\");\n }\n\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subscription.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/subscription.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,SAAS,GAAG,CAAC;KAChB,KAAK,CAAC;IACL,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1D,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,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CAAC,OAAO,IAAI,IAAI;YACrB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAE,CAAC;SACrC,CACF,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,IAAI,EACJ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,EAChE,8CAA8C,CAC/C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type {\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n SubscriptionEntitlementOutcome,\n} from \"../../types/subscriptions.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst timestamp = 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 : new Date(value)).toISOString());\nconst SubscriptionStatusSchema = z.enum([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst SubscriptionEntitlementOutcomeSchema = z.enum([\"applied\", \"revoked\", \"preserved\", \"stale\"]);\nconst PersistedSubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\nconst CatalogReferenceSchema = z\n .object({\n offer_id: postgresUuid,\n catalog_revision_id: postgresUuid,\n })\n .strict();\nconst OfferContextSchema = 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\nconst SubscriptionRowSchema = z\n .object({\n id: postgresUuid,\n user_id: postgresUuid,\n provider: z.string().min(1),\n provider_subscription_id: z.string().min(1),\n provider_customer_id: z.string().min(1).nullable(),\n offer_id: postgresUuid,\n offer_key: z.string().min(1),\n plan_id: postgresUuid,\n plan: z.string().min(1),\n status: SubscriptionStatusSchema,\n current_period_start: timestamp.nullable(),\n current_period_end: timestamp.nullable(),\n trial_end: timestamp.nullable(),\n cancel_at: timestamp.nullable(),\n ended_at: timestamp.nullable(),\n grace_ends_at: timestamp.nullable(),\n grace_expired_at: timestamp.nullable(),\n provider_updated_at: timestamp,\n cancel_at_period_end: pgBoolean,\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().positive(),\n metadata: z.record(z.string(), z.json()),\n })\n .strict();\n\nexport type SubscriptionRow = z.infer<typeof SubscriptionRowSchema>;\ntype PersistedSubscriptionRow = z.infer<typeof PersistedSubscriptionRowSchema>;\ntype EnrichedSubscriptionRow = PersistedSubscriptionRow & {\n offer_key: string;\n plan_id: string;\n plan_key: string;\n billing_unit: \"day\" | \"week\" | \"month\" | \"year\";\n billing_count: number;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n interval_count: number;\n};\n\nfunction persistedSubscription(row: PostgresRow, context: string): PersistedSubscriptionRow {\n const value = row;\n return safeParse(\n PersistedSubscriptionRowSchema,\n {\n id: value.id,\n subject_id: value.subject_id,\n provider: value.provider,\n provider_subscription_id: value.provider_subscription_id,\n provider_customer_id: value.provider_customer_id,\n offer_id: value.offer_id,\n catalog_revision_id: value.catalog_revision_id,\n status: value.status,\n current_period_start: value.current_period_start,\n current_period_end: value.current_period_end,\n trial_end: value.trial_end,\n cancel_at: value.cancel_at,\n ended_at: value.ended_at,\n grace_ends_at: value.grace_ends_at,\n grace_expired_at: value.grace_expired_at,\n provider_updated_at: value.provider_updated_at,\n cancel_at_period_end: value.cancel_at_period_end,\n metadata: value.metadata,\n },\n context,\n );\n}\n\nexport class BillingSubscriptionRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(state: BillingSubscriptionState): Promise<void> {\n const provider = state.provider;\n const providerSubscriptionId = state.providerSubscriptionId;\n const userId = state.userId;\n let providerCustomerId = state.providerCustomerId ?? null;\n let offerId = state.offerId ?? null;\n\n if (!provider || !providerSubscriptionId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n\n const existing = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const rawExisting = optionalRecordRow(\n existing,\n \"BillingSubscriptionRepository.upsert.existing\",\n );\n const existingRow =\n rawExisting === null\n ? null\n : persistedSubscription(rawExisting, \"BillingSubscriptionRepository.upsert.existing\");\n if (providerCustomerId === null && existingRow !== null) {\n providerCustomerId = existingRow.provider_customer_id;\n }\n if (offerId === null && existingRow !== null) offerId = existingRow.offer_id;\n\n const offerKey = state.offerKey ?? null;\n if (offerId === null && offerKey !== null) {\n const offerRows = await this.query(`SELECT * FROM bursar.resolve_active_catalog_offer($1)`, [\n offerKey,\n ]);\n const offerRow = optionalRecordRow(offerRows, \"BillingSubscriptionRepository.upsert.offer\");\n if (offerRow !== null) {\n offerId = safeParse(\n postgresUuid,\n offerRow.id,\n \"BillingSubscriptionRepository.upsert.offer.id\",\n );\n }\n }\n\n if (!userId || !offerId) {\n throw new TypeError(\n \"subscription.upsert: subject, provider, subscription, and offer are required\",\n );\n }\n const providerUpdatedAt = safeParse(\n timestamp,\n state.providerUpdatedAt,\n \"BillingSubscriptionRepository.upsert.providerUpdatedAt\",\n );\n\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_subscription($1::uuid,$2,$3,$4,$5::uuid,$6::bursar.billing_subscription_status,$7,$8,$9,$10::jsonb,$11,$12,$13,$14,$15) AS id\",\n [\n userId,\n provider,\n providerSubscriptionId,\n providerCustomerId,\n offerId,\n state.status,\n state.currentPeriodStart ?? null,\n state.currentPeriodEnd ?? null,\n state.cancelAtPeriodEnd,\n JSON.stringify(state.metadata ?? {}),\n state.trialEnd ?? null,\n state.cancelAt ?? null,\n state.endedAt ?? null,\n providerUpdatedAt,\n state.graceEndsAt ?? null,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingSubscriptionRepository.upsert\");\n }\n\n private map(row: EnrichedSubscriptionRow): SubscriptionRow {\n const r = row;\n return safeParse(\n SubscriptionRowSchema,\n {\n id: r.id,\n user_id: r.subject_id,\n provider: r.provider,\n provider_subscription_id: r.provider_subscription_id,\n provider_customer_id: r.provider_customer_id,\n offer_id: r.offer_id,\n offer_key: r.offer_key,\n plan_id: r.plan_id,\n plan: r.plan,\n status: r.status,\n current_period_start: r.current_period_start,\n current_period_end: r.current_period_end,\n trial_end: r.trial_end,\n cancel_at: r.cancel_at,\n ended_at: r.ended_at,\n grace_ends_at: r.grace_ends_at,\n grace_expired_at: r.grace_expired_at,\n provider_updated_at: r.provider_updated_at,\n cancel_at_period_end: r.cancel_at_period_end,\n interval: r.interval,\n interval_count: r.interval_count,\n metadata: r.metadata,\n },\n \"BillingSubscriptionRepository\",\n );\n }\n\n private async withOfferContext(\n value: PersistedSubscriptionRow,\n ): Promise<EnrichedSubscriptionRow> {\n const reference = safeParse(\n CatalogReferenceSchema,\n { offer_id: value.offer_id, catalog_revision_id: value.catalog_revision_id },\n \"BillingSubscriptionRepository.withOfferContext.reference\",\n );\n const contextRows = await this.query(\n `SELECT * FROM bursar.get_catalog_offer_context($1::uuid, $2::uuid)`,\n [reference.offer_id, reference.catalog_revision_id],\n );\n const rawContext = optionalRecordRow(\n contextRows,\n \"BillingSubscriptionRepository.withOfferContext\",\n );\n if (rawContext === null) {\n throw new StoreError(\"Billing subscription offer context is missing\", {\n details: {\n offerId: reference.offer_id,\n catalogRevisionId: reference.catalog_revision_id,\n },\n });\n }\n const context = safeParse(\n OfferContextSchema,\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 \"BillingSubscriptionRepository.withOfferContext.context\",\n );\n return {\n ...value,\n ...context,\n plan: context.plan_key,\n interval: context.billing_unit,\n interval_count: context.billing_count,\n };\n }\n\n async get(provider: string, providerSubscriptionId: string): Promise<SubscriptionRow | null> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_billing_subscription_by_provider($1, $2)`,\n [provider, providerSubscriptionId],\n );\n const row = optionalRecordRow(rows, \"BillingSubscriptionRepository.get\");\n return row === null\n ? null\n : this.map(\n await this.withOfferContext(\n persistedSubscription(row, \"BillingSubscriptionRepository.get\"),\n ),\n );\n }\n async getUserSubscription(userId: string, statuses?: string[]): Promise<SubscriptionRow | null> {\n const allowed = new Set(\n safeParse(\n z.array(SubscriptionStatusSchema),\n statuses ?? [\"active\", \"trialing\"],\n \"BillingSubscriptionRepository.getUserSubscription.statuses\",\n ),\n );\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const candidates = rows\n .map((row) => persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscription\"))\n .filter((row) => allowed.has(row.status))\n .sort(\n (left, right) =>\n Date.parse(right.provider_updated_at) - Date.parse(left.provider_updated_at),\n );\n const selected = candidates[0];\n return selected === undefined ? null : this.map(await this.withOfferContext(selected));\n }\n async getUserSubscriptions(userId: string): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_billing_subscriptions($1::uuid)`, [\n userId,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.getUserSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async listExpiredGraceSubscriptions(now: string, limit = 100): Promise<SubscriptionRow[]> {\n const rows = await this.query(`SELECT * FROM bursar.list_expired_grace_subscriptions($1, $2)`, [\n now,\n limit,\n ]);\n const persisted = rows.map((row) =>\n persistedSubscription(row, \"BillingSubscriptionRepository.listExpiredGraceSubscriptions\"),\n );\n const enriched = await Promise.all(persisted.map((row) => this.withOfferContext(row)));\n return enriched.map((row) => this.map(row));\n }\n\n async reconcileEntitlement(\n subjectId: string,\n subscriptionId: string,\n billingEventId: string,\n expectedStatus: BillingSubscriptionStatus,\n expectedProviderUpdatedAt: string,\n planAssignedAt: Date | string | null,\n applyEntitlement: boolean,\n terminalPlanKey: string | null,\n reason: string,\n ): Promise<SubscriptionEntitlementOutcome> {\n const expectedTimestamp = safeParse(\n timestamp,\n expectedProviderUpdatedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.expectedProviderUpdatedAt\",\n );\n const assignmentTimestamp =\n planAssignedAt === null\n ? null\n : safeParse(\n timestamp,\n planAssignedAt,\n \"BillingSubscriptionRepository.reconcileEntitlement.planAssignedAt\",\n );\n const rows = await this.query(\n `SELECT bursar.reconcile_subscription_entitlement(\n $1::uuid, $2::uuid, $3::uuid, $4::bursar.billing_subscription_status,\n $5::timestamptz, $6::timestamptz, $7, $8, $9\n ) AS outcome`,\n [\n subjectId,\n subscriptionId,\n billingEventId,\n expectedStatus,\n expectedTimestamp,\n assignmentTimestamp,\n applyEntitlement,\n terminalPlanKey,\n reason,\n ],\n );\n return requireResultField(\n rows,\n \"outcome\",\n SubscriptionEntitlementOutcomeSchema,\n \"BillingSubscriptionRepository.reconcileEntitlement\",\n );\n }\n\n async expireGracePeriod(\n subjectId: string,\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt: string,\n terminalPlanKey: string | null,\n ): Promise<boolean> {\n const rows = await this.query(\n `SELECT bursar.expire_subscription_grace_period($1::uuid, $2::uuid, $3, $4, $5) AS expired`,\n [subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey],\n );\n return requireResultField(\n rows,\n \"expired\",\n pgBoolean,\n \"BillingSubscriptionRepository.expireGracePeriod\",\n );\n }\n\n async recordConflict(input: {\n userId?: string | null;\n provider: string;\n duplicateSubscriptionId: string;\n existingSubscriptionId?: string | null;\n eventId?: string | null;\n metadata?: JsonObject;\n }): Promise<string> {\n const rows = await this.query(\n `SELECT bursar.record_subscription_conflict(\n $1::uuid, $2, $3, $4, $5, $6::jsonb\n ) AS id`,\n [\n input.userId ?? null,\n input.provider,\n input.duplicateSubscriptionId,\n input.existingSubscriptionId ?? null,\n input.eventId ?? null,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n z.union([z.string().min(1), z.number().int()]).transform(String),\n \"BillingSubscriptionRepository.recordConflict\",\n );\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import type { QueryFn } from "../../../shared/postgres-types.js";
|
|
|
4
4
|
declare const BillingTopupRowSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
6
6
|
topup_key: z.ZodString;
|
|
7
|
-
credits_per_unit: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.
|
|
7
|
+
credits_per_unit: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodInstanceOf<Decimal>]>, z.ZodTransform<Decimal, string | number | Decimal>>;
|
|
8
8
|
bucket_key: z.ZodString;
|
|
9
9
|
amount_minor: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>, z.ZodTransform<number, string | number>>;
|
|
10
10
|
currency: z.ZodString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBAuBvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"topup.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/topup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAajE,QAAA,MAAM,qBAAqB;;;;;;;;;;kBAuBvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,+CAA+C;AAC/C,qBAAa,sBAAsB;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAAlC,YAA6B,KAAK,EAAE,OAAO,EAAI;IAEzC,cAAc,CAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,SAAS,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAGjC;IAEK,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAA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":["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 SafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingTopupRowSchema = z\n .object({\n id: postgresUuid,\n topup_key: z.string().min(1),\n credits_per_unit: PositiveDecimalSchema,\n bucket_key: z.string().min(1),\n amount_minor: SafeMinorUnitsSchema,\n currency: z.string().regex(/^[A-Z]{3}$/),\n min_quantity: z.number().int().positive(),\n max_quantity: z.number().int().positive(),\n default_quantity: z.number().int().positive(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.max_quantity < row.min_quantity) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"max_quantity is below min_quantity\" });\n }\n if (row.default_quantity < row.min_quantity || row.default_quantity > row.max_quantity) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"default_quantity is outside the configured range\",\n });\n }\n });\n\nexport type BillingTopupRow = z.infer<typeof BillingTopupRowSchema>;\n\n/** Repository for credit top-up resolution. */\nexport class BillingTopupRepository {\n constructor(private readonly query: QueryFn) {}\n\n async resolveByPrice(\n provider: string,\n priceId: string | null,\n productId: string | null,\n ): Promise<BillingTopupRow | 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<BillingTopupRow | 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<BillingTopupRow | null> {\n if (!provider.trim()) throw new TypeError(\"provider must not be empty\");\n if (!lookupValue?.trim()) return null;\n\n const context = `BillingTopupRepository.${operation}`;\n const rows = await this.query(\"SELECT * FROM bursar.resolve_catalog_topup($1, $2, $3)\", [\n provider,\n lookupType,\n lookupValue,\n ]);\n if (rows.length > 1) {\n throw new StoreError(`${context}: expected at most one top-up`, {\n details: { rowCount: rows.length },\n });\n }\n const raw = unwrapJsonb(rows);\n if (raw?.id == null) return null;\n return safeParse(\n BillingTopupRowSchema,\n {\n id: raw.id,\n topup_key: raw.topup_key,\n credits_per_unit: raw.credits_per_unit,\n bucket_key: raw.bucket_key,\n amount_minor: raw.amount_minor,\n currency: raw.currency,\n min_quantity: raw.min_quantity,\n max_quantity: raw.max_quantity,\n default_quantity: raw.default_quantity,\n },\n context,\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Decimal } from "decimal.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { JsonObject } from "../../shared/json.js";
|
|
3
|
+
import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCreditPostingResult, BillingCustomerRecord, BillingEventClaim, BillingOfferResult, BillingPaymentRecord, BillingPreferences, BillingSubscriptionChange, BillingSubscriptionChangeInput, BillingSubscriptionState, BillingSubscriptionStatus, SubscriptionEntitlementOutcome, CheckoutIntent, BillingTopupResult } from "../types/index.js";
|
|
3
4
|
import { BillingStore } from "../billing-store.js";
|
|
4
5
|
import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
|
|
5
6
|
import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
|
|
@@ -52,7 +53,7 @@ export declare class PostgresBillingStore extends BillingStore {
|
|
|
52
53
|
private rowToOffer;
|
|
53
54
|
resolveBillingOffer(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingOfferResult | null>;
|
|
54
55
|
resolveBillingOfferByLookup(provider: string, lookupKey: string): Promise<BillingOfferResult | null>;
|
|
55
|
-
claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?:
|
|
56
|
+
claimBillingEvent(provider: string, eventId: string, eventType: string, envelope?: JsonObject): Promise<BillingEventClaim>;
|
|
56
57
|
completeBillingEvent(provider: string, eventId: string, claimToken: string): Promise<boolean>;
|
|
57
58
|
failBillingEvent(provider: string, eventId: string, claimToken: string, error?: string): Promise<boolean>;
|
|
58
59
|
upsertBillingCustomer(provider: string, providerCustomerId: string, userId: string, email?: string | null): Promise<void>;
|
|
@@ -62,12 +63,12 @@ export declare class PostgresBillingStore extends BillingStore {
|
|
|
62
63
|
createBillingSubscriptionChange(input: BillingSubscriptionChangeInput): Promise<BillingSubscriptionChange>;
|
|
63
64
|
getOpenBillingSubscriptionChange(provider: string, providerSubscriptionId: string): Promise<BillingSubscriptionChange | null>;
|
|
64
65
|
listExpiredGraceSubscriptions(now: string, limit?: number): Promise<BillingSubscriptionState[]>;
|
|
65
|
-
|
|
66
|
+
reconcileSubscriptionEntitlement(subjectId: string, subscriptionId: string, billingEventId: string, expectedStatus: BillingSubscriptionStatus, expectedProviderUpdatedAt: string, planAssignedAt: Date | string | null, applyEntitlement: boolean, terminalPlanKey: string | null, reason: string): Promise<SubscriptionEntitlementOutcome>;
|
|
67
|
+
expireSubscriptionGracePeriod(subjectId: string, subscriptionId: string, expectedGraceEndsAt: string, expiredAt: string, terminalPlanKey: string | null): Promise<boolean>;
|
|
66
68
|
updateBillingSubscriptionChange(id: string, update: BillingSubscriptionChangeUpdate): Promise<void>;
|
|
67
69
|
getUserSubscription(userId: string, statuses?: string[]): Promise<BillingSubscriptionState | null>;
|
|
68
70
|
getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]>;
|
|
69
71
|
recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void>;
|
|
70
|
-
selectSubscriptionEntitlementSource(userId: string, provider: string, providerSubscriptionId?: string | null): Promise<boolean>;
|
|
71
72
|
private rowToTopup;
|
|
72
73
|
resolveCreditTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
|
|
73
74
|
resolveCreditTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
|
|
@@ -83,7 +84,7 @@ export declare class PostgresBillingStore extends BillingStore {
|
|
|
83
84
|
upsertBillingDispute(options: BillingDisputeUpsert): Promise<void>;
|
|
84
85
|
getBillingPayment(provider: string, providerPaymentId: string): Promise<BillingPaymentRecord | null>;
|
|
85
86
|
private rowToSubscriptionState;
|
|
86
|
-
getActiveCatalogDocument(): Promise<
|
|
87
|
+
getActiveCatalogDocument(): Promise<JsonObject | null>;
|
|
87
88
|
pseudonymizeFinancialSubject(userId: string): Promise<boolean>;
|
|
88
89
|
getBillingPreferences(userId: string): Promise<BillingPreferences | null>;
|
|
89
90
|
upsertBillingPreferences(prefs: BillingPreferences): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAA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 -88,10 +88,10 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
88
88
|
_subscriptionChange = null;
|
|
89
89
|
constructor(options) {
|
|
90
90
|
super();
|
|
91
|
-
if (
|
|
91
|
+
if (!z.object({}).safeParse(options).success) {
|
|
92
92
|
throw new TypeError("PostgresBillingStore options are required");
|
|
93
93
|
}
|
|
94
|
-
if (
|
|
94
|
+
if (!z.string().safeParse(options.postgres).success && options.poolConstructor !== undefined) {
|
|
95
95
|
throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
|
|
96
96
|
}
|
|
97
97
|
const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
|
|
@@ -222,6 +222,8 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
222
222
|
});
|
|
223
223
|
}
|
|
224
224
|
const row = rows[0];
|
|
225
|
+
if (!row)
|
|
226
|
+
throw new StoreError("getCheckoutIntent: expected one row");
|
|
225
227
|
return this.rowToCheckoutIntent(safeParse(CheckoutIntentRowSchema, {
|
|
226
228
|
id: row.id,
|
|
227
229
|
subject_id: row.subject_id,
|
|
@@ -350,8 +352,11 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
350
352
|
const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);
|
|
351
353
|
return rows.map((row) => this.rowToSubscriptionState(row));
|
|
352
354
|
}
|
|
353
|
-
async
|
|
354
|
-
return this.billingSubscription.
|
|
355
|
+
async reconcileSubscriptionEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason) {
|
|
356
|
+
return this.billingSubscription.reconcileEntitlement(subjectId, subscriptionId, billingEventId, expectedStatus, expectedProviderUpdatedAt, planAssignedAt, applyEntitlement, terminalPlanKey, reason);
|
|
357
|
+
}
|
|
358
|
+
async expireSubscriptionGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey) {
|
|
359
|
+
return this.billingSubscription.expireGracePeriod(subjectId, subscriptionId, expectedGraceEndsAt, expiredAt, terminalPlanKey);
|
|
355
360
|
}
|
|
356
361
|
async updateBillingSubscriptionChange(id, update) {
|
|
357
362
|
await this.billingSubscriptionChange.update(id, update);
|
|
@@ -369,9 +374,6 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
369
374
|
async recordSubscriptionConflict(input) {
|
|
370
375
|
await this.billingSubscription.recordConflict(input);
|
|
371
376
|
}
|
|
372
|
-
async selectSubscriptionEntitlementSource(userId, provider, providerSubscriptionId) {
|
|
373
|
-
return this.billingSubscription.selectEntitlementSource(userId, provider, providerSubscriptionId);
|
|
374
|
-
}
|
|
375
377
|
rowToTopup(r) {
|
|
376
378
|
if (!r)
|
|
377
379
|
return null;
|
|
@@ -529,14 +531,14 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
529
531
|
}
|
|
530
532
|
async getActiveCatalogDocument() {
|
|
531
533
|
const rows = await this.queryFn("SELECT * FROM bursar.active_catalog_revision()", []);
|
|
532
|
-
|
|
534
|
+
const row = optionalRecordRow(rows, "PostgresBillingStore.getActiveCatalogDocument");
|
|
535
|
+
if (row === null)
|
|
533
536
|
return null;
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
});
|
|
537
|
+
const sourceDocument = row.source_document;
|
|
538
|
+
if (sourceDocument === undefined) {
|
|
539
|
+
throw new StoreError("active catalog revision returned no source document");
|
|
538
540
|
}
|
|
539
|
-
return safeParse(z.record(z.string(), z.
|
|
541
|
+
return safeParse(z.record(z.string(), z.json()), sourceDocument, "PostgresBillingStore.getActiveCatalogDocument");
|
|
540
542
|
}
|
|
541
543
|
async pseudonymizeFinancialSubject(userId) {
|
|
542
544
|
const rows = await this.queryFn(`SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`, [userId]);
|