"use client"; import { useState, useEffect, useMemo, useCallback } from "react"; import { formatDate } from "~/lib/format.js"; import { trpc } from "~/lib/trpc/client.js"; import { AllocationModal } from "./AllocationModal.js"; import type { AllocationLike, AllocationReadModel, AllocationWithDetails, ColumnDef } from "@capakraken/shared"; import { AllocationStatus, ALLOCATION_COLUMNS } from "@capakraken/shared"; import { useSelection } from "~/hooks/useSelection.js"; import { BatchActionBar } from "~/components/ui/BatchActionBar.js"; import { ConfirmDialog } from "~/components/ui/ConfirmDialog.js"; import { FilterBar } from "~/components/ui/FilterBar.js"; import { FilterChips } from "~/components/ui/FilterChips.js"; import { ResourceCombobox } from "~/components/ui/ResourceCombobox.js"; import { ProjectCombobox } from "~/components/ui/ProjectCombobox.js"; import { ColumnTogglePanel } from "~/components/ui/ColumnTogglePanel.js"; import { SortableColumnHeader } from "~/components/ui/SortableColumnHeader.js"; import { useTableSort } from "~/hooks/useTableSort.js"; import { usePermissions } from "~/hooks/usePermissions.js"; import { useColumnConfig } from "~/hooks/useColumnConfig.js"; import { useViewPrefs } from "~/hooks/useViewPrefs.js"; import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js"; import { ALLOCATION_STATUS_BADGE as STATUS_BADGE } from "~/lib/status-styles.js"; import { SuccessToast } from "~/components/ui/SuccessToast.js"; import { collapseAllAllocationGroups, createInitialCollapsedAllocationGroups, expandAllAllocationGroups, toggleCollapsedAllocationGroup, type CollapsedAllocationGroups, } from "./allocationGroupState.js"; /** Left-border color by allocation status for instant visual scanning */ const STATUS_LEFT_BORDER: Record = { ACTIVE: "border-l-green-500", PROPOSED: "border-l-amber-500", CONFIRMED: "border-l-blue-500", COMPLETED: "border-l-gray-400", CANCELLED: "border-l-red-500", }; /** Fragment wrapper for grouped rows — avoids unnecessary DOM nodes */ function GroupRows({ children }: { children: React.ReactNode }) { return <>{children}; } const ALL_ALLOC_STATUSES = [ { value: "PROPOSED", label: "Proposed" }, { value: "CONFIRMED", label: "Confirmed" }, { value: "ACTIVE", label: "Active" }, { value: "COMPLETED", label: "Completed" }, { value: "CANCELLED", label: "Cancelled" }, ] as const; type AllocationAssignmentsView = AllocationReadModel; type DemandRow = AllocationWithDetails & { sourceAllocationId?: string; requestedHeadcount?: number; unfilledHeadcount?: number; }; export function AllocationsClient() { const [modalOpen, setModalOpen] = useState(false); const [editingAllocation, setEditingAllocation] = useState(null); const [filterProjectId, setFilterProjectId] = useState(""); const [filterResourceId, setFilterResourceId] = useState(""); const [filterStatus, setFilterStatus] = useState(""); const [hidePastProjects, setHidePastProjects] = useState(true); const [hideCompletedProjects, setHideCompletedProjects] = useState(true); const [hideDraftProjects, setHideDraftProjects] = useState(false); const [confirmDelete, setConfirmDelete] = useState<{ single?: AllocationWithDetails; ids?: string[] } | null>(null); const [batchStatusPicker, setBatchStatusPicker] = useState(false); const [confirmBatchStatus, setConfirmBatchStatus] = useState<{ ids: string[]; status: string } | null>(null); const [showStatusToast, setShowStatusToast] = useState(false); const selection = useSelection(); const utils = trpc.useUtils(); const { canViewCosts } = usePermissions(); // ─── Column visibility ──────────────────────────────────────────────────── const baseColumns = useMemo( () => (canViewCosts ? ALLOCATION_COLUMNS : ALLOCATION_COLUMNS.filter((c) => c.key !== "cost")), [canViewCosts], ); const { allColumns, visibleColumns, visibleKeys, setVisible } = useColumnConfig("allocations", baseColumns); const defaultKeys = useMemo(() => baseColumns.filter((c) => c.defaultVisible).map((c) => c.key), [baseColumns]); const { data: allocationView, isLoading } = trpc.allocation.listView.useQuery( { projectId: filterProjectId || undefined, resourceId: filterResourceId || undefined, status: (filterStatus as AllocationStatus) || undefined, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any { placeholderData: (prev: any) => prev, staleTime: 15_000 }, ) as { data: AllocationAssignmentsView | undefined; isLoading: boolean }; const deleteDemandMutation = trpc.allocation.deleteDemandRequirement.useMutation({ onSuccess: async () => { await utils.allocation.list.invalidate(); await utils.allocation.listView.invalidate(); }, }); const deleteAssignmentMutation = trpc.allocation.deleteAssignment.useMutation({ onSuccess: async () => { await utils.allocation.list.invalidate(); await utils.allocation.listView.invalidate(); }, }); const batchDeleteMutation = trpc.allocation.batchDelete.useMutation({ onSuccess: async () => { await utils.allocation.list.invalidate(); await utils.allocation.listView.invalidate(); selection.clear(); }, }); const batchStatusMutation = trpc.allocation.batchUpdateStatus.useMutation({ onSuccess: async () => { await utils.allocation.list.invalidate(); await utils.allocation.listView.invalidate(); selection.clear(); setShowStatusToast(true); }, }); useEffect(() => { selection.clear(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [filterProjectId, filterResourceId, filterStatus, hidePastProjects, hideCompletedProjects, hideDraftProjects]); function openCreate() { setEditingAllocation(null); setModalOpen(true); } function openEdit(alloc: AllocationWithDetails) { setEditingAllocation(alloc); setModalOpen(true); } function closeModal() { setModalOpen(false); setEditingAllocation(null); } const assignmentList = (allocationView?.assignments ?? []) as unknown as AllocationWithDetails[]; const demandList = (allocationView?.demands ?? []) as unknown as DemandRow[]; const today = new Date(); today.setHours(0, 0, 0, 0); const filteredAllocations = assignmentList.filter((alloc) => { if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today) return false; if (hideCompletedProjects && alloc.project?.status && ["COMPLETED", "CANCELLED"].includes(alloc.project.status)) return false; if (hideDraftProjects && alloc.project?.status === "DRAFT") return false; return true; }); const filteredDemands = demandList.filter((alloc) => { if (filterResourceId) return false; if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today) return false; if (hideCompletedProjects && alloc.project?.status && ["COMPLETED", "CANCELLED"].includes(alloc.project.status)) return false; if (hideDraftProjects && alloc.project?.status === "DRAFT") return false; return true; }); const allocViewPrefs = useViewPrefs("allocations"); const { sorted, sortField, sortDir, toggle } = useTableSort(filteredAllocations, { initialField: allocViewPrefs.savedSort?.field ?? null, initialDir: allocViewPrefs.savedSort?.dir ?? null, onSortChange: (field, dir) => { allocViewPrefs.setSavedSort(field && dir ? { field, dir } : null); }, }); const allocationIds = sorted.map((a) => a.id); const allocationMutationIdsByDisplayId = useMemo( () => new Map( sorted.map((allocation) => [allocation.id, getPlanningEntryMutationId(allocation)]), ), [sorted], ); const selectedMutationIds = useMemo( () => selection.selectedArray.flatMap((displayId) => { const mutationId = allocationMutationIdsByDisplayId.get(displayId); return mutationId ? [mutationId] : []; }), [allocationMutationIdsByDisplayId, selection.selectedArray], ); // ─── View mode: grouped (default) vs flat ────────────────────────────────── const [viewMode, setViewMode] = useState<"grouped" | "flat">(() => { if (typeof window === "undefined") return "grouped"; return (localStorage.getItem("capakraken:allocations:viewMode") as "grouped" | "flat") ?? "grouped"; }); const [collapsedGroups, setCollapsedGroups] = useState( () => createInitialCollapsedAllocationGroups(), ); // Track expanded project sub-groups: key = "resourceId::projectId" const [expandedSubGroups, setExpandedSubGroups] = useState>(new Set()); const toggleViewMode = useCallback(() => { setViewMode((prev) => { const next = prev === "grouped" ? "flat" : "grouped"; localStorage.setItem("capakraken:allocations:viewMode", next); return next; }); }, []); type ProjectSubGroup = { projectId: string; projectName: string; projectCode: string; allocations: AllocationWithDetails[]; typicalHoursPerDay: number; earliestStart: Date; latestEnd: Date; }; type AllocGroup = { resourceId: string; resourceName: string; eid: string; chapter: string | null; allocations: AllocationWithDetails[]; projectSubGroups: ProjectSubGroup[]; }; const groups = useMemo(() => { const map = new Map(); for (const alloc of sorted) { const rid = alloc.resource?.id ?? "__unassigned__"; let group = map.get(rid); if (!group) { group = { resourceId: rid, resourceName: alloc.resource?.displayName ?? "Unassigned", eid: alloc.resource?.eid ?? "", chapter: (alloc.resource as { chapter?: string | null } | undefined)?.chapter ?? null, allocations: [], projectSubGroups: [], }; map.set(rid, group); } group.allocations.push(alloc); } // Build project sub-groups within each person group for (const group of map.values()) { const projMap = new Map(); for (const alloc of group.allocations) { const pid = alloc.project?.id ?? "__no_project__"; let list = projMap.get(pid); if (!list) { list = []; projMap.set(pid, list); } list.push(alloc); } group.projectSubGroups = [...projMap.entries()].map(([pid, allocs]) => { const first = allocs[0]!; let earliest = new Date(first.startDate); let latest = new Date(first.endDate); // Find the most common hoursPerDay value across allocations const hpdCounts = new Map(); for (const a of allocs) { const s = new Date(a.startDate); const e = new Date(a.endDate); if (s < earliest) earliest = s; if (e > latest) latest = e; hpdCounts.set(a.hoursPerDay, (hpdCounts.get(a.hoursPerDay) ?? 0) + 1); } // Pick the most frequent hoursPerDay; fall back to first let typicalH = first.hoursPerDay; let maxCount = 0; for (const [h, count] of hpdCounts) { if (count > maxCount) { typicalH = h; maxCount = count; } } return { projectId: pid, projectName: first.project?.name ?? "Unknown", projectCode: first.project?.shortCode ?? "", allocations: allocs, typicalHoursPerDay: typicalH, earliestStart: earliest, latestEnd: latest, }; }); group.projectSubGroups.sort((a, b) => a.projectName.localeCompare(b.projectName)); } const arr = [...map.values()]; arr.sort((a, b) => { if (a.resourceId === "__unassigned__") return 1; if (b.resourceId === "__unassigned__") return -1; return a.resourceName.localeCompare(b.resourceName); }); return arr; }, [sorted]); const groupIds = useMemo(() => groups.map((g) => g.resourceId), [groups]); const toggleGroup = useCallback((resourceId: string) => { setCollapsedGroups((prev) => toggleCollapsedAllocationGroup(prev, groupIds, resourceId)); }, [groupIds]); const collapseAll = useCallback(() => { setCollapsedGroups(collapseAllAllocationGroups()); }, []); const expandAll = useCallback(() => { setCollapsedGroups(expandAllAllocationGroups()); }, []); const toggleSubGroup = useCallback((resourceId: string, projectId: string) => { const key = `${resourceId}::${projectId}`; setExpandedSubGroups((prev) => { const next = new Set(prev); if (next.has(key)) next.delete(key); else next.add(key); return next; }); }, []); function handleSort(field: string) { if (field === "resource") { toggle("resource", (a) => a.resource?.displayName ?? null); } else if (field === "project") { toggle("project", (a) => a.project?.name ?? null); } else { toggle(field); } } function clearAll() { setFilterProjectId(""); setFilterResourceId(""); setFilterStatus(""); setHidePastProjects(false); setHideCompletedProjects(false); setHideDraftProjects(false); } const chips = [ ...(filterProjectId ? [{ label: `Project filter active`, onRemove: () => setFilterProjectId("") }] : []), ...(filterResourceId ? [{ label: `Resource filter active`, onRemove: () => setFilterResourceId("") }] : []), ...(filterStatus ? [{ label: `Status: ${filterStatus}`, onRemove: () => setFilterStatus("") }] : []), ...(hidePastProjects ? [{ label: "Hiding past projects", onRemove: () => setHidePastProjects(false) }] : []), ...(hideCompletedProjects ? [{ label: "Hiding completed/cancelled", onRemove: () => setHideCompletedProjects(false) }] : []), ...(hideDraftProjects ? [{ label: "Hiding draft projects", onRemove: () => setHideDraftProjects(false) }] : []), ]; function formatPeriod(alloc: AllocationWithDetails) { return formatDate(alloc.startDate) + " \u2192 " + formatDate(alloc.endDate); } function handleSingleDelete(allocation: AllocationWithDetails) { const id = getPlanningEntryMutationId(allocation); if (!allocation.resourceId) { deleteDemandMutation.mutate({ id }); return; } deleteAssignmentMutation.mutate({ id }); } const singleDeletePending = deleteDemandMutation.isPending || deleteAssignmentMutation.isPending; // colSpan for empty/loading states: checkbox + visible columns + actions const totalColSpan = 1 + visibleColumns.length + 1; function renderAllocRow(alloc: AllocationWithDetails, isGrouped = false, rowIndex = 0) { const isSelected = selection.selectedIds.has(alloc.id); const leftBorder = STATUS_LEFT_BORDER[alloc.status] ?? "border-l-gray-300"; return ( selection.toggle(alloc.id)} className="rounded border-gray-300 dark:border-gray-600" /> {visibleColumns.map((col) => { switch (col.key) { case "resource": return ( {isGrouped ? : (alloc.resource?.displayName ?? "—")} ); case "project": return ( {alloc.project ? ( <>{alloc.project.shortCode} {alloc.project.name} ) : "—"} ); case "role": return {alloc.role}; case "dates": return {formatPeriod(alloc)}; case "hoursPerDay": return {alloc.hoursPerDay}h; case "cost": return {(alloc.dailyCostCents / 100).toFixed(0)} €; case "status": return ( {alloc.status} ); default: return —; } })}
); } return (
setShowStatusToast(false)} />

