124 lines
5.6 KiB
TypeScript
124 lines
5.6 KiB
TypeScript
// P17 HR-Hub workflows (AK-P17b) — survey participation + item editor. Employees
|
|
// answer an open survey (one submission, anonymous via submitterHash when set);
|
|
// managers (hr.write) add items here. Read needs hr.read_own. Transitional UI.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
|
import { buildHrSurveyParticipationVM, type HrSurveyParticipationVM, type HrSurveyItemType } from "@hivegrid/view-models";
|
|
import { badRequestResponse, hrActionErrorResponse, hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
|
|
import { addItem, getSurveyWithItems, hasSubmitted, removeItem, submitResponse } from "~/utils/integrations/hrSurveyService.server";
|
|
import { requireHrAudienceViewer } from "~/utils/integrations/hrAudience.server";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { HrSurveyParticipationPage } from "~/components/screens/hr/HrSurveyParticipationPage";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
type LoaderData = { title: string; vm: HrSurveyParticipationVM; canManage: boolean; status: string };
|
|
const ITEM_TYPES: HrSurveyItemType[] = ["text", "rating_5", "nps", "choice", "boolean", "date"];
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const ctx = await loadHrContext({ request, params });
|
|
const surveyId = params.id ?? "";
|
|
if (!ctx.hasModule) throw notFoundResponse();
|
|
try {
|
|
requireHrPermission(ctx, "hr.read_own");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const { survey, items } = await getSurveyWithItems(ctx.tenantId, surveyId);
|
|
try {
|
|
await requireHrAudienceViewer({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
kind: survey.audienceKind,
|
|
ref: survey.audienceRef,
|
|
canManage: hrHasPermission(ctx, "hr.write"),
|
|
});
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const submitted = await hasSubmitted(ctx.tenantId, surveyId, ctx.userId, survey.isAnonymous);
|
|
const vm = buildHrSurveyParticipationVM({
|
|
surveyId: survey.id,
|
|
title: survey.title,
|
|
description: survey.description,
|
|
isAnonymous: survey.isAnonymous,
|
|
items: items.map((i) => ({ id: i.id, itemType: i.itemType, prompt: i.prompt, required: i.required, options: i.options })),
|
|
alreadySubmitted: submitted,
|
|
});
|
|
return Response.json({ title: `${survey.title} | ${process.env.APP_NAME}`, vm, canManage: hrHasPermission(ctx, "hr.write"), status: survey.status } satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadHrContext({ request, params, requireModule: true });
|
|
requireHrPermission(ctx, "hr.read_own");
|
|
const surveyId = params.id ?? "";
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
try {
|
|
const { survey } = await getSurveyWithItems(ctx.tenantId, surveyId);
|
|
await requireHrAudienceViewer({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
kind: survey.audienceKind,
|
|
ref: survey.audienceRef,
|
|
canManage: hrHasPermission(ctx, "hr.write"),
|
|
});
|
|
if (intent === "submit") {
|
|
const { items } = await getSurveyWithItems(ctx.tenantId, surveyId);
|
|
const answers: Record<string, unknown> = {};
|
|
for (const item of items) {
|
|
const value = form.get(`item:${item.id}`);
|
|
if (value !== null) answers[item.id] = value.toString();
|
|
}
|
|
await submitResponse({ tenantId: ctx.tenantId, surveyId, userId: ctx.userId, answers });
|
|
return Response.json({ intent, ok: true, messageKey: "hr.surveys.toast.responseSubmitted" });
|
|
}
|
|
if (intent === "add-item") {
|
|
requireHrPermission(ctx, "hr.write");
|
|
const type = (form.get("itemType")?.toString() ?? "text") as HrSurveyItemType;
|
|
const options = (form.get("options")?.toString() ?? "").split(",").map((o) => o.trim()).filter(Boolean);
|
|
await addItem({ tenantId: ctx.tenantId, surveyId, itemType: ITEM_TYPES.includes(type) ? type : "text", prompt: form.get("prompt")?.toString() ?? "", required: form.get("required") === "1", options });
|
|
return Response.json({ intent, ok: true, messageKey: "hr.surveys.toast.itemAdded" });
|
|
}
|
|
if (intent === "remove-item") {
|
|
requireHrPermission(ctx, "hr.write");
|
|
await removeItem({ tenantId: ctx.tenantId, surveyId, itemId: form.get("itemId")?.toString() ?? "" });
|
|
return Response.json({ intent, ok: true, messageKey: "hr.surveys.toast.itemRemoved" });
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) throw error;
|
|
return hrActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function HrSurveyParticipateRoute() {
|
|
const { vm, canManage, status } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher();
|
|
useSaveToast(fetcher.data);
|
|
return (
|
|
<HrSurveyParticipationPage
|
|
vm={vm}
|
|
canManage={canManage}
|
|
status={status}
|
|
submitting={fetcher.state !== "idle"}
|
|
actions={{
|
|
onSubmit: (answers) => {
|
|
const body = new FormData();
|
|
body.set("intent", "submit");
|
|
for (const [itemId, value] of Object.entries(answers)) body.set(`item:${itemId}`, value);
|
|
fetcher.submit(body, { method: "post" });
|
|
},
|
|
onAddItem: ({ itemType, prompt, options, required }) =>
|
|
fetcher.submit({ intent: "add-item", itemType, prompt, options, required: required ? "1" : "0" }, { method: "post" }),
|
|
onRemoveItem: (itemId) => fetcher.submit({ intent: "remove-item", itemId }, { method: "post" }),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: "hr" };
|