// P17 HR-Hub workflows (AK-P17b) — survey results. Gated: hr.surveys.results, or // the survey's resultVisibility allows the viewer (everyone, or participants who // submitted). Aggregates per item (distribution + average); charts are the UI's // job. 404 when not allowed (never 403). Transitional UI. import { type LoaderFunctionArgs, useLoaderData } from "react-router"; import { buildHrSurveyResultsVM, type HrSurveyResultsVM } from "@hivegrid/view-models"; import { hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server"; import { getResults, getSurveyWithItems, hasSubmitted } from "~/utils/integrations/hrSurveyService.server"; import { requireHrAudienceViewer } from "~/utils/integrations/hrAudience.server"; import ServerError from "~/components/ui/errors/ServerError"; import { HrSurveyResultsPage } from "~/components/screens/hr/HrSurveyResultsPage"; type LoaderData = { title: string; vm: HrSurveyResultsVM }; 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 } = await getSurveyWithItems(ctx.tenantId, surveyId); const canResults = hrHasPermission(ctx, "hr.surveys.results"); try { await requireHrAudienceViewer({ tenantId: ctx.tenantId, userId: ctx.userId, kind: survey.audienceKind, ref: survey.audienceRef, canManage: canResults, }); } catch { throw notFoundResponse(); } const submitted = await hasSubmitted(ctx.tenantId, surveyId, ctx.userId, survey.isAnonymous); const allowed = canResults || survey.resultVisibility === "everyone" || (survey.resultVisibility === "participants" && submitted); if (!allowed) { // Result-visibility denial surfaces as 404, never 403 (Bauprinzip A.5.3). throw notFoundResponse(); } const results = await getResults(ctx.tenantId, surveyId); const vm = buildHrSurveyResultsVM({ surveyId: survey.id, title: survey.title, submissionCount: results.submissionCount, isAnonymous: survey.isAnonymous, items: results.items.map((item) => ({ itemId: item.itemId, prompt: item.prompt, itemType: item.itemType, responseCount: item.responseCount, distribution: item.distribution, average: item.average, textResponses: item.textResponses })), }); return Response.json({ title: `${survey.title} | ${process.env.APP_NAME}`, vm } satisfies LoaderData); }; export default function HrSurveyResultsRoute() { const { vm } = useLoaderData(); return ; } export function ErrorBoundary() { return ; } export const handle = { moduleKey: "hr" };