import "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { MemoryRouter } from "react-router"; vi.mock("@hivegrid/db/notifications.server", () => ({ getUserNotificationPreferences: vi.fn(), upsertUserNotificationPreference: vi.fn(), })); vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: vi.fn(), })); vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(), })); vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn(), })); vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf-test-token" }), })); const routeTranslations: Record = { "settings.notifications.heading": "Notification preferences", "settings.notifications.description": "Choose which workspace updates you receive in-app and by email. Preferences are scoped to your current workspace and user account.", "settings.notifications.saved": "Notification preference saved.", "settings.notifications.categories.default": "Default", "settings.notifications.categories.billing": "Billing", "settings.notifications.categories.team": "Team", "settings.notifications.modules.general": "General", "settings.notifications.modules.billing": "Billing module", "settings.notifications.modules.team": "Team module", "settings.notifications.master.heading": "Email master switch", "settings.notifications.master.description": "Turns off all email notifications at once.", "settings.notifications.master.disableAllEmails": "Disable all emails", "settings.notifications.master.save": "Save all", "settings.notifications.channels.inApp": "In-app", "settings.notifications.channels.email": "Email", "settings.notifications.errors.invalidPreferenceAction": "Invalid notification preference action.", "settings.notifications.errors.invalidPreferenceCategory": "Invalid notification preference category.", "settings.notifications.errors.invalidPreferenceChannel": "Invalid notification preference channel.", "shared.save": "Save", }; vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => routeTranslations[key] ?? key, })), })); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string, options?: Record) => { if (key === "settings.notifications.categoryDescription") { return `Manage ${options?.category ?? ""} workspace notifications.`; } return routeTranslations[key] ?? key; }, }), })); vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, useActionData: () => routeActionData, useLoaderData: () => routeLoaderData, useFetcher: () => ({ submit: vi.fn(), data: routeActionData, state: "idle" }), }; }); import { buildNotificationSettingsVM } from "@hivegrid/view-models"; import { getUserNotificationPreferences, upsertUserNotificationPreference } from "@hivegrid/db/notifications.server"; import { requireAuth } from "~/utils/loaders.middleware"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { getUserInfo } from "~/utils/session.server"; import WorkspaceNotificationSettingsRoute, { action, loader } from "./notifications"; let routeLoaderData: unknown; let routeActionData: unknown; const request = new Request("https://app.example.test/acme/settings/notifications"); const params = { tenant: "acme" }; function routeArgs(customRequest: Request = request) { return { request: customRequest, params, context: {}, unstable_pattern: "app.$tenant/settings/notifications" }; } function postFormRequest(formData: FormData) { return new Request(request.url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(formData as unknown as Record), }); } function preferenceForm(overrides?: Record) { const form = new FormData(); form.set("action", "update-preference"); form.set("category", "billing"); form.set("channel", "EMAIL"); form.set("enabled", "on"); Object.entries(overrides ?? {}).forEach(([key, value]) => form.set(key, value)); return form; } describe("workspace notification settings route", () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1"); vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never); vi.mocked(getUserNotificationPreferences).mockResolvedValue([]); vi.mocked(upsertUserNotificationPreference).mockResolvedValue({ id: "pref_1" }); routeLoaderData = { vm: buildNotificationSettingsVM([ { category: "billing", channel: "EMAIL", enabled: false }, { category: "team", channel: "IN_APP", enabled: false }, ]), }; routeActionData = undefined; }); it("requires auth and loads notification preferences only for the current tenant and user", async () => { vi.mocked(getUserNotificationPreferences).mockResolvedValue([ { tenantId: "tenant_1", userId: "user_1", category: "billing", channel: "EMAIL", enabled: false }, { tenantId: "tenant_1", userId: "user_1", category: "team", channel: "IN_APP", enabled: false }, { tenantId: "tenant_1", userId: "user_1", category: "unknown", channel: "EMAIL", enabled: false }, ] as never); const response = (await loader(routeArgs())) as Response; const body = await response.json(); expect(requireAuth).toHaveBeenCalledWith({ request, params }); expect(getTenantIdFromUrl).toHaveBeenCalledWith(params); expect(getUserInfo).toHaveBeenCalledWith(request); expect(getUserNotificationPreferences).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" }); expect(body.vm.status).toBe("ready"); const channels = Object.fromEntries( body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record }[] }) => group.categories.map((category) => [category.category, category.channels]), ), ); expect(channels).toEqual({ default: { IN_APP: true, EMAIL: true }, billing: { IN_APP: true, EMAIL: false }, team: { IN_APP: false, EMAIL: true }, }); expect(JSON.stringify(body)).not.toContain("unknown"); }); it("shows category preferences using the same default fallback as the worker", async () => { vi.mocked(getUserNotificationPreferences).mockResolvedValue([{ tenantId: "tenant_1", userId: "user_1", category: "default", channel: "EMAIL", enabled: false }] as never); const response = (await loader(routeArgs())) as Response; const body = await response.json(); expect(body.vm.data.allEmailsDisabled).toBe(true); const channels = Object.fromEntries( body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record }[] }) => group.categories.map((category) => [category.category, category.channels]), ), ); expect(channels).toEqual({ default: { IN_APP: true, EMAIL: false }, billing: { IN_APP: true, EMAIL: false }, team: { IN_APP: true, EMAIL: false }, }); }); it("returns bounded 400 JSON for an invalid category without calling upsert", async () => { const form = preferenceForm({ category: "security" }); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(response.status).toBe(400); expect(body).toEqual({ error: "Invalid notification preference category." }); expect(upsertUserNotificationPreference).not.toHaveBeenCalled(); }); it("returns bounded 400 JSON for an invalid notification action without calling upsert", async () => { const form = preferenceForm({ action: "delete-preference" }); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(response.status).toBe(400); expect(body).toEqual({ error: "Invalid notification preference action." }); expect(upsertUserNotificationPreference).not.toHaveBeenCalled(); }); it("returns bounded 400 JSON for an invalid channel without calling upsert", async () => { const form = preferenceForm({ channel: "SMS" }); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(response.status).toBe(400); expect(body).toEqual({ error: "Invalid notification preference channel." }); expect(upsertUserNotificationPreference).not.toHaveBeenCalled(); }); it("writes a valid preference update with tenant, user, normalized category, channel, and enabled state", async () => { const form = preferenceForm({ category: " Team ", channel: "in-app", enabled: "true" }); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(requireAuth).toHaveBeenCalledWith({ request: expect.any(Request), params }); expect(getTenantIdFromUrl).toHaveBeenCalledWith(params); expect(getUserInfo).toHaveBeenCalledWith(expect.any(Request)); expect(upsertUserNotificationPreference).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "team", enabled: true, }); expect(body).toEqual({ ok: true }); }); it("disables email for every registered category when the master switch is turned on", async () => { const form = new FormData(); form.set("action", "set-email-master"); form.set("disableAllEmails", "on"); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(body).toEqual({ ok: true }); expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3); for (const category of ["default", "billing", "team"]) { expect(upsertUserNotificationPreference).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category, enabled: false, }); } }); it("re-enables email for every registered category when the master switch is cleared", async () => { const form = new FormData(); form.set("action", "set-email-master"); const response = (await action(routeArgs(postFormRequest(form)))) as Response; const body = await response.json(); expect(body).toEqual({ ok: true }); expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3); expect(upsertUserNotificationPreference).toHaveBeenCalledWith( expect.objectContaining({ channel: "EMAIL", category: "default", enabled: true }), ); }); it("renders the email master switch alongside the per-category controls", () => { const { container } = render( , ); expect(container.querySelector('[data-ui-id="ui.settings.notifications.master.email"]')).toBeInTheDocument(); expect(screen.getAllByText("In-app")).toHaveLength(3); expect(screen.getAllByText("Email")).toHaveLength(3); }); it("renders compact controls for default, billing, and team notification preferences", () => { const { container } = render( , ); expect(screen.getByText("Notification preferences")).toBeInTheDocument(); expect(screen.getByText("Preferences are scoped to your current workspace and user account.", { exact: false })).toBeInTheDocument(); expect(screen.getByText("Default")).toBeInTheDocument(); expect(screen.getByText("Billing")).toBeInTheDocument(); expect(screen.getByText("Team")).toBeInTheDocument(); expect(screen.getAllByText("In-app")).toHaveLength(3); expect(screen.getAllByText("Email")).toHaveLength(3); // Switch state mirrors the VM: billing EMAIL off, team IN_APP off. const billingEmail = container .querySelector('[data-ui-id="ui.settings.notifications.preference.billing.email"]') ?.querySelector('[role="switch"]'); const teamInApp = container .querySelector('[data-ui-id="ui.settings.notifications.preference.team.in_app"]') ?.querySelector('[role="switch"]'); expect(billingEmail).toHaveAttribute("aria-checked", "false"); expect(teamInApp).toHaveAttribute("aria-checked", "false"); }); });