feat: AI assistant (HartBOT), demand filling, budget-per-role, project favorites, and UX improvements
AI Assistant (HartBOT): - Chat panel with inline layout, session persistence, message history (up-arrow recall) - OpenAI function calling with 20+ tools (search, navigate, create/cancel allocations, update status) - RBAC-aware tool filtering, fuzzy search with word-level matching - Navigation actions (router.push) and data invalidation after mutations - Country/metro city/org unit/role filtering on resource search Demand Filling Enhancements: - Two-phase fill modal: plan multiple resources, then confirm & assign all at once - Availability preview per resource (available/partial/conflict days, existing bookings) - Coverage bar showing demand hours distribution across assigned resources - Fill demand from project detail page (new Assign button per demand) - Fixed: filled demands no longer shown on timeline, demand bars no longer overlap Budget per Role: - DemandRequirement.budgetCents field (schema + API + UI) - Project wizard step 3: budget input per role with allocation summary bar - Project detail: allocated vs booked budget per demand - Fill demand modal: role budget display with cost estimates - AllocationModal: budget field for demand editing Project Favorites: - User.favoriteProjectIds (JSONB) with toggle API - Star button on projects list and detail page (optimistic updates) - "My Projects" dashboard widget (favorites + responsible person projects) Project Management: - Edit project from detail page (ProjectModal integration) - Edit demands from detail page (AllocationModal integration) - Admin-only project deletion (cascades assignments + demands) - Create user accounts from admin panel Timeline Fixes: - Country multi-select filter with backend support - URL param sync for same-page navigation (AI assistant integration) - Demand lane stacking (no more overlapping bars) - Single-day booking resize handles (always visible, min 6px) - Single-day resize allowed (start === end) - "All Clients" toggle (select all / deselect all) Other Fixes: - crypto.randomUUID fallback for non-secure contexts - Chat message limit raised (200 max, client sends last 40) - Status dropdown portal (no longer clipped by table overflow) - Cents display restored in budget views (2 decimal places) - Allocations grouped view with project sub-groups (collapsed by default) - Server-side resource search for project wizard (no 500 limit) Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
@@ -36,6 +36,10 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
|
||||
const [roleId, setRoleId] = useState(allocation?.roleId ?? "");
|
||||
const [roleFreeText, setRoleFreeText] = useState(allocation?.role ?? "");
|
||||
const [headcount, setHeadcount] = useState(allocation?.headcount ?? 1);
|
||||
const [budgetEur, setBudgetEur] = useState(() => {
|
||||
const cents = (allocation as { budgetCents?: number } | undefined)?.budgetCents ?? 0;
|
||||
return cents > 0 ? String(cents / 100) : "";
|
||||
});
|
||||
const [startDate, setStartDate] = useState(toDateInputValue(allocation?.startDate));
|
||||
const [endDate, setEndDate] = useState(toDateInputValue(allocation?.endDate));
|
||||
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation?.hoursPerDay ?? 8);
|
||||
@@ -172,6 +176,7 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
|
||||
role: roleString,
|
||||
roleId: roleId || undefined,
|
||||
headcount: isDemandEntry ? headcount : 1,
|
||||
...(isDemandEntry && budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
|
||||
startDate: start,
|
||||
endDate: end,
|
||||
hoursPerDay,
|
||||
@@ -186,6 +191,7 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
|
||||
role: roleString,
|
||||
roleId: roleId || undefined,
|
||||
headcount,
|
||||
...(budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
|
||||
startDate: start,
|
||||
endDate: end,
|
||||
hoursPerDay,
|
||||
@@ -270,16 +276,30 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
|
||||
</div>
|
||||
</label>
|
||||
{isDemandEntry && (
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label>
|
||||
<input
|
||||
type="number"
|
||||
value={headcount}
|
||||
onChange={(e) => setHeadcount(Math.max(1, Number(e.target.value)))}
|
||||
min={1}
|
||||
max={50}
|
||||
className="w-16 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm text-center dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label>
|
||||
<input
|
||||
type="number"
|
||||
value={headcount}
|
||||
onChange={(e) => setHeadcount(Math.max(1, Number(e.target.value)))}
|
||||
min={1}
|
||||
max={50}
|
||||
className="w-16 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm text-center dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Budget (EUR):</label>
|
||||
<input
|
||||
type="number"
|
||||
value={budgetEur}
|
||||
onChange={(e) => setBudgetEur(e.target.value)}
|
||||
min={0}
|
||||
step={100}
|
||||
placeholder="0"
|
||||
className="w-28 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
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";
|
||||
@@ -22,6 +22,11 @@ import { useViewPrefs } from "~/hooks/useViewPrefs.js";
|
||||
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
|
||||
import { ALLOCATION_STATUS_BADGE as STATUS_BADGE } from "~/lib/status-styles.js";
|
||||
|
||||
/** 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" },
|
||||
@@ -168,6 +173,146 @@ export function AllocationsClient() {
|
||||
[allocationMutationIdsByDisplayId, selection.selectedArray],
|
||||
);
|
||||
|
||||
// ─── View mode: grouped (default) vs flat ──────────────────────────────────
|
||||
const [viewMode, setViewMode] = useState<"grouped" | "flat">(() => {
|
||||
if (typeof window === "undefined") return "grouped";
|
||||
return (localStorage.getItem("planarchy:allocations:viewMode") as "grouped" | "flat") ?? "grouped";
|
||||
});
|
||||
const [collapsedGroups, setCollapsedGroups] = useState<Set<string> | "all">("all");
|
||||
// Track expanded project sub-groups: key = "resourceId::projectId"
|
||||
const [expandedSubGroups, setExpandedSubGroups] = useState<Set<string>>(new Set());
|
||||
|
||||
const toggleViewMode = useCallback(() => {
|
||||
setViewMode((prev) => {
|
||||
const next = prev === "grouped" ? "flat" : "grouped";
|
||||
localStorage.setItem("planarchy: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<AllocGroup[]>(() => {
|
||||
const map = new Map<string, AllocGroup>();
|
||||
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<string, AllocationWithDetails[]>();
|
||||
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<number, number>();
|
||||
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) => {
|
||||
// "all" → expand just this one (materialize all IDs minus clicked)
|
||||
if (prev === "all") {
|
||||
const next = new Set(groupIds);
|
||||
next.delete(resourceId);
|
||||
return next;
|
||||
}
|
||||
const next = new Set(prev);
|
||||
if (next.has(resourceId)) next.delete(resourceId);
|
||||
else next.add(resourceId);
|
||||
return next;
|
||||
});
|
||||
}, [groupIds]);
|
||||
|
||||
const collapseAll = useCallback(() => {
|
||||
setCollapsedGroups("all");
|
||||
}, []);
|
||||
|
||||
const expandAll = useCallback(() => {
|
||||
setCollapsedGroups(new Set());
|
||||
}, []);
|
||||
|
||||
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);
|
||||
@@ -213,6 +358,74 @@ export function AllocationsClient() {
|
||||
|
||||
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) {
|
||||
const isSelected = selection.selectedIds.has(alloc.id);
|
||||
return (
|
||||
<tr key={alloc.id} className={`transition-colors hover:bg-gray-50/80 dark:hover:bg-gray-900/60 ${isSelected ? "bg-brand-50 dark:bg-brand-900/20" : ""}`}>
|
||||
<td className="px-4 py-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.toggle(alloc.id)}
|
||||
className="rounded border-gray-300 dark:border-gray-600"
|
||||
/>
|
||||
</td>
|
||||
{visibleColumns.map((col) => {
|
||||
switch (col.key) {
|
||||
case "resource":
|
||||
return (
|
||||
<td key={col.key} className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{isGrouped ? <span className="text-gray-400 dark:text-gray-500">↳</span> : (alloc.resource?.displayName ?? "—")}
|
||||
</td>
|
||||
);
|
||||
case "project":
|
||||
return (
|
||||
<td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300">
|
||||
{alloc.project ? (
|
||||
<><span className="font-mono text-xs">{alloc.project.shortCode}</span> {alloc.project.name}</>
|
||||
) : "—"}
|
||||
</td>
|
||||
);
|
||||
case "role":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300">{alloc.role}</td>;
|
||||
case "dates":
|
||||
return <td key={col.key} className="whitespace-nowrap px-4 py-3 text-xs text-gray-500 dark:text-gray-400">{formatPeriod(alloc)}</td>;
|
||||
case "hoursPerDay":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100">{alloc.hoursPerDay}h</td>;
|
||||
case "cost":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100">{(alloc.dailyCostCents / 100).toFixed(0)} €</td>;
|
||||
case "status":
|
||||
return (
|
||||
<td key={col.key} className="px-4 py-3">
|
||||
<span className={`inline-block px-2 py-0.5 text-xs rounded-full font-medium ${STATUS_BADGE[alloc.status] ?? "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"}`}>
|
||||
{alloc.status}
|
||||
</span>
|
||||
</td>
|
||||
);
|
||||
default:
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">—</td>;
|
||||
}
|
||||
})}
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button type="button" onClick={() => openEdit(alloc)} className="text-xs font-medium text-blue-600 hover:text-blue-800 hover:underline dark:text-blue-300 dark:hover:text-blue-200">Edit</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConfirmDelete({ single: alloc })}
|
||||
disabled={singleDeletePending}
|
||||
className="text-xs font-medium text-red-500 hover:text-red-700 hover:underline disabled:opacity-50 dark:text-red-300 dark:hover:text-red-200"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page space-y-5 pb-24">
|
||||
<div className="app-page-header gap-4">
|
||||
@@ -311,6 +524,42 @@ export function AllocationsClient() {
|
||||
onSetVisible={setVisible}
|
||||
defaultKeys={defaultKeys}
|
||||
/>
|
||||
|
||||
{/* View mode toggle */}
|
||||
<div className="flex items-center rounded-lg border border-gray-300 dark:border-gray-600 overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleViewMode}
|
||||
title="Grouped by person"
|
||||
className={`px-2.5 py-2 text-sm transition-colors ${viewMode === "grouped" ? "bg-brand-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800"}`}
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleViewMode}
|
||||
title="Flat list"
|
||||
className={`px-2.5 py-2 text-sm transition-colors ${viewMode === "flat" ? "bg-brand-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800"}`}
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{viewMode === "grouped" && groups.length > 1 && (
|
||||
<div className="flex items-center gap-1">
|
||||
<button type="button" onClick={expandAll} className="text-xs text-brand-600 hover:text-brand-800 dark:text-brand-400 dark:hover:text-brand-200 whitespace-nowrap">
|
||||
Expand all
|
||||
</button>
|
||||
<span className="text-gray-300 dark:text-gray-600">|</span>
|
||||
<button type="button" onClick={collapseAll} className="text-xs text-brand-600 hover:text-brand-800 dark:text-brand-400 dark:hover:text-brand-200 whitespace-nowrap">
|
||||
Collapse all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</FilterBar>
|
||||
|
||||
{/* Filter chips */}
|
||||
@@ -363,75 +612,128 @@ export function AllocationsClient() {
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{isLoading && (
|
||||
<tr>
|
||||
<td colSpan={9} className="py-12 text-center text-sm text-gray-500 dark:text-gray-400">Loading allocations…</td>
|
||||
<td colSpan={totalColSpan} className="py-12 text-center text-sm text-gray-500 dark:text-gray-400">Loading allocations…</td>
|
||||
</tr>
|
||||
)}
|
||||
|
||||
{!isLoading && sorted.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={9} className="py-12 text-center text-sm text-gray-500 dark:text-gray-400">No assignments found.</td>
|
||||
<td colSpan={totalColSpan} className="py-12 text-center text-sm text-gray-500 dark:text-gray-400">No assignments found.</td>
|
||||
</tr>
|
||||
)}
|
||||
|
||||
{!isLoading &&
|
||||
sorted.map((alloc) => {
|
||||
const isSelected = selection.selectedIds.has(alloc.id);
|
||||
{!isLoading && viewMode === "flat" &&
|
||||
sorted.map((alloc) => renderAllocRow(alloc))}
|
||||
|
||||
{!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 (
|
||||
<tr key={alloc.id} className={`transition-colors hover:bg-gray-50/80 dark:hover:bg-gray-900/60 ${isSelected ? "bg-brand-50 dark:bg-brand-900/20" : ""}`}>
|
||||
<td className="px-4 py-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.toggle(alloc.id)}
|
||||
className="rounded border-gray-300 dark:border-gray-600"
|
||||
/>
|
||||
</td>
|
||||
{visibleColumns.map((col) => {
|
||||
switch (col.key) {
|
||||
case "resource":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-gray-100">{alloc.resource?.displayName ?? "—"}</td>;
|
||||
case "project":
|
||||
return (
|
||||
<td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300">
|
||||
{alloc.project ? (
|
||||
<><span className="font-mono text-xs">{alloc.project.shortCode}</span> {alloc.project.name}</>
|
||||
) : "—"}
|
||||
</td>
|
||||
);
|
||||
case "role":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300">{alloc.role}</td>;
|
||||
case "dates":
|
||||
return <td key={col.key} className="whitespace-nowrap px-4 py-3 text-xs text-gray-500 dark:text-gray-400">{formatPeriod(alloc)}</td>;
|
||||
case "hoursPerDay":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100">{alloc.hoursPerDay}h</td>;
|
||||
case "cost":
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100">{(alloc.dailyCostCents / 100).toFixed(0)} €</td>;
|
||||
case "status":
|
||||
return (
|
||||
<td key={col.key} className="px-4 py-3">
|
||||
<span className={`inline-block px-2 py-0.5 text-xs rounded-full font-medium ${STATUS_BADGE[alloc.status] ?? "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"}`}>
|
||||
{alloc.status}
|
||||
</span>
|
||||
</td>
|
||||
);
|
||||
default:
|
||||
return <td key={col.key} className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">—</td>;
|
||||
<GroupRows key={group.resourceId}>
|
||||
{/* Group header */}
|
||||
<tr
|
||||
className="bg-gray-50 dark:bg-gray-800/50 cursor-pointer select-none hover:bg-gray-100 dark:hover:bg-gray-800/80 transition-colors"
|
||||
onClick={() => toggleGroup(group.resourceId)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleGroup(group.resourceId); } }}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-expanded={!isCollapsed}
|
||||
>
|
||||
<td className="px-4 py-2.5" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allGroupSelected}
|
||||
ref={(el) => { if (el) el.indeterminate = groupIndeterminate; }}
|
||||
onChange={() => selection.toggleAll(groupAllocIds)}
|
||||
className="rounded border-gray-300 dark:border-gray-600"
|
||||
/>
|
||||
</td>
|
||||
<td colSpan={visibleColumns.length + 1} className="px-4 py-2.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-gray-400 dark:text-gray-500 text-xs">
|
||||
{isCollapsed ? "▸" : "▾"}
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{group.resourceName}
|
||||
</span>
|
||||
{group.eid && (
|
||||
<span className="text-xs font-mono text-gray-400 dark:text-gray-500">
|
||||
{group.eid}
|
||||
</span>
|
||||
)}
|
||||
{group.chapter && (
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
· {group.chapter}
|
||||
</span>
|
||||
)}
|
||||
<span className="inline-flex items-center rounded-full bg-gray-200 px-2 py-0.5 text-xs font-medium text-gray-600 dark:bg-gray-700 dark:text-gray-300">
|
||||
{group.allocations.length}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/* 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 <GroupRows key={subKey}>{renderAllocRow(subGroup.allocations[0]!, true)}</GroupRows>;
|
||||
}
|
||||
|
||||
// Multiple allocations — show collapsible project sub-group
|
||||
return (
|
||||
<GroupRows key={subKey}>
|
||||
<tr
|
||||
className="bg-gray-25 dark:bg-gray-850/30 cursor-pointer select-none hover:bg-gray-100/60 dark:hover:bg-gray-800/40 transition-colors"
|
||||
onClick={() => 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); } }}
|
||||
>
|
||||
<td className="px-4 py-2" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selection.isAllSelected(subGroup.allocations.map((a) => 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"
|
||||
/>
|
||||
</td>
|
||||
<td colSpan={visibleColumns.length + 1} className="px-4 py-2">
|
||||
<div className="flex items-center gap-2 pl-4">
|
||||
<span className="text-gray-400 dark:text-gray-500 text-xs">
|
||||
{isSubExpanded ? "▾" : "▸"}
|
||||
</span>
|
||||
<span className="font-mono text-xs text-gray-400 dark:text-gray-500">{subGroup.projectCode}</span>
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">{subGroup.projectName}</span>
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">
|
||||
{formatDate(subGroup.earliestStart)} → {formatDate(subGroup.latestEnd)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{subGroup.typicalHoursPerDay}h/day
|
||||
</span>
|
||||
<span className="inline-flex items-center rounded-full bg-gray-200 px-1.5 py-0.5 text-[10px] font-medium text-gray-500 dark:bg-gray-700 dark:text-gray-400">
|
||||
{subGroup.allocations.length}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{isSubExpanded && subGroup.allocations.map((alloc) => renderAllocRow(alloc, true))}
|
||||
</GroupRows>
|
||||
);
|
||||
})}
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<button type="button" onClick={() => openEdit(alloc)} className="text-xs font-medium text-blue-600 hover:text-blue-800 hover:underline dark:text-blue-300 dark:hover:text-blue-200">Edit</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConfirmDelete({ single: alloc })}
|
||||
disabled={singleDeletePending}
|
||||
className="text-xs font-medium text-red-500 hover:text-red-700 hover:underline disabled:opacity-50 dark:text-red-300 dark:hover:text-red-200"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</GroupRows>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { useRef, useState, useMemo, useCallback } from "react";
|
||||
import { AllocationStatus } from "@planarchy/shared";
|
||||
import { useFocusTrap } from "~/hooks/useFocusTrap.js";
|
||||
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
|
||||
@@ -17,6 +17,7 @@ interface OpenDemandAllocation {
|
||||
startDate: Date | string;
|
||||
endDate: Date | string;
|
||||
hoursPerDay: number;
|
||||
budgetCents?: number;
|
||||
roleEntity?: { id: string; name: string; color: string | null } | null;
|
||||
project?: { id: string; name: string; shortCode: string };
|
||||
}
|
||||
@@ -27,159 +28,478 @@ interface FillOpenDemandModalProps {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function formatDate(date: Date | string): string {
|
||||
/** A planned (not yet submitted) resource assignment. */
|
||||
interface PlannedResource {
|
||||
resourceId: string;
|
||||
resourceName: string;
|
||||
eid: string;
|
||||
hoursPerDay: number;
|
||||
availableHours: number;
|
||||
availableDays: number;
|
||||
conflictDays: number;
|
||||
coveragePercent: number;
|
||||
estimatedCostCents: number;
|
||||
}
|
||||
|
||||
function fmtDate(date: Date | string): string {
|
||||
const d = typeof date === "string" ? new Date(date) : date;
|
||||
return d.toLocaleDateString("en-GB", { year: "numeric", month: "short", day: "numeric" });
|
||||
}
|
||||
|
||||
export function FillOpenDemandModal({ allocation, onClose, onSuccess }: FillOpenDemandModalProps) {
|
||||
// ─── Phase: "plan" (select resources) → "confirm" (review & submit) ──
|
||||
const [phase, setPhase] = useState<"plan" | "confirm">("plan");
|
||||
const [planned, setPlanned] = useState<PlannedResource[]>([]);
|
||||
|
||||
// Planning phase state
|
||||
const [resourceId, setResourceId] = useState("");
|
||||
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation.hoursPerDay);
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
// Submit phase state
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitProgress, setSubmitProgress] = useState(0);
|
||||
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
useFocusTrap(panelRef, true);
|
||||
|
||||
const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
function handleSearchChange(value: string) {
|
||||
setSearch(value);
|
||||
clearTimeout(searchTimerRef.current);
|
||||
searchTimerRef.current = setTimeout(() => setDebouncedSearch(value), 200);
|
||||
}
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
const invalidatePlanningViews = async () => {
|
||||
const invalidatePlanningViews = useCallback(async () => {
|
||||
await utils.allocation.list.invalidate();
|
||||
await utils.allocation.listView.invalidate();
|
||||
await utils.timeline.getEntries.invalidate();
|
||||
await utils.timeline.getEntriesView.invalidate();
|
||||
await utils.timeline.getProjectContext.invalidate();
|
||||
await utils.timeline.getBudgetStatus.invalidate();
|
||||
};
|
||||
}, [utils]);
|
||||
|
||||
const { data: resources } = trpc.resource.list.useQuery(
|
||||
{ isActive: true, search: search || undefined, limit: 100 },
|
||||
{ isActive: true, search: debouncedSearch || undefined, limit: 50 },
|
||||
{ staleTime: 15_000 },
|
||||
) as { data: { resources: Array<{ id: string; displayName: string; eid: string }> } | undefined };
|
||||
) as { data: { resources: Array<{ id: string; displayName: string; eid: string; lcrCents: number }> } | undefined };
|
||||
|
||||
const fillOpenDemandMutation = trpc.allocation.fillOpenDemandByAllocation.useMutation({
|
||||
onSuccess: async () => {
|
||||
await invalidatePlanningViews();
|
||||
onSuccess();
|
||||
const availabilityQuery = trpc.allocation.checkResourceAvailability.useQuery(
|
||||
{
|
||||
resourceId,
|
||||
startDate: new Date(allocation.startDate),
|
||||
endDate: new Date(allocation.endDate),
|
||||
hoursPerDay,
|
||||
},
|
||||
onError: (err) => setServerError(err.message),
|
||||
});
|
||||
{ enabled: !!resourceId && phase === "plan", staleTime: 10_000 },
|
||||
);
|
||||
|
||||
const fillMutation = trpc.allocation.fillOpenDemandByAllocation.useMutation();
|
||||
|
||||
const roleName = allocation.roleEntity?.name ?? allocation.role ?? "Unknown Role";
|
||||
const roleColor = allocation.roleEntity?.color ?? "#6366f1";
|
||||
|
||||
const resourceList = resources?.resources ?? [];
|
||||
const isPending = fillOpenDemandMutation.isPending;
|
||||
const avail = availabilityQuery.data;
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!resourceId) {
|
||||
setServerError("Please select a resource.");
|
||||
return;
|
||||
const totalDemandHours = useMemo(() => {
|
||||
let workingDays = 0;
|
||||
const d = new Date(allocation.startDate);
|
||||
const end = new Date(allocation.endDate);
|
||||
while (d <= end) {
|
||||
if (d.getDay() !== 0 && d.getDay() !== 6) workingDays++;
|
||||
d.setDate(d.getDate() + 1);
|
||||
}
|
||||
fillOpenDemandMutation.mutate({
|
||||
allocationId: getPlanningEntryMutationId(allocation),
|
||||
resourceId,
|
||||
return workingDays * allocation.hoursPerDay;
|
||||
}, [allocation.startDate, allocation.endDate, allocation.hoursPerDay]);
|
||||
|
||||
const consumedHours = planned.reduce((sum, r) => sum + r.availableHours, 0);
|
||||
const remainingHours = Math.max(0, totalDemandHours - consumedHours);
|
||||
|
||||
// ─── Planning phase actions ──────────────────────────────────────────
|
||||
function addToPlan() {
|
||||
if (!resourceId || !avail) return;
|
||||
const selectedResource = resourceList.find((r) => r.id === resourceId);
|
||||
if (!selectedResource) return;
|
||||
|
||||
// Estimated cost = LCR * available hours
|
||||
const lcrCents = selectedResource.lcrCents ?? 0;
|
||||
const estimatedCostCents = Math.round(lcrCents * avail.totalAvailableHours);
|
||||
|
||||
setPlanned((prev) => [...prev, {
|
||||
resourceId: selectedResource.id,
|
||||
resourceName: selectedResource.displayName,
|
||||
eid: selectedResource.eid,
|
||||
hoursPerDay,
|
||||
status: AllocationStatus.PROPOSED,
|
||||
});
|
||||
availableHours: avail.totalAvailableHours,
|
||||
availableDays: avail.availableDays,
|
||||
conflictDays: avail.conflictDays,
|
||||
coveragePercent: avail.coveragePercent,
|
||||
estimatedCostCents,
|
||||
}]);
|
||||
|
||||
// Reset for next resource
|
||||
setResourceId("");
|
||||
setSearch("");
|
||||
setDebouncedSearch("");
|
||||
setHoursPerDay(allocation.hoursPerDay);
|
||||
}
|
||||
|
||||
function removeFromPlan(rid: string) {
|
||||
setPlanned((prev) => prev.filter((r) => r.resourceId !== rid));
|
||||
}
|
||||
|
||||
// ─── Confirm phase: submit all planned resources sequentially ────────
|
||||
async function handleConfirmSubmit() {
|
||||
setSubmitting(true);
|
||||
setServerError(null);
|
||||
setSubmitProgress(0);
|
||||
|
||||
const allocationId = getPlanningEntryMutationId(allocation);
|
||||
|
||||
for (let i = 0; i < planned.length; i++) {
|
||||
const p = planned[i]!;
|
||||
setSubmitProgress(i + 1);
|
||||
try {
|
||||
await fillMutation.mutateAsync({
|
||||
allocationId,
|
||||
resourceId: p.resourceId,
|
||||
hoursPerDay: p.hoursPerDay,
|
||||
status: AllocationStatus.PROPOSED,
|
||||
});
|
||||
} catch (err) {
|
||||
setServerError(`Failed to assign ${p.resourceName}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await invalidatePlanningViews();
|
||||
setSubmitting(false);
|
||||
onSuccess();
|
||||
}
|
||||
|
||||
const isAlreadyPlanned = (rid: string) => planned.some((p) => p.resourceId === rid);
|
||||
|
||||
// ─── Render ──────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-50 flex items-start justify-center overflow-y-auto py-8"
|
||||
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
||||
onClick={(e) => { if (e.target === e.currentTarget && !submitting) onClose(); }}
|
||||
>
|
||||
<div
|
||||
ref={panelRef}
|
||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md mx-4"
|
||||
onKeyDown={(e) => { if (e.key === "Escape") onClose(); }}
|
||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg mx-4"
|
||||
onKeyDown={(e) => { if (e.key === "Escape" && !submitting) onClose(); }}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Assign Open Demand</h2>
|
||||
<button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-xl leading-none">×</button>
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{phase === "plan" ? "Plan Demand Assignment" : "Confirm Assignments"}
|
||||
</h2>
|
||||
<button type="button" onClick={onClose} disabled={submitting} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-xl leading-none disabled:opacity-30">×</button>
|
||||
</div>
|
||||
|
||||
<div className="px-6 pt-4 pb-2">
|
||||
<div className="px-6 pt-4 pb-2 space-y-3">
|
||||
{/* Demand summary */}
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3 mb-4 flex items-start gap-3">
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3 flex items-start gap-3">
|
||||
<div className="w-3 h-3 rounded-full mt-1 flex-shrink-0" style={{ backgroundColor: roleColor }} />
|
||||
<div>
|
||||
<div className="flex-1">
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100">{roleName}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
{allocation.project?.name} · {formatDate(allocation.startDate)} – {formatDate(allocation.endDate)}
|
||||
{allocation.project?.name} · {fmtDate(allocation.startDate)} – {fmtDate(allocation.endDate)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{allocation.hoursPerDay}h/day · {totalDemandHours.toLocaleString()}h total
|
||||
{allocation.budgetCents && allocation.budgetCents > 0 ? ` · Budget: ${(allocation.budgetCents / 100).toLocaleString("de-DE")} EUR` : ""}
|
||||
</div>
|
||||
{allocation.headcount > 1 && (
|
||||
<div className="text-xs text-amber-600 mt-0.5">
|
||||
{allocation.headcount} slots remaining — assigning one resource
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Coverage bar */}
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3">
|
||||
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 mb-1.5">
|
||||
<span>Demand coverage</span>
|
||||
<span>{Math.round(consumedHours)}h / {totalDemandHours}h ({totalDemandHours > 0 ? Math.round((consumedHours / totalDemandHours) * 100) : 0}%)</span>
|
||||
</div>
|
||||
<div className="w-full h-2.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden flex">
|
||||
{planned.map((r, i) => (
|
||||
<div
|
||||
key={r.resourceId}
|
||||
className="h-full transition-all"
|
||||
style={{
|
||||
width: `${Math.min(100, (r.availableHours / totalDemandHours) * 100)}%`,
|
||||
backgroundColor: `hsl(${(i * 60 + 200) % 360}, 60%, 55%)`,
|
||||
}}
|
||||
title={`${r.resourceName}: ${Math.round(r.availableHours)}h`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Planned resources list */}
|
||||
{planned.length > 0 && (
|
||||
<div className="mt-2 space-y-1">
|
||||
{planned.map((r, i) => (
|
||||
<div key={r.resourceId} className="flex items-center gap-2 text-xs group">
|
||||
<div className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: `hsl(${(i * 60 + 200) % 360}, 60%, 55%)` }} />
|
||||
<span className="text-gray-700 dark:text-gray-300 font-medium">{r.resourceName}</span>
|
||||
<span className="text-gray-400">({r.eid})</span>
|
||||
<span className="text-gray-500">{r.hoursPerDay}h/day</span>
|
||||
<span className="ml-auto text-gray-500">{Math.round(r.availableHours)}h · {r.coveragePercent}%</span>
|
||||
{phase === "plan" && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeFromPlan(r.resourceId)}
|
||||
className="text-red-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="Remove"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{remainingHours > 0 && (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<div className="w-2 h-2 rounded-full bg-gray-300 dark:bg-gray-600 flex-shrink-0" />
|
||||
<span className="text-amber-600 dark:text-amber-400 font-medium">Remaining: {Math.round(remainingHours)}h</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="px-6 pb-5 space-y-4">
|
||||
{/* Resource search */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Search Resource
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or EID…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Assign Resource <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={resourceId}
|
||||
onChange={(e) => setResourceId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
required
|
||||
size={Math.min(6, Math.max(3, resourceList.length))}
|
||||
>
|
||||
<option value="">Select a resource…</option>
|
||||
{resourceList.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.displayName} ({r.eid})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Hours / Day</label>
|
||||
<input
|
||||
type="number"
|
||||
value={hoursPerDay}
|
||||
onChange={(e) => setHoursPerDay(Number(e.target.value))}
|
||||
min={0.5}
|
||||
max={8}
|
||||
step={0.5}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{serverError && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-400">
|
||||
{serverError}
|
||||
{/* ─── PLAN PHASE: add resources ──────────────────────────────── */}
|
||||
{phase === "plan" && (
|
||||
<div className="px-6 pb-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Search Resource</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or EID..."
|
||||
value={search}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-end gap-3 pt-2">
|
||||
<button type="button" onClick={onClose} disabled={isPending} className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 disabled:opacity-50">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" disabled={isPending || !resourceId} className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50">
|
||||
{isPending ? "Assigning…" : "Create Assignment"}
|
||||
</button>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Select Resource</label>
|
||||
<select
|
||||
value={resourceId}
|
||||
onChange={(e) => setResourceId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
size={Math.min(6, Math.max(3, resourceList.length))}
|
||||
>
|
||||
<option value="">Select a resource...</option>
|
||||
{resourceList.map((r) => {
|
||||
const alreadyPlanned = isAlreadyPlanned(r.id);
|
||||
return (
|
||||
<option key={r.id} value={r.id} disabled={alreadyPlanned}>
|
||||
{r.displayName} ({r.eid}){alreadyPlanned ? " (planned)" : ""}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Hours / Day</label>
|
||||
<input
|
||||
type="number"
|
||||
value={hoursPerDay}
|
||||
onChange={(e) => setHoursPerDay(Number(e.target.value))}
|
||||
min={0.5}
|
||||
max={24}
|
||||
step={0.5}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Availability preview */}
|
||||
{resourceId && avail && (
|
||||
<div className={`rounded-lg p-3 border text-sm ${
|
||||
avail.coveragePercent >= 100
|
||||
? "bg-green-50 border-green-200 dark:bg-green-900/20 dark:border-green-800"
|
||||
: avail.coveragePercent >= 50
|
||||
? "bg-amber-50 border-amber-200 dark:bg-amber-900/20 dark:border-amber-800"
|
||||
: "bg-red-50 border-red-200 dark:bg-red-900/20 dark:border-red-800"
|
||||
}`}>
|
||||
<div className="font-medium text-gray-900 dark:text-gray-100 mb-1.5">
|
||||
Availability: {avail.resource.name}
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-xs">
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">Available</span>
|
||||
<div className="font-semibold text-green-700 dark:text-green-400">{avail.availableDays} days</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">Conflicts</span>
|
||||
<div className="font-semibold text-red-700 dark:text-red-400">{avail.conflictDays} days</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">Hours</span>
|
||||
<div className="font-semibold text-gray-900 dark:text-gray-100">{avail.totalAvailableHours}h / {avail.totalRequestedHours}h</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{avail.existingAssignments.length > 0 && (
|
||||
<div className="mt-2 pt-2 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mb-1">Existing bookings:</div>
|
||||
{avail.existingAssignments.slice(0, 4).map((a, i) => (
|
||||
<div key={i} className="text-xs text-gray-600 dark:text-gray-300">
|
||||
{a.code} · {a.hoursPerDay}h/day · {a.start} – {a.end}
|
||||
</div>
|
||||
))}
|
||||
{avail.existingAssignments.length > 4 && (
|
||||
<div className="text-xs text-gray-400">+{avail.existingAssignments.length - 4} more</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{resourceId && availabilityQuery.isLoading && (
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500 animate-pulse">Checking availability...</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="flex items-center justify-between gap-3 pt-2">
|
||||
<button type="button" onClick={onClose} className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100">
|
||||
Cancel
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={addToPlan}
|
||||
disabled={!resourceId || !avail || isAlreadyPlanned(resourceId)}
|
||||
className="px-4 py-2 border border-brand-600 text-brand-600 rounded-lg hover:bg-brand-50 dark:hover:bg-brand-900/20 text-sm font-medium disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
+ Add to Plan
|
||||
</button>
|
||||
{planned.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase("confirm")}
|
||||
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium"
|
||||
>
|
||||
Review ({planned.length})
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* ─── CONFIRM PHASE: review & submit all ────────────────────── */}
|
||||
{phase === "confirm" && (
|
||||
<div className="px-6 pb-5 space-y-4">
|
||||
<div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400">Resource</th>
|
||||
<th className="px-3 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">h/day</th>
|
||||
<th className="px-3 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">Hours</th>
|
||||
<th className="px-3 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">Est. Cost</th>
|
||||
<th className="px-3 py-2 text-right text-xs font-medium text-gray-500 dark:text-gray-400">Coverage</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{planned.map((r) => (
|
||||
<tr key={r.resourceId}>
|
||||
<td className="px-3 py-2 font-medium text-gray-900 dark:text-gray-100">
|
||||
{r.resourceName}
|
||||
<span className="ml-1 text-xs text-gray-400 font-mono">{r.eid}</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600 dark:text-gray-300">{r.hoursPerDay}h</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600 dark:text-gray-300">{Math.round(r.availableHours)}h</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600 dark:text-gray-300">{(r.estimatedCostCents / 100).toLocaleString("de-DE")} EUR</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<span className={`font-medium ${r.coveragePercent >= 100 ? "text-green-600" : r.coveragePercent >= 50 ? "text-amber-600" : "text-red-600"}`}>
|
||||
{r.coveragePercent}%
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<td className="px-3 py-2 text-xs font-semibold text-gray-700 dark:text-gray-300">Total</td>
|
||||
<td className="px-3 py-2" />
|
||||
<td className="px-3 py-2 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">
|
||||
{Math.round(consumedHours)}h / {totalDemandHours}h
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">
|
||||
{(planned.reduce((s, r) => s + r.estimatedCostCents, 0) / 100).toLocaleString("de-DE")} EUR
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">
|
||||
{totalDemandHours > 0 ? Math.round((consumedHours / totalDemandHours) * 100) : 0}%
|
||||
</td>
|
||||
</tr>
|
||||
{allocation.budgetCents && allocation.budgetCents > 0 && (
|
||||
<tr>
|
||||
<td colSpan={3} className="px-3 py-1.5 text-right text-xs text-gray-500 dark:text-gray-400">Role Budget:</td>
|
||||
<td className="px-3 py-1.5 text-right text-xs font-semibold text-gray-700 dark:text-gray-300">
|
||||
{(allocation.budgetCents / 100).toLocaleString("de-DE")} EUR
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-right text-xs">
|
||||
{(() => {
|
||||
const totalCost = planned.reduce((s, r) => s + r.estimatedCostCents, 0);
|
||||
const remain = allocation.budgetCents! - totalCost;
|
||||
return (
|
||||
<span className={remain < 0 ? "text-red-600 font-medium" : "text-green-600"}>
|
||||
{remain < 0 ? `${(Math.abs(remain) / 100).toLocaleString("de-DE")} over` : `${(remain / 100).toLocaleString("de-DE")} left`}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{remainingHours > 0 && (
|
||||
<div className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded-lg px-3 py-2 border border-amber-200 dark:border-amber-800">
|
||||
{Math.round(remainingHours)}h remain uncovered. You can add more resources or assign partially.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{submitting && (
|
||||
<div className="text-sm text-brand-600 dark:text-brand-400 animate-pulse">
|
||||
Assigning resource {submitProgress}/{planned.length}...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{serverError && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-400">
|
||||
{serverError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhase("plan")}
|
||||
disabled={submitting}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 disabled:opacity-50"
|
||||
>
|
||||
Back to Planning
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleConfirmSubmit()}
|
||||
disabled={submitting || planned.length === 0}
|
||||
className="px-5 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-semibold disabled:opacity-50"
|
||||
>
|
||||
{submitting ? `Assigning ${submitProgress}/${planned.length}...` : `Confirm & Assign ${planned.length} Resource${planned.length !== 1 ? "s" : ""}`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user