// P4 Tasks (AK-P4b) ยง6 โ€” Tasks browser route. Loader builds the TaskListVM once // (server-side); the component only renders (DoD A). Module off -> locked empty // state. Missing tasks.read_own -> 404. Presets (mine/created/all) + server-side // filters. The list shape is the reusable component (DoD 8); this route is its // standalone host. // // Interim-UI (AD-28): renders the ~/ui preview screen TasksListPage; the loader // owns navigation for preset/filter changes (server-side) and provides the assignee // options for the "Neue Aufgabe" dialog (which posts to the tasks/new action). Final // Subframe optics land as a tracked design-nachzug once David's D-P4 delta ships. import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData, useNavigate, useSubmit } from "react-router"; import { buildTaskListVM, taskEntityLabelKey, taskPriorityKey, taskSourceKey, taskStatusKey, type TaskListRow, type TaskListVM, } from "@hivegrid/view-models"; import { getTranslations } from "~/locale/i18next.server"; import { badRequestResponse, loadTasksContext, notFoundResponse, requireTasksPermission } from "~/utils/integrations/taskAccess.server"; import { listAssignableGroups, listAssignableUsers, listTasksForBrowser, resolveGroupLabels, resolveUserLabels, updateTask, type LabeledOption, type TaskPriority, type TaskRow, type TaskStatus, } from "~/utils/integrations/taskService.server"; import { auditTaskEvent } from "~/utils/integrations/taskAudit.server"; import { tasksDetailPath, tasksListPath, tasksNewPath } from "~/utils/integrations/taskRoutePaths"; import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server"; import { TasksListPage, type TaskListQuery } from "~/components/screens/tasks/TasksListPage"; import ServerError from "~/components/ui/errors/ServerError"; type LoaderData = { title: string; vm: TaskListVM; includeDemoData: boolean; demoDataUiEnabled: boolean; nextHref: string | null; // Assignee picker options for the "Neue Aufgabe" dialog โ€” only loaded for writers. assignableUsers: LabeledOption[]; assignableGroups: LabeledOption[]; }; const TASK_STATUSES: readonly TaskStatus[] = ["open", "in_progress", "blocked", "done", "cancelled"]; const TASK_PRIORITIES: readonly TaskPriority[] = ["low", "normal", "high", "urgent"]; const TERMINAL: ReadonlySet = new Set(["done", "cancelled"]); /** Cap the needle so a pasted wall of text cannot turn into a pathological LIKE. */ const MAX_SEARCH_LENGTH = 120; /** Free-text needle from the URL; empty/whitespace-only means "no search". */ function parseSearch(value: string | null): string | null { const needle = (value ?? "").trim(); return needle ? needle.slice(0, MAX_SEARCH_LENGTH) : null; } export const loader = async ({ request, params }: LoaderFunctionArgs) => { const { t } = await getTranslations(request); const ctx = await loadTasksContext({ request, params }); const tenantSlug = params.tenant ?? ""; const url = new URL(request.url); // Outside staging/dev the `demo=show` query param is ignored server-side โ€” // hiding the checkbox alone would leave demo rows reachable via URL. const demoDataUiEnabled = isDemoDataUiEnabled(undefined, { tenantId: ctx.tenantId, tenantSlug }); const includeDemoData = demoDataUiEnabled && url.searchParams.get("demo") === "show"; const emptyFilter = { search: null, status: null, priority: null, assignedToUserId: null, includeArchived: false }; if (!ctx.hasModule) { const vm = buildTaskListVM({ rows: [], filter: emptyFilter, canWrite: false, canDelete: false, createHref: tasksNewPath(tenantSlug) }); return Response.json({ title: `${t("tasks.list.title")} | ${process.env.APP_NAME}`, vm, includeDemoData, demoDataUiEnabled, nextHref: null, assignableUsers: [], assignableGroups: [], } satisfies LoaderData); } try { requireTasksPermission(ctx, "tasks.read_own"); } catch { throw notFoundResponse(); } const search = parseSearch(url.searchParams.get("q")); const status = (url.searchParams.get("status") as TaskStatus | null) || null; const priority = (url.searchParams.get("priority") as TaskPriority | null) || null; const includeArchived = url.searchParams.get("archived") === "1"; const cursor = url.searchParams.get("cursor"); const { rows, nextCursor } = await listTasksForBrowser({ tenantId: ctx.tenantId, ctx, filter: { search, status, priority, includeArchived, includeDemoData }, cursor, }); // Batch-resolve assignee display names for the page. const [userLabels, groupLabels] = await Promise.all([ resolveUserLabels(rows.map((row) => row.assignedToUserId).filter((id): id is string => Boolean(id))), resolveGroupLabels( ctx.tenantId, rows.map((row) => row.assignedToGroupId).filter((id): id is string => Boolean(id)) ), ]); const now = Date.now(); const listRows: TaskListRow[] = rows.map((task) => toTaskListRow(task, { tenantSlug, userLabels, groupLabels, now })); const canWrite = ctx.permissions.includes("tasks.write"); const canDelete = ctx.permissions.includes("tasks.delete"); // The create dialog lives on the list; readers never see it, so skip the queries. const [assignableUsers, assignableGroups] = canWrite ? await Promise.all([listAssignableUsers(ctx.tenantId), listAssignableGroups(ctx.tenantId)]) : [[] as LabeledOption[], [] as LabeledOption[]]; const vm = buildTaskListVM({ rows: listRows, filter: { search, status, priority, assignedToUserId: null, includeArchived }, canWrite, canDelete, createHref: tasksNewPath(tenantSlug), nextCursor, }); // Preserve the active search/filter when paging via cursor. const nextParams = new URLSearchParams(); if (search) nextParams.set("q", search); if (status) nextParams.set("status", status); if (priority) nextParams.set("priority", priority); if (includeArchived) nextParams.set("archived", "1"); if (includeDemoData) nextParams.set("demo", "show"); if (nextCursor) nextParams.set("cursor", nextCursor); const nextHref = nextCursor ? `?${nextParams.toString()}` : null; return Response.json({ title: `${t("tasks.list.title")} | ${process.env.APP_NAME}`, vm, includeDemoData, demoDataUiEnabled, nextHref, assignableUsers, assignableGroups, } satisfies LoaderData); }; /** * Inline status/priority changes from the table (same affordance the lead inbox * has): the badge is the edit control, picking a value POSTs here and the list * reloads with the value stored. Permission + tenant visibility are enforced by * updateTask, which runs inside withTenantRLS. */ export const action = async ({ request, params }: ActionFunctionArgs) => { const ctx = await loadTasksContext({ request, params, requireModule: true }); const tenantSlug = params.tenant ?? ""; const formData = await request.formData(); const intent = String(formData.get("intent") ?? ""); const taskId = String(formData.get("taskId") ?? "").trim(); try { requireTasksPermission(ctx, "tasks.write"); if (!taskId) throw badRequestResponse(); if (intent === "setStatus") { const status = String(formData.get("status") ?? ""); if (!TASK_STATUSES.includes(status as TaskStatus)) throw badRequestResponse(); await updateTask({ tenantId: ctx.tenantId, taskId, ctx, status: status as TaskStatus }); await auditTaskEvent({ ctx, action: "task.updated", taskId, metadata: { status } }); } else if (intent === "setPriority") { const priority = String(formData.get("priority") ?? ""); if (!TASK_PRIORITIES.includes(priority as TaskPriority)) throw badRequestResponse(); await updateTask({ tenantId: ctx.tenantId, taskId, ctx, priority: priority as TaskPriority }); await auditTaskEvent({ ctx, action: "task.updated", taskId, metadata: { priority } }); } else { throw badRequestResponse(); } } catch (error) { if (error instanceof Response) throw error; throw notFoundResponse(); } // Keep the active preset/filter/page: the POST goes to the current URL. const search = new URL(request.url).searchParams; search.set("toast", intent === "setStatus" ? "tasks.toast.statusChanged" : "tasks.toast.priorityChanged"); return redirect(`${tasksListPath(tenantSlug)}?${search.toString()}`); }; /** Map a domain TaskRow to the routing-resolved TaskListRow (shared by embeds). */ export function toTaskListRow( task: TaskRow, deps: { tenantSlug: string; userLabels: Map; groupLabels: Map; now: number } ): TaskListRow { const assignee = task.assignedToUserId ? { kind: "user" as const, label: deps.userLabels.get(task.assignedToUserId) ?? task.assignedToUserId } : task.assignedToGroupId ? { kind: "group" as const, label: deps.groupLabels.get(task.assignedToGroupId) ?? task.assignedToGroupId } : null; return { id: task.id, title: task.title, status: task.status, statusKey: taskStatusKey(task.status), priority: task.priority, priorityKey: taskPriorityKey(task.priority), deadlineIso: task.deadline ? task.deadline.toISOString() : null, isOverdue: Boolean(task.deadline && task.deadline.getTime() < deps.now && !TERMINAL.has(task.status)), assignee, linkedEntity: task.linkedEntityType && task.linkedEntityId ? { entityType: task.linkedEntityType, entityId: task.linkedEntityId, labelKey: taskEntityLabelKey(task.linkedEntityType) } : null, source: task.source, sourceKey: taskSourceKey(task.source), sourceHref: null, detailHref: tasksDetailPath(deps.tenantSlug, task.id), }; } export default function TasksBrowserRoute() { const { vm, includeDemoData, demoDataUiEnabled, nextHref, assignableUsers, assignableGroups } = useLoaderData(); const navigate = useNavigate(); const submit = useSubmit(); const canWrite = vm.status === "ready" && Boolean(vm.data?.canWrite); function postField(taskId: string, intent: "setStatus" | "setPriority", field: "status" | "priority", value: string) { const form = new FormData(); form.set("intent", intent); form.set("taskId", taskId); form.set(field, value); void submit(form, { method: "post" }); } function onApply(query: TaskListQuery) { const params = new URLSearchParams(); if (query.search) params.set("q", query.search); if (query.status) params.set("status", query.status); if (query.priority) params.set("priority", query.priority); if (query.includeArchived) params.set("archived", "1"); if (query.includeDemoData) params.set("demo", "show"); // Reset cursor pagination whenever the search/filter changes. navigate({ search: params.toString() }); } return ( postField(taskId, "setStatus", "status", status) : undefined, onSetPriority: canWrite ? (taskId, priority) => postField(taskId, "setPriority", "priority", priority) : undefined, }} /> ); } export function ErrorBoundary() { return ; }