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:
2026-03-16 15:31:48 +01:00
parent f5551e33c7
commit b0e55786c3
44 changed files with 4516 additions and 609 deletions
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState, useEffect, useCallback, useMemo, useRef } from "react"; import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { createPortal } from "react-dom";
import { formatDate } from "~/lib/format.js"; import { formatDate } from "~/lib/format.js";
import type { Project, ColumnDef } from "@planarchy/shared"; import type { Project, ColumnDef } from "@planarchy/shared";
import { ProjectStatus, PROJECT_COLUMNS, BlueprintTarget } from "@planarchy/shared"; import { ProjectStatus, PROJECT_COLUMNS, BlueprintTarget } from "@planarchy/shared";
@@ -80,7 +81,9 @@ function BudgetBar({ utilizationPercent, budgetCents }: { utilizationPercent: nu
function StatusDropdown({ project, isOpen, onOpen, onClose }: { project: ProjectRow; isOpen: boolean; onOpen: () => void; onClose: () => void }) { function StatusDropdown({ project, isOpen, onOpen, onClose }: { project: ProjectRow; isOpen: boolean; onOpen: () => void; onClose: () => void }) {
const utils = trpc.useUtils(); const utils = trpc.useUtils();
const dropdownRef = useRef<HTMLDivElement>(null); const triggerRef = useRef<HTMLButtonElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState({ top: 0, left: 0 });
const updateStatus = trpc.project.updateStatus.useMutation({ const updateStatus = trpc.project.updateStatus.useMutation({
onSuccess: async () => { onSuccess: async () => {
@@ -89,18 +92,29 @@ function StatusDropdown({ project, isOpen, onOpen, onClose }: { project: Project
}, },
}); });
// Position the portal dropdown below the trigger button
useEffect(() => {
if (!isOpen || !triggerRef.current) return;
const rect = triggerRef.current.getBoundingClientRect();
setPos({ top: rect.bottom + 4, left: rect.left });
}, [isOpen]);
useEffect(() => { useEffect(() => {
if (!isOpen) return; if (!isOpen) return;
function handleOutsideClick(e: MouseEvent) { function handleOutsideClick(e: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) onClose(); const target = e.target as Node;
if (triggerRef.current?.contains(target)) return;
if (panelRef.current?.contains(target)) return;
onClose();
} }
document.addEventListener("mousedown", handleOutsideClick); document.addEventListener("mousedown", handleOutsideClick);
return () => document.removeEventListener("mousedown", handleOutsideClick); return () => document.removeEventListener("mousedown", handleOutsideClick);
}, [isOpen, onClose]); }, [isOpen, onClose]);
return ( return (
<div className="relative" ref={dropdownRef}> <>
<button <button
ref={triggerRef}
type="button" type="button"
onClick={(e) => { e.stopPropagation(); isOpen ? onClose() : onOpen(); }} onClick={(e) => { e.stopPropagation(); isOpen ? onClose() : onOpen(); }}
className={clsx( className={clsx(
@@ -114,8 +128,12 @@ function StatusDropdown({ project, isOpen, onOpen, onClose }: { project: Project
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg> </svg>
</button> </button>
{isOpen && ( {isOpen && createPortal(
<div className="absolute left-0 top-full z-20 mt-2 min-w-[160px] rounded-2xl border border-gray-200 bg-white p-2 shadow-xl dark:border-gray-700 dark:bg-gray-900"> <div
ref={panelRef}
className="fixed z-[9999] min-w-[160px] rounded-2xl border border-gray-200 bg-white p-2 shadow-xl dark:border-gray-700 dark:bg-gray-900"
style={{ top: pos.top, left: pos.left }}
>
{ALL_STATUSES.map((s) => ( {ALL_STATUSES.map((s) => (
<button <button
key={s.value} key={s.value}
@@ -134,9 +152,10 @@ function StatusDropdown({ project, isOpen, onOpen, onClose }: { project: Project
</span> </span>
</button> </button>
))} ))}
</div> </div>,
document.body,
)} )}
</div> </>
); );
} }
@@ -182,6 +201,34 @@ export function ProjectsClient() {
}, },
}); });
// ─── Favorites ──────────────────────────────────────────────────────────
const { data: favoriteIds } = trpc.user.getFavoriteProjectIds.useQuery(undefined, { staleTime: 30_000 });
const favSet = useMemo(() => new Set(favoriteIds ?? []), [favoriteIds]);
const toggleFavMutation = trpc.user.toggleFavoriteProject.useMutation({
onMutate: async ({ projectId }) => {
// Cancel any outgoing refetches so they don't overwrite optimistic update
await utils.user.getFavoriteProjectIds.cancel();
// Snapshot previous value
const previous = utils.user.getFavoriteProjectIds.getData();
// Optimistically update the cache
const current = previous ?? [];
const next = current.includes(projectId)
? current.filter((id: string) => id !== projectId)
: [...current, projectId];
utils.user.getFavoriteProjectIds.setData(undefined, next);
return { previous };
},
onError: (_err, _vars, context) => {
// Rollback on error
if (context?.previous !== undefined) {
utils.user.getFavoriteProjectIds.setData(undefined, context.previous);
}
},
onSettled: () => {
void utils.user.getFavoriteProjectIds.invalidate();
},
});
// ─── Custom field columns from global blueprints ────────────────────────── // ─── Custom field columns from global blueprints ──────────────────────────
const { data: globalFieldDefs } = trpc.blueprint.getGlobalFieldDefs.useQuery( const { data: globalFieldDefs } = trpc.blueprint.getGlobalFieldDefs.useQuery(
{ target: BlueprintTarget.PROJECT }, { target: BlueprintTarget.PROJECT },
@@ -490,6 +537,7 @@ export function ProjectsClient() {
<tr> <tr>
{/* Drag handle column */} {/* Drag handle column */}
<th className="w-8 px-2" /> <th className="w-8 px-2" />
<th className="w-8 px-2" />
<th className="px-4 py-3 w-10"> <th className="px-4 py-3 w-10">
<input <input
type="checkbox" type="checkbox"
@@ -518,6 +566,16 @@ export function ProjectsClient() {
onDrop={(draggedId) => reorder(draggedId, project.id)} onDrop={(draggedId) => reorder(draggedId, project.id)}
className={`transition-colors hover:bg-gray-50/80 dark:hover:bg-gray-900/60 ${isSelected ? "bg-brand-50 dark:bg-brand-900/20" : ""}`} 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-2 py-3 w-8">
<button
type="button"
onClick={(e) => { e.stopPropagation(); e.preventDefault(); toggleFavMutation.mutate({ projectId: project.id }); }}
className={`text-sm transition-colors ${favSet.has(project.id) ? "text-amber-500 hover:text-amber-600" : "text-gray-300 hover:text-amber-400 dark:text-gray-600 dark:hover:text-amber-500"}`}
title={favSet.has(project.id) ? "Remove from favorites" : "Add to favorites"}
>
{favSet.has(project.id) ? "★" : "☆"}
</button>
</td>
<td className="px-4 py-3"> <td className="px-4 py-3">
<input <input
type="checkbox" type="checkbox"
+12 -61
View File
@@ -3,6 +3,8 @@ import { formatDate } from "~/lib/format.js";
import Link from "next/link"; import Link from "next/link";
import { createCaller } from "~/server/trpc.js"; import { createCaller } from "~/server/trpc.js";
import { BudgetStatusCard } from "~/components/projects/BudgetStatusCard.js"; import { BudgetStatusCard } from "~/components/projects/BudgetStatusCard.js";
import { ProjectDetailActions } from "~/components/projects/ProjectDetailClient.js";
import { ProjectDemandsTable } from "~/components/projects/ProjectDemandsTable.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js"; import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
interface ProjectDetailPageProps { interface ProjectDetailPageProps {
@@ -75,7 +77,8 @@ export default async function ProjectDetailPage({ params }: ProjectDetailPagePro
</div> </div>
<h1 className="text-2xl font-bold text-gray-900">{project.name}</h1> <h1 className="text-2xl font-bold text-gray-900">{project.name}</h1>
</div> </div>
<div className="text-right text-sm text-gray-500 flex-shrink-0"> <div className="flex items-start gap-4 flex-shrink-0">
<div className="text-right text-sm text-gray-500">
<div className="font-medium text-gray-800"> <div className="font-medium text-gray-800">
{formatDate(project.startDate)} {formatDate(project.startDate)}
{" — "} {" — "}
@@ -83,6 +86,8 @@ export default async function ProjectDetailPage({ params }: ProjectDetailPagePro
</div> </div>
<div className="mt-0.5">Win probability: {project.winProbability}%</div> <div className="mt-0.5">Win probability: {project.winProbability}%</div>
</div> </div>
<ProjectDetailActions project={project as never} />
</div>
</div> </div>
<dl className="grid grid-cols-2 gap-x-8 gap-y-3 sm:grid-cols-4 mt-4 pt-4 border-t border-gray-100"> <dl className="grid grid-cols-2 gap-x-8 gap-y-3 sm:grid-cols-4 mt-4 pt-4 border-t border-gray-100">
@@ -169,7 +174,7 @@ export default async function ProjectDetailPage({ params }: ProjectDetailPagePro
</td> </td>
<td className="px-4 py-3 text-sm text-gray-900">{assignment.hoursPerDay}h</td> <td className="px-4 py-3 text-sm text-gray-900">{assignment.hoursPerDay}h</td>
<td className="px-4 py-3 text-sm text-gray-900"> <td className="px-4 py-3 text-sm text-gray-900">
{(assignment.dailyCostCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 0 })} {(assignment.dailyCostCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })}
</td> </td>
<td className="px-4 py-3"> <td className="px-4 py-3">
<span <span
@@ -187,65 +192,11 @@ export default async function ProjectDetailPage({ params }: ProjectDetailPagePro
)} )}
</div> </div>
{/* Open demands table */} {/* Open demands table (client component with fill action) */}
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden"> <ProjectDemandsTable
<div className="px-6 py-4 border-b border-gray-200"> demands={project.demands as never}
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wider"> project={{ id: project.id, name: project.name, shortCode: project.shortCode }}
Open Demands ({project.demands.length}) />
</h2>
</div>
<table className="w-full">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Role
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Period
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Requested
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Unfilled
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Hours/Day
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{project.demands.map((demand) => (
<tr key={demand.id} className="hover:bg-gray-50 transition-colors">
<td className="px-4 py-3 text-sm text-gray-900">
{demand.roleEntity?.name ?? demand.role ?? "Unassigned"}
</td>
<td className="px-4 py-3 text-xs text-gray-500">
{formatDate(demand.startDate)}
{" → "}
{formatDate(demand.endDate)}
</td>
<td className="px-4 py-3 text-sm text-right text-gray-900">{demand.requestedHeadcount}</td>
<td className="px-4 py-3 text-sm text-right text-gray-900">{demand.unfilledHeadcount}</td>
<td className="px-4 py-3 text-sm text-right text-gray-900">{demand.hoursPerDay}h</td>
<td className="px-4 py-3">
<span
className={`inline-block px-2 py-0.5 text-xs rounded-full ${ALLOC_STATUS_COLORS[demand.status] ?? "bg-gray-100 text-gray-600"}`}
>
{demand.status}
</span>
</td>
</tr>
))}
</tbody>
</table>
{project.demands.length === 0 && (
<div className="text-center py-12 text-gray-500 text-sm">No open demands for this project.</div>
)}
</div>
</div> </div>
); );
} }
+147 -1
View File
@@ -65,9 +65,24 @@ type EditState = {
chapterIds: string; chapterIds: string;
}; };
type CreateState = {
name: string;
email: string;
password: string;
systemRole: SystemRole;
};
const EMPTY_CREATE: CreateState = {
name: "",
email: "",
password: "",
systemRole: SystemRole.USER,
};
export function UsersClient() { export function UsersClient() {
const [selectedUserId, setSelectedUserId] = useState<string | null>(null); const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
const [editState, setEditState] = useState<EditState | null>(null); const [editState, setEditState] = useState<EditState | null>(null);
const [createState, setCreateState] = useState<CreateState | null>(null);
const [actionError, setActionError] = useState<string | null>(null); const [actionError, setActionError] = useState<string | null>(null);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [roleFilter, setRoleFilter] = useState<SystemRole | "">(""); const [roleFilter, setRoleFilter] = useState<SystemRole | "">("");
@@ -101,6 +116,15 @@ export function UsersClient() {
onError: (err) => setActionError(err.message), onError: (err) => setActionError(err.message),
}); });
const createUserMutation = trpc.user.create.useMutation({
onSuccess: async () => {
await utils.user.list.invalidate();
setCreateState(null);
setActionError(null);
},
onError: (err) => setActionError(err.message),
});
const resetPermissionsMutation = trpc.user.resetPermissions.useMutation({ const resetPermissionsMutation = trpc.user.resetPermissions.useMutation({
onSuccess: async () => { onSuccess: async () => {
await utils.user.list.invalidate(); await utils.user.list.invalidate();
@@ -221,10 +245,22 @@ export function UsersClient() {
const selectedUser = editState ? allUsers.find((u) => u.id === editState.userId) : null; const selectedUser = editState ? allUsers.find((u) => u.id === editState.userId) : null;
async function handleCreateUser() {
if (!createState) return;
setActionError(null);
await createUserMutation.mutateAsync({
name: createState.name,
email: createState.email,
password: createState.password,
systemRole: createState.systemRole,
});
}
const isPending = const isPending =
updateRoleMutation.isPending || updateRoleMutation.isPending ||
setPermissionsMutation.isPending || setPermissionsMutation.isPending ||
resetPermissionsMutation.isPending; resetPermissionsMutation.isPending ||
createUserMutation.isPending;
function clearAll() { function clearAll() {
setSearch(""); setSearch("");
@@ -245,6 +281,16 @@ export function UsersClient() {
Manage user roles and permission overrides Manage user roles and permission overrides
</p> </p>
</div> </div>
<button
type="button"
onClick={() => { setCreateState({ ...EMPTY_CREATE }); setActionError(null); }}
className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
Create User
</button>
</div> </div>
{/* Filters */} {/* Filters */}
@@ -350,6 +396,106 @@ export function UsersClient() {
</table> </table>
</div> </div>
{/* Create User Modal */}
{createState && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-full max-w-md mx-4 flex flex-col">
<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">
Create User
</h2>
<button
type="button"
onClick={() => { setCreateState(null); setActionError(null); }}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-2xl leading-none"
>
&times;
</button>
</div>
<div className="px-6 py-5 space-y-4">
{actionError && (
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-3 py-2 text-sm text-red-700 dark:text-red-400">
{actionError}
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Name
</label>
<input
type="text"
value={createState.name}
onChange={(e) => setCreateState({ ...createState, name: e.target.value })}
placeholder="Max Mustermann"
className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Email
</label>
<input
type="email"
value={createState.email}
onChange={(e) => setCreateState({ ...createState, email: e.target.value })}
placeholder="user@example.com"
className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Password
</label>
<input
type="password"
value={createState.password}
onChange={(e) => setCreateState({ ...createState, password: e.target.value })}
placeholder="Min. 8 characters"
className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Role
</label>
<select
value={createState.systemRole}
onChange={(e) => setCreateState({ ...createState, systemRole: e.target.value as SystemRole })}
className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
>
{Object.values(SystemRole).map((role) => (
<option key={role} value={role}>{SYSTEM_ROLE_LABELS[role]}</option>
))}
</select>
</div>
</div>
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
<button
type="button"
onClick={() => { setCreateState(null); setActionError(null); }}
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
>
Cancel
</button>
<button
type="button"
onClick={() => void handleCreateUser()}
disabled={isPending || !createState.name.trim() || !createState.email.trim() || createState.password.length < 8}
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{createUserMutation.isPending ? "Creating..." : "Create User"}
</button>
</div>
</div>
</div>
)}
{/* Edit Modal */} {/* Edit Modal */}
{editState && selectedUser && ( {editState && selectedUser && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"> <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
@@ -36,6 +36,10 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
const [roleId, setRoleId] = useState(allocation?.roleId ?? ""); const [roleId, setRoleId] = useState(allocation?.roleId ?? "");
const [roleFreeText, setRoleFreeText] = useState(allocation?.role ?? ""); const [roleFreeText, setRoleFreeText] = useState(allocation?.role ?? "");
const [headcount, setHeadcount] = useState(allocation?.headcount ?? 1); 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 [startDate, setStartDate] = useState(toDateInputValue(allocation?.startDate));
const [endDate, setEndDate] = useState(toDateInputValue(allocation?.endDate)); const [endDate, setEndDate] = useState(toDateInputValue(allocation?.endDate));
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation?.hoursPerDay ?? 8); const [hoursPerDay, setHoursPerDay] = useState<number>(allocation?.hoursPerDay ?? 8);
@@ -172,6 +176,7 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
role: roleString, role: roleString,
roleId: roleId || undefined, roleId: roleId || undefined,
headcount: isDemandEntry ? headcount : 1, headcount: isDemandEntry ? headcount : 1,
...(isDemandEntry && budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
startDate: start, startDate: start,
endDate: end, endDate: end,
hoursPerDay, hoursPerDay,
@@ -186,6 +191,7 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
role: roleString, role: roleString,
roleId: roleId || undefined, roleId: roleId || undefined,
headcount, headcount,
...(budgetEur ? { budgetCents: Math.round(parseFloat(budgetEur) * 100) } : {}),
startDate: start, startDate: start,
endDate: end, endDate: end,
hoursPerDay, hoursPerDay,
@@ -270,6 +276,7 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
</div> </div>
</label> </label>
{isDemandEntry && ( {isDemandEntry && (
<div className="flex items-center gap-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label> <label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label>
<input <input
@@ -281,6 +288,19 @@ export function AllocationModal({ allocation, onClose, onSuccess }: AllocationMo
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" 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>
<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> </div>
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState, useEffect, useMemo } from "react"; import { useState, useEffect, useMemo, useCallback } from "react";
import { formatDate } from "~/lib/format.js"; import { formatDate } from "~/lib/format.js";
import { trpc } from "~/lib/trpc/client.js"; import { trpc } from "~/lib/trpc/client.js";
import { AllocationModal } from "./AllocationModal.js"; import { AllocationModal } from "./AllocationModal.js";
@@ -22,6 +22,11 @@ import { useViewPrefs } from "~/hooks/useViewPrefs.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js"; import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
import { ALLOCATION_STATUS_BADGE as STATUS_BADGE } from "~/lib/status-styles.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 = [ const ALL_ALLOC_STATUSES = [
{ value: "PROPOSED", label: "Proposed" }, { value: "PROPOSED", label: "Proposed" },
{ value: "CONFIRMED", label: "Confirmed" }, { value: "CONFIRMED", label: "Confirmed" },
@@ -168,6 +173,146 @@ export function AllocationsClient() {
[allocationMutationIdsByDisplayId, selection.selectedArray], [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) { function handleSort(field: string) {
if (field === "resource") { if (field === "resource") {
toggle("resource", (a) => a.resource?.displayName ?? null); toggle("resource", (a) => a.resource?.displayName ?? null);
@@ -213,6 +358,74 @@ export function AllocationsClient() {
const singleDeletePending = deleteDemandMutation.isPending || deleteAssignmentMutation.isPending; 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 ( return (
<div className="app-page space-y-5 pb-24"> <div className="app-page space-y-5 pb-24">
<div className="app-page-header gap-4"> <div className="app-page-header gap-4">
@@ -311,6 +524,42 @@ export function AllocationsClient() {
onSetVisible={setVisible} onSetVisible={setVisible}
defaultKeys={defaultKeys} 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> </FilterBar>
{/* Filter chips */} {/* Filter chips */}
@@ -363,75 +612,128 @@ export function AllocationsClient() {
<tbody className="divide-y divide-gray-100 dark:divide-gray-800"> <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{isLoading && ( {isLoading && (
<tr> <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> </tr>
)} )}
{!isLoading && sorted.length === 0 && ( {!isLoading && sorted.length === 0 && (
<tr> <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> </tr>
)} )}
{!isLoading && {!isLoading && viewMode === "flat" &&
sorted.map((alloc) => { sorted.map((alloc) => renderAllocRow(alloc))}
const isSelected = selection.selectedIds.has(alloc.id);
{!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 ( 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" : ""}`}> <GroupRows key={group.resourceId}>
<td className="px-4 py-3"> {/* 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 <input
type="checkbox" type="checkbox"
checked={isSelected} checked={allGroupSelected}
onChange={() => selection.toggle(alloc.id)} ref={(el) => { if (el) el.indeterminate = groupIndeterminate; }}
onChange={() => selection.toggleAll(groupAllocIds)}
className="rounded border-gray-300 dark:border-gray-600" className="rounded border-gray-300 dark:border-gray-600"
/> />
</td> </td>
{visibleColumns.map((col) => { <td colSpan={visibleColumns.length + 1} className="px-4 py-2.5">
switch (col.key) { <div className="flex items-center gap-2">
case "resource": <span className="text-gray-400 dark:text-gray-500 text-xs">
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>; {isCollapsed ? "▸" : ""}
case "project": </span>
return ( <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
<td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300"> {group.resourceName}
{alloc.project ? ( </span>
<><span className="font-mono text-xs">{alloc.project.shortCode}</span> {alloc.project.name}</> {group.eid && (
) : "—"} <span className="text-xs font-mono text-gray-400 dark:text-gray-500">
</td> {group.eid}
); </span>
case "role": )}
return <td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-300">{alloc.role}</td>; {group.chapter && (
case "dates": <span className="text-xs text-gray-400 dark:text-gray-500">
return <td key={col.key} className="whitespace-nowrap px-4 py-3 text-xs text-gray-500 dark:text-gray-400">{formatPeriod(alloc)}</td>; · {group.chapter}
case "hoursPerDay": </span>
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": <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">
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>; {group.allocations.length}
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> </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> </div>
</td> </td>
</tr> </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>
);
})}
</GroupRows>
); );
})} })}
</tbody> </tbody>
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useRef, useState } from "react"; import { useRef, useState, useMemo, useCallback } from "react";
import { AllocationStatus } from "@planarchy/shared"; import { AllocationStatus } from "@planarchy/shared";
import { useFocusTrap } from "~/hooks/useFocusTrap.js"; import { useFocusTrap } from "~/hooks/useFocusTrap.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js"; import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
@@ -17,6 +17,7 @@ interface OpenDemandAllocation {
startDate: Date | string; startDate: Date | string;
endDate: Date | string; endDate: Date | string;
hoursPerDay: number; hoursPerDay: number;
budgetCents?: number;
roleEntity?: { id: string; name: string; color: string | null } | null; roleEntity?: { id: string; name: string; color: string | null } | null;
project?: { id: string; name: string; shortCode: string }; project?: { id: string; name: string; shortCode: string };
} }
@@ -27,128 +28,280 @@ interface FillOpenDemandModalProps {
onSuccess: () => void; 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; const d = typeof date === "string" ? new Date(date) : date;
return d.toLocaleDateString("en-GB", { year: "numeric", month: "short", day: "numeric" }); return d.toLocaleDateString("en-GB", { year: "numeric", month: "short", day: "numeric" });
} }
export function FillOpenDemandModal({ allocation, onClose, onSuccess }: FillOpenDemandModalProps) { 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 [resourceId, setResourceId] = useState("");
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation.hoursPerDay); const [hoursPerDay, setHoursPerDay] = useState<number>(allocation.hoursPerDay);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [serverError, setServerError] = useState<string | null>(null); 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); const panelRef = useRef<HTMLDivElement>(null);
useFocusTrap(panelRef, true); 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 utils = trpc.useUtils();
const invalidatePlanningViews = async () => { const invalidatePlanningViews = useCallback(async () => {
await utils.allocation.list.invalidate(); await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate(); await utils.allocation.listView.invalidate();
await utils.timeline.getEntries.invalidate(); await utils.timeline.getEntries.invalidate();
await utils.timeline.getEntriesView.invalidate(); await utils.timeline.getEntriesView.invalidate();
await utils.timeline.getProjectContext.invalidate(); await utils.timeline.getProjectContext.invalidate();
await utils.timeline.getBudgetStatus.invalidate(); await utils.timeline.getBudgetStatus.invalidate();
}; }, [utils]);
const { data: resources } = trpc.resource.list.useQuery( const { data: resources } = trpc.resource.list.useQuery(
{ isActive: true, search: search || undefined, limit: 100 }, { isActive: true, search: debouncedSearch || undefined, limit: 50 },
{ staleTime: 15_000 }, { 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({ const availabilityQuery = trpc.allocation.checkResourceAvailability.useQuery(
onSuccess: async () => { {
await invalidatePlanningViews(); resourceId,
onSuccess(); 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 roleName = allocation.roleEntity?.name ?? allocation.role ?? "Unknown Role";
const roleColor = allocation.roleEntity?.color ?? "#6366f1"; const roleColor = allocation.roleEntity?.color ?? "#6366f1";
const resourceList = resources?.resources ?? []; const resourceList = resources?.resources ?? [];
const isPending = fillOpenDemandMutation.isPending; const avail = availabilityQuery.data;
function handleSubmit(e: React.FormEvent) { const totalDemandHours = useMemo(() => {
e.preventDefault(); let workingDays = 0;
if (!resourceId) { const d = new Date(allocation.startDate);
setServerError("Please select a resource."); const end = new Date(allocation.endDate);
return; while (d <= end) {
if (d.getDay() !== 0 && d.getDay() !== 6) workingDays++;
d.setDate(d.getDate() + 1);
} }
fillOpenDemandMutation.mutate({ return workingDays * allocation.hoursPerDay;
allocationId: getPlanningEntryMutationId(allocation), }, [allocation.startDate, allocation.endDate, allocation.hoursPerDay]);
resourceId,
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, hoursPerDay,
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, 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 ( return (
<div <div
className="fixed inset-0 bg-black/50 z-50 flex items-start justify-center overflow-y-auto py-8" 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 <div
ref={panelRef} ref={panelRef}
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md mx-4" className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg mx-4"
onKeyDown={(e) => { if (e.key === "Escape") onClose(); }} 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"> <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> <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
<button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-xl leading-none">&times;</button> {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">&times;</button>
</div> </div>
<div className="px-6 pt-4 pb-2"> <div className="px-6 pt-4 pb-2 space-y-3">
{/* Demand summary */} {/* 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 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="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"> <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>
{allocation.headcount > 1 && ( <div className="text-xs text-gray-500 dark:text-gray-400">
<div className="text-xs text-amber-600 mt-0.5"> {allocation.hoursPerDay}h/day · {totalDemandHours.toLocaleString()}h total
{allocation.headcount} slots remaining assigning one resource {allocation.budgetCents && allocation.budgetCents > 0 ? ` · Budget: ${(allocation.budgetCents / 100).toLocaleString("de-DE")} EUR` : ""}
</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"
>
&times;
</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> </div>
</div> </div>
</div>
<form onSubmit={handleSubmit} className="px-6 pb-5 space-y-4"> {/* ─── PLAN PHASE: add resources ──────────────────────────────── */}
{/* Resource search */} {phase === "plan" && (
<div className="px-6 pb-5 space-y-4">
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Search Resource</label>
Search Resource
</label>
<input <input
type="text" type="text"
placeholder="Search by name or EID" placeholder="Search by name or EID..."
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} 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" 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>
<div> <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Select Resource</label>
Assign Resource <span className="text-red-500">*</span>
</label>
<select <select
value={resourceId} value={resourceId}
onChange={(e) => setResourceId(e.target.value)} 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" 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))} size={Math.min(6, Math.max(3, resourceList.length))}
> >
<option value="">Select a resource</option> <option value="">Select a resource...</option>
{resourceList.map((r) => ( {resourceList.map((r) => {
<option key={r.id} value={r.id}> const alreadyPlanned = isAlreadyPlanned(r.id);
{r.displayName} ({r.eid}) return (
<option key={r.id} value={r.id} disabled={alreadyPlanned}>
{r.displayName} ({r.eid}){alreadyPlanned ? " (planned)" : ""}
</option> </option>
))} );
})}
</select> </select>
</div> </div>
@@ -159,27 +312,194 @@ export function FillOpenDemandModal({ allocation, onClose, onSuccess }: FillOpen
value={hoursPerDay} value={hoursPerDay}
onChange={(e) => setHoursPerDay(Number(e.target.value))} onChange={(e) => setHoursPerDay(Number(e.target.value))}
min={0.5} min={0.5}
max={8} max={24}
step={0.5} 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" 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>
{/* 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>
)}
{/* ─── 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 && ( {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"> <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} {serverError}
</div> </div>
)} )}
<div className="flex items-center justify-end gap-3 pt-2"> <div className="flex items-center justify-between 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"> <button
Cancel 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>
<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"> <button
{isPending ? "Assigning…" : "Create Assignment"} 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> </button>
</div> </div>
</form> </div>
)}
</div> </div>
</div> </div>
); );
@@ -0,0 +1,181 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { trpc } from "~/lib/trpc/client.js";
import { ChatMessage, TypingIndicator } from "./ChatMessage.js";
/** Map route prefixes to human-readable page context for the AI */
const ROUTE_CONTEXT: Record<string, string> = {
"/dashboard": "Dashboard — Übersicht mit KPIs, aktive Projekte, Ressourcen-Auslastung",
"/timeline": "Timeline — Gantt-artige Ansicht aller Allokationen und Projekte",
"/allocations": "Allokationen — Liste aller Zuweisungen von Ressourcen zu Projekten",
"/staffing": "Staffing — Projektbesetzung und Kapazitätsplanung",
"/resources": "Ressourcen — Liste aller Mitarbeiter mit Details (FTE, LCR, Skills, Chapter)",
"/projects": "Projekte — Liste aller Projekte mit Budget, Status, Zeitraum",
"/roles": "Rollen — Verwaltung der verfügbaren Rollen",
"/estimates": "Estimating — Aufwandsschätzungen für Projekte",
"/vacations/my": "Meine Urlaube — Eigene Urlaubsanträge und Saldo",
"/vacations": "Urlaubsverwaltung — Alle Urlaubsanträge, Genehmigungen, Team-Kalender",
"/analytics/skills": "Skills Analytics — Skill-Verteilung und -Analyse über alle Ressourcen",
"/analytics/computation-graph": "Computation Graph — Berechnungsvisualisierung für Budget/Kosten",
"/reports/chargeability": "Chargeability Report — Auslastungsanalyse pro Ressource",
"/admin/settings": "Admin-Einstellungen — System-Konfiguration, AI-Credentials, SMTP",
"/admin/users": "Benutzerverwaltung — Rollen, Berechtigungen, Zugänge",
};
function resolvePageContext(pathname: string): string {
// Try exact match first, then prefix match (longest first)
const exact = ROUTE_CONTEXT[pathname];
if (exact) return exact;
const sorted = Object.keys(ROUTE_CONTEXT).sort((a, b) => b.length - a.length);
for (const prefix of sorted) {
const ctx = ROUTE_CONTEXT[prefix];
if (pathname.startsWith(prefix) && ctx) return ctx;
}
return pathname;
}
interface Message {
role: "user" | "assistant";
content: string;
}
export function ChatDrawer({ onClose }: { onClose: () => void }) {
const pathname = usePathname();
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const chatMutation = trpc.assistant.chat.useMutation();
// Auto-scroll to bottom on new messages
useEffect(() => {
const el = scrollRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [messages, isLoading]);
// Focus input on mount
useEffect(() => {
inputRef.current?.focus();
}, []);
const sendMessage = useCallback(async () => {
const text = input.trim();
if (!text || isLoading) return;
setInput("");
setError(null);
const userMsg: Message = { role: "user", content: text };
const updated = [...messages, userMsg];
setMessages(updated);
setIsLoading(true);
try {
const reply = await chatMutation.mutateAsync({
messages: updated.map((m) => ({ role: m.role, content: m.content })),
...(pathname ? { pageContext: resolvePageContext(pathname) } : {}),
});
setMessages((prev) => [...prev, { role: "assistant", content: reply.content }]);
} catch (err) {
const msg = err instanceof Error ? err.message : "Something went wrong";
setError(msg);
} finally {
setIsLoading(false);
}
}, [input, isLoading, messages, chatMutation]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void sendMessage();
}
};
return (
<>
{/* Backdrop */}
<div className="fixed inset-0 z-40 bg-black/20 backdrop-blur-sm" onClick={onClose} />
{/* Panel */}
<div className="fixed right-0 top-0 z-50 flex h-full w-full max-w-md flex-col border-l border-gray-200 bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900">
{/* Header */}
<div className="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-slate-700">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-xl bg-brand-600 text-white">
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</div>
<h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">Planarchy Assistant</h2>
</div>
<button
type="button"
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300"
>
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Messages */}
<div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4 space-y-3">
{messages.length === 0 && !isLoading && (
<div className="flex flex-col items-center justify-center py-16 text-center text-sm text-gray-400 dark:text-gray-500">
<svg className="mb-3 h-10 w-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
<p className="font-medium">Frag mich etwas!</p>
<p className="mt-1 text-xs">z.B. &quot;Welche Ressourcen gibt es?&quot; oder &quot;Budget von Z033T593?&quot;</p>
</div>
)}
{messages.map((msg, i) => (
<ChatMessage key={i} role={msg.role} content={msg.content} />
))}
{isLoading && <TypingIndicator />}
{error && (
<div className="rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-400">
{error}
</div>
)}
</div>
{/* Input */}
<div className="border-t border-gray-200 px-4 py-3 dark:border-slate-700">
<div className="flex items-end gap-2">
<textarea
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Nachricht eingeben..."
rows={1}
className="flex-1 resize-none rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-brand-500 focus:outline-none focus:ring-1 focus:ring-brand-500 dark:border-slate-600 dark:bg-slate-800 dark:text-gray-100 dark:placeholder:text-gray-500 dark:focus:border-brand-500"
style={{ maxHeight: "120px" }}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = "auto";
target.style.height = `${Math.min(target.scrollHeight, 120)}px`;
}}
/>
<button
type="button"
onClick={() => void sendMessage()}
disabled={!input.trim() || isLoading}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-brand-600 text-white transition-colors hover:bg-brand-700 disabled:opacity-40 disabled:cursor-not-allowed"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M12 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
</div>
</>
);
}
@@ -0,0 +1,142 @@
"use client";
import { useMemo } from "react";
interface ChatMessageProps {
role: "user" | "assistant";
content: string;
}
/**
* Lightweight inline markdown renderer — handles bold, italic, code,
* bullet lists, and numbered lists without a full markdown library.
*/
function renderMarkdown(text: string) {
const lines = text.split("\n");
const elements: React.ReactNode[] = [];
let listItems: React.ReactNode[] = [];
let listType: "ul" | "ol" | null = null;
const flushList = () => {
if (listItems.length > 0 && listType) {
const Tag = listType;
elements.push(
<Tag key={`list-${elements.length}`} className={listType === "ul" ? "list-disc pl-4 my-1 space-y-0.5" : "list-decimal pl-4 my-1 space-y-0.5"}>
{listItems}
</Tag>,
);
listItems = [];
listType = null;
}
};
for (const [i, line] of lines.entries()) {
// Bullet list: "- item" or "* item"
const bulletMatch = line.match(/^[\s]*[-*]\s+(.*)/);
if (bulletMatch?.[1]) {
if (listType !== "ul") flushList();
listType = "ul";
listItems.push(<li key={`li-${i}`}>{inlineFormat(bulletMatch[1])}</li>);
continue;
}
// Numbered list: "1. item"
const numMatch = line.match(/^[\s]*\d+\.\s+(.*)/);
if (numMatch?.[1]) {
if (listType !== "ol") flushList();
listType = "ol";
listItems.push(<li key={`li-${i}`}>{inlineFormat(numMatch[1])}</li>);
continue;
}
// Not a list item — flush any pending list
flushList();
// Empty line → spacing
if (line.trim() === "") {
elements.push(<div key={`br-${i}`} className="h-2" />);
continue;
}
// Regular paragraph
elements.push(<p key={`p-${i}`} className="my-0">{inlineFormat(line)}</p>);
}
flushList();
return elements;
}
/** Parse inline formatting: **bold**, *italic*, `code` */
function inlineFormat(text: string): React.ReactNode {
// Split by inline patterns, preserving delimiters
const parts: React.ReactNode[] = [];
// Regex: **bold**, *italic*, `code`
const regex = /(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = regex.exec(text)) !== null) {
// Text before this match
if (match.index > lastIndex) {
parts.push(text.slice(lastIndex, match.index));
}
if (match[2]) {
// **bold**
parts.push(<strong key={`b-${match.index}`} className="font-semibold">{match[2]}</strong>);
} else if (match[3]) {
// *italic*
parts.push(<em key={`i-${match.index}`}>{match[3]}</em>);
} else if (match[4]) {
// `code`
parts.push(
<code key={`c-${match.index}`} className="rounded bg-black/10 px-1 py-0.5 text-xs font-mono dark:bg-white/10">
{match[4]}
</code>,
);
}
lastIndex = match.index + match[0].length;
}
// Remaining text
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts.length === 1 ? parts[0] : <>{parts}</>;
}
export function ChatMessage({ role, content }: ChatMessageProps) {
const isUser = role === "user";
const rendered = useMemo(() => (isUser ? null : renderMarkdown(content)), [isUser, content]);
return (
<div className={`flex ${isUser ? "justify-end" : "justify-start"}`}>
<div
className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${
isUser
? "bg-brand-600 text-white"
: "bg-gray-100 text-gray-800 dark:bg-slate-800 dark:text-gray-200"
}`}
>
{isUser ? (
<span className="whitespace-pre-wrap break-words">{content}</span>
) : (
<div className="space-y-0.5 break-words">{rendered}</div>
)}
</div>
</div>
);
}
export function TypingIndicator() {
return (
<div className="flex justify-start">
<div className="rounded-2xl bg-gray-100 px-4 py-3 dark:bg-slate-800">
<div className="flex gap-1.5">
<span className="h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-gray-500" style={{ animationDelay: "0ms" }} />
<span className="h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-gray-500" style={{ animationDelay: "150ms" }} />
<span className="h-2 w-2 animate-bounce rounded-full bg-gray-400 dark:bg-gray-500" style={{ animationDelay: "300ms" }} />
</div>
</div>
</div>
);
}
@@ -0,0 +1,270 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { trpc } from "~/lib/trpc/client.js";
import { ChatMessage, TypingIndicator } from "./ChatMessage.js";
/** Map route prefixes to human-readable page context for the AI */
const ROUTE_CONTEXT: Record<string, string> = {
"/dashboard": "Dashboard — Übersicht mit KPIs, aktive Projekte, Ressourcen-Auslastung",
"/timeline": "Timeline — Gantt-artige Ansicht aller Allokationen und Projekte",
"/allocations": "Allokationen — Liste aller Zuweisungen von Ressourcen zu Projekten",
"/staffing": "Staffing — Projektbesetzung und Kapazitätsplanung",
"/resources": "Ressourcen — Liste aller Mitarbeiter mit Details (FTE, LCR, Skills, Chapter)",
"/projects": "Projekte — Liste aller Projekte mit Budget, Status, Zeitraum",
"/roles": "Rollen — Verwaltung der verfügbaren Rollen",
"/estimates": "Estimating — Aufwandsschätzungen für Projekte",
"/vacations/my": "Meine Urlaube — Eigene Urlaubsanträge und Saldo",
"/vacations": "Urlaubsverwaltung — Alle Urlaubsanträge, Genehmigungen, Team-Kalender",
"/analytics/skills": "Skills Analytics — Skill-Verteilung und -Analyse über alle Ressourcen",
"/analytics/computation-graph": "Computation Graph — Berechnungsvisualisierung für Budget/Kosten",
"/reports/chargeability": "Chargeability Report — Auslastungsanalyse pro Ressource",
"/admin/settings": "Admin-Einstellungen — System-Konfiguration, AI-Credentials, SMTP",
"/admin/users": "Benutzerverwaltung — Rollen, Berechtigungen, Zugänge",
};
function resolvePageContext(pathname: string): string {
const exact = ROUTE_CONTEXT[pathname];
if (exact) return exact;
const sorted = Object.keys(ROUTE_CONTEXT).sort((a, b) => b.length - a.length);
for (const prefix of sorted) {
const ctx = ROUTE_CONTEXT[prefix];
if (pathname.startsWith(prefix) && ctx) return ctx;
}
return pathname;
}
interface Message {
role: "user" | "assistant";
content: string;
}
const STORAGE_KEY = "planarchy-chat-messages";
/** Load messages from sessionStorage (survives page reloads, clears on tab close). */
function loadPersistedMessages(): Message[] {
if (typeof window === "undefined") return [];
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw) as Message[];
} catch { /* ignore corrupt data */ }
return [];
}
/** Module-level cache — avoids re-parsing sessionStorage on every client-side navigation. */
let cachedMessages: Message[] | null = null;
export function ChatPanel({ onClose }: { onClose: () => void }) {
const pathname = usePathname();
const router = useRouter();
const utils = trpc.useUtils();
const [messages, setMessages] = useState<Message[]>(() => cachedMessages ?? loadPersistedMessages());
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const chatMutation = trpc.assistant.chat.useMutation();
// Sync to module-level cache + sessionStorage on every change
useEffect(() => {
cachedMessages = messages;
try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); } catch { /* quota exceeded */ }
}, [messages]);
// Auto-scroll to bottom on new messages
useEffect(() => {
const el = scrollRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [messages, isLoading]);
// Focus input on mount
useEffect(() => {
inputRef.current?.focus();
}, []);
const sendMessage = useCallback(async () => {
const text = input.trim();
if (!text || isLoading) return;
setInput("");
setError(null);
const userMsg: Message = { role: "user", content: text };
const updated = [...messages, userMsg];
setMessages(updated);
setIsLoading(true);
try {
const reply = await chatMutation.mutateAsync({
messages: updated.slice(-40).map((m) => ({ role: m.role, content: m.content })),
...(pathname ? { pageContext: resolvePageContext(pathname) } : {}),
});
setMessages((prev) => [...prev, { role: "assistant", content: reply.content }]);
// Handle actions from the AI (navigation, data invalidation)
const actions = (reply as { actions?: Array<{ type: string; url?: string; scope?: string[] }> }).actions;
if (actions) {
for (const action of actions) {
if (action.type === "navigate" && action.url) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
router.push(action.url as any);
} else if (action.type === "invalidate" && action.scope) {
// Invalidate relevant tRPC queries so the UI refreshes
for (const scope of action.scope) {
if (scope === "allocation" || scope === "timeline") {
void utils.allocation.invalidate();
void utils.timeline.invalidate();
}
if (scope === "resource") void utils.resource.invalidate();
if (scope === "project") void utils.project.invalidate();
}
}
}
}
} catch (err) {
const msg = err instanceof Error ? err.message : "Something went wrong";
setError(msg);
} finally {
setIsLoading(false);
}
}, [input, isLoading, messages, chatMutation, pathname]);
// Track user message history for up-arrow recall
const userHistory = useRef<string[]>([]);
const historyIndex = useRef(-1);
// Keep userHistory in sync with messages
useEffect(() => {
userHistory.current = messages.filter((m) => m.role === "user").map((m) => m.content);
historyIndex.current = -1;
}, [messages]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "ArrowUp" && input === "" && userHistory.current.length > 0) {
e.preventDefault();
const nextIdx = historyIndex.current < 0
? userHistory.current.length - 1
: Math.max(0, historyIndex.current - 1);
historyIndex.current = nextIdx;
setInput(userHistory.current[nextIdx] ?? "");
return;
}
if (e.key === "ArrowDown" && historyIndex.current >= 0) {
e.preventDefault();
const nextIdx = historyIndex.current + 1;
if (nextIdx >= userHistory.current.length) {
historyIndex.current = -1;
setInput("");
} else {
historyIndex.current = nextIdx;
setInput(userHistory.current[nextIdx] ?? "");
}
return;
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void sendMessage();
}
};
const clearChat = () => {
setMessages([]);
setError(null);
cachedMessages = null;
try { sessionStorage.removeItem(STORAGE_KEY); } catch { /* noop */ }
};
return (
<div className="w-96 shrink-0 flex flex-col border-l border-gray-200 bg-white dark:border-slate-800 dark:bg-slate-950/75">
{/* Header */}
<div className="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-slate-800">
<div className="flex items-center gap-2">
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-brand-600 text-white">
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</div>
<h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">HartBOT</h2>
</div>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<button
type="button"
onClick={clearChat}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300"
title="Chat leeren"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
)}
<button
type="button"
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
{/* Messages */}
<div ref={scrollRef} className="flex-1 overflow-y-auto px-3 py-3 space-y-3">
{messages.length === 0 && !isLoading && (
<div className="flex flex-col items-center justify-center py-12 text-center text-sm text-gray-400 dark:text-gray-500">
<svg className="mb-2 h-8 w-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
<p className="font-medium">Frag mich etwas!</p>
<p className="mt-1 text-xs">z.B. &quot;Welche Ressourcen gibt es?&quot;</p>
</div>
)}
{messages.map((msg, i) => (
<ChatMessage key={i} role={msg.role} content={msg.content} />
))}
{isLoading && <TypingIndicator />}
{error && (
<div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-400">
{error}
</div>
)}
</div>
{/* Input */}
<div className="border-t border-gray-200 px-3 py-2.5 dark:border-slate-800">
<div className="flex items-end gap-2">
<textarea
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Nachricht eingeben..."
rows={1}
className="flex-1 resize-none rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-brand-500 focus:outline-none focus:ring-1 focus:ring-brand-500 dark:border-slate-600 dark:bg-slate-800 dark:text-gray-100 dark:placeholder:text-gray-500 dark:focus:border-brand-500"
style={{ maxHeight: "120px" }}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = "auto";
target.style.height = `${Math.min(target.scrollHeight, 120)}px`;
}}
/>
<button
type="button"
onClick={() => void sendMessage()}
disabled={!input.trim() || isLoading}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-brand-600 text-white transition-colors hover:bg-brand-700 disabled:opacity-40 disabled:cursor-not-allowed"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M12 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
</div>
);
}
@@ -2,6 +2,7 @@
import { useState } from "react"; import { useState } from "react";
import type { StaffingRequirement } from "@planarchy/shared"; import type { StaffingRequirement } from "@planarchy/shared";
import { uuid } from "~/lib/uuid.js";
const INPUT_CLS = const INPUT_CLS =
"px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm"; "px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm";
@@ -11,7 +12,7 @@ const BTN_DANGER =
function makeEmptyPreset(): StaffingRequirement { function makeEmptyPreset(): StaffingRequirement {
return { return {
id: crypto.randomUUID(), id: uuid(),
role: "", role: "",
requiredSkills: [], requiredSkills: [],
preferredSkills: [], preferredSkills: [],
@@ -49,6 +49,10 @@ export const WIDGET_REGISTRY: Record<DashboardWidgetType, WidgetDefinition> = {
...DASHBOARD_WIDGET_CATALOG.find((widget) => widget.type === "chargeability-overview")!, ...DASHBOARD_WIDGET_CATALOG.find((widget) => widget.type === "chargeability-overview")!,
component: lazy(() => import("./widgets/ChargeabilityWidget.js").then((m) => ({ default: m.ChargeabilityWidget }))), component: lazy(() => import("./widgets/ChargeabilityWidget.js").then((m) => ({ default: m.ChargeabilityWidget }))),
}, },
"my-projects": {
...DASHBOARD_WIDGET_CATALOG.find((widget) => widget.type === "my-projects")!,
component: lazy(() => import("./widgets/MyProjectsWidget.js").then((m) => ({ default: m.MyProjectsWidget }))),
},
}; };
export function getWidget(type: DashboardWidgetType): WidgetDefinition { export function getWidget(type: DashboardWidgetType): WidgetDefinition {
@@ -0,0 +1,136 @@
"use client";
import { useMemo } from "react";
import Link from "next/link";
import { trpc } from "~/lib/trpc/client.js";
import type { WidgetProps } from "../widget-registry.js";
const STATUS_DOT: Record<string, string> = {
ACTIVE: "bg-green-500",
DRAFT: "bg-gray-400",
ON_HOLD: "bg-yellow-500",
COMPLETED: "bg-blue-500",
CANCELLED: "bg-red-400",
};
export function MyProjectsWidget({ config }: WidgetProps) {
const showFavorites = (config as { showFavorites?: boolean }).showFavorites !== false;
const showResponsible = (config as { showResponsible?: boolean }).showResponsible !== false;
const { data: favoriteIds } = trpc.user.getFavoriteProjectIds.useQuery(undefined, {
staleTime: 30_000,
enabled: showFavorites,
});
const { data: projectsData } = trpc.project.listWithCosts.useQuery(
{ limit: 200 },
{ staleTime: 30_000 },
);
const { data: session } = trpc.user.me.useQuery(undefined, { staleTime: 60_000 });
const favorites = favoriteIds ?? [];
const allProjects = (projectsData?.projects ?? []) as Array<{
id: string;
shortCode: string;
name: string;
status: string;
responsiblePerson?: string | null;
budgetCents?: number;
startDate?: Date | string;
endDate?: Date | string;
}>;
const userName = session?.name ?? "";
const { favoriteProjects, responsibleProjects } = useMemo(() => {
const favSet = new Set(favorites);
const favProjects = showFavorites
? allProjects.filter((p) => favSet.has(p.id))
: [];
const respProjects = showResponsible && userName
? allProjects.filter((p) => p.responsiblePerson?.toLowerCase().includes(userName.toLowerCase()) && !favSet.has(p.id))
: [];
return { favoriteProjects: favProjects, responsibleProjects: respProjects };
}, [allProjects, favorites, showFavorites, showResponsible, userName]);
const toggleMutation = trpc.user.toggleFavoriteProject.useMutation({
onSuccess: () => {
void trpc.useUtils().user.getFavoriteProjectIds.invalidate();
},
});
const isEmpty = favoriteProjects.length === 0 && responsibleProjects.length === 0;
return (
<div className="h-full flex flex-col">
{isEmpty && (
<div className="flex-1 flex items-center justify-center text-sm text-gray-400 dark:text-gray-500">
<div className="text-center">
<div className="text-2xl mb-1"></div>
<p>No favorite projects yet.</p>
<p className="text-xs mt-1">Star projects from the project list to see them here.</p>
</div>
</div>
)}
{!isEmpty && (
<div className="flex-1 overflow-y-auto divide-y divide-gray-100 dark:divide-gray-800">
{favoriteProjects.length > 0 && (
<div>
<div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-amber-600 dark:text-amber-400 bg-amber-50/50 dark:bg-amber-900/10">
Favorites
</div>
{favoriteProjects.map((p) => (
<ProjectRow key={p.id} project={p} isFavorite onToggleFavorite={() => toggleMutation.mutate({ projectId: p.id })} />
))}
</div>
)}
{responsibleProjects.length > 0 && (
<div>
<div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-brand-600 dark:text-brand-400 bg-brand-50/50 dark:bg-brand-900/10">
Responsible
</div>
{responsibleProjects.map((p) => (
<ProjectRow key={p.id} project={p} isFavorite={false} onToggleFavorite={() => toggleMutation.mutate({ projectId: p.id })} />
))}
</div>
)}
</div>
)}
</div>
);
}
function ProjectRow({
project,
isFavorite,
onToggleFavorite,
}: {
project: { id: string; shortCode: string; name: string; status: string };
isFavorite: boolean;
onToggleFavorite: () => void;
}) {
return (
<div className="flex items-center gap-2 px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-800/30 transition-colors group">
<button
type="button"
onClick={(e) => { e.preventDefault(); onToggleFavorite(); }}
className={`flex-shrink-0 text-sm transition-colors ${isFavorite ? "text-amber-500" : "text-gray-300 dark:text-gray-600 opacity-0 group-hover:opacity-100"}`}
title={isFavorite ? "Remove from favorites" : "Add to favorites"}
>
{isFavorite ? "★" : "☆"}
</button>
<div className={`w-2 h-2 rounded-full flex-shrink-0 ${STATUS_DOT[project.status] ?? "bg-gray-400"}`} />
<Link
href={`/projects/${project.id}`}
className="min-w-0 flex-1 truncate text-sm text-gray-900 dark:text-gray-100 hover:text-brand-600 dark:hover:text-brand-400"
>
<span className="font-mono text-xs text-gray-400 dark:text-gray-500 mr-1.5">{project.shortCode}</span>
{project.name}
</Link>
<span className="flex-shrink-0 text-[10px] text-gray-400 dark:text-gray-500 uppercase">{project.status}</span>
</div>
);
}
@@ -1,6 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import Link from "next/link";
import { trpc } from "~/lib/trpc/client.js"; import { trpc } from "~/lib/trpc/client.js";
import type { WidgetProps } from "~/components/dashboard/widget-registry.js"; import type { WidgetProps } from "~/components/dashboard/widget-registry.js";
import { ProjectStatus } from "@planarchy/shared/types"; import { ProjectStatus } from "@planarchy/shared/types";
@@ -63,8 +64,10 @@ export function ProjectTableWidget({ config, onConfigChange }: WidgetProps) {
shortCode: string; shortCode: string;
name: string; name: string;
status: string; status: string;
budgetCents: number;
totalCostCents: number; totalCostCents: number;
totalPersonDays: number; totalPersonDays: number;
utilizationPercent: number;
} }
const list = ((projects as unknown as { projects: ProjectRow[] } | undefined)?.projects ?? const list = ((projects as unknown as { projects: ProjectRow[] } | undefined)?.projects ??
[]) as ProjectRow[]; []) as ProjectRow[];
@@ -210,7 +213,7 @@ export function ProjectTableWidget({ config, onConfigChange }: WidgetProps) {
onClick={() => toggleSort("personDays")} onClick={() => toggleSort("personDays")}
className="inline-flex items-center gap-0.5 hover:text-gray-700 cursor-pointer" className="inline-flex items-center gap-0.5 hover:text-gray-700 cursor-pointer"
> >
Person Days PD
<span className="text-[10px] ml-0.5"> <span className="text-[10px] ml-0.5">
{sortKey === "personDays" ? ( {sortKey === "personDays" ? (
sortDir === "asc" ? ( sortDir === "asc" ? (
@@ -223,19 +226,30 @@ export function ProjectTableWidget({ config, onConfigChange }: WidgetProps) {
)} )}
</span> </span>
</button> </button>
<InfoTooltip content="Total working days allocated across all non-cancelled allocations (sum of allocation durations in working days)." /> <InfoTooltip content="Total person-days across all non-cancelled allocations." />
</span> </span>
</th> </th>
<th className="px-3 py-2 text-right font-medium text-gray-500">
Budget
</th>
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800"> <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{sorted.map((p) => ( {sorted.map((p) => {
const overBudget = p.budgetCents > 0 && p.totalCostCents > p.budgetCents;
const util = p.utilizationPercent;
return (
<tr key={p.id} className="transition hover:bg-gray-50 dark:hover:bg-gray-800/60"> <tr key={p.id} className="transition hover:bg-gray-50 dark:hover:bg-gray-800/60">
<td className="px-3 py-2 font-mono text-gray-600 dark:text-gray-300"> <td className="px-3 py-2 font-mono text-gray-600 dark:text-gray-300">
{p.shortCode} {p.shortCode}
</td> </td>
<td className="px-3 py-2 max-w-[180px] truncate font-medium text-gray-900 dark:text-gray-100"> <td className="px-3 py-2 max-w-[180px] truncate font-medium">
<Link
href={`/projects/${p.id}`}
className="text-gray-900 dark:text-gray-100 hover:text-brand-600 dark:hover:text-brand-400 hover:underline"
>
{p.name} {p.name}
</Link>
</td> </td>
<td className="px-3 py-2"> <td className="px-3 py-2">
<span <span
@@ -245,13 +259,29 @@ export function ProjectTableWidget({ config, onConfigChange }: WidgetProps) {
</span> </span>
</td> </td>
<td className="px-3 py-2 text-right text-gray-700 dark:text-gray-200"> <td className="px-3 py-2 text-right text-gray-700 dark:text-gray-200">
{(p.totalCostCents / 100).toLocaleString("de-DE", { maximumFractionDigits: 0 })} {(p.totalCostCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })}
</td> </td>
<td className="px-3 py-2 text-right text-gray-700 dark:text-gray-200"> <td className="px-3 py-2 text-right text-gray-700 dark:text-gray-200">
{p.totalPersonDays}d {p.totalPersonDays}d
</td> </td>
<td className="px-3 py-2 text-right">
{p.budgetCents > 0 ? (
<div className="flex items-center justify-end gap-1.5">
<span className="text-gray-700 dark:text-gray-200">
{(p.budgetCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 0 })}
</span>
<span
className={`inline-block w-2 h-2 rounded-full flex-shrink-0 ${overBudget ? "bg-red-500" : util >= 80 ? "bg-amber-500" : "bg-green-500"}`}
title={`${util}% utilized${overBudget ? " — over budget!" : ""}`}
/>
</div>
) : (
<span className="text-gray-400 dark:text-gray-600"></span>
)}
</td>
</tr> </tr>
))} );
})}
</tbody> </tbody>
</table> </table>
{list.length === 0 && ( {list.length === 0 && (
@@ -11,6 +11,7 @@ import { useFocusTrap } from "~/hooks/useFocusTrap.js";
import { ProjectCombobox } from "~/components/ui/ProjectCombobox.js"; import { ProjectCombobox } from "~/components/ui/ProjectCombobox.js";
import { ResourceCombobox } from "~/components/ui/ResourceCombobox.js"; import { ResourceCombobox } from "~/components/ui/ResourceCombobox.js";
import { trpc } from "~/lib/trpc/client.js"; import { trpc } from "~/lib/trpc/client.js";
import { uuid } from "~/lib/uuid.js";
const INPUT_CLS = const INPUT_CLS =
"w-full rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-100"; "w-full rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-100";
@@ -73,7 +74,7 @@ interface ResourceOption {
function makeAssumption(): AssumptionRow { function makeAssumption(): AssumptionRow {
return { return {
id: crypto.randomUUID(), id: uuid(),
category: "commercial", category: "commercial",
key: "", key: "",
label: "", label: "",
@@ -83,7 +84,7 @@ function makeAssumption(): AssumptionRow {
function makeScope(sequenceNo = 1): ScopeRow { function makeScope(sequenceNo = 1): ScopeRow {
return { return {
id: crypto.randomUUID(), id: uuid(),
sequenceNo, sequenceNo,
scopeType: "SHOT", scopeType: "SHOT",
name: "", name: "",
@@ -93,7 +94,7 @@ function makeScope(sequenceNo = 1): ScopeRow {
function makeDemand(): DemandRow { function makeDemand(): DemandRow {
return { return {
id: crypto.randomUUID(), id: uuid(),
name: "", name: "",
roleId: null, roleId: null,
resourceId: null, resourceId: null,
@@ -277,7 +278,7 @@ export function EstimateWizard({ onClose }: { onClose: () => void }) {
if (result.rows.length > 0) { if (result.rows.length > 0) {
const imported: ScopeRow[] = result.rows.map((row) => ({ const imported: ScopeRow[] = result.rows.map((row) => ({
id: crypto.randomUUID(), id: uuid(),
sequenceNo: row.sequenceNo, sequenceNo: row.sequenceNo,
scopeType: row.scopeType, scopeType: row.scopeType,
name: row.name, name: row.name,
+35 -2
View File
@@ -10,6 +10,7 @@ import { Suspense, useState } from "react";
import { PreferencesModal } from "./PreferencesModal.js"; import { PreferencesModal } from "./PreferencesModal.js";
import { ThemeProvider } from "./ThemeProvider.js"; import { ThemeProvider } from "./ThemeProvider.js";
import { NotificationBell } from "../notifications/NotificationBell.js"; import { NotificationBell } from "../notifications/NotificationBell.js";
import { ChatPanel } from "../assistant/ChatPanel.js";
import { NavProgressBar } from "~/components/ui/NavProgressBar.js"; import { NavProgressBar } from "~/components/ui/NavProgressBar.js";
function IconFrame({ children }: { children: ReactNode }) { function IconFrame({ children }: { children: ReactNode }) {
@@ -53,6 +54,9 @@ function SkillsIcon() {
function ChargeabilityIcon() { function ChargeabilityIcon() {
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M5 17l4-4 3 3 7-8M19 19H5V5" /></svg>; return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M5 17l4-4 3 3 7-8M19 19H5V5" /></svg>;
} }
function GraphIcon() {
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="6" cy="6" r="2.5" strokeWidth={1.8} /><circle cx="18" cy="6" r="2.5" strokeWidth={1.8} /><circle cx="12" cy="18" r="2.5" strokeWidth={1.8} /><path strokeLinecap="round" strokeWidth={1.8} d="M8.5 7.5l2 7M15.5 7.5l-2 7M8.5 6h7" /></svg>;
}
function AdminIcon() { function AdminIcon() {
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M12 8a4 4 0 100 8 4 4 0 000-8zm8 4l-2.1.7a7.9 7.9 0 01-.6 1.5l1 2-2.1 2.1-2-1a7.9 7.9 0 01-1.5.6L12 20l-1.7-2.1a7.9 7.9 0 01-1.5-.6l-2 1-2.1-2.1 1-2a7.9 7.9 0 01-.6-1.5L4 12l2.1-1.7a7.9 7.9 0 01.6-1.5l-1-2 2.1-2.1 2 1a7.9 7.9 0 011.5-.6L12 4l1.7 2.1a7.9 7.9 0 011.5.6l2-1 2.1 2.1-1 2a7.9 7.9 0 01.6 1.5L20 12z" /></svg>; return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M12 8a4 4 0 100 8 4 4 0 000-8zm8 4l-2.1.7a7.9 7.9 0 01-.6 1.5l1 2-2.1 2.1-2-1a7.9 7.9 0 01-1.5.6L12 20l-1.7-2.1a7.9 7.9 0 01-1.5-.6l-2 1-2.1-2.1 1-2a7.9 7.9 0 01-.6-1.5L4 12l2.1-1.7a7.9 7.9 0 01.6-1.5l-1-2 2.1-2.1 2 1a7.9 7.9 0 011.5-.6L12 4l1.7 2.1a7.9 7.9 0 011.5.6l2-1 2.1 2.1-1 2a7.9 7.9 0 01.6 1.5L20 12z" /></svg>;
} }
@@ -93,6 +97,7 @@ const navSections: NavSection[] = [
items: [ items: [
{ href: "/analytics/skills", label: "Skills Analytics", icon: <SkillsIcon />, roles: ["ADMIN", "MANAGER", "CONTROLLER", "VIEWER"] }, { href: "/analytics/skills", label: "Skills Analytics", icon: <SkillsIcon />, roles: ["ADMIN", "MANAGER", "CONTROLLER", "VIEWER"] },
{ href: "/reports/chargeability", label: "Chargeability", icon: <ChargeabilityIcon />, roles: ["ADMIN", "MANAGER", "CONTROLLER"] }, { href: "/reports/chargeability", label: "Chargeability", icon: <ChargeabilityIcon />, roles: ["ADMIN", "MANAGER", "CONTROLLER"] },
{ href: "/analytics/computation-graph", label: "Computation Graph", icon: <GraphIcon />, roles: ["ADMIN", "MANAGER", "CONTROLLER"] },
], ],
}, },
{ {
@@ -131,7 +136,7 @@ const adminNavEntries: AdminEntry[] = [
{ href: "/admin/skill-import", label: "Skill Import", icon: <AdminIcon /> }, { href: "/admin/skill-import", label: "Skill Import", icon: <AdminIcon /> },
]; ];
function Sidebar({ userRole }: { userRole: string }) { function Sidebar({ userRole, onChatOpen }: { userRole: string; onChatOpen: () => void }) {
const pathname = usePathname(); const pathname = usePathname();
const [prefsOpen, setPrefsOpen] = useState(false); const [prefsOpen, setPrefsOpen] = useState(false);
@@ -320,6 +325,18 @@ function Sidebar({ userRole }: { userRole: string }) {
<NotificationBell /> <NotificationBell />
<span className="text-xs uppercase tracking-[0.16em] text-gray-400 dark:text-gray-500">Notifications</span> <span className="text-xs uppercase tracking-[0.16em] text-gray-400 dark:text-gray-500">Notifications</span>
</div> </div>
<button
type="button"
onClick={onChatOpen}
className="flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-sm text-gray-700 transition-colors hover:bg-gray-100/90 dark:text-gray-300 dark:hover:bg-slate-900"
>
<IconFrame>
<svg className="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</IconFrame>
<span>HartBOT</span>
</button>
<button <button
type="button" type="button"
onClick={() => setPrefsOpen(true)} onClick={() => setPrefsOpen(true)}
@@ -354,15 +371,31 @@ function Sidebar({ userRole }: { userRole: string }) {
} }
export function AppShell({ children, userRole = "USER" }: { children: React.ReactNode; userRole?: string }) { export function AppShell({ children, userRole = "USER" }: { children: React.ReactNode; userRole?: string }) {
const [chatOpen, setChatOpen] = useState(false);
return ( return (
<ThemeProvider> <ThemeProvider>
<Suspense> <Suspense>
<NavProgressBar /> <NavProgressBar />
</Suspense> </Suspense>
<div className="flex h-screen bg-transparent"> <div className="flex h-screen bg-transparent">
<Sidebar userRole={userRole} /> <Sidebar userRole={userRole} onChatOpen={() => setChatOpen(true)} />
<main className="flex-1 overflow-auto bg-transparent">{children}</main> <main className="flex-1 overflow-auto bg-transparent">{children}</main>
{chatOpen && <ChatPanel onClose={() => setChatOpen(false)} />}
</div> </div>
{/* Floating chat FAB — always visible when panel is closed */}
{!chatOpen && (
<button
type="button"
onClick={() => setChatOpen(true)}
className="fixed bottom-6 right-6 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-brand-600 text-white shadow-lg shadow-brand-600/30 transition-all hover:bg-brand-700 hover:shadow-xl hover:shadow-brand-600/40 active:scale-95"
title="HartBOT"
>
<svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</button>
)}
</ThemeProvider> </ThemeProvider>
); );
} }
@@ -20,8 +20,8 @@ function formatEur(cents: number): string {
return (cents / 100).toLocaleString("de-DE", { return (cents / 100).toLocaleString("de-DE", {
style: "currency", style: "currency",
currency: "EUR", currency: "EUR",
minimumFractionDigits: 0, minimumFractionDigits: 2,
maximumFractionDigits: 0, maximumFractionDigits: 2,
}); });
} }
@@ -12,8 +12,8 @@ function formatEur(cents: number): string {
return (cents / 100).toLocaleString("de-DE", { return (cents / 100).toLocaleString("de-DE", {
style: "currency", style: "currency",
currency: "EUR", currency: "EUR",
minimumFractionDigits: 0, minimumFractionDigits: 2,
maximumFractionDigits: 0, maximumFractionDigits: 2,
}); });
} }
@@ -0,0 +1,221 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { formatDate } from "~/lib/format.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { FillOpenDemandModal } from "~/components/allocations/FillOpenDemandModal.js";
import { AllocationModal } from "~/components/allocations/AllocationModal.js";
import type { AllocationWithDetails } from "@planarchy/shared";
import type { OpenDemandAssignment } from "~/components/timeline/TimelineProjectPanel.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { trpc } from "~/lib/trpc/client.js";
const ALLOC_STATUS_COLORS: Record<string, string> = {
ACTIVE: "bg-green-100 text-green-700",
PROPOSED: "bg-yellow-100 text-yellow-700",
CONFIRMED: "bg-blue-100 text-blue-700",
CANCELLED: "bg-gray-100 text-gray-500",
COMPLETED: "bg-blue-100 text-blue-600",
};
interface DemandRow {
id: string;
projectId: string;
role: string | null;
roleId: string | null;
roleEntity?: { id: string; name: string; color: string | null } | null;
startDate: Date | string;
endDate: Date | string;
hoursPerDay: number;
headcount: number;
budgetCents?: number;
requestedHeadcount: number;
unfilledHeadcount: number;
status: string;
project?: { id: string; name: string; shortCode: string };
assignments?: Array<{ dailyCostCents: number; startDate: Date | string; endDate: Date | string; status: string }>;
}
interface ProjectDemandsTableProps {
demands: DemandRow[];
project: { id: string; name: string; shortCode: string };
}
export function ProjectDemandsTable({ demands, project }: ProjectDemandsTableProps) {
const [fillTarget, setFillTarget] = useState<OpenDemandAssignment | null>(null);
const [editTarget, setEditTarget] = useState<AllocationWithDetails | null>(null);
const { canEdit } = usePermissions();
const router = useRouter();
const utils = trpc.useUtils();
function handleMutationSuccess() {
// Invalidate budget status so BudgetStatusCard refetches
void utils.timeline.getBudgetStatus.invalidate();
void utils.allocation.listView.invalidate();
router.refresh();
}
const activeDemands = demands.filter((d) => d.status !== "CANCELLED" && d.status !== "COMPLETED");
const allDemands = demands;
return (
<>
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider">
Open Demands ({allDemands.length})
</h2>
{activeDemands.length > 0 && (
<span className="text-xs text-amber-600 dark:text-amber-400">
{activeDemands.reduce((sum, d) => sum + d.unfilledHeadcount, 0)} seats unfilled
</span>
)}
</div>
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Role
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Period
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
<span className="inline-flex items-center justify-end gap-0.5">
Headcount <InfoTooltip content="Requested / Unfilled seats for this demand." />
</span>
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Hours/Day
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
<span className="inline-flex items-center justify-end gap-0.5">
Budget <InfoTooltip content="Allocated role budget vs. booked cost from assignments." />
</span>
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Status
</th>
{canEdit && (
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Actions
</th>
)}
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{allDemands.map((demand) => {
const isFillable = demand.status !== "CANCELLED" && demand.status !== "COMPLETED" && demand.unfilledHeadcount > 0;
return (
<tr key={demand.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/30 transition-colors">
<td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100">
{demand.roleEntity?.name ?? demand.role ?? "Unassigned"}
</td>
<td className="px-4 py-3 text-xs text-gray-500 dark:text-gray-400">
{formatDate(demand.startDate)} {formatDate(demand.endDate)}
</td>
<td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">
<span className="font-medium">{demand.unfilledHeadcount}</span>
<span className="text-gray-400"> / {demand.requestedHeadcount}</span>
</td>
<td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">{demand.hoursPerDay}h</td>
<td className="px-4 py-3 text-right text-sm">
{demand.budgetCents && demand.budgetCents > 0 ? (() => {
// Calculate booked cost from assignments
const bookedCents = (demand.assignments ?? [])
.filter((a) => a.status !== "CANCELLED")
.reduce((sum, a) => {
const s = new Date(a.startDate);
const e = new Date(a.endDate);
let days = 0;
const cur = new Date(s);
while (cur <= e) { if (cur.getDay() !== 0 && cur.getDay() !== 6) days++; cur.setDate(cur.getDate() + 1); }
return sum + a.dailyCostCents * days;
}, 0);
const remainCents = demand.budgetCents! - bookedCents;
return (
<div>
<div className="text-gray-900 dark:text-gray-100">
{(demand.budgetCents! / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} EUR
</div>
<div className={`text-xs ${remainCents < 0 ? "text-red-500" : "text-gray-400"}`}>
{bookedCents > 0 ? `${(bookedCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} booked` : ""}
{remainCents < 0 ? ` (${(Math.abs(remainCents) / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} over)` : ""}
</div>
</div>
);
})() : (
<span className="text-gray-400 text-xs"></span>
)}
</td>
<td className="px-4 py-3">
<span className={`inline-block px-2 py-0.5 text-xs rounded-full ${ALLOC_STATUS_COLORS[demand.status] ?? "bg-gray-100 text-gray-600"}`}>
{demand.status}
</span>
</td>
{canEdit && (
<td className="px-4 py-3 text-right">
<div className="flex items-center justify-end gap-2">
<button
type="button"
onClick={() => setEditTarget(demand as unknown as AllocationWithDetails)}
className="text-xs font-medium text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200"
>
Edit
</button>
{isFillable && (
<button
type="button"
onClick={() => setFillTarget({
id: demand.id,
projectId: demand.projectId,
roleId: demand.roleId,
role: demand.role,
headcount: demand.headcount,
...(demand.budgetCents ? { budgetCents: demand.budgetCents } : {}),
startDate: new Date(demand.startDate),
endDate: new Date(demand.endDate),
hoursPerDay: demand.hoursPerDay,
roleEntity: demand.roleEntity ?? null,
project,
})}
className="inline-flex items-center gap-1 text-xs font-medium text-brand-600 hover:text-brand-800 dark:text-brand-400 dark:hover:text-brand-200"
>
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
</svg>
Assign
</button>
)}
</div>
</td>
)}
</tr>
);
})}
</tbody>
</table>
{allDemands.length === 0 && (
<div className="text-center py-12 text-gray-500 dark:text-gray-400 text-sm">No open demands for this project.</div>
)}
</div>
{fillTarget && (
<FillOpenDemandModal
allocation={fillTarget as never}
onClose={() => { setFillTarget(null); handleMutationSuccess(); }}
onSuccess={() => { setFillTarget(null); handleMutationSuccess(); }}
/>
)}
{editTarget && (
<AllocationModal
allocation={editTarget}
onClose={() => { setEditTarget(null); handleMutationSuccess(); }}
onSuccess={() => { setEditTarget(null); handleMutationSuccess(); }}
/>
)}
</>
);
}
@@ -0,0 +1,98 @@
"use client";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import type { Project } from "@planarchy/shared";
import { ProjectModal } from "./ProjectModal.js";
import { ConfirmDialog } from "~/components/ui/ConfirmDialog.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { trpc } from "~/lib/trpc/client.js";
interface ProjectDetailActionsProps {
project: Project;
}
export function ProjectDetailActions({ project }: ProjectDetailActionsProps) {
const [editOpen, setEditOpen] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const { canEdit, role } = usePermissions();
const isAdmin = role === "ADMIN";
const router = useRouter();
const { data: favoriteIds } = trpc.user.getFavoriteProjectIds.useQuery(undefined, { staleTime: 30_000 });
const isFavorite = useMemo(() => (favoriteIds ?? []).includes(project.id), [favoriteIds, project.id]);
const utils = trpc.useUtils();
const toggleFav = trpc.user.toggleFavoriteProject.useMutation({
onSuccess: () => void utils.user.getFavoriteProjectIds.invalidate(),
});
const deleteMutation = trpc.project.delete.useMutation({
onSuccess: () => {
router.push("/projects");
},
});
return (
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => toggleFav.mutate({ projectId: project.id })}
className={`text-xl transition-colors ${isFavorite ? "text-amber-500 hover:text-amber-600" : "text-gray-300 hover:text-amber-400 dark:text-gray-600 dark:hover:text-amber-500"}`}
title={isFavorite ? "Remove from favorites" : "Add to favorites"}
>
{isFavorite ? "★" : "☆"}
</button>
{canEdit && (
<button
type="button"
onClick={() => setEditOpen(true)}
className="inline-flex items-center gap-2 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 transition dark:border-gray-600 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
Edit
</button>
)}
{isAdmin && (
<button
type="button"
onClick={() => setConfirmDelete(true)}
disabled={deleteMutation.isPending}
className="inline-flex items-center gap-2 rounded-lg border border-red-300 bg-white px-3 py-2 text-sm font-medium text-red-600 shadow-sm hover:bg-red-50 transition disabled:opacity-50 dark:border-red-700 dark:bg-gray-800 dark:text-red-400 dark:hover:bg-red-900/20"
>
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
Delete
</button>
)}
{editOpen && (
<ProjectModal
project={project}
onClose={() => {
setEditOpen(false);
router.refresh();
}}
/>
)}
{confirmDelete && (
<ConfirmDialog
title="Delete Project"
message={`Permanently delete "${project.name}" (${(project as unknown as { shortCode: string }).shortCode})? This will also delete all assignments and demand requirements. This cannot be undone.`}
confirmLabel="Delete Project"
variant="danger"
onConfirm={() => {
deleteMutation.mutate({ id: project.id });
setConfirmDelete(false);
}}
onCancel={() => setConfirmDelete(false)}
/>
)}
</div>
);
}
@@ -5,6 +5,7 @@ import { clsx } from "clsx";
import type { StaffingRequirement } from "@planarchy/shared"; import type { StaffingRequirement } from "@planarchy/shared";
import { BlueprintTarget, OrderType, AllocationType, ProjectStatus, AllocationStatus } from "@planarchy/shared"; import { BlueprintTarget, OrderType, AllocationType, ProjectStatus, AllocationStatus } from "@planarchy/shared";
import { trpc } from "~/lib/trpc/client.js"; import { trpc } from "~/lib/trpc/client.js";
import { uuid } from "~/lib/uuid.js";
import { DateInput } from "~/components/ui/DateInput.js"; import { DateInput } from "~/components/ui/DateInput.js";
import { SkillTagInput } from "~/components/ui/SkillTagInput.js"; import { SkillTagInput } from "~/components/ui/SkillTagInput.js";
import { usePermissions } from "~/hooks/usePermissions.js"; import { usePermissions } from "~/hooks/usePermissions.js";
@@ -93,7 +94,7 @@ function makeDefaultState(): WizardState {
function makeReq(): StaffingRequirement { function makeReq(): StaffingRequirement {
return { return {
id: crypto.randomUUID(), id: uuid(),
role: "", role: "",
requiredSkills: [], requiredSkills: [],
preferredSkills: [], preferredSkills: [],
@@ -301,29 +302,26 @@ function Step1({ state, onChange }: Step1Props) {
function ResourcePersonPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) { function ResourcePersonPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [query, setQuery] = useState(value); const [query, setQuery] = useState(value);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [debouncedSearch, setDebouncedSearch] = useState("");
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
// Debounce search query to avoid excessive API calls
useEffect(() => {
const timer = setTimeout(() => setDebouncedSearch(query), 200);
return () => clearTimeout(timer);
}, [query]);
// Server-side search — no client-side limit, searches full database
const { data } = trpc.resource.list.useQuery( const { data } = trpc.resource.list.useQuery(
{ isActive: true }, { isActive: true, search: debouncedSearch || undefined, limit: 30 },
{ staleTime: 60_000 }, // eslint-disable-next-line @typescript-eslint/no-explicit-any
{ staleTime: 15_000, placeholderData: (prev: any) => prev },
); );
const resources = useMemo( const filtered = useMemo(
() => (data?.resources ?? []) as unknown as Array<{ id: string; displayName: string; eid: string }>, () => (data?.resources ?? []) as unknown as Array<{ id: string; displayName: string; eid: string }>,
[data], [data],
); );
const filtered = useMemo(() => {
const q = query.toLowerCase().replace(/[-_\s]/g, "");
if (!q) return resources.slice(0, 20);
return resources
.filter((r) => {
const name = r.displayName.toLowerCase().replace(/[-_\s]/g, "");
const eid = r.eid.toLowerCase();
return name.includes(q) || eid.includes(q);
})
.slice(0, 20);
}, [resources, query]);
// Sync local query when external value changes (e.g. wizard reset) // Sync local query when external value changes (e.g. wizard reset)
useEffect(() => { useEffect(() => {
setQuery(value); setQuery(value);
@@ -490,6 +488,30 @@ function Step3({ state, onChange }: Step3Props) {
</div> </div>
)} )}
{/* Budget allocation summary */}
{state.budgetEur && parseFloat(state.budgetEur) > 0 && state.staffingReqs.length > 0 && (() => {
const projectBudgetCents = Math.round(parseFloat(state.budgetEur || "0") * 100);
const allocatedCents = state.staffingReqs.reduce((sum, r) => sum + (r.budgetCents ?? 0), 0);
const remainingCents = projectBudgetCents - allocatedCents;
const pct = projectBudgetCents > 0 ? Math.round((allocatedCents / projectBudgetCents) * 100) : 0;
return (
<div className={`mb-3 rounded-lg border p-3 text-xs ${remainingCents < 0 ? "bg-red-50 border-red-200 text-red-700" : remainingCents === 0 ? "bg-green-50 border-green-200 text-green-700" : "bg-amber-50 border-amber-200 text-amber-700"}`}>
<div className="flex items-center justify-between mb-1.5">
<span className="font-semibold">Budget Allocation</span>
<span>{pct}% allocated</span>
</div>
<div className="w-full h-1.5 bg-gray-200 rounded-full overflow-hidden mb-1.5">
<div className={`h-full rounded-full transition-all ${remainingCents < 0 ? "bg-red-500" : remainingCents === 0 ? "bg-green-500" : "bg-amber-500"}`} style={{ width: `${Math.min(100, pct)}%` }} />
</div>
<div className="flex justify-between">
<span>Project: {(projectBudgetCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} EUR</span>
<span>Allocated: {(allocatedCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} EUR</span>
<span className="font-semibold">Remaining: {(remainingCents / 100).toLocaleString("de-DE", { minimumFractionDigits: 2 })} EUR</span>
</div>
</div>
);
})()}
<div className="space-y-3 max-h-[45vh] overflow-y-auto pr-1"> <div className="space-y-3 max-h-[45vh] overflow-y-auto pr-1">
{state.staffingReqs.length === 0 && ( {state.staffingReqs.length === 0 && (
<p className="text-sm text-gray-400 text-center py-8"> <p className="text-sm text-gray-400 text-center py-8">
@@ -557,6 +579,21 @@ function Step3({ state, onChange }: Step3Props) {
className={INPUT_CLS} className={INPUT_CLS}
/> />
</div> </div>
<div className="w-28">
<label className="text-xs text-gray-400">Budget (EUR)</label>
<input
type="number"
value={req.budgetCents ? req.budgetCents / 100 : ""}
min={0}
step={100}
onChange={(e) => {
const val = parseFloat(e.target.value);
updateReq(idx, { budgetCents: Number.isFinite(val) && val > 0 ? Math.round(val * 100) : 0 } as Partial<StaffingRequirement>);
}}
placeholder="0"
className={INPUT_CLS}
/>
</div>
<div className="pt-5"> <div className="pt-5">
<button <button
type="button" type="button"
@@ -7,7 +7,8 @@ import {
type Assignment, type Assignment,
type DemandRequirement, type DemandRequirement,
} from "@planarchy/shared"; } from "@planarchy/shared";
import { createContext, useContext, useMemo, useState, type ReactNode } from "react"; import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useSearchParams } from "next/navigation";
import { useTimelineSSE } from "~/hooks/useTimelineSSE.js"; import { useTimelineSSE } from "~/hooks/useTimelineSSE.js";
import { trpc } from "~/lib/trpc/client.js"; import { trpc } from "~/lib/trpc/client.js";
import { readAppPreferences, useAppPreferences } from "~/hooks/useAppPreferences.js"; import { readAppPreferences, useAppPreferences } from "~/hooks/useAppPreferences.js";
@@ -176,20 +177,104 @@ export function TimelineProvider({
isDragging, isDragging,
children, children,
}: TimelineProviderProps) { }: TimelineProviderProps) {
const searchParams = useSearchParams();
const today = useMemo(() => { const today = useMemo(() => {
const d = new Date(); const d = new Date();
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
return d; return d;
}, []); }, []);
const [viewStart, setViewStart] = useState(() => addDays(today, -30)); // Support URL params: ?startDate=2026-01-01&days=120
const [viewDays, setViewDays] = useState(180); const [viewStart, setViewStart] = useState(() => {
const sp = searchParams.get("startDate");
if (sp) {
const d = new Date(sp);
if (!isNaN(d.getTime())) return d;
}
return addDays(today, -30);
});
const [viewDays, setViewDays] = useState(() => {
const sp = searchParams.get("days");
if (sp) {
const n = parseInt(sp, 10);
if (n > 0 && n <= 365) return n;
}
return 180;
});
const viewEnd = addDays(viewStart, viewDays); const viewEnd = addDays(viewStart, viewDays);
const [filters, setFilters] = useState<TimelineFilters>(() => ({ // Support URL params: ?eids=EMP-001,EMP-002&projectIds=id1,id2&chapters=ch1
const [filters, setFilters] = useState<TimelineFilters>(() => {
const base: TimelineFilters = {
...DEFAULT_FILTERS, ...DEFAULT_FILTERS,
hideCompletedProjects: readAppPreferences().hideCompletedProjects, hideCompletedProjects: readAppPreferences().hideCompletedProjects,
})); };
const eids = searchParams.get("eids");
if (eids) base.eids = eids.split(",").filter(Boolean);
const projectIds = searchParams.get("projectIds");
if (projectIds) base.projectIds = projectIds.split(",").filter(Boolean);
const chapters = searchParams.get("chapters");
if (chapters) base.chapters = chapters.split(",").filter(Boolean);
const clientIds = searchParams.get("clientIds");
if (clientIds) base.clientIds = clientIds.split(",").filter(Boolean);
const countryCodes = searchParams.get("countryCodes");
if (countryCodes) base.countryCodes = countryCodes.split(",").filter(Boolean);
// If URL params specify filters, also show drafts and don't hide completed
if (eids || projectIds) {
base.showDrafts = true;
base.hideCompletedProjects = false;
}
return base;
});
// Track whether this is the initial mount (URL params already applied via useState initializers)
const isInitialMount = useRef(true);
// Sync filters/viewStart/viewDays when URL search params change AFTER initial mount
// (e.g. when the AI assistant calls router.push("/timeline?eids=...") while already on /timeline)
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
// Update viewStart if param changed
const spStart = searchParams.get("startDate");
if (spStart) {
const d = new Date(spStart);
if (!isNaN(d.getTime())) setViewStart(d);
}
// Update viewDays if param changed
const spDays = searchParams.get("days");
if (spDays) {
const n = parseInt(spDays, 10);
if (n > 0 && n <= 365) setViewDays(n);
}
// Update filters if any filter params present
const eids = searchParams.get("eids");
const projectIds = searchParams.get("projectIds");
const chapters = searchParams.get("chapters");
const clientIds = searchParams.get("clientIds");
const countryCodes = searchParams.get("countryCodes");
if (eids || projectIds || chapters || clientIds || countryCodes) {
setFilters((prev) => {
const next = { ...prev };
if (eids) next.eids = eids.split(",").filter(Boolean);
if (projectIds) next.projectIds = projectIds.split(",").filter(Boolean);
if (chapters) next.chapters = chapters.split(",").filter(Boolean);
if (clientIds) next.clientIds = clientIds.split(",").filter(Boolean);
if (countryCodes) next.countryCodes = countryCodes.split(",").filter(Boolean);
if (eids || projectIds) {
next.showDrafts = true;
next.hideCompletedProjects = false;
}
return next;
});
}
}, [searchParams]);
const [filterOpen, setFilterOpen] = useState(false); const [filterOpen, setFilterOpen] = useState(false);
const [viewMode, setViewMode] = useState<ViewMode>("resource"); const [viewMode, setViewMode] = useState<ViewMode>("resource");
@@ -208,6 +293,7 @@ export function TimelineProvider({
...(filters.projectIds.length > 0 ? { projectIds: filters.projectIds } : {}), ...(filters.projectIds.length > 0 ? { projectIds: filters.projectIds } : {}),
...(filters.chapters.length > 0 ? { chapters: filters.chapters } : {}), ...(filters.chapters.length > 0 ? { chapters: filters.chapters } : {}),
...(filters.eids.length > 0 ? { eids: filters.eids } : {}), ...(filters.eids.length > 0 ? { eids: filters.eids } : {}),
...(filters.countryCodes.length > 0 ? { countryCodes: filters.countryCodes } : {}),
}, },
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
{ placeholderData: (prev: any) => prev }, { placeholderData: (prev: any) => prev },
@@ -259,6 +345,10 @@ export function TimelineProvider({
if (entry.project.status === "DRAFT" && !filters.showDrafts) return false; if (entry.project.status === "DRAFT" && !filters.showDrafts) return false;
if (DONE_STATUSES.has(entry.project.status) && filters.hideCompletedProjects) return false; if (DONE_STATUSES.has(entry.project.status) && filters.hideCompletedProjects) return false;
if (!filters.showPlaceholders) return false; if (!filters.showPlaceholders) return false;
// Hide fully-filled demands (status COMPLETED or unfilledHeadcount <= 0)
const demandEntry = entry as { status?: string; unfilledHeadcount?: number };
if (demandEntry.status === "COMPLETED") return false;
if (typeof demandEntry.unfilledHeadcount === "number" && demandEntry.unfilledHeadcount <= 0) return false;
return true; return true;
}), }),
[demands, filters.hideCompletedProjects, filters.showDrafts, filters.showPlaceholders], [demands, filters.hideCompletedProjects, filters.showDrafts, filters.showPlaceholders],
@@ -469,7 +559,8 @@ export function TimelineProvider({
filters.clientIds.length + filters.clientIds.length +
filters.chapters.length + filters.chapters.length +
filters.eids.length + filters.eids.length +
filters.projectIds.length; filters.projectIds.length +
filters.countryCodes.length;
const value = useMemo<TimelineContextValue>( const value = useMemo<TimelineContextValue>(
() => ({ () => ({
@@ -26,6 +26,8 @@ export interface TimelineFilters {
showVacations: boolean; showVacations: boolean;
/** Show open-demand entries (no resource assigned yet). Default: true. */ /** Show open-demand entries (no resource assigned yet). Default: true. */
showPlaceholders: boolean; showPlaceholders: boolean;
/** Filter to specific country IDs */
countryCodes: string[];
} }
export const DEFAULT_FILTERS: TimelineFilters = { export const DEFAULT_FILTERS: TimelineFilters = {
@@ -33,6 +35,7 @@ export const DEFAULT_FILTERS: TimelineFilters = {
chapters: [], chapters: [],
eids: [], eids: [],
projectIds: [], projectIds: [],
countryCodes: [],
showWeekends: false, showWeekends: false,
zoom: "day", zoom: "day",
hideCompletedProjects: true, // overridden at runtime from AppPreferences hideCompletedProjects: true, // overridden at runtime from AppPreferences
@@ -212,7 +215,8 @@ export function TimelineFilter({
filters.clientIds.length + filters.clientIds.length +
filters.chapters.length + filters.chapters.length +
filters.eids.length + filters.eids.length +
filters.projectIds.length; filters.projectIds.length +
filters.countryCodes.length;
return createPortal( return createPortal(
<div <div
@@ -65,6 +65,7 @@ export interface OpenDemandAssignment {
roleId: string | null; roleId: string | null;
role: string | null; role: string | null;
headcount: number; headcount: number;
budgetCents?: number;
startDate: Date; startDate: Date;
endDate: Date; endDate: Date;
hoursPerDay: number; hoursPerDay: number;
@@ -402,7 +403,18 @@ export function TimelineProjectPanel({
const rowVirtualizer = useVirtualizer({ const rowVirtualizer = useVirtualizer({
count: flatRows.length, count: flatRows.length,
getScrollElement: () => scrollContainerRef.current, getScrollElement: () => scrollContainerRef.current,
estimateSize: (index) => (flatRows[index]?.type === "header" ? PROJECT_HEADER_HEIGHT : ROW_HEIGHT), estimateSize: (index) => {
const row = flatRows[index];
if (!row) return ROW_HEIGHT;
if (row.type === "header") return PROJECT_HEADER_HEIGHT;
if (row.type === "open-demand") {
const laneCount = assignDemandLanes(row.openDemands).size > 0
? Math.max(...assignDemandLanes(row.openDemands).values()) + 1
: 1;
return Math.max(ROW_HEIGHT, laneCount * (DEMAND_LANE_HEIGHT + DEMAND_LANE_GAP) + 8);
}
return ROW_HEIGHT;
},
overscan: 8, overscan: 8,
getItemKey: (index) => flatRows[index]?.key ?? index, getItemKey: (index) => flatRows[index]?.key ?? index,
}); });
@@ -902,6 +914,42 @@ function ProjectPanelTooltips({
// ─── Pure render functions ────────────────────────────────────────────────── // ─── Pure render functions ──────────────────────────────────────────────────
/** Assign lane indices to demands so overlapping bars don't stack on top of each other. */
function assignDemandLanes(
demands: TimelineDemandEntry[],
): Map<string, number> {
const laneMap = new Map<string, number>();
// Each lane tracks the latest end-date occupying it
const laneEnds: Date[] = [];
// Sort by start date for greedy lane assignment
const sorted = [...demands].sort(
(a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime(),
);
for (const d of sorted) {
const start = new Date(d.startDate);
let assigned = -1;
for (let i = 0; i < laneEnds.length; i++) {
if (laneEnds[i]! < start) {
assigned = i;
laneEnds[i] = new Date(d.endDate);
break;
}
}
if (assigned === -1) {
assigned = laneEnds.length;
laneEnds.push(new Date(d.endDate));
}
laneMap.set(d.id, assigned);
}
return laneMap;
}
const DEMAND_LANE_HEIGHT = 30;
const DEMAND_LANE_GAP = 2;
function renderOpenDemandRow( function renderOpenDemandRow(
openDemands: TimelineDemandEntry[], openDemands: TimelineDemandEntry[],
CELL_WIDTH: number, CELL_WIDTH: number,
@@ -913,14 +961,18 @@ function renderOpenDemandRow(
) { ) {
if (openDemands.length === 0) return null; if (openDemands.length === 0) return null;
const laneMap = assignDemandLanes(openDemands);
const laneCount = laneMap.size > 0 ? Math.max(...laneMap.values()) + 1 : 1;
const rowHeight = Math.max(ROW_HEIGHT, laneCount * (DEMAND_LANE_HEIGHT + DEMAND_LANE_GAP) + 8);
return ( return (
<div <div
className="flex border-b border-dashed border-amber-200 bg-amber-50/30 hover:bg-amber-50/50 group" className="flex border-b border-dashed border-amber-200 bg-amber-50/30 hover:bg-amber-50/50 group"
style={{ height: ROW_HEIGHT }} style={{ minHeight: rowHeight }}
> >
<div <div
className="flex-shrink-0 border-r border-amber-200 flex items-center pl-8 pr-4 gap-2 bg-amber-50 sticky left-0 z-30" className="flex-shrink-0 border-r border-amber-200 flex items-center pl-8 pr-4 gap-2 bg-amber-50 sticky left-0 z-30"
style={{ width: LABEL_WIDTH }} style={{ width: LABEL_WIDTH, minHeight: rowHeight }}
> >
<div className="w-6 h-6 rounded-full bg-amber-100 flex items-center justify-center text-[10px] font-bold text-amber-600 flex-shrink-0 border border-dashed border-amber-400"> <div className="w-6 h-6 rounded-full bg-amber-100 flex items-center justify-center text-[10px] font-bold text-amber-600 flex-shrink-0 border border-dashed border-amber-400">
? ?
@@ -935,7 +987,7 @@ function renderOpenDemandRow(
<div <div
className="relative overflow-hidden" className="relative overflow-hidden"
style={{ width: totalCanvasWidth, height: ROW_HEIGHT, ...rowGridStyle }} style={{ width: totalCanvasWidth, minHeight: rowHeight, ...rowGridStyle }}
> >
{openDemands.map((alloc) => { {openDemands.map((alloc) => {
const allocStart = new Date(alloc.startDate); const allocStart = new Date(alloc.startDate);
@@ -951,6 +1003,8 @@ function renderOpenDemandRow(
roleEntity?.name ?? (alloc as { role?: string | null }).role ?? "Open demand"; roleEntity?.name ?? (alloc as { role?: string | null }).role ?? "Open demand";
const roleColor = roleEntity?.color ?? "#f59e0b"; const roleColor = roleEntity?.color ?? "#f59e0b";
const headcount = (alloc as { headcount?: number }).headcount ?? 1; const headcount = (alloc as { headcount?: number }).headcount ?? 1;
const lane = laneMap.get(alloc.id) ?? 0;
const top = 4 + lane * (DEMAND_LANE_HEIGHT + DEMAND_LANE_GAP);
return ( return (
<div <div
@@ -959,8 +1013,8 @@ function renderOpenDemandRow(
style={{ style={{
left: left + 2, left: left + 2,
width: width - 4, width: width - 4,
top: 8, top,
height: SUB_LANE_HEIGHT - 8, height: DEMAND_LANE_HEIGHT,
backgroundColor: `${roleColor}33`, backgroundColor: `${roleColor}33`,
border: `2px dashed ${roleColor}99`, border: `2px dashed ${roleColor}99`,
}} }}
@@ -1118,7 +1172,8 @@ function renderProjectDragHandles(
const width = Math.max(CELL_WIDTH, toWidth(dispStart, dispEnd)); const width = Math.max(CELL_WIDTH, toWidth(dispStart, dispEnd));
if (width <= 0 || left >= totalCanvasWidth) return null; if (width <= 0 || left >= totalCanvasWidth) return null;
const HANDLE_W = width >= 48 ? 8 : 0; // Always show resize handles — for narrow bars, use overlapping handles
const HANDLE_W = width >= 48 ? 8 : 6;
const hasRecurrence = !!(alloc.metadata as Record<string, unknown> | null)?.recurrence; const hasRecurrence = !!(alloc.metadata as Record<string, unknown> | null)?.recurrence;
const allocInfo: AllocMouseDownInfo = { const allocInfo: AllocMouseDownInfo = {
@@ -1153,7 +1208,6 @@ function renderProjectDragHandles(
); );
}} }}
> >
{HANDLE_W > 0 && (
<div <div
className="flex-shrink-0 cursor-ew-resize" className="flex-shrink-0 cursor-ew-resize"
style={{ width: HANDLE_W }} style={{ width: HANDLE_W }}
@@ -1163,7 +1217,6 @@ function renderProjectDragHandles(
onAllocTouchStart(e, { ...allocInfo, mode: "resize-start" }); onAllocTouchStart(e, { ...allocInfo, mode: "resize-start" });
}} }}
/> />
)}
<div <div
className={clsx( className={clsx(
"flex-1 min-w-0 flex items-center", "flex-1 min-w-0 flex items-center",
@@ -1181,7 +1234,6 @@ function renderProjectDragHandles(
</span> </span>
)} )}
</div> </div>
{HANDLE_W > 0 && (
<div <div
className="flex-shrink-0 cursor-ew-resize" className="flex-shrink-0 cursor-ew-resize"
style={{ width: HANDLE_W }} style={{ width: HANDLE_W }}
@@ -1191,7 +1243,6 @@ function renderProjectDragHandles(
onAllocTouchStart(e, { ...allocInfo, mode: "resize-end" }); onAllocTouchStart(e, { ...allocInfo, mode: "resize-end" });
}} }}
/> />
)}
</div> </div>
); );
}); });
@@ -162,6 +162,10 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
{ isActive: true }, { isActive: true },
{ staleTime: 60_000 }, { staleTime: 60_000 },
); );
const { data: countriesData } = trpc.country.list.useQuery(
{ isActive: true },
{ staleTime: 60_000 },
);
const resources = ((resourceData?.resources as ResourceOption[] | undefined) ?? []).slice(); const resources = ((resourceData?.resources as ResourceOption[] | undefined) ?? []).slice();
const eidSuggestions = ( const eidSuggestions = (
@@ -189,6 +193,14 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
[clientsData], [clientsData],
); );
const countries = useMemo(
() =>
((countriesData ?? []) as Array<{ id: string; code: string; name: string }>)
.map((c) => ({ id: c.id, code: c.code, name: c.name }))
.sort((a, b) => a.name.localeCompare(b.name)),
[countriesData],
);
const resourceMap = useMemo( const resourceMap = useMemo(
() => new Map(resources.map((resource) => [resource.eid, resource])), () => new Map(resources.map((resource) => [resource.eid, resource])),
[resources], [resources],
@@ -197,6 +209,10 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
() => new Map(clients.map((client) => [client.id, client])), () => new Map(clients.map((client) => [client.id, client])),
[clients], [clients],
); );
const countryMap = useMemo(
() => new Map(countries.map((c) => [c.code, c])),
[countries],
);
const clientLabel = buildSelectionLabel("Clients", filters.clientIds.length, clients.length || 1); const clientLabel = buildSelectionLabel("Clients", filters.clientIds.length, clients.length || 1);
const chapterLabel = buildSelectionLabel( const chapterLabel = buildSelectionLabel(
@@ -204,6 +220,11 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
filters.chapters.length, filters.chapters.length,
chapters.length || 1, chapters.length || 1,
); );
const countryLabel = buildSelectionLabel(
"Countries",
filters.countryCodes.length,
countries.length || 1,
);
const peopleLabel = const peopleLabel =
filters.eids.length === 0 ? "All people" : `People: ${filters.eids.length}`; filters.eids.length === 0 ? "All people" : `People: ${filters.eids.length}`;
@@ -225,6 +246,17 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
onChange({ ...filters, chapters: nextChapters }); onChange({ ...filters, chapters: nextChapters });
} }
function toggleCountry(code: string) {
const next = filters.countryCodes.includes(code)
? filters.countryCodes.filter((c) => c !== code)
: [...filters.countryCodes, code].sort((a, b) => {
const aName = countryMap.get(a)?.name ?? a;
const bName = countryMap.get(b)?.name ?? b;
return aName.localeCompare(bName);
});
onChange({ ...filters, countryCodes: next });
}
function addEid(eid: string) { function addEid(eid: string) {
if (filters.eids.includes(eid)) return; if (filters.eids.includes(eid)) return;
onChange({ ...filters, eids: [...filters.eids, eid] }); onChange({ ...filters, eids: [...filters.eids, eid] });
@@ -260,7 +292,13 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
<input <input
type="checkbox" type="checkbox"
checked={filters.clientIds.length === 0} checked={filters.clientIds.length === 0}
onChange={() => onChange({ ...filters, clientIds: [] })} ref={(el) => {
if (el) el.indeterminate = filters.clientIds.length > 0 && filters.clientIds.length < clients.length;
}}
onChange={() => {
// Toggle all ↔ none: if showing all → select all explicitly; if any selected → clear filter (show all)
onChange({ ...filters, clientIds: filters.clientIds.length === 0 ? clients.map((c) => c.id) : [] });
}}
className="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500 dark:border-gray-600" className="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500 dark:border-gray-600"
/> />
<span className="font-medium">All clients</span> <span className="font-medium">All clients</span>
@@ -336,6 +374,56 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
</div> </div>
</TimelineFilterDropdown> </TimelineFilterDropdown>
<TimelineFilterDropdown
label={countryLabel}
widthClassName="w-80"
tooltipContent="Multi-select country filter. Checked countries stay visible in both timeline views."
>
<div className="mb-3 flex items-start justify-between gap-3">
<div>
<h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">Countries</h2>
<p className="text-xs text-gray-500">Checked countries stay visible.</p>
</div>
<button
type="button"
onClick={() => onChange({ ...filters, countryCodes: [] })}
className="text-xs font-medium text-brand-600 hover:text-brand-800 dark:text-brand-300 dark:hover:text-brand-100"
>
Show all
</button>
</div>
<div className="rounded-xl border border-gray-200 dark:border-gray-700">
<label className="flex items-center gap-3 border-b border-gray-200 px-3 py-2 text-sm text-gray-700 dark:border-gray-700 dark:text-gray-200">
<input
type="checkbox"
checked={filters.countryCodes.length === 0}
onChange={() => onChange({ ...filters, countryCodes: [] })}
className="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500 dark:border-gray-600"
/>
<span className="font-medium">All countries</span>
</label>
<div className="max-h-64 overflow-auto">
{countries.map((country) => (
<label
key={country.code}
className="flex items-center gap-3 border-b border-gray-100 px-3 py-2 text-sm text-gray-700 last:border-b-0 hover:bg-gray-50 dark:border-gray-800 dark:text-gray-200 dark:hover:bg-gray-800"
>
<input
type="checkbox"
checked={filters.countryCodes.length === 0 || filters.countryCodes.includes(country.code)}
onChange={() => toggleCountry(country.code)}
className="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500 dark:border-gray-600"
/>
<span className="min-w-0 flex-1 truncate">{country.name}</span>
<span className="flex-shrink-0 text-xs text-gray-400 dark:text-gray-500">
{country.code}
</span>
</label>
))}
</div>
</div>
</TimelineFilterDropdown>
<TimelineFilterDropdown <TimelineFilterDropdown
label={peopleLabel} label={peopleLabel}
widthClassName="w-96" widthClassName="w-96"
@@ -781,7 +781,7 @@ function renderAllocBlocksFromData(
text: "text-white", text: "text-white",
light: "", light: "",
}; };
const HANDLE_W = width >= 48 ? 10 : 0; const HANDLE_W = width >= 48 ? 10 : 6;
const hasRecurrence = !!(alloc.metadata as Record<string, unknown> | null)?.recurrence; const hasRecurrence = !!(alloc.metadata as Record<string, unknown> | null)?.recurrence;
const allocInfo: AllocMouseDownInfo = { const allocInfo: AllocMouseDownInfo = {
@@ -821,7 +821,6 @@ function renderAllocBlocksFromData(
}} }}
> >
{/* Left resize handle */} {/* Left resize handle */}
{HANDLE_W > 0 && (
<div <div
className="flex-shrink-0 flex items-center justify-center cursor-ew-resize hover:bg-black/20 transition-colors" className="flex-shrink-0 flex items-center justify-center cursor-ew-resize hover:bg-black/20 transition-colors"
style={{ width: HANDLE_W }} style={{ width: HANDLE_W }}
@@ -831,12 +830,13 @@ function renderAllocBlocksFromData(
onAllocTouchStart(e, { ...allocInfo, mode: "resize-start" }); onAllocTouchStart(e, { ...allocInfo, mode: "resize-start" });
}} }}
> >
{HANDLE_W >= 10 && (
<div className="flex flex-col gap-0.5 opacity-60 group-hover/block:opacity-100"> <div className="flex flex-col gap-0.5 opacity-60 group-hover/block:opacity-100">
<div className="w-px h-2.5 bg-white rounded" /> <div className="w-px h-2.5 bg-white rounded" />
<div className="w-px h-2.5 bg-white rounded" /> <div className="w-px h-2.5 bg-white rounded" />
</div> </div>
</div>
)} )}
</div>
{/* Center -- move */} {/* Center -- move */}
<div <div
@@ -861,7 +861,6 @@ function renderAllocBlocksFromData(
</div> </div>
{/* Right resize handle */} {/* Right resize handle */}
{HANDLE_W > 0 && (
<div <div
className="flex-shrink-0 flex items-center justify-center cursor-ew-resize hover:bg-black/20 transition-colors" className="flex-shrink-0 flex items-center justify-center cursor-ew-resize hover:bg-black/20 transition-colors"
style={{ width: HANDLE_W }} style={{ width: HANDLE_W }}
@@ -871,13 +870,14 @@ function renderAllocBlocksFromData(
onAllocTouchStart(e, { ...allocInfo, mode: "resize-end" }); onAllocTouchStart(e, { ...allocInfo, mode: "resize-end" });
}} }}
> >
{HANDLE_W >= 10 && (
<div className="flex flex-col gap-0.5 opacity-60 group-hover/block:opacity-100"> <div className="flex flex-col gap-0.5 opacity-60 group-hover/block:opacity-100">
<div className="w-px h-2.5 bg-white rounded" /> <div className="w-px h-2.5 bg-white rounded" />
<div className="w-px h-2.5 bg-white rounded" /> <div className="w-px h-2.5 bg-white rounded" />
</div> </div>
</div>
)} )}
</div> </div>
</div>
); );
}); });
} }
@@ -46,7 +46,8 @@ export function TimelineToolbar({
filters.clientIds.length + filters.clientIds.length +
filters.chapters.length + filters.chapters.length +
filters.eids.length + filters.eids.length +
filters.projectIds.length; filters.projectIds.length +
filters.countryCodes.length;
const filterAnchorRef = useRef<HTMLDivElement | null>(null); const filterAnchorRef = useRef<HTMLDivElement | null>(null);
function clearQuickFilters() { function clearQuickFilters() {
+4 -2
View File
@@ -348,11 +348,13 @@ export function useTimelineDrag({
newEnd.setDate(newEnd.getDate() + daysDelta); newEnd.setDate(newEnd.getDate() + daysDelta);
} else if (alloc.mode === "resize-start") { } else if (alloc.mode === "resize-start") {
newStart.setDate(newStart.getDate() + daysDelta); newStart.setDate(newStart.getDate() + daysDelta);
if (newStart >= newEnd) newStart.setTime(newEnd.getTime() - 86400000); // Allow same-day (single day booking), prevent crossing
if (newStart > newEnd) newStart.setTime(newEnd.getTime());
} else { } else {
// resize-end // resize-end
newEnd.setDate(newEnd.getDate() + daysDelta); newEnd.setDate(newEnd.getDate() + daysDelta);
if (newEnd <= newStart) newEnd.setTime(newStart.getTime() + 86400000); // Allow same-day (single day booking), prevent crossing
if (newEnd < newStart) newEnd.setTime(newStart.getTime());
} }
const updated: AllocDragState = { const updated: AllocDragState = {
+10
View File
@@ -0,0 +1,10 @@
/** Generate a UUID v4, with fallback for non-secure contexts (plain HTTP). */
export function uuid(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
});
}
+129
View File
@@ -82,6 +82,7 @@ function toDemandRequirementUpdateInput(input: AllocationEntryUpdateInput) {
...(input.role !== undefined ? { role: input.role } : {}), ...(input.role !== undefined ? { role: input.role } : {}),
...(input.roleId !== undefined ? { roleId: input.roleId } : {}), ...(input.roleId !== undefined ? { roleId: input.roleId } : {}),
...(input.headcount !== undefined ? { headcount: input.headcount } : {}), ...(input.headcount !== undefined ? { headcount: input.headcount } : {}),
...(input.budgetCents !== undefined ? { budgetCents: input.budgetCents } : {}),
...(input.status !== undefined ? { status: input.status } : {}), ...(input.status !== undefined ? { status: input.status } : {}),
...(input.metadata !== undefined ? { metadata: input.metadata } : {}), ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
}; };
@@ -298,6 +299,134 @@ export const allocationRouter = createTRPCRouter({
); );
}), }),
/**
* Check a resource's availability for a date range.
* Returns working days, existing allocations, conflict days, and available capacity.
*/
checkResourceAvailability: protectedProcedure
.input(z.object({
resourceId: z.string(),
startDate: z.coerce.date(),
endDate: z.coerce.date(),
hoursPerDay: z.number().min(0.5).max(24).default(8),
}))
.query(async ({ ctx, input }) => {
const resource = await ctx.db.resource.findUnique({
where: { id: input.resourceId },
select: {
id: true, displayName: true, eid: true, fte: true,
country: { select: { dailyWorkingHours: true } },
},
});
if (!resource) throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
const dailyCapacity = (resource.country?.dailyWorkingHours ?? 8) * (resource.fte ?? 1);
// Get existing assignments in the date range
const existingAssignments = await ctx.db.assignment.findMany({
where: {
resourceId: input.resourceId,
status: { not: "CANCELLED" },
startDate: { lte: input.endDate },
endDate: { gte: input.startDate },
},
select: {
id: true, startDate: true, endDate: true, hoursPerDay: true, status: true,
project: { select: { name: true, shortCode: true } },
},
orderBy: { startDate: "asc" },
});
// Get vacations in the date range
const vacations = await ctx.db.vacation.findMany({
where: {
resourceId: input.resourceId,
status: "APPROVED",
startDate: { lte: input.endDate },
endDate: { gte: input.startDate },
},
select: { startDate: true, endDate: true, isHalfDay: true },
});
// Calculate day-by-day availability
let totalWorkingDays = 0;
let availableDays = 0;
let conflictDays = 0;
let partialDays = 0;
let totalAvailableHours = 0;
const requestedHpd = input.hoursPerDay;
const d = new Date(input.startDate);
const end = new Date(input.endDate);
while (d <= end) {
const dow = d.getDay();
if (dow !== 0 && dow !== 6) {
totalWorkingDays++;
// Check vacation
const isVacation = vacations.some((v) => {
const vs = new Date(v.startDate); vs.setHours(0, 0, 0, 0);
const ve = new Date(v.endDate); ve.setHours(0, 0, 0, 0);
const dc = new Date(d); dc.setHours(0, 0, 0, 0);
return dc >= vs && dc <= ve;
});
if (isVacation) {
conflictDays++;
d.setDate(d.getDate() + 1);
continue;
}
// Sum existing hours on this day
let bookedHours = 0;
for (const a of existingAssignments) {
const as2 = new Date(a.startDate); as2.setHours(0, 0, 0, 0);
const ae = new Date(a.endDate); ae.setHours(0, 0, 0, 0);
const dc = new Date(d); dc.setHours(0, 0, 0, 0);
if (dc >= as2 && dc <= ae) {
bookedHours += a.hoursPerDay;
}
}
const remainingCapacity = Math.max(0, dailyCapacity - bookedHours);
if (remainingCapacity >= requestedHpd) {
availableDays++;
totalAvailableHours += requestedHpd;
} else if (remainingCapacity > 0) {
partialDays++;
totalAvailableHours += remainingCapacity;
} else {
conflictDays++;
}
}
d.setDate(d.getDate() + 1);
}
const totalRequestedHours = totalWorkingDays * requestedHpd;
return {
resource: { id: resource.id, name: resource.displayName, eid: resource.eid },
dailyCapacity,
totalWorkingDays,
availableDays,
partialDays,
conflictDays,
totalAvailableHours: Math.round(totalAvailableHours * 10) / 10,
totalRequestedHours,
coveragePercent: totalRequestedHours > 0
? Math.round((totalAvailableHours / totalRequestedHours) * 100)
: 0,
existingAssignments: existingAssignments.map((a) => ({
project: a.project.name,
code: a.project.shortCode,
hoursPerDay: a.hoursPerDay,
start: a.startDate.toISOString().slice(0, 10),
end: a.endDate.toISOString().slice(0, 10),
status: a.status,
})),
};
}),
createDemandRequirement: managerProcedure createDemandRequirement: managerProcedure
.input(CreateDemandRequirementSchema) .input(CreateDemandRequirementSchema)
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
File diff suppressed because it is too large Load Diff
+197
View File
@@ -0,0 +1,197 @@
/**
* AI Assistant router — provides a chat endpoint that uses OpenAI Function Calling
* to answer questions about Planarchy data and modify resources/projects.
*/
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { resolvePermissions, type PermissionOverrides, type SystemRole } from "@planarchy/shared";
import { createTRPCRouter, protectedProcedure } from "../trpc.js";
import { createAiClient, isAiConfigured, parseAiError } from "../ai-client.js";
import { TOOL_DEFINITIONS, executeTool, type ToolContext, type ToolAction } from "./assistant-tools.js";
const MAX_TOOL_ITERATIONS = 8;
const SYSTEM_PROMPT = `Du bist der Planarchy-Assistent — ein hilfreicher AI-Assistent für Ressourcenplanung und Projektmanagement in einer 3D-Produktionsumgebung.
Deine Fähigkeiten:
- Fragen über Ressourcen, Projekte, Allokationen, Budget, Urlaub, Estimates, Org-Struktur beantworten
- Chargeability-Analysen, Urlaubsübersichten, Budget-Analysen
- Ressourcen/Projekte aktualisieren, Allokationen erstellen/stornieren (nur mit Berechtigung + expliziter Bestätigung)
- Den User zu relevanten Seiten navigieren (Timeline, Dashboard, etc. mit Filtern)
Wichtige Regeln:
- Antworte in der Sprache des Users (Deutsch oder Englisch)
- Geldbeträge: intern in Cent, konvertiere zu EUR für den User
- Vor Datenänderungen: kurze Zusammenfassung + Bestätigung einholen
- Sei KURZ und DIREKT. Keine langen Erklärungen wenn nicht nötig. Antworte knapp und präzise.
- Rufe Tools PARALLEL auf wenn möglich (z.B. search_resources + list_allocations gleichzeitig)
- Fasse Ergebnisse kompakt zusammen — keine unnötigen Wiederholungen der Tool-Ergebnisse
- Wenn eine Suche keine Treffer ergibt, versuche einzelne Wörter aus der Anfrage als Suchbegriffe. Die Tools unterstützen automatisch wort-basierte Fuzzy-Suche — zeige dem User die Vorschläge wenn welche gefunden werden
Datenmodell:
- Ressourcen: EID, FTE (0-1), LCR (EUR/h), Chargeability-Target, Skills, Chapter, OrgUnit
- Projekte: ShortCode, Budget (Cent), Win-Probability, Status (DRAFT/ACTIVE/ON_HOLD/COMPLETED/CANCELLED)
- Allokationen (Assignments): resourceId + projectId, hoursPerDay, dailyCostCents, Zeitraum, Status (PROPOSED/CONFIRMED/ACTIVE/COMPLETED/CANCELLED)
- Chargeability = gebuchte/verfügbare Stunden × 100%
- Urlaub: Typen VACATION/SICK/PARENTAL/SPECIAL/PUBLIC_HOLIDAY, Status PENDING/APPROVED/REJECTED/CANCELLED
`;
/** Map tool names to the permission required to use them */
const TOOL_PERMISSION_MAP: Record<string, string> = {
update_resource: "manageResources",
update_project: "manageProjects",
create_allocation: "manageAllocations",
cancel_allocation: "manageAllocations",
update_allocation_status: "manageAllocations",
};
/** Tools that require cost visibility */
const COST_TOOLS = new Set(["get_budget_status", "get_chargeability"]);
export const assistantRouter = createTRPCRouter({
chat: protectedProcedure
.input(z.object({
messages: z.array(z.object({
role: z.enum(["user", "assistant"]),
content: z.string(),
})).min(1).max(200),
pageContext: z.string().optional(),
}))
.mutation(async ({ ctx, input }) => {
// 1. Load AI settings
const settings = await ctx.db.systemSettings.findUnique({
where: { id: "singleton" },
});
if (!isAiConfigured(settings)) {
throw new TRPCError({
code: "PRECONDITION_FAILED",
message: "AI is not configured. Please set up OpenAI credentials in Admin → Settings.",
});
}
const client = createAiClient(settings!);
const userRole = ctx.dbUser?.systemRole ?? "USER";
// Use configured token limit, but ensure a reasonable minimum for multi-tool responses
const maxTokens = Math.max(settings?.aiMaxCompletionTokens ?? 2500, 1500);
const temperature = settings?.aiTemperature ?? 0.7;
const model = settings?.azureOpenAiDeployment ?? "gpt-4o-mini";
// 2. Resolve granular permissions
const permissions = resolvePermissions(
userRole as SystemRole,
(ctx.dbUser?.permissionOverrides as PermissionOverrides | null) ?? null,
);
const permissionList = [...permissions];
// 3. Build system prompt with user context
let contextBlock = `\n\nAktueller User: ${ctx.session?.user?.name ?? "Unknown"} (Rolle: ${userRole})`;
contextBlock += `\nBerechtigungen: ${permissionList.length > 0 ? permissionList.join(", ") : "Nur Lese-Zugriff auf eigene Daten"}`;
if (input.pageContext) {
contextBlock += `\nAktuelle Seite: ${input.pageContext}`;
contextBlock += `\nHinweis: Beziehe dich bevorzugt auf den Kontext der aktuellen Seite wenn die Frage des Users dazu passt.`;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const openaiMessages: any[] = [
{ role: "system", content: SYSTEM_PROMPT + contextBlock },
...input.messages.slice(-20).map((m) => ({
role: m.role,
content: m.content,
})),
];
// 4. Filter tools based on granular permissions
const availableTools = TOOL_DEFINITIONS.filter((t) => {
const toolName = t.function.name;
// Check write permission
const requiredPerm = TOOL_PERMISSION_MAP[toolName];
if (requiredPerm && !permissions.has(requiredPerm as import("@planarchy/shared").PermissionKey)) {
return false;
}
// Hide cost/budget tools if user lacks viewCosts
if (COST_TOOLS.has(toolName) && !permissions.has("viewCosts" as import("@planarchy/shared").PermissionKey)) {
return false;
}
return true;
});
// 5. Function calling loop
const toolCtx: ToolContext = { db: ctx.db, userRole, permissions };
const collectedActions: ToolAction[] = [];
for (let i = 0; i < MAX_TOOL_ITERATIONS; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let response: any;
try {
response = await client.chat.completions.create({
model,
messages: openaiMessages,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tools: availableTools as any,
max_completion_tokens: maxTokens,
temperature,
});
} catch (err) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `AI error: ${parseAiError(err)}`,
});
}
const choice = response.choices?.[0];
if (!choice) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "No response from AI" });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg = choice.message as any;
// If the AI wants to call tools
if (msg.tool_calls && msg.tool_calls.length > 0) {
openaiMessages.push(msg);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
for (const toolCall of msg.tool_calls as Array<{ id: string; function: { name: string; arguments: string } }>) {
const result = await executeTool(
toolCall.function.name,
toolCall.function.arguments,
toolCtx,
);
// Collect any actions (e.g. navigation)
if (result.action) {
collectedActions.push(result.action);
}
openaiMessages.push({
role: "tool",
tool_call_id: toolCall.id,
content: result.content,
});
}
continue;
}
// AI returned a text response — we're done
return {
content: (msg.content as string) ?? "I couldn't generate a response.",
role: "assistant" as const,
...(collectedActions.length > 0 ? { actions: collectedActions } : {}),
};
}
// Exceeded max iterations
return {
content: "I had to stop after too many tool calls. Please try a simpler question.",
role: "assistant" as const,
...(collectedActions.length > 0 ? { actions: collectedActions } : {}),
};
}),
});
+4
View File
@@ -1,8 +1,10 @@
import { createTRPCRouter } from "../trpc.js"; import { createTRPCRouter } from "../trpc.js";
import { allocationRouter } from "./allocation.js"; import { allocationRouter } from "./allocation.js";
import { assistantRouter } from "./assistant.js";
import { calculationRuleRouter } from "./calculation-rules.js"; import { calculationRuleRouter } from "./calculation-rules.js";
import { blueprintRouter } from "./blueprint.js"; import { blueprintRouter } from "./blueprint.js";
import { chargeabilityReportRouter } from "./chargeability-report.js"; import { chargeabilityReportRouter } from "./chargeability-report.js";
import { computationGraphRouter } from "./computation-graph.js";
import { clientRouter } from "./client.js"; import { clientRouter } from "./client.js";
import { countryRouter } from "./country.js"; import { countryRouter } from "./country.js";
import { dashboardRouter } from "./dashboard.js"; import { dashboardRouter } from "./dashboard.js";
@@ -26,6 +28,7 @@ import { utilizationCategoryRouter } from "./utilization-category.js";
import { vacationRouter } from "./vacation.js"; import { vacationRouter } from "./vacation.js";
export const appRouter = createTRPCRouter({ export const appRouter = createTRPCRouter({
assistant: assistantRouter,
dashboard: dashboardRouter, dashboard: dashboardRouter,
effortRule: effortRuleRouter, effortRule: effortRuleRouter,
experienceMultiplier: experienceMultiplierRouter, experienceMultiplier: experienceMultiplierRouter,
@@ -51,6 +54,7 @@ export const appRouter = createTRPCRouter({
rateCard: rateCardRouter, rateCard: rateCardRouter,
chargeabilityReport: chargeabilityReportRouter, chargeabilityReport: chargeabilityReportRouter,
calculationRule: calculationRuleRouter, calculationRule: calculationRuleRouter,
computationGraph: computationGraphRouter,
}); });
export type AppRouter = typeof appRouter; export type AppRouter = typeof appRouter;
+38 -1
View File
@@ -10,7 +10,7 @@ import { paginate, paginateCursor, PaginationInputSchema, CursorInputSchema } fr
import { assertBlueprintDynamicFields } from "./blueprint-validation.js"; import { assertBlueprintDynamicFields } from "./blueprint-validation.js";
import { buildDynamicFieldWhereClauses } from "./custom-field-filters.js"; import { buildDynamicFieldWhereClauses } from "./custom-field-filters.js";
import { loadProjectPlanningReadModel } from "./project-planning-read-model.js"; import { loadProjectPlanningReadModel } from "./project-planning-read-model.js";
import { controllerProcedure, createTRPCRouter, managerProcedure, protectedProcedure, requirePermission } from "../trpc.js"; import { adminProcedure, controllerProcedure, createTRPCRouter, managerProcedure, protectedProcedure, requirePermission } from "../trpc.js";
export const projectRouter = createTRPCRouter({ export const projectRouter = createTRPCRouter({
list: protectedProcedure list: protectedProcedure
@@ -309,4 +309,41 @@ export const projectRouter = createTRPCRouter({
return { projects, nextCursor: result.nextCursor }; return { projects, nextCursor: result.nextCursor };
}), }),
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const project = await ctx.db.project.findUnique({
where: { id: input.id },
select: { id: true, name: true, shortCode: true },
});
if (!project) throw new TRPCError({ code: "NOT_FOUND", message: "Project not found" });
// Delete all related records in a transaction
await ctx.db.$transaction(async (tx) => {
// Delete assignments (which reference demandRequirements)
await tx.assignment.deleteMany({ where: { projectId: input.id } });
// Delete demand requirements
await tx.demandRequirement.deleteMany({ where: { projectId: input.id } });
// Unlink calculation rules
await tx.calculationRule.updateMany({
where: { projectId: input.id },
data: { projectId: null },
});
// Delete the project
await tx.project.delete({ where: { id: input.id } });
// Audit log
await tx.auditLog.create({
data: {
entityType: "Project",
entityId: input.id,
action: "DELETE",
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
changes: { before: { id: project.id, name: project.name, shortCode: project.shortCode } } as never,
},
});
});
return { id: input.id, name: project.name };
}),
}); });
+16 -12
View File
@@ -48,6 +48,7 @@ type TimelineEntriesFilters = {
clientIds?: string[] | undefined; clientIds?: string[] | undefined;
chapters?: string[] | undefined; chapters?: string[] | undefined;
eids?: string[] | undefined; eids?: string[] | undefined;
countryCodes?: string[] | undefined;
}; };
function getAssignmentResourceIds( function getAssignmentResourceIds(
@@ -66,23 +67,25 @@ async function loadTimelineEntriesReadModel(
db: TimelineEntriesDbClient, db: TimelineEntriesDbClient,
input: TimelineEntriesFilters, input: TimelineEntriesFilters,
) { ) {
const { startDate, endDate, resourceIds, projectIds, clientIds, chapters, eids } = input; const { startDate, endDate, resourceIds, projectIds, clientIds, chapters, eids, countryCodes } = input;
// When resource-level filters are active (resourceIds, chapters, or eids), // When resource-level filters are active (resourceIds, chapters, eids, or countryCodes),
// resolve matching resource IDs so we can push the filter to the DB query. // resolve matching resource IDs so we can push the filter to the DB query.
const effectiveResourceIds = await (async () => { const effectiveResourceIds = await (async () => {
if (resourceIds && resourceIds.length > 0) return resourceIds; if (resourceIds && resourceIds.length > 0) return resourceIds;
const hasChapters = chapters && chapters.length > 0; const hasChapters = chapters && chapters.length > 0;
const hasEids = eids && eids.length > 0; const hasEids = eids && eids.length > 0;
if (!hasChapters && !hasEids) return undefined; const hasCountry = countryCodes && countryCodes.length > 0;
if (!hasChapters && !hasEids && !hasCountry) return undefined;
const andConditions: Record<string, unknown>[] = [];
if (hasChapters) andConditions.push({ chapter: { in: chapters } });
if (hasEids) andConditions.push({ eid: { in: eids } });
if (hasCountry) andConditions.push({ country: { code: { in: countryCodes } } });
const matching = await db.resource.findMany({ const matching = await db.resource.findMany({
where: { // eslint-disable-next-line @typescript-eslint/no-explicit-any
...(hasChapters && hasEids where: (andConditions.length === 1 ? andConditions[0]! : { AND: andConditions }) as any,
? { AND: [{ chapter: { in: chapters } }, { eid: { in: eids } }] }
: hasChapters
? { chapter: { in: chapters } }
: { eid: { in: eids! } }),
},
select: { id: true }, select: { id: true },
}); });
return matching.map((r) => r.id); return matching.map((r) => r.id);
@@ -288,6 +291,7 @@ export const timelineRouter = createTRPCRouter({
clientIds: z.array(z.string()).optional(), clientIds: z.array(z.string()).optional(),
chapters: z.array(z.string()).optional(), chapters: z.array(z.string()).optional(),
eids: z.array(z.string()).optional(), eids: z.array(z.string()).optional(),
countryCodes: z.array(z.string()).optional(),
}), }),
) )
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
@@ -306,6 +310,7 @@ export const timelineRouter = createTRPCRouter({
clientIds: z.array(z.string()).optional(), clientIds: z.array(z.string()).optional(),
chapters: z.array(z.string()).optional(), chapters: z.array(z.string()).optional(),
eids: z.array(z.string()).optional(), eids: z.array(z.string()).optional(),
countryCodes: z.array(z.string()).optional(),
}), }),
) )
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
@@ -736,9 +741,8 @@ export const timelineRouter = createTRPCRouter({
"Project", "Project",
); );
// Use wide date range to catch all assignments (including those extending beyond project dates)
const bookings = await listAssignmentBookings(ctx.db, { const bookings = await listAssignmentBookings(ctx.db, {
startDate: project.startDate,
endDate: project.endDate,
projectIds: [project.id], projectIds: [project.id],
}); });
+27
View File
@@ -113,6 +113,33 @@ export const userRouter = createTRPCRouter({
return { updatedAt: updated.updatedAt }; return { updatedAt: updated.updatedAt };
}), }),
// ─── Favorite Projects ──────────────────────────────────────────────────
getFavoriteProjectIds: protectedProcedure.query(async ({ ctx }) => {
const user = await ctx.db.user.findUnique({
where: { id: ctx.dbUser!.id },
select: { favoriteProjectIds: true },
});
return ((user?.favoriteProjectIds as string[] | null) ?? []) as string[];
}),
toggleFavoriteProject: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ ctx, input }) => {
const user = await ctx.db.user.findUnique({
where: { id: ctx.dbUser!.id },
select: { favoriteProjectIds: true },
});
const current = ((user?.favoriteProjectIds as string[] | null) ?? []) as string[];
const next = current.includes(input.projectId)
? current.filter((id) => id !== input.projectId)
: [...current, input.projectId];
await ctx.db.user.update({
where: { id: ctx.dbUser!.id },
data: { favoriteProjectIds: next as unknown as Prisma.InputJsonValue },
});
return { favoriteProjectIds: next, added: !current.includes(input.projectId) };
}),
setPermissions: adminProcedure setPermissions: adminProcedure
.input( .input(
z.object({ z.object({
@@ -32,6 +32,7 @@ export async function createDemandRequirement(
role: input.role ?? null, role: input.role ?? null,
roleId: input.roleId ?? null, roleId: input.roleId ?? null,
headcount: input.headcount ?? 1, headcount: input.headcount ?? 1,
budgetCents: input.budgetCents ?? 0,
status: input.status, status: input.status,
metadata: input.metadata as unknown as Prisma.InputJsonValue, metadata: input.metadata as unknown as Prisma.InputJsonValue,
}, },
@@ -33,6 +33,7 @@ export async function updateDemandRequirement(
...(input.role !== undefined ? { role: input.role } : {}), ...(input.role !== undefined ? { role: input.role } : {}),
...(input.roleId !== undefined ? { roleId: input.roleId } : {}), ...(input.roleId !== undefined ? { roleId: input.roleId } : {}),
...(input.headcount !== undefined ? { headcount: input.headcount } : {}), ...(input.headcount !== undefined ? { headcount: input.headcount } : {}),
...(input.budgetCents !== undefined ? { budgetCents: input.budgetCents } : {}),
...(input.status !== undefined ? { status: input.status } : {}), ...(input.status !== undefined ? { status: input.status } : {}),
...(input.metadata !== undefined ...(input.metadata !== undefined
? { metadata: input.metadata as unknown as Prisma.InputJsonValue } ? { metadata: input.metadata as unknown as Prisma.InputJsonValue }
+2
View File
@@ -176,6 +176,7 @@ model User {
permissionOverrides Json? @db.JsonB permissionOverrides Json? @db.JsonB
dashboardLayout Json? @db.JsonB dashboardLayout Json? @db.JsonB
columnPreferences Json? @db.JsonB columnPreferences Json? @db.JsonB
favoriteProjectIds Json? @db.JsonB // string[] of project IDs
accounts Account[] accounts Account[]
sessions Session[] sessions Session[]
@@ -1177,6 +1178,7 @@ model DemandRequirement {
role String? role String?
roleId String? roleId String?
headcount Int @default(1) headcount Int @default(1)
budgetCents Int @default(0)
status AllocationStatus @default(PROPOSED) status AllocationStatus @default(PROPOSED)
metadata Json @db.JsonB @default("{}") metadata Json @db.JsonB @default("{}")
@@ -11,6 +11,7 @@ export const CreateAllocationBaseSchema = z.object({
role: z.string().max(200).optional(), role: z.string().max(200).optional(),
roleId: z.string().optional(), roleId: z.string().optional(),
headcount: z.number().int().min(1).default(1), headcount: z.number().int().min(1).default(1),
budgetCents: z.number().int().min(0).optional(),
status: z.nativeEnum(AllocationStatus).default(AllocationStatus.PROPOSED), status: z.nativeEnum(AllocationStatus).default(AllocationStatus.PROPOSED),
metadata: z.record(z.string(), z.unknown()).default({}), metadata: z.record(z.string(), z.unknown()).default({}),
}); });
@@ -24,6 +25,7 @@ export const CreateDemandRequirementBaseSchema = z.object({
role: z.string().max(200).optional(), role: z.string().max(200).optional(),
roleId: z.string().optional(), roleId: z.string().optional(),
headcount: z.number().int().min(1).default(1), headcount: z.number().int().min(1).default(1),
budgetCents: z.number().int().min(0).optional(),
status: z.nativeEnum(AllocationStatus).default(AllocationStatus.PROPOSED), status: z.nativeEnum(AllocationStatus).default(AllocationStatus.PROPOSED),
metadata: z.record(z.string(), z.unknown()).default({}), metadata: z.record(z.string(), z.unknown()).default({}),
}); });
@@ -63,6 +63,11 @@ const chargeabilityWidgetConfigSchema = z.object({
watchlistThreshold: z.number().int().min(0).max(100).optional(), watchlistThreshold: z.number().int().min(0).max(100).optional(),
}); });
const myProjectsWidgetConfigSchema = z.object({
showFavorites: z.boolean().optional(),
showResponsible: z.boolean().optional(),
});
export const dashboardWidgetConfigSchemas = { export const dashboardWidgetConfigSchemas = {
"stat-cards": z.object({}), "stat-cards": z.object({}),
"resource-table": resourceTableWidgetConfigSchema, "resource-table": resourceTableWidgetConfigSchema,
@@ -71,6 +76,7 @@ export const dashboardWidgetConfigSchemas = {
"demand-view": demandWidgetConfigSchema, "demand-view": demandWidgetConfigSchema,
"top-value-resources": topValueWidgetConfigSchema, "top-value-resources": topValueWidgetConfigSchema,
"chargeability-overview": chargeabilityWidgetConfigSchema, "chargeability-overview": chargeabilityWidgetConfigSchema,
"my-projects": myProjectsWidgetConfigSchema,
} as const; } as const;
type DashboardWidgetConfigSchemaMap = typeof dashboardWidgetConfigSchemas; type DashboardWidgetConfigSchemaMap = typeof dashboardWidgetConfigSchemas;
+1
View File
@@ -85,6 +85,7 @@ export interface DemandRequirementRecord {
role: string | null; role: string | null;
roleId: string | null; roleId: string | null;
headcount: number; headcount: number;
budgetCents: number;
status: AllocationStatus; status: AllocationStatus;
metadata: DemandRequirementMetadata; metadata: DemandRequirementMetadata;
createdAt: Date; createdAt: Date;
+19
View File
@@ -37,6 +37,11 @@ export interface ChargeabilityOverviewWidgetConfig {
watchlistThreshold?: number; watchlistThreshold?: number;
} }
export interface MyProjectsWidgetConfig {
showFavorites?: boolean;
showResponsible?: boolean;
}
export interface DashboardWidgetConfigMap { export interface DashboardWidgetConfigMap {
"stat-cards": StatCardsWidgetConfig; "stat-cards": StatCardsWidgetConfig;
"resource-table": ResourceTableWidgetConfig; "resource-table": ResourceTableWidgetConfig;
@@ -45,6 +50,7 @@ export interface DashboardWidgetConfigMap {
"demand-view": DemandWidgetConfig; "demand-view": DemandWidgetConfig;
"top-value-resources": TopValueResourcesWidgetConfig; "top-value-resources": TopValueResourcesWidgetConfig;
"chargeability-overview": ChargeabilityOverviewWidgetConfig; "chargeability-overview": ChargeabilityOverviewWidgetConfig;
"my-projects": MyProjectsWidgetConfig;
} }
export const DASHBOARD_WIDGET_TYPES = [ export const DASHBOARD_WIDGET_TYPES = [
@@ -55,6 +61,7 @@ export const DASHBOARD_WIDGET_TYPES = [
"demand-view", "demand-view",
"top-value-resources", "top-value-resources",
"chargeability-overview", "chargeability-overview",
"my-projects",
] as const; ] as const;
export type DashboardWidgetType = (typeof DASHBOARD_WIDGET_TYPES)[number]; export type DashboardWidgetType = (typeof DASHBOARD_WIDGET_TYPES)[number];
@@ -163,4 +170,16 @@ export const DASHBOARD_WIDGET_CATALOG = [
watchlistThreshold: 15, watchlistThreshold: 15,
}, },
}, },
{
type: "my-projects",
label: "My Projects",
description: "Quick access to your favorite and responsible projects",
icon: "⭐",
defaultSize: { w: 6, h: 6 },
minSize: { w: 4, h: 3 },
defaultConfig: {
showFavorites: true,
showResponsible: true,
},
},
] as const satisfies readonly DashboardWidgetCatalogEntry[]; ] as const satisfies readonly DashboardWidgetCatalogEntry[];
+1
View File
@@ -8,6 +8,7 @@ export interface StaffingRequirement {
preferredSkills?: string[]; preferredSkills?: string[];
hoursPerDay: number; hoursPerDay: number;
headcount: number; headcount: number;
budgetCents?: number;
startDate?: string; startDate?: string;
endDate?: string; endDate?: string;
notes?: string; notes?: string;
+73 -236
View File
@@ -1,21 +1,21 @@
# Plan: Calculation Rules Engine # Plan: Budget per Role / Demand
## Anforderungsanalyse ## Anforderungsanalyse
Planarchy berechnet Kosten und Chargeability aktuell hart verdrahtet: Vacation blockiert Stunden komplett, Sick Days werden nicht modelliert, und die Chargeability-Berechnung kennt keine Regeln fuer die Entkopplung von "Person ist chargeable" vs. "Projekt wird belastet". Jede Staffing-Demand (Rolle) in einem Projekt soll ein eigenes Budget bekommen. Aktuell gibt es nur ein einziges `budgetCents` auf Projektebene. Ziel:
**Gewuenschtes Verhalten (Beispiele):** 1. **DemandRequirement** bekommt ein `budgetCents` Feld (wie viel Budget ist dieser Rolle zugewiesen)
2. **StaffingRequirement** (JSONB auf Project) bekommt ein optionales `budgetCents` Feld fuer den Wizard
3. **Project Wizard Step 3** zeigt Budget-Input pro Rolle + verbleibendes unverteiltes Projekt-Budget
4. **Project Detail Page** zeigt pro Demand: zugewiesenes Budget vs. gebuchtes Budget (aus Assignments berechnet)
5. **Fill Demand Modal** zeigt verbleibendes Rollen-Budget beim Zuweisen von Ressourcen
| Szenario | Person chargeable? | Projekt belastet? | Heute | ### Architektur-Entscheidung
|----------|-------------------|-------------------|-------|
| Krank + gebucht auf Projekt | Ja | Nein | Nicht modelliert |
| Urlaub + gebucht auf Projekt | Ja | Nein | Urlaub blockiert Stunden komplett |
| Urlaub, nicht gebucht | Ja | — | Urlaub mindert SAH |
| Normal gebucht | Ja | Ja | Korrekt |
**Kernidee:** Ein regelbasiertes System, das pro Tag entscheidet: `budgetCents` als **explizite Spalte** auf `DemandRequirement` (nicht in `metadata` JSONB), weil:
1. **costEffect** — Wird der Tag dem Projekt belastet? (`charge` / `zero` / `reduce`) - Typsicher, indizierbar, aggregierbar via SQL
2. **chargeabilityEffect** — Zaehlt der Tag fuer die Chargeability der Person? (`count` / `skip`) - Konsistent mit dem Muster auf `Project.budgetCents`
- Default `0` = kein Budget zugewiesen (abwaertskompatibel)
--- ---
@@ -23,264 +23,101 @@ Planarchy berechnet Kosten und Chargeability aktuell hart verdrahtet: Vacation b
| Paket | Dateien | Art der Aenderung | | Paket | Dateien | Art der Aenderung |
|-------|---------|-----------------| |-------|---------|-----------------|
| shared | `src/types/calculation-rules.ts` | create | | `packages/db` | `prisma/schema.prisma` | **edit**`budgetCents` auf DemandRequirement |
| shared | `src/schemas/calculation-rules.schema.ts` | create | | `packages/shared` | `src/types/project.ts` | **edit**`budgetCents?` auf StaffingRequirement |
| shared | `src/types/index.ts` | edit (re-export) | | `packages/shared` | `src/types/allocation.ts` | **edit**`budgetCents` auf DemandRequirementRecord |
| db | `prisma/schema.prisma` | edit (neues Model) | | `packages/shared` | `src/schemas/allocation.schema.ts` | **edit**`budgetCents` in CreateDemandRequirementSchema |
| engine | `src/rules/engine.ts` | create | | `packages/api` | `src/router/allocation.ts` | **edit** — budgetCents durchreichen in create/update |
| engine | `src/rules/default-rules.ts` | create | | `packages/api` | `src/router/project.ts` | **edit** — bei Demand-Erstellung aus Wizard budgetCents uebernehmen |
| engine | `src/rules/index.ts` | create | | `apps/web` | `src/components/projects/ProjectWizard.tsx` | **edit** — Step 3: Budget-Input pro Rolle + Restbudget-Anzeige |
| engine | `src/allocation/calculator.ts` | edit (Rules-Integration) | | `apps/web` | `src/components/projects/ProjectDemandsTable.tsx` | **edit** — Spalten: Allocated Budget, Booked Budget |
| engine | `src/chargeability/calculator.ts` | edit (Rules-Integration) | | `apps/web` | `src/components/allocations/FillOpenDemandModal.tsx` | **edit** — Rollen-Budget-Anzeige |
| engine | `src/budget/monitor.ts` | edit (Rules-Integration) |
| engine | `src/__tests__/rules-engine.test.ts` | create |
| engine | `src/__tests__/calculator-rules.test.ts` | create |
| api | `src/router/calculation-rules.ts` | create |
| api | `src/router/index.ts` | edit (Router registrieren) |
| api | `src/router/timeline.ts` | edit (Rules durchreichen) |
| api | `src/router/allocation.ts` | edit (Rules bei Berechnung) |
| web | `src/app/(app)/admin/calculation-rules/page.tsx` | create |
| web | `src/components/admin/CalculationRulesClient.tsx` | create |
| web | `src/components/layout/AppShell.tsx` | edit (Navigation) |
--- ---
## Architektur ## Task-Liste
### Datenmodell ### Task 1: Prisma Schema — `budgetCents` auf DemandRequirement
```prisma Datei: `packages/db/prisma/schema.prisma`
model CalculationRule {
id String @id @default(cuid())
name String // "Sick Leave — Chargeable, No Project Cost"
description String?
// ── Matching ── - [ ] `budgetCents Int @default(0)` auf DemandRequirement hinzufuegen
triggerType AbsenceTrigger // SICK, VACATION, PUBLIC_HOLIDAY, CUSTOM - [ ] `pnpm db:push` ausfuehren (generiert Prisma Client)
// Optional narrowing (null = all): - [ ] Dev-Server neustarten (`.next/` Cache loeschen)
projectId String?
orderType OrderType? // CHARGEABLE, INTERNAL, INVESTMENT
// ── Effects ── ### Task 2: Shared Types aktualisieren
costEffect CostEffect // CHARGE, ZERO, REDUCE
costReductionPercent Int? // nur bei REDUCE (0-100)
chargeabilityEffect ChargeabilityEffect // COUNT, SKIP
// ── Ordering ── Dateien:
priority Int @default(0) // hoehere Prioritaet gewinnt - `packages/shared/src/types/project.ts``budgetCents?: number` auf `StaffingRequirement`
isActive Boolean @default(true) - `packages/shared/src/types/allocation.ts``budgetCents: number` auf `DemandRequirementRecord`
- `packages/shared/src/schemas/allocation.schema.ts``budgetCents: z.number().int().min(0).default(0)` in `CreateDemandRequirementBaseSchema`
createdAt DateTime @default(now()) ### Task 3: API — budgetCents durchreichen
updatedAt DateTime @updatedAt
project Project? @relation(fields: [projectId], references: [id]) Datei: `packages/api/src/router/allocation.ts`
@@map("calculation_rules") - [ ] `createDemandRequirement``budgetCents` aus Input an Prisma create weitergeben
} - [ ] `updateDemandRequirement``budgetCents` updatebar machen
- [ ] `checkResourceAvailability` — optional: gebuchte Kosten vs. Rollen-Budget zurueckgeben
enum AbsenceTrigger { Datei: `packages/api/src/router/project.ts`
SICK
VACATION
PUBLIC_HOLIDAY
CUSTOM
}
enum CostEffect { - [ ] Bei Projekt-Erstellung mit StaffingReqs: wenn `staffingReq.budgetCents` vorhanden, an DemandRequirement weitergeben
CHARGE // normaler Kostenauftrag ans Projekt
ZERO // keine Kosten ans Projekt
REDUCE // reduzierte Kosten (costReductionPercent)
}
enum ChargeabilityEffect { ### Task 4: Project Wizard Step 3 — Budget-Input pro Rolle
COUNT // Person zaehlt als chargeable
SKIP // Person zaehlt nicht (Tag wird aus SAH-Nenner genommen)
}
```
### Rule Matching (Engine) Datei: `apps/web/src/components/projects/ProjectWizard.tsx`
``` - [ ] Pro StaffingRequirement-Karte: neues Feld "Role Budget (EUR)" (Input, konvertiert zu Cents)
findMatchingRule(day, absenceType, projectId?, orderType?): - [ ] Oben im Step: Anzeige "Project Budget: X EUR | Allocated: Y EUR | Remaining: Z EUR"
candidates = rules.filter(r => - [ ] Farbkodierung: gruen wenn alles verteilt, amber wenn Rest, rot wenn ueberallokiert
r.isActive && - [ ] Budget-Wert wird in `state.staffingReqs[i].budgetCents` gespeichert
r.triggerType === absenceType &&
(r.projectId === null || r.projectId === projectId) &&
(r.orderType === null || r.orderType === orderType)
)
// Spezifischere Regeln gewinnen, dann priority
return candidates.sort(bySpecificityThenPriority)[0] ?? DEFAULT_RULE
```
**Specificity scoring:** ### Task 5: Project Detail Page — Budget-Spalten pro Demand
| Filter combination | Score |
|-------------------|-------|
| projectId + orderType | 3 |
| projectId only | 2 |
| orderType only | 1 |
| global (no filter) | 0 |
### Default Rules (Seed) Datei: `apps/web/src/components/projects/ProjectDemandsTable.tsx`
| Name | Trigger | Cost | Chargeability | - [ ] Neue Spalte "Allocated Budget" — zeigt `demand.budgetCents` formatiert als EUR
|------|---------|------|---------------| - [ ] Neue Spalte "Booked Budget" — berechnet: Summe der `dailyCostCents * Arbeitstage` aller Assignments dieses Demands
| Urlaub — Person chargeable, Projekt nicht belastet | VACATION | ZERO | COUNT | - Hinweis: Die Demand-Daten vom Server enthalten `assignments[]` — daraus berechnen
| Krankheit — Person chargeable, Projekt nicht belastet | SICK | ZERO | COUNT | - [ ] Neue Spalte "Remaining" — Allocated minus Booked
| Feiertag — kein Effekt | PUBLIC_HOLIDAY | ZERO | SKIP | - [ ] Farbkodierung: gruen wenn unter Budget, rot wenn ueber Budget
### Integration Points ### Task 6: Fill Demand Modal — Rollen-Budget anzeigen
**1. `calculateAllocation()` (engine/allocation/calculator.ts)** Datei: `apps/web/src/components/allocations/FillOpenDemandModal.tsx`
Aktuell: Vacation-Tag → `effectiveHours = 0`, `costCents = 0`. - [ ] Im Demand-Summary oben: "Role Budget: X EUR | Booked: Y EUR | Remaining: Z EUR"
Neu: Fuer jeden Tag pruefen ob eine Regel greift. Das DailyBreakdown bekommt zwei neue Felder: - [ ] Beim Hinzufuegen einer Ressource zum Plan: geschaetzte Kosten anzeigen (LCR * verfuegbare Stunden)
- [ ] Warnung wenn geplante Kosten das Rollen-Budget ueberschreiten
```ts
interface DailyBreakdown {
date: Date;
isWorkday: boolean;
hours: number; // effektive Stunden (wie bisher)
costCents: number; // Kosten fuer das Projekt (regel-gesteuert)
// NEU:
absenceType?: AbsenceTrigger; // was fuer ein Tag ist das?
chargeableHours: number; // Stunden die fuer Chargeability zaehlen
}
```
- Wenn `costEffect === ZERO`: `costCents = 0`, aber `chargeableHours = hoursPerDay`
- Wenn `costEffect === REDUCE`: `costCents = round(normal * (100 - reduction) / 100)`
- Wenn `chargeabilityEffect === COUNT`: `chargeableHours = hoursPerDay` (selbst wenn absent)
- Wenn `chargeabilityEffect === SKIP`: `chargeableHours = 0`
**2. `deriveResourceForecast()` (engine/chargeability/calculator.ts)**
Aktuell: `absence` Ratio ist immer 0 (kein Input).
Neu: Erhaelt `chargeableHours` pro Assignment-Slice statt nur `hoursPerDay * workingDays`.
Die Summe der chargeable Hours wird gegen SAH normiert.
**3. `computeBudgetStatus()` (engine/budget/monitor.ts)**
Aktuell: `dailyCostCents * workingDays` — nimmt an, jeder Tag kostet gleich.
Neu: Bekommt optional ein `adjustedTotalCostCents` pro Allocation, das bereits die Regel-Reduktionen enthaelt. Fallback auf bisherige Berechnung wenn keine Rules aktiv.
**4. Timeline Router (api/router/timeline.ts)**
Laedt Rules einmal, reicht sie an den Calculator durch. Rules werden gecacht (sie aendern sich selten).
---
## Task-Liste (atomare Schritte in Reihenfolge)
### Phase A: Datenmodell & Types
- [x] **A1:** Shared Types erstellen — `AbsenceTrigger`, `CostEffect`, `ChargeabilityEffect`, `CalculationRule` Interface → `packages/shared/src/types/calculation-rules.ts`
- [x] **A2:** Zod Schemas erstellen — `CreateCalculationRuleSchema`, `UpdateCalculationRuleSchema``packages/shared/src/schemas/calculation-rules.schema.ts`
- [x] **A3:** Re-exports in `packages/shared/src/types/index.ts` und `packages/shared/src/schemas/index.ts`
- [x] **A4:** Prisma Schema erweitern — `CalculationRule` Model + Enums → `packages/db/prisma/schema.prisma`
- [x] **A5:** Prisma Client regenerieren (db:push erfordert laufende DB)
### Phase B: Rules Engine (Pure Logic)
- [x] **B1:** Rule Matching Engine — `findMatchingRule()`, Specificity-Scoring → `packages/engine/src/rules/engine.ts`
- [x] **B2:** Default Rules — hartcodierte Fallback-Regeln → `packages/engine/src/rules/default-rules.ts`
- [x] **B3:** Index-Datei → `packages/engine/src/rules/index.ts`
- [x] **B4:** Tests fuer Rule Matching — 20 Tests (Specificity, Priority, Fallback, applyCostEffect) → `packages/engine/src/__tests__/rules-engine.test.ts`
### Phase C: Calculator-Integration
- [x] **C1:** `DailyBreakdown` erweitern — `absenceType`, `chargeableHours``packages/shared/src/types/engine.ts`
- [x] **C2:** `AllocationCalculationInput` erweitern — `calculationRules`, `absenceDays`, `projectId`, `orderType``packages/shared/src/types/engine.ts`
- [x] **C3:** `calculateAllocation()` anpassen — Regel-Lookup pro Tag, neue Felder befuellen → `packages/engine/src/allocation/calculator.ts`
- [x] **C4:** `AllocationCalculationResult` erweitern — `totalChargeableHours`, `totalProjectCostCents` (regelbereinigt)
- [x] **C5:** `deriveResourceForecast()``AssignmentSlice.totalChargeableHours` optional, verwendet statt `hoursPerDay*workingDays``packages/engine/src/chargeability/calculator.ts`
- [x] **C6:** `computeBudgetStatus()` — optional `adjustedTotalCostCents` pro Allocation → `packages/engine/src/budget/monitor.ts`
- [x] **C7:** Tests — 9 Tests (Sick+Booked, Vacation+Booked, Feiertag, Half-Day, REDUCE, Defaults) → `packages/engine/src/__tests__/calculator-rules.test.ts`
- [x] **C8:** Bestehende Calculator-Tests verifiziert — 283/283 bestanden, volle Rueckwaertskompatibilitaet
### Phase D: API Router
- [x] **D1:** `calculation-rules.ts` Router — CRUD (list, getById, getActive, create, update, delete) → `packages/api/src/router/calculation-rules.ts`
- [x] **D2:** Router registrieren → `packages/api/src/router/index.ts`
- [x] **D3:** Timeline Router — `loadCalculationRules()` + `buildAbsenceDays()` Helpers; `updateAllocationInline` + `applyShift` nutzen Rules → `packages/api/src/router/timeline.ts`
- [x] **D4:** Allocation Router — nutzt calculateAllocation nicht direkt (laeuft ueber Timeline); kein Handlungsbedarf
- [x] **D5:** Seed — 3 Default-Regeln einfuegen → `packages/db/src/seed.ts`
### Phase E: Admin UI
- [x] **E1:** `CalculationRulesClient.tsx` — Tabelle mit Rules, Create/Edit Modal → `apps/web/src/components/admin/CalculationRulesClient.tsx`
- [x] **E2:** Page Route → `apps/web/src/app/(app)/admin/calculation-rules/page.tsx`
- [x] **E3:** AppShell Navigation — "Calc. Rules" unter Admin-Bereich → `apps/web/src/components/layout/AppShell.tsx`
### Phase F: Sick Days Pipeline
- [x] **F1:** Timeline Router — `buildAbsenceDays()` laedt SICK/VACATION/PUBLIC_HOLIDAY mit Typ-Tag und reicht an Calculator → `packages/api/src/router/timeline.ts`
- [x] **F2:** Chargeability Report — Vacation-Query um `type`+`isHalfDay` erweitert; per-Monat AbsenceDays gebaut; `calculateAllocation()` mit Rules fuer `totalChargeableHours`; Rules aus DB geladen → `packages/api/src/router/chargeability-report.ts`
--- ---
## Abhaengigkeiten ## Abhaengigkeiten
``` - **Task 1 → Task 2 → Task 3** (sequentiell: Schema → Types → API)
A1 ─── A2 ─── A3 (shared types muessen zuerst stehen) - **Task 4** benoetigt Task 2 (StaffingRequirement-Typ mit budgetCents)
A4 ─── A5 (Schema vor DB push) - **Task 5** benoetigt Task 1+3 (budgetCents auf DemandRequirement + API liefert es)
- **Task 6** benoetigt Task 5 (gleiche Berechnung)
B1 ─── B4 (Engine vor Tests) - Task 4 und Task 5 koennen **parallel** nach Task 3
B2 ─── B3 (Default Rules vor Index)
A3 ──┐
├── B1 (Types muessen existieren)
A5 ──┘
B4 ──┐
├── C1 → C2 → C3 → C4 (Calculator braucht Types + Engine)
C3 ──── C5 (Chargeability braucht neue DailyBreakdown-Felder)
C3 ──── C6 (Budget braucht adjustierte Kosten)
C3 ──── C7 (Tests nach Implementation)
C4 ──── C8 (Regressionstest)
C4 ──── D1 (Router braucht funktionierende Engine)
D1 ──── D2 (Registrierung nach Router)
D1 ──── D3 (Timeline braucht Router fuer Daten-Zugriff)
D1 ──── D4
D2 ──── E1 → E2 → E3 (UI braucht API)
D3 ──── F1 (Sick Dates Pipeline braucht Rule-aware Timeline)
C5 ──── F2 (Forecast braucht neue chargeableHours)
```
**Parallelisierbar:**
- A1+A2+A3 parallel zu A4 (Types vs. Schema — keine Datei-Ueberschneidung)
- B1+B2 parallel (verschiedene Dateien)
- C5+C6 parallel (verschiedene Calculator-Dateien, nachdem C3 fertig)
- E1+E2+E3 als eigener Stream nachdem D2 fertig
--- ---
## Akzeptanzkriterien ## Akzeptanzkriterien
- [ ] `pnpm --filter @planarchy/engine exec vitest run` — alle bestehenden Tests + neue Rules-Tests gruen - [ ] `pnpm db:push` laeuft ohne Fehler
- [ ] `pnpm --filter @planarchy/api exec vitest run` — alle Tests gruen - [ ] `pnpm test:unit` — alle Tests gruen
- [ ] `pnpm --filter @planarchy/web exec tsc --noEmit`0 neue Errors - [ ] `pnpm --filter @planarchy/web exec tsc --noEmit`keine neuen Errors
- [ ] Ohne konfigurierte Rules: exakt gleiches Verhalten wie heute (Rueckwaertskompatibilitaet) - [ ] Project Wizard Step 3: Budget-Input pro Rolle sichtbar, Restbudget wird live berechnet
- [ ] Default-Regeln: Urlaub+Gebucht → Person chargeable, Projekt nicht belastet - [ ] Project Detail `/projects/[id]`: Demands-Tabelle zeigt Allocated / Booked / Remaining Budget
- [ ] Default-Regeln: Krank+Gebucht → Person chargeable, Projekt nicht belastet - [ ] Fill Demand Modal: Rollen-Budget und geschaetzte Kosten sichtbar
- [ ] Admin-UI: Rules erstellen, bearbeiten, loeschen, (de-)aktivieren, priorisieren - [ ] Bestehende Projekte/Demands funktionieren weiterhin (budgetCents default 0)
- [ ] Budget Monitor zeigt regelkonforme Kosten (Sick/Vacation-Tage nicht auf Projekt)
- [ ] Chargeability Report zeigt korrekte Ratios (Sick/Vacation als chargeable)
--- ---
## Risiken & offene Fragen ## Risiken & offene Fragen
1. **Rueckwaertskompatibilitaet** — Wenn keine Rules existieren UND kein Seed gelaufen ist, muss der Calculator sich exakt wie heute verhalten. Loesung: `DEFAULT_RULES` als Fallback in der Engine hartcodiert. 1. **Abwaertskompatibilitaet:** `@default(0)` stellt sicher, dass bestehende Demands kein Budget haben (0 = nicht gesetzt). UI sollte "Not set" anzeigen wenn 0.
2. **Budget-Berechnung Booked:** `dailyCostCents` ist pro Tag. Gebuchte Kosten = `dailyCostCents * Anzahl Arbeitstage im Zeitraum`. Diese Berechnung existiert bereits im Engine-Paket (`computeBudgetStatus`).
2. **Performance** — Rules werden pro Tag pro Allocation evaluiert. Bei 100 Allocations x 250 Tage = 25.000 Evaluierungen. Mitigiert durch: Rules einmal laden + im Memory halten (typisch <10 Regeln), Matching ist O(n) mit n ≈ 5-10. 3. **StaffingReqs JSONB:** Die `staffingReqs` auf Project sind JSONB. Aeltere Projekte haben kein `budgetCents` darin — der Wizard muss `budgetCents ?? 0` defaulten.
4. **Budget-Ueberschreitung:** Soll weiterhin erlaubt sein (Warnung, kein Block) — konsistent mit dem bestehenden Ansatz bei Projekt-Budget.
3. **Sick Days nicht im Allocation-Calculator** — Aktuell kennt `calculateAllocation()` nur `vacationDates`. Es braucht einen neuen Input `sickDates` (oder generischer: `absenceDates` mit Typ-Tag). Die Daten kommen aus der Vacation-Tabelle mit `type = SICK`.
4. **Half-Day Absences** — Das aktuelle System modelliert halbe Tage (`isHalfDay` auf Vacation). Die Rules Engine muss damit umgehen: halber Krankheitstag → halbe Stunden chargeable, halbe Stunden Projektkosten.
5. **Historische Korrektheit** — Aenderungen an Rules wirken sich auf alle zukuenftigen Berechnungen aus. Es gibt kein "Versioning" von Rules. Falls gewuenscht, koennte man `validFrom`/`validTo` Felder ergaenzen — aber erst wenn der Use Case auftritt (YAGNI).
6. **SAH-Integration** — SAH-Calculator hat eigenen Absence-Abzug. Die Rules Engine darf die SAH-Berechnung nicht doppelt reduzieren. Loesung: SAH bleibt wie ist (zaehlt alle Absences ab), die Rules Engine steuert nur die **Zuordnung** der Stunden (chargeable vs. nicht, Projekt vs. nicht).