// P4 Tasks (AK-P4b) §6 — Task detail route. Loader builds TaskDetailVM; action // handles update/complete/archive/reactivate/delete/reassign/watcher + audit + // activity. Not-visible / foreign task -> 404 (Bauprinzip A.5.3). Baseline UI. import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData } from "react-router"; import { useTranslation } from "react-i18next"; import { buildTaskDetailVM, taskEntityLabelKey, type TaskDetailVM, type TaskWatcherView } from "@toolctrl/view-models"; import { badRequestResponse, loadTasksContext, notFoundResponse, requireTasksPermission } from "~/utils/integrations/taskAccess.server"; import { archiveTask, completeTask, getVisibleTaskWithWatchers, hardDeleteTask, listAssignableGroups, listAssignableUsers, reactivateTask, reassignTask, removeWatcher, addWatcher, resolveGroupLabels, resolveUserLabels, updateTask, type TaskPriority, type TaskStatus, } from "~/utils/integrations/taskService.server"; import { auditTaskEvent, logTaskActivity } from "~/utils/integrations/taskAudit.server"; import { tasksDetailPath, tasksListPath } from "~/utils/integrations/taskRoutePaths"; import ServerError from "~/components/ui/errors/ServerError"; type LoaderData = { title: string; vm: TaskDetailVM }; const TASK_STATUSES: TaskStatus[] = ["open", "in_progress", "blocked", "done", "cancelled"]; const TASK_PRIORITIES: TaskPriority[] = ["low", "normal", "high", "urgent"]; const TERMINAL: ReadonlySet = new Set(["done", "cancelled"]); function isStatus(value: string): value is TaskStatus { return TASK_STATUSES.includes(value as TaskStatus); } function isPriority(value: string): value is TaskPriority { return TASK_PRIORITIES.includes(value as TaskPriority); } export const loader = async ({ request, params }: LoaderFunctionArgs) => { const ctx = await loadTasksContext({ request, params, requireModule: true }); const taskId = params.id ?? ""; const tenantSlug = params.tenant ?? ""; let task, watchers; try { ({ task, watchers } = await getVisibleTaskWithWatchers(ctx.tenantId, taskId, ctx)); } catch { throw notFoundResponse(); } const canWrite = ctx.permissions.includes("tasks.write"); const canDelete = ctx.permissions.includes("tasks.delete"); // Resolve assignee + watcher display names; load picker options for writers. const watcherIds = watchers.map((watcher) => watcher.userId); const assigneeUserIds = task.assignedToUserId ? [task.assignedToUserId] : []; const [userLabels, groupLabels, assignableUsers, assignableGroups] = await Promise.all([ resolveUserLabels([...watcherIds, ...assigneeUserIds]), task.assignedToGroupId ? resolveGroupLabels(ctx.tenantId, [task.assignedToGroupId]) : Promise.resolve(new Map()), canWrite ? listAssignableUsers(ctx.tenantId) : Promise.resolve([]), canWrite ? listAssignableGroups(ctx.tenantId) : Promise.resolve([]), ]); const assignee = task.assignedToUserId ? { kind: "user" as const, label: userLabels.get(task.assignedToUserId) ?? task.assignedToUserId } : task.assignedToGroupId ? { kind: "group" as const, label: groupLabels.get(task.assignedToGroupId) ?? task.assignedToGroupId } : null; const watcherViews: TaskWatcherView[] = watchers.map((watcher) => ({ userId: watcher.userId, label: userLabels.get(watcher.userId) ?? watcher.userId, })); const vm = buildTaskDetailVM({ task: { id: task.id, title: task.title, description: task.description, status: task.status, priority: task.priority, deadlineIso: task.deadline ? task.deadline.toISOString() : null, isOverdue: Boolean(task.deadline && task.deadline.getTime() < Date.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, sourceHref: null, watchers: watcherViews, createdAtIso: task.createdAt.toISOString(), completedAtIso: task.completedAt ? task.completedAt.toISOString() : null, }, assignableUsers, assignableGroups, canWrite, canDelete, listHref: tasksListPath(tenantSlug), }); return Response.json({ title: `${task.title} | ${process.env.APP_NAME}`, vm } satisfies LoaderData); }; export const action = async ({ request, params }: ActionFunctionArgs) => { const ctx = await loadTasksContext({ request, params, requireModule: true }); const taskId = params.id ?? ""; const tenantSlug = params.tenant ?? ""; const formData = await request.formData(); const intent = String(formData.get("intent") ?? ""); try { if (intent === "delete") { requireTasksPermission(ctx, "tasks.delete"); await hardDeleteTask({ tenantId: ctx.tenantId, taskId }); await auditTaskEvent({ ctx, action: "task.deleted", taskId }); return redirect(tasksListPath(tenantSlug)); } requireTasksPermission(ctx, "tasks.write"); if (intent === "update") { const title = String(formData.get("title") ?? "").trim(); const description = String(formData.get("description") ?? ""); const statusRaw = String(formData.get("status") ?? ""); const priorityRaw = String(formData.get("priority") ?? ""); const deadlineRaw = String(formData.get("deadline") ?? "").trim(); if (!title || (statusRaw && !isStatus(statusRaw)) || (priorityRaw && !isPriority(priorityRaw))) { throw badRequestResponse(); } await updateTask({ tenantId: ctx.tenantId, taskId, title, description: description || null, status: statusRaw ? (statusRaw as TaskStatus) : undefined, priority: priorityRaw ? (priorityRaw as TaskPriority) : undefined, deadline: deadlineRaw ? new Date(deadlineRaw) : null, }); await auditTaskEvent({ ctx, action: "task.updated", taskId }); return redirect(tasksDetailPath(tenantSlug, taskId)); } if (intent === "complete") { await completeTask({ tenantId: ctx.tenantId, taskId }); await auditTaskEvent({ ctx, action: "task.completed", taskId }); const linked = await getVisibleTaskWithWatchers(ctx.tenantId, taskId, ctx).catch(() => null); await logTaskActivity({ ctx, taskId, activityType: "task_completed", summaryText: "Aufgabe erledigt", linkedEntityType: linked?.task.linkedEntityType ?? null, linkedEntityId: linked?.task.linkedEntityId ?? null, }); return redirect(tasksDetailPath(tenantSlug, taskId)); } if (intent === "reassign") { const assigneeType = String(formData.get("assigneeType") ?? "user"); const assigneeId = String(formData.get("assigneeId") ?? "").trim(); if (!assigneeId) { throw badRequestResponse(); } await reassignTask({ tenantId: ctx.tenantId, taskId, assignedToUserId: assigneeType === "user" ? assigneeId : null, assignedToGroupId: assigneeType === "group" ? assigneeId : null, }); await auditTaskEvent({ ctx, action: "task.reassigned", taskId, metadata: { assigneeType } }); return redirect(tasksDetailPath(tenantSlug, taskId)); } if (intent === "addWatcher") { const userId = String(formData.get("userId") ?? "").trim(); if (!userId) { throw badRequestResponse(); } await addWatcher({ tenantId: ctx.tenantId, taskId, userId }); await auditTaskEvent({ ctx, action: "task.watcher_added", taskId, metadata: { userId } }); return redirect(tasksDetailPath(tenantSlug, taskId)); } if (intent === "removeWatcher") { const userId = String(formData.get("userId") ?? "").trim(); await removeWatcher({ tenantId: ctx.tenantId, taskId, userId }); await auditTaskEvent({ ctx, action: "task.watcher_removed", taskId, metadata: { userId } }); return redirect(tasksDetailPath(tenantSlug, taskId)); } if (intent === "archive") { await archiveTask({ tenantId: ctx.tenantId, taskId }); await auditTaskEvent({ ctx, action: "task.archived", taskId }); } else if (intent === "reactivate") { await reactivateTask({ tenantId: ctx.tenantId, taskId }); await auditTaskEvent({ ctx, action: "task.reactivated", taskId }); } return redirect(tasksDetailPath(tenantSlug, taskId)); } catch (error) { if (error instanceof Response) throw error; throw notFoundResponse(); } }; export default function TaskDetailRoute() { const { t, i18n } = useTranslation(); const { vm } = useLoaderData(); if (vm.status !== "ready" || !vm.data) { return
; } const data = vm.data; const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" }); return (
{t("tasks.detail.back")}

{data.title}

{t(data.statusKey)} · {t(data.priorityKey)} · {t(data.sourceKey)}

{data.deadlineIso ? (

{t("tasks.detail.field.deadline")}: {dateFormatter.format(new Date(data.deadlineIso))}

) : null}

{t("tasks.detail.field.assignee")}: {data.assignee ? data.assignee.label : t("tasks.detail.unassigned")}

{data.linkedEntity ? (

{t(data.linkedEntity.labelKey)} · {data.linkedEntity.entityId}

) : null} {data.description ? (

{t("tasks.detail.section.description")}

{data.description}

) : null}
{data.canWrite && data.status !== "done" ? (
) : null} {data.canWrite ? (
) : null} {data.canDelete ? (
) : null}
{data.canWrite ? (

{t("tasks.detail.section.edit")}