410 lines
18 KiB
TypeScript
410 lines
18 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). 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<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 });
|
|
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<LoaderData>();
|
|
if (vm.status !== "ready" || !vm.data) {
|
|
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.tasks.detail" />;
|
|
}
|
|
const data = vm.data;
|
|
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
|
|
|
|
return (
|
|
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.tasks.detail">
|
|
<a href={data.listHref} className="text-muted-foreground text-sm">
|
|
{t("tasks.detail.back")}
|
|
</a>
|
|
<h1 className="text-foreground mt-2 text-xl font-semibold">{data.title}</h1>
|
|
<p className="text-muted-foreground mt-1 text-sm">
|
|
{t(data.statusKey)} · {t(data.priorityKey)} · {t(data.sourceKey)}
|
|
</p>
|
|
|
|
{data.deadlineIso ? (
|
|
<p className="mt-2 text-sm" data-ui-id="ui.tasks.detail.deadline" data-overdue={data.isOverdue}>
|
|
{t("tasks.detail.field.deadline")}: {dateFormatter.format(new Date(data.deadlineIso))}
|
|
</p>
|
|
) : null}
|
|
|
|
<p className="mt-2 text-sm">
|
|
{t("tasks.detail.field.assignee")}: {data.assignee ? data.assignee.label : t("tasks.detail.unassigned")}
|
|
</p>
|
|
|
|
{data.linkedEntity ? (
|
|
<p className="mt-1 text-sm" data-ui-id="ui.tasks.detail.linkedEntity">
|
|
{t(data.linkedEntity.labelKey)} · {data.linkedEntity.entityId}
|
|
</p>
|
|
) : null}
|
|
|
|
{data.description ? (
|
|
<section className="mt-6">
|
|
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("tasks.detail.section.description")}</h2>
|
|
<p className="mt-1 text-sm whitespace-pre-wrap">{data.description}</p>
|
|
</section>
|
|
) : null}
|
|
|
|
<div className="mt-6 flex flex-wrap gap-3" data-ui-id="ui.tasks.detail.actions">
|
|
{data.canWrite && data.status !== "done" ? (
|
|
<form method="post">
|
|
<input type="hidden" name="intent" value="complete" />
|
|
<button type="submit" className="text-theme-600 font-medium" data-ui-id="ui.tasks.detail.complete">
|
|
{t("tasks.detail.actions.complete")}
|
|
</button>
|
|
</form>
|
|
) : null}
|
|
{data.canWrite ? (
|
|
<form method="post">
|
|
<input type="hidden" name="intent" value="archive" />
|
|
<button type="submit" className="text-theme-600 font-medium" data-ui-id="ui.tasks.detail.archive">
|
|
{t("tasks.detail.actions.archive")}
|
|
</button>
|
|
</form>
|
|
) : null}
|
|
{data.canDelete ? (
|
|
<form method="post">
|
|
<input type="hidden" name="intent" value="delete" />
|
|
<button type="submit" className="text-destructive font-medium" data-ui-id="ui.tasks.detail.delete">
|
|
{t("tasks.detail.actions.delete")}
|
|
</button>
|
|
</form>
|
|
) : null}
|
|
</div>
|
|
|
|
{data.canWrite ? (
|
|
<section className="mt-8" data-ui-id="ui.tasks.detail.edit">
|
|
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("tasks.detail.section.edit")}</h2>
|
|
<form method="post" className="mt-3 grid gap-3">
|
|
<input type="hidden" name="intent" value="update" />
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.title")}</span>
|
|
<input name="title" defaultValue={data.title} required className="border-muted-foreground/40 w-full rounded border px-2 py-1" />
|
|
</label>
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.description")}</span>
|
|
<textarea name="description" defaultValue={data.description ?? ""} className="border-muted-foreground/40 w-full rounded border px-2 py-1" />
|
|
</label>
|
|
<div className="flex flex-wrap gap-3">
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.status")}</span>
|
|
<select name="status" defaultValue={data.status} className="border-muted-foreground/40 rounded border px-2 py-1">
|
|
{TASK_STATUSES.map((status) => (
|
|
<option key={status} value={status}>
|
|
{t(`tasks.status.${status}`)}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.priority")}</span>
|
|
<select name="priority" defaultValue={data.priority} className="border-muted-foreground/40 rounded border px-2 py-1">
|
|
{TASK_PRIORITIES.map((priority) => (
|
|
<option key={priority} value={priority}>
|
|
{t(`tasks.priority.${priority}`)}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.deadline")}</span>
|
|
<input
|
|
type="date"
|
|
name="deadline"
|
|
defaultValue={data.deadlineIso ? data.deadlineIso.slice(0, 10) : ""}
|
|
className="border-muted-foreground/40 rounded border px-2 py-1"
|
|
/>
|
|
</label>
|
|
</div>
|
|
<button type="submit" className="text-theme-600 w-fit font-medium">
|
|
{t("tasks.detail.actions.save")}
|
|
</button>
|
|
</form>
|
|
|
|
<form method="post" className="mt-4 flex flex-wrap items-end gap-2" data-ui-id="ui.tasks.detail.reassign">
|
|
<input type="hidden" name="intent" value="reassign" />
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.assigneeType")}</span>
|
|
<select name="assigneeType" className="border-muted-foreground/40 rounded border px-2 py-1">
|
|
<option value="user">{t("tasks.detail.assignee.user")}</option>
|
|
<option value="group">{t("tasks.detail.assignee.group")}</option>
|
|
</select>
|
|
</label>
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.assignee")}</span>
|
|
<select name="assigneeId" className="border-muted-foreground/40 rounded border px-2 py-1">
|
|
<optgroup label={t("tasks.detail.assignee.user")}>
|
|
{data.assignableUsers.map((user) => (
|
|
<option key={`u-${user.id}`} value={user.id}>
|
|
{user.label}
|
|
</option>
|
|
))}
|
|
</optgroup>
|
|
<optgroup label={t("tasks.detail.assignee.group")}>
|
|
{data.assignableGroups.map((group) => (
|
|
<option key={`g-${group.id}`} value={group.id}>
|
|
{group.label}
|
|
</option>
|
|
))}
|
|
</optgroup>
|
|
</select>
|
|
</label>
|
|
<button type="submit" className="text-theme-600 font-medium">
|
|
{t("tasks.detail.actions.reassign")}
|
|
</button>
|
|
</form>
|
|
</section>
|
|
) : null}
|
|
|
|
<section className="mt-8" data-ui-id="ui.tasks.detail.watchers">
|
|
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("tasks.detail.section.watchers")}</h2>
|
|
{data.watchers.length > 0 ? (
|
|
<ul className="mt-1 text-sm">
|
|
{data.watchers.map((watcher) => (
|
|
<li key={watcher.userId} className="flex items-center gap-2" data-watcher-id={watcher.userId}>
|
|
<span>{watcher.label}</span>
|
|
{data.canWrite ? (
|
|
<form method="post">
|
|
<input type="hidden" name="intent" value="removeWatcher" />
|
|
<input type="hidden" name="userId" value={watcher.userId} />
|
|
<button type="submit" className="text-muted-foreground text-xs underline">
|
|
{t("tasks.detail.actions.removeWatcher")}
|
|
</button>
|
|
</form>
|
|
) : null}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
) : (
|
|
<p className="text-muted-foreground mt-1 text-sm">{t("tasks.detail.watchers.empty")}</p>
|
|
)}
|
|
{data.canWrite ? (
|
|
<form method="post" className="mt-3 flex flex-wrap items-end gap-2">
|
|
<input type="hidden" name="intent" value="addWatcher" />
|
|
<label className="text-sm">
|
|
<span className="text-muted-foreground block text-xs">{t("tasks.detail.field.watcher")}</span>
|
|
<select name="userId" className="border-muted-foreground/40 rounded border px-2 py-1">
|
|
{data.assignableUsers.map((user) => (
|
|
<option key={`w-${user.id}`} value={user.id}>
|
|
{user.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<button type="submit" className="text-theme-600 font-medium">
|
|
{t("tasks.detail.actions.addWatcher")}
|
|
</button>
|
|
</form>
|
|
) : null}
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|