import type Stripe from "stripe"; import { createNotificationDelivery } from "@hivegrid/db/notifications.server"; import { db } from "~/utils/db.server"; import { clearTenantSubscriptionCache } from "./subscriptionService"; export const BILLING_DUNNING_DAY_MARKS = [1, 3, 7] as const; const DAY_MS = 24 * 60 * 60 * 1000; const UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE = "billing.stripeWebhook.unknownError"; export type BillingDunningDecision = | { kind: "noop" } | { kind: "send_dunning"; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 } | { kind: "freeze"; thresholdDays: 7 }; export type BillingDunningSubscription = { status: string | null; pastDueSince: Date | string | null; dunningAttemptCount: number | null; }; type BillingDunningDeps = { now?: Date; sendDunningNotice?: (input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }) => Promise; client?: Pick; }; type StripeSubscriptionLike = { id: string; status?: string | null; current_period_start?: number | null; current_period_end?: number | null; cancel_at?: number | null; canceled_at?: number | null; }; function asDate(value: Date | string | null | undefined): Date | null { if (!value) return null; const date = value instanceof Date ? value : new Date(value); return Number.isNaN(date.getTime()) ? null : date; } function fromUnix(value: number | null | undefined): Date | null { return typeof value === "number" && Number.isFinite(value) ? new Date(value * 1000) : null; } function daysSince(from: Date, now: Date): number { return Math.floor((now.getTime() - from.getTime()) / DAY_MS); } export function evaluateBillingDunning(input: BillingDunningSubscription, now: Date = new Date()): BillingDunningDecision { if (input.status !== "past_due") return { kind: "noop" }; const pastDueSince = asDate(input.pastDueSince); if (!pastDueSince) return { kind: "noop" }; const elapsedDays = daysSince(pastDueSince, now); const attempts = Math.max(0, input.dunningAttemptCount ?? 0); if (attempts >= BILLING_DUNNING_DAY_MARKS.length) { return elapsedDays >= 7 ? { kind: "freeze", thresholdDays: 7 } : { kind: "noop" }; } const thresholdDays = BILLING_DUNNING_DAY_MARKS[attempts]; if (elapsedDays < thresholdDays) return { kind: "noop" }; return { kind: "send_dunning", attempt: (attempts + 1) as 1 | 2 | 3, thresholdDays }; } export function billingStatusFromStripeSubscription(status: string | null | undefined): "trial" | "active" | "past_due" | "cancelled" { if (status === "trialing") return "trial"; if (status === "active") return "active"; if (status === "canceled") return "cancelled"; if (status === "past_due" || status === "unpaid" || status === "incomplete" || status === "incomplete_expired") return "past_due"; return "active"; } export async function createBillingDunningNotification(input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }): Promise { await createNotificationDelivery({ tenantId: input.tenantId, channel: "EMAIL", category: "billing", messageKey: `billing.notify.dunning.attempt${input.attempt}`, sourceKey: `billing-dunning:${input.tenantId}:attempt:${input.attempt}`, payloadMetadata: { attempt: input.attempt, thresholdDays: input.thresholdDays, }, }); } export async function applyBillingDunningCycle(deps: BillingDunningDeps = {}) { const client = deps.client ?? db; const now = deps.now ?? new Date(); const sendDunningNotice = deps.sendDunningNotice ?? createBillingDunningNotification; const subscriptions = await client.tenantSubscription.findMany({ where: { status: "past_due", pastDueSince: { not: null } }, select: { tenantId: true, status: true, pastDueSince: true, dunningAttemptCount: true }, }); const results: { tenantId: string; decision: BillingDunningDecision }[] = []; for (const subscription of subscriptions) { const decision = evaluateBillingDunning(subscription, now); if (decision.kind === "send_dunning") { await sendDunningNotice({ tenantId: subscription.tenantId, attempt: decision.attempt, thresholdDays: decision.thresholdDays }); await client.tenantSubscription.update({ where: { tenantId: subscription.tenantId }, data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now }, }); clearTenantSubscriptionCache(subscription.tenantId); } else if (decision.kind === "freeze") { await client.tenantSubscription.update({ where: { tenantId: subscription.tenantId }, data: { status: "frozen", frozenAt: now }, }); clearTenantSubscriptionCache(subscription.tenantId); } results.push({ tenantId: subscription.tenantId, decision }); } return results; } async function setBillingStatusForTenant( tenantId: string, status: "trial" | "active" | "past_due" | "cancelled" | "frozen", now: Date, client: BillingDunningDeps["client"] = db, ) { if (status === "past_due") { const existingSubscription = await client.tenantSubscription.findUnique({ where: { tenantId }, select: { pastDueSince: true }, }); await client.tenantSubscription.update({ where: { tenantId }, data: { status, pastDueSince: existingSubscription?.pastDueSince ?? now, frozenAt: null, }, }); clearTenantSubscriptionCache(tenantId); return; } await client.tenantSubscription.update({ where: { tenantId }, data: { status, pastDueSince: null, frozenAt: null, cancelledAt: status === "cancelled" ? now : null, dunningAttemptCount: 0, lastDunningSentAt: null, }, }); clearTenantSubscriptionCache(tenantId); } function subscriptionIdFromInvoice(invoice: Record): string | null { const direct = invoice.subscription; if (typeof direct === "string") return direct; if (direct && typeof direct === "object" && "id" in direct && typeof direct.id === "string") return direct.id; const parent = invoice.parent as { subscription_details?: { subscription?: unknown } } | null | undefined; const parentSubscription = parent?.subscription_details?.subscription; if (typeof parentSubscription === "string") return parentSubscription; if (parentSubscription && typeof parentSubscription === "object" && "id" in parentSubscription && typeof parentSubscription.id === "string") { return parentSubscription.id; } return null; } async function syncSubscriptionStatusFromStripeSubscription( subscription: StripeSubscriptionLike, now: Date, client: BillingDunningDeps["client"] = db, ): Promise { const tenantProduct = await client.tenantSubscriptionProduct.findFirst({ where: { billingProviderSubscriptionId: subscription.id }, select: { id: true, tenantSubscription: { select: { tenantId: true } } }, }); if (!tenantProduct) return null; await client.tenantSubscriptionProduct.update({ where: { id: tenantProduct.id }, data: { currentPeriodStart: fromUnix(subscription.current_period_start), currentPeriodEnd: fromUnix(subscription.current_period_end), endsAt: fromUnix(subscription.cancel_at), cancelledAt: fromUnix(subscription.canceled_at), }, }); await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, billingStatusFromStripeSubscription(subscription.status), now, client); return tenantProduct.tenantSubscription.tenantId; } async function markInvoiceSubscriptionStatus( invoice: Record, status: "active" | "past_due", now: Date, client: BillingDunningDeps["client"] = db, ): Promise { const subscriptionId = subscriptionIdFromInvoice(invoice); if (!subscriptionId) return null; const tenantProduct = await client.tenantSubscriptionProduct.findFirst({ where: { billingProviderSubscriptionId: subscriptionId }, select: { tenantSubscription: { select: { tenantId: true } } }, }); if (!tenantProduct) return null; await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, status, now, client); return tenantProduct.tenantSubscription.tenantId; } export async function processStripeBillingEvent(event: Stripe.Event, deps: BillingDunningDeps = {}) { const client = deps.client ?? db; const now = deps.now ?? new Date(); const existing = await client.stripeWebhookLog.findUnique({ where: { stripeEventId: event.id } }); if (existing?.processedAt) { return { replayed: true, relatedTenantId: existing.relatedTenantId ?? null }; } await client.stripeWebhookLog.upsert({ where: { stripeEventId: event.id }, create: { stripeEventId: event.id, eventType: event.type }, update: { eventType: event.type, error: null }, }); try { let relatedTenantId: string | null = null; if (event.type === "customer.subscription.updated" || event.type === "customer.subscription.deleted") { relatedTenantId = await syncSubscriptionStatusFromStripeSubscription(event.data.object as StripeSubscriptionLike, now, client); } else if (event.type === "invoice.payment_failed") { relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record, "past_due", now, client); } else if (event.type === "invoice.paid" || event.type === "invoice.payment_succeeded") { relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record, "active", now, client); } await client.stripeWebhookLog.update({ where: { stripeEventId: event.id }, data: { processedAt: now, relatedTenantId, error: null }, }); return { replayed: false, relatedTenantId }; } catch (error) { await client.stripeWebhookLog.update({ where: { stripeEventId: event.id }, data: { error: error instanceof Error ? error.message : UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE }, }); throw error; } }