@zonastery/bursar 2.0.4 → 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-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js.map +1 -1
- 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.map +1 -1
- 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.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.map +1 -1
- 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.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +3 -3
- package/dist/billing/postgres/repositories/payment.d.ts.map +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.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +5 -5
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- 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.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.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.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.map +1 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js.map +1 -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.map +1 -1
- 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.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 +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- 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.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 +10 -10
- 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.map +1 -1
- package/dist/credits/postgres/store.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/store.d.ts.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.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/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/providers/dodo/better-auth-core.d.ts +0 -2
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts +0 -2
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +2 -1
- 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.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/environment.d.ts.map +1 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- 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 +1 -1
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/retry.js.map +1 -1
- package/dist/shared/idempotency.js.map +1 -1
- 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.map +1 -1
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/maintenance.d.ts.map +1 -1
- package/dist/storage/maintenance.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/opentelemetry.d.ts.map +1 -1
- package/dist/telemetry/opentelemetry.js.map +1 -1
- package/package.json +30 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"financial-event-handlers.js","sourceRoot":"","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B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,UAAU;SACpC,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,KAAmB;QAC3C,IAAI,CAAC,KAAK,CAAC,OAAO;YAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;QACxE,MAAM,IAAI,CAAC,KAAK,CAAC,oBAAoB,CAAC;YACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,UAAU;SACpC,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport type { BillingEvent, BillingEventResult, BillingTopupResult } from \"./types/index.js\";\n\nexport class BillingFinancialEventHandlers {\n constructor(\n private readonly store: BillingStore,\n private readonly logger: NormalizedLogger,\n private readonly pastDueGracePeriodMs: number,\n private readonly resolveAccountId: (event: BillingEvent) => Promise<string | null>,\n private readonly handleSubscriptionRenewed: (\n event: BillingEvent,\n ) => Promise<BillingEventResult>,\n private readonly updateCheckoutIntentFromEvent: (\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ) => Promise<void>,\n private readonly applyPastDueSubscription: (\n event: BillingEvent,\n graceEndsAt: string,\n ) => Promise<BillingEventResult>,\n ) {}\n\n async handleInvoicePaid(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleInvoicePaid\", {\n provider: event.provider,\n eventId: event.eventId,\n invoiceId: event.invoice?.providerInvoiceId,\n });\n if (!event.invoice) return { handled: false, error: \"no_invoice_data\" };\n const renewalResult = event.subscription\n ? await this.handleSubscriptionRenewed(event)\n : { handled: true, action: \"invoice_paid\" };\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.invoice.providerInvoiceId,\n providerSubscriptionId: event.subscription?.providerSubscriptionId,\n userId: uid,\n status: event.invoice.status,\n amountPaidMinor: event.invoice.amountPaidMinor,\n amountDueMinor: event.invoice.amountDueMinor,\n currency: event.invoice.currency,\n periodStart: event.invoice.periodStart,\n periodEnd: event.invoice.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n return renewalResult;\n }\n\n async handlePaymentSucceeded(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentSucceeded\", {\n provider: event.provider,\n eventId: event.eventId,\n amountMinor: event.payment?.amountMinor,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n\n const uid = await this.resolveAccountId(event);\n const refs = event.payment.refs;\n let topupConfig: BillingTopupResult | null = null;\n if (refs) {\n topupConfig = await this.store.resolveCreditTopup(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n }\n\n let paymentId: string | null = null;\n if (uid) {\n const paymentMetadata: JsonObject | null =\n topupConfig && event.payment.purpose === \"credit_topup\"\n ? { credits_per_unit: topupConfig.creditsPerUnit.toString() }\n : null;\n paymentId = await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n metadata: paymentMetadata,\n });\n\n // Dodo represents subscription receipts as payment.succeeded events,\n // while Stripe emits invoice.paid. Materialize the Dodo payment as a\n // paid invoice so invoice history is provider-agnostic.\n if (event.payment.purpose === \"subscription\" && event.subscription) {\n const renewalResult = await this.handleSubscriptionRenewed(event);\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.payment.providerPaymentId,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n userId: uid,\n status: \"paid\",\n amountPaidMinor: event.payment.amountMinor,\n amountDueMinor: event.payment.amountMinor,\n currency: event.payment.currency,\n periodStart: event.subscription.periodStart,\n periodEnd: event.subscription.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n }\n\n if (topupConfig && event.payment.purpose === \"credit_topup\" && uid) {\n if (\n event.payment.amountMinor < topupConfig.minAmountMinor ||\n event.payment.amountMinor > topupConfig.maxAmountMinor\n ) {\n this.logger.warn(\n `[BillingService] topup amount ${event.payment.amountMinor} exceeds cap ${topupConfig.maxAmountMinor} for topup key ${topupConfig.topupKey} (user ${uid})`,\n );\n return { handled: true, action: \"payment_succeeded_out_of_bounds\" };\n }\n const credits = await this.store.computeTopupCredits(event.payment.amountMinor, topupConfig);\n const quantity =\n topupConfig.amountMinor <= 0 ? 0 : event.payment.amountMinor / topupConfig.amountMinor;\n if (\n credits.gt(0) &&\n paymentId &&\n Number.isSafeInteger(quantity) &&\n topupConfig.creditsPerUnit.gt(0)\n ) {\n const grantId = await this.store.createBillingCreditGrant({\n paymentId,\n topupId: topupConfig.topupId,\n configuredCredits: topupConfig.creditsPerUnit,\n quantity,\n });\n await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:topup`);\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"succeeded\",\n });\n }\n\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n\n return { handled: true, action: \"payment_succeeded\" };\n }\n\n async handlePaymentFailed(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentFailed\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n });\n }\n if (uid && event.subscription) {\n const occurredAt = new Date(event.occurredAt);\n if (Number.isNaN(occurredAt.getTime())) {\n throw new TypeError(\"billing event occurredAt must be a valid instant\");\n }\n const subscriptionResult = await this.applyPastDueSubscription(\n event,\n new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n );\n if (subscriptionResult.action === \"stale_subscription_event\") return subscriptionResult;\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"failed\",\n failureCode: \"provider_payment_failed\",\n });\n await this.updateCheckoutIntentFromEvent(event, \"failed\");\n return { handled: true, action: \"payment_failed_recorded\" };\n }\n\n async handleRefundCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.refund) return { handled: false, error: \"no_refund_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n const refundId = await this.store.upsertBillingRefund({\n provider: event.provider,\n providerRefundId: event.refund.providerRefundId,\n providerPaymentId: event.refund.providerPaymentId,\n userId: uid,\n amountMinor: event.refund.amountMinor,\n currency: event.refund.currency,\n reason: event.refund.reason,\n status: event.refund.status,\n providerUpdatedAt: event.occurredAt,\n metadata: event.metadata,\n });\n if (event.refund.status === \"succeeded\") {\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.refund.providerPaymentId,\n );\n\n if (payment?.purpose === \"credit_topup\" && payment.id) {\n const grantId = await this.store.getBillingCreditGrantByPayment(String(payment.id));\n if (grantId) {\n const result = await this.store.postBillingRefund(\n refundId,\n grantId,\n event.refund.amountMinor,\n `billing:${event.eventId}:refund`,\n );\n if (!result.errorCode) return { handled: true, action: \"refund_clawback\" };\n }\n }\n }\n }\n return { handled: true, action: \"refund_recorded\" };\n }\n\n async handleDisputeCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_recorded\" };\n }\n\n async handleDisputeClosed(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_closed\" };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"financial-event-handlers.js","sourceRoot":"","sources":["../../src/billing/financial-event-handlers.ts"],"names":[],"mappings":"AAKA,MAAM,OAAO,6BAA6B;IAErB,KAAK;IACL,MAAM;IACN,oBAAoB;IACpB,gBAAgB;IAChB,yBAAyB;IAGzB,6BAA6B;IAI7B,wBAAwB;IAZ3C,YACmB,KAAmB,EACnB,MAAwB,EACxB,oBA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,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;QACxE,MAAM,IAAI,CAAC,KAAK,CAAC,oBAAoB,CAAC;YACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,iBAAiB;YAClD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,iBAAiB,EAAE,KAAK,CAAC,UAAU;SACpC,CAAC,CAAC;QACH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport type { BillingEvent, BillingEventResult, BillingTopupResult } from \"./types/index.js\";\n\nexport class BillingFinancialEventHandlers {\n constructor(\n private readonly store: BillingStore,\n private readonly logger: NormalizedLogger,\n private readonly pastDueGracePeriodMs: number,\n private readonly resolveAccountId: (event: BillingEvent) => Promise<string | null>,\n private readonly handleSubscriptionRenewed: (\n event: BillingEvent,\n ) => Promise<BillingEventResult>,\n private readonly updateCheckoutIntentFromEvent: (\n event: BillingEvent,\n status: \"completed\" | \"failed\" | \"expired\",\n ) => Promise<void>,\n private readonly applyPastDueSubscription: (\n event: BillingEvent,\n graceEndsAt: string,\n ) => Promise<BillingEventResult>,\n ) {}\n\n async handleInvoicePaid(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handleInvoicePaid\", {\n provider: event.provider,\n eventId: event.eventId,\n invoiceId: event.invoice?.providerInvoiceId,\n });\n if (!event.invoice) return { handled: false, error: \"no_invoice_data\" };\n const renewalResult = event.subscription\n ? await this.handleSubscriptionRenewed(event)\n : { handled: true, action: \"invoice_paid\" };\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.invoice.providerInvoiceId,\n providerSubscriptionId: event.subscription?.providerSubscriptionId,\n userId: uid,\n status: event.invoice.status,\n amountPaidMinor: event.invoice.amountPaidMinor,\n amountDueMinor: event.invoice.amountDueMinor,\n currency: event.invoice.currency,\n periodStart: event.invoice.periodStart,\n periodEnd: event.invoice.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n return renewalResult;\n }\n\n async handlePaymentSucceeded(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentSucceeded\", {\n provider: event.provider,\n eventId: event.eventId,\n amountMinor: event.payment?.amountMinor,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n\n const uid = await this.resolveAccountId(event);\n const refs = event.payment.refs;\n let topupConfig: BillingTopupResult | null = null;\n if (refs) {\n topupConfig = await this.store.resolveCreditTopup(\n event.provider,\n refs.productId ?? null,\n refs.priceId ?? null,\n );\n }\n\n let paymentId: string | null = null;\n if (uid) {\n const paymentMetadata: JsonObject | null =\n topupConfig && event.payment.purpose === \"credit_topup\"\n ? { credits_per_unit: topupConfig.creditsPerUnit.toString() }\n : null;\n paymentId = await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n metadata: paymentMetadata,\n });\n\n // Dodo represents subscription receipts as payment.succeeded events,\n // while Stripe emits invoice.paid. Materialize the Dodo payment as a\n // paid invoice so invoice history is provider-agnostic.\n if (event.payment.purpose === \"subscription\" && event.subscription) {\n const renewalResult = await this.handleSubscriptionRenewed(event);\n if (!renewalResult.handled) return renewalResult;\n if (renewalResult.action === \"stale_subscription_event\") return renewalResult;\n await this.store.upsertBillingInvoice({\n provider: event.provider,\n providerInvoiceId: event.payment.providerPaymentId,\n providerSubscriptionId: event.subscription.providerSubscriptionId,\n userId: uid,\n status: \"paid\",\n amountPaidMinor: event.payment.amountMinor,\n amountDueMinor: event.payment.amountMinor,\n currency: event.payment.currency,\n periodStart: event.subscription.periodStart,\n periodEnd: event.subscription.periodEnd,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n }\n }\n\n if (topupConfig && event.payment.purpose === \"credit_topup\" && uid) {\n if (\n event.payment.amountMinor < topupConfig.minAmountMinor ||\n event.payment.amountMinor > topupConfig.maxAmountMinor\n ) {\n this.logger.warn(\n `[BillingService] topup amount ${event.payment.amountMinor} exceeds cap ${topupConfig.maxAmountMinor} for topup key ${topupConfig.topupKey} (user ${uid})`,\n );\n return { handled: true, action: \"payment_succeeded_out_of_bounds\" };\n }\n const credits = await this.store.computeTopupCredits(event.payment.amountMinor, topupConfig);\n const quantity =\n topupConfig.amountMinor <= 0 ? 0 : event.payment.amountMinor / topupConfig.amountMinor;\n if (\n credits.gt(0) &&\n paymentId &&\n Number.isSafeInteger(quantity) &&\n topupConfig.creditsPerUnit.gt(0)\n ) {\n const grantId = await this.store.createBillingCreditGrant({\n paymentId,\n topupId: topupConfig.topupId,\n configuredCredits: topupConfig.creditsPerUnit,\n quantity,\n });\n await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:topup`);\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"succeeded\",\n });\n }\n\n await this.updateCheckoutIntentFromEvent(event, \"completed\");\n\n return { handled: true, action: \"payment_succeeded\" };\n }\n\n async handlePaymentFailed(event: BillingEvent): Promise<BillingEventResult> {\n this.logger.info(\"[BillingService] handlePaymentFailed\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n if (!event.payment) return { handled: false, error: \"no_payment_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n await this.store.upsertBillingPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n userId: uid,\n amountMinor: event.payment.amountMinor,\n taxMinor: event.payment.taxMinor,\n currency: event.payment.currency,\n purpose: event.payment.purpose,\n status: event.payment.status,\n providerUpdatedAt: event.occurredAt,\n });\n }\n if (uid && event.subscription) {\n const occurredAt = new Date(event.occurredAt);\n if (Number.isNaN(occurredAt.getTime())) {\n throw new TypeError(\"billing event occurredAt must be a valid instant\");\n }\n const subscriptionResult = await this.applyPastDueSubscription(\n event,\n new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n );\n if (subscriptionResult.action === \"stale_subscription_event\") return subscriptionResult;\n }\n await this.store.updateAutoRechargeAttemptByProviderPayment({\n provider: event.provider,\n providerPaymentId: event.payment.providerPaymentId,\n state: \"failed\",\n failureCode: \"provider_payment_failed\",\n });\n await this.updateCheckoutIntentFromEvent(event, \"failed\");\n return { handled: true, action: \"payment_failed_recorded\" };\n }\n\n async handleRefundCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.refund) return { handled: false, error: \"no_refund_data\" };\n const uid = await this.resolveAccountId(event);\n if (uid) {\n const refundId = await this.store.upsertBillingRefund({\n provider: event.provider,\n providerRefundId: event.refund.providerRefundId,\n providerPaymentId: event.refund.providerPaymentId,\n userId: uid,\n amountMinor: event.refund.amountMinor,\n currency: event.refund.currency,\n reason: event.refund.reason,\n status: event.refund.status,\n providerUpdatedAt: event.occurredAt,\n metadata: event.metadata,\n });\n if (event.refund.status === \"succeeded\") {\n const payment = await this.store.getBillingPayment(\n event.provider,\n event.refund.providerPaymentId,\n );\n\n if (payment?.purpose === \"credit_topup\" && payment.id) {\n const grantId = await this.store.getBillingCreditGrantByPayment(String(payment.id));\n if (grantId) {\n const result = await this.store.postBillingRefund(\n refundId,\n grantId,\n event.refund.amountMinor,\n `billing:${event.eventId}:refund`,\n );\n if (!result.errorCode) return { handled: true, action: \"refund_clawback\" };\n }\n }\n }\n }\n return { handled: true, action: \"refund_recorded\" };\n }\n\n async handleDisputeCreated(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_recorded\" };\n }\n\n async handleDisputeClosed(event: BillingEvent): Promise<BillingEventResult> {\n if (!event.dispute) return { handled: false, error: \"no_dispute_data\" };\n await this.store.upsertBillingDispute({\n provider: event.provider,\n providerDisputeId: event.dispute.providerDisputeId,\n providerPaymentId: event.dispute.providerPaymentId,\n status: event.dispute.status,\n reason: event.dispute.reason,\n metadata: event.metadata,\n providerUpdatedAt: event.occurredAt,\n });\n return { handled: true, action: \"dispute_closed\" };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"management.d.ts","sourceRoot":"","sources":["../../src/billing/management.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC1B,qBAAqB,EACrB,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EAExB,kBAAkB,EAClB,cAAc,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;GAKG;AACH,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"management.d.ts","sourceRoot":"","sources":["../../src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from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n CheckoutIntent,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Public billing reads and commands that delegate directly to BillingStore.\n *\n * Webhook lifecycle orchestration lives in BillingService; this class keeps\n * the stable facade surface separate from that state machine.\n */\nexport class BillingManagement {\n constructor(private readonly store: BillingStore) {}\n\n async createOrGetCheckoutIntent(input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0]) {\n return this.store.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.store.updateCheckoutIntent(id, update);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.store.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n ]);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.store.getBillingPreferences(userId);\n }\n\n async listBillingInvoices(userId: string) {\n return this.store.listBillingInvoices(userId);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.store.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.store.createBillingSubscriptionChange(input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.store.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.store.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.store.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.store.upsertBillingPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.store.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.store.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n const subscriptions = await this.listCancellableSubscriptions(userId);\n return subscriptions.map((subscription) => subscription.providerSubscriptionId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const cancellableStatuses = new Set<BillingSubscriptionStatus>([\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n SUBSCRIPTION_STATUS.UNPAID,\n SUBSCRIPTION_STATUS.PAUSED,\n ]);\n const subscriptions = await this.store.getUserSubscriptions(userId);\n return subscriptions.filter(\n (subscription) =>\n subscription.status != null &&\n cancellableStatuses.has(subscription.status) &&\n Boolean(subscription.providerSubscriptionId),\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.store.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.store.upsertAutoRechargeProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n return this.store.claimAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n return this.store.updateAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n return this.store.updateAutoRechargeAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.store.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.store.getBillingCustomerByUserId(userId, provider);\n }\n\n async resolveOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOfferByLookup(provider, lookupKey);\n }\n\n async resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopupByLookup(provider, lookupKey);\n }\n\n async upsertCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.store.upsertBillingCustomer(provider, providerCustomerId, userId, email);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"management.js","sourceRoot":"","sources":["../../src/billing/management.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,mBA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AAgB,EAChB,SAAyB,EACzB,OAAuB;QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,YAAY,CAChB,QAAgB,EAChB,SAAyB,EACzB,OAAuB;QAEvB,OAAO,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,SAAiB;QAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACpE,CAAC;IAED,KAAK,CAAC,cAAc,CAClB,QAAgB,EAChB,kBAA0B,EAC1B,MAAc,EACd,KAAqB;QAErB,MAAM,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACtF,CAAC;CACF","sourcesContent":["import type { BillingStore } from \"./billing-store.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingOfferResult,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n CheckoutIntent,\n} from \"./types/index.js\";\nimport { SUBSCRIPTION_STATUS } from \"./types/index.js\";\nimport type { JsonObject } from \"../shared/json.js\";\n\n/**\n * Public billing reads and commands that delegate directly to BillingStore.\n *\n * Webhook lifecycle orchestration lives in BillingService; this class keeps\n * the stable facade surface separate from that state machine.\n */\nexport class BillingManagement {\n constructor(private readonly store: BillingStore) {}\n\n async createOrGetCheckoutIntent(input: Parameters<BillingStore[\"createOrGetCheckoutIntent\"]>[0]) {\n return this.store.createOrGetCheckoutIntent(input);\n }\n\n async updateCheckoutIntent(\n id: string,\n update: Parameters<BillingStore[\"updateCheckoutIntent\"]>[1],\n ): Promise<void> {\n await this.store.updateCheckoutIntent(id, update);\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n return this.store.getCheckoutIntent(id, subjectId);\n }\n\n async getActiveSubscription(userId: string): Promise<BillingSubscriptionState | null> {\n return this.store.getUserSubscription(userId, [\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n ]);\n }\n\n async getUserPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.store.getBillingPreferences(userId);\n }\n\n async listBillingInvoices(userId: string) {\n return this.store.listBillingInvoices(userId);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.store.upsertBillingSubscription(state);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n return this.store.createBillingSubscriptionChange(input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.store.getOpenBillingSubscriptionChange(provider, providerSubscriptionId);\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: Parameters<BillingStore[\"updateBillingSubscriptionChange\"]>[1],\n ): Promise<void> {\n await this.store.updateBillingSubscriptionChange(id, update);\n }\n\n async recordSubscriptionConflict(\n input: Parameters<BillingStore[\"recordSubscriptionConflict\"]>[0],\n ): Promise<void> {\n await this.store.recordSubscriptionConflict(input);\n }\n\n async updateUserPreferences(preferences: BillingPreferences): Promise<void> {\n await this.store.upsertBillingPreferences(preferences);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.store.getAutoRechargeProfile(userId);\n }\n\n async getActiveCatalogDocument(): Promise<JsonObject | null> {\n return this.store.getActiveCatalogDocument();\n }\n\n async listCancellableProviderSubscriptionIds(userId: string): Promise<string[]> {\n const subscriptions = await this.listCancellableSubscriptions(userId);\n return subscriptions.map((subscription) => subscription.providerSubscriptionId);\n }\n\n async listCancellableSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const cancellableStatuses = new Set<BillingSubscriptionStatus>([\n SUBSCRIPTION_STATUS.ACTIVE,\n SUBSCRIPTION_STATUS.TRIALING,\n SUBSCRIPTION_STATUS.PAST_DUE,\n SUBSCRIPTION_STATUS.INCOMPLETE,\n SUBSCRIPTION_STATUS.UNPAID,\n SUBSCRIPTION_STATUS.PAUSED,\n ]);\n const subscriptions = await this.store.getUserSubscriptions(userId);\n return subscriptions.filter(\n (subscription) =>\n subscription.status != null &&\n cancellableStatuses.has(subscription.status) &&\n Boolean(subscription.providerSubscriptionId),\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<void> {\n await this.store.pseudonymizeFinancialSubject(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.store.upsertAutoRechargeProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n return this.store.claimAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n return this.store.updateAutoRechargeAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n return this.store.updateAutoRechargeAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.store.countAutoRechargeAttempts(userId, since);\n }\n\n async getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n return this.store.getBillingCustomerByUserId(userId, provider);\n }\n\n async resolveOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOffer(provider, productId, priceId);\n }\n\n async resolveOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n return this.store.resolveBillingOfferByLookup(provider, lookupKey);\n }\n\n async resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopup(provider, productId, priceId);\n }\n\n async resolveTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n return this.store.resolveCreditTopupByLookup(provider, lookupKey);\n }\n\n async upsertCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.store.upsertBillingCustomer(provider, providerCustomerId, userId, email);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy-window.js","sourceRoot":"","sources":["../../src/billing/policy-window.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAIjD,MAAM,oBAAoB,GAAG,UAAU,CAAC;AACxC,MAAM,eAAe,GAAG,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC9D,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAc1D,SAAS,YAAY,CACnB,GAA2B,EAC3B,IAA0E,EAC1E,KAAa;IAEb,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,GAAG,CAAC,QAAQ,CAAC,EAA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,oBAAoB;SACvB,CAAC;IACJ,CAAC;IAED,MAAM,QAAQ,GAAG,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACzD,MAAM,KAAK,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IACjE,MAAM,GAAG,GAAG,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1D,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,MAAM,EAAE,UAAU;QAClB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,KAAK,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC,QAAQ,EAAE;QACnC,GAAG,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,QAAQ,EAAE;QAC/B,YAAY,EACV,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,iBAAiB,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC,iBAAiB,CAAC;YACzE,oBAAoB;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import { Temporal } from \"@js-temporal/polyfill\";\n\nimport type { Window } from \"../config.js\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst CALENDAR_ANCHOR = Temporal.PlainDate.from(\"2000-01-01\");\nconst WEEK_ANCHOR = Temporal.PlainDate.from(\"2000-01-03\");\n\ntype AutoRechargeWindow = Extract<Window, { type: \"calendar\" | \"rolling\" }>;\n\nexport interface ResolvedPolicyWindow {\n unit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n count: number;\n anchor: \"calendar\" | \"rolling\";\n timezone: string;\n start: string;\n end: string;\n durationDays: number;\n}\n\nfunction rollingStart(\n end: Temporal.ZonedDateTime,\n unit: Extract<AutoRechargeWindow, { type: \"rolling\" }>[\"duration\"][\"unit\"],\n count: number,\n): Temporal.ZonedDateTime {\n switch (unit) {\n case \"second\":\n return end.subtract({ seconds: count });\n case \"minute\":\n return end.subtract({ minutes: count });\n case \"hour\":\n return end.subtract({ hours: count });\n case \"day\":\n return end.subtract({ days: count });\n case \"week\":\n return end.subtract({ weeks: count });\n default:\n throw new Error(\"auto_recharge_window_unit_not_supported\");\n }\n}\n\nfunction calendarStart(\n now: Temporal.ZonedDateTime,\n unit: Extract<AutoRechargeWindow, { type: \"calendar\" }>[\"unit\"],\n count: number,\n): Temporal.ZonedDateTime {\n if (unit === \"day\" || unit === \"week\") {\n const anchor = unit === \"week\" ? WEEK_ANCHOR : CALENDAR_ANCHOR;\n const stepDays = count * (unit === \"week\" ? 7 : 1);\n const elapsedDays = anchor.until(now.toPlainDate(), { largestUnit: \"day\" }).days;\n const startDate = anchor.add({\n days: Math.floor(elapsedDays / stepDays) * stepDays,\n });\n return startDate.toZonedDateTime(now.timeZoneId);\n }\n\n const stepMonths = count * (unit === \"year\" ? 12 : 1);\n const currentMonth = now.year * 12 + now.month - 1;\n const anchorMonth = 2000 * 12;\n const startMonth =\n anchorMonth + Math.floor((currentMonth - anchorMonth) / stepMonths) * stepMonths;\n const year = Math.floor(startMonth / 12);\n const month = startMonth - year * 12 + 1;\n return Temporal.PlainDate.from({ year, month, day: 1 }).toZonedDateTime(now.timeZoneId);\n}\n\nfunction calendarEnd(\n start: Temporal.ZonedDateTime,\n unit: Extract<AutoRechargeWindow, { type: \"calendar\" }>[\"unit\"],\n count: number,\n): Temporal.ZonedDateTime {\n switch (unit) {\n case \"day\":\n return start.add({ days: count });\n case \"week\":\n return start.add({ weeks: count });\n case \"month\":\n return start.add({ months: count });\n case \"year\":\n return start.add({ years: count });\n }\n}\n\n/**\n * Resolves the reporting boundary that corresponds to PostgreSQL's\n * `bursar.policy_period_window`.\n *\n * SQL remains authoritative for claiming an auto-recharge attempt. This\n * calculation is used only to report the current window and query its count.\n */\nexport function resolveAutoRechargeWindow(\n window: AutoRechargeWindow,\n now: Temporal.Instant = Temporal.Now.instant(),\n): ResolvedPolicyWindow {\n if (window.type === \"rolling\") {\n const timezone = \"UTC\";\n const end = now.toZonedDateTimeISO(timezone);\n const start = rollingStart(end, window.duration.unit, window.duration.count);\n return {\n unit: window.duration.unit,\n count: window.duration.count,\n anchor: \"rolling\",\n timezone,\n start: start.toInstant().toString(),\n end: end.toInstant().toString(),\n durationDays:\n (end.toInstant().epochMilliseconds - start.toInstant().epochMilliseconds) /\n MILLISECONDS_PER_DAY,\n };\n }\n\n const zonedNow = now.toZonedDateTimeISO(window.timezone);\n const start = calendarStart(zonedNow, window.unit, window.count);\n const end = calendarEnd(start, window.unit, window.count);\n return {\n unit: window.unit,\n count: window.count,\n anchor: \"calendar\",\n timezone: window.timezone,\n start: start.toInstant().toString(),\n end: end.toInstant().toString(),\n durationDays:\n (end.toInstant().epochMilliseconds - start.toInstant().epochMilliseconds) /\n MILLISECONDS_PER_DAY,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AACvE,OAAO,KAAK,EACV,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC3B,MAAM,sBAAsB,CAAC;AAqQ9B,qBAAa,6BAA6B;IAC5B,OAAO,CAAC,QAAQ,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"auto-recharge.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,yBAAyB,CAAC;AACvE,OAAO,KAAK,E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AI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,OAAO,EACP,CAAC;aACE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;aAC9C,SAAS,CAAC,MAAM,CAAC;aACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,EAC9C,6CAA6C,CAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n} from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeNonnegativeInteger = z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nconst positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());\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 decimal = z\n .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && !value.isNegative(), \"expected a non-negative decimal\");\n\nconst ProfileRowSchema = z\n .object({\n subject_id: postgresUuid,\n enabled: pgBoolean,\n armed: pgBoolean,\n state: z.enum([\"disabled\", \"active\", \"paused\"]),\n provider: z.string().min(1).nullable(),\n topup_id: postgresUuid.nullable(),\n quantity: positiveInteger,\n threshold: decimal,\n max_charges_per_window: positiveInteger.nullable(),\n window_unit: z.enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"]),\n window_count: positiveInteger,\n window_anchor: z.enum([\"calendar\", \"rolling\"]),\n window_timezone: z.string().min(1),\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.enabled !== (row.state !== \"disabled\")) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"enabled and state are inconsistent\" });\n }\n if (row.enabled && (row.provider === null || row.topup_id === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled profile requires provider and topup_id\",\n });\n }\n });\n\nconst AttemptStateSchema = z.enum([\n \"claimed\",\n \"submitted\",\n \"processing\",\n \"unknown\",\n \"succeeded\",\n \"failed\",\n \"action_required\",\n]);\nconst AttemptRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n idempotency_key: z.string().min(1),\n provider_attempt_id: z.string().min(1).nullable(),\n topup_id: postgresUuid,\n quantity: positiveInteger,\n state: AttemptStateSchema,\n window_start: timestamp,\n window_end: timestamp,\n quoted_amount_minor: safeNonnegativeInteger.nullable(),\n currency: z\n .string()\n .regex(/^[A-Z]{3}$/)\n .nullable(),\n failure_code: z.string().min(1).nullable(),\n failure_message: z.string().min(1).nullable(),\n metadata: z.record(z.string(), z.json()),\n created_at: timestamp,\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"window_end must be later than window_start\",\n });\n }\n if ((row.quoted_amount_minor === null) !== (row.currency === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"quoted_amount_minor and currency must be present together\",\n });\n }\n });\n\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"submitted\", \"processing\"]],\n [\"succeeded\", [\"submitted\", \"processing\", \"succeeded\"]],\n [\"failed\", [\"submitted\", \"processing\", \"failed\"]],\n [\"unknown\", [\"submitted\", \"processing\", \"unknown\"]],\n [\"action_required\", [\"submitted\", \"action_required\"]],\n ]),\n ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", []],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\n return {\n subject_id: row.subject_id,\n enabled: row.enabled,\n armed: row.armed,\n state: row.state,\n provider: row.provider,\n topup_id: row.topup_id,\n quantity: row.quantity,\n threshold: row.threshold,\n max_charges_per_window: row.max_charges_per_window,\n window_unit: row.window_unit,\n window_count: row.window_count,\n window_anchor: row.window_anchor,\n window_timezone: row.window_timezone,\n updated_at: row.updated_at,\n };\n}\n\nfunction projectAttempt(row: PostgresRow) {\n return {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n idempotency_key: row.idempotency_key,\n provider_attempt_id: row.provider_attempt_id,\n topup_id: row.topup_id,\n quantity: row.quantity,\n state: row.state,\n window_start: row.window_start,\n window_end: row.window_end,\n quoted_amount_minor: row.quoted_amount_minor,\n currency: row.currency,\n failure_code: row.failure_code,\n failure_message: row.failure_message,\n metadata: row.metadata,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\nfunction profileFromRow(row: PostgresRow): BillingAutoRechargeProfile {\n const parsed = safeParse(\n ProfileRowSchema,\n projectProfile(row),\n \"BillingAutoRechargeRepository.profile\",\n );\n return {\n userId: parsed.subject_id,\n enabled: parsed.enabled,\n armed: parsed.armed,\n state: parsed.state,\n provider: parsed.provider,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n threshold: parsed.threshold,\n maxChargesPerWindow: parsed.max_charges_per_window,\n windowUnit: parsed.window_unit,\n windowCount: parsed.window_count,\n windowAnchor: parsed.window_anchor,\n windowTimezone: parsed.window_timezone,\n updatedAt: parsed.updated_at,\n };\n}\n\nfunction attemptFromRow(row: PostgresRow): BillingAutoRechargeAttempt {\n const parsed = safeParse(\n AttemptRowSchema,\n projectAttempt(row),\n \"BillingAutoRechargeRepository.attempt\",\n );\n return {\n id: parsed.id,\n userId: parsed.subject_id,\n provider: parsed.provider,\n idempotencyKey: parsed.idempotency_key,\n providerAttemptId: parsed.provider_attempt_id,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n state: parsed.state,\n windowStart: parsed.window_start,\n windowEnd: parsed.window_end,\n quotedAmountMinor: parsed.quoted_amount_minor,\n currency: parsed.currency,\n failureCode: parsed.failure_code,\n failureMessage: parsed.failure_message,\n metadata: parsed.metadata,\n createdAt: parsed.created_at,\n updatedAt: parsed.updated_at,\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.getProfile\");\n return row === null ? null : profileFromRow(row);\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n options.resetCooldown ?? false,\n ],\n );\n if (\n !requireResultField(rows, \"updated\", pgBoolean, \"BillingAutoRechargeRepository.upsertProfile\")\n ) {\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2)\",\n [input.userId, input.idempotencyKey],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.claimAttempt\");\n return row === null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const currentRow = optionalRecordRow(\n currentRows,\n \"BillingAutoRechargeRepository.advanceAttempt.current\",\n );\n if (currentRow === null) {\n throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {\n details: { attemptId: input.id },\n });\n }\n const current = safeParse(\n AttemptStateSchema,\n currentRow.state,\n \"BillingAutoRechargeRepository.advanceAttempt.current.state\",\n );\n const path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(input.state);\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, currentState: current, requestedState: input.state },\n });\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (\n !requireResultField(\n rows,\n \"advanced\",\n pgBoolean,\n \"BillingAutoRechargeRepository.advanceAttempt\",\n )\n ) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, requestedState: state },\n });\n }\n }\n }\n\n async updateAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n const row = optionalRecordRow(\n rows,\n \"BillingAutoRechargeRepository.updateAttemptByProviderPayment\",\n );\n if (row === null) return;\n const attempt = attemptFromRow(row);\n await this.advanceAttempt({\n id: attempt.id,\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return requireResultField(\n rows,\n \"count\",\n z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().safe()),\n \"BillingAutoRechargeRepository.countAttempts\",\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/auto-recharge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAQhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,sBAAsB,GAAG,CAAC;KAC7B,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KAC9C,SAAS,CAAC,MAAM,CAAC;KACjB,IAAI,CAAC,CAAC,CAAC,MAAM,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CAAC;YACxB,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAc,EAAE,KAAoB;QACtD,MAAM,SAAS,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QAClE,IAAI,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACtC,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,gFAAgF,EAChF,CAAC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAClC,CAAC;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,OAAO,EACP,CAAC;aACE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;aAC9C,SAAS,CAAC,MAAM,CAAC;aACjB,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,EAC9C,6CAA6C,CAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject, PostgresRow } from \"../../../shared/json.js\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeAttemptState,\n BillingAutoRechargeProfile,\n} from \"../../types/index.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst safeNonnegativeInteger = z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nconst positiveInteger = safeNonnegativeInteger.pipe(z.number().positive());\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 decimal = z\n .union([z.instanceof(Decimal), z.string().min(1), z.number().finite()])\n .transform((value) => new Decimal(value))\n .refine((value) => value.isFinite() && !value.isNegative(), \"expected a non-negative decimal\");\n\nconst ProfileRowSchema = z\n .object({\n subject_id: postgresUuid,\n enabled: pgBoolean,\n armed: pgBoolean,\n state: z.enum([\"disabled\", \"active\", \"paused\"]),\n provider: z.string().min(1).nullable(),\n topup_id: postgresUuid.nullable(),\n quantity: positiveInteger,\n threshold: decimal,\n max_charges_per_window: positiveInteger.nullable(),\n window_unit: z.enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"]),\n window_count: positiveInteger,\n window_anchor: z.enum([\"calendar\", \"rolling\"]),\n window_timezone: z.string().min(1),\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.enabled !== (row.state !== \"disabled\")) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"enabled and state are inconsistent\" });\n }\n if (row.enabled && (row.provider === null || row.topup_id === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"enabled profile requires provider and topup_id\",\n });\n }\n });\n\nconst AttemptStateSchema = z.enum([\n \"claimed\",\n \"submitted\",\n \"processing\",\n \"unknown\",\n \"succeeded\",\n \"failed\",\n \"action_required\",\n]);\nconst AttemptRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n idempotency_key: z.string().min(1),\n provider_attempt_id: z.string().min(1).nullable(),\n topup_id: postgresUuid,\n quantity: positiveInteger,\n state: AttemptStateSchema,\n window_start: timestamp,\n window_end: timestamp,\n quoted_amount_minor: safeNonnegativeInteger.nullable(),\n currency: z\n .string()\n .regex(/^[A-Z]{3}$/)\n .nullable(),\n failure_code: z.string().min(1).nullable(),\n failure_message: z.string().min(1).nullable(),\n metadata: z.record(z.string(), z.json()),\n created_at: timestamp,\n updated_at: timestamp,\n })\n .strict()\n .superRefine((row, ctx) => {\n if (new Date(row.window_end).getTime() <= new Date(row.window_start).getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"window_end must be later than window_start\",\n });\n }\n if ((row.quoted_amount_minor === null) !== (row.currency === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"quoted_amount_minor and currency must be present together\",\n });\n }\n });\n\ntype AttemptTransitionPath = readonly BillingAutoRechargeAttemptState[];\n\nfunction attemptTransitions(\n entries: ReadonlyArray<readonly [BillingAutoRechargeAttemptState, AttemptTransitionPath]>,\n): ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath> {\n return new Map(entries);\n}\n\nconst ATTEMPT_TRANSITION_PATHS = new Map<\n BillingAutoRechargeAttemptState,\n ReadonlyMap<BillingAutoRechargeAttemptState, AttemptTransitionPath>\n>([\n [\n \"claimed\",\n attemptTransitions([\n [\"submitted\", [\"submitted\"]],\n [\"processing\", [\"submitted\", \"processing\"]],\n [\"succeeded\", [\"submitted\", \"processing\", \"succeeded\"]],\n [\"failed\", [\"submitted\", \"processing\", \"failed\"]],\n [\"unknown\", [\"submitted\", \"processing\", \"unknown\"]],\n [\"action_required\", [\"submitted\", \"action_required\"]],\n ]),\n ],\n [\n \"submitted\",\n attemptTransitions([\n [\"submitted\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"processing\", \"succeeded\"]],\n [\"failed\", [\"processing\", \"failed\"]],\n [\"unknown\", [\"processing\", \"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"processing\",\n attemptTransitions([\n [\"processing\", []],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"unknown\", [\"unknown\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"unknown\",\n attemptTransitions([\n [\"unknown\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n [\"action_required\", [\"action_required\"]],\n ]),\n ],\n [\n \"action_required\",\n attemptTransitions([\n [\"action_required\", []],\n [\"processing\", [\"processing\"]],\n [\"succeeded\", [\"succeeded\"]],\n [\"failed\", [\"failed\"]],\n ]),\n ],\n]);\n\nfunction projectProfile(row: PostgresRow) {\n return {\n subject_id: row.subject_id,\n enabled: row.enabled,\n armed: row.armed,\n state: row.state,\n provider: row.provider,\n topup_id: row.topup_id,\n quantity: row.quantity,\n threshold: row.threshold,\n max_charges_per_window: row.max_charges_per_window,\n window_unit: row.window_unit,\n window_count: row.window_count,\n window_anchor: row.window_anchor,\n window_timezone: row.window_timezone,\n updated_at: row.updated_at,\n };\n}\n\nfunction projectAttempt(row: PostgresRow) {\n return {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n idempotency_key: row.idempotency_key,\n provider_attempt_id: row.provider_attempt_id,\n topup_id: row.topup_id,\n quantity: row.quantity,\n state: row.state,\n window_start: row.window_start,\n window_end: row.window_end,\n quoted_amount_minor: row.quoted_amount_minor,\n currency: row.currency,\n failure_code: row.failure_code,\n failure_message: row.failure_message,\n metadata: row.metadata,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\nfunction profileFromRow(row: PostgresRow): BillingAutoRechargeProfile {\n const parsed = safeParse(\n ProfileRowSchema,\n projectProfile(row),\n \"BillingAutoRechargeRepository.profile\",\n );\n return {\n userId: parsed.subject_id,\n enabled: parsed.enabled,\n armed: parsed.armed,\n state: parsed.state,\n provider: parsed.provider,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n threshold: parsed.threshold,\n maxChargesPerWindow: parsed.max_charges_per_window,\n windowUnit: parsed.window_unit,\n windowCount: parsed.window_count,\n windowAnchor: parsed.window_anchor,\n windowTimezone: parsed.window_timezone,\n updatedAt: parsed.updated_at,\n };\n}\n\nfunction attemptFromRow(row: PostgresRow): BillingAutoRechargeAttempt {\n const parsed = safeParse(\n AttemptRowSchema,\n projectAttempt(row),\n \"BillingAutoRechargeRepository.attempt\",\n );\n return {\n id: parsed.id,\n userId: parsed.subject_id,\n provider: parsed.provider,\n idempotencyKey: parsed.idempotency_key,\n providerAttemptId: parsed.provider_attempt_id,\n topupId: parsed.topup_id,\n quantity: parsed.quantity,\n state: parsed.state,\n windowStart: parsed.window_start,\n windowEnd: parsed.window_end,\n quotedAmountMinor: parsed.quoted_amount_minor,\n currency: parsed.currency,\n failureCode: parsed.failure_code,\n failureMessage: parsed.failure_message,\n metadata: parsed.metadata,\n createdAt: parsed.created_at,\n updatedAt: parsed.updated_at,\n };\n}\n\nexport class BillingAutoRechargeRepository {\n constructor(private readonly query: QueryFn) {}\n\n async getProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_auto_recharge_profile($1::uuid)\", [\n userId,\n ]);\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.getProfile\");\n return row === null ? null : profileFromRow(row);\n }\n\n async upsertProfile(\n profile: BillingAutoRechargeProfile,\n options: { resetCooldown?: boolean } = {},\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_auto_recharge_profile(\n $1::uuid, $2, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14\n ) AS updated`,\n [\n profile.userId,\n profile.enabled,\n profile.provider,\n profile.topupId,\n profile.quantity,\n profile.threshold.toString(),\n profile.maxChargesPerWindow,\n profile.windowUnit,\n profile.windowCount,\n profile.windowAnchor,\n profile.windowTimezone,\n profile.armed,\n profile.state,\n options.resetCooldown ?? false,\n ],\n );\n if (\n !requireResultField(rows, \"updated\", pgBoolean, \"BillingAutoRechargeRepository.upsertProfile\")\n ) {\n throw new StoreError(`auto-recharge profile update rejected: ${profile.userId}`);\n }\n }\n\n async claimAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null> {\n const rows = await this.query(\n \"SELECT * FROM bursar.claim_auto_recharge_attempt($1::uuid, $2)\",\n [input.userId, input.idempotencyKey],\n );\n const row = optionalRecordRow(rows, \"BillingAutoRechargeRepository.claimAttempt\");\n return row === null ? null : attemptFromRow(row);\n }\n\n private async advanceAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n const failureMessage = optionalBoundedDiagnosticMessage(input.failureMessage);\n const currentRows = await this.query(\n \"SELECT * FROM bursar.get_auto_recharge_attempt($1::uuid)\",\n [input.id],\n );\n const currentRow = optionalRecordRow(\n currentRows,\n \"BillingAutoRechargeRepository.advanceAttempt.current\",\n );\n if (currentRow === null) {\n throw new StoreError(`auto-recharge attempt not found: ${input.id}`, {\n details: { attemptId: input.id },\n });\n }\n const current = safeParse(\n AttemptStateSchema,\n currentRow.state,\n \"BillingAutoRechargeRepository.advanceAttempt.current.state\",\n );\n const path = ATTEMPT_TRANSITION_PATHS.get(current)?.get(input.state);\n if (!path) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, currentState: current, requestedState: input.state },\n });\n }\n for (const state of path) {\n const rows = await this.query(\n `SELECT bursar.advance_auto_recharge_attempt(\n $1::uuid,\n $2::bursar.recharge_attempt_status,\n $3,\n $4,\n $5,\n $6::jsonb\n ) AS advanced`,\n [\n input.id,\n state,\n input.providerAttemptId ?? null,\n input.failureCode ?? null,\n failureMessage,\n JSON.stringify(input.metadata ?? {}),\n ],\n );\n if (\n !requireResultField(\n rows,\n \"advanced\",\n pgBoolean,\n \"BillingAutoRechargeRepository.advanceAttempt\",\n )\n ) {\n throw new StoreError(`auto-recharge attempt transition rejected: ${input.id}`, {\n details: { attemptId: input.id, requestedState: state },\n });\n }\n }\n }\n\n async updateAttempt(input: {\n id: string;\n state: BillingAutoRechargeAttemptState;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: JsonObject;\n }): Promise<void> {\n return this.advanceAttempt(input);\n }\n\n async updateAttemptByProviderPayment(input: {\n provider: string;\n providerPaymentId: string;\n state: BillingAutoRechargeAttemptState;\n failureCode?: string | null;\n failureMessage?: string | null;\n }): Promise<void> {\n const rows = await this.query(\n `SELECT * FROM bursar.get_auto_recharge_attempt_by_provider($1, $2)`,\n [input.provider, input.providerPaymentId],\n );\n const row = optionalRecordRow(\n rows,\n \"BillingAutoRechargeRepository.updateAttemptByProviderPayment\",\n );\n if (row === null) return;\n const attempt = attemptFromRow(row);\n await this.advanceAttempt({\n id: attempt.id,\n state: input.state,\n providerAttemptId: input.providerPaymentId,\n failureCode: input.failureCode,\n failureMessage: input.failureMessage,\n });\n }\n\n async countAttempts(userId: string, since: string | Date): Promise<number> {\n const sinceDate = since instanceof Date ? since : new Date(since);\n if (Number.isNaN(sinceDate.getTime())) {\n throw new TypeError(\"auto-recharge attempt boundary must be a valid instant\");\n }\n const rows = await this.query(\n `SELECT bursar.count_auto_recharge_attempts($1::uuid, $2::timestamptz) AS count`,\n [userId, sinceDate.toISOString()],\n );\n return requireResultField(\n rows,\n \"count\",\n z\n .union([z.number(), z.string().regex(/^\\d+$/)])\n .transform(Number)\n .pipe(z.number().int().nonnegative().safe()),\n \"BillingAutoRechargeRepository.countAttempts\",\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAiBjE,qBAAa,yBAAyB;IACxB,OAAO,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAiBjE,qBAAa,yBAAyB;IACxB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,EAC1B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,GACnB,OAAO,CAAC,IAAI,CAAC,CAMf;IAEK,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAS9E;IAEK,WAAW,CACf,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,kBAAkB,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CASlE;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/customer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACjC,UAAU,EAAE,YAAY;CACzB,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAA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AC,+DAA+D,EAAE;YAC7F,QAAQ;YACR,kBAAkB;SACnB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,+BAA+B,CAAC,CAAC;QACrE,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,iBAAiB,EAAE,GAAG,EAAE,+BAA+B,CAAC,CAAC,UAAU,CAAC;IACpF,CAAC;IAED,KAAK,CAAC,WAAW,CACf,MAAc,EACd,QAAwB;QAExB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,yDAAyD,EAAE;YACvF,MAAM;YACN,QAAQ,IAAI,IAAI;SACjB,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,uCAAuC,CAAC,CAAC;QAC7E,IAAI,GAAG,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,SAAS,CAAC,uBAAuB,EAAE,GAAG,EAAE,uCAAuC,CAAC,CAAC;QAChG,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,kBAAkB,EAAE,MAAM,CAAC,oBAAoB,EAAE,CAAC;IACxF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireResultField,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst CustomerRowSchema = z.object({\n subject_id: postgresUuid,\n});\n\nconst CustomerByUserRowSchema = z.object({\n provider: z.string().min(1),\n provider_customer_id: z.string().min(1),\n});\n\nexport class BillingCustomerRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email: string | null,\n ): Promise<void> {\n const rows = await this.query(\n \"SELECT bursar.upsert_billing_customer($1::uuid, $2, $3, $4) AS id\",\n [userId, provider, providerCustomerId, email],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingCustomerRepository.upsert\");\n }\n\n async get(provider: string, providerCustomerId: string): Promise<string | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer_by_provider($1, $2)\", [\n provider,\n providerCustomerId,\n ]);\n const row = optionalRecordRow(rows, \"BillingCustomerRepository.get\");\n return row === null\n ? null\n : safeParse(CustomerRowSchema, row, \"BillingCustomerRepository.get\").subject_id;\n }\n\n async getByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<{ provider: string; providerCustomerId: string } | null> {\n const rows = await this.query(\"SELECT * FROM bursar.get_billing_customer($1::uuid, $2)\", [\n userId,\n provider ?? null,\n ]);\n const row = optionalRecordRow(rows, \"BillingCustomerRepository.getByUserId\");\n if (row === null) return null;\n const parsed = safeParse(CustomerByUserRowSchema, row, \"BillingCustomerRepository.getByUserId\");\n return { provider: parsed.provider, providerCustomerId: parsed.provider_customer_id };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispute.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAG1D,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"dispute.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAG1D,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,QAAQ,EAAE,UAAU,EACpB,iBAAiB,EAAE,MAAM,GACxB,OAAO,CAAC,IAAI,CAAC,CAcf;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispute.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AAE1F,MAAM,OAAO,wBAAwB;IACf;
|
|
1
|
+
{"version":3,"file":"dispute.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/dispute.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AAE1F,MAAM,OAAO,wBAAwB;IACf,KAAK;IAAzB,YAAoB,KAAc;qBAAd,KAAK;IAAY,CAAC;IAEtC,KAAK,CAAC,MAAM,CACV,QAAgB,EAChB,iBAAyB,EACzB,SAAiB,EACjB,MAAc,EACd,MAAqB,EACrB,QAAoB,EACpB,iBAAyB;QAEzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,qFAAqF,EACrF;YACE,QAAQ;YACR,iBAAiB;YACjB,SAAS;YACT,MAAM;YACN,MAAM;YACN,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 type { QueryFn } from \"../../../shared/postgres-types.js\";\nimport type { JsonObject } from \"../../../shared/json.js\";\nimport { postgresUuid, requireResultField } from \"../../../shared/postgres-validation.js\";\n\nexport class BillingDisputeRepository {\n constructor(private query: QueryFn) {}\n\n async upsert(\n provider: string,\n providerDisputeId: string,\n paymentId: string,\n status: string,\n reason: string | null,\n metadata: JsonObject,\n providerUpdatedAt: string,\n ): Promise<void> {\n const rows = await this.query(\n `SELECT bursar.upsert_billing_dispute($1, $2, $3::uuid, $4, $5, $6::jsonb, $7) AS id`,\n [\n provider,\n providerDisputeId,\n paymentId,\n status,\n reason,\n JSON.stringify(metadata),\n providerUpdatedAt,\n ],\n );\n requireResultField(rows, \"id\", postgresUuid, \"BillingDisputeRepository.upsert\");\n }\n}\n"]}
|
|
@@ -2,11 +2,11 @@ import { z } from "zod";
|
|
|
2
2
|
import type { QueryFn } from "../../../shared/postgres-types.js";
|
|
3
3
|
declare const BillingEventRowSchema: z.ZodObject<{
|
|
4
4
|
status: z.ZodEnum<{
|
|
5
|
-
|
|
5
|
+
busy: "busy";
|
|
6
6
|
claimed: "claimed";
|
|
7
7
|
duplicate: "duplicate";
|
|
8
|
-
busy: "busy";
|
|
9
8
|
idempotency_conflict: "idempotency_conflict";
|
|
9
|
+
invalid_request: "invalid_request";
|
|
10
10
|
max_retries_exceeded: "max_retries_exceeded";
|
|
11
11
|
}>;
|
|
12
12
|
event_id: z.ZodNullable<z.ZodString>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAUjE,QAAA,MAAM,qBAAqB;;;;;;;;;;;kBA6CvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAMpE,yDAAyD;AACzD,qBAAa,sBAAsB;IACrB,OAAO,CAAC,KAAK;
|
|
1
|
+
{"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAUjE,QAAA,MAAM,qBAAqB;;;;;;;;;;;kBA6CvB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAMpE,yDAAyD;AACzD,qBAAa,sBAAsB;IACrB,OAAO,CAAC,KAAK;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEtC,+DAA+D;IACzD,KAAK,CACT,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,eAAe,CAAC,CAc1B;IAED,yCAAyC;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMtF;IAED,sCAAsC;IAChC,IAAI,CACR,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,CAAC,CAMlB;CACF"}
|
|
@@ -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;AAGxB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,MAAM,qBAAqB,GAAG,CAAC;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC;QACb,SAAS;QACT,WAAW;QACX,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,sBAAsB;KACvB,CAAC;IACF,QAAQ,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AAG,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAC3D,CAAC;AAED,yDAAyD;AACzD,MAAM,OAAO,sBAAsB;IACb;
|
|
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;KAC5B,MAAM,CAAC;IACN,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC;QACb,SAAS;QACT,WAAW;QACX,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,sBAAsB;KACvB,CAAC;IACF,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE;IACjC,WAAW,EAAE,YAAY,CAAC,QAAQ,EAAE;CACrC,CAAC;KACD,MAAM,EAAE;KACR,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAC7B,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;YACtD,GAAG,CAAC,QAAQ,CAAC;gBACX,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;gBAC3B,OAAO,EAAE,yDAAyD;aACnE,CAAC,CAAC;QACL,CAAC;QACD,OAAO;IACT,CAAC;IACD,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;QAC7B,GAAG,CAAC,QAAQ,CAAC;YACX,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;YAC3B,OAAO,EAAE,qDAAqD;SAC/D,CAAC,CAAC;IACL,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE,CAA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,QAAQ,CAAC,QAAgB,EAAE,OAAe,EAAE,UAAkB;QAClE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAC3B,qEAAqE,EACrE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,CAChC,CAAC;QACF,OAAO,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,iCAAiC,CAAC,CAAC;IAC7E,CAAC;IAED,sCAAsC;IACtC,KAAK,CAAC,IAAI,CACR,QAAgB,EAChB,OAAe,EACf,UAAkB,EAClB,KAAc;QAEd,MAAM,IAAI,GAAG,MAAM,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 +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,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAgCjE,qBAAa,wBAAwB;IACvB,OAAO,CAAC,KAAK;
|
|
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;IAAzB,YAAoB,KAAK,EAAE,OAAO,EAAI;IAEhC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CA4BjE;IAEK,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,CAmBf;CACF"}
|
|
@@ -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;AAIxB,OAAO,EACL,YAAY,EACZ,kB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M;gBACrB,eAAe,EAAE,MAAM,CAAC,iBAAiB;gBACzC,cAAc,EAAE,MAAM,CAAC,gBAAgB;gBACvC,QAAQ,EAAE,MAAM,CAAC,QAAQ;gBACzB,WAAW,EAAE,MAAM,CAAC,YAAY;gBAChC,SAAS,EAAE,MAAM,CAAC,UAAU;aACE,CAAC;QACnC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CACV,SAAiB,EACjB,QAAgB,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,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;
|
|
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,Q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EAAE;aAC7E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,aAAa,GAAwB;YACzC,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,MAAM,EAAE,YAAY,CAAC,OAAO;YAC5B,QAAQ,EAAE,KAAK,CAAC,SAAS;YACzB,IAAI,EAAE,KAAK,CAAC,QAAQ;YACpB,QAAQ,EAAE,KAAK,CAAC,YAAY;YAC5B,aAAa,EAAE,KAAK,CAAC,aAAa;SACnC,CAAC;QACF,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACtC,OAAO;gBACL,GAAG,aAAa;gBAChB,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;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];\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"]}
|
|
1
|
+
{"version":3,"file":"offer.js","sourceRoot":"","sources":["../../../../src/billing/postgres/repositories/offer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,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,QAA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CAAC,QAAQ;YACpB,QAAQ,EAAE,KAAK,CAAC,YAAY;YAC5B,aAAa,EAAE,KAAK,CAAC,aAAa;SACnC,CAAC;QACF,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACtC,OAAO;gBACL,GAAG,aAAa;gBAChB,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;gBACjB,iBAAiB,EAAE,KAAK;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,sBAAsB,KAAK,IAAI,IAAI,KAAK,CAAC,mBAAmB,KAAK,IAAI,EAAE,CAAC;YAChF,MAAM,IAAI,UAAU,CAAC,GAAG,OAAO,gDAAgD,EAAE;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];\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"]}
|