Files
2026-07-08 16:15:37 +02:00

161 lines
7.4 KiB
TypeScript

// P17 HR-Hub workflows (AK-P17b) — sick-leave route. Employees report their own
// sick leave and attach an (encrypted) AU certificate; HR (hr.write) reports on
// behalf and reveals certificates. The certificate is never rendered directly —
// a POST reveal decrypts the File id on demand (audited). Transitional UI.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrSickOwnVM, buildHrSickOfficeVM, type HrSickLeaveOwnVM, type HrSickLeaveOfficeVM, type HrSickLeaveInputRow } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { resolveUserLabels } from "~/utils/integrations/hrService.server";
import { attachCertificate, cancelSickLeave, closeSickLeave, listOwnSickLeave, listSickLeaveForOffice, reportSickLeave, revealCertificateFileId, type SickLeaveRow } from "~/utils/integrations/hrSickLeaveService.server";
import { hrSickPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrSickPage, type HrSickTab } from "~/components/screens/hr/HrSickPage";
type LoaderData = {
title: string;
tab: "own" | "office";
canManage: boolean;
selfHref: string;
filesBase: string;
ownVm: HrSickLeaveOwnVM;
officeVm: HrSickLeaveOfficeVM;
};
const dateIso = (date: Date | null) => (date ? date.toISOString().slice(0, 10) : null);
function toInputRow(row: SickLeaveRow, revealHref: string): HrSickLeaveInputRow {
return {
id: row.id,
status: row.status,
startDateIso: dateIso(row.startDate)!,
expectedReturnDateIso: dateIso(row.expectedReturnDate),
returnDateIso: dateIso(row.returnDate),
note: row.note,
hasCertificate: row.certificateRefCiphertext != null,
revealHref,
};
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const url = new URL(request.url);
const tab: LoaderData["tab"] = url.searchParams.get("tab") === "office" ? "office" : "own";
const title = `${t("hr.sick.title")} | ${process.env.APP_NAME}`;
const revealHref = hrSickPath(tenantSlug);
const filesBase = `/${tenantSlug}/files`;
const empty: LoaderData = { title, tab, canManage: false, selfHref: revealHref, filesBase, ownVm: buildHrSickOwnVM({ rows: [], canReport: false }), officeVm: buildHrSickOfficeVM({ rows: [] }) };
if (!ctx.hasModule) {
return Response.json(empty satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const canManage = hrHasPermission(ctx, "hr.write");
const own = await listOwnSickLeave(ctx.tenantId, ctx.userId);
const ownVm = buildHrSickOwnVM({ rows: own.map((row) => toInputRow(row, revealHref)), canReport: true });
let officeVm = buildHrSickOfficeVM({ rows: [] });
if (canManage && tab === "office") {
const reports = await listSickLeaveForOffice(ctx.tenantId);
const labels = await resolveUserLabels(reports.map((r) => r.employeeUserId));
officeVm = buildHrSickOfficeVM({ rows: reports.map((row) => ({ ...toInputRow(row, revealHref), employeeLabel: labels.get(row.employeeUserId)?.label ?? row.employeeUserId })) });
}
return Response.json({ title, tab, canManage, selfHref: revealHref, filesBase, ownVm, officeVm } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.read_own");
const form = await request.formData();
const intent = form.get("intent")?.toString();
const reportId = form.get("reportId")?.toString() ?? "";
try {
if (intent === "report") {
const start = form.get("startDate")?.toString() ?? "";
if (!start) throw badRequestResponse();
const expected = form.get("expectedReturnDate")?.toString();
await reportSickLeave({ tenantId: ctx.tenantId, employeeUserId: ctx.userId, reportedByUserId: ctx.userId, startDate: new Date(start), expectedReturnDate: expected ? new Date(expected) : null, note: form.get("note")?.toString() ?? null });
return Response.json({ ok: true });
}
if (intent === "report-for") {
requireHrPermission(ctx, "hr.write");
const employeeUserId = form.get("employeeUserId")?.toString() ?? "";
const start = form.get("startDate")?.toString() ?? "";
if (!employeeUserId || !start) throw badRequestResponse();
await reportSickLeave({ tenantId: ctx.tenantId, employeeUserId, reportedByUserId: ctx.userId, startDate: new Date(start) });
return Response.json({ ok: true });
}
if (intent === "attach") {
await attachCertificate({ tenantId: ctx.tenantId, reportId, actorUserId: ctx.userId, certificateFileId: form.get("certificateFileId")?.toString() ?? "" });
return Response.json({ ok: true });
}
if (intent === "reveal") {
const fileId = await revealCertificateFileId({ tenantId: ctx.tenantId, reportId, revealerUserId: ctx.userId });
return Response.json({ ok: true, fileId });
}
if (intent === "close") {
const ret = form.get("returnDate")?.toString() ?? "";
if (!ret) throw badRequestResponse();
await closeSickLeave({ tenantId: ctx.tenantId, reportId, actorUserId: ctx.userId, returnDate: new Date(ret) });
return Response.json({ ok: true });
}
if (intent === "cancel") {
await cancelSickLeave({ tenantId: ctx.tenantId, reportId, actorUserId: ctx.userId });
return Response.json({ ok: true });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrSickRoute() {
const { tab, canManage, selfHref, filesBase, ownVm, officeVm } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
async function revealCertificate(reportId: string) {
const body = new FormData();
body.set("intent", "reveal");
body.set("reportId", reportId);
const response = await fetch(selfHref, { method: "POST", body });
if (!response.ok) return;
const data = (await response.json()) as { fileId?: string | null };
if (data.fileId) window.open(`${filesBase}/${data.fileId}`, "_blank", "noreferrer");
}
return (
<HrSickPage
tab={tab}
canManage={canManage}
ownVm={ownVm}
officeVm={officeVm}
tabHref={(next: HrSickTab) => `?tab=${next}`}
submitting={fetcher.state !== "idle"}
actions={{
onReport: ({ startDate, expectedReturnDate }) => submit({ intent: "report", startDate, expectedReturnDate }),
onReportFor: ({ employeeUserId, startDate }) => submit({ intent: "report-for", employeeUserId, startDate }),
onAttach: (reportId, certificateFileId) => submit({ intent: "attach", reportId, certificateFileId }),
onRevealCertificate: revealCertificate,
onClose: (reportId, returnDate) => submit({ intent: "close", reportId, returnDate }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };