ad0855902b
Phase 1 — Quick Wins: centralize formatMoney/formatCents, extract findUniqueOrThrow helper (19 routers), shared Prisma select constants, useInvalidatePlanningViews hook, status badge consolidation, composite DB indexes. Phase 2 — Timeline Split: extract TimelineContext, TimelineResourcePanel, TimelineProjectPanel; split 28-dep useMemo into 3 focused memos. TimelineView.tsx reduced from 1,903 to 538 lines. Phase 3 — Query Performance: server-side filtering for getEntriesView, remove availability from timeline resource select, SSE event debouncing (50ms batch window). Phase 4 — Estimate Workspace: extract 7 tab components and 3 editor components. EstimateWorkspaceClient 1,298→306 lines, EstimateWorkspaceDraftEditor 1,205→581 lines. Phase 5 — Package Cleanup: split commit-dispo-import-batch (1,112→573 lines), extract shared pagination helper with 11 tests. All tests pass: 209 API, 254 engine, 67 application. Co-Authored-By: claude-flow <ruv@ruv.net>
475 lines
17 KiB
TypeScript
475 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useRef } from "react";
|
|
import { useFocusTrap } from "~/hooks/useFocusTrap.js";
|
|
import { useInvalidatePlanningViews } from "~/hooks/useInvalidatePlanningViews.js";
|
|
import { AllocationStatus } from "@planarchy/shared";
|
|
import type { AllocationWithDetails, RecurrencePattern } from "@planarchy/shared";
|
|
import { trpc } from "~/lib/trpc/client.js";
|
|
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
|
|
import { DateInput } from "~/components/ui/DateInput.js";
|
|
import { RecurrenceEditor } from "./RecurrenceEditor.js";
|
|
|
|
const ALLOCATION_STATUSES = Object.values(AllocationStatus);
|
|
type EntryKind = "demand" | "assignment";
|
|
|
|
interface AllocationModalProps {
|
|
allocation?: AllocationWithDetails | null;
|
|
onClose: () => void;
|
|
onSuccess: () => void;
|
|
}
|
|
|
|
function toDateInputValue(date: Date | string | null | undefined): string {
|
|
if (!date) return "";
|
|
const d = typeof date === "string" ? new Date(date) : date;
|
|
return d.toISOString().split("T")[0] ?? "";
|
|
}
|
|
|
|
export function AllocationModal({ allocation, onClose, onSuccess }: AllocationModalProps) {
|
|
const isEditing = Boolean(allocation);
|
|
const initialEntryKind: EntryKind = allocation && !allocation.resourceId ? "demand" : "assignment";
|
|
const [entryKind, setEntryKind] = useState<EntryKind>(initialEntryKind);
|
|
const isDemandEntry = entryKind === "demand";
|
|
|
|
const [resourceId, setResourceId] = useState(allocation?.resourceId ?? "");
|
|
const [projectId, setProjectId] = useState(allocation?.projectId ?? "");
|
|
const [roleId, setRoleId] = useState(allocation?.roleId ?? "");
|
|
const [roleFreeText, setRoleFreeText] = useState(allocation?.role ?? "");
|
|
const [headcount, setHeadcount] = useState(allocation?.headcount ?? 1);
|
|
const [startDate, setStartDate] = useState(toDateInputValue(allocation?.startDate));
|
|
const [endDate, setEndDate] = useState(toDateInputValue(allocation?.endDate));
|
|
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation?.hoursPerDay ?? 8);
|
|
const [status, setStatus] = useState<AllocationStatus>(
|
|
allocation?.status ?? AllocationStatus.PROPOSED,
|
|
);
|
|
const existingMeta = allocation?.metadata as Record<string, unknown> | undefined;
|
|
const [isRecurring, setIsRecurring] = useState<boolean>(!!existingMeta?.recurrence);
|
|
const [recurrence, setRecurrence] = useState<RecurrencePattern | undefined>(
|
|
existingMeta?.recurrence as RecurrencePattern | undefined,
|
|
);
|
|
const [serverError, setServerError] = useState<string | null>(null);
|
|
|
|
const panelRef = useRef<HTMLDivElement>(null);
|
|
useFocusTrap(panelRef, true);
|
|
|
|
const { data: resources } = trpc.resource.list.useQuery(
|
|
{ isActive: true, limit: 500 },
|
|
{ staleTime: 60_000 },
|
|
);
|
|
const { data: projects } = trpc.project.list.useQuery(
|
|
{ limit: 500 },
|
|
{ staleTime: 60_000 },
|
|
);
|
|
const { data: rolesData } = trpc.role.list.useQuery(
|
|
{ isActive: true },
|
|
{ staleTime: 60_000 },
|
|
);
|
|
|
|
const invalidatePlanningViews = useInvalidatePlanningViews();
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const createDemandMutation = (trpc.allocation.createDemandRequirement.useMutation as any)({
|
|
onSuccess: () => {
|
|
invalidatePlanningViews();
|
|
onSuccess();
|
|
},
|
|
onError: (err: { message: string }) => {
|
|
setServerError(err.message);
|
|
},
|
|
}) as {
|
|
isPending: boolean;
|
|
isError: boolean;
|
|
error?: { message: string };
|
|
mutate: (input: unknown) => void;
|
|
};
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const createAssignmentMutation = (trpc.allocation.createAssignment.useMutation as any)({
|
|
onSuccess: () => {
|
|
invalidatePlanningViews();
|
|
onSuccess();
|
|
},
|
|
onError: (err: { message: string }) => {
|
|
setServerError(err.message);
|
|
},
|
|
}) as {
|
|
isPending: boolean;
|
|
isError: boolean;
|
|
error?: { message: string };
|
|
mutate: (input: unknown) => void;
|
|
};
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const updateMutation = (trpc.allocation.update.useMutation as any)({
|
|
onSuccess: () => {
|
|
invalidatePlanningViews();
|
|
onSuccess();
|
|
},
|
|
onError: (err: { message: string }) => {
|
|
setServerError(err.message);
|
|
},
|
|
}) as {
|
|
isPending: boolean;
|
|
isError: boolean;
|
|
error?: { message: string };
|
|
mutate: (input: unknown) => void;
|
|
};
|
|
|
|
const isPending =
|
|
createDemandMutation.isPending ||
|
|
createAssignmentMutation.isPending ||
|
|
updateMutation.isPending;
|
|
|
|
useEffect(() => {
|
|
setServerError(null);
|
|
}, [resourceId, projectId, roleId, roleFreeText, startDate, endDate, hoursPerDay, status, entryKind]);
|
|
|
|
function handleSubmit(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
setServerError(null);
|
|
|
|
if (!projectId) {
|
|
setServerError("Please select a project.");
|
|
return;
|
|
}
|
|
if (!isDemandEntry && !resourceId) {
|
|
setServerError("Please select a resource.");
|
|
return;
|
|
}
|
|
if (!startDate || !endDate) {
|
|
setServerError("Please fill in start and end dates.");
|
|
return;
|
|
}
|
|
|
|
const start = new Date(startDate);
|
|
const end = new Date(endDate);
|
|
|
|
if (end < start) {
|
|
setServerError("End date must be on or after start date.");
|
|
return;
|
|
}
|
|
|
|
const baseMeta = (allocation?.metadata as Record<string, unknown> | undefined) ?? {};
|
|
const metadata: Record<string, unknown> = {
|
|
...baseMeta,
|
|
...(isRecurring && recurrence ? { recurrence } : { recurrence: undefined }),
|
|
};
|
|
if (!isRecurring) delete metadata.recurrence;
|
|
|
|
// Determine role string from roleId if set
|
|
const rolesList = rolesData ?? [];
|
|
const selectedRole = rolesList.find((r) => r.id === roleId);
|
|
const roleString = selectedRole ? selectedRole.name : (roleFreeText || undefined);
|
|
|
|
const percentage = Math.min(100, Math.round((hoursPerDay / 8) * 100));
|
|
|
|
if (isEditing && allocation) {
|
|
updateMutation.mutate({
|
|
id: getPlanningEntryMutationId(allocation),
|
|
data: {
|
|
resourceId: isDemandEntry ? undefined : (resourceId || undefined),
|
|
projectId,
|
|
role: roleString,
|
|
roleId: roleId || undefined,
|
|
headcount: isDemandEntry ? headcount : 1,
|
|
startDate: start,
|
|
endDate: end,
|
|
hoursPerDay,
|
|
percentage,
|
|
status: status as AllocationStatus,
|
|
metadata,
|
|
},
|
|
});
|
|
} else if (isDemandEntry) {
|
|
createDemandMutation.mutate({
|
|
projectId,
|
|
role: roleString,
|
|
roleId: roleId || undefined,
|
|
headcount,
|
|
startDate: start,
|
|
endDate: end,
|
|
hoursPerDay,
|
|
percentage,
|
|
status: status as AllocationStatus,
|
|
metadata,
|
|
});
|
|
} else {
|
|
createAssignmentMutation.mutate({
|
|
resourceId,
|
|
projectId,
|
|
role: roleString,
|
|
roleId: roleId || undefined,
|
|
startDate: start,
|
|
endDate: end,
|
|
hoursPerDay,
|
|
percentage,
|
|
status: status as AllocationStatus,
|
|
metadata,
|
|
});
|
|
}
|
|
}
|
|
|
|
const inputClass =
|
|
"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";
|
|
const labelClass = "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1";
|
|
|
|
const resourceList = (resources?.resources ?? []) as Array<{ id: string; displayName: string; eid: string }>;
|
|
const projectList = (projects?.projects ?? []) as Array<{ id: string; name: string; shortCode: string }>;
|
|
const rolesList = (rolesData ?? []) as Array<{ id: string; name: string; color: string | null }>;
|
|
const entryLabel = isDemandEntry ? "Open Demand" : "Assignment";
|
|
|
|
return (
|
|
<div
|
|
className="fixed inset-0 bg-black/50 z-50 flex items-start justify-center overflow-y-auto py-8"
|
|
onClick={(e) => {
|
|
if (e.target === e.currentTarget) onClose();
|
|
}}
|
|
>
|
|
<div
|
|
ref={panelRef}
|
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-xl mx-4"
|
|
onKeyDown={(e) => { if (e.key === "Escape") onClose(); }}
|
|
>
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
|
{isEditing ? `Edit ${entryLabel}` : `New ${entryLabel}`}
|
|
</h2>
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="text-gray-400 hover:text-gray-600 transition-colors text-xl leading-none"
|
|
aria-label="Close"
|
|
>
|
|
×
|
|
</button>
|
|
</div>
|
|
|
|
{/* Form */}
|
|
<form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
|
|
{/* Demand toggle */}
|
|
<div className="flex items-center gap-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
|
|
<label className="flex items-center gap-2 text-sm cursor-pointer select-none flex-1">
|
|
<input
|
|
type="checkbox"
|
|
checked={isDemandEntry}
|
|
disabled={isEditing}
|
|
onChange={(e) => {
|
|
setEntryKind(e.target.checked ? "demand" : "assignment");
|
|
if (e.target.checked) setResourceId("");
|
|
}}
|
|
className="rounded border-gray-300 dark:border-gray-600 disabled:cursor-not-allowed disabled:opacity-60"
|
|
/>
|
|
<div>
|
|
<span className="font-medium text-gray-800 dark:text-gray-100">Open demand</span>
|
|
<span className="block text-xs text-gray-500 dark:text-gray-400">
|
|
{isEditing
|
|
? "Demand vs assignment type is fixed after creation during the compatibility migration."
|
|
: "No resource assigned yet and tracked as staffing demand"}
|
|
</span>
|
|
</div>
|
|
</label>
|
|
{isDemandEntry && (
|
|
<div className="flex items-center gap-2">
|
|
<label className="text-xs text-gray-600 dark:text-gray-400 whitespace-nowrap">Headcount:</label>
|
|
<input
|
|
type="number"
|
|
value={headcount}
|
|
onChange={(e) => setHeadcount(Math.max(1, Number(e.target.value)))}
|
|
min={1}
|
|
max={50}
|
|
className="w-16 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm text-center dark:bg-gray-900 dark:text-gray-100"
|
|
/>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Resource is only required for assignments */}
|
|
{!isDemandEntry && (
|
|
<div>
|
|
<label htmlFor="modal-resource" className={labelClass}>
|
|
Resource <span className="text-red-500">*</span>
|
|
</label>
|
|
<select
|
|
id="modal-resource"
|
|
value={resourceId}
|
|
onChange={(e) => setResourceId(e.target.value)}
|
|
className={inputClass}
|
|
required={!isDemandEntry}
|
|
>
|
|
<option value="">Select a resource…</option>
|
|
{resourceList.map((r) => (
|
|
<option key={r.id} value={r.id}>
|
|
{r.displayName} ({r.eid})
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
|
|
{/* Project */}
|
|
<div>
|
|
<label htmlFor="modal-project" className={labelClass}>
|
|
Project <span className="text-red-500">*</span>
|
|
</label>
|
|
<select
|
|
id="modal-project"
|
|
value={projectId}
|
|
onChange={(e) => setProjectId(e.target.value)}
|
|
className={inputClass}
|
|
required
|
|
>
|
|
<option value="">Select a project…</option>
|
|
{projectList.map((p) => (
|
|
<option key={p.id} value={p.id}>
|
|
{p.shortCode} — {p.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
{/* Role */}
|
|
<div>
|
|
<label htmlFor="modal-role" className={labelClass}>Role</label>
|
|
<select
|
|
id="modal-role"
|
|
value={roleId}
|
|
onChange={(e) => setRoleId(e.target.value)}
|
|
className={inputClass}
|
|
>
|
|
<option value="">No role / custom…</option>
|
|
{rolesList.map((r) => (
|
|
<option key={r.id} value={r.id}>
|
|
{r.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
{!roleId && (
|
|
<input
|
|
type="text"
|
|
value={roleFreeText}
|
|
onChange={(e) => setRoleFreeText(e.target.value)}
|
|
placeholder="Or type a custom role…"
|
|
className={`${inputClass} mt-1`}
|
|
maxLength={200}
|
|
/>
|
|
)}
|
|
</div>
|
|
|
|
{/* Dates */}
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label htmlFor="modal-start" className={labelClass}>
|
|
Start Date <span className="text-red-500">*</span>
|
|
</label>
|
|
<DateInput
|
|
id="modal-start"
|
|
value={startDate}
|
|
onChange={setStartDate}
|
|
className={inputClass}
|
|
required
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label htmlFor="modal-end" className={labelClass}>
|
|
End Date <span className="text-red-500">*</span>
|
|
</label>
|
|
<DateInput
|
|
id="modal-end"
|
|
value={endDate}
|
|
onChange={setEndDate}
|
|
min={startDate}
|
|
className={inputClass}
|
|
required
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Hours/Day + Status */}
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label htmlFor="modal-hours" className={labelClass}>
|
|
Hours / Day
|
|
</label>
|
|
<input
|
|
id="modal-hours"
|
|
type="number"
|
|
value={hoursPerDay}
|
|
onChange={(e) => setHoursPerDay(Number(e.target.value))}
|
|
min={0.5}
|
|
max={8}
|
|
step={0.5}
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label htmlFor="modal-status" className={labelClass}>
|
|
Status
|
|
</label>
|
|
<select
|
|
id="modal-status"
|
|
value={status}
|
|
onChange={(e) => setStatus(e.target.value as AllocationStatus)}
|
|
className={inputClass}
|
|
>
|
|
{ALLOCATION_STATUSES.map((s) => (
|
|
<option key={s} value={s}>
|
|
{s}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Recurring toggle */}
|
|
<div>
|
|
<label className="flex items-center gap-2 text-sm cursor-pointer select-none">
|
|
<input
|
|
type="checkbox"
|
|
checked={isRecurring}
|
|
onChange={(e) => {
|
|
setIsRecurring(e.target.checked);
|
|
if (!e.target.checked) setRecurrence(undefined);
|
|
}}
|
|
className="rounded border-gray-300 dark:border-gray-600"
|
|
/>
|
|
<span className="font-medium text-gray-700 dark:text-gray-300">Recurring schedule</span>
|
|
</label>
|
|
{isRecurring && (
|
|
<div className="mt-2">
|
|
<RecurrenceEditor value={recurrence} onChange={setRecurrence} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Server error */}
|
|
{serverError && (
|
|
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-400">
|
|
{serverError}
|
|
</div>
|
|
)}
|
|
|
|
{/* Footer */}
|
|
<div className="flex items-center justify-end gap-3 pt-2">
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
disabled={isPending}
|
|
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={isPending}
|
|
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
|
|
>
|
|
{isPending ? "Saving…" : "Save"}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|