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"; import AdminSettingsGeneral, { action } from "./general"; import { getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server"; import { createAdminLog } from "~/utils/db/logs.db.server"; import { storeFile } from "~/utils/integrations/storageService"; import { createUserSession } from "~/utils/session.server"; let routeLoaderData = { title: "General Settings", appConfiguration: { app: { name: "HiveGrid", url: "https://example.com", theme: "light" }, branding: { logo: "", logoDarkMode: "", icon: "", iconDarkMode: "", favicon: "" }, scripts: { head: "", body: "" }, }, }; let routeActionData: { success?: string; error?: string; fieldErrors?: Record } | undefined; let canUpdate = true; vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, Form: ({ children, ...props }: React.ComponentProps<"form">) =>
{children}
, useLoaderData: () => routeLoaderData, useActionData: () => routeActionData, }; }); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })), })); vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({ permissions: canUpdate ? ["admin.settings.general.update"] : [] }), })); vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn(() => canUpdate), })); vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(), })); vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn(), getOrCreateAppConfiguration: vi.fn(), updateAppConfiguration: vi.fn(), })); vi.mock("~/utils/db/logs.db.server", () => ({ createAdminLog: vi.fn(), })); vi.mock("~/utils/integrations/storageService", () => ({ storeFile: vi.fn(async ({ id }: { id: string }) => `stored:${id}`), })); vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user-1", theme: "light" })), createUserSession: vi.fn(async () => new Response(null, { status: 204 })), validateCSRFToken: vi.fn(), })); vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf-test-token" }), })); vi.mock("react-hot-toast", () => ({ default: { success: vi.fn(), error: vi.fn() }, })); vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: ({ title, children }: { title: React.ReactNode; children: React.ReactNode }) => (
{title}
{children}
), })); vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({ default: ({ children }: { children: React.ReactNode }) =>

{children}

, })); vi.mock("~/components/ui/buttons/LoadingButton", () => ({ default: ({ children, ...props }: React.ComponentProps<"button">) => , })); vi.mock("~/components/ui/forms/InputGroup", () => ({ default: ({ title, children }: { title: string; children: React.ReactNode }) => (

{title}

{children}
), })); vi.mock("~/components/ui/input/InputText", () => ({ default: ({ name, title, defaultValue, disabled, required }: { name: string; title: string; defaultValue?: string; disabled?: boolean; required?: boolean }) => ( ), })); vi.mock("~/components/ui/input/InputImage", () => ({ default: ({ name, title, value, disabled }: { name: string; title: string; value?: string; disabled?: boolean }) => ( ), })); vi.mock("~/components/ui/input/InputSelect", () => ({ default: ({ name, title, defaultValue, options }: { name: string; title: string; defaultValue?: string; options: { name: string; value: string }[] }) => ( ), })); const getOrCreateAppConfigurationMock = vi.mocked(getOrCreateAppConfiguration); const updateAppConfigurationMock = vi.mocked(updateAppConfiguration); const createAdminLogMock = vi.mocked(createAdminLog); const storeFileMock = vi.mocked(storeFile); const createUserSessionMock = vi.mocked(createUserSession); function postRequest(form: FormData) { return new Request("https://admin.example.com/settings/general?token=secret", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form as unknown as Record), }); } function validForm() { const form = new FormData(); form.set("action", "update"); form.set("name", "HiveGrid Cloud"); form.set("theme", "dark"); form.set("logo", "data:image/png;base64,logo-secret"); form.set("logoDarkMode", ""); form.set("icon", "https://cdn.example.com/icon.png?token=secret"); form.set("iconDarkMode", ""); form.set("favicon", ""); form.set("headScripts", ""); form.set("bodyScripts", ""); return form; } describe("admin general settings route", () => { beforeEach(() => { vi.clearAllMocks(); routeActionData = undefined; canUpdate = true; routeLoaderData = { title: "General Settings", appConfiguration: { app: { name: "HiveGrid", url: "https://example.com", theme: "light" }, branding: { logo: "", logoDarkMode: "", icon: "", iconDarkMode: "", favicon: "" }, scripts: { head: "", body: "" }, }, }; getOrCreateAppConfigurationMock.mockResolvedValue(undefined as never); updateAppConfigurationMock.mockResolvedValue(undefined as never); createAdminLogMock.mockResolvedValue(undefined as never); createUserSessionMock.mockResolvedValue(new Response(null, { status: 204 }) as never); }); it("rejects invalid actions before database, storage, or audit side effects", async () => { const form = validForm(); form.set("action", "delete"); const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/general" }); const body = await (response as Response).json(); expect((response as Response).status).toBe(400); expect(body.fieldErrors.action).toEqual(["Invalid action."]); expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled(); expect(updateAppConfigurationMock).not.toHaveBeenCalled(); expect(storeFileMock).not.toHaveBeenCalled(); expect(createAdminLogMock).not.toHaveBeenCalled(); }); it("rejects an empty application name before database, storage, or audit side effects", async () => { const form = validForm(); form.set("name", " "); const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/general" }); const body = await (response as Response).json(); expect((response as Response).status).toBe(400); expect(body.fieldErrors.name).toEqual(["This field is required."]); expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled(); expect(updateAppConfigurationMock).not.toHaveBeenCalled(); expect(storeFileMock).not.toHaveBeenCalled(); expect(createAdminLogMock).not.toHaveBeenCalled(); }); it("updates valid settings and writes a redacted audit payload without raw scripts or query strings", async () => { const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/general" }); expect((response as Response).status).toBe(204); expect(storeFileMock).toHaveBeenCalledWith(expect.objectContaining({ bucket: "branding", content: "data:image/png;base64,logo-secret", id: "logo", scan: expect.objectContaining({ context: "mediaLibrary", filename: "logo" }) })); expect(storeFileMock).toHaveBeenCalledWith(expect.objectContaining({ bucket: "branding", content: "https://cdn.example.com/icon.png?token=secret", id: "icon", scan: expect.objectContaining({ context: "mediaLibrary", filename: "icon" }) })); expect(updateAppConfigurationMock).toHaveBeenCalledWith( expect.objectContaining({ name: "HiveGrid Cloud", brandingLogo: "stored:logo", brandingIcon: "stored:icon", headScripts: "", bodyScripts: "", }) ); expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String)); const auditPayload = createAdminLogMock.mock.calls[0][2]; expect(auditPayload).toContain("general"); expect(auditPayload).toContain("headScripts"); expect(auditPayload).toContain("brandingLogo"); expect(auditPayload).not.toContain("window.secret"); expect(auditPayload).not.toContain("window.token"); expect(auditPayload).not.toContain("logo-secret"); expect(auditPayload).not.toContain("token=secret"); }); it("renders accessible action and field errors", () => { routeActionData = { error: "settings.admin.invalid", fieldErrors: { name: ["This field is required."], action: ["Invalid action."] } }; render( ); const alert = screen.getByRole("alert"); expect(alert).toHaveTextContent("settings.admin.invalid"); expect(alert).toHaveTextContent("name: This field is required."); expect(alert).toHaveTextContent("action: Invalid action."); }); it("disables editable controls when the admin lacks update permission", () => { canUpdate = false; render( ); expect(screen.getByLabelText("settings.admin.general.fields.applicationName")).toBeDisabled(); expect(screen.getByLabelText("settings.admin.general.fields.logoLightMode")).toBeDisabled(); expect(screen.getByLabelText("settings.admin.general.fields.headScripts")).toBeDisabled(); expect(screen.getByRole("button", { name: "shared.save" })).toBeDisabled(); }); it("renders theme preset choices through translation keys", () => { render( ); expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.emerald" })).toBeInTheDocument(); expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.blue" })).toBeInTheDocument(); }); });