Allocations

{isLoading ? "Loading…" : `${filteredAllocations.length} assignment${filteredAllocations.length !== 1 ? "s" : ""}${filteredDemands.length > 0 ? ` · ${filteredDemands.length} open demand${filteredDemands.length !== 1 ? "s" : ""}` : ""}`}

↓ PDF ↓ XLS
setFilterProjectId(id ?? "")} placeholder="Filter by project…" className="min-w-[280px]" /> setFilterResourceId(id ?? "")} placeholder="Filter by resource…" className="min-w-[180px]" /> {/* View mode toggle */}
{viewMode === "grouped" && groups.length > 1 && (
|
)}
{/* Filter chips */} {chips.length > 0 && (
)}
{visibleColumns.map((col) => { const tooltips: Record = { resource: { tip: "The person assigned to this time block. Grouped view clusters entries by resource." }, project: { tip: "The project this allocation belongs to, identified by short code and name." }, role: { tip: "The role this allocation was created for. May differ from the resource's primary role." }, dates: { tip: "Start and end date of this allocation period (inclusive)." }, hoursPerDay: { tip: "Planned working hours per calendar day for this allocation." }, cost: { tip: "Daily cost = resource LCR x hours per day. Total cost = daily cost x working days.", width: "w-72" }, status: { tip: "PROPOSED = requested · CONFIRMED = approved · ACTIVE = ongoing · COMPLETED = finished · CANCELLED = removed.", width: "w-72" }, }; const t = tooltips[col.key]; const fieldMap: Record = { dates: "startDate", hoursPerDay: "hoursPerDay", cost: "dailyCostCents" }; return ( ); })} {isLoading && ( )} {!isLoading && sorted.length === 0 && ( )} {!isLoading && viewMode === "flat" && sorted.map((alloc, index) => renderAllocRow(alloc, false, index))} {!isLoading && viewMode === "grouped" && groups.map((group) => { const isCollapsed = collapsedGroups === "all" || collapsedGroups.has(group.resourceId); const groupAllocIds = group.allocations.map((a) => a.id); const allGroupSelected = selection.isAllSelected(groupAllocIds); const groupIndeterminate = !allGroupSelected && groupAllocIds.some((id) => selection.selectedIds.has(id)); return ( {/* Group header */} toggleGroup(group.resourceId)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleGroup(group.resourceId); } }} tabIndex={0} role="button" aria-expanded={!isCollapsed} > {/* Project sub-groups within person */} {!isCollapsed && group.projectSubGroups.map((subGroup) => { const subKey = `${group.resourceId}::${subGroup.projectId}`; const isSubExpanded = expandedSubGroups.has(subKey); // Single allocation for this project — render directly, no sub-group header if (subGroup.allocations.length === 1) { return {renderAllocRow(subGroup.allocations[0]!, true, 0)}; } // Multiple allocations — show collapsible project sub-group return ( toggleSubGroup(group.resourceId, subGroup.projectId)} tabIndex={0} role="button" aria-expanded={isSubExpanded} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleSubGroup(group.resourceId, subGroup.projectId); } }} > {isSubExpanded && subGroup.allocations.map((alloc, idx) => renderAllocRow(alloc, true, idx))} ); })} ); })}
{ if (el) el.indeterminate = selection.isIndeterminate(allocationIds); }} onChange={() => selection.toggleAll(allocationIds)} className="rounded border-gray-300 dark:border-gray-600" />
Loading allocations…
No assignments found.
e.stopPropagation()}> { if (el) el.indeterminate = groupIndeterminate; }} onChange={() => selection.toggleAll(groupAllocIds)} className="rounded border-gray-300 dark:border-gray-600" />
{isCollapsed ? "▸" : "▾"} {group.resourceName} {group.eid && ( {group.eid} )} {group.chapter && ( · {group.chapter} )} {group.allocations.length}
e.stopPropagation()}> a.id))} ref={(el) => { if (el) { const ids = subGroup.allocations.map((a) => a.id); el.indeterminate = !selection.isAllSelected(ids) && ids.some((id) => selection.selectedIds.has(id)); } }} onChange={() => selection.toggleAll(subGroup.allocations.map((a) => a.id))} className="rounded border-gray-300 dark:border-gray-600" />
{isSubExpanded ? "▾" : "▸"} {subGroup.projectCode} {subGroup.projectName} {formatDate(subGroup.earliestStart)} → {formatDate(subGroup.latestEnd)} {subGroup.typicalHoursPerDay}h/day {subGroup.allocations.length}
{!isLoading && filteredDemands.length > 0 && (

Open Demands

Placeholder demand rows not yet assigned to a resource.

{filteredDemands.length} item{filteredDemands.length !== 1 ? "s" : ""}
{filteredDemands.map((demand) => (
{demand.project ? ( <>{demand.project.shortCode} {demand.project.name} ) : "Unknown project"}
{(demand.role ?? "Placeholder role")} · {formatPeriod(demand)} · {demand.hoursPerDay}h/day
Unfilled
{demand.unfilledHeadcount ?? demand.headcount} / {demand.requestedHeadcount ?? demand.headcount}
))}
)} {/* Batch Status Picker */} {batchStatusPicker && (
setBatchStatusPicker(false)}>
e.stopPropagation()}>

Set status for {selection.count} allocations

{ALL_ALLOC_STATUSES.map((s) => ( ))}
)} {/* Confirm single delete */} {confirmDelete?.single && ( { handleSingleDelete(confirmDelete.single!); setConfirmDelete(null); }} onCancel={() => setConfirmDelete(null)} /> )} {/* Confirm batch delete */} {confirmDelete?.ids && ( { batchDeleteMutation.mutate({ ids: confirmDelete.ids! }); setConfirmDelete(null); }} onCancel={() => setConfirmDelete(null)} /> )} {/* Confirm batch status */} {confirmBatchStatus && ( { batchStatusMutation.mutate({ ids: confirmBatchStatus.ids, status: confirmBatchStatus.status as never }); setConfirmBatchStatus(null); }} onCancel={() => setConfirmBatchStatus(null)} /> )} {/* Batch Action Bar */} setBatchStatusPicker(true), disabled: batchStatusMutation.isPending, }, { label: `Delete (${selection.count})`, variant: "danger", onClick: () => setConfirmDelete({ ids: selectedMutationIds }), disabled: batchDeleteMutation.isPending, }, ]} /> {/* Modal */} {modalOpen && ( )}
); }