import { useActionData, useFetcher, useLoaderData, useLocation, useNavigate, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs, } from "react-router"; import { fromZonedTime } from "date-fns-tz"; import { addDaysIso, buildPlantafelVM, parsePlantafelSort, startOfWeekIso, type PlantafelSort } from "@hivegrid/view-models"; import { APP_TIME_ZONE } from "~/locale/format"; import { applyOfflineMutation, bulkReassignScheduleEntries, listEditablePlantafelProjectOptions, loadPlantafel, updateScheduleEntryStatus, upsertScheduleEntry, type PlantafelVM, type ScheduleEntryStatus, } from "~/utils/integrations/projects/plantafelAcceptanceService.server"; import { loadProjectContext, projectActionErrorResponse, projectNotFoundResponse, requireProjectPermission, requireProjectView, } from "~/utils/integrations/projects/projectAccess.server"; import { listAssignableUsers, resolveUserLabels } from "~/utils/integrations/crm/crmService.server"; import { PlantafelPage, type PlantafelOption, type PlantafelViewMode } from "~/components/screens/projects/PlantafelPage"; import { useSaveToast } from "~/hooks/use-save-toast"; type LoaderData = { plantafel: PlantafelVM; projectLabels: PlantafelOption[]; editableProjectIds: string[]; projectOptions: PlantafelOption[]; projectOptionsHasMore: boolean; assigneeOptions: PlantafelOption[]; canWrite: boolean; canBulkReassign: boolean; filter: { assignedUserId: string | null; includePast: boolean; sort: PlantafelSort }; view: PlantafelViewMode; anchorIso: string; todayIso: string; }; type ProjectPickerLoaderData = { resource: "projectPicker"; projectOptions: PlantafelOption[]; projectOptionsHasMore: boolean; projectQuery: string; }; type PlantafelActionData = { intent: string | null; ok?: boolean; error?: string; }; function formString(formData: FormData, name: string): string | null { const value = formData.get(name); return typeof value === "string" ? value : null; } function parseJsonObject(value: string | null): Record { if (!value) return {}; const parsed = JSON.parse(value) as unknown; return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? (parsed as Record) : {}; } function parseEntryIds(formData: FormData): string[] { const raw = formString(formData, "entryIds"); if (!raw) return []; const parsed = JSON.parse(raw) as unknown; return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : []; } function dateParam(url: URL, name: string, fallback: Date): Date { const value = url.searchParams.get(name); const parsed = value ? new Date(value) : fallback; return Number.isNaN(parsed.getTime()) ? fallback : parsed; } const DATE_ISO_RE = /^\d{4}-\d{2}-\d{2}$/u; /** How far back the table reaches once past appointments are switched on. */ const PLANTAFEL_PAST_WINDOW_DAYS = 21; /** Today as `YYYY-MM-DD` in the fixed app time zone, so server and client agree on the cells. */ function todayIsoInAppTz(now: Date): string { return new Intl.DateTimeFormat("en-CA", { timeZone: APP_TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(now); } /** Local midnight of a calendar date in the app time zone, as an absolute instant. */ function startOfDayInAppTz(dateIso: string): Date { return fromZonedTime(`${dateIso}T00:00:00`, APP_TIME_ZONE); } export async function loader({ request, params }: LoaderFunctionArgs) { const ctx = await requireProjectView({ request, params }, ["plantafel.read_all", "plantafel.read_own"]); const url = new URL(request.url); const now = new Date(); // `range=today` narrows the table window to the current day; without it the // table shows the next 7 days. The quick-range buttons are gone from the // toolbar (search + monteur picker took their place), but the parameter stays // part of the URL contract - the mobile Monteur "today" view is a tracked // design-nachzug and links pointing at it must keep working. const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Past appointments are hidden by default - the plantafel is a planning // board, not an archive. The toggle widens the window backwards; the service // caps a range at 31 days, so three weeks back plus the seven ahead stays // safely inside it even across a DST change. const includePast = url.searchParams.get("past") === "1"; const pastWindowStart = new Date(startOfToday.getTime() - PLANTAFEL_PAST_WINDOW_DAYS * 24 * 60 * 60 * 1000); // Calendar view renders a fixed Monday-Sunday week, so it resolves its own // window from the anchor instead of the quick ranges above. const view: PlantafelViewMode = url.searchParams.get("view") === "calendar" ? "calendar" : "table"; const todayIso = todayIsoInAppTz(now); const anchorParam = url.searchParams.get("anchor"); const anchorIso = anchorParam && DATE_ISO_RE.test(anchorParam) ? anchorParam : todayIso; const weekStartIso = startOfWeekIso(anchorIso); const from = view === "calendar" ? startOfDayInAppTz(weekStartIso) : url.searchParams.get("range") === "today" ? startOfToday : dateParam(url, "from", includePast ? pastWindowStart : startOfToday); const to = view === "calendar" ? startOfDayInAppTz(addDaysIso(weekStartIso, 7)) : url.searchParams.get("range") === "today" ? new Date(startOfToday.getTime() + 24 * 60 * 60 * 1000) : // The window always reaches the same seven days ahead - switching the // past on extends it backwards, it must not drag the end back too. dateParam(url, "to", new Date(startOfToday.getTime() + 7 * 24 * 60 * 60 * 1000)); // Whose appointments to show. A user without plantafel.read_all is pinned to // their own rows by the service, no matter what this parameter says. const assignedUserId = url.searchParams.get("assignedUserId"); // Row order for the table. Narrowed here so an unknown value falls back to // the chronological default instead of reaching the component. const sort = parsePlantafelSort(url.searchParams.get("sort")); const canWrite = ctx.permissions.includes("plantafel.write"); const canReadAll = ctx.permissions.includes("plantafel.read_all"); const canBulkReassign = ctx.permissions.includes("plantafel.bulk_reassign"); if (url.searchParams.get("_resource") === "projectPicker") { if (!canWrite) throw projectNotFoundResponse(); const picker = await listEditablePlantafelProjectOptions({ tenantId: ctx.tenantId, ctx, query: url.searchParams.get("projectQuery"), }); return Response.json({ resource: "projectPicker", projectOptions: picker.options, projectOptionsHasMore: picker.hasMore, projectQuery: picker.query, } satisfies ProjectPickerLoaderData); } const assigneeOptionsPromise = canWrite || canReadAll ? listAssignableUsers(ctx.tenantId) : resolveUserLabels([ctx.userId]).then((labels) => { const label = labels.get(ctx.userId); return label ? [{ id: ctx.userId, label }] : []; }); const projectOptionsPromise = canWrite ? listEditablePlantafelProjectOptions({ tenantId: ctx.tenantId, ctx }) : Promise.resolve({ options: [], hasMore: false, query: "" }); const [plantafel, projectPicker, assigneeOptions] = await Promise.all([ loadPlantafel({ tenantId: ctx.tenantId, ctx, from, to, assignedUserId, }), projectOptionsPromise, assigneeOptionsPromise, ]); return Response.json({ plantafel, projectLabels: plantafel.projectLabels, editableProjectIds: plantafel.editableProjectIds, projectOptions: projectPicker.options, projectOptionsHasMore: projectPicker.hasMore, assigneeOptions, canWrite, canBulkReassign, filter: { assignedUserId, includePast, sort }, view, anchorIso, todayIso, } satisfies LoaderData); } export async function action({ request, params }: ActionFunctionArgs) { const ctx = await loadProjectContext({ request, params, requireModule: true }); const formData = await request.formData(); const intent = formString(formData, "_action"); try { if (intent === "upsertSchedule") { requireProjectPermission(ctx, "plantafel.write"); const result = await upsertScheduleEntry({ tenantId: ctx.tenantId, ctx, entryId: formString(formData, "entryId"), projektId: formString(formData, "projektId") ?? "", assignedUserId: formString(formData, "assignedUserId") ?? "", title: formString(formData, "title") ?? "", startAt: formString(formData, "startAt") ?? "", endAt: formString(formData, "endAt") ?? "", status: (formString(formData, "status") as ScheduleEntryStatus | null) ?? "planned", calendarEventId: formString(formData, "calendarEventId"), conflictOverrideReason: formString(formData, "conflictOverrideReason"), clientMutationId: formString(formData, "clientMutationId"), }); return Response.json({ ok: true, intent, ...result }); } if (intent === "updateStatus") { requireProjectPermission(ctx, "plantafel.write"); const entry = await updateScheduleEntryStatus({ tenantId: ctx.tenantId, ctx, entryId: formString(formData, "entryId") ?? "", status: (formString(formData, "status") as ScheduleEntryStatus | null) ?? "planned", clientMutationId: formString(formData, "clientMutationId"), }); return Response.json({ ok: true, intent, entry }); } if (intent === "bulkReassign") { requireProjectPermission(ctx, "plantafel.bulk_reassign"); const result = await bulkReassignScheduleEntries({ tenantId: ctx.tenantId, ctx, entryIds: parseEntryIds(formData), assignedUserId: formString(formData, "assignedUserId") ?? "", conflictOverrideReason: formString(formData, "conflictOverrideReason"), }); return Response.json({ ok: true, intent, ...result }); } if (intent === "offlineSync") { const result = await applyOfflineMutation({ tenantId: ctx.tenantId, ctx, clientMutationId: formString(formData, "clientMutationId") ?? "", operation: formString(formData, "operation"), payload: parseJsonObject(formString(formData, "payload")), }); return Response.json({ ok: true, intent, ...result }); } return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 }); } catch (error) { const response = projectActionErrorResponse(error); const payload = (await response.json()) as Record; return Response.json({ ...payload, intent }, { status: response.status }); } } export default function PlantafelRoute() { const data = useLoaderData(); const actionData = useActionData(); const projectPicker = useFetcher(); const location = useLocation(); const navigate = useNavigate(); const navigation = useNavigation(); const submit = useSubmit(); const vm = buildPlantafelVM(data.plantafel); // Every write here answers with `{ ok }` or an error key, so the confirmation // follows the server's verdict rather than the click. `offlineSync` stays out: // it reports its outcome in the card it runs from, and a toast would say the // same thing twice. useSaveToast(actionData, { intents: ["upsertSchedule", "updateStatus", "bulkReassign"] }); return ( { const fd = new FormData(); fd.set("_action", intent); for (const [key, value] of Object.entries(fields ?? {})) fd.set(key, value); submit(fd, { method: "post" }); }, onProjectSearch: (query) => { const search = new URLSearchParams(location.search); search.set("_resource", "projectPicker"); search.set("projectQuery", query); projectPicker.load(`${location.pathname}?${search.toString()}`); }, onFilterChange: (next) => { const search = new URLSearchParams(location.search); if (next.assignedUserId) search.set("assignedUserId", next.assignedUserId); else search.delete("assignedUserId"); if (next.includePast) search.set("past", "1"); else search.delete("past"); if (next.sort !== "start_asc") search.set("sort", next.sort); else search.delete("sort"); const query = search.toString(); void navigate(`${location.pathname}${query ? `?${query}` : ""}`); }, onViewChange: (next) => { const search = new URLSearchParams(location.search); // The table's quick ranges and the week's anchor describe different // windows - drop the other view's window parameters on the switch. search.delete("from"); search.delete("to"); if (next === "calendar") { search.set("view", "calendar"); search.delete("range"); } else { search.delete("view"); search.delete("anchor"); } void navigate(`${location.pathname}?${search.toString()}`); }, onAnchorChange: (anchorIso) => { const search = new URLSearchParams(location.search); search.set("view", "calendar"); search.set("anchor", anchorIso); void navigate(`${location.pathname}?${search.toString()}`); }, }} /> ); }