import { describe, expect, it, vi } from "vitest"; const { writeAdminSalesAudit } = vi.hoisted(() => ({ writeAdminSalesAudit: vi.fn(), })); vi.mock("./admin-sales-core.server.js", async (importOriginal) => { const original = await importOriginal(); return { ...original, writeAdminSalesAudit }; }); import { assignAdminEmailMessage, claimAdminEmailSyncTargets, createPrismaAdminEmailSyncRepository, failAdminEmailSyncTarget, findAdminEmailMatchCandidates, } from "./admin-email-sync.server.js"; function txFixture() { return { adminMailboxSyncCursor: { findFirst: vi.fn().mockResolvedValue({ id: "cursor-1" }), updateMany: vi.fn().mockResolvedValue({ count: 1 }), }, adminEmailThread: { upsert: vi.fn().mockResolvedValue({ id: "thread-1" }), update: vi.fn().mockResolvedValue({ id: "thread-1" }), }, adminEmailMessage: { findUnique: vi.fn().mockResolvedValue(null), create: vi.fn().mockResolvedValue({ id: "message-1" }), update: vi.fn().mockResolvedValue({ id: "message-1" }), }, adminEmailParticipant: { upsert: vi.fn().mockResolvedValue({ id: "participant-1" }), }, adminEmailAttachment: { upsert: vi.fn().mockResolvedValue({ id: "attachment-1" }), }, adminNoReplyReminder: { updateMany: vi.fn().mockResolvedValue({ count: 1 }), }, adminActivity: { create: vi.fn().mockResolvedValue({ id: "activity-1" }), }, adminMailbox: { update: vi.fn().mockResolvedValue({ id: "mailbox-1" }), }, }; } const input = { adminUserId: "admin-1", mailboxId: "mailbox-1", externalFolderId: "inbox", expectedCursor: "cursor-1", nextCursor: "cursor-2", messages: [ { providerMessageId: "provider-1", providerThreadId: "provider-thread-1", internetMessageId: "rfc-1", direction: "inbound" as const, from: { address: "BUYER@example.com", name: "Buyer" }, to: [{ address: "sales@hivegrid.de" }], cc: [], bcc: [], subject: "Re: Demo", snippet: "Hallo", bodyHtml: "

Hallo

", bodyText: "Hallo", sentAt: new Date("2026-07-24T10:00:00.000Z"), receivedAt: new Date("2026-07-24T10:00:01.000Z"), isRead: false, isNewsletter: false, providerLabels: ["INBOX"], match: { status: "matched" as const, contactId: "contact-1", leadId: null, dealId: "deal-1", reason: "single_open_deal", candidates: [{ id: "contact-1" }], }, }, ], }; describe("admin email sync persistence", () => { it("persists message, participants, activity and cursor in one transaction", async () => { const tx = txFixture(); const client = { $transaction: vi.fn((callback) => callback(tx)), }; const repository = createPrismaAdminEmailSyncRepository(client as never); await expect(repository.persistBatch(input)).resolves.toEqual({ upserted: 1, replayed: 0, messages: [ { providerMessageId: "provider-1", messageId: "message-1", dealId: "deal-1", }, ], }); expect(tx.adminEmailMessage.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ fromAddress: "buyer@example.com", matchStatus: "matched", matchedContactId: "contact-1", matchedDealId: "deal-1", }), }) ); expect(tx.adminActivity.create).toHaveBeenCalledOnce(); expect(tx.adminNoReplyReminder.updateMany).toHaveBeenCalledWith({ where: { adminUserId: "admin-1", status: "pending", outboundMessage: { threadId: "thread-1", sentAt: { lte: new Date("2026-07-24T10:00:01.000Z") }, }, }, data: { status: "cancelled" }, }); expect(tx.adminMailboxSyncCursor.updateMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ cursorToken: "cursor-1" }), data: expect.objectContaining({ cursorToken: "cursor-2" }), }) ); }); it("treats provider replay as an update without duplicating activity", async () => { const tx = txFixture(); tx.adminEmailMessage.findUnique.mockResolvedValue({ id: "message-1" }); const client = { $transaction: vi.fn((callback) => callback(tx)), }; const repository = createPrismaAdminEmailSyncRepository(client as never); await expect(repository.persistBatch(input)).resolves.toEqual({ upserted: 0, replayed: 1, messages: [ { providerMessageId: "provider-1", messageId: "message-1", dealId: "deal-1", }, ], }); expect(tx.adminEmailMessage.update).toHaveBeenCalledOnce(); expect(tx.adminEmailMessage.create).not.toHaveBeenCalled(); expect(tx.adminActivity.create).not.toHaveBeenCalled(); expect(tx.adminNoReplyReminder.updateMany).not.toHaveBeenCalled(); }); it("stores clean attachment metadata on the matched deal in the same transaction", async () => { const tx = txFixture(); const client = { $transaction: vi.fn((callback) => callback(tx)), }; const repository = createPrismaAdminEmailSyncRepository(client as never); const attachmentInput = { ...input, messages: [ { ...input.messages[0], attachments: [ { providerAttachmentId: "provider-attachment-1", filename: "angebot.pdf", mimeType: "application/pdf", sizeBytes: 128, storageBucket: "hivegrid-files", storageKey: "admin-email/admin-1/mailbox-1/file", checksumSha256: "a".repeat(64), scannedAt: new Date("2026-07-24T10:00:02.000Z"), }, ], }, ], }; await repository.persistBatch(attachmentInput); expect(tx.adminEmailAttachment.upsert).toHaveBeenCalledWith({ where: { admin_email_attachment_message_checksum_key: { messageId: "message-1", checksumSha256: "a".repeat(64), }, }, create: expect.objectContaining({ adminUserId: "admin-1", messageId: "message-1", linkedDealId: "deal-1", storageBucket: "hivegrid-files", }), update: expect.objectContaining({ linkedDealId: "deal-1", storageBucket: "hivegrid-files", }), select: { id: true }, }); expect(tx.adminActivity.create).toHaveBeenCalledTimes(2); }); it("rejects a stale cursor before writing messages", async () => { const tx = txFixture(); tx.adminMailboxSyncCursor.findFirst.mockResolvedValue(null); const client = { $transaction: vi.fn((callback) => callback(tx)), }; const repository = createPrismaAdminEmailSyncRepository(client as never); await expect(repository.persistBatch(input)).rejects.toMatchObject({ code: "stale_cursor", }); expect(tx.adminEmailMessage.create).not.toHaveBeenCalled(); }); }); describe("manual admin email assignment", () => { it("checks message ownership and writes assignment, activity and audit atomically", async () => { const tx = { adminEmailMessage: { findFirst: vi.fn().mockResolvedValue({ id: "message-1", subject: "Demo", matchedLeadId: "lead-1", }), update: vi.fn().mockResolvedValue({ id: "message-1", matchStatus: "manual", }), }, adminContact: { findFirst: vi.fn().mockResolvedValue({ id: "contact-1" }), }, adminDeal: { findFirst: vi.fn().mockResolvedValue({ id: "deal-1" }), }, adminActivity: { create: vi.fn().mockResolvedValue({ id: "activity-1" }), }, }; const client = { $transaction: vi.fn((callback) => callback(tx)) }; await expect( assignAdminEmailMessage(client as never, { adminUserId: "admin-1", messageId: "message-1", contactId: "contact-1", dealId: "deal-1", actor: { adminUserId: "admin-1", email: "raffael@hivegrid.de", reason: "E-Mail einem Sales-Vorgang zuordnen", }, }) ).resolves.toMatchObject({ matchStatus: "manual" }); expect(tx.adminEmailMessage.findFirst).toHaveBeenCalledWith( expect.objectContaining({ where: { id: "message-1", adminUserId: "admin-1" }, }) ); expect(tx.adminEmailMessage.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ matchedContactId: "contact-1", matchedDealId: "deal-1", matchStatus: "manual", }), }) ); expect(tx.adminActivity.create).toHaveBeenCalledOnce(); expect(writeAdminSalesAudit).toHaveBeenCalledOnce(); }); it("rejects an assignment without a contact or deal", async () => { await expect( assignAdminEmailMessage({} as never, { adminUserId: "admin-1", messageId: "message-1", contactId: null, dealId: null, actor: { adminUserId: "admin-1", email: "raffael@hivegrid.de", reason: "E-Mail einem Sales-Vorgang zuordnen", }, }) ).rejects.toThrow("admin_email_assignment_target_required"); }); }); describe("admin email sync worker repository", () => { it("claims each due cursor with a compare-and-set transition", async () => { const updateMany = vi .fn() .mockResolvedValueOnce({ count: 0 }) .mockResolvedValueOnce({ count: 1 }); const tx = { adminMailboxSyncCursor: { updateMany, findMany: vi.fn(async () => [ { id: "cursor-1", adminUserId: "admin-1", mailboxId: "mailbox-1", externalFolderId: "inbox", cursorToken: "delta-1", mailbox: { emailAddress: "sales@hivegrid.de", connectionId: "connection-1", connection: { provider: "microsoft_mail" }, }, }, ]), }, }; const client = { $transaction: vi.fn(async (callback) => callback(tx)), }; await expect( claimAdminEmailSyncTargets(client as never, { now: new Date("2026-07-24T10:00:00.000Z"), }) ).resolves.toEqual([ { cursorId: "cursor-1", adminUserId: "admin-1", mailboxId: "mailbox-1", mailboxAddress: "sales@hivegrid.de", connectionId: "connection-1", provider: "microsoft_mail", externalFolderId: "inbox", cursorToken: "delta-1", }, ]); expect(updateMany).toHaveBeenLastCalledWith( expect.objectContaining({ where: expect.objectContaining({ id: "cursor-1" }), data: expect.objectContaining({ syncStatus: "running" }), }) ); }); it("returns contacts and leads with stable open-deal candidates", async () => { const client = { adminContact: { findMany: vi.fn(async () => [ { id: "contact-1", deals: [ { isPrimary: true, deal: { id: "deal-1" }, }, ], }, ]), }, adminLead: { findMany: vi.fn(async () => [ { id: "lead-1", convertedDeal: null }, ]), }, }; await expect( findAdminEmailMatchCandidates(client as never, "buyer@example.com") ).resolves.toEqual([ { id: "contact-1", kind: "contact", primary: true, openDealIds: ["deal-1"], }, { id: "lead-1", kind: "lead", openDealIds: [], }, ]); }); it("resets an expired provider cursor instead of replaying it", async () => { const update = vi.fn(async () => ({})); await failAdminEmailSyncTarget( { adminMailboxSyncCursor: { update } } as never, { cursorId: "cursor-1", fullResyncRequired: true, errorMessageKey: "admin.sales.email.sync.cursorExpired", } ); expect(update).toHaveBeenCalledWith({ where: { id: "cursor-1" }, data: { cursorToken: null, syncStatus: "pending", recoveryGeneration: { increment: 1 }, lastErrorMessageKey: "admin.sales.email.sync.cursorExpired", }, }); }); });