Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+178
@@ -0,0 +1,178 @@
|
||||
// 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, createDocument, listEmployeeDocuments } from "~/utils/integrations/hrService.server";
|
||||
import { createFileFromBytes } 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";
|
||||
|
||||
type LoaderData = { title: string; vm: HrDocumentListVM; tenantSlug: string };
|
||||
type UploadActionData = { ok?: boolean; 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({ ok: true });
|
||||
}
|
||||
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({ error: "hr.documents.upload.error.generic" } satisfies UploadActionData, { status: 400 });
|
||||
}
|
||||
if (fileEntry.size > HR_DOC_MAX_BYTES) {
|
||||
return Response.json({ 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,
|
||||
});
|
||||
await createDocument({
|
||||
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,
|
||||
});
|
||||
return Response.json({ ok: true } satisfies UploadActionData);
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof StorageScanRejectedError) {
|
||||
return Response.json({ 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>();
|
||||
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 />;
|
||||
}
|
||||
Reference in new issue
Block a user