Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/tasks.new.tsx
T

128 lines
5.6 KiB
TypeScript

// P4 Tasks (AK-P4b) §6 — Task create route. Loader provides the assignee picker
// options + optional entity pre-fill (when opened as the "new task" CTA from an
// entity detail view). Action creates the task, audits, logs activity, redirects
// back to the list. Missing tasks.write -> 404.
//
// Interim-UI (AD-28): renders the ~/ui preview screen TaskNewPage; the form posts to
// this route action. Final Subframe optics land as a tracked design-nachzug once
// David's D-P4 delta ships.
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { badRequestResponse, loadTasksContext, notFoundResponse, requireTasksPermission } from "~/utils/integrations/taskAccess.server";
import {
createTask,
listAssignableGroups,
listAssignableUsers,
type LabeledOption,
type TaskEntityType,
type TaskPriority,
} from "~/utils/integrations/taskService.server";
import { auditTaskEvent, logTaskActivity } from "~/utils/integrations/taskAudit.server";
import { tasksListPath } from "~/utils/integrations/taskRoutePaths";
import { TaskNewPage, TASK_CREATOR_ASSIGNEE } from "~/components/screens/tasks/TaskNewPage";
import ServerError from "~/components/ui/errors/ServerError";
const TASK_PRIORITIES: TaskPriority[] = ["low", "normal", "high", "urgent"];
const TASK_ENTITY_TYPES: TaskEntityType[] = ["contact", "company", "lead", "deal", "project", "user", "order", "appointment"];
type Prefill = { entityType: TaskEntityType; entityId: string } | null;
type LoaderData = {
title: string;
assignableUsers: LabeledOption[];
assignableGroups: LabeledOption[];
prefill: Prefill;
cancelHref: string;
};
function parsePrefill(url: URL): Prefill {
const entityType = url.searchParams.get("entityType");
const entityId = url.searchParams.get("entityId");
if (entityType && entityId && TASK_ENTITY_TYPES.includes(entityType as TaskEntityType)) {
return { entityType: entityType as TaskEntityType, entityId };
}
return null;
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadTasksContext({ request, params, requireModule: true });
try {
requireTasksPermission(ctx, "tasks.write");
} catch {
throw notFoundResponse();
}
const [assignableUsers, assignableGroups] = await Promise.all([listAssignableUsers(ctx.tenantId), listAssignableGroups(ctx.tenantId)]);
return Response.json({
title: `${t("tasks.new.title")} | ${process.env.APP_NAME}`,
assignableUsers,
assignableGroups,
prefill: parsePrefill(new URL(request.url)),
cancelHref: tasksListPath(params.tenant ?? ""),
} satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadTasksContext({ request, params, requireModule: true });
const tenantSlug = params.tenant ?? "";
try {
requireTasksPermission(ctx, "tasks.write");
const formData = await request.formData();
const title = String(formData.get("title") ?? "").trim();
if (!title) {
throw badRequestResponse();
}
const description = String(formData.get("description") ?? "");
const priorityRaw = String(formData.get("priority") ?? "normal");
const priority = (TASK_PRIORITIES.includes(priorityRaw as TaskPriority) ? priorityRaw : "normal") as TaskPriority;
const deadlineRaw = String(formData.get("deadline") ?? "").trim();
const assigneeType = String(formData.get("assigneeType") ?? "");
const rawAssigneeId = String(formData.get("assigneeId") ?? "").trim();
// The creator-default sentinel maps back to "no explicit assignee".
const assigneeId = rawAssigneeId === TASK_CREATOR_ASSIGNEE ? "" : rawAssigneeId;
const entityTypeRaw = String(formData.get("entityType") ?? "").trim();
const entityId = String(formData.get("entityId") ?? "").trim();
const linkedEntityType = entityTypeRaw && TASK_ENTITY_TYPES.includes(entityTypeRaw as TaskEntityType) ? (entityTypeRaw as TaskEntityType) : null;
const task = await createTask({
tenantId: ctx.tenantId,
tenantSlug: params.tenant,
ctx,
title,
description: description || null,
priority,
deadline: deadlineRaw ? new Date(deadlineRaw) : null,
assignedToUserId: assigneeType === "user" && assigneeId ? assigneeId : null,
assignedToGroupId: assigneeType === "group" && assigneeId ? assigneeId : null,
linkedEntityType,
linkedEntityId: linkedEntityType && entityId ? entityId : null,
source: "manual",
});
await auditTaskEvent({ ctx, action: "task.created", taskId: task.id, metadata: { source: "manual" } });
await logTaskActivity({
ctx,
taskId: task.id,
activityType: "task_created",
summaryText: "crm.activity.task_created",
linkedEntityType: task.linkedEntityType,
linkedEntityId: task.linkedEntityId,
});
// Back to the list, not into the new task's detail view: creating a task is
// a side task while working through the list, and being thrown into the
// detail page meant navigating back for every single one.
return redirect(`${tasksListPath(tenantSlug)}?toast=${encodeURIComponent("tasks.toast.created")}`);
} catch (error) {
if (error instanceof Response) throw error;
throw notFoundResponse();
}
};
export default function TaskCreateRoute() {
const { assignableUsers, assignableGroups, prefill, cancelHref } = useLoaderData<LoaderData>();
return <TaskNewPage assignableUsers={assignableUsers} assignableGroups={assignableGroups} prefill={prefill} cancelHref={cancelHref} />;
}
export function ErrorBoundary() {
return <ServerError />;
}