import { describe, expect, it, vi } from "vitest"; import { assignmentRuleMatches, createAdminSalesLeadService, createPrismaAdminSalesLeadRepository, evaluateAdminLeadScore, selectRoundRobinAssignee, type AdminSalesLeadRepository, } from "./admin-sales-leads.server.js"; const actor = { adminUserId: "admin-1", email: "sales@example.test", reason: "Lead qualifizieren und kontrolliert weiterführen", } as const; const leadFacts = { id: "lead-1", sourceId: "source-web", sourceKey: "website", firstName: "Ada", lastName: "Lovelace", email: "ada@example.test", normalizedEmail: "ada@example.test", phone: "+4930123456", normalizedPhone: "+4930123456", company: "Example GmbH", assignedToAdminUserId: null, region: "DACH", country: "DE", } as const; function serviceFixture() { const repository = { listAutomationConfig: vi.fn(async () => ({ assignmentRules: [], scoreRules: [] })), createAssignmentRule: vi.fn(async (input) => input as never), createScoreRule: vi.fn(async (input) => input as never), scoreLead: vi.fn(async () => ({}) as never), enrichLead: vi.fn(async () => ({}) as never), autoAssignLead: vi.fn(async () => ({ leadId: "lead-1", assignedToAdminUserId: "admin-1", ruleId: "rule-1", })), detectDuplicates: vi.fn(async () => ({ candidates: [], duplicateHintOfLeadId: null })), dismissDuplicate: vi.fn(async () => ({}) as never), mergeLeads: vi.fn(async () => ({ survivorLeadId: "lead-1", mergedLeadId: "lead-2", replayed: false, })), convertLead: vi.fn(async () => ({ leadId: "lead-1", companyId: "company-1", contactId: "contact-1", dealId: "deal-1", replayed: false, })), } satisfies AdminSalesLeadRepository; const authorize = vi.fn(async () => undefined); return { repository, authorize, service: createAdminSalesLeadService({ repository, authorize }), }; } describe("admin sales lead qualification domain", () => { it("evaluates score rules in a deterministic, explainable snapshot", () => { const result = evaluateAdminLeadScore(leadFacts, [ { id: "score-source", field: "source", operator: "equals", value: "WEBSITE", points: 25, version: 2, }, { id: "score-region", field: "region", operator: "contains", value: "dach", points: 30, version: 3, }, { id: "score-email", field: "has_email", operator: "equals", value: "true", points: 20, version: 1, }, { id: "score-miss", field: "country", operator: "equals", value: "AT", points: 100, version: 1, }, ]); expect(result).toEqual({ score: 75, scoreBand: "hot", scoreVersion: 3, breakdown: [ { ruleId: "score-source", points: 25 }, { ruleId: "score-region", points: 30 }, { ruleId: "score-email", points: 20 }, ], }); }); it("matches source and region criteria as an AND contract", () => { expect(assignmentRuleMatches({ sourceId: "source-web", region: "dach" }, leadFacts)).toBe(true); expect(assignmentRuleMatches({ sourceId: "source-partner", region: "dach" }, leadFacts)).toBe(false); expect(assignmentRuleMatches({ sourceId: null, region: null }, leadFacts)).toBe(true); }); it("advances and wraps the round-robin cursor without randomness", () => { expect(selectRoundRobinAssignee(["admin-a", "admin-b", "admin-c"], 1)).toEqual({ adminUserId: "admin-b", nextAssigneeIndex: 2, }); expect(selectRoundRobinAssignee(["admin-a", "admin-b", "admin-c"], 5)).toEqual({ adminUserId: "admin-c", nextAssigneeIndex: 0, }); }); }); describe("admin sales lead service", () => { it("uses assignment permission and normalizes round-robin members", async () => { const { service, repository, authorize } = serviceFixture(); await service.createAssignmentRule({ name: " DACH Website ", priority: 10, sourceId: "source-web", region: " DACH ", strategy: "round_robin", roundRobinAdminUserIds: ["admin-b", "admin-a", "admin-b"], actor, }); expect(authorize).toHaveBeenCalledWith("admin_sales.crm.assign"); expect(repository.createAssignmentRule).toHaveBeenCalledWith( expect.objectContaining({ name: "DACH Website", region: "DACH", roundRobinAdminUserIds: ["admin-b", "admin-a"], }) ); }); it("rejects ambiguous assignment rules before persistence", async () => { const { service, repository } = serviceFixture(); await expect( service.createAssignmentRule({ name: "Ungültig", priority: 10, strategy: "fixed", fixedAssigneeAdminUserId: "admin-a", roundRobinAdminUserIds: ["admin-b"], actor, }) ).rejects.toThrow("exactly one fixed operator"); expect(repository.createAssignmentRule).not.toHaveBeenCalled(); }); it("requires merge permission and two distinct lead identities", async () => { const { service, repository } = serviceFixture(); await expect( service.mergeLeads({ candidateId: "candidate-1", survivorLeadId: "lead-1", mergedLeadId: "lead-1", reason: "Doppelte Anfrage", actor, }) ).rejects.toThrow("two different records"); expect(repository.mergeLeads).not.toHaveBeenCalled(); }); }); describe("admin sales lead Prisma repository", () => { it("records rule configuration as shared activity and immutable audit in the same transaction", async () => { const assignmentRule = { id: "assignment-1", createdAt: new Date(), updatedAt: new Date(), archivedAt: null, name: "DACH", active: true, priority: 10, sourceId: "source-web", region: "DACH", strategy: "fixed" as const, fixedAssigneeAdminUserId: "admin-1", roundRobinAdminUserIds: [], nextAssigneeIndex: 0, lastAssignedAt: null, }; const scoreRule = { id: "score-1", createdAt: new Date(), updatedAt: new Date(), archivedAt: null, name: "Website", active: true, priority: 10, field: "source" as const, operator: "equals" as const, value: "website", points: 25, version: 1, }; const tx = { adminLeadSource: { findUnique: vi.fn(async () => ({ id: "source-web" })), }, adminUser: { count: vi.fn(async () => 1), }, adminLeadAssignmentRule: { create: vi.fn(async () => assignmentRule), }, adminLeadScoreRule: { create: vi.fn(async () => scoreRule), }, adminActivity: { create: vi.fn(async () => ({ id: "activity-1" })), }, }; const client = { $transaction: vi.fn( async (run: (transaction: typeof tx) => Promise) => run(tx) ), }; const writeAudit = vi.fn(async () => undefined); const repository = createPrismaAdminSalesLeadRepository(client as never, { writeAudit, }); await repository.createAssignmentRule({ name: "DACH", priority: 10, sourceId: "source-web", strategy: "fixed", fixedAssigneeAdminUserId: "admin-1", actor, }); await repository.createScoreRule({ name: "Website", priority: 10, field: "source", operator: "equals", value: "website", points: 25, actor, }); expect(tx.adminActivity.create).toHaveBeenNthCalledWith(1, { data: expect.objectContaining({ type: "configuration_changed", actorAdminUserId: "admin-1", payload: expect.objectContaining({ configurationType: "lead_assignment_rule", configurationId: "assignment-1", }), }), }); expect(tx.adminActivity.create).toHaveBeenNthCalledWith(2, { data: expect.objectContaining({ type: "configuration_changed", actorAdminUserId: "admin-1", payload: expect.objectContaining({ configurationType: "lead_score_rule", configurationId: "score-1", }), }), }); expect(writeAudit).toHaveBeenCalledTimes(2); }); it("records duplicate detection and dismissal in the lead activity stream", async () => { const detectedCandidate = { id: "candidate-1", primaryLeadId: "lead-1", duplicateLeadId: "lead-2", matchKeys: ["email"], confidenceBasisPoints: 8_000, status: "open" as const, }; const tx = { $queryRaw: vi.fn(async () => [{ id: "lead-1" }]), adminLead: { findUnique: vi.fn(async () => ({ id: "lead-1", archivedAt: null, capturedAt: new Date("2026-07-20T00:00:00.000Z"), normalizedEmail: "ada@example.test", normalizedPhone: null, })), findMany: vi.fn(async () => [ { id: "lead-2", capturedAt: new Date("2026-07-21T00:00:00.000Z"), normalizedEmail: "ada@example.test", normalizedPhone: null, }, ]), update: vi.fn(), }, adminDuplicateCandidate: { upsert: vi.fn(async () => detectedCandidate), findUnique: vi.fn(async () => ({ ...detectedCandidate, primaryLead: { assignedToAdminUserId: "admin-1" }, duplicateLead: { assignedToAdminUserId: "admin-1" }, })), update: vi.fn(async () => ({ ...detectedCandidate, status: "dismissed" as const, })), }, adminActivity: { create: vi.fn(async () => ({ id: "activity-1" })), }, }; const client = { $transaction: vi.fn( async (run: (transaction: typeof tx) => Promise) => run(tx) ), }; const writeAudit = vi.fn(async () => undefined); const repository = createPrismaAdminSalesLeadRepository(client as never, { writeAudit, }); await repository.detectDuplicates({ leadId: "lead-1", actor }); await repository.dismissDuplicate({ candidateId: "candidate-1", reason: "Nach manueller Prüfung keine Dublette", actor, }); expect(tx.adminActivity.create).toHaveBeenNthCalledWith(1, { data: expect.objectContaining({ type: "lead_updated", leadId: "lead-1", payload: expect.objectContaining({ operation: "duplicates_detected", candidateIds: ["candidate-1"], }), }), }); expect(tx.adminActivity.create).toHaveBeenNthCalledWith(2, { data: expect.objectContaining({ type: "lead_updated", leadId: "lead-1", payload: expect.objectContaining({ operation: "duplicate_dismissed", candidateId: "candidate-1", duplicateLeadId: "lead-2", }), }), }); expect(writeAudit).toHaveBeenCalledTimes(2); }); it("rejects a merge unless the supplied open candidate proves the exact survivor pair", async () => { const survivor = { id: "lead-primary", status: "qualified", archivedAt: null, normalizedEmail: "ada@example.test", normalizedPhone: null, convertedCompany: null, convertedContact: null, convertedDeal: null, }; const merged = { ...survivor, id: "lead-duplicate", status: "new", }; const tx = { $queryRaw: vi.fn(async () => []), adminLead: { findUnique: vi.fn(async ({ where }: { where: { id: string } }) => where.id === survivor.id ? survivor : merged ), update: vi.fn(), }, adminMergeRecord: { findUnique: vi.fn(async () => null), create: vi.fn(), }, adminDuplicateCandidate: { findUnique: vi.fn(async () => ({ id: "candidate-1", status: "open", primaryLeadId: "lead-other", duplicateLeadId: merged.id, })), update: vi.fn(), }, adminLeadActivity: { create: vi.fn() }, adminActivity: { create: vi.fn() }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => Promise) => operation(tx) ), }; const repository = createPrismaAdminSalesLeadRepository(client as never, { writeAudit: vi.fn(), }); await expect( repository.mergeLeads({ candidateId: "candidate-1", survivorLeadId: survivor.id, mergedLeadId: merged.id, reason: "Doppelte Anfrage kontrolliert zusammenführen", actor, }) ).rejects.toThrow("matching open duplicate candidate"); expect(tx.adminLead.update).not.toHaveBeenCalled(); expect(tx.adminMergeRecord.create).not.toHaveBeenCalled(); }); it("serializes round-robin selection and persists assignment, notification, activity and audit atomically", async () => { const rules = [ { id: "rule-1", createdAt: new Date(), updatedAt: new Date(), archivedAt: null, name: "Website", active: true, priority: 10, sourceId: "source-web", region: "DACH", strategy: "round_robin" as const, fixedAssigneeAdminUserId: null, roundRobinAdminUserIds: ["admin-a", "admin-b"], nextAssigneeIndex: 1, lastAssignedAt: null, }, ]; const tx = { $queryRaw: vi.fn(async () => [{ id: "locked" }]), adminLead: { findUnique: vi.fn(async () => ({ ...leadFacts, archivedAt: null, metadata: { region: "DACH" }, source: { key: "website" }, qualification: null, })), update: vi.fn(async () => ({ id: "lead-1" })), }, adminLeadAssignmentRule: { findMany: vi.fn(async () => rules), findUnique: vi.fn(async () => rules[0]), update: vi.fn(async () => rules[0]), }, adminUser: { count: vi.fn(async () => 1), }, adminActivity: { create: vi.fn(async () => ({ id: "activity-1" })), }, notificationDelivery: { findFirst: vi.fn(async () => null), create: vi.fn(async () => ({ id: "notification-1" })), }, outboxEvent: { create: vi.fn(async () => ({ id: "outbox-1" })), findUnique: vi.fn(async () => null), }, }; const client = { $transaction: vi.fn(async (run: (transaction: typeof tx) => Promise) => run(tx)), }; const writeAudit = vi.fn(async () => undefined); const repository = createPrismaAdminSalesLeadRepository(client as never, { writeAudit }); await expect(repository.autoAssignLead({ leadId: "lead-1", actor })).resolves.toEqual({ leadId: "lead-1", assignedToAdminUserId: "admin-b", ruleId: "rule-1", }); expect(tx.$queryRaw).toHaveBeenCalledTimes(2); expect(tx.adminLead.update).toHaveBeenCalledWith({ where: { id: "lead-1" }, data: expect.objectContaining({ assignedToAdminUserId: "admin-b", activities: { create: expect.objectContaining({ type: "assigned", payload: expect.objectContaining({ assignmentRuleId: "rule-1", to: "admin-b" }), }), }, }), }); expect(tx.adminLeadAssignmentRule.update).toHaveBeenCalledWith({ where: { id: "rule-1" }, data: { nextAssigneeIndex: 0, lastAssignedAt: expect.any(Date) }, }); expect(tx.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ tenantId: null, userId: null, adminUserId: "admin-b", messageKey: "admin.sales.notifications.leadassigned", sourceKey: "admin-sales:lead-assigned:lead-1:admin-b", }), }); expect(tx.outboxEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ eventType: "notification.platform.requested.v1", dispatchKey: "platform-notification:notification-1", payload: expect.objectContaining({ adminUserId: "admin-b", metadata: { leadId: "lead-1", deeplink: "/sales/leads/lead-1", }, }), }), }); expect(writeAudit).toHaveBeenCalledWith( tx, expect.objectContaining({ action: "admin.sales.lead.autoAssigned", targetId: "lead-1", }) ); }); it("converts one qualified lead into company, contact and first-stage deal in one transaction", async () => { const tx = { $queryRaw: vi.fn(async () => [{ id: "lead-1" }]), adminLead: { findUnique: vi.fn(async () => ({ ...leadFacts, archivedAt: null, status: "qualified", convertedCompany: null, convertedContact: null, convertedDeal: null, duplicateCandidatesPrimary: [], duplicateCandidatesSecondary: [], })), update: vi.fn(async () => ({ id: "lead-1" })), }, adminUser: { count: vi.fn(async () => 1), }, adminPipeline: { findFirst: vi.fn(async () => ({ id: "pipeline-1", stages: [{ id: "stage-lead", probabilityBasisPoints: 1_000 }], })), }, adminCompany: { create: vi.fn(async () => ({ id: "company-1" })), }, adminContact: { create: vi.fn(async () => ({ id: "contact-1" })), }, adminDeal: { create: vi.fn(async () => ({ id: "deal-1" })), }, adminActivity: { create: vi.fn(async () => ({ id: "activity-1" })), }, }; const client = { $transaction: vi.fn(async (run: (transaction: typeof tx) => Promise) => run(tx)), }; const writeAudit = vi.fn(async () => undefined); const repository = createPrismaAdminSalesLeadRepository(client as never, { writeAudit }); await expect( repository.convertLead({ leadId: "lead-1", companyName: "Example GmbH", firstName: "Ada", lastName: "Lovelace", dealTitle: "HiveGrid SaaS", ownerAdminUserId: "admin-1", amountCents: 120_000, nextStep: "Demo terminieren", actor, }) ).resolves.toEqual({ leadId: "lead-1", companyId: "company-1", contactId: "contact-1", dealId: "deal-1", replayed: false, }); expect(tx.adminCompany.create).toHaveBeenCalledWith({ data: expect.objectContaining({ sourceLeadId: "lead-1", ownerAdminUserId: "admin-1" }), }); expect(tx.adminContact.create).toHaveBeenCalledWith({ data: expect.objectContaining({ sourceLeadId: "lead-1", companyId: "company-1" }), }); expect(tx.adminDeal.create).toHaveBeenCalledWith({ data: expect.objectContaining({ sourceLeadId: "lead-1", companyId: "company-1", stageId: "stage-lead", contacts: { create: { contactId: "contact-1", isPrimary: true } }, history: { create: expect.objectContaining({ reason: "lead_conversion", actorAdminUserId: "admin-1" }), }, }), }); expect(tx.adminActivity.create).toHaveBeenCalledWith({ data: expect.objectContaining({ type: "lead_converted", leadId: "lead-1", companyId: "company-1", contactId: "contact-1", dealId: "deal-1", }), }); }); it("replays an already completed conversion without duplicate writes", async () => { const tx = { $queryRaw: vi.fn(async () => [{ id: "lead-1" }]), adminLead: { findUnique: vi.fn(async () => ({ ...leadFacts, archivedAt: null, status: "qualified", convertedCompany: { id: "company-1" }, convertedContact: { id: "contact-1" }, convertedDeal: { id: "deal-1" }, duplicateCandidatesPrimary: [], duplicateCandidatesSecondary: [], })), }, }; const client = { $transaction: vi.fn(async (run: (transaction: typeof tx) => Promise) => run(tx)), }; const repository = createPrismaAdminSalesLeadRepository(client as never); await expect( repository.convertLead({ leadId: "lead-1", companyName: "Example GmbH", firstName: "Ada", lastName: "Lovelace", dealTitle: "HiveGrid SaaS", ownerAdminUserId: "admin-1", actor, }) ).resolves.toEqual({ leadId: "lead-1", companyId: "company-1", contactId: "contact-1", dealId: "deal-1", replayed: true, }); }); it("hides another sales owner's lead before qualification writes run", async () => { const tx = { $queryRaw: vi.fn(async () => [{ id: "lead-foreign" }]), adminLead: { findUnique: vi.fn(async () => ({ ...leadFacts, id: "lead-foreign", assignedToAdminUserId: "admin-2", archivedAt: null, metadata: null, source: { key: "website" }, qualification: null, })), }, adminLeadScoreRule: { findMany: vi.fn(), }, }; const client = { $transaction: vi.fn( async (run: (transaction: typeof tx) => Promise) => run(tx) ), }; const repository = createPrismaAdminSalesLeadRepository(client as never, { accessScope: { adminUserId: "admin-1", canReadAll: false, canWriteAll: false, canReadAllCommunication: false, }, }); await expect( repository.scoreLead({ leadId: "lead-foreign", actor }) ).rejects.toThrow("not found"); expect(tx.adminLeadScoreRule.findMany).not.toHaveBeenCalled(); }); });