Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+122
@@ -0,0 +1,122 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireContext: vi.fn(),
|
||||
loadSnapshot: vi.fn(),
|
||||
updateInbox: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/customer-portal/CustomerPortalInterimPages", () => ({ PortalAdminInboxPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/services/customer-portal/portal-admin-context.server", () => ({
|
||||
requirePortalAdminWorkspaceContext: (...args: unknown[]) => mocks.requireContext(...args),
|
||||
}));
|
||||
vi.mock("~/services/customer-portal/portal-admin.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/services/customer-portal/portal-admin.server")>();
|
||||
return {
|
||||
...actual,
|
||||
loadPortalAdminSnapshot: (...args: unknown[]) => mocks.loadSnapshot(...args),
|
||||
updatePortalInbox: (...args: unknown[]) => mocks.updateInbox(...args),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: (...args: unknown[]) => mocks.validateCsrf(...args) }));
|
||||
|
||||
import { action, loader } from "./inbox";
|
||||
|
||||
const configuration = {
|
||||
published: true,
|
||||
lifecycleMode: "customer" as const,
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
enabledProjectTypes: ["shk"],
|
||||
statusEmailsEnabled: true,
|
||||
imprintUrl: "https://example.test/imprint",
|
||||
privacyUrl: "https://example.test/privacy",
|
||||
termsUrl: null,
|
||||
legalLinksComplete: true,
|
||||
visibleStageCount: 2,
|
||||
autoReleaseRuleCount: 0,
|
||||
emailTemplateHref: "/acme/settings/customer-portal/email-templates",
|
||||
};
|
||||
|
||||
describe("customer portal service inbox route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.requireContext.mockResolvedValue({
|
||||
tenantId: "tenant_1",
|
||||
tenantSlug: "acme",
|
||||
userId: "user_1",
|
||||
permissions: ["portal.activity.read", "portal.activity.manage"],
|
||||
});
|
||||
mocks.loadSnapshot.mockResolvedValue({
|
||||
frozen: false,
|
||||
portalId: "portal_1",
|
||||
published: true,
|
||||
configuration,
|
||||
users: [],
|
||||
accessRows: [],
|
||||
inbox: [],
|
||||
stages: [],
|
||||
autoReleaseRules: [],
|
||||
projectOptions: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("loads for an activity-only reader and asks for the narrow read permission", async () => {
|
||||
const response = await loader({
|
||||
request: new Request("https://app.example.test/acme/customer-portal/inbox"),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
} as never);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.vm).toMatchObject({ status: "ready", data: { permissions: { canReadActivity: true, canManageActivity: true } } });
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(expect.any(Request), { tenant: "acme" }, "portal.activity.read");
|
||||
});
|
||||
|
||||
it("validates CSRF and the manage permission before updating one scoped item", async () => {
|
||||
const request = new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ itemId: "inbox_1", status: "resolved", csrf: "token" }),
|
||||
});
|
||||
const response = await action({ request, params: { tenant: "acme" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.activity.manage");
|
||||
expect(mocks.updateInbox).toHaveBeenCalledWith({ tenantId: "tenant_1", actorUserId: "user_1", itemId: "inbox_1", status: "resolved" });
|
||||
});
|
||||
|
||||
it("rejects an unknown status before calling the mutation", async () => {
|
||||
const response = await action({
|
||||
request: new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ itemId: "inbox_1", status: "other", csrf: "token" }),
|
||||
}),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mocks.updateInbox).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns manage-permission failures before CSRF and payload validation", async () => {
|
||||
const notFound = new Response(null, { status: 404 });
|
||||
mocks.requireContext.mockRejectedValueOnce(notFound);
|
||||
const request = new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ status: "other" }),
|
||||
});
|
||||
|
||||
await expect(action({ request, params: { tenant: "acme" }, context: {} } as never)).rejects.toBe(notFound);
|
||||
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.activity.manage");
|
||||
expect(mocks.validateCsrf).not.toHaveBeenCalled();
|
||||
expect(mocks.updateInbox).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { buildPortalAdminVM, type PortalAdminVM } from "@hivegrid/view-models";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useParams } from "react-router";
|
||||
|
||||
import { PortalAdminInboxPage } from "~/components/screens/customer-portal/CustomerPortalInterimPages";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requirePortalAdminWorkspaceContext } from "~/services/customer-portal/portal-admin-context.server";
|
||||
import { loadPortalAdminSnapshot, PortalAdminError, updatePortalInbox } from "~/services/customer-portal/portal-admin.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = { readonly title: string; readonly vm: PortalAdminVM };
|
||||
type ActionData = { readonly ok?: true; readonly messageKey?: string; readonly errorKey?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, ctx] = await Promise.all([
|
||||
getTranslations(request),
|
||||
requirePortalAdminWorkspaceContext(request, params, "portal.activity.read"),
|
||||
]);
|
||||
const snapshot = await loadPortalAdminSnapshot({ tenantId: ctx.tenantId, tenantSlug: ctx.tenantSlug });
|
||||
const vm = buildPortalAdminVM({
|
||||
frozen: snapshot.frozen,
|
||||
permissions: {
|
||||
canRead: ctx.permissions.includes("portal.read"),
|
||||
canManageUsers: false,
|
||||
canManageAccess: false,
|
||||
canDeleteUsers: false,
|
||||
canReadActivity: true,
|
||||
canManageActivity: ctx.permissions.includes("portal.activity.manage"),
|
||||
canAdminister: ctx.permissions.includes("portal.admin"),
|
||||
},
|
||||
configuration: snapshot.configuration,
|
||||
stages: [],
|
||||
autoReleaseRules: [],
|
||||
projectOptions: [],
|
||||
users: [],
|
||||
accessRows: [],
|
||||
inbox: snapshot.inbox,
|
||||
});
|
||||
return Response.json({ title: `${t("customerPortal.admin.inbox.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const ctx = await requirePortalAdminWorkspaceContext(request, params, "portal.activity.manage");
|
||||
const form = await request.formData();
|
||||
await validateCSRFToken(request, { formData: form });
|
||||
const itemId = required(form, "itemId");
|
||||
const status = required(form, "status");
|
||||
if (status !== "open" && status !== "in_progress" && status !== "resolved" && status !== "dismissed") {
|
||||
return Response.json({ errorKey: "customerPortal.admin.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await updatePortalInbox({ tenantId: ctx.tenantId, actorUserId: ctx.userId, itemId, status });
|
||||
return Response.json({ ok: true, messageKey: "customerPortal.admin.messages.saved" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof PortalAdminError) return Response.json({ errorKey: error.messageKey } satisfies ActionData, { status: error.status });
|
||||
if (error instanceof Response) throw error;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default function CustomerPortalServiceInboxRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
return (
|
||||
<PortalAdminInboxPage
|
||||
vm={vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
messageKey={fetcher.data?.ok ? fetcher.data.messageKey : null}
|
||||
errorKey={fetcher.data?.errorKey ?? null}
|
||||
actions={{
|
||||
onUpdate: ({ itemId, status }) => {
|
||||
const form = new FormData();
|
||||
form.set("itemId", itemId);
|
||||
form.set("status", status);
|
||||
fetcher.submit(appendCSRFToken(form), { method: "post" });
|
||||
},
|
||||
onBackToSettings: () => navigate(`/${encodeURIComponent(params.tenant ?? "")}/settings/customer-portal`),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function required(form: FormData, key: string): string {
|
||||
const value = form.get(key);
|
||||
if (typeof value !== "string" || !value.trim()) throw new PortalAdminError("customerPortal.admin.errors.invalidInput", 400);
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { breadcrumbKey: "customerPortal.admin.inbox.title" };
|
||||
Reference in new issue
Block a user