114 lines
5.5 KiB
TypeScript
114 lines
5.5 KiB
TypeScript
// P17 HR-Hub workflows (AK-P17b) — payslip administration. Bulk auto-match: the
|
|
// admin pastes "fileId,fileName" lines + a period; the pure matchPayslipFile
|
|
// classifies each (hard/soft/none, color confidence); the admin confirms per
|
|
// row. Needs hr.write. Transitional UI.
|
|
|
|
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 { resolveUserLabels } from "~/utils/integrations/hrService.server";
|
|
import { adminListPayslips, createPayslip, listEmployeesForMatch } from "~/utils/integrations/hrPayslipService.server";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { HrAdminPayslipsPage } from "~/components/screens/hr/HrAdminPayslipsPage";
|
|
|
|
type PreviewRow = HrPayslipMatchInputRow & { confidenceKey: string; confidenceTone: string };
|
|
type AdminRow = { id: string; employeeLabel: string; periodLabel: string; isRead: boolean };
|
|
type LoaderData = { title: string; rows: AdminRow[] };
|
|
type ActionData = { preview?: PreviewRow[]; periodYear?: number; periodMonth?: number; created?: number };
|
|
|
|
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: [] } satisfies LoaderData);
|
|
try {
|
|
requireHrPermission(ctx, "hr.write");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const payslips = await adminListPayslips(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 ?? p.employeeUserId,
|
|
periodLabel: `${p.periodYear}-${String(p.periodMonth).padStart(2, "0")}`,
|
|
isRead: p.isRead,
|
|
}));
|
|
return Response.json({ title, rows } 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 lines = (form.get("files")?.toString() ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
|
|
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[] = lines.map((line) => {
|
|
const [fileId, ...rest] = line.split(",");
|
|
const fileName = rest.join(",").trim() || fileId.trim();
|
|
const result = matchPayslipFile(fileName, employees);
|
|
return {
|
|
fileId: fileId.trim(),
|
|
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({ preview, periodYear, periodMonth } satisfies ActionData);
|
|
}
|
|
if (intent === "confirm-one") {
|
|
await createPayslip({
|
|
tenantId: ctx.tenantId,
|
|
employeeUserId: form.get("employeeUserId")?.toString() ?? "",
|
|
uploadedByUserId: ctx.userId,
|
|
periodYear: Number(form.get("periodYear")),
|
|
periodMonth: Number(form.get("periodMonth")),
|
|
fileId: form.get("fileId")?.toString() ?? "",
|
|
});
|
|
return Response.json({ created: 1 } satisfies ActionData);
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) throw error;
|
|
return hrActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function HrAdminPayslipsRoute() {
|
|
const { rows } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher<ActionData>();
|
|
const preview = fetcher.data?.preview ?? [];
|
|
const period = { year: String(fetcher.data?.periodYear ?? ""), month: String(fetcher.data?.periodMonth ?? "") };
|
|
return (
|
|
<HrAdminPayslipsPage
|
|
rows={rows}
|
|
preview={preview}
|
|
period={period}
|
|
submitting={fetcher.state !== "idle"}
|
|
actions={{
|
|
onMatch: ({ periodYear, periodMonth, files }) => fetcher.submit({ intent: "match", periodYear, periodMonth, files }, { method: "post" }),
|
|
onConfirm: ({ fileId, employeeUserId, periodYear, periodMonth }) =>
|
|
fetcher.submit({ intent: "confirm-one", fileId, employeeUserId, periodYear, periodMonth }, { method: "post" }),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: "hr" };
|