Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/routes/app.$tenant/tasks._index.tsx
T

207 lines
8.1 KiB
TypeScript

// 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.
//
// Baseline functional UI (data-ui-id markers for e2e); the Subframe visual polish
// follows Davids D-P4 delta (Dev-Nachzug).
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import {
buildTaskListVM,
taskEntityLabelKey,
taskPriorityKey,
taskSourceKey,
taskStatusKey,
type TaskListPreset,
type TaskListRow,
type TaskListVM,
} from "@toolctrl/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadTasksContext, notFoundResponse, requireTasksPermission } from "~/utils/integrations/taskAccess.server";
import {
listTasksForBrowser,
resolveGroupLabels,
resolveUserLabels,
type TaskPriority,
type TaskRow,
type TaskStatus,
} from "~/utils/integrations/taskService.server";
import { tasksDetailPath, tasksNewPath } from "~/utils/integrations/taskRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
type LoaderData = { title: string; vm: TaskListVM };
const PRESETS: readonly TaskListPreset[] = ["mine", "created", "all"];
const TERMINAL: ReadonlySet<TaskStatus> = new Set<TaskStatus>(["done", "cancelled"]);
function parsePreset(value: string | null): TaskListPreset {
return PRESETS.includes(value as TaskListPreset) ? (value as TaskListPreset) : "all";
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadTasksContext({ request, params });
const tenantSlug = params.tenant ?? "";
const emptyFilter = { preset: "all" as TaskListPreset, 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 } satisfies LoaderData);
}
try {
requireTasksPermission(ctx, "tasks.read_own");
} catch {
throw notFoundResponse();
}
const url = new URL(request.url);
const preset = parsePreset(url.searchParams.get("preset"));
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: { preset, status, priority, includeArchived },
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");
const vm = buildTaskListVM({
rows: listRows,
filter: { preset, status, priority, assignedToUserId: null, includeArchived },
canWrite,
canDelete,
createHref: tasksNewPath(tenantSlug),
nextCursor,
});
return Response.json({ title: `${t("tasks.list.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
};
/** Map a domain TaskRow to the routing-resolved TaskListRow (shared by embeds). */
export function toTaskListRow(
task: TaskRow,
deps: { tenantSlug: string; userLabels: Map<string, string>; groupLabels: Map<string, string>; 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 { t, i18n } = useTranslation();
const { vm } = useLoaderData<LoaderData>();
if (vm.status !== "ready" || !vm.data) {
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.tasks.list" />;
}
const { rows, canWrite, createHref, emptyHeadlineKey, emptyBodyKey } = vm.data;
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.tasks.list">
<div className="flex items-center justify-between">
<div>
<h1 className="text-foreground text-xl font-semibold">{t("tasks.list.title")}</h1>
<p className="text-muted-foreground mt-1 text-sm">{t("tasks.list.subtitle")}</p>
</div>
{canWrite ? (
<a href={createHref} className="text-theme-600 font-medium" data-ui-id="ui.tasks.list.new">
{t("tasks.list.actions.new")}
</a>
) : null}
</div>
<nav className="text-muted-foreground mt-4 flex gap-4 text-sm" data-ui-id="ui.tasks.list.presets">
{PRESETS.map((preset) => (
<a key={preset} href={`?preset=${preset}`} className="hover:text-foreground">
{t(`tasks.list.preset.${preset}`)}
</a>
))}
</nav>
{rows.length === 0 ? (
<div className="mt-10 text-center" data-ui-id="ui.tasks.list.empty">
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
</div>
) : (
<table className="mt-6 w-full text-left text-sm" data-ui-id="ui.tasks.list.table">
<thead>
<tr className="text-muted-foreground border-b">
<th className="py-2">{t("tasks.list.column.title")}</th>
<th className="py-2">{t("tasks.list.column.status")}</th>
<th className="py-2">{t("tasks.list.column.priority")}</th>
<th className="py-2">{t("tasks.list.column.assignee")}</th>
<th className="py-2">{t("tasks.list.column.deadline")}</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id} className="border-b" data-row-id={row.id}>
<td className="py-2">
<a href={row.detailHref} className="text-theme-600">
{row.title}
</a>
</td>
<td className="py-2">{t(row.statusKey)}</td>
<td className="py-2">{t(row.priorityKey)}</td>
<td className="py-2">{row.assignee ? row.assignee.label : "—"}</td>
<td className="py-2" data-overdue={row.isOverdue}>
{row.deadlineIso ? dateFormatter.format(new Date(row.deadlineIso)) : "—"}
</td>
</tr>
))}
</tbody>
</table>
)}
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}