Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+246
-50
@@ -1,18 +1,65 @@
|
||||
import { Form, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
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 OfflineSyncOperation,
|
||||
type PlantafelVM,
|
||||
type ScheduleEntryStatus,
|
||||
} from "~/utils/integrations/projects/plantafelAcceptanceService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireAnyProjectPermission, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.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 };
|
||||
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);
|
||||
@@ -38,14 +85,115 @@ function dateParam(url: URL, name: string, fallback: Date): Date {
|
||||
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 = requireAnyProjectPermission(await loadProjectContext({ request, params, requireModule: true }), ["plantafel.read_all", "plantafel.read_own"]);
|
||||
const ctx = await requireProjectView({ request, params }, ["plantafel.read_all", "plantafel.read_own"]);
|
||||
const url = new URL(request.url);
|
||||
const now = new Date();
|
||||
const from = dateParam(url, "from", new Date(now.getFullYear(), now.getMonth(), now.getDate()));
|
||||
const to = dateParam(url, "to", new Date(from.getTime() + 7 * 24 * 60 * 60 * 1000));
|
||||
const plantafel = await loadPlantafel({ tenantId: ctx.tenantId, ctx, from, to, assignedUserId: url.searchParams.get("assignedUserId") });
|
||||
return Response.json({ plantafel } satisfies LoaderData);
|
||||
// `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) {
|
||||
@@ -57,7 +205,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
requireProjectPermission(ctx, "plantafel.write");
|
||||
const result = await upsertScheduleEntry({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
entryId: formString(formData, "entryId"),
|
||||
projektId: formString(formData, "projektId") ?? "",
|
||||
assignedUserId: formString(formData, "assignedUserId") ?? "",
|
||||
@@ -69,78 +217,126 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
conflictOverrideReason: formString(formData, "conflictOverrideReason"),
|
||||
clientMutationId: formString(formData, "clientMutationId"),
|
||||
});
|
||||
return Response.json({ ok: true, ...result });
|
||||
return Response.json({ ok: true, intent, ...result });
|
||||
}
|
||||
if (intent === "updateStatus") {
|
||||
requireProjectPermission(ctx, "plantafel.write");
|
||||
const entry = await updateScheduleEntryStatus({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
entryId: formString(formData, "entryId") ?? "",
|
||||
status: (formString(formData, "status") as ScheduleEntryStatus | null) ?? "planned",
|
||||
clientMutationId: formString(formData, "clientMutationId"),
|
||||
});
|
||||
return Response.json({ ok: true, entry });
|
||||
return Response.json({ ok: true, intent, entry });
|
||||
}
|
||||
if (intent === "bulkReassign") {
|
||||
requireProjectPermission(ctx, "plantafel.bulk_reassign");
|
||||
const result = await bulkReassignScheduleEntries({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
entryIds: parseEntryIds(formData),
|
||||
assignedUserId: formString(formData, "assignedUserId") ?? "",
|
||||
conflictOverrideReason: formString(formData, "conflictOverrideReason"),
|
||||
});
|
||||
return Response.json({ ok: true, ...result });
|
||||
return Response.json({ ok: true, intent, ...result });
|
||||
}
|
||||
if (intent === "offlineSync") {
|
||||
requireAnyProjectPermission(ctx, ["plantafel.write", "acceptance.write"]);
|
||||
const result = await applyOfflineMutation({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
clientMutationId: formString(formData, "clientMutationId") ?? "",
|
||||
operation: formString(formData, "operation") as OfflineSyncOperation,
|
||||
operation: formString(formData, "operation"),
|
||||
payload: parseJsonObject(formString(formData, "payload")),
|
||||
});
|
||||
return Response.json({ ok: true, ...result });
|
||||
return Response.json({ ok: true, intent, ...result });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
const response = projectActionErrorResponse(error);
|
||||
const payload = (await response.json()) as Record<string, unknown>;
|
||||
return Response.json({ ...payload, intent }, { status: response.status });
|
||||
}
|
||||
}
|
||||
|
||||
export default function PlantafelRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<PlantafelActionData>();
|
||||
const projectPicker = useFetcher<ProjectPickerLoaderData>();
|
||||
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 (
|
||||
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("projects.plantafel.title")}</h1>
|
||||
</header>
|
||||
<section className="grid gap-3">
|
||||
{data.plantafel.entries.map((entry) => (
|
||||
<article key={entry.id} className="rounded-md border bg-background p-4">
|
||||
<h2 className="font-semibold">{entry.title}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{entry.assignedUserId} · {entry.status}
|
||||
</p>
|
||||
{entry.conflicts && entry.conflicts.length > 0 ? <p className="text-sm text-destructive">{t("projects.plantafel.conflicts", { count: entry.conflicts.length })}</p> : null}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<Form className="grid gap-3 rounded-md border bg-background p-4" method="post">
|
||||
<input type="hidden" name="_action" value="upsertSchedule" />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="projektId" placeholder={t("projects.fields.projectId")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="assignedUserId" placeholder={t("projects.fields.assignedUserId")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="title" placeholder={t("projects.fields.scheduleTitle")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="startAt" type="datetime-local" />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="endAt" type="datetime-local" />
|
||||
<button className="rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground" type="submit">
|
||||
{t("projects.actions.saveScheduleEntry")}
|
||||
</button>
|
||||
</Form>
|
||||
</main>
|
||||
<PlantafelPage
|
||||
vm={vm}
|
||||
projectLabels={data.projectLabels}
|
||||
editableProjectIds={data.editableProjectIds}
|
||||
projectOptions={projectPicker.data?.resource === "projectPicker" ? projectPicker.data.projectOptions : data.projectOptions}
|
||||
projectOptionsHasMore={projectPicker.data?.resource === "projectPicker" ? projectPicker.data.projectOptionsHasMore : data.projectOptionsHasMore}
|
||||
projectPickerLoading={projectPicker.state !== "idle"}
|
||||
assigneeOptions={data.assigneeOptions}
|
||||
canWrite={data.canWrite}
|
||||
canBulkReassign={data.canBulkReassign}
|
||||
filter={data.filter}
|
||||
view={data.view}
|
||||
anchorIso={data.anchorIso}
|
||||
todayIso={data.todayIso}
|
||||
submitting={navigation.state !== "idle"}
|
||||
actionResult={actionData ?? null}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
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()}`);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user