import { getDbClient } from "./client.server.js"; const NON_RETRYABLE_TERMINAL_RUN_STATUSES = ["cancelled", "unsubscribed"] as const; export type EmailSequenceProviderWebhookResult = | { status: "bounced"; deliveryId: string; runId: string } | { status: "already_bounced"; deliveryId: string; runId: string } | { status: "unknown_delivery" }; export type MarkEmailSequenceDeliveryBouncedInput = { providerMessageId: string; bouncedAt: Date; errorMessage: string; }; type EmailSequenceDeliveryWithRun = { id: string; runId: string; status: string; bouncedAt: Date | null; run: { id: string; status: string; }; }; export type EmailSequenceProviderWebhookTransactionClient = { emailSequenceStepDelivery: { findFirst(args: { where: { providerMessageId: string }; include: { run: { select: { id: true; status: true } } }; }): Promise; updateMany(args: { where: { id: string; status?: { not: string } }; data: { status: "bounced"; bouncedAt: Date; errorMessage: string }; }): Promise<{ count: number }>; }; emailSequenceRun: { updateMany(args: { where: { id: string; status?: { notIn: readonly string[] } }; data: { status: "failed"; completedAt: Date }; }): Promise<{ count: number }>; }; }; export type EmailSequenceProviderWebhookClient = EmailSequenceProviderWebhookTransactionClient & { $transaction(runner: (tx: EmailSequenceProviderWebhookTransactionClient) => Promise): Promise; }; export function markEmailSequenceDeliveryBounced( input: MarkEmailSequenceDeliveryBouncedInput, client: EmailSequenceProviderWebhookClient = getDbClient() as unknown as EmailSequenceProviderWebhookClient ): Promise { return client.$transaction(async (tx) => { const delivery = await tx.emailSequenceStepDelivery.findFirst({ where: { providerMessageId: input.providerMessageId }, include: { run: { select: { id: true, status: true } } }, }); if (!delivery) { return { status: "unknown_delivery" }; } if (delivery.status === "bounced" && delivery.bouncedAt) { return { status: "already_bounced", deliveryId: delivery.id, runId: delivery.runId }; } await tx.emailSequenceStepDelivery.updateMany({ where: { id: delivery.id, status: { not: "bounced" } }, data: { status: "bounced", bouncedAt: input.bouncedAt, errorMessage: input.errorMessage, }, }); await tx.emailSequenceRun.updateMany({ where: { id: delivery.run.id, status: { notIn: NON_RETRYABLE_TERMINAL_RUN_STATUSES } }, data: { status: "failed", completedAt: input.bouncedAt }, }); return { status: "bounced", deliveryId: delivery.id, runId: delivery.runId }; }); }