import { describe, expect, it, vi } from "vitest"; import { AdminLeadIngestionError, PLATFORM_LEAD_METADATA_KEYS, authenticatePlatformLeadSourceCredential, buildLegacyPlatformLeadActivityId, buildLegacyPlatformLeadExternalId, createAdminLeadIngestionService, createManualPlatformLead, hashPlatformLeadSourceCredential, importPlatformLead, ingestPlatformLead, normalizePlatformLeadPayload, type AdminLeadIngestionRepository, } from "./platform-leads.server.js"; const CREDENTIAL = "platform-source-credential-1234567890"; const FINGERPRINT = "a".repeat(64); function makeRepository(overrides: Partial = {}): AdminLeadIngestionRepository { return { authenticateCredential: vi.fn().mockResolvedValue({ sourceId: "source_1", sourceKey: "website", rateLimitPerMinute: 60 }), ingestS2S: vi.fn().mockResolvedValue({ outcome: "created", lead: { id: "lead_1", status: "new", createdAt: "2026-07-16T12:00:00.000Z" }, }), ingestManaged: vi.fn().mockResolvedValue({ outcome: "created", lead: { id: "lead_2", status: "new", createdAt: "2026-07-16T12:00:00.000Z" }, }), ...overrides, }; } describe("platform lead ingestion domain", () => { it("builds deterministic PII-safe legacy identities from source store and source id", () => { const first = buildLegacyPlatformLeadExternalId({ legacyStore: "lead-inbox-postgres", legacyId: "customer@example.test" }); const replay = buildLegacyPlatformLeadExternalId({ legacyStore: "lead-inbox-postgres", legacyId: "customer@example.test" }); const otherStore = buildLegacyPlatformLeadExternalId({ legacyStore: "hivegrid-cloud-legacy", legacyId: "customer@example.test" }); expect(first).toBe(replay); expect(first).toMatch(/^legacy:lead-inbox-postgres:[a-f0-9]{64}$/u); expect(first).not.toContain("customer@example.test"); expect(otherStore).not.toBe(first); }); it("accepts thin phone- or message-only leads and normalizes contact hints without requiring email", () => { expect(normalizePlatformLeadPayload({ phone: " +49 (30) 1234-567 ", message: " Bitte zurückrufen " })).toMatchObject({ email: null, phone: "+49 (30) 1234-567", normalizedPhone: "+49301234567", message: "Bitte zurückrufen", }); expect(normalizePlatformLeadPayload({ company: " Geerkens GmbH " })).toMatchObject({ company: "Geerkens GmbH" }); }); it("rejects empty leads, malformed optional contacts, oversized fields, and unreviewed metadata keys", () => { expect(() => normalizePlatformLeadPayload({})).toThrowError(AdminLeadIngestionError); expect(() => normalizePlatformLeadPayload({ email: "not-an-email" })).toThrow(/email address is invalid/i); expect(() => normalizePlatformLeadPayload({ phone: "12" })).toThrow(/phone number is invalid/i); expect(() => normalizePlatformLeadPayload({ message: "x".repeat(8_001) })).toThrow(/field message is invalid/i); expect(() => normalizePlatformLeadPayload({ message: "Hello", metadata: { arbitraryPayload: "secret" } })).toThrow(/unsupported key/i); expect(PLATFORM_LEAD_METADATA_KEYS).not.toContain("rawPayload"); }); it("allows only bounded scalar values for reviewed metadata keys", () => { expect( normalizePlatformLeadPayload({ message: "Interested", metadata: { formId: "demo", consent: true, locale: "de", submissionId: 42 }, }).metadata ).toEqual({ formId: "demo", consent: true, locale: "de", submissionId: 42 }); expect(() => normalizePlatformLeadPayload({ message: "Interested", metadata: { formId: Number.NaN } })).toThrow(/value formId is invalid/i); expect(() => normalizePlatformLeadPayload({ message: "Interested", metadata: { formId: { nested: true } } })).toThrow(/value formId is invalid/i); expect(() => normalizePlatformLeadPayload({ message: "Interested", metadata: { formName: "PII\nspill" } })).toThrow(/value formName is invalid/i); }); it("enforces the normalized payload byte ceiling consistently for every intake port", async () => { const oversizedPayload = { externalId: "legacy_oversized", message: "m".repeat(8_000), referrer: "r".repeat(2_048), landingPage: "l".repeat(2_048), utmSource: "s".repeat(500), utmMedium: "m".repeat(500), utmCampaign: "c".repeat(500), utmTerm: "t".repeat(500), utmContent: "u".repeat(500), sourceDetail: "d".repeat(500), firstName: "a".repeat(200), lastName: "b".repeat(200), company: "c".repeat(300), metadata: { formName: "f".repeat(500) }, }; expect(() => normalizePlatformLeadPayload(oversizedPayload)).toThrow(/payload is too large/i); const repository = makeRepository(); const service = createAdminLeadIngestionService(repository); await expect( service.ingestS2S({ channel: "s2s", sourceId: "source_1", sourceCredential: CREDENTIAL, idempotencyKey: "oversized_s2s", requestFingerprint: "a".repeat(64), payload: oversizedPayload, }) ).rejects.toMatchObject({ code: "VALIDATION" }); await expect( service.createManual({ channel: "manual", sourceId: "source_1", actorAdminUserId: "admin_1", reason: "Oversized manual intake", payload: oversizedPayload, }) ).rejects.toMatchObject({ code: "VALIDATION" }); await expect( service.importLead({ channel: "import", sourceId: "source_1", actorAdminUserId: "admin_1", reason: "Oversized legacy import", capturedAt: new Date("2026-07-16T10:00:00.000Z"), payload: oversizedPayload, }) ).rejects.toMatchObject({ code: "VALIDATION" }); expect(repository.ingestS2S).not.toHaveBeenCalled(); expect(repository.ingestManaged).not.toHaveBeenCalled(); }); it("hashes source credentials before repository authentication and fails closed on malformed tokens", async () => { const repository = makeRepository(); const service = createAdminLeadIngestionService(repository); await expect(service.authenticateSourceCredential(CREDENTIAL)).resolves.toMatchObject({ sourceId: "source_1" }); expect(repository.authenticateCredential).toHaveBeenCalledWith(hashPlatformLeadSourceCredential(CREDENTIAL)); expect(hashPlatformLeadSourceCredential(CREDENTIAL)).toMatch(/^[a-f0-9]{64}$/u); await expect(service.authenticateSourceCredential("too-short")).resolves.toBeNull(); expect(repository.authenticateCredential).toHaveBeenCalledTimes(1); }); it("uses one validated service command for S2S intake without accepting a body-defined source", async () => { const repository = makeRepository(); const service = createAdminLeadIngestionService(repository); await expect( service.ingestS2S({ channel: "s2s", sourceId: "source_1", sourceCredential: CREDENTIAL, idempotencyKey: "submission_1", requestFingerprint: FINGERPRINT, payload: { firstName: " Ada ", email: " ADA@Example.test ", metadata: { formId: "demo" } }, }) ).resolves.toMatchObject({ outcome: "created", lead: { id: "lead_1" } }); expect(repository.ingestS2S).toHaveBeenCalledWith( expect.objectContaining({ sourceId: "source_1", credentialHash: hashPlatformLeadSourceCredential(CREDENTIAL), idempotencyKey: "submission_1", requestFingerprint: FINGERPRINT, leadId: expect.stringMatching(/^[0-9a-f-]{36}$/u), activityId: expect.stringMatching(/^[0-9a-f-]{36}$/u), payload: expect.objectContaining({ firstName: "Ada", email: "ada@example.test", normalizedEmail: "ada@example.test" }), }) ); }); it("rejects invalid S2S identity and idempotency values before touching the repository", async () => { const repository = makeRepository(); const service = createAdminLeadIngestionService(repository); const valid = { channel: "s2s" as const, sourceId: "source_1", sourceCredential: CREDENTIAL, idempotencyKey: "submission_1", requestFingerprint: FINGERPRINT, payload: { message: "Hello" }, }; await expect(service.ingestS2S({ ...valid, sourceCredential: "short" })).rejects.toMatchObject({ code: "AUTHENTICATION" }); await expect(service.ingestS2S({ ...valid, requestFingerprint: "not-a-hash" })).rejects.toMatchObject({ code: "VALIDATION" }); await expect(service.ingestS2S({ ...valid, idempotencyKey: "\n" })).rejects.toMatchObject({ code: "VALIDATION" }); expect(repository.ingestS2S).not.toHaveBeenCalled(); }); it("routes manual and import intake through the same repository port and requires stable import identity", async () => { const repository = makeRepository(); const service = createAdminLeadIngestionService(repository); const capturedAt = new Date("2026-03-01T10:00:00.000Z"); await service.createManual({ channel: "manual", sourceId: "source_manual", actorAdminUserId: "admin_1", reason: "Manual lead creation", payload: { company: "Geerkens GmbH" }, }); await service.importLead({ channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", initialStatus: "contacted", reason: "Legacy lead import", capturedAt, payload: { externalId: "lead-inbox:42", message: "Legacy request" }, legacyActivities: [ { externalActivityId: "event_2", occurredAt: new Date("2026-03-01T11:00:00.000Z"), type: "status_changed", payload: { from: "new", to: "contacted", legacyActorRef: "operator_7" }, }, { externalActivityId: "event_1", occurredAt: capturedAt, type: "captured", payload: { legacyType: "captured" }, }, ], }); expect(repository.ingestManaged).toHaveBeenNthCalledWith( 1, expect.objectContaining({ channel: "manual", sourceId: "source_manual", actorAdminUserId: "admin_1" }) ); expect(repository.ingestManaged).toHaveBeenNthCalledWith( 2, expect.objectContaining({ channel: "import", sourceId: "source_legacy", initialStatus: "contacted", capturedAt, payload: expect.objectContaining({ externalId: "lead-inbox:42" }), legacyActivities: [ expect.objectContaining({ id: buildLegacyPlatformLeadActivityId({ sourceId: "source_legacy", externalActivityId: "event_1" }), occurredAt: capturedAt, type: "captured", }), expect.objectContaining({ id: buildLegacyPlatformLeadActivityId({ sourceId: "source_legacy", externalActivityId: "event_2" }), occurredAt: new Date("2026-03-01T11:00:00.000Z"), type: "status_changed", }), ], }) ); await expect( service.importLead({ channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", reason: "Legacy lead import", capturedAt, payload: { externalId: "", message: "Legacy request" }, }) ).rejects.toMatchObject({ code: "VALIDATION" }); await expect( service.importLead({ channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", initialStatus: "trial" as never, reason: "Legacy lead import", capturedAt, payload: { externalId: "lead-inbox:43", message: "Legacy request" }, }) ).rejects.toMatchObject({ code: "VALIDATION" }); }); }); describe("platform lead Prisma repository", () => { it("uses reviewed capability functions for credential resolution and S2S capture", async () => { const queryRaw = vi .fn() .mockResolvedValueOnce([{ source_id: "source_1", source_key: "website", rate_limit_per_minute: 30 }]) .mockResolvedValueOnce([ { result: { outcome: "created", lead: { id: "lead_1", status: "new", createdAt: "2026-07-16T12:00:00.000Z" }, }, }, ]); const client = { $queryRaw: queryRaw }; await expect(authenticatePlatformLeadSourceCredential(CREDENTIAL, { client: client as never })).resolves.toEqual({ sourceId: "source_1", sourceKey: "website", rateLimitPerMinute: 30, }); await expect( ingestPlatformLead( { channel: "s2s", sourceId: "source_1", sourceCredential: CREDENTIAL, idempotencyKey: "submission_1", requestFingerprint: FINGERPRINT, payload: { message: "Interested" }, }, { client: client as never } ) ).resolves.toMatchObject({ outcome: "created" }); expect(String(queryRaw.mock.calls[0]?.[0]?.strings?.join("?"))).toContain("hivegrid_authenticate_admin_lead_source(?)"); expect(String(queryRaw.mock.calls[1]?.[0]?.strings?.join("?"))).toContain("hivegrid_capture_admin_lead("); expect(queryRaw.mock.calls[0]?.[0]?.values).toEqual([hashPlatformLeadSourceCredential(CREDENTIAL)]); }); it("maps capability conflict, in-progress, disabled, and auth outcomes to stable domain error codes", async () => { for (const [outcome, code] of [ ["conflict", "IDEMPOTENCY_CONFLICT"], ["in_progress", "IDEMPOTENCY_IN_PROGRESS"], ["source_disabled", "SOURCE_DISABLED"], ["authentication_failed", "AUTHENTICATION"], ] as const) { const client = { $queryRaw: vi.fn().mockResolvedValue([{ result: { outcome } }]) }; await expect( ingestPlatformLead( { channel: "s2s", sourceId: "source_1", sourceCredential: CREDENTIAL, idempotencyKey: "submission_1", requestFingerprint: FINGERPRINT, payload: { message: "Interested" }, }, { client: client as never } ) ).rejects.toMatchObject({ code }); } }); it("creates manual leads transactionally with source defaults, append-only activities, and a visible duplicate hint", async () => { const create = vi.fn().mockResolvedValue({ id: "lead_2", status: "new", createdAt: new Date("2026-07-16T12:00:00.000Z") }); const tx = { $queryRaw: vi.fn().mockResolvedValue([{ hivegrid_enqueue_admin_lead_audit: true }]), adminUser: { findUnique: vi.fn().mockResolvedValue({ status: "active", roles: [{ adminRoleId: "role_sales" }], }), }, adminLeadSource: { findUnique: vi.fn().mockResolvedValue({ id: "source_manual", enabled: true, defaultAssigneeAdminUserId: "admin_haris" }), }, adminLead: { findUnique: vi.fn(), findFirst: vi.fn().mockResolvedValue({ id: "lead_existing" }), create, }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => unknown) => operation(tx)) }; await expect( createManualPlatformLead( { channel: "manual", sourceId: "source_manual", actorAdminUserId: "admin_1", reason: "Manual lead creation", payload: { email: "ada@example.test" }, }, { client: client as never } ) ).resolves.toMatchObject({ outcome: "created", lead: { id: "lead_2" } }); expect(create).toHaveBeenCalledWith({ data: expect.objectContaining({ sourceId: "source_manual", assignedToAdminUserId: "admin_haris", duplicateHintOfLeadId: "lead_existing", activities: { create: [ expect.objectContaining({ type: "manually_created", actorAdminUserId: "admin_1", payload: { sourceId: "source_manual" } }), expect.objectContaining({ type: "duplicate_hint_recorded", payload: { duplicateHintOfLeadId: "lead_existing" } }), ], }, }), }); }); it("rejects a tampered manual assignee before creating the lead", async () => { const tx = { adminUser: { findUnique: vi.fn().mockResolvedValue(null) }, adminLeadSource: { findUnique: vi.fn().mockResolvedValue({ id: "source_manual", enabled: true, defaultAssigneeAdminUserId: null }), }, adminLead: { findUnique: vi.fn(), findFirst: vi.fn(), create: vi.fn() }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => unknown) => operation(tx)) }; await expect( createManualPlatformLead( { channel: "manual", sourceId: "source_manual", actorAdminUserId: "admin_1", assignedToAdminUserId: "missing_operator", reason: "Manual lead creation", payload: { email: "ada@example.test" }, }, { client: client as never } ) ).rejects.toMatchObject({ code: "VALIDATION" }); expect(tx.adminLead.create).not.toHaveBeenCalled(); }); it("rejects an ineligible source-default assignee during import", async () => { const tx = { adminUser: { findUnique: vi.fn().mockResolvedValue({ user: { active: true, pendingDeletion: false, pseudonymized: false, roles: [] }, }), }, adminLeadSource: { findUnique: vi.fn().mockResolvedValue({ id: "source_legacy", enabled: false, defaultAssigneeAdminUserId: "operator_without_lead_access", }), }, adminLead: { findUnique: vi.fn(), findFirst: vi.fn(), create: vi.fn() }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => unknown) => operation(tx)) }; await expect( importPlatformLead( { channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", reason: "Legacy import", capturedAt: new Date("2026-03-01T09:00:00.000Z"), payload: { externalId: "legacy:store:lead_1", email: "ada@example.test" }, }, { client: client as never } ) ).rejects.toMatchObject({ code: "VALIDATION" }); expect(tx.adminLead.create).not.toHaveBeenCalled(); }); it("imports original lead and legacy activity timestamps atomically without notification side effects", async () => { const capturedAt = new Date("2026-03-01T10:00:00.000Z"); const eventAt = new Date("2026-03-02T12:00:00.000Z"); const create = vi.fn().mockResolvedValue({ id: "lead_imported", status: "contacted", createdAt: capturedAt }); const tx = { $queryRaw: vi.fn().mockResolvedValue([{ hivegrid_enqueue_admin_lead_audit: true }]), adminLeadSource: { findUnique: vi.fn().mockResolvedValue({ id: "source_legacy", enabled: false, defaultAssigneeAdminUserId: null }), }, adminLead: { findUnique: vi.fn().mockResolvedValue(null), findFirst: vi.fn().mockResolvedValue(null), create, }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => unknown) => operation(tx)) }; await expect( importPlatformLead( { channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", initialStatus: "contacted", reason: "Legacy lead import", capturedAt, payload: { externalId: "lead-inbox:99", message: "Legacy request" }, legacyActivities: [ { externalActivityId: "legacy_event_99", occurredAt: eventAt, type: "status_changed", payload: { from: "new", to: "contacted" }, }, ], }, { client: client as never } ) ).resolves.toMatchObject({ outcome: "created", lead: { id: "lead_imported" } }); expect(create).toHaveBeenCalledWith({ data: expect.objectContaining({ sourceId: "source_legacy", externalId: "lead-inbox:99", capturedAt, createdAt: capturedAt, updatedAt: capturedAt, status: "contacted", activities: { create: [ expect.objectContaining({ type: "imported", actorAdminUserId: "admin_1", createdAt: capturedAt }), expect.objectContaining({ id: buildLegacyPlatformLeadActivityId({ sourceId: "source_legacy", externalActivityId: "legacy_event_99" }), type: "status_changed", actorAdminUserId: null, payload: { from: "new", to: "contacted" }, createdAt: eventAt, }), ], }, }), }); }); it("replays imports by source and stable externalId without creating another row", async () => { const existing = { id: "lead_existing", status: "new", createdAt: new Date("2026-03-01T10:00:00.000Z") }; const tx = { $queryRaw: vi.fn().mockResolvedValue([{ hivegrid_enqueue_admin_lead_audit: true }]), adminLeadSource: { findUnique: vi.fn().mockResolvedValue({ id: "source_legacy", enabled: false, defaultAssigneeAdminUserId: null }) }, adminLead: { findUnique: vi.fn().mockResolvedValue(existing), findFirst: vi.fn(), create: vi.fn() }, }; const client = { $transaction: vi.fn(async (operation: (transaction: typeof tx) => unknown) => operation(tx)) }; await expect( importPlatformLead( { channel: "import", sourceId: "source_legacy", actorAdminUserId: "admin_1", reason: "Legacy lead import", capturedAt: existing.createdAt, payload: { externalId: "lead-inbox:42", message: "Legacy" }, }, { client: client as never } ) ).resolves.toEqual({ outcome: "replayed", lead: { id: "lead_existing", status: "new", createdAt: "2026-03-01T10:00:00.000Z" }, }); expect(tx.adminLead.findUnique).toHaveBeenCalledWith({ where: { admin_lead_source_external_id_key: { sourceId: "source_legacy", externalId: "lead-inbox:42" } }, }); expect(tx.adminLead.create).not.toHaveBeenCalled(); }); });