import { describe, expect, test, vi } from "vitest"; import { assertI18nKey, bundleNotifications, CRITICAL_NOTIFICATION_CATEGORIES, isCriticalNotificationCategory, isNotificationEnabled, notify, notifyPlatform, type NotificationClient, type NotificationInput, type PlatformNotificationClient, } from "./notifications.js"; function createClient() { return { notificationDelivery: { create: vi.fn(async (args: { data: unknown }) => args.data), upsert: vi.fn(async (args: { create: unknown }) => args.create), }, } satisfies NotificationClient; } function createPlatformClient() { const findFirst = vi.fn(async (): Promise => null); const create = vi.fn( async (args: Parameters[0]): Promise => ({ id: "platform_delivery_1", ...args.data, }) ); return { notificationDelivery: { findFirst, create, }, } satisfies PlatformNotificationClient; } describe("assertI18nKey", () => { test("returns valid dotted/dashed lowercase keys", () => { expect(assertI18nKey("foundation.errors.not-found")).toBe("foundation.errors.not-found"); expect(assertI18nKey("a")).toBe("a"); }); test("rejects keys that do not match the i18n key grammar", () => { expect(() => assertI18nKey("Foundation.Bad")).toThrow(/Invalid i18n key/); expect(() => assertI18nKey("1leading.digit")).toThrow(/Invalid i18n key/); expect(() => assertI18nKey("trailing.")).toThrow(/Invalid i18n key/); expect(() => assertI18nKey("")).toThrow(/Invalid i18n key/); }); }); describe("notify payload sanitization", () => { test("keeps boolean and null metadata values while dropping empty keys", async () => { const client = createClient(); await notify( { tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.flags", payloadMetadata: { active: true, dismissed: false, cleared: null, " ": "ignored" }, }, client ); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ payloadMetadata: { active: true, dismissed: false, cleared: null } }), }); }); test("drops non-serializable values and yields null metadata when nothing survives", async () => { const client = createClient(); await notify( { tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.empty", payloadMetadata: { nested: { deep: 1 }, infinite: Number.POSITIVE_INFINITY, broken: Number.NaN }, }, client ); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ payloadMetadata: null }) }); }); test("truncates over-long string metadata to the configured maximum", async () => { const client = createClient(); await notify({ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.long", payloadMetadata: { note: "x".repeat(600) } }, client); const call = client.notificationDelivery.create.mock.calls[0][0] as { data: { payloadMetadata: { note: string } } }; expect(call.data.payloadMetadata.note).toHaveLength(500); }); }); describe("notify status mapping", () => { test("queues EMAIL deliveries as PENDING with no send timestamp", async () => { const client = createClient(); await notify({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" }, client); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ channel: "EMAIL", status: "PENDING", attemptsMade: 0, sentAt: null, lastError: null }), }); }); test("marks deliveries SKIPPED when a preference disables the channel", async () => { const client = createClient(); await notify({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" }, client, [ { tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", enabled: false }, ]); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ status: "SKIPPED", attemptsMade: 0, lastError: "preference_disabled", sentAt: null }), }); }); test("persists a null user id for tenant-wide deliveries", async () => { const client = createClient(); await notify({ tenantId: "tenant_1", messageKey: "foundation.notifications.broadcast" }, client); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ userId: null, channel: "IN_APP", status: "SENT" }) }); // Without a userId the source-key upsert path is never taken. expect(client.notificationDelivery.upsert).not.toHaveBeenCalled(); }); test("rejects an unscoped tenant before any write", async () => { const client = createClient(); await expect(notify({ tenantId: " ", userId: "user_1", messageKey: "foundation.notifications.x" }, client)).rejects.toThrow( "Notification delivery tenant scope is required." ); expect(client.notificationDelivery.create).not.toHaveBeenCalled(); }); }); describe("notifyPlatform", () => { test("persists a tenantless PENDING delivery with a mandatory recipient and source key", async () => { const client = createPlatformClient(); await notifyPlatform( { userId: "user_haris", channel: "EMAIL", category: "Leads", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:email", payloadMetadata: { leadId: "lead_1", sourceId: "hivegrid-website", deeplink: "/leads/lead_1", replay: false, }, }, client ); expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({ where: { tenantId: null, userId: "user_haris", channel: "EMAIL", sourceKey: "platform-lead:lead_1:email", }, }); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ tenantId: null, userId: "user_haris", channel: "EMAIL", category: "leads", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:email", status: "PENDING", attemptsMade: 0, payloadMetadata: { leadId: "lead_1", sourceId: "hivegrid-website", deeplink: "/leads/lead_1", replay: false, }, }), }); }); test("returns an existing logical delivery instead of creating a duplicate", async () => { const client = createPlatformClient(); vi.mocked(client.notificationDelivery.findFirst).mockResolvedValue({ id: "existing_delivery" }); await expect( notifyPlatform( { userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app", }, client ) ).resolves.toEqual({ id: "existing_delivery" }); expect(client.notificationDelivery.create).not.toHaveBeenCalled(); }); test("returns the concurrent winner when the partial unique index rejects a racing insert", async () => { const client = createPlatformClient(); vi.mocked(client.notificationDelivery.findFirst) .mockResolvedValueOnce(null) .mockResolvedValueOnce({ id: "concurrent_delivery" }); vi.mocked(client.notificationDelivery.create).mockRejectedValueOnce(new Error("unique constraint")); await expect( notifyPlatform( { userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app", }, client ) ).resolves.toEqual({ id: "concurrent_delivery" }); expect(client.notificationDelivery.findFirst).toHaveBeenCalledTimes(2); }); test("does not hide an unrelated database failure when no concurrent delivery exists", async () => { const client = createPlatformClient(); const databaseError = new Error("database unavailable"); vi.mocked(client.notificationDelivery.create).mockRejectedValueOnce(databaseError); await expect( notifyPlatform( { userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app", }, client ) ).rejects.toBe(databaseError); expect(client.notificationDelivery.findFirst).toHaveBeenCalledTimes(2); }); test("rejects tenant scope, empty recipients and unstable source keys before a write", async () => { const client = createPlatformClient(); await expect( notifyPlatform( { tenantId: null, userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app", } as never, client ) ).rejects.toThrow("must not accept a tenant scope"); await expect(notifyPlatform({ userId: " ", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app" }, client)).rejects.toThrow( "userId must be a stable non-secret identifier" ); await expect(notifyPlatform({ userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "Bearer secret/value" }, client)).rejects.toThrow( "sourceKey must be a stable non-secret identifier" ); await expect( notifyPlatform( { userId: "user_haris", channel: "SMS" as never, messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:sms", }, client ) ).rejects.toThrow("channel must be IN_APP or EMAIL"); expect(client.notificationDelivery.create).not.toHaveBeenCalled(); }); test("persists only allowlisted PII-minimized metadata", async () => { const client = createPlatformClient(); await notifyPlatform( { userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app", payloadMetadata: { leadId: "lead_1", email: "person@example.test", phone: "+491701234567", message: "private lead message", token: "secret-token", deeplink: "/leads/lead_1?email=person@example.test", }, }, client ); const call = client.notificationDelivery.create.mock.calls[0]?.[0]; expect(call?.data.payloadMetadata).toEqual({ leadId: "lead_1" }); expect(JSON.stringify(call)).not.toContain("person@example.test"); expect(JSON.stringify(call)).not.toContain("private lead message"); expect(JSON.stringify(call)).not.toContain("secret-token"); }); }); describe("isNotificationEnabled", () => { test("defaults to enabled when no preference exists for the scope", () => { expect(isNotificationEnabled({ tenantId: "tenant_1", userId: "user_1", messageKey: "k" }, [])).toBe(true); }); test("normalizes the category before matching preferences", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: " Ops ", messageKey: "k" }; expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }])).toBe(false); }); test("treats a null userId distinctly from a concrete user", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: null, channel: "IN_APP", category: "ops", messageKey: "k" }; expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }])).toBe(true); }); test("critical categories stay enabled even with an explicit disabled preference", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "critical", messageKey: "k" }; expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "critical", enabled: false }])).toBe(true); }); test("critical categories ignore a disabled default fallback", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: " Critical ", messageKey: "k" }; expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }])).toBe(true); }); test("a non-critical category still falls back to the disabled default", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "system", messageKey: "k" }; expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }])).toBe(false); }); }); describe("isCriticalNotificationCategory", () => { test("recognizes the critical category regardless of casing/whitespace", () => { expect(isCriticalNotificationCategory("critical")).toBe(true); expect(isCriticalNotificationCategory(" Critical ")).toBe(true); expect(isCriticalNotificationCategory("system")).toBe(false); expect(isCriticalNotificationCategory(null)).toBe(false); expect(isCriticalNotificationCategory(undefined)).toBe(false); }); test("exposes the critical set for the settings UI to mirror", () => { expect([...CRITICAL_NOTIFICATION_CATEGORIES]).toContain("critical"); }); }); describe("bundleNotifications", () => { test("merges same-scope messages and deduplicates message keys", () => { const bundles = bundleNotifications([ { tenantId: "tenant_1", userId: "user_1", messageKey: "a" }, { tenantId: "tenant_1", userId: "user_1", messageKey: "a" }, { tenantId: "tenant_1", userId: "user_1", messageKey: "b", payloadMetadata: { count: 2 } }, ]); expect(bundles).toEqual([ { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", messageKeys: ["a", "b"], payloadMetadata: { count: 2 }, }, ]); }); test("bundles tenant-wide messages under a null user id", () => { const bundles = bundleNotifications([ { tenantId: "tenant_1", messageKey: "a" }, { tenantId: "tenant_1", messageKey: "b" }, ]); expect(bundles).toHaveLength(1); expect(bundles[0]).toMatchObject({ userId: null, messageKeys: ["a", "b"] }); }); test("separates bundles across distinct channel/category scopes", () => { const bundles = bundleNotifications([ { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", messageKey: "a" }, { tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "ops", messageKey: "b" }, ]); expect(bundles).toHaveLength(2); expect(bundles.map((bundle) => bundle.channel)).toEqual(["IN_APP", "EMAIL"]); }); });