@zonastery/bursar 2.0.1 → 2.0.2
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 +21 -14
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +6 -4
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +3 -0
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js +2 -0
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +2 -3
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +38 -49
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.js +4 -4
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +2 -2
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +7 -7
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +5 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +5 -0
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.d.ts +2 -15
- package/dist/billing/service-types.d.ts.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/events.d.ts +3 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +2 -2
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/bursar.d.ts +21 -11
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +40 -4
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/index.d.ts +0 -1
- package/dist/commerce/index.d.ts.map +1 -1
- package/dist/commerce/index.js +0 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +99 -59
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +8 -4
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +0 -6
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/types.d.ts +0 -5
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +7 -0
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +8 -0
- package/dist/credits/amount.d.ts.map +1 -0
- package/dist/credits/amount.js +32 -0
- package/dist/credits/amount.js.map +1 -0
- package/dist/credits/catalog-runtime.d.ts +4 -6
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +3 -12
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +23 -20
- 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 +2 -3
- package/dist/credits/low-balance-monitor.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/store.d.ts +15 -11
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +24 -15
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/service-types.d.ts +17 -15
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +16 -17
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +61 -33
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +16 -22
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +3 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +1 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/parser.d.ts +1 -0
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js +15 -3
- package/dist/expr/parser.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +31 -29
- package/dist/generated/pricing-config.types.d.ts +6 -18
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -3
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +14 -29
- package/dist/load-config-file.js.map +1 -1
- package/dist/providers/_shared.js +1 -1
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +3 -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.d.ts +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +5 -13
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +4 -6
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +22 -71
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js +0 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +6 -0
- package/dist/providers/environment.d.ts.map +1 -0
- package/dist/providers/environment.js +10 -0
- package/dist/providers/environment.js.map +1 -0
- package/dist/providers/index.d.ts +3 -7
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +1 -5
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/provider.d.ts +6 -8
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +18 -50
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.js +11 -11
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts +3 -3
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +37 -24
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +9 -19
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/idempotency.d.ts +9 -0
- package/dist/shared/idempotency.d.ts.map +1 -0
- package/dist/shared/idempotency.js +34 -0
- package/dist/shared/idempotency.js.map +1 -0
- package/dist/shared/postgres-client.d.ts +4 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +6 -2
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +22 -21
- 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 +67 -46
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +11 -7
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +52 -8
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +52 -36
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-processor.js","sourceRoot":"","sources":["../../src/billing/event-processor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAGtD,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAEpE,MAAM,OAAO,qBAAqB;IAcb;IAbF,aAAa,CAAyD;IACtE,MAAM,CAAmB;IACzB,QAAQ,CAAuB;IAC/B,mBAAmB,GAA0B,IAAI,GAAG,CAAC;QACpE,gBAAgB,CAAC,gBAAgB;QACjC,gBAAgB,CAAC,gBAAgB;KAClC,CAAC,CAAC;IAEH,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;IACvC,CAAC;IAED,YACmB,KAAmB,EACpC,OAA+B;QADd,UAAK,GAAL,KAAK,CAAc;QAGpC,IAAI,CAAC,aAAa,GAAG,OAAO,EAAE,aAAa,IAAI,EAAE,CAAC;QAClD,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,IAAI,oBAAoB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC;IAED,oFAAoF;IACpF,oBAAoB;QAClB,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qCAAqC,EAAE;YACvD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AAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport { normalizeLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { BillingEvent, BillingEventHandler, BillingEventResult } from \"./types/index.js\";\nimport { assertBillingEvent, BillingEventType } from \"./types/index.js\";\nimport { BillingEventHandlers } from \"./event-handlers.js\";\nimport type { BillingServiceOptions } from \"./service-types.js\";\nimport { boundedDiagnosticMessage } from \"../shared/diagnostics.js\";\n\nexport class BillingEventProcessor {\n private readonly eventHandlers: Partial<Record<BillingEventType, BillingEventHandler>>;\n private readonly logger: NormalizedLogger;\n private readonly handlers: BillingEventHandlers;\n private readonly IGNORED_EVENT_TYPES: Set<BillingEventType> = new Set([\n BillingEventType.CHECKOUT_EXPIRED,\n BillingEventType.INVOICE_UPCOMING,\n ]);\n\n get hasProvisioning(): boolean {\n return this.handlers.hasProvisioning;\n }\n\n constructor(\n private readonly store: BillingStore,\n options?: BillingServiceOptions,\n ) {\n this.eventHandlers = options?.eventHandlers ?? {};\n this.logger = normalizeLogger(options?.logger);\n this.handlers = new BillingEventHandlers(store, options);\n }\n\n /** Invalidate the offer cache so the next resolution call re-fetches fresh data. */\n invalidateOfferCache(): void {\n this.handlers.invalidateOfferCache();\n }\n\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n assertBillingEvent(event);\n this.logger.debug(\"[BillingService] ingestBillingEvent\", {\n eventId: event.eventId,\n provider: event.provider,\n eventType: event.eventType,\n });\n const claimEnvelope = { ...event } as Record<string, unknown>;\n delete claimEnvelope[\"occurredAt\"];\n delete claimEnvelope[\"raw\"];\n delete claimEnvelope[\"billingEventId\"];\n const claim = await this.store.claimBillingEvent(\n event.provider,\n event.eventId,\n event.eventType,\n claimEnvelope,\n );\n this.logger.debug(\"[BillingService] claim status\", {\n status: claim.status,\n eventId: event.eventId,\n });\n\n if (claim.status === \"duplicate\") {\n this.logger.debug(\"[BillingService] duplicate event\", { eventId: event.eventId });\n return { handled: true, action: \"duplicate\" };\n }\n if (claim.status === \"busy\") {\n this.logger.debug(\"[BillingService] event is already processing\", { eventId: event.eventId });\n return { handled: false, error: \"claim_busy\" };\n }\n if (claim.status === \"retry\") {\n this.logger.warn(\"[BillingService] claim retry\", { eventId: event.eventId });\n return { handled: false, error: \"claim_failed_retry\" };\n }\n\n let result: BillingEventResult;\n try {\n result = await this.routeEvent({\n ...event,\n billingEventId: claim.billingEventId,\n });\n this.logger.debug(\"[BillingService] routeEvent result\", { result, eventId: event.eventId });\n } catch (err) {\n return this.recordBillingEventFailure(event, claim.claimToken, err);\n }\n\n if (!result.handled) {\n const message = boundedDiagnosticMessage(result.error, \"billing_event_not_handled\");\n await this.recordBillingEventFailure(event, claim.claimToken, message, false);\n return { ...result, error: message };\n }\n\n let completed: boolean;\n try {\n completed = await this.store.completeBillingEvent(\n event.provider,\n event.eventId,\n claim.claimToken,\n );\n } catch (err) {\n return this.recordBillingEventFailure(event, claim.claimToken, err);\n }\n\n if (!completed) {\n return this.recordBillingEventFailure(\n event,\n claim.claimToken,\n \"billing_event_completion_rejected\",\n );\n }\n return result;\n }\n\n private async recordBillingEventFailure(\n event: BillingEvent,\n claimToken: string,\n error: unknown,\n logAsError = true,\n ): Promise<BillingEventResult> {\n const message = boundedDiagnosticMessage(error, \"billing_event_processing_failed\");\n const log = logAsError ? this.logger.error : this.logger.warn;\n log(`[BillingService] failed to handle billing event ${event.provider}/${event.eventId}`, {\n error: message,\n });\n const failed = await this.store.failBillingEvent(\n event.provider,\n event.eventId,\n claimToken,\n message,\n );\n if (!failed) {\n this.logger.warn(\"[BillingService] billing event failure was not persisted\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n }\n return { handled: false, error: message };\n }\n\n private async routeEvent(event: BillingEvent): Promise<BillingEventResult> {\n const handler = this.handlers.getHandler(event.eventType);\n if (!handler) {\n if (this.IGNORED_EVENT_TYPES.has(event.eventType)) {\n if (event.eventType === BillingEventType.CHECKOUT_EXPIRED) {\n await this.handlers.updateCheckoutIntentFromEvent(event, \"expired\");\n }\n return { handled: true, action: \"ignored\" };\n }\n return { handled: false, error: \"unhandled_event_type\" };\n }\n const result = await handler(event);\n if (result.handled) {\n await this.fireEventHandlers(event, event.userId ?? null);\n }\n return result;\n }\n\n private async fireEventHandlers(event: BillingEvent, userId: string | null): Promise<void> {\n if (!userId) return;\n const handler = this.eventHandlers[event.eventType];\n if (!handler) return;\n try {\n await handler(event, userId);\n } catch (err) {\n this.logger.error(\n `[BillingService] event handler failed for ${event.provider}/${event.eventId}`,\n { error: err instanceof Error ? err.message : String(err) },\n );\n }\n }\n\n async revokeIfCurrentSubscription(userId: string, subscriptionId: string): Promise<void> {\n await this.handlers.revokeIfCurrentSubscription(userId, subscriptionId);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"event-processor.js","sourceRoot":"","sources":["../../src/billing/event-processor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAGtD,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAEpE,MAAM,OAAO,qBAAqB;IAcb;IAbF,aAAa,CAAyD;IACtE,MAAM,CAAmB;IACzB,QAAQ,CAAuB;IAC/B,mBAAmB,GAA0B,IAAI,GAAG,CAAC;QACpE,gBAAgB,CAAC,gBAAgB;QACjC,gBAAgB,CAAC,gBAAgB;KAClC,CAAC,CAAC;IAEH,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC;IACvC,CAAC;IAED,YACmB,KAAmB,EACpC,OAA+B;QADd,UAAK,GAAL,KAAK,CAAc;QAGpC,IAAI,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AAC,OAAO;YAAE,OAAO;QACrB,IAAI,CAAC;YACH,MAAM,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;QAClC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,6CAA6C,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,EAAE,EAC9E,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC5D,CAAC;QACJ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,2BAA2B,CAAC,MAAc,EAAE,cAAsB;QACtE,MAAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import type { NormalizedLogger } from \"../shared/logger.js\";\nimport { normalizeLogger } from \"../shared/logger.js\";\nimport type { BillingStore } from \"./billing-store.js\";\nimport type { BillingEvent, BillingEventHandler, BillingEventResult } from \"./types/index.js\";\nimport { assertBillingEvent, BillingEventType } from \"./types/index.js\";\nimport { BillingEventHandlers } from \"./event-handlers.js\";\nimport type { BillingServiceOptions } from \"./service-types.js\";\nimport { boundedDiagnosticMessage } from \"../shared/diagnostics.js\";\n\nexport class BillingEventProcessor {\n private readonly eventHandlers: Partial<Record<BillingEventType, BillingEventHandler>>;\n private readonly logger: NormalizedLogger;\n private readonly handlers: BillingEventHandlers;\n private readonly IGNORED_EVENT_TYPES: Set<BillingEventType> = new Set([\n BillingEventType.CHECKOUT_EXPIRED,\n BillingEventType.INVOICE_UPCOMING,\n ]);\n\n get hasProvisioning(): boolean {\n return this.handlers.hasProvisioning;\n }\n\n constructor(\n private readonly store: BillingStore,\n options?: BillingServiceOptions,\n ) {\n this.eventHandlers = options?.eventHandlers ?? {};\n this.logger = normalizeLogger(options?.logger);\n this.handlers = new BillingEventHandlers(store, options);\n }\n\n /** Invalidate the offer cache so the next resolution call re-fetches fresh data. */\n invalidateOfferCache(): void {\n this.handlers.invalidateOfferCache();\n }\n\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n assertBillingEvent(event);\n this.logger.debug(\"[BillingService] ingestBillingEvent\", {\n eventId: event.eventId,\n provider: event.provider,\n eventType: event.eventType,\n });\n const claimEnvelope = { ...event } as Record<string, unknown>;\n delete claimEnvelope[\"occurredAt\"];\n delete claimEnvelope[\"raw\"];\n delete claimEnvelope[\"billingEventId\"];\n const claim = await this.store.claimBillingEvent(\n event.provider,\n event.eventId,\n event.eventType,\n claimEnvelope,\n );\n this.logger.debug(\"[BillingService] claim status\", {\n status: claim.status,\n eventId: event.eventId,\n });\n\n if (claim.status === \"duplicate\") {\n this.logger.debug(\"[BillingService] duplicate event\", { eventId: event.eventId });\n return { handled: true, action: \"duplicate\" };\n }\n if (claim.status === \"busy\") {\n this.logger.debug(\"[BillingService] event is already processing\", { eventId: event.eventId });\n return { handled: false, error: \"claim_busy\" };\n }\n if (claim.status === \"retry\") {\n this.logger.warn(\"[BillingService] claim retry\", { eventId: event.eventId });\n return { handled: false, error: \"claim_failed_retry\" };\n }\n\n let result: BillingEventResult;\n try {\n result = await this.routeEvent({\n ...event,\n billingEventId: claim.billingEventId,\n });\n this.logger.debug(\"[BillingService] routeEvent result\", { result, eventId: event.eventId });\n } catch (err) {\n return this.recordBillingEventFailure(event, claim.claimToken, err);\n }\n\n if (!result.handled) {\n const message = boundedDiagnosticMessage(result.error, \"billing_event_not_handled\");\n await this.recordBillingEventFailure(event, claim.claimToken, message, false);\n return { ...result, error: message };\n }\n\n let completed: boolean;\n try {\n completed = await this.store.completeBillingEvent(\n event.provider,\n event.eventId,\n claim.claimToken,\n );\n } catch (err) {\n return this.recordBillingEventFailure(event, claim.claimToken, err);\n }\n\n if (!completed) {\n return this.recordBillingEventFailure(\n event,\n claim.claimToken,\n \"billing_event_completion_rejected\",\n );\n }\n return result;\n }\n\n private async recordBillingEventFailure(\n event: BillingEvent,\n claimToken: string,\n error: unknown,\n logAsError = true,\n ): Promise<BillingEventResult> {\n const message = boundedDiagnosticMessage(error, \"billing_event_processing_failed\");\n const log = logAsError ? this.logger.error : this.logger.warn;\n log(`[BillingService] failed to handle billing event ${event.provider}/${event.eventId}`, {\n error: message,\n });\n const failed = await this.store.failBillingEvent(\n event.provider,\n event.eventId,\n claimToken,\n message,\n );\n if (!failed) {\n this.logger.warn(\"[BillingService] billing event failure was not persisted\", {\n provider: event.provider,\n eventId: event.eventId,\n });\n }\n return { handled: false, error: message };\n }\n\n private async routeEvent(event: BillingEvent): Promise<BillingEventResult> {\n const handler = this.handlers.getHandler(event.eventType);\n if (!handler) {\n if (this.IGNORED_EVENT_TYPES.has(event.eventType)) {\n if (event.eventType === BillingEventType.CHECKOUT_EXPIRED) {\n await this.handlers.updateCheckoutIntentFromEvent(event, \"expired\");\n }\n return { handled: true, action: \"ignored\" };\n }\n return { handled: false, error: \"unhandled_event_type\" };\n }\n const result = await handler(event);\n if (result.handled) {\n await this.fireEventHandlers(event, event.accountId ?? null);\n }\n return result;\n }\n\n private async fireEventHandlers(event: BillingEvent, accountId: string | null): Promise<void> {\n if (!accountId) return;\n const handler = this.eventHandlers[event.eventType];\n if (!handler) return;\n try {\n await handler(event, accountId);\n } catch (err) {\n this.logger.error(\n `[BillingService] event handler failed for ${event.provider}/${event.eventId}`,\n { error: err instanceof Error ? err.message : String(err) },\n );\n }\n }\n\n async revokeIfCurrentSubscription(userId: string, subscriptionId: string): Promise<void> {\n await this.handlers.revokeIfCurrentSubscription(userId, subscriptionId);\n }\n}\n"]}
|
|
@@ -10,12 +10,12 @@ export declare class BillingFinancialEventHandlers {
|
|
|
10
10
|
private readonly store;
|
|
11
11
|
private readonly logger;
|
|
12
12
|
private readonly pastDueGracePeriodMs;
|
|
13
|
-
private readonly
|
|
13
|
+
private readonly resolveAccountId;
|
|
14
14
|
private readonly handleSubscriptionRenewed;
|
|
15
15
|
private readonly updateCheckoutIntentFromEvent;
|
|
16
16
|
private readonly getExistingSubscription;
|
|
17
17
|
private readonly buildSubscriptionState;
|
|
18
|
-
constructor(store: BillingStore, logger: NormalizedLogger, pastDueGracePeriodMs: number,
|
|
18
|
+
constructor(store: BillingStore, logger: NormalizedLogger, pastDueGracePeriodMs: number, resolveAccountId: (event: BillingEvent) => Promise<string | null>, handleSubscriptionRenewed: (event: BillingEvent) => Promise<BillingEventResult>, updateCheckoutIntentFromEvent: (event: BillingEvent, status: "completed" | "failed" | "expired") => Promise<void>, getExistingSubscription: (event: BillingEvent) => Promise<BillingSubscriptionState | null>, buildSubscriptionState: (event: BillingEvent, userId: string, existing: BillingSubscriptionState | null, overrides?: FinancialSubscriptionOverrides) => BillingSubscriptionState);
|
|
19
19
|
handleInvoicePaid(event: BillingEvent): Promise<BillingEventResult>;
|
|
20
20
|
handlePaymentSucceeded(event: BillingEvent): Promise<BillingEventResult>;
|
|
21
21
|
handlePaymentFailed(event: BillingEvent): Promise<BillingEventResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"financial-event-handlers.d.ts","sourceRoot":"","sources":["../../src/billing/financial-event-handlers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EACV,YAAY,EACZ,kBAAkB,EAClB,wBAAwB,EACxB,yBAAyB,EAE1B,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,8BAA8B;IAC7C,MAAM,CAAC,EAAE,yBAAyB,GAAG,IAAI,CAAC;IAC1C,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,qBAAa,6BAA6B;IAEtC,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CA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AE,WAAW,GAAG,QAAQ,GAAG,SAAS,KACvC,OAAO,CAAC,IAAI,CAAC,EACD,uBAAuB,EAAE,CACxC,KAAK,EAAE,YAAY,KAChB,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC,EAC5B,sBAAsB,EAAE,CACvC,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,wBAAwB,GAAG,IAAI,EACzC,SAAS,CAAC,EAAE,8BAA8B,KACvC,wBAAwB;IAGzB,iBAAiB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IA+BnE,sBAAsB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAoGxE,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IA2CrE,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAuCrE,oBAAoB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IActE,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAa5E"}
|
|
@@ -2,16 +2,16 @@ export class BillingFinancialEventHandlers {
|
|
|
2
2
|
store;
|
|
3
3
|
logger;
|
|
4
4
|
pastDueGracePeriodMs;
|
|
5
|
-
|
|
5
|
+
resolveAccountId;
|
|
6
6
|
handleSubscriptionRenewed;
|
|
7
7
|
updateCheckoutIntentFromEvent;
|
|
8
8
|
getExistingSubscription;
|
|
9
9
|
buildSubscriptionState;
|
|
10
|
-
constructor(store, logger, pastDueGracePeriodMs,
|
|
10
|
+
constructor(store, logger, pastDueGracePeriodMs, resolveAccountId, handleSubscriptionRenewed, updateCheckoutIntentFromEvent, getExistingSubscription, buildSubscriptionState) {
|
|
11
11
|
this.store = store;
|
|
12
12
|
this.logger = logger;
|
|
13
13
|
this.pastDueGracePeriodMs = pastDueGracePeriodMs;
|
|
14
|
-
this.
|
|
14
|
+
this.resolveAccountId = resolveAccountId;
|
|
15
15
|
this.handleSubscriptionRenewed = handleSubscriptionRenewed;
|
|
16
16
|
this.updateCheckoutIntentFromEvent = updateCheckoutIntentFromEvent;
|
|
17
17
|
this.getExistingSubscription = getExistingSubscription;
|
|
@@ -30,7 +30,7 @@ export class BillingFinancialEventHandlers {
|
|
|
30
30
|
: { handled: true, action: "invoice_paid" };
|
|
31
31
|
if (!renewalResult.handled)
|
|
32
32
|
return renewalResult;
|
|
33
|
-
const uid = await this.
|
|
33
|
+
const uid = await this.resolveAccountId(event);
|
|
34
34
|
if (uid) {
|
|
35
35
|
await this.store.upsertBillingInvoice({
|
|
36
36
|
provider: event.provider,
|
|
@@ -57,7 +57,7 @@ export class BillingFinancialEventHandlers {
|
|
|
57
57
|
});
|
|
58
58
|
if (!event.payment)
|
|
59
59
|
return { handled: false, error: "no_payment_data" };
|
|
60
|
-
const uid = await this.
|
|
60
|
+
const uid = await this.resolveAccountId(event);
|
|
61
61
|
const refs = event.payment.refs;
|
|
62
62
|
let topupConfig = null;
|
|
63
63
|
if (refs) {
|
|
@@ -139,7 +139,7 @@ export class BillingFinancialEventHandlers {
|
|
|
139
139
|
});
|
|
140
140
|
if (!event.payment)
|
|
141
141
|
return { handled: false, error: "no_payment_data" };
|
|
142
|
-
const uid = await this.
|
|
142
|
+
const uid = await this.resolveAccountId(event);
|
|
143
143
|
if (uid) {
|
|
144
144
|
await this.store.upsertBillingPayment({
|
|
145
145
|
provider: event.provider,
|
|
@@ -178,7 +178,7 @@ export class BillingFinancialEventHandlers {
|
|
|
178
178
|
async handleRefundCreated(event) {
|
|
179
179
|
if (!event.refund)
|
|
180
180
|
return { handled: false, error: "no_refund_data" };
|
|
181
|
-
const uid = await this.
|
|
181
|
+
const uid = await this.resolveAccountId(event);
|
|
182
182
|
if (uid) {
|
|
183
183
|
const refundId = await this.store.upsertBillingRefund({
|
|
184
184
|
provider: event.provider,
|
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E,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,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 {\n BillingEvent,\n BillingEventResult,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n} from \"./types/index.js\";\n\nexport interface FinancialSubscriptionOverrides {\n status?: BillingSubscriptionStatus | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n}\n\nexport class BillingFinancialEventHandlers {\n constructor(\n private readonly store: BillingStore,\n private readonly logger: NormalizedLogger,\n private readonly pastDueGracePeriodMs: number,\n private readonly resolveUserId: (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 getExistingSubscription: (\n event: BillingEvent,\n ) => Promise<BillingSubscriptionState | null>,\n private readonly buildSubscriptionState: (\n event: BillingEvent,\n userId: string,\n existing: BillingSubscriptionState | null,\n overrides?: FinancialSubscriptionOverrides,\n ) => BillingSubscriptionState,\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 const uid = await this.resolveUserId(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.resolveUserId(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: Record<string, unknown> | 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 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.resolveUserId(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 existing = await this.getExistingSubscription(event);\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 pastDue = this.buildSubscriptionState(event, uid, existing, {\n status: \"past_due\",\n graceEndsAt: new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n graceExpiredAt: null,\n });\n await this.store.upsertBillingSubscription(pastDue);\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.resolveUserId(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":"AAgBA,MAAM,OAAO,6BAA6B;IAErB;IACA;IACA;IACA;IACA;IAGA;IAIA;IAGA;IAfnB,YACmB,KAAmB,EACnB,MAAwB,EACxB,oBAA4B,EAC5B,gBAAiE,EACjE,yBAEe,EACf,6BAGC,EACD,uBAE4B,EAC5B,sBAKY;QAnBZ,UAAK,GAAL,KAAK,CAAc;QACnB,WAAM,GAAN,MAAM,CAAkB;QACxB,yBAAoB,GAApB,oBAAoB,CAAQ;QAC5B,qBAAgB,GAAhB,gBAAgB,CAAiD;QACjE,8BAAyB,GAAzB,yBAAyB,CAEV;QACf,kCAA6B,GAA7B,6BAA6B,CAG5B;QACD,4BAAuB,GAAvB,uBAAuB,CAEK;QAC5B,2BAAsB,GAAtB,sBAAsB,CAKV;IAC5B,CAAC;IAEJ,KAAK,CAAC,iBAAiB,CAAC,KAAmB;QACzC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,oCAAoC,EAAE;YACrD,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,SAAS,EAAE,KAAK,CAAC,OAAO,EAAE,iBAAiB;SAC5C,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,CAAC,OAAO;YAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;QACxE,MAAM,aAAa,GAAG,KAAK,CAAC,YAAY;YACtC,CAAC,CAAC,MAAM,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAC7C,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC;QAC9C,IAAI,CAAC,aAAa,CAAC,OAAO;YAAE,OAAO,aAAa,CAAC;QAC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E,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,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 {\n BillingEvent,\n BillingEventResult,\n BillingSubscriptionState,\n BillingSubscriptionStatus,\n BillingTopupResult,\n} from \"./types/index.js\";\n\nexport interface FinancialSubscriptionOverrides {\n status?: BillingSubscriptionStatus | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n}\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 getExistingSubscription: (\n event: BillingEvent,\n ) => Promise<BillingSubscriptionState | null>,\n private readonly buildSubscriptionState: (\n event: BillingEvent,\n userId: string,\n existing: BillingSubscriptionState | null,\n overrides?: FinancialSubscriptionOverrides,\n ) => BillingSubscriptionState,\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 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: Record<string, unknown> | 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 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 existing = await this.getExistingSubscription(event);\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 pastDue = this.buildSubscriptionState(event, uid, existing, {\n status: \"past_due\",\n graceEndsAt: new Date(occurredAt.getTime() + this.pastDueGracePeriodMs).toISOString(),\n graceExpiredAt: null,\n });\n await this.store.upsertBillingSubscription(pastDue);\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"]}
|
|
@@ -3,17 +3,21 @@ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCre
|
|
|
3
3
|
import { BillingStore } from "../billing-store.js";
|
|
4
4
|
import type { AutoRechargeAttemptClaim, AutoRechargeAttemptUpdate, AutoRechargeProviderPaymentUpdate, BillingCreditGrantCreate, BillingDisputeUpsert, BillingInvoiceUpsert, BillingPaymentUpsert, BillingRefundUpsert, BillingSubscriptionChangeUpdate, BillingSubscriptionConflictCreate, CheckoutIntentCreate, CheckoutIntentUpdate } from "../contracts.js";
|
|
5
5
|
import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
|
|
6
|
-
|
|
6
|
+
import { type ProviderEnvironment } from "../../providers/environment.js";
|
|
7
|
+
export interface PostgresBillingStoreOptions extends Omit<PostgresConnectionOptions, "providerEnvironment"> {
|
|
7
8
|
/** PostgreSQL connection string or an application-owned pool. */
|
|
8
9
|
postgres: PostgresPool | string;
|
|
9
10
|
/** Tenant UUID bound to every store transaction. */
|
|
10
11
|
tenantId: string;
|
|
12
|
+
/** Explicit financial namespace; billing stores never guess live vs test. */
|
|
13
|
+
providerEnvironment: ProviderEnvironment;
|
|
11
14
|
/** Injectable `pg.Pool` constructor for custom runtimes and tests. */
|
|
12
15
|
poolConstructor?: PostgresPoolConstructor;
|
|
13
16
|
billingPayloadBackend?: "postgres" | "s3";
|
|
14
17
|
}
|
|
15
18
|
export declare class PostgresBillingStore extends BillingStore {
|
|
16
19
|
private readonly postgres;
|
|
20
|
+
readonly providerEnvironment: ProviderEnvironment;
|
|
17
21
|
private _offer;
|
|
18
22
|
private _topup;
|
|
19
23
|
private _customer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAiC,EACjC,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,8BAA8B,EAC9B,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iCAAiC,EACjC,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,+BAA+B,EAC/B,iCAAi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AAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;CAQzC"}
|
|
@@ -2,6 +2,7 @@ import Decimal from "decimal.js";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { BillingStore } from "../billing-store.js";
|
|
4
4
|
import { PostgresClient, } from "../../shared/postgres-client.js";
|
|
5
|
+
import { normalizeProviderEnvironment, } from "../../providers/environment.js";
|
|
5
6
|
import { StoreClosedError, StoreError } from "../../errors.js";
|
|
6
7
|
import { optionalBoundedDiagnosticMessage } from "../../shared/diagnostics.js";
|
|
7
8
|
import { optionalRecordRow, pgBoolean, postgresUuid, requireRecordRow, requireResultField, safeParse, } from "../../shared/postgres-validation.js";
|
|
@@ -71,6 +72,7 @@ function billingCreditPostingResult(rows, context) {
|
|
|
71
72
|
}
|
|
72
73
|
export class PostgresBillingStore extends BillingStore {
|
|
73
74
|
postgres;
|
|
75
|
+
providerEnvironment;
|
|
74
76
|
_offer = null;
|
|
75
77
|
_topup = null;
|
|
76
78
|
_customer = null;
|
|
@@ -91,8 +93,11 @@ export class PostgresBillingStore extends BillingStore {
|
|
|
91
93
|
if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
|
|
92
94
|
throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
|
|
93
95
|
}
|
|
96
|
+
const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
|
|
97
|
+
this.providerEnvironment = providerEnvironment;
|
|
94
98
|
this.postgres = new PostgresClient(options.postgres, {
|
|
95
99
|
tenantId: options.tenantId,
|
|
100
|
+
providerEnvironment,
|
|
96
101
|
poolConstructor: options.poolConstructor,
|
|
97
102
|
billingPayloadBackend: options.billingPayloadBackend,
|
|
98
103
|
connectionTimeoutMs: options.connectionTimeoutMs,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,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,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends PostgresConnectionOptions {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`,\n [\n input.subjectId,\n input.provider,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (\n result.status === \"invalid_request\" ||\n result.status === \"idempotency_conflict\" ||\n result.status === \"max_retries_exceeded\"\n ) {\n return { status: \"retry\" as const };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/billing/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAgBxB,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAgBnD,OAAO,EACL,cAAc,GAIf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,GACV,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,sBAAsB,EAAwB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,6BAA6B,G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OAAqC;QAErC,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,wBAAwB,CAC5B,KAA+B;QAE/B,OAAO,IAAI,CAAC,mBAAmB,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,KAAgC;QAC9D,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,0CAA0C,CAC9C,KAAwC;QAExC,OAAO,IAAI,CAAC,mBAAmB,CAAC,8BAA8B,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,yBAAyB,CAAC,MAAc,EAAE,KAAoB;QAClE,OAAO,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,KAAK,CAAC,0BAA0B,CAC9B,MAAc,EACd,QAAwB;QAExB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,OAAO;YACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { z } from \"zod\";\nimport type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCreditPostingResult,\n BillingCustomerRecord,\n BillingEventClaim,\n BillingOfferResult,\n BillingPaymentRecord,\n BillingPreferences,\n BillingSubscriptionChange,\n BillingSubscriptionChangeInput,\n BillingSubscriptionState,\n CheckoutIntent,\n BillingTopupResult,\n} from \"../types/index.js\";\nimport { BillingStore } from \"../billing-store.js\";\nimport type {\n AutoRechargeAttemptClaim,\n AutoRechargeAttemptUpdate,\n AutoRechargeProviderPaymentUpdate,\n BillingCreditGrantCreate,\n BillingDisputeUpsert,\n BillingInvoiceUpsert,\n BillingPaymentUpsert,\n BillingRefundUpsert,\n BillingSubscriptionChangeUpdate,\n BillingSubscriptionConflictCreate,\n CheckoutIntentCreate,\n CheckoutIntentUpdate,\n} from \"../contracts.js\";\nimport type { QueryFn } from \"../../shared/postgres-types.js\";\nimport {\n PostgresClient,\n type PostgresConnectionOptions,\n type PostgresPool,\n type PostgresPoolConstructor,\n} from \"../../shared/postgres-client.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../../providers/environment.js\";\nimport { StoreClosedError, StoreError } from \"../../errors.js\";\nimport { optionalBoundedDiagnosticMessage } from \"../../shared/diagnostics.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n postgresUuid,\n requireRecordRow,\n requireResultField,\n safeParse,\n} from \"../../shared/postgres-validation.js\";\nimport { BillingOfferRepository, type BillingOfferRow } from \"./repositories/offer.js\";\nimport { BillingTopupRepository, type BillingTopupRow } from \"./repositories/topup.js\";\nimport { BillingCustomerRepository } from \"./repositories/customer.js\";\nimport {\n BillingSubscriptionRepository,\n type SubscriptionRow,\n} from \"./repositories/subscription.js\";\nimport { BillingEventRepository } from \"./repositories/event.js\";\nimport { BillingPaymentRepository } from \"./repositories/payment.js\";\nimport { BillingRefundRepository } from \"./repositories/refund.js\";\nimport { BillingInvoiceRepository } from \"./repositories/invoice.js\";\nimport { BillingDisputeRepository } from \"./repositories/dispute.js\";\nimport { BillingPreferencesRepository } from \"./repositories/preferences.js\";\nimport { BillingAutoRechargeRepository } from \"./repositories/auto-recharge.js\";\nimport { BillingSubscriptionChangeRepository } from \"./repositories/subscription-change.js\";\n\nconst PgSafeMinorUnitsSchema = z\n .union([z.string().regex(/^\\d+$/), z.number().int().nonnegative().safe()])\n .transform(Number)\n .refine(Number.isSafeInteger, \"minor-unit amount exceeds JavaScript's safe integer range\");\n\nconst BillingCreditPostingRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n balance_after: z\n .union([z.string(), z.number(), z.instanceof(Decimal)])\n .nullable()\n .transform((value) => (value === null ? null : new Decimal(value))),\n replayed: pgBoolean,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, ctx) => {\n if (row.error_code === null && (row.ledger_entry_id === null || row.balance_after === null)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"successful posting requires ledger_entry_id and balance_after\",\n });\n }\n });\n\nconst CheckoutIntentRowSchema = z\n .object({\n id: postgresUuid,\n subject_id: postgresUuid,\n provider: z.string().min(1),\n checkout_kind: z.enum([\"subscription\", \"credit_topup\"]),\n product_key: z.string().min(1),\n request_digest: z.instanceof(Uint8Array).refine((value) => value.byteLength === 32),\n status: z.enum([\"open\", \"completed\", \"failed\", \"expired\"]),\n provider_session_id: z.string().min(1).nullable(),\n checkout_url: z.string().min(1).nullable(),\n expires_at: z.union([z.string().datetime({ offset: true }), z.date()]),\n })\n .strict();\n\nfunction billingCreditPostingResult(\n rows: readonly unknown[] | null | undefined,\n context: string,\n): BillingCreditPostingResult {\n const raw = requireRecordRow(rows, context);\n const row = safeParse(\n BillingCreditPostingRowSchema,\n {\n ledger_entry_id: raw.ledger_entry_id,\n balance_after: raw.balance_after,\n replayed: raw.replayed,\n error_code: raw.error_code,\n },\n context,\n { indeterminate: true },\n );\n return {\n ledgerEntryId: row.ledger_entry_id,\n balanceAfter: row.balance_after,\n replayed: row.replayed,\n errorCode: row.error_code,\n };\n}\n\nexport interface PostgresBillingStoreOptions extends Omit<\n PostgresConnectionOptions,\n \"providerEnvironment\"\n> {\n /** PostgreSQL connection string or an application-owned pool. */\n postgres: PostgresPool | string;\n /** Tenant UUID bound to every store transaction. */\n tenantId: string;\n /** Explicit financial namespace; billing stores never guess live vs test. */\n providerEnvironment: ProviderEnvironment;\n /** Injectable `pg.Pool` constructor for custom runtimes and tests. */\n poolConstructor?: PostgresPoolConstructor;\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport class PostgresBillingStore extends BillingStore {\n private readonly postgres: PostgresClient;\n readonly providerEnvironment: ProviderEnvironment;\n\n private _offer: BillingOfferRepository | null = null;\n private _topup: BillingTopupRepository | null = null;\n private _customer: BillingCustomerRepository | null = null;\n private _subscription: BillingSubscriptionRepository | null = null;\n private _event: BillingEventRepository | null = null;\n private _payment: BillingPaymentRepository | null = null;\n private _refund: BillingRefundRepository | null = null;\n private _invoice: BillingInvoiceRepository | null = null;\n private _dispute: BillingDisputeRepository | null = null;\n private _preferences: BillingPreferencesRepository | null = null;\n private _autoRecharge: BillingAutoRechargeRepository | null = null;\n private _subscriptionChange: BillingSubscriptionChangeRepository | null = null;\n constructor(options: PostgresBillingStoreOptions) {\n super();\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"PostgresBillingStore options are required\");\n }\n if (typeof options.postgres !== \"string\" && options.poolConstructor !== undefined) {\n throw new TypeError(\"poolConstructor cannot be used with an existing PostgreSQL pool\");\n }\n const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.providerEnvironment = providerEnvironment;\n this.postgres = new PostgresClient(options.postgres, {\n tenantId: options.tenantId,\n providerEnvironment,\n poolConstructor: options.poolConstructor,\n billingPayloadBackend: options.billingPayloadBackend,\n connectionTimeoutMs: options.connectionTimeoutMs,\n statementTimeoutMs: options.statementTimeoutMs,\n idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n maxConnections: options.maxConnections,\n applicationName: options.applicationName,\n onPoolError: options.onPoolError,\n closedError: () => new StoreClosedError(\"Billing store has been closed\"),\n });\n }\n\n async close(): Promise<void> {\n await this.postgres.close();\n }\n\n private get queryFn(): QueryFn {\n return this.postgres.query;\n }\n\n private get billingOffer(): BillingOfferRepository {\n if (!this._offer) this._offer = new BillingOfferRepository(this.queryFn);\n return this._offer;\n }\n\n private get billingTopup(): BillingTopupRepository {\n if (!this._topup) this._topup = new BillingTopupRepository(this.queryFn);\n return this._topup;\n }\n\n private get billingCustomer(): BillingCustomerRepository {\n if (!this._customer) this._customer = new BillingCustomerRepository(this.queryFn);\n return this._customer;\n }\n\n private get billingSubscription(): BillingSubscriptionRepository {\n if (!this._subscription) this._subscription = new BillingSubscriptionRepository(this.queryFn);\n return this._subscription;\n }\n\n private get billingEvent(): BillingEventRepository {\n if (!this._event) this._event = new BillingEventRepository(this.queryFn);\n return this._event;\n }\n\n private get billingPayment(): BillingPaymentRepository {\n if (!this._payment) this._payment = new BillingPaymentRepository(this.queryFn);\n return this._payment;\n }\n\n private get billingRefund(): BillingRefundRepository {\n if (!this._refund) this._refund = new BillingRefundRepository(this.queryFn);\n return this._refund;\n }\n\n private get billingInvoice(): BillingInvoiceRepository {\n if (!this._invoice) this._invoice = new BillingInvoiceRepository(this.queryFn);\n return this._invoice;\n }\n\n private get billingDispute(): BillingDisputeRepository {\n if (!this._dispute) this._dispute = new BillingDisputeRepository(this.queryFn);\n return this._dispute;\n }\n\n private get billingPreferences(): BillingPreferencesRepository {\n if (!this._preferences) this._preferences = new BillingPreferencesRepository(this.queryFn);\n return this._preferences;\n }\n\n private get billingAutoRecharge(): BillingAutoRechargeRepository {\n if (!this._autoRecharge) this._autoRecharge = new BillingAutoRechargeRepository(this.queryFn);\n return this._autoRecharge;\n }\n\n private get billingSubscriptionChange(): BillingSubscriptionChangeRepository {\n if (!this._subscriptionChange) {\n this._subscriptionChange = new BillingSubscriptionChangeRepository(this.queryFn);\n }\n return this._subscriptionChange;\n }\n\n async createOrGetCheckoutIntent(input: CheckoutIntentCreate): Promise<CheckoutIntent> {\n if (!/^[0-9a-fA-F]{64}$/.test(input.requestDigest)) {\n throw new TypeError(\"requestDigest must be a 32-byte hex string\");\n }\n const rows = await this.queryFn(\n `SELECT bursar.create_checkout_intent($1::uuid, $2, $3, $4, decode($5, 'hex'), $6::timestamptz) AS id`,\n [\n input.subjectId,\n input.provider,\n input.checkoutKind,\n input.productKey,\n input.requestDigest,\n input.expiresAt,\n ],\n );\n const id = requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createOrGetCheckoutIntent\",\n );\n const intent = await this.getCheckoutIntent(id, input.subjectId);\n if (!intent) {\n throw new StoreError(\"checkout intent could not be read after creation\", {\n indeterminate: true,\n details: { checkoutIntentId: id },\n });\n }\n return intent;\n }\n\n async updateCheckoutIntent(id: string, update: CheckoutIntentUpdate): Promise<void> {\n const rows = await this.queryFn(\n `SELECT bursar.advance_checkout_intent($1::uuid, $2, $3, $4) AS advanced`,\n [id, update.status ?? null, update.providerSessionId ?? null, update.checkoutUrl ?? null],\n );\n if (\n !requireResultField(rows, \"advanced\", pgBoolean, \"PostgresBillingStore.updateCheckoutIntent\")\n ) {\n throw new StoreError(`checkout intent transition rejected: ${id}`, {\n details: { checkoutIntentId: id },\n });\n }\n }\n\n async getCheckoutIntent(id: string, subjectId: string): Promise<CheckoutIntent | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_checkout_intent($1::uuid, $2::uuid)`,\n [id, subjectId],\n );\n if (rows.length === 0) return null;\n if (rows.length !== 1) {\n throw new StoreError(\"getCheckoutIntent: expected at most one row\", {\n details: { rowCount: rows.length, checkoutIntentId: id },\n });\n }\n const row = rows[0] as Record<string, unknown>;\n return this.rowToCheckoutIntent(\n safeParse(\n CheckoutIntentRowSchema,\n {\n id: row.id,\n subject_id: row.subject_id,\n provider: row.provider,\n checkout_kind: row.checkout_kind,\n product_key: row.product_key,\n request_digest: row.request_digest,\n status: row.status,\n provider_session_id: row.provider_session_id,\n checkout_url: row.checkout_url,\n expires_at: row.expires_at,\n },\n \"PostgresBillingStore.getCheckoutIntent\",\n ),\n );\n }\n\n private rowToCheckoutIntent(row: z.infer<typeof CheckoutIntentRowSchema>): CheckoutIntent {\n return {\n id: row.id,\n subjectId: row.subject_id,\n provider: row.provider,\n checkoutKind: row.checkout_kind,\n productKey: row.product_key,\n requestDigest: Buffer.from(row.request_digest).toString(\"hex\"),\n status: row.status,\n providerSessionId: row.provider_session_id,\n checkoutUrl: row.checkout_url,\n expiresAt: row.expires_at instanceof Date ? row.expires_at.toISOString() : row.expires_at,\n };\n }\n\n private rowToOffer(row: BillingOfferRow | null): BillingOfferResult | null {\n if (!row) return null;\n return {\n offerId: row.id,\n offerKey: row.offerKey,\n planId: row.planId,\n plan: row.plan,\n interval: row.interval,\n intervalCount: row.intervalCount,\n grant:\n row.grantCredits === null\n ? null\n : {\n mode: \"cycle_grant\",\n credits: row.grantCredits,\n bucket: row.grantBucket,\n replacePrior: row.grantReplacePrior,\n },\n };\n }\n\n async resolveBillingOffer(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToOffer(r);\n }\n\n async resolveBillingOfferByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingOfferResult | null> {\n const r = await this.billingOffer.resolveByLookup(provider, lookupKey);\n return this.rowToOffer(r);\n }\n\n async claimBillingEvent(\n provider: string,\n eventId: string,\n eventType: string,\n envelope?: Record<string, unknown>,\n ): Promise<BillingEventClaim> {\n const result = await this.billingEvent.claim(\n provider,\n eventId,\n eventType,\n JSON.stringify(envelope ?? { eventType }),\n );\n if (result.status === \"claimed\") {\n if (result.claim_token === null || result.event_id === null) {\n throw new StoreError(\"Billing event claim returned no claim identifiers\", {\n details: { provider, eventId },\n });\n }\n return {\n status: \"claimed\" as const,\n claimToken: result.claim_token,\n billingEventId: result.event_id,\n };\n }\n if (result.status === \"duplicate\") return { status: \"duplicate\" as const };\n if (result.status === \"busy\") return { status: \"busy\" as const };\n if (\n result.status === \"invalid_request\" ||\n result.status === \"idempotency_conflict\" ||\n result.status === \"max_retries_exceeded\"\n ) {\n return { status: \"retry\" as const };\n }\n throw new StoreError(\"Billing event claim returned an unsupported status\", {\n details: { provider, eventId, status: result.status },\n });\n }\n\n async completeBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n ): Promise<boolean> {\n return this.billingEvent.complete(provider, eventId, claimToken);\n }\n\n async failBillingEvent(\n provider: string,\n eventId: string,\n claimToken: string,\n error?: string,\n ): Promise<boolean> {\n return this.billingEvent.fail(\n provider,\n eventId,\n claimToken,\n optionalBoundedDiagnosticMessage(error) ?? undefined,\n );\n }\n\n async upsertBillingCustomer(\n provider: string,\n providerCustomerId: string,\n userId: string,\n email?: string | null,\n ): Promise<void> {\n await this.billingCustomer.upsert(provider, providerCustomerId, userId, email ?? null);\n }\n\n async upsertBillingSubscription(state: BillingSubscriptionState): Promise<void> {\n await this.billingSubscription.upsert(state);\n }\n\n async getBillingCustomer(provider: string, providerCustomerId: string): Promise<string | null> {\n return this.billingCustomer.get(provider, providerCustomerId);\n }\n\n async getBillingSubscription(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.get(provider, providerSubscriptionId);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async createBillingSubscriptionChange(\n input: BillingSubscriptionChangeInput,\n ): Promise<BillingSubscriptionChange> {\n const subscription = await this.billingSubscription.get(\n input.provider,\n input.providerSubscriptionId,\n );\n if (!subscription?.id) {\n throw new StoreError(\"subscription change requires a persisted subscription\", {\n retryable: true,\n details: {\n provider: input.provider,\n providerSubscriptionId: input.providerSubscriptionId,\n },\n });\n }\n return this.billingSubscriptionChange.create(subscription.id, input);\n }\n\n async getOpenBillingSubscriptionChange(\n provider: string,\n providerSubscriptionId: string,\n ): Promise<BillingSubscriptionChange | null> {\n return this.billingSubscriptionChange.getOpen(provider, providerSubscriptionId);\n }\n\n async listExpiredGraceSubscriptions(\n now: string,\n limit = 100,\n ): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.listExpiredGraceSubscriptions(now, limit);\n return rows.map((row) => this.rowToSubscriptionState(row));\n }\n\n async markSubscriptionGraceExpired(\n subscriptionId: string,\n expectedGraceEndsAt: string,\n expiredAt = new Date().toISOString(),\n ): Promise<boolean> {\n return this.billingSubscription.markGraceExpired(\n subscriptionId,\n expectedGraceEndsAt,\n expiredAt,\n );\n }\n\n async updateBillingSubscriptionChange(\n id: string,\n update: BillingSubscriptionChangeUpdate,\n ): Promise<void> {\n await this.billingSubscriptionChange.update(id, update);\n }\n\n async getUserSubscription(\n userId: string,\n statuses?: string[],\n ): Promise<BillingSubscriptionState | null> {\n const r = await this.billingSubscription.getUserSubscription(userId, statuses);\n if (!r) return null;\n return this.rowToSubscriptionState(r);\n }\n\n async getUserSubscriptions(userId: string): Promise<BillingSubscriptionState[]> {\n const rows = await this.billingSubscription.getUserSubscriptions(userId);\n return rows.map((r) => this.rowToSubscriptionState(r));\n }\n\n async recordSubscriptionConflict(input: BillingSubscriptionConflictCreate): Promise<void> {\n await this.billingSubscription.recordConflict(input);\n }\n\n async selectSubscriptionEntitlementSource(\n userId: string,\n provider: string,\n providerSubscriptionId?: string | null,\n ): Promise<boolean> {\n return this.billingSubscription.selectEntitlementSource(\n userId,\n provider,\n providerSubscriptionId,\n );\n }\n\n private rowToTopup(r: BillingTopupRow | null): BillingTopupResult | null {\n if (!r) return null;\n const minAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.min_quantity,\n \"PostgresBillingStore.rowToTopup.minAmountMinor\",\n );\n const maxAmountMinor = safeParse(\n PgSafeMinorUnitsSchema,\n r.amount_minor * r.max_quantity,\n \"PostgresBillingStore.rowToTopup.maxAmountMinor\",\n );\n return {\n topupId: r.id,\n topupKey: r.topup_key,\n creditsPerUnit: r.credits_per_unit,\n depositTo: r.bucket_key,\n amountMinor: r.amount_minor,\n currency: r.currency,\n minQuantity: r.min_quantity,\n maxQuantity: r.max_quantity,\n defaultQuantity: r.default_quantity,\n minAmountMinor,\n maxAmountMinor,\n };\n }\n\n async resolveCreditTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByPrice(provider, priceId ?? null, productId ?? null);\n return this.rowToTopup(r);\n }\n\n async resolveCreditTopupByLookup(\n provider: string,\n lookupKey: string,\n ): Promise<BillingTopupResult | null> {\n const r = await this.billingTopup.resolveByLookup(provider, lookupKey);\n return this.rowToTopup(r);\n }\n\n async computeTopupCredits(\n amountMinor: number,\n topupConfig: BillingTopupResult,\n ): Promise<Decimal> {\n if (!Number.isSafeInteger(amountMinor) || amountMinor < 0) {\n throw new TypeError(\"amountMinor must be a non-negative safe integer\");\n }\n const unitAmount = topupConfig.amountMinor;\n if (unitAmount <= 0 || amountMinor % unitAmount !== 0) return new Decimal(0);\n const quantity = amountMinor / unitAmount;\n if (quantity < topupConfig.minQuantity || quantity > topupConfig.maxQuantity) {\n return new Decimal(0);\n }\n return topupConfig.creditsPerUnit.mul(quantity);\n }\n\n async upsertBillingPayment(options: BillingPaymentUpsert): Promise<string> {\n return this.billingPayment.upsert(\n options.provider,\n options.providerPaymentId,\n options.providerInvoiceId ?? null,\n options.userId,\n options.amountMinor,\n options.taxMinor,\n options.currency,\n options.purpose,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async createBillingCreditGrant(input: BillingCreditGrantCreate): Promise<string> {\n const rows = await this.queryFn(\n \"SELECT bursar.create_billing_credit_grant($1::uuid, $2::uuid, $3::uuid, $4, $5, $6::uuid) AS id\",\n [\n input.paymentId ?? null,\n input.subscriptionId ?? null,\n input.topupId ?? null,\n input.configuredCredits.toString(),\n input.quantity,\n input.billingEventId ?? null,\n ],\n );\n return requireResultField(\n rows,\n \"id\",\n postgresUuid,\n \"PostgresBillingStore.createBillingCreditGrant\",\n );\n }\n\n async grantBillingCredit(\n grantId: string,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.grant_billing_credit($1::uuid, $2)\", [\n grantId,\n idempotencyKey,\n ]);\n return billingCreditPostingResult(rows, \"PostgresBillingStore.grantBillingCredit\");\n }\n\n async getBillingCreditGrantByPayment(paymentId: string): Promise<string | null> {\n const rows = await this.queryFn(\n `SELECT * FROM bursar.get_billing_credit_grant_by_payment($1::uuid)`,\n [paymentId],\n );\n const row = optionalRecordRow(rows, \"PostgresBillingStore.getBillingCreditGrantByPayment\");\n return row === null\n ? null\n : safeParse(postgresUuid, row.id, \"PostgresBillingStore.getBillingCreditGrantByPayment.id\");\n }\n\n async postBillingRefund(\n refundId: string,\n grantId: string,\n amountMinor: number,\n idempotencyKey: string,\n ): Promise<BillingCreditPostingResult> {\n const rows = await this.queryFn(\n \"SELECT * FROM bursar.post_billing_refund($1::uuid, $2::uuid, $3, $4)\",\n [refundId, grantId, amountMinor, idempotencyKey],\n );\n return billingCreditPostingResult(rows, \"PostgresBillingStore.postBillingRefund\");\n }\n\n async upsertBillingRefund(options: BillingRefundUpsert): Promise<string> {\n return this.billingRefund.upsert(\n options.provider,\n options.providerRefundId,\n options.providerPaymentId,\n options.userId,\n options.amountMinor,\n options.currency,\n options.reason ?? null,\n options.metadata ? JSON.stringify(options.metadata) : null,\n options.status,\n options.providerUpdatedAt,\n );\n }\n\n async upsertBillingInvoice(options: BillingInvoiceUpsert): Promise<void> {\n const subscription = options.providerSubscriptionId\n ? await this.billingSubscription.get(options.provider, options.providerSubscriptionId)\n : null;\n if (options.providerSubscriptionId && !subscription) {\n throw new StoreError(\"invoice subscription is not available\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerInvoiceId: options.providerInvoiceId,\n providerSubscriptionId: options.providerSubscriptionId ?? null,\n },\n });\n }\n await this.billingInvoice.upsert(\n options.userId,\n options.provider,\n options.providerInvoiceId,\n subscription?.id ? String(subscription.id) : null,\n options.status,\n options.amountDueMinor,\n options.amountPaidMinor,\n options.currency,\n options.periodStart ?? null,\n options.periodEnd ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async listBillingInvoices(userId: string) {\n return this.billingInvoice.listForUser(userId);\n }\n\n async upsertBillingDispute(options: BillingDisputeUpsert): Promise<void> {\n const payment = await this.billingPayment.getForRefund(\n options.provider,\n options.providerPaymentId,\n );\n if (!payment?.id) {\n throw new StoreError(\"dispute payment is required\", {\n retryable: true,\n details: {\n provider: options.provider,\n providerDisputeId: options.providerDisputeId,\n providerPaymentId: options.providerPaymentId ?? null,\n },\n });\n }\n await this.billingDispute.upsert(\n options.provider,\n options.providerDisputeId,\n String(payment.id),\n options.status,\n options.reason ?? null,\n options.metadata ?? {},\n options.providerUpdatedAt,\n );\n }\n\n async getBillingPayment(\n provider: string,\n providerPaymentId: string,\n ): Promise<BillingPaymentRecord | null> {\n const row = await this.billingPayment.getForRefund(provider, providerPaymentId);\n if (!row) return null;\n return {\n id: row.id,\n provider: row.provider,\n providerPaymentId: row.provider_payment_id,\n providerInvoiceId: row.provider_invoice_id,\n userId: row.subject_id,\n amountMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.amount_minor,\n \"PostgresBillingStore.getBillingPayment.amountMinor\",\n ),\n taxMinor: safeParse(\n PgSafeMinorUnitsSchema,\n row.tax_minor,\n \"PostgresBillingStore.getBillingPayment.taxMinor\",\n ),\n currency: row.currency,\n purpose: row.purpose,\n status: row.status,\n providerUpdatedAt:\n row.provider_updated_at instanceof Date\n ? row.provider_updated_at.toISOString()\n : row.provider_updated_at,\n metadata: row.metadata,\n };\n }\n\n private rowToSubscriptionState(r: SubscriptionRow): BillingSubscriptionState {\n return {\n subscriptionId: r.id,\n userId: r.user_id,\n provider: r.provider,\n providerSubscriptionId: r.provider_subscription_id,\n providerCustomerId: r.provider_customer_id,\n offerId: r.offer_id,\n offerKey: r.offer_key,\n planId: r.plan_id,\n plan: r.plan,\n status: r.status,\n currentPeriodStart: r.current_period_start,\n currentPeriodEnd: r.current_period_end,\n trialEnd: r.trial_end,\n cancelAt: r.cancel_at,\n endedAt: r.ended_at,\n graceEndsAt: r.grace_ends_at,\n graceExpiredAt: r.grace_expired_at,\n providerUpdatedAt: r.provider_updated_at,\n cancelAtPeriodEnd: r.cancel_at_period_end,\n interval: r.interval,\n intervalCount: r.interval_count,\n metadata: r.metadata,\n };\n }\n\n async getActiveCatalogDocument(): Promise<Record<string, unknown> | null> {\n const rows = await this.queryFn(\"SELECT * FROM bursar.active_catalog_revision()\", []);\n if (rows.length === 0) return null;\n if (rows.length !== 1 || typeof rows[0] !== \"object\" || rows[0] === null) {\n throw new StoreError(\"active catalog revision returned a malformed row\", {\n details: { rowCount: rows.length },\n });\n }\n return safeParse(\n z.record(z.string(), z.unknown()),\n (rows[0] as Record<string, unknown>).source_document,\n \"PostgresBillingStore.getActiveCatalogDocument\",\n );\n }\n\n async pseudonymizeFinancialSubject(userId: string): Promise<boolean> {\n const rows = await this.queryFn(\n `SELECT bursar.pseudonymize_financial_subject($1::uuid) AS pseudonymized`,\n [userId],\n );\n return requireResultField(\n rows,\n \"pseudonymized\",\n pgBoolean,\n \"PostgresBillingStore.pseudonymizeFinancialSubject\",\n );\n }\n\n async getBillingPreferences(userId: string): Promise<BillingPreferences | null> {\n return this.billingPreferences.get(userId);\n }\n\n async upsertBillingPreferences(prefs: BillingPreferences): Promise<void> {\n await this.billingPreferences.upsert(prefs);\n }\n\n async getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null> {\n return this.billingAutoRecharge.getProfile(userId);\n }\n\n async upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void> {\n return this.billingAutoRecharge.upsertProfile(profile, options);\n }\n\n async claimAutoRechargeAttempt(\n input: AutoRechargeAttemptClaim,\n ): Promise<BillingAutoRechargeAttempt | null> {\n return this.billingAutoRecharge.claimAttempt(input);\n }\n\n async updateAutoRechargeAttempt(input: AutoRechargeAttemptUpdate): Promise<void> {\n return this.billingAutoRecharge.updateAttempt(input);\n }\n\n async updateAutoRechargeAttemptByProviderPayment(\n input: AutoRechargeProviderPaymentUpdate,\n ): Promise<void> {\n return this.billingAutoRecharge.updateAttemptByProviderPayment(input);\n }\n\n async countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number> {\n return this.billingAutoRecharge.countAttempts(userId, since);\n }\n\n async getBillingCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null> {\n const result = await this.billingCustomer.getByUserId(userId, provider ?? null);\n if (!result) return null;\n return {\n provider: result.provider,\n providerCustomerId: result.providerCustomerId,\n };\n }\n}\n"]}
|