241 lines
10 KiB
TypeScript
241 lines
10 KiB
TypeScript
// 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).
|
|
//
|
|
// Interim-UI (AD-28): renders the ~/ui preview screen TaskDetailPage; mutations stay
|
|
// server-driven (<form method="post"> + intent). Final Subframe optics land as a
|
|
// tracked design-nachzug once David's D-P4 delta ships.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
|
import { buildTaskDetailVM, taskEntityLabelKey, type TaskDetailVM, type TaskWatcherView } from "@hivegrid/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 { tasksListPath } from "~/utils/integrations/taskRoutePaths";
|
|
import { NO_WATCHER, TaskDetailPage } from "~/components/screens/tasks/TaskDetailPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
type LoaderData = { title: string; vm: TaskDetailVM };
|
|
|
|
type ActionData = { intent: string; ok?: true; messageKey?: string; error?: string };
|
|
|
|
const TASK_SUCCESS_KEYS: Readonly<Record<string, string>> = {
|
|
update: "tasks.toast.saved",
|
|
complete: "tasks.toast.completed",
|
|
removeWatcher: "tasks.toast.watcherRemoved",
|
|
archive: "tasks.toast.archived",
|
|
reactivate: "tasks.toast.reactivated",
|
|
};
|
|
|
|
const TASK_STATUSES: TaskStatus[] = ["open", "in_progress", "blocked", "done", "cancelled"];
|
|
const TASK_PRIORITIES: TaskPriority[] = ["low", "normal", "high", "urgent"];
|
|
const TERMINAL: ReadonlySet<TaskStatus> = new Set<TaskStatus>(["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<string, string>()),
|
|
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, ctx });
|
|
await auditTaskEvent({ ctx, action: "task.deleted", taskId });
|
|
return redirect(`${tasksListPath(tenantSlug)}?toast=${encodeURIComponent("tasks.toast.deleted")}`);
|
|
}
|
|
|
|
requireTasksPermission(ctx, "tasks.write");
|
|
|
|
// One save for the whole detail form: master data, assignment and an
|
|
// optionally added watcher. The screen has a single save button, so
|
|
// reassignment and watcher-add are folded into this intent instead of
|
|
// sitting behind their own submits.
|
|
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,
|
|
ctx,
|
|
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 });
|
|
|
|
const assigneeType = String(formData.get("assigneeType") ?? "user");
|
|
const assigneeId = String(formData.get("assigneeId") ?? "").trim();
|
|
if (assigneeId) {
|
|
await reassignTask({
|
|
tenantId: ctx.tenantId,
|
|
tenantSlug: params.tenant,
|
|
taskId,
|
|
ctx,
|
|
assignedToUserId: assigneeType === "user" ? assigneeId : null,
|
|
assignedToGroupId: assigneeType === "group" ? assigneeId : null,
|
|
});
|
|
await auditTaskEvent({ ctx, action: "task.reassigned", taskId, metadata: { assigneeType } });
|
|
}
|
|
|
|
// The picker's sentinel means "no watcher picked" and must not be stored.
|
|
const watcherUserId = String(formData.get("watcherUserId") ?? "").trim();
|
|
if (watcherUserId && watcherUserId !== NO_WATCHER) {
|
|
await addWatcher({ tenantId: ctx.tenantId, taskId, userId: watcherUserId, ctx });
|
|
await auditTaskEvent({ ctx, action: "task.watcher_added", taskId, metadata: { userId: watcherUserId } });
|
|
}
|
|
return Response.json({ intent, ok: true, messageKey: TASK_SUCCESS_KEYS[intent] } satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "complete") {
|
|
await completeTask({ tenantId: ctx.tenantId, taskId, ctx });
|
|
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: "crm.activity.task_completed",
|
|
linkedEntityType: linked?.task.linkedEntityType ?? null,
|
|
linkedEntityId: linked?.task.linkedEntityId ?? null,
|
|
});
|
|
return Response.json({ intent, ok: true, messageKey: TASK_SUCCESS_KEYS[intent] } satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "removeWatcher") {
|
|
const userId = String(formData.get("userId") ?? "").trim();
|
|
await removeWatcher({ tenantId: ctx.tenantId, taskId, userId, ctx });
|
|
await auditTaskEvent({ ctx, action: "task.watcher_removed", taskId, metadata: { userId } });
|
|
return Response.json({ intent, ok: true, messageKey: TASK_SUCCESS_KEYS[intent] } satisfies ActionData);
|
|
}
|
|
|
|
if (intent === "archive") {
|
|
await archiveTask({ tenantId: ctx.tenantId, taskId, ctx });
|
|
await auditTaskEvent({ ctx, action: "task.archived", taskId });
|
|
} else if (intent === "reactivate") {
|
|
await reactivateTask({ tenantId: ctx.tenantId, taskId, ctx });
|
|
await auditTaskEvent({ ctx, action: "task.reactivated", taskId });
|
|
}
|
|
const messageKey = TASK_SUCCESS_KEYS[intent];
|
|
if (!messageKey) return Response.json({ intent, error: "tasks.error.invalidAction" } satisfies ActionData, { status: 400 });
|
|
return Response.json({ intent, ok: true, messageKey } satisfies ActionData);
|
|
} catch (error) {
|
|
if (error instanceof Response) throw error;
|
|
throw notFoundResponse();
|
|
}
|
|
};
|
|
|
|
export default function TaskDetailRoute() {
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
|
|
useSaveToast(actionData);
|
|
|
|
if (vm.status !== "ready" || !vm.data) {
|
|
return <div className="flex w-full max-w-[960px] flex-col gap-6 p-6" data-ui-id="ui.tasks.detail" />;
|
|
}
|
|
return <TaskDetailPage data={vm.data} />;
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|