import type { AdminEmailOutboundPolicy, Prisma, PrismaClient, } from "../generated/prisma/client/client.js"; import { writeAdminSalesAudit } from "./admin-sales-core.server.js"; const CLAIM_TIMEOUT_MS = 15 * 60 * 1_000; const SENT_LOOKBACK_MS = 48 * 60 * 60 * 1_000; export type ClaimedAdminEmail = { readonly id: string; readonly adminUserId: string; readonly connectionId: string; readonly provider: "google_mail" | "microsoft_mail"; readonly mailboxId: string; readonly fromAddress: string; readonly fromName: string | null; readonly contactId: string | null; readonly leadId: string | null; readonly dealId: string | null; readonly threadId: string | null; readonly bulkRunId: string | null; readonly providerThreadId: string | null; readonly toAddresses: readonly string[]; readonly ccAddresses: readonly string[]; readonly bccAddresses: readonly string[]; readonly subject: string; readonly bodyHtml: string; readonly bodyText: string | null; readonly idempotencyKey: string; readonly noReplyAfterDays: number | null; readonly trackingEnabled: boolean; readonly liveOpenEnabled: boolean; readonly trackingRetentionDays: number; }; export type AdminEmailDeliveryResult = { readonly inspected: number; readonly claimed: readonly ClaimedAdminEmail[]; readonly blocked: number; readonly deferred: number; readonly recoveredUnknown: number; }; export async function claimDueAdminEmails( client: PrismaClient, input: { readonly now?: Date; readonly take?: number; readonly claimTimeoutMs?: number; } = {} ): Promise { const now = input.now ?? new Date(); const take = Math.max(1, Math.min(input.take ?? 50, 250)); return client.$transaction(async (tx) => { const recovered = await tx.adminScheduledEmail.updateMany({ where: { status: "sending", claimedAt: { lte: new Date( now.getTime() - (input.claimTimeoutMs ?? CLAIM_TIMEOUT_MS) ), }, }, data: { status: "failed", lastErrorMessageKey: "admin.sales.email.delivery.errors.providerOutcomeUnknown", }, }); const candidates = await tx.adminScheduledEmail.findMany({ where: { status: "queued", scheduledFor: { lte: now } }, orderBy: [{ scheduledFor: "asc" }, { id: "asc" }], take, include: { mailbox: { select: { emailAddress: true, displayName: true, status: true, archivedAt: true, connection: { select: { id: true, provider: true, status: true, archivedAt: true, }, }, }, }, thread: { select: { providerThreadId: true } }, }, }); const recentSent = await tx.adminScheduledEmail.findMany({ where: { status: "sent", sentAt: { gte: new Date(now.getTime() - SENT_LOOKBACK_MS) }, }, select: { adminUserId: true, sentAt: true }, }); const policyByOwner = new Map(); const claimed: ClaimedAdminEmail[] = []; let blocked = 0; let deferred = 0; for (const candidate of candidates) { let policy = policyByOwner.get(candidate.adminUserId); if (policy === undefined) { policy = await tx.adminEmailOutboundPolicy.findUnique({ where: { adminUserId: candidate.adminUserId }, }); policyByOwner.set(candidate.adminUserId, policy); } if ( !isConfiguredPolicy(policy) || candidate.mailbox.status !== "active" || candidate.mailbox.archivedAt || candidate.mailbox.connection.status !== "active" || candidate.mailbox.connection.archivedAt || !isMailProvider(candidate.mailbox.connection.provider) ) { await tx.adminScheduledEmail.updateMany({ where: { id: candidate.id, status: "queued" }, data: { status: "blocked", lastErrorMessageKey: "admin.sales.email.delivery.errors.outboundLocked", }, }); blocked += 1; continue; } if (!isInsideAdminEmailWorkWindow(policy, now)) { deferred += 1; continue; } const localDay = localDateKey(now, policy.timeZone); const sentToday = recentSent.filter( (row) => row.adminUserId === candidate.adminUserId && row.sentAt && localDateKey(row.sentAt, policy.timeZone) === localDay ).length + claimed.filter((row) => row.adminUserId === candidate.adminUserId) .length; if (sentToday >= policy.dailySendLimit) { await tx.adminScheduledEmail.updateMany({ where: { id: candidate.id, status: "queued" }, data: { lastErrorMessageKey: "admin.sales.email.delivery.errors.dailySendLimitReached" }, }); deferred += 1; continue; } const claim = await tx.adminScheduledEmail.updateMany({ where: { id: candidate.id, status: "queued" }, data: { status: "sending", claimedAt: now, sendAttemptCount: { increment: 1 }, lastErrorMessageKey: null, }, }); if (claim.count !== 1) continue; if (candidate.bulkRunId) { await tx.adminBulkEmailRun.updateMany({ where: { id: candidate.bulkRunId, status: "queued" }, data: { status: "running" }, }); } claimed.push({ id: candidate.id, adminUserId: candidate.adminUserId, connectionId: candidate.mailbox.connection.id, provider: candidate.mailbox.connection.provider, mailboxId: candidate.mailboxId, fromAddress: candidate.mailbox.emailAddress, fromName: candidate.mailbox.displayName, contactId: candidate.contactId, leadId: candidate.leadId, dealId: candidate.dealId, threadId: candidate.threadId, bulkRunId: candidate.bulkRunId, providerThreadId: candidate.thread?.providerThreadId ?? null, toAddresses: candidate.toAddresses, ccAddresses: candidate.ccAddresses, bccAddresses: candidate.bccAddresses, subject: candidate.subject, bodyHtml: candidate.bodyHtml, bodyText: candidate.bodyText, idempotencyKey: candidate.idempotencyKey, noReplyAfterDays: candidate.noReplyAfterDays, trackingEnabled: policy.trackingEnabled, liveOpenEnabled: policy.liveOpenEnabled, trackingRetentionDays: policy.trackingRetentionDays, }); } return { inspected: candidates.length, claimed, blocked, deferred, recoveredUnknown: recovered.count, }; }); } export async function completeAdminEmailDelivery( client: PrismaClient, input: { readonly email: ClaimedAdminEmail; readonly providerMessageId: string | null; readonly providerThreadId?: string | null; readonly sentAt?: Date; readonly deliveredBodyHtml?: string; readonly trackingLinks?: readonly { readonly destinationUrl: string; readonly trackingTokenHash: string; }[]; } ): Promise<{ readonly messageId: string }> { const sentAt = input.sentAt ?? new Date(); return client.$transaction(async (tx) => { const scheduled = await tx.adminScheduledEmail.findFirst({ where: { id: input.email.id, status: "sending" }, select: { id: true }, }); if (!scheduled) { throw new AdminEmailDeliveryError("delivery_not_claimed"); } const thread = input.email.threadId ? await tx.adminEmailThread.findFirst({ where: { id: input.email.threadId, adminUserId: input.email.adminUserId, mailboxId: input.email.mailboxId, }, }) : null; const activeThread = thread ?? (await tx.adminEmailThread.create({ data: { adminUserId: input.email.adminUserId, mailboxId: input.email.mailboxId, providerThreadId: input.providerThreadId ?? `scheduled:${input.email.id}`, normalizedSubject: input.email.subject.trim().toLowerCase(), latestMessageAt: sentAt, messageCount: 0, }, })); const providerMessageId = input.providerMessageId ?? `scheduled:${input.email.id}`; const message = await tx.adminEmailMessage.create({ data: { adminUserId: input.email.adminUserId, mailboxId: input.email.mailboxId, threadId: activeThread.id, providerMessageId, direction: "outbound", fromAddress: input.email.fromAddress, subject: input.email.subject, snippet: input.email.bodyText?.slice(0, 500) ?? null, bodyHtml: input.deliveredBodyHtml ?? input.email.bodyHtml, bodyText: input.email.bodyText, sentAt, isRead: true, matchStatus: "manual", matchedContactId: input.email.contactId, matchedLeadId: input.email.leadId, matchedDealId: input.email.dealId, matchedAt: sentAt, matchedByAdminUserId: input.email.adminUserId, matchingReason: "admin_scheduled_send", participants: { create: [ { adminUserId: input.email.adminUserId, kind: "from", emailAddress: input.email.fromAddress, displayName: input.email.fromName, }, ...input.email.toAddresses.map((emailAddress) => ({ adminUserId: input.email.adminUserId, kind: "to", emailAddress, })), ...input.email.ccAddresses.map((emailAddress) => ({ adminUserId: input.email.adminUserId, kind: "cc", emailAddress, })), ...input.email.bccAddresses.map((emailAddress) => ({ adminUserId: input.email.adminUserId, kind: "bcc", emailAddress, })), ], }, events: { create: { adminUserId: input.email.adminUserId, type: "sent", providerEventId: `scheduled:${input.email.id}`, occurredAt: sentAt, }, }, ...(input.trackingLinks?.length ? { links: { create: input.trackingLinks.map((link) => ({ adminUserId: input.email.adminUserId, destinationUrl: link.destinationUrl, trackingTokenHash: link.trackingTokenHash, })), }, } : {}), }, select: { id: true }, }); await tx.adminEmailThread.update({ where: { id: activeThread.id }, data: { latestMessageAt: sentAt, messageCount: { increment: 1 }, }, }); await tx.adminActivity.create({ data: { type: "email", actorAdminUserId: input.email.adminUserId, contactId: input.email.contactId, leadId: input.email.leadId, dealId: input.email.dealId, emailMessageId: message.id, occurredAt: sentAt, summary: `E-Mail gesendet: ${input.email.subject}`, payload: { scheduledEmailId: input.email.id, recipientCount: input.email.toAddresses.length, }, }, }); await tx.adminScheduledEmail.update({ where: { id: input.email.id }, data: { status: "sent", sentAt, providerMessageId, sentMessageId: message.id, lastErrorMessageKey: null, }, }); if (input.email.noReplyAfterDays) { await tx.adminNoReplyReminder.upsert({ where: { idempotencyKey: `admin-email-no-reply:${message.id}`, }, create: { adminUserId: input.email.adminUserId, outboundMessageId: message.id, dueAt: new Date( sentAt.getTime() + input.email.noReplyAfterDays * 24 * 60 * 60 * 1_000 ), status: "pending", idempotencyKey: `admin-email-no-reply:${message.id}`, }, update: {}, }); } if (input.email.bulkRunId) { await recordAdminBulkEmailOutcome(tx, input.email.bulkRunId, "sent"); } await writeAdminSalesAudit(tx, { actor: { adminUserId: input.email.adminUserId, email: "system@worker.invalid", reason: "Zeitgesteuerte Admin-Sales-E-Mail zugestellt", }, action: "admin.sales.email.send.completed", targetType: "AdminScheduledEmail", targetId: input.email.id, after: { messageId: message.id, providerMessageId, sentAt: sentAt.toISOString(), } as Prisma.InputJsonValue, }); return { messageId: message.id }; }); } export async function failAdminEmailDelivery( client: PrismaClient, input: { readonly id: string; readonly errorMessageKey: | "admin.sales.email.delivery.errors.providerSendFailed" | "admin.sales.email.delivery.errors.providerOutcomeUnknown"; } ): Promise { return client.$transaction(async (tx) => { const scheduled = await tx.adminScheduledEmail.findFirst({ where: { id: input.id, status: "sending" }, select: { bulkRunId: true }, }); if (!scheduled) return false; const result = await tx.adminScheduledEmail.updateMany({ where: { id: input.id, status: "sending" }, data: { status: "failed", lastErrorMessageKey: input.errorMessageKey, }, }); if (result.count === 1 && scheduled.bulkRunId) { await recordAdminBulkEmailOutcome(tx, scheduled.bulkRunId, "failed"); } return result.count === 1; }); } export async function fireDueAdminNoReplyReminders( client: PrismaClient, input: { readonly now?: Date; readonly take?: number; } = {} ): Promise<{ readonly scanned: number; readonly created: number }> { const now = input.now ?? new Date(); const take = Math.max(1, Math.min(input.take ?? 100, 500)); const candidates = await client.adminNoReplyReminder.findMany({ where: { status: "pending", dueAt: { lte: now }, }, orderBy: [{ dueAt: "asc" }, { id: "asc" }], take, select: { id: true }, }); let created = 0; for (const candidate of candidates) { const didCreate = await client.$transaction(async (tx) => { const reminder = await tx.adminNoReplyReminder.findFirst({ where: { id: candidate.id, status: "pending", dueAt: { lte: now }, }, select: { id: true, adminUserId: true, outboundMessageId: true, outboundMessage: { select: { matchedContactId: true, matchedLeadId: true, matchedDealId: true, subject: true, }, }, }, }); if (!reminder) return false; const claim = await tx.adminNoReplyReminder.updateMany({ where: { id: reminder.id, status: "pending" }, data: { status: "fired" }, }); if (claim.count !== 1) return false; const policy = await tx.adminEmailOutboundPolicy.findUnique({ where: { adminUserId: reminder.adminUserId }, select: { timeZone: true }, }); const activity = await tx.adminActivity.create({ data: { type: "task_created", actorAdminUserId: reminder.adminUserId, contactId: reminder.outboundMessage.matchedContactId, leadId: reminder.outboundMessage.matchedLeadId, dealId: reminder.outboundMessage.matchedDealId, emailMessageId: reminder.outboundMessageId, occurredAt: now, summary: "Nachfass-Aufgabe aus E-Mail-Erinnerung erstellt", payload: { noReplyReminderId: reminder.id, }, }, select: { id: true }, }); const task = await tx.adminTask.create({ data: { title: reminder.outboundMessage.subject ? `E-Mail nachfassen: ${reminder.outboundMessage.subject}` : "E-Mail nachfassen", contactId: reminder.outboundMessage.matchedContactId, dealId: reminder.outboundMessage.matchedDealId, assignedToAdminUserId: reminder.adminUserId, createdByAdminUserId: reminder.adminUserId, dueAt: now, timeZone: policy?.timeZone ?? "Europe/Berlin", reminderAt: now, priority: "normal", source: "email", sourceActivityId: activity.id, }, select: { id: true }, }); await Promise.all([ tx.adminActivity.update({ where: { id: activity.id }, data: { taskId: task.id }, }), tx.adminNoReplyReminder.update({ where: { id: reminder.id }, data: { taskId: task.id }, }), ]); await writeAdminSalesAudit(tx, { actor: { adminUserId: reminder.adminUserId, email: "system@worker.invalid", reason: "Nachfass-Erinnerung nach ausbleibender E-Mail-Antwort", }, action: "admin.sales.email.no_reply_reminder.fired", targetType: "AdminNoReplyReminder", targetId: reminder.id, after: { taskId: task.id, outboundMessageId: reminder.outboundMessageId, } as Prisma.InputJsonValue, }); return true; }); if (didCreate) created += 1; } return { scanned: candidates.length, created }; } async function recordAdminBulkEmailOutcome( tx: Prisma.TransactionClient, bulkRunId: string, outcome: "sent" | "failed" ) { const run = await tx.adminBulkEmailRun.update({ where: { id: bulkRunId }, data: outcome === "sent" ? { sentCount: { increment: 1 } } : { failedCount: { increment: 1 } }, select: { recipientCount: true, sentCount: true, failedCount: true, }, }); if (run.sentCount + run.failedCount >= run.recipientCount) { await tx.adminBulkEmailRun.update({ where: { id: bulkRunId }, data: { status: run.failedCount > 0 ? "failed" : "complete", lastErrorMessageKey: run.failedCount > 0 ? "admin.sales.email.delivery.errors.bulkRecipientFailed" : null, }, }); } } export function isInsideAdminEmailWorkWindow( policy: Pick< AdminEmailOutboundPolicy, | "timeZone" | "allowedWeekDays" | "workdayStartMinutes" | "workdayEndMinutes" >, now: Date ): boolean { const parts = zonedParts(now, policy.timeZone); const minuteOfDay = parts.hour * 60 + parts.minute; return ( policy.allowedWeekDays.includes(parts.weekDay) && minuteOfDay >= policy.workdayStartMinutes && minuteOfDay < policy.workdayEndMinutes ); } function isConfiguredPolicy( policy: AdminEmailOutboundPolicy | null ): policy is AdminEmailOutboundPolicy { return Boolean( policy?.configuredAt && policy.consentRulesConfigured && policy.dailySendLimit > 0 && policy.allowedWeekDays.length > 0 && policy.workdayStartMinutes < policy.workdayEndMinutes ); } function localDateKey(date: Date, timeZone: string): string { const parts = zonedParts(date, timeZone); return `${parts.year}-${String(parts.month).padStart(2, "0")}-${String( parts.day ).padStart(2, "0")}`; } function zonedParts(date: Date, timeZone: string) { let values: Record; try { values = Object.fromEntries( new Intl.DateTimeFormat("en-US", { timeZone, weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23", }) .formatToParts(date) .map((part) => [part.type, part.value]) ); } catch { throw new AdminEmailDeliveryError("invalid_time_zone"); } const weekDay = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf( values.weekday ?? "" ); if (weekDay < 0) { throw new AdminEmailDeliveryError("invalid_time_zone"); } return { year: Number(values.year), month: Number(values.month), day: Number(values.day), hour: Number(values.hour), minute: Number(values.minute), weekDay, }; } function isMailProvider( value: string ): value is "google_mail" | "microsoft_mail" { return value === "google_mail" || value === "microsoft_mail"; } export class AdminEmailDeliveryError extends Error { readonly code: string; constructor(code: string) { super(code); this.name = "AdminEmailDeliveryError"; this.code = code; } }