import type { MappedEmailMessage } from "./email-message-mapping.js"; export type AdminEmailMatchCandidate = { readonly id: string; readonly kind: "contact" | "lead"; readonly primary?: boolean; readonly openDealIds?: readonly string[]; }; export type AdminEmailMatchDecision = { readonly status: "matched" | "ambiguous" | "unmatched"; readonly contactId: string | null; readonly leadId: string | null; readonly dealId: string | null; readonly reason: | "exact_contact" | "exact_lead" | "subject_deal" | "single_open_deal" | "ambiguous_identity" | "ambiguous_deal" | "newsletter" | "no_candidate"; readonly candidates: readonly AdminEmailMatchCandidate[]; }; export type AdminMailboxCursorState = { readonly cursorToken: string | null; readonly status: "pending" | "running" | "complete" | "failed"; readonly recoveryGeneration: number; readonly lastErrorMessageKey: string | null; }; const DEAL_REFERENCE = /\[\s*Deal\s*#\s*([\w-]+)\s*\]/i; export function decideAdminEmailMatch(input: { readonly message: Pick< MappedEmailMessage, "direction" | "from" | "to" | "subject" | "isNewsletter" >; readonly mailboxAddresses: readonly string[]; readonly candidates: readonly AdminEmailMatchCandidate[]; }): AdminEmailMatchDecision { if (input.message.isNewsletter) { return decision("unmatched", "newsletter", input.candidates); } const counterpart = adminEmailCounterpartAddress( input.message, input.mailboxAddresses ); const candidates = counterpart ? [...input.candidates].sort((left, right) => left.id.localeCompare(right.id)) : []; const contacts = candidates.filter((candidate) => candidate.kind === "contact"); const leads = candidates.filter((candidate) => candidate.kind === "lead"); const contact = selectSingleIdentity(contacts); if (contacts.length > 0 && !contact) { return decision("ambiguous", "ambiguous_identity", candidates); } if (!contact && leads.length > 1) { return decision("ambiguous", "ambiguous_identity", candidates); } const identity = contact ?? leads[0] ?? null; if (!identity) { return decision("unmatched", "no_candidate", candidates); } const subjectDealId = input.message.subject?.match(DEAL_REFERENCE)?.[1] ?? null; const openDealIds = [...new Set(identity.openDealIds ?? [])].sort(); if (subjectDealId) { if (!openDealIds.includes(subjectDealId)) { return decision("ambiguous", "ambiguous_deal", candidates, identity); } return decision("matched", "subject_deal", candidates, identity, subjectDealId); } if (openDealIds.length > 1) { return decision("ambiguous", "ambiguous_deal", candidates, identity); } return decision( "matched", openDealIds.length === 1 ? "single_open_deal" : identity.kind === "contact" ? "exact_contact" : "exact_lead", candidates, identity, openDealIds[0] ?? null ); } export function adminEmailCounterpartAddress( message: Pick, mailboxAddresses: readonly string[] ): string | null { const own = new Set(mailboxAddresses.map(normalizeEmail)); if (message.direction === "inbound") { const address = normalizeEmail(message.from.address); return address && !own.has(address) ? address : null; } return ( message.to .map((recipient) => normalizeEmail(recipient.address)) .find((address) => address.length > 0 && !own.has(address)) ?? null ); } export function providerMessageKey(input: { readonly mailboxId: string; readonly providerMessageId: string; }): string { const mailboxId = requiredToken(input.mailboxId, "mailboxId"); const providerMessageId = requiredToken( input.providerMessageId, "providerMessageId" ); return `${mailboxId}:${providerMessageId}`; } export function advanceAdminMailboxCursor(input: { readonly current: AdminMailboxCursorState; readonly nextCursor: string | null; readonly outcome: "success" | "retryable_failure" | "cursor_expired"; readonly errorMessageKey?: string | null; }): AdminMailboxCursorState { if (input.outcome === "cursor_expired") { return Object.freeze({ cursorToken: null, status: "pending", recoveryGeneration: input.current.recoveryGeneration + 1, lastErrorMessageKey: "admin.sales.email.sync.cursorExpired", }); } if (input.outcome === "retryable_failure") { return Object.freeze({ ...input.current, status: "failed", lastErrorMessageKey: input.errorMessageKey ?? "admin.sales.email.sync.retryableFailure", }); } const nextCursor = requiredToken(input.nextCursor ?? "", "nextCursor"); return Object.freeze({ cursorToken: nextCursor, status: "complete", recoveryGeneration: input.current.recoveryGeneration, lastErrorMessageKey: null, }); } export type AdminEmailSyncRepository = { persistBatch(input: { readonly adminUserId: string; readonly mailboxId: string; readonly externalFolderId: string; readonly expectedCursor: string | null; readonly nextCursor: string; readonly messages: ReadonlyArray<{ readonly key: string; readonly message: MappedEmailMessage; readonly match: AdminEmailMatchDecision; readonly attachments: readonly AdminPreparedEmailAttachment[]; }>; }): Promise<{ readonly upserted: number; readonly replayed: number; readonly messages?: readonly { readonly providerMessageId: string; readonly messageId: string; readonly dealId: string | null; }[]; }>; }; export type AdminPreparedEmailAttachment = { readonly providerAttachmentId: string; readonly filename: string; readonly mimeType: string | null; readonly sizeBytes: number; readonly storageBucket: string; readonly storageKey: string; readonly checksumSha256: string; readonly scannedAt: Date; }; export function createAdminEmailSyncService(repository: AdminEmailSyncRepository) { return { async persistProviderBatch(input: { readonly adminUserId: string; readonly mailboxId: string; readonly mailboxAddresses: readonly string[]; readonly externalFolderId: string; readonly expectedCursor: string | null; readonly nextCursor: string; readonly messages: readonly MappedEmailMessage[]; readonly candidatesFor: ( counterpartAddress: string | null ) => Promise; readonly attachmentsFor?: ( message: MappedEmailMessage ) => Promise; }) { const messages = []; for (const message of input.messages) { const counterpart = adminEmailCounterpartAddress( message, input.mailboxAddresses ); const candidates = await input.candidatesFor(counterpart); messages.push({ key: providerMessageKey({ mailboxId: input.mailboxId, providerMessageId: message.providerMessageId, }), message, match: decideAdminEmailMatch({ message, mailboxAddresses: input.mailboxAddresses, candidates, }), attachments: input.attachmentsFor ? await input.attachmentsFor(message) : [], }); } return repository.persistBatch({ adminUserId: requiredToken(input.adminUserId, "adminUserId"), mailboxId: requiredToken(input.mailboxId, "mailboxId"), externalFolderId: requiredToken( input.externalFolderId, "externalFolderId" ), expectedCursor: input.expectedCursor, nextCursor: requiredToken(input.nextCursor, "nextCursor"), messages, }); }, }; } function selectSingleIdentity( candidates: readonly AdminEmailMatchCandidate[] ): AdminEmailMatchCandidate | null { if (candidates.length === 1) return candidates[0] ?? null; const primaries = candidates.filter((candidate) => candidate.primary); return primaries.length === 1 ? primaries[0] ?? null : null; } function decision( status: AdminEmailMatchDecision["status"], reason: AdminEmailMatchDecision["reason"], candidates: readonly AdminEmailMatchCandidate[], identity: AdminEmailMatchCandidate | null = null, dealId: string | null = null ): AdminEmailMatchDecision { return Object.freeze({ status, contactId: identity?.kind === "contact" ? identity.id : null, leadId: identity?.kind === "lead" ? identity.id : null, dealId, reason, candidates: Object.freeze([...candidates]), }); } function normalizeEmail(value: string): string { return value.trim().toLowerCase(); } function requiredToken(value: string, field: string): string { const normalized = value.trim(); if (!normalized || normalized.length > 1_024) { throw new AdminEmailSyncError("invalid_sync_input", field); } return normalized; } export class AdminEmailSyncError extends Error { readonly code = "invalid_sync_input"; readonly field: string; constructor(code: "invalid_sync_input", field: string) { super(code); this.name = "AdminEmailSyncError"; this.field = field; } }