216 lines
8.7 KiB
TypeScript
216 lines
8.7 KiB
TypeScript
// 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 { 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 {
|
|
approveRequest,
|
|
countOverlappingApproved,
|
|
listApprovedAbsencesForRange,
|
|
listForApprover,
|
|
listOwnVacationRequests,
|
|
rejectRequest,
|
|
replyToClarification,
|
|
requestClarification,
|
|
submitVacationRequest,
|
|
withdrawRequest,
|
|
type HrLeaveRequestStatus,
|
|
} from "~/utils/integrations/hrLeaveService.server";
|
|
import { hrLeaveDetailPath, hrLeavePath } from "~/utils/integrations/hrRoutePaths";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { HrLeavePage, type HrLeaveTab } from "~/components/screens/hr/HrLeavePage";
|
|
|
|
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[];
|
|
};
|
|
|
|
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,
|
|
};
|
|
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 = await listOwnVacationRequests(ctx.tenantId, ctx.userId);
|
|
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: hrLeaveDetailPath(tenantSlug, row.id),
|
|
})),
|
|
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 ?? row.employeeUserId,
|
|
kind: row.requestKind,
|
|
status: row.status as Exclude<HrLeaveRequestStatus, never>,
|
|
startDateIso: dateIso(row.startDate),
|
|
endDateIso: dateIso(row.endDate),
|
|
note: row.note,
|
|
conflictCount,
|
|
detailHref: hrLeaveDetailPath(tenantSlug, row.id),
|
|
});
|
|
}
|
|
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 listApprovedAbsencesForRange(ctx.tenantId, from, to);
|
|
const labels = await resolveUserLabels(absences.map((a) => a.employeeUserId));
|
|
team = absences.map((a) => ({ id: a.id, employeeLabel: labels.get(a.employeeUserId)?.label ?? a.employeeUserId, 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 } 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 kind = (form.get("requestKind")?.toString() ?? "vacation") as HrVacationRequestKind;
|
|
const start = form.get("startDate")?.toString() ?? "";
|
|
const end = form.get("endDate")?.toString() ?? "";
|
|
if (!start || !end) throw badRequestResponse();
|
|
await submitVacationRequest({
|
|
tenantId: ctx.tenantId,
|
|
employeeUserId: ctx.userId,
|
|
requestKind: KINDS.includes(kind) ? kind : "vacation",
|
|
startDate: new Date(start),
|
|
endDate: new Date(end),
|
|
note: form.get("note")?.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 === "reply") {
|
|
await replyToClarification({ tenantId: ctx.tenantId, requestId, employeeUserId: ctx.userId, reply: form.get("reply")?.toString() ?? "" });
|
|
return Response.json({ ok: true });
|
|
}
|
|
if (intent === "approve") {
|
|
await approveRequest({ tenantId: ctx.tenantId, requestId, deciderUserId: ctx.userId, canApproveAny, decisionNote: form.get("note")?.toString() ?? null });
|
|
return Response.json({ ok: true });
|
|
}
|
|
if (intent === "reject") {
|
|
await rejectRequest({ tenantId: ctx.tenantId, requestId, deciderUserId: ctx.userId, canApproveAny, 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 HrLeaveRoute() {
|
|
const { tab, canApprove, ownVm, approverVm, team, kinds } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher();
|
|
const submit = (values: Record<string, string>) => fetcher.submit(values, { method: "post" });
|
|
return (
|
|
<HrLeavePage
|
|
tab={tab}
|
|
canApprove={canApprove}
|
|
ownVm={ownVm}
|
|
approverVm={approverVm}
|
|
team={team}
|
|
kinds={kinds}
|
|
tabHref={(next: HrLeaveTab) => `?tab=${next}`}
|
|
submitting={fetcher.state !== "idle"}
|
|
actions={{
|
|
onSubmit: ({ requestKind, approverUserId, startDate, endDate, note }) =>
|
|
submit({ intent: "submit", requestKind, approverUserId, startDate, endDate, note }),
|
|
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" };
|