Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,107 @@
// P17 HR-Hub workflows (AK-P17b) — announcements editor (admin). Create with
// audience, acknowledgement requirement, pin, schedule and expiry; archive.
// Needs hr.write. Transitional UI.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { archiveAnnouncement, createAnnouncement, listAllAnnouncements, type HrAudienceKind } from "~/utils/integrations/hrAnnouncementService.server";
import { listHrAudienceOptions, type HrAudienceOption } from "~/utils/integrations/hrAudience.server";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAdminAnnouncementsPage } from "~/components/screens/hr/HrAdminAnnouncementsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type Row = { id: string; title: string; audienceKind: string; requiresAck: boolean; pinned: boolean; publishedIso: string | null };
type LoaderData = { title: string; rows: Row[]; audienceOptions: HrAudienceOption[] };
const AUDIENCES: HrAudienceKind[] = ["all", "team", "location"];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const title = `${t("hr.announcements.admin.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) return Response.json({ title, rows: [], audienceOptions: [] } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.write");
} catch {
throw notFoundResponse();
}
const [list, audienceOptions] = await Promise.all([
listAllAnnouncements(ctx.tenantId),
listHrAudienceOptions(ctx.tenantId),
]);
const rows: Row[] = list.map((a) => ({ id: a.id, title: a.title, audienceKind: a.audienceKind, requiresAck: a.requiresAcknowledgement, pinned: a.pinnedAt != null, publishedIso: a.publishAt ? a.publishAt.toISOString() : null }));
return Response.json({ title, rows, audienceOptions } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "create") {
const audience = (form.get("audienceKind")?.toString() ?? "all") as HrAudienceKind;
const publishAt = form.get("publishAt")?.toString();
const expiresAt = form.get("expiresAt")?.toString();
await createAnnouncement({
tenantId: ctx.tenantId,
authorUserId: ctx.userId,
title: form.get("title")?.toString() ?? "",
body: form.get("body")?.toString() ?? "",
audienceKind: AUDIENCES.includes(audience) ? audience : "all",
audienceRef: form.get("audienceRef")?.toString() || null,
requiresAcknowledgement: form.get("requiresAck") === "1",
pinned: form.get("pinned") === "1",
publishAt: publishAt ? new Date(publishAt) : null,
expiresAt: expiresAt ? new Date(expiresAt) : null,
});
return Response.json({ intent, ok: true, messageKey: "hr.announcements.toast.created" });
}
if (intent === "archive") {
await archiveAnnouncement({ tenantId: ctx.tenantId, actorUserId: ctx.userId, announcementId: form.get("announcementId")?.toString() ?? "" });
return Response.json({ intent, ok: true, messageKey: "hr.announcements.toast.archived" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrAdminAnnouncementsRoute() {
const { rows, audienceOptions } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
return (
<HrAdminAnnouncementsPage
rows={rows}
audiences={AUDIENCES}
audienceOptions={audienceOptions}
submitting={fetcher.state !== "idle"}
actions={{
onCreate: (input) =>
fetcher.submit(
{
intent: "create",
title: input.title,
body: input.body,
audienceKind: input.audienceKind,
audienceRef: input.audienceRef,
requiresAck: input.requiresAck ? "1" : "0",
pinned: input.pinned ? "1" : "0",
publishAt: input.publishAt,
expiresAt: input.expiresAt,
},
{ method: "post" },
),
onArchive: (announcementId) => fetcher.submit({ intent: "archive", announcementId }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,3 @@
import { legacyPasswordSafeRedirectLoader } from "~/utils/integrations/passwordSafeLegacyRedirect.server";
export const loader = legacyPasswordSafeRedirectLoader("admin");
@@ -0,0 +1,168 @@
// P17 HR-Hub workflows (AK-P17b) — payslip administration. Bulk auto-match: the
// admin selects PDFs + a period; the server classifies the filenames
// (hard/soft/none, color confidence). Only a confirmed assignment stores and
// scans its file, then links it with compensating cleanup. Needs hr.write.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrPayslipMatchPreviewVM, matchPayslipFile, type HrPayslipMatchInputRow, type PayslipMatchEmployee } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { createFileFromBytes, hardDeleteFile } from "~/utils/integrations/fileService.server";
import { listHrMemberOptions, requireActiveHrMember, resolveUserLabels, type HrMemberOption } from "~/utils/integrations/hrService.server";
import { adminListPayslips, createPayslip, listEmployeesForMatch } from "~/utils/integrations/hrPayslipService.server";
import { StorageScanRejectedError } from "~/utils/integrations/storageService";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAdminPayslipsPage } from "~/components/screens/hr/HrAdminPayslipsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type PreviewRow = HrPayslipMatchInputRow & { confidenceKey: string; confidenceTone: string };
type AdminRow = { id: string; employeeLabel: string; periodLabel: string; isRead: boolean };
type LoaderData = { title: string; rows: AdminRow[]; memberOptions: HrMemberOption[] };
type ActionData = { intent?: string; ok?: boolean; messageKey?: string; preview?: PreviewRow[]; periodYear?: number; periodMonth?: number; created?: number; error?: string };
const PAYSLIP_MAX_BYTES = 25 * 1024 * 1024;
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const title = `${t("hr.payslips.admin.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) return Response.json({ title, rows: [], memberOptions: [] } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.write");
} catch {
throw notFoundResponse();
}
const [payslips, memberOptions] = await Promise.all([adminListPayslips(ctx.tenantId), listHrMemberOptions(ctx.tenantId)]);
const labels = await resolveUserLabels(payslips.map((p) => p.employeeUserId));
const rows: AdminRow[] = payslips.map((p) => ({
id: p.id,
employeeLabel: labels.get(p.employeeUserId)?.label ?? t("hr.picker.unknownMember"),
periodLabel: `${p.periodYear}-${String(p.periodMonth).padStart(2, "0")}`,
isRead: p.isRead,
}));
return Response.json({ title, rows, memberOptions } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "match") {
const periodYear = Number(form.get("periodYear"));
const periodMonth = Number(form.get("periodMonth"));
const fileNames = form.getAll("fileNames").map((entry) => entry.toString().trim()).filter(Boolean);
if (fileNames.length === 0) {
return Response.json({ intent, error: "hr.payslips.upload.invalid" } satisfies ActionData, { status: 400 });
}
const profiles = await listEmployeesForMatch(ctx.tenantId);
const labels = await resolveUserLabels(profiles.map((p) => p.userId));
const employees: PayslipMatchEmployee[] = profiles.map((p) => ({ userId: p.userId, personalNumber: p.personalNumber, name: labels.get(p.userId)?.label ?? "" }));
const inputRows: HrPayslipMatchInputRow[] = fileNames.map((fileName, index) => {
const result = matchPayslipFile(fileName, employees);
return {
fileId: String(index),
fileName,
confidence: result.confidence,
employeeUserId: result.employeeUserId,
employeeLabel: result.employeeUserId ? (labels.get(result.employeeUserId)?.label ?? null) : null,
candidateUserIds: result.candidateUserIds,
};
});
const vm = buildHrPayslipMatchPreviewVM({ rows: inputRows });
const preview: PreviewRow[] = (vm.data?.rows ?? []).map((r) => ({ ...r, confidenceKey: r.confidenceKey, confidenceTone: r.confidenceTone }));
return Response.json({ intent, preview, periodYear, periodMonth } satisfies ActionData);
}
if (intent === "confirm-one") {
const employeeUserId = form.get("employeeUserId")?.toString() ?? "";
const upload = form.get("file");
if (!(upload instanceof File) || upload.size === 0 || upload.size > PAYSLIP_MAX_BYTES || (upload.type && upload.type !== "application/pdf")) {
return Response.json(
{ intent, error: upload instanceof File && upload.size > PAYSLIP_MAX_BYTES ? "hr.payslips.upload.tooLarge" : "hr.payslips.upload.invalid" } satisfies ActionData,
{ status: 400 },
);
}
await requireActiveHrMember(ctx.tenantId, employeeUserId);
const createdFile = await createFileFromBytes({
tenantId: ctx.tenantId,
userId: ctx.userId,
filename: upload.name,
mimeType: upload.type || "application/pdf",
bytes: new Uint8Array(await upload.arrayBuffer()),
scanContext: "formUpload",
});
try {
await createPayslip({
tenantId: ctx.tenantId,
employeeUserId,
uploadedByUserId: ctx.userId,
periodYear: Number(form.get("periodYear")),
periodMonth: Number(form.get("periodMonth")),
fileId: createdFile.id,
});
} catch (error) {
await hardDeleteFile({ tenantId: ctx.tenantId, fileId: createdFile.id }).catch(() => undefined);
throw error;
}
return Response.json({ intent, ok: true, created: 1, messageKey: "hr.payslips.toast.assigned" } satisfies ActionData);
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
if (error instanceof StorageScanRejectedError) {
return Response.json({ intent, error: "hr.payslips.upload.rejected" } satisfies ActionData, { status: 422 });
}
return hrActionErrorResponse(error);
}
};
export default function HrAdminPayslipsRoute() {
const { rows, memberOptions } = useLoaderData<LoaderData>();
const fetcher = useFetcher<ActionData>();
useSaveToast(fetcher.data);
const preview = fetcher.data?.preview ?? [];
const period = { year: String(fetcher.data?.periodYear ?? ""), month: String(fetcher.data?.periodMonth ?? "") };
return (
<HrAdminPayslipsPage
rows={rows}
preview={preview}
memberOptions={memberOptions}
period={period}
submitting={fetcher.state !== "idle"}
errorKey={fetcher.data?.error ?? null}
feedbackKey={
fetcher.data?.created
? "hr.payslips.upload.linked"
: fetcher.data?.preview
? "hr.payslips.upload.checked"
: null
}
actions={{
onMatch: ({ periodYear, periodMonth, files }) => {
const body = new FormData();
body.set("intent", "match");
body.set("periodYear", periodYear);
body.set("periodMonth", periodMonth);
for (const file of files) body.append("fileNames", file.name);
fetcher.submit(body, { method: "post" });
},
onConfirm: ({ file, employeeUserId, periodYear, periodMonth }) => {
const body = new FormData();
body.set("intent", "confirm-one");
body.set("file", file);
body.set("employeeUserId", employeeUserId);
body.set("periodYear", periodYear);
body.set("periodMonth", periodMonth);
fetcher.submit(body, { method: "post", encType: "multipart/form-data" });
},
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,115 @@
// P17 HR-Hub workflows (AK-P17b) — request-template editor (admin). Create
// templates (expense/hardware/training/reference) with a default approver and an
// optional linked M05 form (null until AK-P16c); archive. Needs hr.write.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrRequestTemplateListVM, type HrRequestTemplateListVM, type HrRequestKind } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { archiveTemplate, createTemplate, listLinkableHrRequestForms, listTemplates, updateTemplate } from "~/utils/integrations/hrRequestService.server";
import { listHrMemberOptions, requireActiveHrMember, type HrMemberOption } from "~/utils/integrations/hrService.server";
import { hrAdminRequestTemplatesPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAdminRequestTemplatesPage } from "~/components/screens/hr/HrAdminRequestTemplatesPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrRequestTemplateListVM; memberOptions: HrMemberOption[] };
const KINDS: HrRequestKind[] = ["expense", "hardware", "training", "reference"];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const title = `${t("hr.requests.templates.title")} | ${process.env.APP_NAME}`;
const createHref = hrAdminRequestTemplatesPath(tenantSlug);
if (!ctx.hasModule) return Response.json({ title, vm: buildHrRequestTemplateListVM({ rows: [], createHref }), memberOptions: [] } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.write");
} catch {
throw notFoundResponse();
}
const [templates, linkableForms, memberOptions] = await Promise.all([
listTemplates(ctx.tenantId),
listLinkableHrRequestForms(ctx.tenantId),
listHrMemberOptions(ctx.tenantId),
]);
const formLabelById = new Map(linkableForms.map((form) => [form.id, form.name]));
const vm = buildHrRequestTemplateListVM({
rows: templates.map((tpl) => ({
id: tpl.id,
title: tpl.title,
kind: tpl.requestKind,
description: tpl.description,
isActive: tpl.isActive,
editHref: createHref,
linkedFormLabel: tpl.linkedFormId ? (formLabelById.get(tpl.linkedFormId) ?? null) : null,
})),
linkableForms: linkableForms.map((form) => ({ id: form.id, label: form.name })),
createHref,
});
return Response.json({ title, vm, memberOptions } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "create") {
const kind = (form.get("requestKind")?.toString() ?? "expense") as HrRequestKind;
const defaultApproverUserId = form.get("defaultApproverUserId")?.toString() || null;
if (defaultApproverUserId) {
await requireActiveHrMember(ctx.tenantId, defaultApproverUserId);
}
await createTemplate({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
title: form.get("title")?.toString() ?? "",
requestKind: KINDS.includes(kind) ? kind : "expense",
description: form.get("description")?.toString() || null,
defaultApproverUserId,
linkedFormId: form.get("linkedFormId")?.toString() || null,
});
return Response.json({ intent, ok: true, messageKey: "hr.requests.templates.toast.created" });
}
if (intent === "toggle") {
await updateTemplate({ tenantId: ctx.tenantId, actorUserId: ctx.userId, templateId: form.get("templateId")?.toString() ?? "", isActive: form.get("isActive") === "1" });
return Response.json({ intent, ok: true, messageKey: form.get("isActive") === "1" ? "hr.requests.templates.toast.activated" : "hr.requests.templates.toast.deactivated" });
}
if (intent === "archive") {
await archiveTemplate({ tenantId: ctx.tenantId, actorUserId: ctx.userId, templateId: form.get("templateId")?.toString() ?? "" });
return Response.json({ intent, ok: true, messageKey: "hr.requests.templates.toast.archived" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrAdminRequestTemplatesRoute() {
const { vm, memberOptions } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
return (
<HrAdminRequestTemplatesPage
vm={vm}
kinds={KINDS}
memberOptions={memberOptions}
submitting={fetcher.state !== "idle"}
actions={{
onCreate: ({ requestKind, defaultApproverUserId, title, description, linkedFormId }) =>
fetcher.submit({ intent: "create", requestKind, defaultApproverUserId, title, description, linkedFormId }, { method: "post" }),
onToggle: (templateId, isActive) => fetcher.submit({ intent: "toggle", templateId, isActive: isActive ? "1" : "0" }, { method: "post" }),
onArchive: (templateId) => fetcher.submit({ intent: "archive", templateId }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,133 @@
// P17 HR-Hub workflows (AK-P17b) — upload-reminder editor (admin). Define
// reminders (document kind, cadence, audience, mandatory, escalate); pause/resume
// and archive. Dispatch itself runs in the worker cron. Needs hr.write.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrReminderListVM, type HrReminderListVM, type HrReminderInputRow, type HrReminderCadenceKind } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { archiveReminder, createReminder, listDispatches, listReminders, setReminderStatus, type HrAudienceKind, type HrDocumentKind, type HrReminderStatus } from "~/utils/integrations/hrUploadReminderService.server";
import { hrAdminUploadRemindersPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAdminUploadRemindersPage } from "~/components/screens/hr/HrAdminUploadRemindersPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrReminderListVM };
const CADENCES: HrReminderCadenceKind[] = ["once", "yearly", "every_n_months", "on_expiry"];
const DOC_KINDS: HrDocumentKind[] = ["contract", "certificate", "identification", "qualification", "other"];
const AUDIENCES: HrAudienceKind[] = ["all", "team", "location"];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const createHref = hrAdminUploadRemindersPath(tenantSlug);
const title = `${t("hr.reminders.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) return Response.json({ title, vm: buildHrReminderListVM({ rows: [], createHref }) } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.write");
} catch {
throw notFoundResponse();
}
const reminders = await listReminders(ctx.tenantId);
const rows: HrReminderInputRow[] = [];
for (const reminder of reminders) {
const dispatches = await listDispatches(ctx.tenantId, reminder.id);
rows.push({
id: reminder.id,
title: reminder.title,
cadenceKind: reminder.cadenceKind,
intervalMonths: reminder.intervalMonths,
documentKind: reminder.documentKind,
audienceKind: reminder.audienceKind,
mandatory: reminder.mandatory,
escalateToManager: reminder.escalateToManager,
status: reminder.status,
dueIso: reminder.dueAt ? reminder.dueAt.toISOString() : null,
pendingCount: dispatches.filter((d) => d.status !== "acknowledged").length,
detailHref: createHref,
});
}
return Response.json({ title, vm: buildHrReminderListVM({ rows, createHref }) } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "create") {
const cadence = (form.get("cadenceKind")?.toString() ?? "once") as HrReminderCadenceKind;
const docKind = (form.get("documentKind")?.toString() ?? "other") as HrDocumentKind;
const audience = (form.get("audienceKind")?.toString() ?? "all") as HrAudienceKind;
const interval = form.get("intervalMonths")?.toString();
const due = form.get("dueAt")?.toString();
await createReminder({
tenantId: ctx.tenantId,
actorUserId: ctx.userId,
title: form.get("title")?.toString() ?? "",
documentKind: DOC_KINDS.includes(docKind) ? docKind : "other",
cadenceKind: CADENCES.includes(cadence) ? cadence : "once",
intervalMonths: interval ? Number(interval) : null,
audienceKind: AUDIENCES.includes(audience) ? audience : "all",
mandatory: form.get("mandatory") === "1",
escalateToManager: form.get("escalate") === "1",
dueAt: due ? new Date(due) : null,
});
return Response.json({ intent, ok: true, messageKey: "hr.reminders.toast.created" });
}
if (intent === "status") {
await setReminderStatus({ tenantId: ctx.tenantId, actorUserId: ctx.userId, reminderId: form.get("reminderId")?.toString() ?? "", status: (form.get("status")?.toString() ?? "active") as HrReminderStatus });
return Response.json({ intent, ok: true, messageKey: form.get("status") === "active" ? "hr.reminders.toast.activated" : "hr.reminders.toast.paused" });
}
if (intent === "archive") {
await archiveReminder({ tenantId: ctx.tenantId, actorUserId: ctx.userId, reminderId: form.get("reminderId")?.toString() ?? "" });
return Response.json({ intent, ok: true, messageKey: "hr.reminders.toast.archived" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrAdminUploadRemindersRoute() {
const { vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
return (
<HrAdminUploadRemindersPage
vm={vm}
cadences={CADENCES}
documentKinds={DOC_KINDS}
audiences={AUDIENCES}
submitting={fetcher.state !== "idle"}
actions={{
onCreate: (input) =>
fetcher.submit(
{
intent: "create",
title: input.title,
documentKind: input.documentKind,
cadenceKind: input.cadenceKind,
intervalMonths: input.intervalMonths,
audienceKind: input.audienceKind,
dueAt: input.dueAt,
mandatory: input.mandatory ? "1" : "0",
escalate: input.escalate ? "1" : "0",
},
{ method: "post" },
),
onSetStatus: (reminderId, status) => fetcher.submit({ intent: "status", reminderId, status }, { method: "post" }),
onArchive: (reminderId) => fetcher.submit({ intent: "archive", reminderId }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,129 @@
// P17 HR-Hub workflows (AK-P17b) — announcement detail. Opening marks it read;
// shows the markdown body, grouped reactions (toggle), single-level comments
// (add), an acknowledgement button when required, and a read-receipt table for
// managers (hr.write). Transitional UI.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildAnnouncementDetailVM, type HrAnnouncementDetailVM } 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 { acknowledge, addComment, getAnnouncementOrThrow, getReactionGroups, getUserAckState, listComments, listReadReceipts, markRead, toggleReaction } from "~/utils/integrations/hrAnnouncementService.server";
import { requireHrAudienceViewer } from "~/utils/integrations/hrAudience.server";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAnnouncementDetailPage } from "~/components/screens/hr/HrAnnouncementDetailPage";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrAnnouncementDetailVM };
type ActionData = Exclude<SaveActionResult, null | undefined>;
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const announcementId = params.id ?? "";
if (!ctx.hasModule) throw notFoundResponse();
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const announcement = await getAnnouncementOrThrow(ctx.tenantId, announcementId);
const canManage = hrHasPermission(ctx, "hr.write");
try {
await requireHrAudienceViewer({
tenantId: ctx.tenantId,
userId: ctx.userId,
kind: announcement.audienceKind,
ref: announcement.audienceRef,
canManage,
});
} catch {
throw notFoundResponse();
}
await markRead({ tenantId: ctx.tenantId, announcementId, userId: ctx.userId });
const [reactions, comments, isAcknowledged, receiptsRaw] = await Promise.all([
getReactionGroups(ctx.tenantId, announcementId, ctx.userId),
listComments(ctx.tenantId, announcementId),
getUserAckState(ctx.tenantId, announcementId, ctx.userId),
canManage ? listReadReceipts(ctx.tenantId, announcementId) : Promise.resolve([]),
]);
const labelIds = [announcement.authorUserId, ...comments.map((c) => c.userId), ...receiptsRaw.map((r) => r.userId)];
const labels = await resolveUserLabels(labelIds);
const vm = buildAnnouncementDetailVM({
id: announcement.id,
title: announcement.title,
bodyMarkdown: announcement.body,
authorLabel: labels.get(announcement.authorUserId)?.label ?? t("hr.picker.unknownMember"),
publishedIso: (announcement.publishAt ?? announcement.createdAt).toISOString(),
requiresAcknowledgement: announcement.requiresAcknowledgement,
isAcknowledged,
reactions,
comments: comments.map((c) => ({ id: c.id, authorLabel: labels.get(c.userId)?.label ?? t("hr.picker.unknownMember"), body: c.body, createdIso: c.createdAt.toISOString(), canArchive: canManage })),
canManage,
readReceipts: receiptsRaw.map((r) => ({ userLabel: labels.get(r.userId)?.label ?? t("hr.picker.unknownMember"), readIso: r.readAt.toISOString(), acknowledged: r.acknowledgedAt != null })),
});
return Response.json({ title: `${announcement.title} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.read_own");
const announcementId = params.id ?? "";
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
const announcement = await getAnnouncementOrThrow(ctx.tenantId, announcementId);
await requireHrAudienceViewer({
tenantId: ctx.tenantId,
userId: ctx.userId,
kind: announcement.audienceKind,
ref: announcement.audienceRef,
canManage: hrHasPermission(ctx, "hr.write"),
});
if (intent === "ack") {
await acknowledge({ tenantId: ctx.tenantId, announcementId, userId: ctx.userId });
return Response.json({ intent, ok: true });
}
if (intent === "react") {
await toggleReaction({ tenantId: ctx.tenantId, announcementId, userId: ctx.userId, reaction: form.get("reaction")?.toString() ?? "👍" });
return Response.json({ intent, ok: true });
}
if (intent === "comment") {
await addComment({ tenantId: ctx.tenantId, announcementId, userId: ctx.userId, body: form.get("body")?.toString() ?? "" });
return Response.json({ intent, ok: true });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrAnnouncementDetailRoute() {
const { vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher<ActionData>();
// Acknowledgements, reactions and comments update visibly in place. Only a
// failed mutation needs an additional notification here.
useSaveToast(fetcher.data?.error ? fetcher.data : undefined);
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
return (
<HrAnnouncementDetailPage
vm={vm}
submitting={fetcher.state !== "idle"}
actions={{
onAck: () => submit({ intent: "ack" }),
onReact: (reaction) => submit({ intent: "react", reaction }),
onComment: (body) => submit({ intent: "comment", body }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,64 @@
// P17 HR-Hub workflows (AK-P17b) — announcements feed. Pinned first, optional
// unread-only filter, audience-scoped to the viewer's team/location. Read needs
// hr.read_own; managing (editor) needs hr.write. Transitional UI.
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
import { buildAnnouncementFeedVM, type HrAnnouncementFeedVM, type HrAnnouncementFeedRow } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { getProfileByUser } from "~/utils/integrations/hrService.server";
import { listFeed } from "~/utils/integrations/hrAnnouncementService.server";
import { hrAdminAnnouncementsPath, hrAnnouncementDetailPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrAnnouncementsFeedPage } from "~/components/screens/hr/HrAnnouncementsFeedPage";
type LoaderData = { title: string; vm: HrAnnouncementFeedVM };
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 unreadOnly = url.searchParams.get("unread") === "1";
const title = `${t("hr.announcements.title")} | ${process.env.APP_NAME}`;
const manageHref = hrAdminAnnouncementsPath(tenantSlug);
if (!ctx.hasModule) {
return Response.json({ title, vm: buildAnnouncementFeedVM({ rows: [], unreadOnly, canManage: false, manageHref }) } satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const profile = await getProfileByUser(ctx.tenantId, ctx.userId);
const entries = await listFeed({ tenantId: ctx.tenantId, userId: ctx.userId, viewerTeam: profile?.team ?? null, viewerLocationId: profile?.locationId ?? null });
const rows: HrAnnouncementFeedRow[] = entries.map((entry) => ({
id: entry.id,
title: entry.title,
snippet: entry.body.slice(0, 140),
pinned: entry.pinnedAt != null,
isRead: entry.isRead,
requiresAcknowledgement: entry.requiresAcknowledgement,
isAcknowledged: entry.isAcknowledged,
reactionCount: entry.reactionCount,
commentCount: entry.commentCount,
publishedIso: (entry.publishAt ?? entry.createdAt).toISOString(),
detailHref: hrAnnouncementDetailPath(tenantSlug, entry.id),
}));
const vm = buildAnnouncementFeedVM({ rows, unreadOnly, canManage: hrHasPermission(ctx, "hr.write"), manageHref });
return Response.json({ title, vm } satisfies LoaderData);
};
export default function HrAnnouncementsRoute() {
const { vm } = useLoaderData<LoaderData>();
return <HrAnnouncementsFeedPage vm={vm} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,201 @@
// P17 HR-Hub core (AK-P17a) — employee detail route. Shows master data, lets the
// employee inline-edit their own self-editable fields, and reveals the encrypted
// emergency contact ON DEMAND (self or hr.read_all only) — audited. The reveal
// surfaces the M002 "encryption not provisioned" Klartext until the AD-8 envelope
// ticket lands (crypto seam deferred).
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import {
badRequestResponse,
hrActionErrorResponse,
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import {
getProfileByUser,
requireEmployeeObjectAccess,
resolveUserLabels,
revealEmergencyContact,
setEmergencyContact,
updateOwnProfile,
} from "~/utils/integrations/hrService.server";
import { hrDirectoryPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import {
HrDirectoryDetailPage,
type RevealedEmergencyContact,
} from "~/components/screens/hr/HrDirectoryDetailPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = {
title: string;
backHref: string;
userId: string;
name: string;
email: string;
position: string | null;
team: string | null;
isSelf: boolean;
canRevealEmergency: boolean;
canEditEmergency: boolean;
hasEmergencyContact: boolean;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const userId = params.userId ?? "";
if (!ctx.hasModule) {
throw notFoundResponse();
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
try {
await requireEmployeeObjectAccess({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
employeeUserId: userId,
canReadAll: hrHasPermission(ctx, "hr.read_all"),
});
} catch {
throw notFoundResponse();
}
const isSelf = userId === ctx.userId;
const [profile, labels] = await Promise.all([getProfileByUser(ctx.tenantId, userId), resolveUserLabels([userId])]);
const labeled = labels.get(userId);
if (!labeled) {
throw notFoundResponse();
}
return Response.json({
title: `${labeled.label} | ${process.env.APP_NAME}`,
backHref: hrDirectoryPath(tenantSlug),
userId,
name: labeled.label,
email: labeled.email,
position: profile?.position ?? null,
team: profile?.team ?? null,
isSelf,
canRevealEmergency: isSelf || hrHasPermission(ctx, "hr.read_all"),
canEditEmergency: isSelf || hrHasPermission(ctx, "hr.write"),
hasEmergencyContact: Boolean(profile?.emergencyContactCiphertext),
} satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
const userId = params.userId ?? "";
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "update-own-profile") {
if (userId !== ctx.userId) {
// Editing someone else's profile via the self endpoint -> 404.
throw notFoundResponse();
}
requireHrPermission(ctx, "hr.read_own");
await updateOwnProfile({
tenantId: ctx.tenantId,
userId: ctx.userId,
data: { position: form.get("position")?.toString() ?? null },
});
return Response.json({ intent, ok: true, messageKey: "hr.directory.toast.profileUpdated" });
}
if (intent === "reveal-emergency") {
const isSelf = userId === ctx.userId;
if (!isSelf) {
requireHrPermission(ctx, "hr.read_all");
await requireEmployeeObjectAccess({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
employeeUserId: userId,
canReadAll: true,
});
} else {
requireHrPermission(ctx, "hr.read_own");
}
const contact = await revealEmergencyContact({ tenantId: ctx.tenantId, userId, revealerUserId: ctx.userId });
return Response.json({ intent, ok: true, contact });
}
if (intent === "set-emergency") {
// Self may set their own; setting someone else's requires hr.write (manage).
const isSelf = userId === ctx.userId;
requireHrPermission(ctx, isSelf ? "hr.read_own" : "hr.write");
if (!isSelf) {
await requireEmployeeObjectAccess({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
employeeUserId: userId,
canReadAll: true,
});
}
const name = (form.get("name")?.toString() ?? "").trim();
const phone = (form.get("phone")?.toString() ?? "").trim();
const relation = (form.get("relation")?.toString() ?? "").trim();
if (!name || !phone) {
throw badRequestResponse();
}
await setEmergencyContact({ tenantId: ctx.tenantId, userId, contact: { name, phone, relation } });
return Response.json({ intent, ok: true, messageKey: "hr.directory.toast.emergencyContactUpdated" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) {
throw error;
}
return hrActionErrorResponse(error);
}
};
type ActionResult = { intent?: string; ok?: boolean; messageKey?: string; error?: string; contact?: RevealedEmergencyContact | null };
export default function HrDirectoryDetailRoute() {
const data = useLoaderData<LoaderData>();
const saveFetcher = useFetcher<ActionResult>();
const revealFetcher = useFetcher<ActionResult>();
const emergencyFetcher = useFetcher<ActionResult>();
useSaveToast(saveFetcher.data);
useSaveToast(revealFetcher.data?.error ? revealFetcher.data : undefined);
useSaveToast(emergencyFetcher.data);
return (
<HrDirectoryDetailPage
backHref={data.backHref}
name={data.name}
email={data.email}
position={data.position}
team={data.team}
isSelf={data.isSelf}
canRevealEmergency={data.canRevealEmergency}
canEditEmergency={data.canEditEmergency}
hasEmergencyContact={data.hasEmergencyContact}
revealedContact={revealFetcher.data?.contact ?? null}
revealing={revealFetcher.state !== "idle"}
saving={saveFetcher.state !== "idle"}
savingEmergency={emergencyFetcher.state !== "idle"}
actions={{
onSaveProfile: ({ position }) =>
saveFetcher.submit({ intent: "update-own-profile", position }, { method: "post" }),
onRevealEmergency: () => revealFetcher.submit({ intent: "reveal-emergency" }, { method: "post" }),
onSetEmergency: ({ name, phone, relation }) =>
emergencyFetcher.submit({ intent: "set-emergency", name, phone, relation }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,68 @@
// P17 HR-Hub core (AK-P17a) — employee directory route. Loader builds the
// HrDirectoryVM once (server-side); the component only renders (DoD A). Module off
// -> locked empty; missing hr.read_own -> 404. Sensitive fields are never part of
// the directory list.
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
import { buildHrDirectoryVM, type HrDirectoryRow, type HrDirectoryVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadHrContext, notFoundResponse, requireHrPermission, hrHasPermission } from "~/utils/integrations/hrAccess.server";
import { listDirectoryForViewer, listLocations, resolveUserLabels } from "~/utils/integrations/hrService.server";
import { hrDirectoryDetailPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrDirectoryPage } from "~/components/screens/hr/HrDirectoryPage";
type LoaderData = { title: string; vm: HrDirectoryVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
if (!ctx.hasModule) {
return Response.json({ title: `${t("hr.directory.title")} | ${process.env.APP_NAME}`, vm: buildHrDirectoryVM({ rows: [], canManage: false }) } satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const [entries, locations] = await Promise.all([
listDirectoryForViewer({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
canReadAll: hrHasPermission(ctx, "hr.read_all"),
}),
listLocations(ctx.tenantId),
]);
const userLabels = await resolveUserLabels(entries.map((entry) => entry.userId));
const locationNames = new Map(locations.map((location) => [location.id, location.name]));
const rows: HrDirectoryRow[] = entries.flatMap((entry) => {
const labeled = userLabels.get(entry.userId);
if (!labeled) return [];
return [{
userId: entry.userId,
name: labeled.label,
email: labeled.email,
position: entry.position,
team: entry.team,
locationName: entry.locationId ? (locationNames.get(entry.locationId) ?? null) : null,
detailHref: hrDirectoryDetailPath(tenantSlug, entry.userId),
}];
});
const vm = buildHrDirectoryVM({ rows, canManage: hrHasPermission(ctx, "hr.write") });
return Response.json({ title: `${t("hr.directory.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
};
export default function HrDirectoryRoute() {
const { vm } = useLoaderData<LoaderData>();
return <HrDirectoryPage vm={vm} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,154 @@
// R-UX3 personnel task hub. The loader resolves every count, section and action
// server-side; the presentational screen never infers permissions from roles.
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
import { buildHrHubVM, type HrHubHrefs, type HrHubVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import {
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import { listForApprover as listLeaveForApprover, listOwnVacationRequests } from "~/utils/integrations/hrLeaveService.server";
import { listForApprover as listRequestsForApprover, listOwnRequests } from "~/utils/integrations/hrRequestService.server";
import { listOwnSickLeave } from "~/utils/integrations/hrSickLeaveService.server";
import { listDirectoryForViewer } from "~/utils/integrations/hrService.server";
import {
hrAdminAnnouncementsPath,
hrAdminPayslipsPath,
hrAdminRequestTemplatesPath,
hrAdminUploadRemindersPath,
hrAnnouncementsPath,
hrDirectoryPath,
hrLeavePath,
hrLocationsPath,
hrMyDocumentsPath,
hrPayslipsPath,
hrRequestsPath,
hrSickPath,
hrSurveysPath,
HR_MODULE_KEY,
} from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrHubPage } from "~/components/screens/hr/HrHubPage";
type LoaderData = { title: string; vm: HrHubVM };
function hubHrefs(tenantSlug: string): HrHubHrefs {
const leave = hrLeavePath(tenantSlug);
const requests = hrRequestsPath(tenantSlug);
return {
leave,
sick: hrSickPath(tenantSlug),
documents: hrMyDocumentsPath(tenantSlug),
payslips: hrPayslipsPath(tenantSlug),
announcements: hrAnnouncementsPath(tenantSlug),
requests,
surveys: hrSurveysPath(tenantSlug),
teamDirectory: `${hrDirectoryPath(tenantSlug)}?scope=team`,
teamLeave: `${leave}?tab=team`,
leaveApprovals: `${leave}?tab=approvals`,
requestApprovals: `${requests}?tab=approvals`,
directory: hrDirectoryPath(tenantSlug),
locations: hrLocationsPath(tenantSlug),
announcementAdmin: hrAdminAnnouncementsPath(tenantSlug),
payslipAdmin: hrAdminPayslipsPath(tenantSlug),
requestTemplates: hrAdminRequestTemplatesPath(tenantSlug),
uploadReminders: hrAdminUploadRemindersPath(tenantSlug),
surveyAdmin: hrSurveysPath(tenantSlug),
};
}
const emptyCounts = {
ownLeave: 0,
ownSick: 0,
ownRequests: 0,
pendingLeaveApprovals: 0,
pendingRequestApprovals: 0,
visibleTeamMembers: 0,
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const hrefs = hubHrefs(tenantSlug);
const title = `${t("hr.hub.title")} | ${process.env.APP_NAME}`;
if (!ctx.hasModule) {
return Response.json({
title,
vm: buildHrHubVM({
moduleActive: false,
hrefs,
counts: emptyCounts,
capabilities: {
canReadAll: false,
canWrite: false,
canApproveLeave: false,
canViewSurveyResults: false,
},
}),
} satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const canReadAll = hrHasPermission(ctx, "hr.read_all");
const canWrite = hrHasPermission(ctx, "hr.write");
const canApproveLeave = hrHasPermission(ctx, "hr.leave.approve");
const canViewSurveyResults = hrHasPermission(ctx, "hr.surveys.results");
const [ownLeave, ownSick, ownRequests, leaveApprovals, requestApprovals, directory] =
await Promise.all([
listOwnVacationRequests(ctx.tenantId, ctx.userId),
listOwnSickLeave(ctx.tenantId, ctx.userId),
listOwnRequests(ctx.tenantId, ctx.userId),
listLeaveForApprover(ctx.tenantId, ctx.userId),
listRequestsForApprover(ctx.tenantId, ctx.userId),
listDirectoryForViewer({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
canReadAll,
}),
]);
const vm = buildHrHubVM({
moduleActive: true,
hrefs,
counts: {
ownLeave: ownLeave.filter((entry) =>
entry.status === "submitted" || entry.status === "clarification"
).length,
ownSick: ownSick.filter((entry) => entry.status === "reported").length,
ownRequests: ownRequests.filter((entry) =>
entry.status === "submitted" || entry.status === "clarification"
).length,
pendingLeaveApprovals: leaveApprovals.length,
pendingRequestApprovals: requestApprovals.length,
visibleTeamMembers: directory.filter((entry) => entry.userId !== ctx.userId).length,
},
capabilities: {
canReadAll,
canWrite,
canApproveLeave,
canViewSurveyResults,
},
});
return Response.json({ title, vm } satisfies LoaderData);
};
export default function HrHubRoute() {
const { vm } = useLoaderData<LoaderData>();
return <HrHubPage vm={vm} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: HR_MODULE_KEY };
@@ -0,0 +1,280 @@
// P17 HR-Hub workflows (AK-P17b) — leave/vacation route. Tabs: my requests
// (+ new-request form), approvals (with overlap-conflict hints) and team
// absences. Read needs hr.read_own; deciding needs hr.leave.approve OR being the
// assigned approver (enforced in the service). Transitional functional UI
// (data-ui-id markers); Subframe polish follows David's D-HR delta.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import {
buildHrLeaveOwnVM,
buildHrLeaveApproverVM,
type HrLeaveOwnVM,
type HrLeaveApproverVM,
type HrLeaveApproverInputRow,
type HrVacationRequestKind,
} from "@hivegrid/view-models";
import type { FormDefinition } from "@hivegrid/form-widget";
import { getTranslations } from "~/locale/i18next.server";
import {
badRequestResponse,
hrActionErrorResponse,
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import { listHrMemberOptions, requireActiveHrMember, resolveUserLabels, type HrMemberOption } from "~/utils/integrations/hrService.server";
import {
approveRequest,
countOverlappingApproved,
listApprovedAbsencesForTeamRange,
listForApprover,
listOwnVacationRequests,
rejectRequest,
replyToClarification,
requestClarification,
submitVacationRequest,
withdrawRequest,
type HrLeaveRequestStatus,
} from "~/utils/integrations/hrLeaveService.server";
import { hrLeavePath } from "~/utils/integrations/hrRoutePaths";
import {
buildHrLeaveFormDefinition,
parseHrM05Values,
} from "~/utils/integrations/hrM05Forms";
import ServerError from "~/components/ui/errors/ServerError";
import { HrLeavePage, type HrLeaveTab } from "~/components/screens/hr/HrLeavePage";
import { useSaveToast } from "~/hooks/use-save-toast";
type TeamAbsence = { id: string; employeeLabel: string; source: string; kind: string; startIso: string; endIso: string };
type LoaderData = {
title: string;
tab: "own" | "approvals" | "team";
canApprove: boolean;
ownVm: HrLeaveOwnVM;
approverVm: HrLeaveApproverVM;
team: TeamAbsence[];
kinds: HrVacationRequestKind[];
memberOptions: HrMemberOption[];
formDefinition: FormDefinition;
};
const KINDS: HrVacationRequestKind[] = ["vacation", "special_leave", "unpaid_leave", "overtime_compensation"];
const dateIso = (date: Date) => date.toISOString().slice(0, 10);
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 tabParam = url.searchParams.get("tab");
const tab: LoaderData["tab"] = tabParam === "approvals" || tabParam === "team" ? tabParam : "own";
const title = `${t("hr.leave.title")} | ${process.env.APP_NAME}`;
const empty: LoaderData = {
title,
tab,
canApprove: false,
ownVm: buildHrLeaveOwnVM({ rows: [], canCreate: false, newHref: hrLeavePath(tenantSlug) }),
approverVm: buildHrLeaveApproverVM({ rows: [] }),
team: [],
kinds: KINDS,
memberOptions: [],
formDefinition: buildHrLeaveFormDefinition(t),
};
if (!ctx.hasModule) {
return Response.json(empty satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const canApprove = hrHasPermission(ctx, "hr.leave.approve");
// My requests.
const [own, memberOptions] = await Promise.all([
listOwnVacationRequests(ctx.tenantId, ctx.userId),
listHrMemberOptions(ctx.tenantId),
]);
const ownVm = buildHrLeaveOwnVM({
rows: own.map((row) => ({
id: row.id,
kind: row.requestKind,
status: row.status,
startDateIso: dateIso(row.startDate),
endDateIso: dateIso(row.endDate),
note: row.note,
clarificationNote: row.clarificationNote,
decisionNote: row.decisionNote,
detailHref: hrLeavePath(tenantSlug),
})),
canCreate: true,
newHref: hrLeavePath(tenantSlug),
});
// Approvals (assigned to me, or any if I hold the capability).
let approverVm = buildHrLeaveApproverVM({ rows: [] });
if (canApprove || tab === "approvals") {
const pending = await listForApprover(ctx.tenantId, ctx.userId);
const labels = await resolveUserLabels(pending.map((row) => row.employeeUserId));
const rows: HrLeaveApproverInputRow[] = [];
for (const row of pending) {
const conflictCount = await countOverlappingApproved(ctx.tenantId, row);
rows.push({
id: row.id,
employeeLabel: labels.get(row.employeeUserId)?.label ?? t("hr.picker.unknownMember"),
kind: row.requestKind,
status: row.status as Exclude<HrLeaveRequestStatus, never>,
startDateIso: dateIso(row.startDate),
endDateIso: dateIso(row.endDate),
note: row.note,
conflictCount,
detailHref: hrLeavePath(tenantSlug),
});
}
approverVm = buildHrLeaveApproverVM({ rows });
}
// Team absences (next 90 days of approved vacation + sick).
let team: TeamAbsence[] = [];
if (tab === "team") {
const from = new Date();
const to = new Date(from.getTime() + 90 * 24 * 60 * 60 * 1000);
const absences = await listApprovedAbsencesForTeamRange({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
canReadAll: hrHasPermission(ctx, "hr.read_all"),
from,
to,
});
const labels = await resolveUserLabels(absences.map((a) => a.employeeUserId));
team = absences.map((a) => ({
id: a.id,
employeeLabel: labels.get(a.employeeUserId)?.label ?? t("hr.picker.unknownMember"),
source: a.source,
kind: a.kind,
startIso: dateIso(a.startDate),
endIso: dateIso(a.endDate),
}));
}
return Response.json({
title,
tab,
canApprove,
ownVm,
approverVm,
team,
kinds: KINDS,
memberOptions,
formDefinition: buildHrLeaveFormDefinition(t, memberOptions),
} 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 requestId = form.get("requestId")?.toString() ?? "";
const canApproveAny = hrHasPermission(ctx, "hr.leave.approve");
try {
if (intent === "submit") {
const values = parseHrM05Values(form.get("formValues")?.toString() ?? "");
if (!values) throw badRequestResponse();
const kind = (values.requestKind ?? "vacation") as HrVacationRequestKind;
const start = typeof values.startDate === "string" ? values.startDate : "";
const end = typeof values.endDate === "string" ? values.endDate : "";
if (!start || !end) throw badRequestResponse();
const assignedApproverUserId =
typeof values.approverUserId === "string" &&
values.approverUserId !== "__none__"
? values.approverUserId
: null;
if (assignedApproverUserId) {
await requireActiveHrMember(ctx.tenantId, assignedApproverUserId);
}
await submitVacationRequest({
tenantId: ctx.tenantId,
employeeUserId: ctx.userId,
requestKind: KINDS.includes(kind) ? kind : "vacation",
startDate: new Date(start),
endDate: new Date(end),
note: typeof values.note === "string" ? values.note : null,
assignedApproverUserId,
formValues: values,
});
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.submitted" });
}
if (intent === "withdraw") {
await withdrawRequest({ tenantId: ctx.tenantId, requestId, employeeUserId: ctx.userId });
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.withdrawn" });
}
if (intent === "reply") {
await replyToClarification({ tenantId: ctx.tenantId, requestId, employeeUserId: ctx.userId, reply: form.get("reply")?.toString() ?? "" });
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.clarificationReplied" });
}
if (intent === "approve") {
// Locale-resolved calendar titles for the P16/M25 absence event — the
// service is i18n-free, so the route resolves them (booking precedent).
const { t } = await getTranslations(request);
const absenceTitleByKind = Object.fromEntries(KINDS.map((k) => [k, t(`hr.leave.kind.${k}`)])) as Record<HrVacationRequestKind, string>;
await approveRequest({ tenantId: ctx.tenantId, requestId, deciderUserId: ctx.userId, canApproveAny, decisionNote: form.get("note")?.toString() ?? null, absenceTitleByKind });
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.approved" });
}
if (intent === "reject") {
await rejectRequest({ tenantId: ctx.tenantId, requestId, deciderUserId: ctx.userId, canApproveAny, decisionNote: form.get("note")?.toString() ?? null });
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.rejected" });
}
if (intent === "clarify") {
await requestClarification({
tenantId: ctx.tenantId,
requestId,
deciderUserId: ctx.userId,
canApproveAny,
question: form.get("question")?.toString() ?? "",
});
return Response.json({ intent, ok: true, messageKey: "hr.leave.toast.clarificationRequested" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrLeaveRoute() {
const { tab, canApprove, ownVm, approverVm, team, formDefinition } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
return (
<HrLeavePage
tab={tab}
canApprove={canApprove}
ownVm={ownVm}
approverVm={approverVm}
team={team}
formDefinition={formDefinition}
tabHref={(next: HrLeaveTab) => `?tab=${next}`}
submitting={fetcher.state !== "idle"}
actions={{
onSubmit: (values) =>
submit({ intent: "submit", formValues: JSON.stringify(values) }),
onWithdraw: (requestId) => submit({ intent: "withdraw", requestId }),
onReply: (requestId, reply) => submit({ intent: "reply", requestId, reply }),
onApprove: (requestId) => submit({ intent: "approve", requestId }),
onReject: (requestId) => submit({ intent: "reject", requestId }),
onClarify: (requestId, question) => submit({ intent: "clarify", requestId, question }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,146 @@
// P17 HR-Hub core (AK-P17a) — locations route. Loader builds HrLocationListVM with
// per-location employee counts. Read needs hr.read_own; managing (create/edit/
// default/reassign) needs hr.write — gated in the action. Module off -> locked
// empty; missing permission -> 404.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrLocationListVM, type HrLocationRow as HrLocationVMRow, type HrLocationListVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import {
badRequestResponse,
hrActionErrorResponse,
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import {
archiveLocation,
createLocation,
listDirectory,
listLocations,
reassignLocationEmployees,
updateLocation,
} from "~/utils/integrations/hrService.server";
import { hrLocationsPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrLocationsPage } from "~/components/screens/hr/HrLocationsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrLocationListVM };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
if (!ctx.hasModule) {
return Response.json({
title: `${t("hr.locations.title")} | ${process.env.APP_NAME}`,
vm: buildHrLocationListVM({ rows: [], canManage: false, createHref: hrLocationsPath(tenantSlug) }),
} satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const [locations, directory] = await Promise.all([listLocations(ctx.tenantId), listDirectory(ctx.tenantId)]);
const countByLocation = new Map<string, number>();
for (const entry of directory) {
if (entry.locationId) {
countByLocation.set(entry.locationId, (countByLocation.get(entry.locationId) ?? 0) + 1);
}
}
const rows: HrLocationVMRow[] = locations.map((location) => ({
id: location.id,
name: location.name,
addressLine1: location.addressLine1,
postalCode: location.postalCode,
city: location.city,
country: location.country,
phone: location.phone,
latitude: location.latitude,
longitude: location.longitude,
description: location.description,
isDefault: location.isDefault,
employeeCount: countByLocation.get(location.id) ?? 0,
detailHref: hrLocationsPath(tenantSlug),
}));
const vm = buildHrLocationListVM({ rows, canManage: hrHasPermission(ctx, "hr.write"), createHref: hrLocationsPath(tenantSlug) });
return Response.json({ title: `${t("hr.locations.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
try {
if (intent === "create") {
await createLocation({
tenantId: ctx.tenantId,
name: form.get("name")?.toString() ?? "",
city: form.get("city")?.toString() ?? null,
isDefault: form.get("isDefault") === "1",
});
return Response.json({ intent, ok: true, messageKey: "hr.locations.toast.created" });
}
if (intent === "update") {
await updateLocation({
tenantId: ctx.tenantId,
locationId: form.get("locationId")?.toString() ?? "",
name: form.get("name")?.toString(),
city: form.get("city")?.toString(),
});
return Response.json({ intent, ok: true, messageKey: "hr.locations.toast.updated" });
}
if (intent === "set-default") {
await updateLocation({ tenantId: ctx.tenantId, locationId: form.get("locationId")?.toString() ?? "", isDefault: true });
return Response.json({ intent, ok: true, messageKey: "hr.locations.toast.defaultSet" });
}
if (intent === "archive") {
await archiveLocation({ tenantId: ctx.tenantId, locationId: form.get("locationId")?.toString() ?? "" });
return Response.json({ intent, ok: true, messageKey: "hr.locations.toast.archived" });
}
if (intent === "reassign") {
const count = await reassignLocationEmployees({
tenantId: ctx.tenantId,
fromLocationId: form.get("fromLocationId")?.toString() ?? "",
toLocationId: form.get("toLocationId")?.toString() ?? "",
});
return Response.json({ intent, ok: true, count, messageKey: "hr.locations.toast.reassigned" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) {
throw error;
}
return hrActionErrorResponse(error);
}
};
export default function HrLocationsRoute() {
const { vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
return (
<HrLocationsPage
vm={vm}
submitting={fetcher.state !== "idle"}
actions={{
onCreate: ({ name, city, isDefault }) => fetcher.submit({ intent: "create", name, city, isDefault: isDefault ? "1" : "0" }, { method: "post" }),
onSetDefault: (locationId) => fetcher.submit({ intent: "set-default", locationId }, { method: "post" }),
onArchive: (locationId) => fetcher.submit({ intent: "archive", locationId }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,186 @@
// P17 HR-Hub core (AK-P17a) — employee "my documents" route. The employee sees
// their own employee-visible documents; office-uploaded ones are read-only. Build
// the HrDocumentListVM in the loader; archive own non-office docs in the action.
//
// Self-upload is INDEPENDENT of the Files module's files.write permission: the
// screen posts the file as multipart to intent=upload-doc, gated on hr.read_own.
// The action stores it via the single-shot createFileFromBytes primitive (scan +
// File row + scan/preview fan-out) and links it as an HrEmployeeDocument through
// createDocument. No chunked client, no files.write.
import { useCallback, useEffect, useRef, useState } from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrDocumentListVM, hrDocumentKindKey, type HrDocumentKind, type HrDocumentRow as HrDocumentVMRow, type HrDocumentListVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { archiveDocument, createDocumentWithLink, listEmployeeDocuments } from "~/utils/integrations/hrService.server";
import { createFileFromBytes, hardDeleteFile } from "~/utils/integrations/fileService.server";
import { StorageScanRejectedError } from "~/utils/integrations/storageService";
import { hrMyDocumentsPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrMyDocumentsPage, type HrDocumentUploadState, type HrMyDocumentsUploadInput } from "~/components/screens/hr/HrMyDocumentsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrDocumentListVM; tenantSlug: string };
type UploadActionData = { intent?: string; ok?: boolean; messageKey?: string; error?: string };
// Single-request self-upload cap. HR personnel documents are small; larger files
// belong in the dedicated Files module (chunked). Rejected with a Klartext error.
const HR_DOC_MAX_BYTES = 25 * 1024 * 1024;
const DOCUMENT_KINDS: readonly HrDocumentKind[] = ["contract", "certificate", "identification", "qualification", "other"];
// The underlying file bytes are delivered by the Files auth-proxy route (AK-P4a).
function fileHref(tenantSlug: string, fileId: string): string {
return `/${tenantSlug}/files/${fileId}`;
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
if (!ctx.hasModule) {
return Response.json({ title: `${t("hr.documents.title")} | ${process.env.APP_NAME}`, vm: buildHrDocumentListVM({ rows: [], canUpload: false, uploadHref: hrMyDocumentsPath(tenantSlug) }), tenantSlug } satisfies LoaderData);
}
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const docs = await listEmployeeDocuments({ tenantId: ctx.tenantId, employeeUserId: ctx.userId, viewerIsEmployee: true });
const now = Date.now();
const rows: HrDocumentVMRow[] = docs.map((doc) => ({
id: doc.id,
title: doc.title,
documentKind: doc.documentKind,
kindKey: hrDocumentKindKey(doc.documentKind),
createdAtIso: doc.createdAt.toISOString(),
validUntilIso: doc.validUntil ? doc.validUntil.toISOString() : null,
isExpired: Boolean(doc.validUntil && doc.validUntil.getTime() < now),
readOnly: doc.uploadedByOffice,
fileHref: fileHref(tenantSlug, doc.fileId),
}));
const vm = buildHrDocumentListVM({ rows, canUpload: true, uploadHref: hrMyDocumentsPath(tenantSlug) });
return Response.json({ title: `${t("hr.documents.title")} | ${process.env.APP_NAME}`, vm, tenantSlug } 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();
try {
if (intent === "archive") {
await archiveDocument({ tenantId: ctx.tenantId, documentId: form.get("documentId")?.toString() ?? "", actorUserId: ctx.userId, viewerIsEmployee: true });
return Response.json({ intent, ok: true, messageKey: "hr.documents.toast.archived" });
}
if (intent === "upload-doc") {
const fileEntry = form.get("file");
const title = (form.get("title")?.toString() ?? "").trim();
const kindRaw = form.get("documentKind")?.toString() ?? "other";
const documentKind = (DOCUMENT_KINDS as readonly string[]).includes(kindRaw) ? (kindRaw as HrDocumentKind) : "other";
const validUntilRaw = form.get("validUntil")?.toString() ?? "";
const validUntil = validUntilRaw ? new Date(validUntilRaw) : null;
if (!(fileEntry instanceof File) || fileEntry.size === 0 || !title) {
return Response.json({ intent, error: "hr.documents.upload.error.generic" } satisfies UploadActionData, { status: 400 });
}
if (fileEntry.size > HR_DOC_MAX_BYTES) {
return Response.json({ intent, error: "hr.documents.upload.error.tooLarge" } satisfies UploadActionData, { status: 400 });
}
const bytes = new Uint8Array(await fileEntry.arrayBuffer());
// Self-service: create the File gated on hr.read_own (NOT files.write) and
// link it as the employee's own, editable (non-office) personnel document.
const created = await createFileFromBytes({
tenantId: ctx.tenantId,
userId: ctx.userId,
filename: fileEntry.name || title,
mimeType: fileEntry.type || "application/octet-stream",
bytes,
});
try {
await createDocumentWithLink({
tenantId: ctx.tenantId,
employeeUserId: ctx.userId,
uploadedByUserId: ctx.userId,
title,
documentKind,
fileId: created.id,
visibility: "employee",
uploadedByOffice: false,
validUntil: validUntil && !Number.isNaN(validUntil.getTime()) ? validUntil : null,
});
} catch (error) {
await hardDeleteFile({ tenantId: ctx.tenantId, fileId: created.id }).catch(() => {});
throw error;
}
return Response.json({ intent, ok: true, messageKey: "hr.documents.toast.uploaded" } satisfies UploadActionData);
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) {
throw error;
}
if (error instanceof StorageScanRejectedError) {
return Response.json({ intent, error: "hr.documents.upload.error.rejected" } satisfies UploadActionData, { status: 422 });
}
return hrActionErrorResponse(error);
}
};
const IDLE: HrDocumentUploadState = { status: "idle", errorKey: null };
export default function HrMyDocumentsRoute() {
const { vm } = useLoaderData<LoaderData>();
const archiveFetcher = useFetcher();
const uploadFetcher = useFetcher<UploadActionData>();
useSaveToast(archiveFetcher.data);
useSaveToast(uploadFetcher.data);
const [upload, setUpload] = useState<HrDocumentUploadState>(IDLE);
// True only while a submit initiated in THIS dialog session awaits its result.
// Prevents a prior upload's stale fetcher.data from re-closing a reopened dialog.
const awaitingRef = useRef(false);
const onUpload = useCallback(
(input: HrMyDocumentsUploadInput) => {
awaitingRef.current = true;
setUpload({ status: "uploading", errorKey: null });
const body = new FormData();
body.set("intent", "upload-doc");
body.set("file", input.file);
body.set("title", input.title);
body.set("documentKind", input.documentKind);
body.set("validUntil", input.validUntilIso ?? "");
uploadFetcher.submit(body, { method: "post", encType: "multipart/form-data" });
},
[uploadFetcher],
);
// Reflect the upload fetcher's outcome exactly once per submission.
useEffect(() => {
if (!awaitingRef.current || uploadFetcher.state !== "idle" || !uploadFetcher.data) return;
awaitingRef.current = false;
setUpload(uploadFetcher.data.ok ? { status: "done", errorKey: null } : { status: "error", errorKey: uploadFetcher.data.error ?? "hr.documents.upload.error.generic" });
}, [uploadFetcher.state, uploadFetcher.data]);
return (
<HrMyDocumentsPage
vm={vm}
submitting={archiveFetcher.state !== "idle"}
upload={upload}
actions={{
onArchive: (documentId) => archiveFetcher.submit({ intent: "archive", documentId }, { method: "post" }),
onUpload,
onResetUpload: () => setUpload(IDLE),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,3 @@
import { legacyPasswordSafeRedirectLoader } from "~/utils/integrations/passwordSafeLegacyRedirect.server";
export const loader = legacyPasswordSafeRedirectLoader("vault");
@@ -0,0 +1,3 @@
import { legacyPasswordSafeRedirectLoader } from "~/utils/integrations/passwordSafeLegacyRedirect.server";
export const loader = legacyPasswordSafeRedirectLoader("list");
@@ -0,0 +1,83 @@
// P17 HR-Hub workflows (AK-P17b) — employee payslips. Own list; opening a
// payslip marks it read and audits the read, then returns the File id to open.
// Read needs hr.read_own. Transitional UI.
import { useEffect } from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrPayslipOwnVM, type HrPayslipOwnVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import {
badRequestResponse,
hrActionErrorResponse,
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import { listOwnPayslips, openPayslip } from "~/utils/integrations/hrPayslipService.server";
import { hrPayslipsPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrPayslipsPage } from "~/components/screens/hr/HrPayslipsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; selfHref: string; filesBase: string; vm: HrPayslipOwnVM };
type ActionData = { intent?: string; ok?: boolean; fileId?: string | null; error?: string };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const title = `${t("hr.payslips.title")} | ${process.env.APP_NAME}`;
const selfHref = hrPayslipsPath(tenantSlug);
const filesBase = `/${tenantSlug}/files`;
if (!ctx.hasModule) return Response.json({ title, selfHref, filesBase, vm: buildHrPayslipOwnVM({ rows: [] }) } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const payslips = await listOwnPayslips(ctx.tenantId, ctx.userId);
const vm = buildHrPayslipOwnVM({
rows: payslips.map((p) => ({ id: p.id, periodYear: p.periodYear, periodMonth: p.periodMonth, isRead: p.isRead, openHref: selfHref })),
});
return Response.json({ title, selfHref, filesBase, vm } 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();
if (form.get("intent")?.toString() !== "open") throw badRequestResponse();
try {
const fileId = await openPayslip({
tenantId: ctx.tenantId,
payslipId: form.get("payslipId")?.toString() ?? "",
userId: ctx.userId,
canReadAll: hrHasPermission(ctx, "hr.read_all"),
});
return Response.json({ intent: "open", ok: true, fileId } satisfies ActionData);
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrPayslipsRoute() {
const { filesBase, vm } = useLoaderData<LoaderData>();
const fetcher = useFetcher<ActionData>();
useSaveToast(fetcher.data?.error ? fetcher.data : undefined);
useEffect(() => {
if (fetcher.state === "idle" && fetcher.data?.fileId) {
window.open(`${filesBase}/${fetcher.data.fileId}`, "_blank", "noreferrer");
}
}, [fetcher.state, fetcher.data, filesBase]);
return <HrPayslipsPage vm={vm} submitting={fetcher.state !== "idle"} actions={{ onOpen: (payslipId) => fetcher.submit({ intent: "open", payslipId }, { method: "post" }) }} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,231 @@
// P17 HR-Hub workflows (AK-P17b) — generic HR requests. Tabs: my requests
// (+ new from a template, transitional form) and approvals. Read needs
// hr.read_own; deciding needs hr.write OR being the assigned approver. Until the
// M05 renderer (AK-P16c) lands, the payload is a free-text "details" field.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrRequestOwnVM, buildHrRequestApproverVM, type HrRequestOwnVM, type HrRequestApproverVM, type HrRequestKind } from "@hivegrid/view-models";
import type { FormDefinition } from "@hivegrid/form-widget";
import { getTranslations } from "~/locale/i18next.server";
import {
badRequestResponse,
hrActionErrorResponse,
hrHasPermission,
loadHrContext,
notFoundResponse,
requireHrPermission,
} from "~/utils/integrations/hrAccess.server";
import { listHrMemberOptions, requireActiveHrMember, resolveUserLabels, type HrMemberOption } from "~/utils/integrations/hrService.server";
import {
decideRequest,
listForApprover,
listOwnRequests,
listRequestTemplateDefinitions,
listTemplates,
requestClarification,
submitRequest,
withdrawRequest,
} from "~/utils/integrations/hrRequestService.server";
import { hrRequestsPath } from "~/utils/integrations/hrRoutePaths";
import {
buildHrRequestFormDefinition,
parseHrM05Values,
} from "~/utils/integrations/hrM05Forms";
import ServerError from "~/components/ui/errors/ServerError";
import { HrRequestsPage, type HrRequestsTab } from "~/components/screens/hr/HrRequestsPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type TemplateOption = { id: string; title: string; requestKind: HrRequestKind; definition: FormDefinition };
type LoaderData = {
title: string;
tab: "own" | "approvals";
canApprove: boolean;
ownVm: HrRequestOwnVM;
approverVm: HrRequestApproverVM;
templates: TemplateOption[];
memberOptions: HrMemberOption[];
defaultFormDefinition: FormDefinition;
};
const KINDS: HrRequestKind[] = ["expense", "hardware", "training", "reference"];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const tab: LoaderData["tab"] = new URL(request.url).searchParams.get("tab") === "approvals" ? "approvals" : "own";
const title = `${t("hr.requests.title")} | ${process.env.APP_NAME}`;
const empty: LoaderData = {
title,
tab,
canApprove: false,
ownVm: buildHrRequestOwnVM({ rows: [], newHref: hrRequestsPath(tenantSlug) }),
approverVm: buildHrRequestApproverVM({ rows: [] }),
templates: [],
memberOptions: [],
defaultFormDefinition: buildHrRequestFormDefinition(t),
};
if (!ctx.hasModule) return Response.json(empty satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const canApprove = hrHasPermission(ctx, "hr.write");
const [own, memberOptions, templates, templateDefinitions] = await Promise.all([
listOwnRequests(ctx.tenantId, ctx.userId),
listHrMemberOptions(ctx.tenantId),
listTemplates(ctx.tenantId),
listRequestTemplateDefinitions(ctx.tenantId),
]);
const ownVm = buildHrRequestOwnVM({
rows: own.map((r) => ({
id: r.id,
title: r.title,
kind: r.requestKind,
status: r.status,
createdIso: r.createdAt.toISOString(),
detailHref: hrRequestsPath(tenantSlug),
})),
newHref: hrRequestsPath(tenantSlug),
});
const templateOptions: TemplateOption[] = templates
.flatMap((tpl) => {
const definition = templateDefinitions.get(tpl.id);
return tpl.isActive && definition
? [{ id: tpl.id, title: tpl.title, requestKind: tpl.requestKind, definition }]
: [];
});
let approverVm = buildHrRequestApproverVM({ rows: [] });
if (canApprove || tab === "approvals") {
const pending = await listForApprover(ctx.tenantId, ctx.userId);
const labels = await resolveUserLabels(pending.map((r) => r.employeeUserId));
approverVm = buildHrRequestApproverVM({
rows: pending.map((r) => ({
id: r.id,
title: r.title,
employeeLabel: labels.get(r.employeeUserId)?.label ?? t("hr.picker.unknownMember"),
kind: r.requestKind,
status: r.status,
createdIso: r.createdAt.toISOString(),
detailHref: hrRequestsPath(tenantSlug),
})),
});
}
return Response.json({
title,
tab,
canApprove,
ownVm,
approverVm,
templates: templateOptions,
memberOptions,
defaultFormDefinition: buildHrRequestFormDefinition(t, memberOptions),
} 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 requestId = form.get("requestId")?.toString() ?? "";
const canApproveAny = hrHasPermission(ctx, "hr.write");
try {
if (intent === "submit") {
const values = parseHrM05Values(form.get("formValues")?.toString() ?? "");
if (!values) throw badRequestResponse();
const kind = (values.requestKind ?? "expense") as HrRequestKind;
const assignedApproverUserId =
typeof values.approverUserId === "string" &&
values.approverUserId !== "__none__"
? values.approverUserId
: null;
if (assignedApproverUserId) {
await requireActiveHrMember(ctx.tenantId, assignedApproverUserId);
}
await submitRequest({
tenantId: ctx.tenantId,
employeeUserId: ctx.userId,
templateId: form.get("templateId")?.toString() || null,
requestKind: KINDS.includes(kind) ? kind : "expense",
title: typeof values.title === "string" ? values.title : "",
details: typeof values.details === "string" ? values.details : null,
assignedApproverUserId,
formValues: values,
});
return Response.json({ intent, ok: true, messageKey: "hr.requests.toast.submitted" });
}
if (intent === "withdraw") {
await withdrawRequest({ tenantId: ctx.tenantId, requestId, employeeUserId: ctx.userId });
return Response.json({ intent, ok: true, messageKey: "hr.requests.toast.withdrawn" });
}
if (intent === "approve" || intent === "reject") {
await decideRequest({
tenantId: ctx.tenantId,
requestId,
deciderUserId: ctx.userId,
canApproveAny,
decision: intent === "approve" ? "approved" : "rejected",
decisionNote: form.get("note")?.toString() ?? null,
});
return Response.json({
intent,
ok: true,
messageKey: intent === "approve" ? "hr.requests.toast.approved" : "hr.requests.toast.rejected",
});
}
if (intent === "clarify") {
await requestClarification({
tenantId: ctx.tenantId,
requestId,
deciderUserId: ctx.userId,
canApproveAny,
question: form.get("question")?.toString() ?? "",
});
return Response.json({ intent, ok: true, messageKey: "hr.requests.toast.clarificationRequested" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrRequestsRoute() {
const { tab, canApprove, ownVm, approverVm, templates, defaultFormDefinition } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
return (
<HrRequestsPage
tab={tab}
canApprove={canApprove}
ownVm={ownVm}
approverVm={approverVm}
templates={templates}
defaultFormDefinition={defaultFormDefinition}
tabHref={(next: HrRequestsTab) => `?tab=${next}`}
submitting={fetcher.state !== "idle"}
actions={{
onSubmit: ({ templateId, values }) =>
submit({ intent: "submit", templateId, formValues: JSON.stringify(values) }),
onWithdraw: (requestId) => submit({ intent: "withdraw", requestId }),
onApprove: (requestId) => submit({ intent: "approve", requestId }),
onReject: (requestId) => submit({ intent: "reject", requestId }),
onClarify: (requestId, question) => submit({ intent: "clarify", requestId, question }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,246 @@
// 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 { useState } from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrSickOwnVM, buildHrSickOfficeVM, type HrSickLeaveOwnVM, type HrSickLeaveOfficeVM, type HrSickLeaveInputRow } from "@hivegrid/view-models";
import type { FormDefinition } from "@hivegrid/form-widget";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { listHrMemberOptions, requireEmployeeObjectAccess, resolveUserLabels, type HrMemberOption } from "~/utils/integrations/hrService.server";
import { attachCertificate, cancelSickLeave, closeSickLeave, listOwnSickLeave, listSickLeaveForOffice, reportSickLeave, revealCertificateFileId, type SickLeaveRow } from "~/utils/integrations/hrSickLeaveService.server";
import { createFileFromBytes, hardDeleteFile } from "~/utils/integrations/fileService.server";
import { StorageScanRejectedError } from "~/utils/integrations/storageService";
import { hrSickPath } from "~/utils/integrations/hrRoutePaths";
import {
buildHrSickFormDefinition,
parseHrM05Values,
} from "~/utils/integrations/hrM05Forms";
import ServerError from "~/components/ui/errors/ServerError";
import { HrSickPage, type HrSickTab } from "~/components/screens/hr/HrSickPage";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
type LoaderData = {
title: string;
tab: "own" | "office";
canManage: boolean;
selfHref: string;
filesBase: string;
ownVm: HrSickLeaveOwnVM;
officeVm: HrSickLeaveOfficeVM;
memberOptions: HrMemberOption[];
ownFormDefinition: FormDefinition;
officeFormDefinition: FormDefinition;
};
const HR_CERTIFICATE_MAX_BYTES = 25 * 1024 * 1024;
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: [] }), memberOptions: [], ownFormDefinition: buildHrSickFormDefinition(t), officeFormDefinition: buildHrSickFormDefinition(t) };
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, memberOptions] = await Promise.all([
listOwnSickLeave(ctx.tenantId, ctx.userId),
canManage ? listHrMemberOptions(ctx.tenantId) : Promise.resolve([]),
]);
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 ?? t("hr.picker.unknownMember") })) });
}
return Response.json({
title,
tab,
canManage,
selfHref: revealHref,
filesBase,
ownVm,
officeVm,
memberOptions,
ownFormDefinition: buildHrSickFormDefinition(t),
officeFormDefinition: buildHrSickFormDefinition(t, memberOptions),
} 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() ?? "";
const canManageAny = hrHasPermission(ctx, "hr.write");
try {
if (intent === "report") {
const values = parseHrM05Values(form.get("formValues")?.toString() ?? "");
if (!values) throw badRequestResponse();
const start = typeof values.startDate === "string" ? values.startDate : "";
if (!start) throw badRequestResponse();
const expected =
typeof values.expectedReturnDate === "string"
? values.expectedReturnDate
: "";
await reportSickLeave({ tenantId: ctx.tenantId, employeeUserId: ctx.userId, reportedByUserId: ctx.userId, startDate: new Date(start), expectedReturnDate: expected ? new Date(expected) : null, note: typeof values.note === "string" ? values.note : null, formValues: values });
return Response.json({ intent, ok: true, messageKey: "hr.sick.toast.reported" });
}
if (intent === "report-for") {
requireHrPermission(ctx, "hr.write");
const values = parseHrM05Values(form.get("formValues")?.toString() ?? "");
if (!values) throw badRequestResponse();
const employeeUserId =
typeof values.employeeUserId === "string" ? values.employeeUserId : "";
const start = typeof values.startDate === "string" ? values.startDate : "";
if (!employeeUserId || !start) throw badRequestResponse();
await requireEmployeeObjectAccess({
tenantId: ctx.tenantId,
viewerUserId: ctx.userId,
employeeUserId,
canReadAll: true,
});
await reportSickLeave({ tenantId: ctx.tenantId, employeeUserId, reportedByUserId: ctx.userId, startDate: new Date(start), expectedReturnDate: typeof values.expectedReturnDate === "string" && values.expectedReturnDate ? new Date(values.expectedReturnDate) : null, note: typeof values.note === "string" ? values.note : null, formValues: values });
return Response.json({ intent, ok: true, messageKey: "hr.sick.toast.reportedForEmployee" });
}
if (intent === "attach") {
const certificate = form.get("certificate");
if (!(certificate instanceof File) || certificate.size === 0) throw badRequestResponse();
if (certificate.size > HR_CERTIFICATE_MAX_BYTES) {
return Response.json({ intent, error: "hr.sick.upload.tooLarge" }, { status: 400 });
}
const created = await createFileFromBytes({
tenantId: ctx.tenantId,
userId: ctx.userId,
filename: certificate.name || "au-nachweis",
mimeType: certificate.type || "application/octet-stream",
bytes: new Uint8Array(await certificate.arrayBuffer()),
});
try {
await attachCertificate({
tenantId: ctx.tenantId,
reportId,
actorUserId: ctx.userId,
certificateFileId: created.id,
canManageAny,
});
} catch (error) {
await hardDeleteFile({ tenantId: ctx.tenantId, fileId: created.id }).catch(() => {});
throw error;
}
return Response.json({ intent, ok: true, messageKey: "hr.sick.toast.certificateUploaded" });
}
if (intent === "reveal") {
const fileId = await revealCertificateFileId({ tenantId: ctx.tenantId, reportId, revealerUserId: ctx.userId, canManageAny });
return Response.json({ intent, 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), canManageAny });
return Response.json({ intent, ok: true, messageKey: "hr.sick.toast.closed" });
}
if (intent === "cancel") {
await cancelSickLeave({ tenantId: ctx.tenantId, reportId, actorUserId: ctx.userId, canManageAny });
return Response.json({ intent, ok: true, messageKey: "hr.sick.toast.cancelled" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
if (error instanceof StorageScanRejectedError) {
return Response.json({ intent, error: "hr.sick.upload.rejected" }, { status: 422 });
}
return hrActionErrorResponse(error);
}
};
export default function HrSickRoute() {
const { tab, canManage, selfHref, filesBase, ownVm, officeVm, ownFormDefinition, officeFormDefinition } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
const [revealError, setRevealError] = useState<SaveActionResult>();
useSaveToast(fetcher.data);
useSaveToast(revealError);
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);
try {
const response = await fetch(selfHref, { method: "POST", body });
const data = (await response.json().catch(() => null)) as { fileId?: string | null; error?: string | null } | null;
if (!response.ok || !data?.fileId) {
setRevealError({ intent: "reveal", error: data?.error || "shared.saveToast.errorFallback" });
return;
}
window.open(`${filesBase}/${data.fileId}`, "_blank", "noreferrer");
} catch {
setRevealError({ intent: "reveal", error: "shared.saveToast.errorFallback" });
}
}
return (
<HrSickPage
tab={tab}
canManage={canManage}
ownVm={ownVm}
officeVm={officeVm}
ownFormDefinition={ownFormDefinition}
officeFormDefinition={officeFormDefinition}
tabHref={(next: HrSickTab) => `?tab=${next}`}
submitting={fetcher.state !== "idle"}
actions={{
onReport: (values) => submit({ intent: "report", formValues: JSON.stringify(values) }),
onReportFor: (values) => submit({ intent: "report-for", formValues: JSON.stringify(values) }),
onAttach: (reportId, certificate) => {
const body = new FormData();
body.set("intent", "attach");
body.set("reportId", reportId);
body.set("certificate", certificate);
fetcher.submit(body, { method: "post", encType: "multipart/form-data" });
},
onRevealCertificate: revealCertificate,
onClose: (reportId, returnDate) => submit({ intent: "close", reportId, returnDate }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,66 @@
// 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<LoaderData>();
return <HrSurveyResultsPage vm={vm} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };
@@ -0,0 +1,123 @@
// 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" };
@@ -0,0 +1,127 @@
// P17 HR-Hub workflows (AK-P17b) — surveys list. Participate in open surveys,
// view gated results; managers (hr.write) create surveys and open/close them.
// Result visibility is enforced by hr.surveys.results. Transitional UI.
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
import { buildHrSurveyListVM, type HrSurveyListVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, hrActionErrorResponse, hrHasPermission, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
import { archiveSurvey, createSurvey, hasSubmitted, listSurveys, setSurveyStatus, type HrSurveyResultVisibility, type HrSurveyStatus } from "~/utils/integrations/hrSurveyService.server";
import { isHrAudienceVisible, listHrAudienceOptions, type HrAudienceKind, type HrAudienceOption } from "~/utils/integrations/hrAudience.server";
import { getProfileByUser } from "~/utils/integrations/hrService.server";
import { hrSurveyParticipatePath, hrSurveyResultsPath, hrSurveysPath } from "~/utils/integrations/hrRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
import { HrSurveysListPage } from "~/components/screens/hr/HrSurveysListPage";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = { title: string; vm: HrSurveyListVM; canManage: boolean; statuses: HrSurveyStatus[]; audienceOptions: HrAudienceOption[] };
const VISIBILITIES: HrSurveyResultVisibility[] = ["admins", "participants", "everyone"];
const AUDIENCES: HrAudienceKind[] = ["all", "team", "location"];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadHrContext({ request, params });
const tenantSlug = params.tenant ?? "";
const title = `${t("hr.surveys.title")} | ${process.env.APP_NAME}`;
const createHref = hrSurveysPath(tenantSlug);
if (!ctx.hasModule) return Response.json({ title, vm: buildHrSurveyListVM({ rows: [], canManage: false, createHref }), canManage: false, statuses: [], audienceOptions: [] } satisfies LoaderData);
try {
requireHrPermission(ctx, "hr.read_own");
} catch {
throw notFoundResponse();
}
const canManage = hrHasPermission(ctx, "hr.write");
const canResults = hrHasPermission(ctx, "hr.surveys.results");
const [allSurveys, profile, audienceOptions] = await Promise.all([
listSurveys(ctx.tenantId),
getProfileByUser(ctx.tenantId, ctx.userId),
canManage ? listHrAudienceOptions(ctx.tenantId) : Promise.resolve([]),
]);
const surveys = allSurveys.filter((survey) =>
canManage || isHrAudienceVisible(survey.audienceKind, survey.audienceRef, {
team: profile?.team ?? null,
locationId: profile?.locationId ?? null,
}),
);
const rows = await Promise.all(
surveys.map(async (s) => {
const submitted = await hasSubmitted(ctx.tenantId, s.id, ctx.userId, s.isAnonymous);
const canViewResults = canResults || s.resultVisibility === "everyone" || (s.resultVisibility === "participants" && submitted);
return {
id: s.id,
title: s.title,
status: s.status,
isAnonymous: s.isAnonymous,
hasSubmitted: submitted,
canViewResults,
participateHref: hrSurveyParticipatePath(tenantSlug, s.id),
resultsHref: hrSurveyResultsPath(tenantSlug, s.id),
};
}),
);
return Response.json({ title, vm: buildHrSurveyListVM({ rows, canManage, createHref }), canManage, statuses: ["open", "closed"], audienceOptions } satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadHrContext({ request, params, requireModule: true });
requireHrPermission(ctx, "hr.write");
const form = await request.formData();
const intent = form.get("intent")?.toString();
const surveyId = form.get("surveyId")?.toString() ?? "";
try {
if (intent === "create") {
const visibility = (form.get("resultVisibility")?.toString() ?? "admins") as HrSurveyResultVisibility;
const audienceKind = (form.get("audienceKind")?.toString() ?? "all") as HrAudienceKind;
await createSurvey({
tenantId: ctx.tenantId,
authorUserId: ctx.userId,
title: form.get("title")?.toString() ?? "",
description: form.get("description")?.toString() || null,
isAnonymous: form.get("isAnonymous") === "1",
resultVisibility: VISIBILITIES.includes(visibility) ? visibility : "admins",
audienceKind: AUDIENCES.includes(audienceKind) ? audienceKind : "all",
audienceRef: form.get("audienceRef")?.toString() || null,
});
return Response.json({ intent, ok: true, messageKey: "hr.surveys.toast.created" });
}
if (intent === "open" || intent === "close") {
await setSurveyStatus({ tenantId: ctx.tenantId, actorUserId: ctx.userId, surveyId, status: intent === "open" ? "open" : "closed" });
return Response.json({ intent, ok: true, messageKey: intent === "open" ? "hr.surveys.toast.opened" : "hr.surveys.toast.closed" });
}
if (intent === "archive") {
await archiveSurvey({ tenantId: ctx.tenantId, actorUserId: ctx.userId, surveyId });
return Response.json({ intent, ok: true, messageKey: "hr.surveys.toast.archived" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) throw error;
return hrActionErrorResponse(error);
}
};
export default function HrSurveysRoute() {
const { vm, canManage, audienceOptions } = useLoaderData<LoaderData>();
const fetcher = useFetcher();
useSaveToast(fetcher.data);
return (
<HrSurveysListPage
vm={vm}
canManage={canManage}
audienceOptions={audienceOptions}
submitting={fetcher.state !== "idle"}
actions={{
onCreate: ({ title, description, isAnonymous, resultVisibility, audienceKind, audienceRef }) =>
fetcher.submit({ intent: "create", title, description, isAnonymous: isAnonymous ? "1" : "0", resultVisibility, audienceKind, audienceRef }, { method: "post" }),
onSetStatus: (surveyId, status) => fetcher.submit({ intent: status, surveyId }, { method: "post" }),
onArchive: (surveyId) => fetcher.submit({ intent: "archive", surveyId }, { method: "post" }),
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: "hr" };