138 lines
6.7 KiB
TypeScript
138 lines
6.7 KiB
TypeScript
// 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 { 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 {
|
|
decideRequest,
|
|
listForApprover,
|
|
listOwnRequests,
|
|
listTemplates,
|
|
requestClarification,
|
|
submitRequest,
|
|
withdrawRequest,
|
|
type RequestTemplateRow,
|
|
} from "~/utils/integrations/hrRequestService.server";
|
|
import { hrRequestDetailPath, hrRequestsPath } from "~/utils/integrations/hrRoutePaths";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { HrRequestsPage, type HrRequestsTab } from "~/components/screens/hr/HrRequestsPage";
|
|
|
|
type TemplateOption = { id: string; title: string; requestKind: HrRequestKind };
|
|
type LoaderData = { title: string; tab: "own" | "approvals"; canApprove: boolean; ownVm: HrRequestOwnVM; approverVm: HrRequestApproverVM; templates: TemplateOption[] };
|
|
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: [] };
|
|
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 = await listOwnRequests(ctx.tenantId, ctx.userId);
|
|
const ownVm = buildHrRequestOwnVM({
|
|
rows: own.map((r) => ({ id: r.id, title: r.title, kind: r.requestKind, status: r.status, createdIso: r.createdAt.toISOString(), detailHref: hrRequestDetailPath(tenantSlug, r.id) })),
|
|
newHref: hrRequestsPath(tenantSlug),
|
|
});
|
|
|
|
const templates: RequestTemplateRow[] = await listTemplates(ctx.tenantId);
|
|
const templateOptions: TemplateOption[] = templates.filter((tpl) => tpl.isActive).map((tpl) => ({ id: tpl.id, title: tpl.title, requestKind: tpl.requestKind }));
|
|
|
|
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 ?? r.employeeUserId, kind: r.requestKind, status: r.status, createdIso: r.createdAt.toISOString(), detailHref: hrRequestDetailPath(tenantSlug, r.id) })),
|
|
});
|
|
}
|
|
|
|
return Response.json({ title, tab, canApprove, ownVm, approverVm, templates: templateOptions } 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 kind = (form.get("requestKind")?.toString() ?? "expense") as HrRequestKind;
|
|
await submitRequest({
|
|
tenantId: ctx.tenantId,
|
|
employeeUserId: ctx.userId,
|
|
templateId: form.get("templateId")?.toString() || null,
|
|
requestKind: KINDS.includes(kind) ? kind : "expense",
|
|
title: form.get("title")?.toString() ?? "",
|
|
details: form.get("details")?.toString() ?? null,
|
|
assignedApproverUserId: form.get("approverUserId")?.toString() || null,
|
|
});
|
|
return Response.json({ ok: true });
|
|
}
|
|
if (intent === "withdraw") {
|
|
await withdrawRequest({ tenantId: ctx.tenantId, requestId, employeeUserId: ctx.userId });
|
|
return Response.json({ ok: true });
|
|
}
|
|
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({ ok: true });
|
|
}
|
|
if (intent === "clarify") {
|
|
await requestClarification({ tenantId: ctx.tenantId, requestId, deciderUserId: ctx.userId, canApproveAny, question: form.get("question")?.toString() ?? "" });
|
|
return Response.json({ ok: true });
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) throw error;
|
|
return hrActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function HrRequestsRoute() {
|
|
const { tab, canApprove, ownVm, approverVm, templates } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher();
|
|
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
|
|
return (
|
|
<HrRequestsPage
|
|
tab={tab}
|
|
canApprove={canApprove}
|
|
ownVm={ownVm}
|
|
approverVm={approverVm}
|
|
templates={templates}
|
|
kinds={KINDS}
|
|
tabHref={(next: HrRequestsTab) => `?tab=${next}`}
|
|
submitting={fetcher.state !== "idle"}
|
|
actions={{
|
|
onSubmit: ({ templateId, requestKind, approverUserId, title, details }) =>
|
|
submit({ intent: "submit", templateId, requestKind, approverUserId, title, details }),
|
|
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" };
|