@zonastery/bursar 2.0.3 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/billing/auto-recharge-port.d.ts +3 -2
- package/dist/billing/auto-recharge-port.d.ts.map +1 -1
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.js +3 -3
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +3 -2
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +2 -10
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +6 -6
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +8 -7
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +5 -9
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +191 -285
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +32 -23
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +3 -9
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +10 -12
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +3 -2
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +58 -40
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +8 -12
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +5 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +1 -1
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js +1 -9
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +29 -30
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +6 -5
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +15 -13
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +2 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/documents.d.ts +2 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +3 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +73 -39
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +4 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +3 -2
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +4 -3
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +45 -42
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js +11 -6
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +16 -22
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-access.d.ts +5 -2
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +60 -41
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts +2 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +49 -29
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts +2 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +39 -23
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts +7 -2
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +49 -22
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts +2 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +41 -31
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +15 -11
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +90 -27
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +6 -5
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +65 -35
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +5 -4
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +2 -3
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/events.d.ts +12 -1
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/events.js +35 -21
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +2 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +3 -2
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +14 -6
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +6 -6
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +4 -3
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +2 -2
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +1 -1
- package/dist/credits/postgres/store.d.ts +3 -2
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +17 -10
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +4 -3
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +10 -11
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +10 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +5 -4
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +5 -4
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +2 -1
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +3 -2
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/engine.d.ts +2 -2
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +39 -10
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +7 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +18 -11
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr/tokenizer.d.ts.map +1 -1
- package/dist/expr/tokenizer.js +34 -12
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +12 -6
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/integrations/better-auth.d.ts +4 -1
- package/dist/integrations/better-auth.d.ts.map +1 -1
- package/dist/integrations/better-auth.js +7 -4
- package/dist/integrations/better-auth.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +19 -13
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +2 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +8 -5
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +15 -11
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +32 -0
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
- package/dist/providers/dodo/better-auth-core.js +14 -0
- package/dist/providers/dodo/better-auth-core.js.map +1 -0
- package/dist/providers/dodo/better-auth.d.ts +5 -7
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -13
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +11 -10
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts +7 -4
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +121 -113
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +22 -0
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
- package/dist/providers/dodo/nextjs-core.js +14 -0
- package/dist/providers/dodo/nextjs-core.js.map +1 -0
- package/dist/providers/dodo/nextjs.d.ts +5 -7
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +11 -10
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +3 -3
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +42 -35
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/react-native-core.d.ts +56 -0
- package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
- package/dist/providers/dodo/react-native-core.js +56 -0
- package/dist/providers/dodo/react-native-core.js.map +1 -0
- package/dist/providers/dodo/react-native.d.ts +6 -50
- package/dist/providers/dodo/react-native.d.ts.map +1 -1
- package/dist/providers/dodo/react-native.js +5 -49
- package/dist/providers/dodo/react-native.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +1 -1
- package/dist/providers/environment.d.ts.map +1 -1
- package/dist/providers/environment.js +4 -2
- package/dist/providers/environment.js.map +1 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +5 -10
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +33 -9
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +100 -60
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +16 -9
- package/dist/retry.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +5 -5
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +32 -22
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/idempotency.d.ts +4 -3
- package/dist/shared/idempotency.d.ts.map +1 -1
- package/dist/shared/idempotency.js +21 -10
- package/dist/shared/idempotency.js.map +1 -1
- package/dist/shared/json.d.ts +28 -0
- package/dist/shared/json.d.ts.map +1 -0
- package/dist/shared/json.js +41 -0
- package/dist/shared/json.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -4
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +8 -6
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +69 -47
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js +32 -31
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/postgres-types.d.ts +3 -2
- package/dist/shared/postgres-types.d.ts.map +1 -1
- package/dist/shared/postgres-types.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts +7 -6
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +17 -10
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +11 -4
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +8 -6
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +28 -5
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +48 -33
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +1 -1
- package/dist/storage/diagnostics.js +13 -12
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/maintenance.d.ts.map +1 -1
- package/dist/storage/maintenance.js +31 -25
- package/dist/storage/maintenance.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts +1 -1
- package/dist/storage/outbox-worker.js +18 -18
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +10 -7
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +3 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +10 -4
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +1 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +165 -182
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +10 -6
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +26 -23
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/opentelemetry.js +3 -3
- package/dist/telemetry/opentelemetry.js.map +1 -1
- package/package.json +14 -14
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LRUCache } from "lru-cache";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { normalizeLogger } from "../shared/logger.js";
|
|
3
4
|
import { BillingEventType } from "./types/index.js";
|
|
4
5
|
import { BillingFinancialEventHandlers } from "./financial-event-handlers.js";
|
|
@@ -16,6 +17,9 @@ export class BillingEventHandlers {
|
|
|
16
17
|
get hasProvisioning() {
|
|
17
18
|
return this.provisioning !== null;
|
|
18
19
|
}
|
|
20
|
+
get terminalPlan() {
|
|
21
|
+
return this.terminalPlanKey;
|
|
22
|
+
}
|
|
19
23
|
constructor(store, options) {
|
|
20
24
|
this.store = store;
|
|
21
25
|
this.provisioning = options?.provisioning ?? null;
|
|
@@ -35,7 +39,12 @@ export class BillingEventHandlers {
|
|
|
35
39
|
return { offer };
|
|
36
40
|
},
|
|
37
41
|
});
|
|
38
|
-
this.financial = new BillingFinancialEventHandlers(store, this.logger, this.pastDueGracePeriodMs, (event) => this.resolveAccountId(event), (event) => this.handleSubscriptionRenewed(event), (event, status) => this.updateCheckoutIntentFromEvent(event, status), (event
|
|
42
|
+
this.financial = new BillingFinancialEventHandlers(store, this.logger, this.pastDueGracePeriodMs, (event) => this.resolveAccountId(event), (event) => this.handleSubscriptionRenewed(event), (event, status) => this.updateCheckoutIntentFromEvent(event, status), (event, graceEndsAt) => this.applySubscriptionEvent(event, {
|
|
43
|
+
action: "payment_failed_recorded",
|
|
44
|
+
status: "past_due",
|
|
45
|
+
graceEndsAt,
|
|
46
|
+
graceExpiredAt: null,
|
|
47
|
+
}));
|
|
39
48
|
this.handlerMap = {
|
|
40
49
|
[BillingEventType.CUSTOMER_CREATED]: this.handleCustomerCreated.bind(this),
|
|
41
50
|
[BillingEventType.CUSTOMER_UPDATED]: this.handleCustomerCreated.bind(this),
|
|
@@ -70,8 +79,8 @@ export class BillingEventHandlers {
|
|
|
70
79
|
this.offerCache.clear();
|
|
71
80
|
}
|
|
72
81
|
async updateCheckoutIntentFromEvent(event, status) {
|
|
73
|
-
const intentId = event.metadata?.checkout_intent_id;
|
|
74
|
-
if (
|
|
82
|
+
const intentId = z.string().safeParse(event.metadata?.checkout_intent_id).data;
|
|
83
|
+
if (!intentId)
|
|
75
84
|
return;
|
|
76
85
|
await this.store.updateCheckoutIntent(intentId, { status });
|
|
77
86
|
}
|
|
@@ -103,7 +112,7 @@ export class BillingEventHandlers {
|
|
|
103
112
|
null;
|
|
104
113
|
if (providerPaymentId) {
|
|
105
114
|
const payment = await this.store.getBillingPayment(event.provider, providerPaymentId);
|
|
106
|
-
if (
|
|
115
|
+
if (payment?.userId) {
|
|
107
116
|
event.accountId = payment.userId;
|
|
108
117
|
return payment.userId;
|
|
109
118
|
}
|
|
@@ -138,7 +147,7 @@ export class BillingEventHandlers {
|
|
|
138
147
|
if (event.customer?.providerCustomerId) {
|
|
139
148
|
const uid = await this.resolveAccountId(event);
|
|
140
149
|
if (uid && this.provisioning) {
|
|
141
|
-
await this.
|
|
150
|
+
await this.revokeCustomerAccess(uid);
|
|
142
151
|
}
|
|
143
152
|
}
|
|
144
153
|
return { handled: true, action: "customer_deleted" };
|
|
@@ -185,10 +194,18 @@ export class BillingEventHandlers {
|
|
|
185
194
|
currentPeriodEnd: sub.periodEnd ?? existing?.currentPeriodEnd ?? null,
|
|
186
195
|
trialEnd: sub.trialEnd ?? existing?.trialEnd ?? null,
|
|
187
196
|
cancelAt: sub.cancelAt ?? existing?.cancelAt ?? null,
|
|
188
|
-
endedAt:
|
|
189
|
-
|
|
197
|
+
endedAt: ["incomplete_expired", "canceled", "expired"].includes(status)
|
|
198
|
+
? (sub.endedAt ?? existing?.endedAt ?? null)
|
|
199
|
+
: null,
|
|
200
|
+
graceEndsAt: status === "past_due"
|
|
201
|
+
? overrides && "graceEndsAt" in overrides
|
|
202
|
+
? (overrides.graceEndsAt ?? null)
|
|
203
|
+
: (existing?.graceEndsAt ?? null)
|
|
204
|
+
: null,
|
|
190
205
|
graceExpiredAt: status === "past_due"
|
|
191
|
-
?
|
|
206
|
+
? overrides && "graceExpiredAt" in overrides
|
|
207
|
+
? (overrides.graceExpiredAt ?? null)
|
|
208
|
+
: (existing?.graceExpiredAt ?? null)
|
|
192
209
|
: null,
|
|
193
210
|
providerUpdatedAt: event.occurredAt,
|
|
194
211
|
cancelAtPeriodEnd: overrides?.cancelAtPeriodEnd ??
|
|
@@ -197,7 +214,7 @@ export class BillingEventHandlers {
|
|
|
197
214
|
false,
|
|
198
215
|
interval: overrides?.interval ??
|
|
199
216
|
sub.interval ??
|
|
200
|
-
event.metadata?.billing_interval ??
|
|
217
|
+
z.string().safeParse(event.metadata?.billing_interval).data ??
|
|
201
218
|
existing?.interval ??
|
|
202
219
|
null,
|
|
203
220
|
intervalCount: overrides?.intervalCount ?? sub.intervalCount ?? existing?.intervalCount ?? null,
|
|
@@ -217,8 +234,8 @@ export class BillingEventHandlers {
|
|
|
217
234
|
return {
|
|
218
235
|
offer,
|
|
219
236
|
offerId: offer.offerId,
|
|
220
|
-
offerKey: offer
|
|
221
|
-
plan: offer
|
|
237
|
+
offerKey: offer.offerKey ?? null,
|
|
238
|
+
plan: offer.plan ?? null,
|
|
222
239
|
};
|
|
223
240
|
}
|
|
224
241
|
// Tier 2: Resolve by lookup_key
|
|
@@ -228,14 +245,118 @@ export class BillingEventHandlers {
|
|
|
228
245
|
return {
|
|
229
246
|
offer: lookupOffer,
|
|
230
247
|
offerId: lookupOffer.offerId,
|
|
231
|
-
offerKey: lookupOffer
|
|
232
|
-
plan: lookupOffer
|
|
248
|
+
offerKey: lookupOffer.offerKey ?? null,
|
|
249
|
+
plan: lookupOffer.plan ?? null,
|
|
233
250
|
};
|
|
234
251
|
}
|
|
235
252
|
this.logger.error(`[BillingService] resolveOfferAndKeys: no offer found for ${event.provider}/${refs.lookupKey}`);
|
|
236
253
|
}
|
|
237
254
|
return { offer: null, offerId: null, offerKey: null, plan: null };
|
|
238
255
|
}
|
|
256
|
+
subscriptionPlanAnchor(event, preserveAllowanceAnchor, preservedAllowanceAnchor) {
|
|
257
|
+
if (preserveAllowanceAnchor) {
|
|
258
|
+
if (preservedAllowanceAnchor === null)
|
|
259
|
+
return null;
|
|
260
|
+
const anchor = new Date(preservedAllowanceAnchor);
|
|
261
|
+
if (Number.isNaN(anchor.getTime()))
|
|
262
|
+
return null;
|
|
263
|
+
return anchor.getTime() > Date.now() ? new Date() : anchor;
|
|
264
|
+
}
|
|
265
|
+
const periodStart = event.subscription?.periodStart;
|
|
266
|
+
if (!periodStart)
|
|
267
|
+
return null;
|
|
268
|
+
const anchor = new Date(periodStart);
|
|
269
|
+
if (Number.isNaN(anchor.getTime())) {
|
|
270
|
+
this.logger.warn("[BillingService] invalid periodStart; using database assignment time", {
|
|
271
|
+
periodStart,
|
|
272
|
+
userId: event.accountId ?? null,
|
|
273
|
+
});
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
return anchor;
|
|
277
|
+
}
|
|
278
|
+
async reconcileSubscriptionEvent(uid, event, expected, options) {
|
|
279
|
+
if (!event.subscription || !event.billingEventId) {
|
|
280
|
+
throw new StoreError("subscription reconciliation requires a claimed billing event", {
|
|
281
|
+
indeterminate: true,
|
|
282
|
+
details: { provider: event.provider, providerEventId: event.eventId },
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
const persisted = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
|
|
286
|
+
if (!persisted?.subscriptionId) {
|
|
287
|
+
throw new StoreError("subscription reconciliation requires persisted subscription identity", {
|
|
288
|
+
indeterminate: true,
|
|
289
|
+
details: {
|
|
290
|
+
provider: event.provider,
|
|
291
|
+
providerSubscriptionId: event.subscription.providerSubscriptionId,
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
const applyEntitlement = this.provisioning !== null && this.autoSelectEntitlementSource;
|
|
296
|
+
const planAssignedAt = this.subscriptionPlanAnchor(event, options?.preserveAllowanceAnchor ?? false, options?.preservedAllowanceAnchor ?? null);
|
|
297
|
+
const outcome = await this.store.reconcileSubscriptionEntitlement(uid, persisted.subscriptionId, event.billingEventId, expected.status, expected.providerUpdatedAt, planAssignedAt, applyEntitlement, this.terminalPlanKey, `subscription_${expected.status}`);
|
|
298
|
+
this.logger.info("[BillingService] reconciled subscription entitlement", {
|
|
299
|
+
applyEntitlement,
|
|
300
|
+
outcome,
|
|
301
|
+
provider: event.provider,
|
|
302
|
+
providerSubscriptionId: event.subscription.providerSubscriptionId,
|
|
303
|
+
userId: uid,
|
|
304
|
+
});
|
|
305
|
+
return outcome;
|
|
306
|
+
}
|
|
307
|
+
async applySubscriptionEvent(event, options) {
|
|
308
|
+
const uid = await this.resolveAccountId(event);
|
|
309
|
+
if (!uid)
|
|
310
|
+
return { handled: false, error: "account_not_found" };
|
|
311
|
+
if (!event.subscription?.providerSubscriptionId) {
|
|
312
|
+
return { handled: false, error: "no_subscription_data" };
|
|
313
|
+
}
|
|
314
|
+
const existing = await this.getExistingSubscription(event);
|
|
315
|
+
const resolved = options.resolveOffers === false
|
|
316
|
+
? { offer: null, offerId: null, offerKey: null, plan: null }
|
|
317
|
+
: await this.resolveOfferAndKeys(event);
|
|
318
|
+
const isPlanChange = options.action === "subscription_plan_changed";
|
|
319
|
+
const preservedAllowanceAnchor = isPlanChange && this.provisioning !== null
|
|
320
|
+
? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)
|
|
321
|
+
: null;
|
|
322
|
+
const pending = isPlanChange
|
|
323
|
+
? await this.store.getOpenBillingSubscriptionChange(event.provider, event.subscription.providerSubscriptionId)
|
|
324
|
+
: null;
|
|
325
|
+
const metadata = isPlanChange
|
|
326
|
+
? {
|
|
327
|
+
...(existing?.metadata ?? {}),
|
|
328
|
+
...(event.metadata ?? {}),
|
|
329
|
+
pendingPlanChange: null,
|
|
330
|
+
}
|
|
331
|
+
: undefined;
|
|
332
|
+
const stateOverrides = {
|
|
333
|
+
status: options.status,
|
|
334
|
+
cancelAtPeriodEnd: options.cancelAtPeriodEnd,
|
|
335
|
+
offerKey: resolved.offerKey ?? existing?.offerKey ?? null,
|
|
336
|
+
offerId: resolved.offerId ?? existing?.offerId ?? null,
|
|
337
|
+
plan: resolved.plan ?? existing?.plan ?? null,
|
|
338
|
+
interval: resolved.offer?.interval,
|
|
339
|
+
intervalCount: resolved.offer?.intervalCount,
|
|
340
|
+
metadata,
|
|
341
|
+
};
|
|
342
|
+
if (options.graceEndsAt !== undefined)
|
|
343
|
+
stateOverrides.graceEndsAt = options.graceEndsAt;
|
|
344
|
+
if (options.graceExpiredAt !== undefined) {
|
|
345
|
+
stateOverrides.graceExpiredAt = options.graceExpiredAt;
|
|
346
|
+
}
|
|
347
|
+
const subscriptionState = this.buildSubscriptionState(event, uid, existing, stateOverrides);
|
|
348
|
+
await this.store.upsertBillingSubscription(subscriptionState);
|
|
349
|
+
const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState, {
|
|
350
|
+
preserveAllowanceAnchor: isPlanChange,
|
|
351
|
+
preservedAllowanceAnchor,
|
|
352
|
+
});
|
|
353
|
+
if (outcome === "stale")
|
|
354
|
+
return { handled: true, action: "stale_subscription_event" };
|
|
355
|
+
if (pending) {
|
|
356
|
+
await this.store.updateBillingSubscriptionChange(pending.id, { state: "applied" });
|
|
357
|
+
}
|
|
358
|
+
return { handled: true, action: options.action };
|
|
359
|
+
}
|
|
239
360
|
async handleSubscriptionCreated(event) {
|
|
240
361
|
const uid = await this.resolveAccountId(event);
|
|
241
362
|
this.logger.info("[BillingService] handleSubscriptionCreated", {
|
|
@@ -293,7 +414,7 @@ export class BillingEventHandlers {
|
|
|
293
414
|
// The partial unique index is the final arbiter under concurrent
|
|
294
415
|
// webhooks. Convert its race loser into the same manual-review path as
|
|
295
416
|
// the preflight check instead of retrying a permanently invalid event.
|
|
296
|
-
const code = error.code;
|
|
417
|
+
const code = z.object({ code: z.string().optional() }).safeParse(error).data?.code;
|
|
297
418
|
if (code !== "23505")
|
|
298
419
|
throw error;
|
|
299
420
|
const concurrent = (await this.store.getUserSubscriptions(uid)).find((candidate) => candidate.provider === event.provider &&
|
|
@@ -311,15 +432,19 @@ export class BillingEventHandlers {
|
|
|
311
432
|
});
|
|
312
433
|
return { handled: false, error: "subscription_conflict" };
|
|
313
434
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
435
|
+
const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState);
|
|
436
|
+
if (outcome === "stale") {
|
|
437
|
+
return {
|
|
438
|
+
handled: true,
|
|
439
|
+
action: "stale_subscription_event",
|
|
440
|
+
subscriptionId,
|
|
441
|
+
};
|
|
318
442
|
}
|
|
319
|
-
|
|
443
|
+
const status = event.subscription.status;
|
|
444
|
+
if (["active", "trialing"].includes(status ?? "")) {
|
|
320
445
|
await this.updateCheckoutIntentFromEvent(event, "completed");
|
|
321
446
|
}
|
|
322
|
-
return { handled: true, action: "subscription_created" };
|
|
447
|
+
return { handled: true, action: "subscription_created", subscriptionId };
|
|
323
448
|
}
|
|
324
449
|
async handleSubscriptionUpdated(event) {
|
|
325
450
|
this.logger.info("[BillingService] handleSubscriptionUpdated", {
|
|
@@ -327,140 +452,52 @@ export class BillingEventHandlers {
|
|
|
327
452
|
eventId: event.eventId,
|
|
328
453
|
subId: event.subscription?.providerSubscriptionId,
|
|
329
454
|
});
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const existing = await this.getExistingSubscription(event);
|
|
336
|
-
const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
|
|
337
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
338
|
-
status: event.subscription.status ?? existing?.status ?? "incomplete",
|
|
339
|
-
cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false,
|
|
340
|
-
offerKey: offerKey ?? existing?.offerKey ?? null,
|
|
341
|
-
offerId: offerId ?? existing?.offerId ?? null,
|
|
342
|
-
plan: plan ?? existing?.plan ?? null,
|
|
343
|
-
interval: offer?.interval,
|
|
344
|
-
intervalCount: offer?.intervalCount,
|
|
345
|
-
}));
|
|
346
|
-
if (this.provisioning) {
|
|
347
|
-
await this.reEvaluateAccess(uid, event);
|
|
348
|
-
}
|
|
349
|
-
return { handled: true, action: "subscription_updated" };
|
|
455
|
+
return this.applySubscriptionEvent(event, {
|
|
456
|
+
action: "subscription_updated",
|
|
457
|
+
status: event.subscription?.status,
|
|
458
|
+
cancelAtPeriodEnd: event.subscription?.cancelAtPeriodEnd,
|
|
459
|
+
});
|
|
350
460
|
}
|
|
351
461
|
async handleSubscriptionActivated(event) {
|
|
352
462
|
this.logger.info("[BillingService] handleSubscriptionActivated", {
|
|
353
463
|
provider: event.provider,
|
|
354
464
|
eventId: event.eventId,
|
|
355
465
|
});
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
return { handled: false, error: "account_not_found" };
|
|
359
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
360
|
-
return { handled: false, error: "no_subscription_data" };
|
|
361
|
-
const existing = await this.getExistingSubscription(event);
|
|
362
|
-
const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
|
|
363
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
466
|
+
return this.applySubscriptionEvent(event, {
|
|
467
|
+
action: "subscription_activated",
|
|
364
468
|
status: "active",
|
|
365
|
-
|
|
366
|
-
offerId: offerId ?? existing?.offerId ?? null,
|
|
367
|
-
plan: plan ?? existing?.plan ?? null,
|
|
368
|
-
interval: offer?.interval,
|
|
369
|
-
intervalCount: offer?.intervalCount,
|
|
370
|
-
}));
|
|
371
|
-
if (this.provisioning) {
|
|
372
|
-
await this.provisionSubscription(uid, offer, event);
|
|
373
|
-
}
|
|
374
|
-
return { handled: true, action: "subscription_activated" };
|
|
469
|
+
});
|
|
375
470
|
}
|
|
376
471
|
async handleSubscriptionRenewed(event) {
|
|
377
|
-
const
|
|
378
|
-
|
|
379
|
-
return { handled: false, error: "account_not_found" };
|
|
380
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
381
|
-
return { handled: false, error: "no_subscription_data" };
|
|
382
|
-
const existing = await this.getExistingSubscription(event);
|
|
383
|
-
const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
|
|
384
|
-
const resolvedPlanKey = plan ?? existing?.plan ?? null;
|
|
385
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
472
|
+
const result = await this.applySubscriptionEvent(event, {
|
|
473
|
+
action: "subscription_renewed",
|
|
386
474
|
status: "active",
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
intervalCount: offer?.intervalCount,
|
|
392
|
-
}));
|
|
393
|
-
if (this.provisioning && resolvedPlanKey) {
|
|
394
|
-
await this.provisionSubscription(uid, offer, event);
|
|
475
|
+
});
|
|
476
|
+
if (result.handled && result.action !== "stale_subscription_event") {
|
|
477
|
+
const { offer } = await this.resolveOfferAndKeys(event);
|
|
478
|
+
await this.grantSubscriptionCycle(event, offer);
|
|
395
479
|
}
|
|
396
|
-
|
|
397
|
-
return { handled: true, action: "subscription_renewed" };
|
|
480
|
+
return result;
|
|
398
481
|
}
|
|
399
482
|
async handleSubscriptionPlanChanged(event) {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
return { handled: false, error: "no_subscription_data" };
|
|
405
|
-
const existing = await this.getExistingSubscription(event);
|
|
406
|
-
const { offer, offerId, offerKey, plan } = await this.resolveOfferAndKeys(event);
|
|
407
|
-
// Capture the current allowance anchor before advancing the durable
|
|
408
|
-
// change. The Postgres transition updates the assignment atomically, so
|
|
409
|
-
// reading it afterwards would return the new assignment's timestamp and
|
|
410
|
-
// silently reset the learner's current allowance window.
|
|
411
|
-
const preservedAllowanceAnchor = this.provisioning
|
|
412
|
-
? ((await this.provisioning.getUserPlan(uid))?.planAssignedAt ?? null)
|
|
413
|
-
: undefined;
|
|
414
|
-
const pending = await this.store.getOpenBillingSubscriptionChange(event.provider, event.subscription.providerSubscriptionId);
|
|
415
|
-
if (pending) {
|
|
416
|
-
await this.store.updateBillingSubscriptionChange(pending.id, {
|
|
417
|
-
state: "applied",
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
421
|
-
status: event.subscription.status ?? "active",
|
|
422
|
-
offerKey: offerKey ?? existing?.offerKey ?? null,
|
|
423
|
-
offerId: offerId ?? existing?.offerId ?? null,
|
|
424
|
-
plan: plan ?? existing?.plan ?? null,
|
|
425
|
-
interval: offer?.interval,
|
|
426
|
-
intervalCount: offer?.intervalCount,
|
|
427
|
-
metadata: {
|
|
428
|
-
...(existing?.metadata ?? {}),
|
|
429
|
-
...(event.metadata ?? {}),
|
|
430
|
-
pendingPlanChange: null,
|
|
431
|
-
},
|
|
432
|
-
}));
|
|
433
|
-
if (this.provisioning && (plan ?? existing?.plan)) {
|
|
434
|
-
// Plan-change: prefer new plan over existing (renewal at L422 correctly keeps existing).
|
|
435
|
-
await this.provisionSubscription(uid, offer, event, plan ?? existing?.plan ?? undefined, true, preservedAllowanceAnchor);
|
|
436
|
-
}
|
|
437
|
-
return { handled: true, action: "subscription_plan_changed" };
|
|
483
|
+
return this.applySubscriptionEvent(event, {
|
|
484
|
+
action: "subscription_plan_changed",
|
|
485
|
+
status: event.subscription?.status ?? "active",
|
|
486
|
+
});
|
|
438
487
|
}
|
|
439
488
|
async handleCancellationScheduled(event) {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
return { handled: false, error: "account_not_found" };
|
|
443
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
444
|
-
return { handled: false, error: "no_subscription_data" };
|
|
445
|
-
const existing = await this.getExistingSubscription(event);
|
|
446
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
447
|
-
status: existing?.status ?? event.subscription.status ?? "active",
|
|
489
|
+
return this.applySubscriptionEvent(event, {
|
|
490
|
+
action: "cancellation_scheduled",
|
|
448
491
|
cancelAtPeriodEnd: true,
|
|
449
|
-
|
|
450
|
-
|
|
492
|
+
resolveOffers: false,
|
|
493
|
+
});
|
|
451
494
|
}
|
|
452
495
|
async handleCancellationUnscheduled(event) {
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
return { handled: false, error: "account_not_found" };
|
|
456
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
457
|
-
return { handled: false, error: "no_subscription_data" };
|
|
458
|
-
const existing = await this.getExistingSubscription(event);
|
|
459
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
460
|
-
status: existing?.status ?? event.subscription.status ?? "active",
|
|
496
|
+
return this.applySubscriptionEvent(event, {
|
|
497
|
+
action: "cancellation_unscheduled",
|
|
461
498
|
cancelAtPeriodEnd: false,
|
|
462
|
-
|
|
463
|
-
|
|
499
|
+
resolveOffers: false,
|
|
500
|
+
});
|
|
464
501
|
}
|
|
465
502
|
async handleSubscriptionCanceled(event) {
|
|
466
503
|
this.logger.info("[BillingService] handleSubscriptionCanceled", {
|
|
@@ -483,7 +520,7 @@ export class BillingEventHandlers {
|
|
|
483
520
|
},
|
|
484
521
|
});
|
|
485
522
|
}
|
|
486
|
-
|
|
523
|
+
const subscriptionState = this.buildSubscriptionState(event, uid, existing, {
|
|
487
524
|
status: "canceled",
|
|
488
525
|
cancelAtPeriodEnd: event.subscription.cancelAtPeriodEnd ?? true,
|
|
489
526
|
offerKey: resolved?.offerKey ?? existing?.offerKey ?? null,
|
|
@@ -491,113 +528,40 @@ export class BillingEventHandlers {
|
|
|
491
528
|
plan: resolved?.plan ?? existing?.plan ?? null,
|
|
492
529
|
interval: resolved?.offer?.interval,
|
|
493
530
|
intervalCount: resolved?.offer?.intervalCount,
|
|
494
|
-
})
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
531
|
+
});
|
|
532
|
+
await this.store.upsertBillingSubscription(subscriptionState);
|
|
533
|
+
const outcome = await this.reconcileSubscriptionEvent(uid, event, subscriptionState);
|
|
534
|
+
if (outcome === "stale")
|
|
535
|
+
return { handled: true, action: "stale_subscription_event" };
|
|
498
536
|
return { handled: true, action: "subscription_canceled" };
|
|
499
537
|
}
|
|
500
538
|
async handleSubscriptionExpired(event) {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
return { handled: false, error: "account_not_found" };
|
|
504
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
505
|
-
return { handled: false, error: "no_subscription_data" };
|
|
506
|
-
const existing = await this.getExistingSubscription(event);
|
|
507
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
539
|
+
return this.applySubscriptionEvent(event, {
|
|
540
|
+
action: "subscription_expired",
|
|
508
541
|
status: "expired",
|
|
509
|
-
cancelAtPeriodEnd: event.subscription
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
|
|
513
|
-
}
|
|
514
|
-
return { handled: true, action: "subscription_expired" };
|
|
542
|
+
cancelAtPeriodEnd: event.subscription?.cancelAtPeriodEnd ?? true,
|
|
543
|
+
resolveOffers: false,
|
|
544
|
+
});
|
|
515
545
|
}
|
|
516
546
|
async handleSubscriptionPaused(event) {
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
return { handled: false, error: "account_not_found" };
|
|
520
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
521
|
-
return { handled: false, error: "no_subscription_data" };
|
|
522
|
-
const existing = await this.getExistingSubscription(event);
|
|
523
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
547
|
+
return this.applySubscriptionEvent(event, {
|
|
548
|
+
action: "subscription_paused",
|
|
524
549
|
status: "paused",
|
|
525
|
-
|
|
526
|
-
})
|
|
527
|
-
if (this.provisioning) {
|
|
528
|
-
await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
|
|
529
|
-
}
|
|
530
|
-
return { handled: true, action: "subscription_paused" };
|
|
550
|
+
resolveOffers: false,
|
|
551
|
+
});
|
|
531
552
|
}
|
|
532
553
|
async handleSubscriptionResumed(event) {
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
return { handled: false, error: "account_not_found" };
|
|
536
|
-
if (!event.subscription?.providerSubscriptionId)
|
|
537
|
-
return { handled: false, error: "no_subscription_data" };
|
|
538
|
-
const existing = await this.getExistingSubscription(event);
|
|
539
|
-
const { offer, offerKey, plan } = await this.resolveOfferAndKeys(event);
|
|
540
|
-
await this.store.upsertBillingSubscription(this.buildSubscriptionState(event, uid, existing, {
|
|
554
|
+
return this.applySubscriptionEvent(event, {
|
|
555
|
+
action: "subscription_resumed",
|
|
541
556
|
status: "active",
|
|
542
557
|
cancelAtPeriodEnd: false,
|
|
543
|
-
|
|
544
|
-
plan: plan ?? existing?.plan ?? null,
|
|
545
|
-
}));
|
|
546
|
-
if (this.provisioning) {
|
|
547
|
-
await this.provisionSubscription(uid, offer, event);
|
|
548
|
-
}
|
|
549
|
-
return { handled: true, action: "subscription_resumed" };
|
|
558
|
+
});
|
|
550
559
|
}
|
|
551
560
|
async handleTrialWillEnd(event) {
|
|
552
561
|
// Resolve userId so routeEvent's blanket fireEventCallback has a useful value.
|
|
553
562
|
await this.resolveAccountId(event);
|
|
554
563
|
return { handled: true, action: "trial_will_end_notified" };
|
|
555
564
|
}
|
|
556
|
-
async provisionSubscription(uid, offer, event, planKeyOverride, preserveAllowanceAnchor = false, preservedAllowanceAnchor) {
|
|
557
|
-
if (!this.provisioning) {
|
|
558
|
-
this.logger.debug(`[BillingService] provisionSubscription: no provisioning capability for user ${uid}`);
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
const plan = planKeyOverride ?? offer?.plan;
|
|
562
|
-
if (!plan) {
|
|
563
|
-
this.logger.debug("[BillingService] provisionSubscription skipped (no plan)", { uid });
|
|
564
|
-
return;
|
|
565
|
-
}
|
|
566
|
-
this.logger.debug("[BillingService] provisionSubscription setting plan", { uid, plan });
|
|
567
|
-
let periodStart;
|
|
568
|
-
if (preserveAllowanceAnchor) {
|
|
569
|
-
const existingAnchor = preservedAllowanceAnchor !== undefined
|
|
570
|
-
? preservedAllowanceAnchor
|
|
571
|
-
: (await this.provisioning.getUserPlan(uid))?.planAssignedAt;
|
|
572
|
-
if (existingAnchor) {
|
|
573
|
-
const anchor = new Date(existingAnchor);
|
|
574
|
-
// A provider's subscription period start may actually be its next
|
|
575
|
-
// renewal date. Never let a future anchor hide an already-active
|
|
576
|
-
// entitlement after a plan change.
|
|
577
|
-
if (!Number.isNaN(anchor.getTime()) && anchor.getTime() <= Date.now()) {
|
|
578
|
-
periodStart = anchor;
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
else {
|
|
583
|
-
periodStart = event.subscription?.periodStart;
|
|
584
|
-
}
|
|
585
|
-
const planAssignedAt = periodStart
|
|
586
|
-
? (() => {
|
|
587
|
-
const d = new Date(periodStart);
|
|
588
|
-
return Number.isNaN(d.getTime()) ? undefined : d;
|
|
589
|
-
})()
|
|
590
|
-
: preserveAllowanceAnchor
|
|
591
|
-
? new Date()
|
|
592
|
-
: undefined;
|
|
593
|
-
await this.provisioning.setUserPlan(uid, plan, planAssignedAt);
|
|
594
|
-
if (this.autoSelectEntitlementSource && event.provider) {
|
|
595
|
-
const selected = await this.store.selectSubscriptionEntitlementSource(uid, event.provider, event.subscription?.providerSubscriptionId);
|
|
596
|
-
if (selected) {
|
|
597
|
-
this.logger.debug(`[BillingService] selected ${event.provider} subscription as entitlement source for user ${uid}`);
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
565
|
async grantSubscriptionCycle(event, offer) {
|
|
602
566
|
const credits = offer?.grant?.mode === "cycle_grant" ? offer.grant.credits : null;
|
|
603
567
|
if (!credits || credits.lte(0) || !event.billingEventId || !event.subscription)
|
|
@@ -624,7 +588,7 @@ export class BillingEventHandlers {
|
|
|
624
588
|
});
|
|
625
589
|
await this.store.grantBillingCredit(grantId, `billing:${event.eventId}:subscription-cycle`);
|
|
626
590
|
}
|
|
627
|
-
async
|
|
591
|
+
async revokeCustomerAccess(uid) {
|
|
628
592
|
if (!this.provisioning)
|
|
629
593
|
return;
|
|
630
594
|
if (this.terminalPlanKey) {
|
|
@@ -633,63 +597,5 @@ export class BillingEventHandlers {
|
|
|
633
597
|
}
|
|
634
598
|
await this.provisioning.unsetUserPlan(uid);
|
|
635
599
|
}
|
|
636
|
-
/**
|
|
637
|
-
* Do not revoke access because a stale subscription record ended while a
|
|
638
|
-
* newer subscription for the same user is still active.
|
|
639
|
-
*/
|
|
640
|
-
async revokeIfCurrentSubscription(uid, subscriptionId) {
|
|
641
|
-
const current = await this.store.getUserSubscription(uid, ["active", "trialing", "past_due"]);
|
|
642
|
-
if (!current || current.providerSubscriptionId === subscriptionId) {
|
|
643
|
-
await this.revokeSubscription(uid);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
async reEvaluateAccess(uid, event) {
|
|
647
|
-
if (!this.provisioning || !event.subscription)
|
|
648
|
-
return;
|
|
649
|
-
const status = event.subscription.status;
|
|
650
|
-
// Provider retries (Stripe past_due, Dodo on_hold mapped to past_due)
|
|
651
|
-
// are a grace period. Keep the last paid entitlements until the provider
|
|
652
|
-
// reaches a terminal state instead of revoking access on the first miss.
|
|
653
|
-
if (status && ["active", "trialing"].includes(status)) {
|
|
654
|
-
const offer = await this.resolveOfferFromEvent(event);
|
|
655
|
-
if (offer) {
|
|
656
|
-
await this.provisionSubscription(uid, offer, event);
|
|
657
|
-
}
|
|
658
|
-
else {
|
|
659
|
-
const existing = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
|
|
660
|
-
if (existing?.plan) {
|
|
661
|
-
await this.provisionSubscription(uid, null, event, existing.plan);
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
else if (status === "past_due") {
|
|
666
|
-
const existing = await this.store.getBillingSubscription(event.provider, event.subscription.providerSubscriptionId);
|
|
667
|
-
const graceHasExpired = Boolean(existing?.graceExpiredAt) ||
|
|
668
|
-
(Boolean(existing?.graceEndsAt) &&
|
|
669
|
-
new Date(existing.graceEndsAt).getTime() <= Date.now());
|
|
670
|
-
if (graceHasExpired) {
|
|
671
|
-
await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
|
|
672
|
-
}
|
|
673
|
-
else {
|
|
674
|
-
const offer = await this.resolveOfferFromEvent(event);
|
|
675
|
-
if (offer) {
|
|
676
|
-
await this.provisionSubscription(uid, offer, event);
|
|
677
|
-
}
|
|
678
|
-
else if (existing?.plan) {
|
|
679
|
-
await this.provisionSubscription(uid, null, event, existing.plan);
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
else if (status &&
|
|
684
|
-
["canceled", "expired", "unpaid", "paused", "incomplete_expired"].includes(status)) {
|
|
685
|
-
await this.revokeIfCurrentSubscription(uid, event.subscription.providerSubscriptionId);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
async resolveOfferFromEvent(event) {
|
|
689
|
-
const refs = event.subscription?.refs;
|
|
690
|
-
if (!refs)
|
|
691
|
-
return null;
|
|
692
|
-
return this.resolveBillingOfferCached(event.provider, refs.productId ?? null, refs.priceId ?? null);
|
|
693
|
-
}
|
|
694
600
|
}
|
|
695
601
|
//# sourceMappingURL=event-handlers.js.map
|