Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,283 @@
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: "ToolCTRL", url: "https://example.com", theme: "light" },
branding: { logo: "", logoDarkMode: "", icon: "", iconDarkMode: "", favicon: "" },
scripts: { head: "", body: "" },
},
};
let routeActionData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
let canUpdate = true;
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
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 }) => (
<main>
<header>{title}</header>
{children}
</main>
),
}));
vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
}));
vi.mock("~/components/ui/buttons/LoadingButton", () => ({
default: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
}));
vi.mock("~/components/ui/forms/InputGroup", () => ({
default: ({ title, children }: { title: string; children: React.ReactNode }) => (
<section>
<h2>{title}</h2>
{children}
</section>
),
}));
vi.mock("~/components/ui/input/InputText", () => ({
default: ({ name, title, defaultValue, disabled, required }: { name: string; title: string; defaultValue?: string; disabled?: boolean; required?: boolean }) => (
<label>
{title}
<input name={name} defaultValue={defaultValue} disabled={disabled} required={required} />
</label>
),
}));
vi.mock("~/components/ui/input/InputImage", () => ({
default: ({ name, title, value, disabled }: { name: string; title: string; value?: string; disabled?: boolean }) => (
<label>
{title}
<input name={name} defaultValue={value} disabled={disabled} />
</label>
),
}));
vi.mock("~/components/ui/input/InputSelect", () => ({
default: ({ name, title, defaultValue, options }: { name: string; title: string; defaultValue?: string; options: { name: string; value: string }[] }) => (
<label>
{title}
<select name={name} defaultValue={defaultValue}>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.name}
</option>
))}
</select>
</label>
),
}));
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<string, string>),
});
}
function validForm() {
const form = new FormData();
form.set("action", "update");
form.set("name", "ToolCTRL 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", "<script>window.secret='abc'</script>");
form.set("bodyScripts", "<script>window.token='def'</script>");
return form;
}
describe("admin general settings route", () => {
beforeEach(() => {
vi.clearAllMocks();
routeActionData = undefined;
canUpdate = true;
routeLoaderData = {
title: "General Settings",
appConfiguration: {
app: { name: "ToolCTRL", 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: "ToolCTRL Cloud",
brandingLogo: "stored:logo",
brandingIcon: "stored:icon",
headScripts: "<script>window.secret='abc'</script>",
bodyScripts: "<script>window.token='def'</script>",
})
);
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(
<MemoryRouter>
<AdminSettingsGeneral />
</MemoryRouter>
);
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(
<MemoryRouter>
<AdminSettingsGeneral />
</MemoryRouter>
);
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(
<MemoryRouter>
<AdminSettingsGeneral />
</MemoryRouter>
);
expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.emerald" })).toBeInTheDocument();
expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.blue" })).toBeInTheDocument();
});
});