chore(repo): initialize planarchy workspace

This commit is contained in:
2026-03-14 14:31:09 +01:00
commit dd55d0e78b
769 changed files with 166461 additions and 0 deletions
@@ -0,0 +1,483 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useFocusTrap } from "~/hooks/useFocusTrap.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 utils = trpc.useUtils();
const invalidatePlanningViews = () => {
void utils.allocation.list.invalidate();
void (utils as { allocation: { listView: { invalidate: () => Promise<unknown> } } }).allocation.listView.invalidate();
void utils.allocation.listDemands.invalidate();
void utils.allocation.listAssignments.invalidate();
void utils.timeline.getEntries.invalidate();
void utils.timeline.getEntriesView.invalidate();
void utils.timeline.getProjectContext.invalidate();
void utils.timeline.getBudgetStatus.invalidate();
};
// 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"
>
&times;
</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>
);
}
@@ -0,0 +1,606 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import { formatDate } from "~/lib/format.js";
import { trpc } from "~/lib/trpc/client.js";
import { AllocationModal } from "./AllocationModal.js";
import type { AllocationLike, AllocationReadModel, AllocationWithDetails, ColumnDef } from "@planarchy/shared";
import { AllocationStatus, ALLOCATION_COLUMNS } from "@planarchy/shared";
import { useSelection } from "~/hooks/useSelection.js";
import { BatchActionBar } from "~/components/ui/BatchActionBar.js";
import { ConfirmDialog } from "~/components/ui/ConfirmDialog.js";
import { FilterBar } from "~/components/ui/FilterBar.js";
import { FilterChips } from "~/components/ui/FilterChips.js";
import { ResourceCombobox } from "~/components/ui/ResourceCombobox.js";
import { ProjectCombobox } from "~/components/ui/ProjectCombobox.js";
import { ColumnTogglePanel } from "~/components/ui/ColumnTogglePanel.js";
import { SortableColumnHeader } from "~/components/ui/SortableColumnHeader.js";
import { useTableSort } from "~/hooks/useTableSort.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { useColumnConfig } from "~/hooks/useColumnConfig.js";
import { useViewPrefs } from "~/hooks/useViewPrefs.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
const STATUS_BADGE: Record<string, string> = {
ACTIVE: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
PROPOSED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
CONFIRMED: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
COMPLETED: "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400",
CANCELLED: "bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",
};
const ALL_ALLOC_STATUSES = [
{ value: "PROPOSED", label: "Proposed" },
{ value: "CONFIRMED", label: "Confirmed" },
{ value: "ACTIVE", label: "Active" },
{ value: "COMPLETED", label: "Completed" },
{ value: "CANCELLED", label: "Cancelled" },
] as const;
type AllocationAssignmentsView = AllocationReadModel<AllocationLike>;
type DemandRow = AllocationWithDetails & {
sourceAllocationId?: string;
requestedHeadcount?: number;
unfilledHeadcount?: number;
};
export function AllocationsClient() {
const [modalOpen, setModalOpen] = useState(false);
const [editingAllocation, setEditingAllocation] = useState<AllocationWithDetails | null>(null);
const [filterProjectId, setFilterProjectId] = useState<string>("");
const [filterResourceId, setFilterResourceId] = useState<string>("");
const [filterStatus, setFilterStatus] = useState<string>("");
const [hidePastProjects, setHidePastProjects] = useState(true);
const [hideCompletedProjects, setHideCompletedProjects] = useState(true);
const [hideDraftProjects, setHideDraftProjects] = useState(false);
const [confirmDelete, setConfirmDelete] = useState<{ single?: AllocationWithDetails; ids?: string[] } | null>(null);
const [batchStatusPicker, setBatchStatusPicker] = useState(false);
const [confirmBatchStatus, setConfirmBatchStatus] = useState<{ ids: string[]; status: string } | null>(null);
const selection = useSelection();
const utils = trpc.useUtils();
const { canViewCosts } = usePermissions();
// ─── Column visibility ────────────────────────────────────────────────────
const baseColumns = useMemo<ColumnDef[]>(
() => (canViewCosts ? ALLOCATION_COLUMNS : ALLOCATION_COLUMNS.filter((c) => c.key !== "cost")),
[canViewCosts],
);
const { allColumns, visibleColumns, visibleKeys, setVisible } = useColumnConfig("allocations", baseColumns);
const defaultKeys = useMemo(() => baseColumns.filter((c) => c.defaultVisible).map((c) => c.key), [baseColumns]);
const { data: allocationView, isLoading } = trpc.allocation.listView.useQuery(
{
projectId: filterProjectId || undefined,
resourceId: filterResourceId || undefined,
status: (filterStatus as AllocationStatus) || undefined,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{ placeholderData: (prev: any) => prev, staleTime: 15_000 },
) as { data: AllocationAssignmentsView | undefined; isLoading: boolean };
const deleteDemandMutation = trpc.allocation.deleteDemandRequirement.useMutation({
onSuccess: async () => {
await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate();
},
});
const deleteAssignmentMutation = trpc.allocation.deleteAssignment.useMutation({
onSuccess: async () => {
await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate();
},
});
const batchDeleteMutation = trpc.allocation.batchDelete.useMutation({
onSuccess: async () => {
await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate();
selection.clear();
},
});
const batchStatusMutation = trpc.allocation.batchUpdateStatus.useMutation({
onSuccess: async () => {
await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate();
selection.clear();
},
});
useEffect(() => {
selection.clear();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filterProjectId, filterResourceId, filterStatus, hidePastProjects, hideCompletedProjects, hideDraftProjects]);
function openCreate() {
setEditingAllocation(null);
setModalOpen(true);
}
function openEdit(alloc: AllocationWithDetails) {
setEditingAllocation(alloc);
setModalOpen(true);
}
function closeModal() {
setModalOpen(false);
setEditingAllocation(null);
}
const assignmentList = (allocationView?.assignments ?? []) as unknown as AllocationWithDetails[];
const demandList = (allocationView?.demands ?? []) as unknown as DemandRow[];
const today = new Date();
today.setHours(0, 0, 0, 0);
const filteredAllocations = assignmentList.filter((alloc) => {
if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today) return false;
if (hideCompletedProjects && alloc.project?.status && ["COMPLETED", "CANCELLED"].includes(alloc.project.status)) return false;
if (hideDraftProjects && alloc.project?.status === "DRAFT") return false;
return true;
});
const filteredDemands = demandList.filter((alloc) => {
if (filterResourceId) return false;
if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today) return false;
if (hideCompletedProjects && alloc.project?.status && ["COMPLETED", "CANCELLED"].includes(alloc.project.status)) return false;
if (hideDraftProjects && alloc.project?.status === "DRAFT") return false;
return true;
});
const allocViewPrefs = useViewPrefs("allocations");
const { sorted, sortField, sortDir, toggle } = useTableSort(filteredAllocations, {
initialField: allocViewPrefs.savedSort?.field ?? null,
initialDir: allocViewPrefs.savedSort?.dir ?? null,
onSortChange: (field, dir) => {
allocViewPrefs.setSavedSort(field && dir ? { field, dir } : null);
},
});
const allocationIds = sorted.map((a) => a.id);
const allocationMutationIdsByDisplayId = useMemo(
() =>
new Map(
sorted.map((allocation) => [allocation.id, getPlanningEntryMutationId(allocation)]),
),
[sorted],
);
const selectedMutationIds = useMemo(
() =>
selection.selectedArray.flatMap((displayId) => {
const mutationId = allocationMutationIdsByDisplayId.get(displayId);
return mutationId ? [mutationId] : [];
}),
[allocationMutationIdsByDisplayId, selection.selectedArray],
);
function handleSort(field: string) {
if (field === "resource") {
toggle("resource", (a) => a.resource?.displayName ?? null);
} else if (field === "project") {
toggle("project", (a) => a.project?.name ?? null);
} else {
toggle(field);
}
}
function clearAll() {
setFilterProjectId("");
setFilterResourceId("");
setFilterStatus("");
setHidePastProjects(false);
setHideCompletedProjects(false);
setHideDraftProjects(false);
}
const chips = [
...(filterProjectId ? [{ label: `Project filter active`, onRemove: () => setFilterProjectId("") }] : []),
...(filterResourceId ? [{ label: `Resource filter active`, onRemove: () => setFilterResourceId("") }] : []),
...(filterStatus ? [{ label: `Status: ${filterStatus}`, onRemove: () => setFilterStatus("") }] : []),
...(hidePastProjects ? [{ label: "Hiding past projects", onRemove: () => setHidePastProjects(false) }] : []),
...(hideCompletedProjects ? [{ label: "Hiding completed/cancelled", onRemove: () => setHideCompletedProjects(false) }] : []),
...(hideDraftProjects ? [{ label: "Hiding draft projects", onRemove: () => setHideDraftProjects(false) }] : []),
];
function formatPeriod(alloc: AllocationWithDetails) {
return formatDate(alloc.startDate) + " \u2192 " + formatDate(alloc.endDate);
}
function handleSingleDelete(allocation: AllocationWithDetails) {
const id = getPlanningEntryMutationId(allocation);
if (!allocation.resourceId) {
deleteDemandMutation.mutate({ id });
return;
}
deleteAssignmentMutation.mutate({ id });
}
const singleDeletePending = deleteDemandMutation.isPending || deleteAssignmentMutation.isPending;
return (
<div className="p-6 pb-24">
{/* Page header */}
<div className="mb-6 flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Allocations</h1>
<p className="text-gray-500 dark:text-gray-400 text-sm mt-1">
{isLoading
? "Loading…"
: `${filteredAllocations.length} assignment${filteredAllocations.length !== 1 ? "s" : ""}${filteredDemands.length > 0 ? ` · ${filteredDemands.length} open demand${filteredDemands.length !== 1 ? "s" : ""}` : ""}`}
</p>
</div>
<div className="flex items-center gap-2">
<a
href="/api/reports/allocations"
target="_blank"
rel="noopener noreferrer"
className="px-3 py-1.5 text-sm rounded-lg border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors flex items-center gap-2"
>
PDF
</a>
<a
href="/api/reports/allocations?format=xlsx"
download
className="px-3 py-1.5 text-sm rounded-lg border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors flex items-center gap-2"
>
XLS
</a>
<button
type="button"
onClick={openCreate}
className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
>
New Planning Entry
</button>
</div>
</div>
{/* Filters */}
<FilterBar>
<ProjectCombobox
value={filterProjectId || null}
onChange={(id) => setFilterProjectId(id ?? "")}
placeholder="Filter by project…"
className="min-w-[280px]"
/>
<ResourceCombobox
value={filterResourceId || null}
onChange={(id) => setFilterResourceId(id ?? "")}
placeholder="Filter by resource…"
className="min-w-[180px]"
/>
<select
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
className="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 bg-white dark:bg-gray-900 dark:text-gray-100"
>
<option value="">All Statuses</option>
{ALL_ALLOC_STATUSES.map((s) => (
<option key={s.value} value={s.value}>{s.label}</option>
))}
</select>
<label className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer whitespace-nowrap">
<input
type="checkbox"
checked={hidePastProjects}
onChange={(e) => setHidePastProjects(e.target.checked)}
className="rounded border-gray-300 dark:border-gray-600"
/>
Hide past
</label>
<label className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer whitespace-nowrap">
<input
type="checkbox"
checked={hideCompletedProjects}
onChange={(e) => setHideCompletedProjects(e.target.checked)}
className="rounded border-gray-300 dark:border-gray-600"
/>
Hide completed
</label>
<label className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer whitespace-nowrap">
<input
type="checkbox"
checked={hideDraftProjects}
onChange={(e) => setHideDraftProjects(e.target.checked)}
className="rounded border-gray-300 dark:border-gray-600"
/>
Hide drafts
</label>
<ColumnTogglePanel
allColumns={allColumns}
visibleKeys={visibleKeys}
onSetVisible={setVisible}
defaultKeys={defaultKeys}
/>
</FilterBar>
{/* Filter chips */}
{chips.length > 0 && (
<div className="mb-3">
<FilterChips chips={chips} onClearAll={clearAll} />
</div>
)}
{/* Table */}
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
<tr>
<th className="px-4 py-3 w-10">
<input
type="checkbox"
checked={selection.isAllSelected(allocationIds)}
ref={(el) => {
if (el) el.indeterminate = selection.isIndeterminate(allocationIds);
}}
onChange={() => selection.toggleAll(allocationIds)}
className="rounded border-gray-300 dark:border-gray-600"
/>
</th>
{visibleColumns.map((col) => {
const tooltips: Record<string, { tip: string; width?: string }> = {
role: { tip: "The role this allocation was created for. May differ from the resource's primary role." },
hoursPerDay: { tip: "Planned working hours per calendar day for this allocation." },
cost: { tip: "Resource LCR × hours per day. Reflects the cost of one day of work for this allocation." },
status: { tip: "PROPOSED = requested · CONFIRMED = approved · ACTIVE = ongoing · COMPLETED = finished · CANCELLED = removed.", width: "w-72" },
};
const t = tooltips[col.key];
const fieldMap: Record<string, string> = { dates: "startDate", hoursPerDay: "hoursPerDay", cost: "dailyCostCents" };
return (
<SortableColumnHeader
key={col.key}
label={col.label}
field={fieldMap[col.key] ?? col.key}
sortField={sortField}
sortDir={sortDir}
onSort={handleSort}
{...(t?.tip ? { tooltip: t.tip } : {})}
{...(t?.width ? { tooltipWidth: t.width } : {})}
/>
);
})}
<th className="px-4 py-3" />
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-700">
{isLoading && (
<tr>
<td colSpan={9} className="text-center py-12 text-gray-400 dark:text-gray-500 text-sm">Loading allocations</td>
</tr>
)}
{!isLoading && sorted.length === 0 && (
<tr>
<td colSpan={9} className="text-center py-12 text-gray-500 dark:text-gray-400 text-sm">No assignments found.</td>
</tr>
)}
{!isLoading &&
sorted.map((alloc) => {
const isSelected = selection.selectedIds.has(alloc.id);
return (
<tr key={alloc.id} className={`hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${isSelected ? "bg-brand-50 dark:bg-brand-900/20" : ""}`}>
<td className="px-4 py-3">
<input
type="checkbox"
checked={isSelected}
onChange={() => selection.toggle(alloc.id)}
className="rounded border-gray-300 dark:border-gray-600"
/>
</td>
{visibleColumns.map((col) => {
switch (col.key) {
case "resource":
return <td key={col.key} className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-gray-100">{alloc.resource?.displayName ?? "—"}</td>;
case "project":
return (
<td key={col.key} className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">
{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-400">{alloc.role}</td>;
case "dates":
return <td key={col.key} className="px-4 py-3 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">{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"></td>;
}
})}
<td className="px-4 py-3">
<div className="flex items-center gap-2 justify-end">
<button type="button" onClick={() => openEdit(alloc)} className="text-xs text-blue-600 hover:text-blue-800 font-medium hover:underline">Edit</button>
<button
type="button"
onClick={() => setConfirmDelete({ single: alloc })}
disabled={singleDeletePending}
className="text-xs text-red-500 hover:text-red-700 font-medium hover:underline disabled:opacity-50"
>
Delete
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{!isLoading && filteredDemands.length > 0 && (
<div className="mt-6 bg-white dark:bg-gray-800 rounded-xl border border-amber-200 dark:border-amber-800/60 overflow-hidden">
<div className="px-4 py-3 border-b border-amber-200 dark:border-amber-800/60 bg-amber-50/70 dark:bg-amber-950/20 flex items-center justify-between">
<div>
<h2 className="text-sm font-semibold text-amber-900 dark:text-amber-200">Open Demands</h2>
<p className="text-xs text-amber-700 dark:text-amber-300/80">
Placeholder demand rows not yet assigned to a resource.
</p>
</div>
<span className="text-xs font-medium text-amber-700 dark:text-amber-300">
{filteredDemands.length} item{filteredDemands.length !== 1 ? "s" : ""}
</span>
</div>
<div className="divide-y divide-amber-100 dark:divide-amber-900/40">
{filteredDemands.map((demand) => (
<div
key={demand.id}
className="px-4 py-3 flex items-center justify-between gap-4 hover:bg-amber-50/40 dark:hover:bg-amber-950/10"
>
<div className="min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
{demand.project ? (
<><span className="font-mono text-xs">{demand.project.shortCode}</span> {demand.project.name}</>
) : "Unknown project"}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
{(demand.role ?? "Placeholder role")} · {formatPeriod(demand)} · {demand.hoursPerDay}h/day
</div>
</div>
<div className="flex items-center gap-4 flex-shrink-0">
<div className="text-right">
<div className="text-xs uppercase tracking-wide text-amber-700 dark:text-amber-300">Unfilled</div>
<div className="text-sm font-semibold text-amber-900 dark:text-amber-200">
{demand.unfilledHeadcount ?? demand.headcount} / {demand.requestedHeadcount ?? demand.headcount}
</div>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => openEdit(demand as AllocationWithDetails)}
className="text-xs text-blue-600 hover:text-blue-800 font-medium hover:underline"
>
Edit
</button>
<button
type="button"
onClick={() => setConfirmDelete({ single: demand as AllocationWithDetails })}
disabled={singleDeletePending}
className="text-xs text-red-500 hover:text-red-700 font-medium hover:underline disabled:opacity-50"
>
Delete
</button>
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Batch Status Picker */}
{batchStatusPicker && (
<div className="fixed inset-0 bg-black/30 z-50 flex items-center justify-center p-4" onClick={() => setBatchStatusPicker(false)}>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl p-5 min-w-[220px]" onClick={(e) => e.stopPropagation()}>
<h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-3">Set status for {selection.count} allocations</h3>
<div className="flex flex-col gap-1">
{ALL_ALLOC_STATUSES.map((s) => (
<button
key={s.value}
type="button"
onClick={() => {
setConfirmBatchStatus({ ids: selectedMutationIds, status: s.value });
setBatchStatusPicker(false);
}}
className="w-full text-left px-3 py-2 text-sm rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
<span className={`inline-block px-2 py-0.5 text-xs rounded-full font-medium ${STATUS_BADGE[s.value]}`}>
{s.label}
</span>
</button>
))}
</div>
</div>
</div>
)}
{/* Confirm single delete */}
{confirmDelete?.single && (
<ConfirmDialog
title="Delete Allocation"
message={`Delete allocation for ${confirmDelete.single.resource?.displayName ?? "resource"} on ${confirmDelete.single.project?.name ?? "project"}?`}
confirmLabel="Delete"
variant="danger"
onConfirm={() => {
handleSingleDelete(confirmDelete.single!);
setConfirmDelete(null);
}}
onCancel={() => setConfirmDelete(null)}
/>
)}
{/* Confirm batch delete */}
{confirmDelete?.ids && (
<ConfirmDialog
title="Delete Allocations"
message={`Delete ${confirmDelete.ids.length} selected allocation${confirmDelete.ids.length !== 1 ? "s" : ""}? This cannot be undone.`}
confirmLabel="Delete All"
variant="danger"
onConfirm={() => {
batchDeleteMutation.mutate({ ids: confirmDelete.ids! });
setConfirmDelete(null);
}}
onCancel={() => setConfirmDelete(null)}
/>
)}
{/* Confirm batch status */}
{confirmBatchStatus && (
<ConfirmDialog
title="Update Allocation Status"
message={`Set ${confirmBatchStatus.ids.length} allocation${confirmBatchStatus.ids.length !== 1 ? "s" : ""} to "${confirmBatchStatus.status}"?`}
confirmLabel="Update"
onConfirm={() => {
batchStatusMutation.mutate({ ids: confirmBatchStatus.ids, status: confirmBatchStatus.status as never });
setConfirmBatchStatus(null);
}}
onCancel={() => setConfirmBatchStatus(null)}
/>
)}
{/* Batch Action Bar */}
<BatchActionBar
count={selection.count}
onClear={selection.clear}
actions={[
{
label: "Set Status…",
onClick: () => setBatchStatusPicker(true),
disabled: batchStatusMutation.isPending,
},
{
label: `Delete (${selection.count})`,
variant: "danger",
onClick: () => setConfirmDelete({ ids: selectedMutationIds }),
disabled: batchDeleteMutation.isPending,
},
]}
/>
{/* Modal */}
{modalOpen && (
<AllocationModal allocation={editingAllocation} onClose={closeModal} onSuccess={closeModal} />
)}
</div>
);
}
@@ -0,0 +1,186 @@
"use client";
import { useRef, useState } from "react";
import { AllocationStatus } from "@planarchy/shared";
import { useFocusTrap } from "~/hooks/useFocusTrap.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
import { trpc } from "~/lib/trpc/client.js";
interface OpenDemandAllocation {
id: string;
entityId?: string | null;
sourceAllocationId?: string | null;
projectId: string;
roleId: string | null;
role: string | null;
headcount: number;
startDate: Date | string;
endDate: Date | string;
hoursPerDay: number;
roleEntity?: { id: string; name: string; color: string | null } | null;
project?: { id: string; name: string; shortCode: string };
}
interface FillOpenDemandModalProps {
allocation: OpenDemandAllocation;
onClose: () => void;
onSuccess: () => void;
}
function formatDate(date: Date | string): string {
const d = typeof date === "string" ? new Date(date) : date;
return d.toLocaleDateString("en-GB", { year: "numeric", month: "short", day: "numeric" });
}
export function FillOpenDemandModal({ allocation, onClose, onSuccess }: FillOpenDemandModalProps) {
const [resourceId, setResourceId] = useState("");
const [hoursPerDay, setHoursPerDay] = useState<number>(allocation.hoursPerDay);
const [search, setSearch] = useState("");
const [serverError, setServerError] = useState<string | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
useFocusTrap(panelRef, true);
const utils = trpc.useUtils();
const invalidatePlanningViews = async () => {
await utils.allocation.list.invalidate();
await utils.allocation.listView.invalidate();
await utils.timeline.getEntries.invalidate();
await utils.timeline.getEntriesView.invalidate();
await utils.timeline.getProjectContext.invalidate();
await utils.timeline.getBudgetStatus.invalidate();
};
const { data: resources } = trpc.resource.list.useQuery(
{ isActive: true, search: search || undefined, limit: 100 },
{ staleTime: 15_000 },
) as { data: { resources: Array<{ id: string; displayName: string; eid: string }> } | undefined };
const fillOpenDemandMutation = trpc.allocation.fillOpenDemandByAllocation.useMutation({
onSuccess: async () => {
await invalidatePlanningViews();
onSuccess();
},
onError: (err) => setServerError(err.message),
});
const roleName = allocation.roleEntity?.name ?? allocation.role ?? "Unknown Role";
const roleColor = allocation.roleEntity?.color ?? "#6366f1";
const resourceList = resources?.resources ?? [];
const isPending = fillOpenDemandMutation.isPending;
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!resourceId) {
setServerError("Please select a resource.");
return;
}
fillOpenDemandMutation.mutate({
allocationId: getPlanningEntryMutationId(allocation),
resourceId,
hoursPerDay,
status: AllocationStatus.PROPOSED,
});
}
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-md mx-4"
onKeyDown={(e) => { if (e.key === "Escape") onClose(); }}
>
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Assign Open Demand</h2>
<button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-xl leading-none">&times;</button>
</div>
<div className="px-6 pt-4 pb-2">
{/* Demand summary */}
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3 mb-4 flex items-start gap-3">
<div className="w-3 h-3 rounded-full mt-1 flex-shrink-0" style={{ backgroundColor: roleColor }} />
<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">
{allocation.project?.name} · {formatDate(allocation.startDate)} {formatDate(allocation.endDate)}
</div>
{allocation.headcount > 1 && (
<div className="text-xs text-amber-600 mt-0.5">
{allocation.headcount} slots remaining assigning one resource
</div>
)}
</div>
</div>
</div>
<form onSubmit={handleSubmit} className="px-6 pb-5 space-y-4">
{/* Resource search */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Search Resource
</label>
<input
type="text"
placeholder="Search by name or EID…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Assign Resource <span className="text-red-500">*</span>
</label>
<select
value={resourceId}
onChange={(e) => setResourceId(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
required
size={Math.min(6, Math.max(3, resourceList.length))}
>
<option value="">Select a resource</option>
{resourceList.map((r) => (
<option key={r.id} value={r.id}>
{r.displayName} ({r.eid})
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Hours / Day</label>
<input
type="number"
value={hoursPerDay}
onChange={(e) => setHoursPerDay(Number(e.target.value))}
min={0.5}
max={8}
step={0.5}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 text-sm dark:bg-gray-900 dark:text-gray-100"
/>
</div>
{serverError && (
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-400">
{serverError}
</div>
)}
<div className="flex items-center justify-end gap-3 pt-2">
<button type="button" onClick={onClose} disabled={isPending} className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 disabled:opacity-50">
Cancel
</button>
<button type="submit" disabled={isPending || !resourceId} className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50">
{isPending ? "Assigning…" : "Create Assignment"}
</button>
</div>
</form>
</div>
</div>
);
}
@@ -0,0 +1,202 @@
"use client";
import { RecurrenceFrequency } from "@planarchy/shared";
import type { RecurrencePattern } from "@planarchy/shared";
const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
interface RecurrenceEditorProps {
value: RecurrencePattern | undefined;
onChange: (pattern: RecurrencePattern | undefined) => void;
}
export function RecurrenceEditor({ value, onChange }: RecurrenceEditorProps) {
const freq = value?.frequency ?? RecurrenceFrequency.WEEKLY;
function update(patch: Partial<RecurrencePattern>) {
onChange({ ...value, frequency: freq, ...patch });
}
function setFrequency(f: RecurrenceFrequency) {
// Reset pattern-specific fields when switching frequency
onChange({ frequency: f });
}
function toggleWeekday(dow: number) {
const current = value?.weekdays ?? [];
const next = current.includes(dow)
? current.filter((d) => d !== dow)
: [...current, dow].sort((a, b) => a - b);
update({ weekdays: next });
}
const inputClass =
"px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 dark:bg-gray-900 dark:text-gray-100";
const labelClass = "text-xs font-medium text-gray-600 dark:text-gray-400 block mb-1";
return (
<div className="space-y-3 p-3 bg-gray-50 dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700">
{/* Frequency selector */}
<div>
<span className={labelClass}>Frequency</span>
<div className="flex gap-2 flex-wrap">
{Object.values(RecurrenceFrequency).map((f) => (
<button
key={f}
type="button"
onClick={() => setFrequency(f)}
className={`px-3 py-1 text-xs rounded-full border transition-colors ${
freq === f
? "bg-brand-600 text-white border-brand-600"
: "border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-brand-400"
}`}
>
{f === RecurrenceFrequency.WEEKLY
? "Weekly"
: f === RecurrenceFrequency.BIWEEKLY
? "Biweekly"
: f === RecurrenceFrequency.MONTHLY
? "Monthly"
: "Custom"}
</button>
))}
</div>
</div>
{/* Weekday picker — WEEKLY and BIWEEKLY */}
{(freq === RecurrenceFrequency.WEEKLY || freq === RecurrenceFrequency.BIWEEKLY) && (
<div>
<span className={labelClass}>Days of week</span>
<div className="flex gap-1">
{WEEKDAY_LABELS.map((label, dow) => {
const selected = (value?.weekdays ?? []).includes(dow);
return (
<button
key={dow}
type="button"
onClick={() => toggleWeekday(dow)}
className={`w-9 h-9 text-xs rounded-full border font-medium transition-colors ${
selected
? "bg-brand-600 text-white border-brand-600"
: "border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-brand-400"
}`}
>
{label}
</button>
);
})}
</div>
</div>
)}
{/* Biweekly interval */}
{freq === RecurrenceFrequency.BIWEEKLY && (
<div>
<label className={labelClass}>Every N weeks</label>
<input
type="number"
min={2}
max={8}
value={value?.interval ?? 2}
onChange={(e) => update({ interval: Number(e.target.value) })}
className={`${inputClass} w-24`}
/>
</div>
)}
{/* Monthly — day of month */}
{freq === RecurrenceFrequency.MONTHLY && (
<div>
<label className={labelClass}>Day of month (131)</label>
<input
type="number"
min={1}
max={31}
value={value?.monthDay ?? 1}
onChange={(e) => update({ monthDay: Number(e.target.value) })}
className={`${inputClass} w-24`}
/>
</div>
)}
{/* Custom — hoursPerDay override */}
{freq === RecurrenceFrequency.CUSTOM && (
<div>
<label className={labelClass}>Hours per active day</label>
<input
type="number"
min={0.5}
max={24}
step={0.5}
value={value?.hoursPerDay ?? 8}
onChange={(e) => update({ hoursPerDay: Number(e.target.value) })}
className={`${inputClass} w-24`}
/>
</div>
)}
{/* Optional hours override for WEEKLY/BIWEEKLY/MONTHLY */}
{freq !== RecurrenceFrequency.CUSTOM && (
<div>
<label className={labelClass}>Hours per recurring day (optional override)</label>
<input
type="number"
min={0.5}
max={24}
step={0.5}
placeholder="Use allocation default"
value={value?.hoursPerDay ?? ""}
onChange={(e) => {
const next = { ...value, frequency: freq } as RecurrencePattern;
if (e.target.value === "") {
delete next.hoursPerDay;
} else {
next.hoursPerDay = Number(e.target.value);
}
onChange(next);
}}
className={`${inputClass} w-40`}
/>
</div>
)}
{/* Optional date range overrides */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className={labelClass}>Recurrence start (optional)</label>
<input
type="date"
value={value?.startDate ?? ""}
onChange={(e) => {
const next = { ...value, frequency: freq } as RecurrencePattern;
if (e.target.value) {
next.startDate = e.target.value;
} else {
delete next.startDate;
}
onChange(next);
}}
className={inputClass}
/>
</div>
<div>
<label className={labelClass}>Recurrence end (optional)</label>
<input
type="date"
value={value?.endDate ?? ""}
onChange={(e) => {
const next = { ...value, frequency: freq } as RecurrencePattern;
if (e.target.value) {
next.endDate = e.target.value;
} else {
delete next.endDate;
}
onChange(next);
}}
className={inputClass}
/>
</div>
</div>
</div>
);
}