chore(repo): checkpoint current capakraken implementation state

This commit is contained in:
2026-03-29 12:47:12 +02:00
parent beae1a5d6e
commit 47e4d701ff
94 changed files with 4283 additions and 1710 deletions
@@ -248,6 +248,9 @@ export function ChatPanel({ onClose }: { onClose: () => void }) {
}
if (scope === "resource") void utils.resource.invalidate();
if (scope === "project") void utils.project.invalidate();
if (scope === "country") void utils.country.invalidate();
if (scope === "holidayCalendar") void utils.holidayCalendar.invalidate();
if (scope === "vacation") void utils.vacation.invalidate();
}
}
}
@@ -2,7 +2,7 @@
import type { DashboardWidgetConfig, DashboardWidgetType } from "@capakraken/shared/types";
import dynamic from "next/dynamic";
import { Suspense, useState, useRef, useEffect } from "react";
import { Suspense, useState, useRef, useEffect, useMemo } from "react";
import { useDashboardLayout } from "~/hooks/useDashboardLayout.js";
import { WidgetContainer } from "./WidgetContainer.js";
import { AddWidgetModal } from "./AddWidgetModal.js";
@@ -44,6 +44,94 @@ function renderWidget(
);
}
function DeferredWidgetFallback() {
return (
<div className="flex h-full min-h-32 flex-col gap-3 p-1">
<div className="h-3 w-32 shimmer-skeleton rounded" />
<div className="h-20 w-full shimmer-skeleton rounded-2xl" />
<div className="h-3 w-4/5 shimmer-skeleton rounded" />
<div className="h-3 w-3/5 shimmer-skeleton rounded" />
</div>
);
}
function DeferredWidgetBody({
type,
config,
activationRank,
isPriority,
onConfigChange,
}: {
type: DashboardWidgetType;
config: DashboardWidgetConfig;
activationRank: number;
isPriority: boolean;
onConfigChange: (u: Record<string, unknown>) => void;
}) {
const containerRef = useRef<HTMLDivElement>(null);
const [isActive, setIsActive] = useState(isPriority);
useEffect(() => {
if (isPriority) {
setIsActive(true);
}
}, [isPriority]);
useEffect(() => {
if (isActive) return;
const element = containerRef.current;
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => {
if (!entry?.isIntersecting) return;
setIsActive(true);
observer.disconnect();
},
{ rootMargin: "320px 0px", threshold: 0.05 },
);
observer.observe(element);
return () => observer.disconnect();
}, [isActive]);
useEffect(() => {
if (isActive || isPriority || typeof window === "undefined") return;
const activationDelayMs = 900 + Math.min(activationRank, 6) * 180;
let timeoutId: number | null = null;
let idleId: number | null = null;
const browserWindow = window as Window &
typeof globalThis & {
requestIdleCallback?: (
callback: IdleRequestCallback,
options?: IdleRequestOptions,
) => number;
cancelIdleCallback?: (handle: number) => void;
};
const activate = () => setIsActive(true);
if (typeof browserWindow.requestIdleCallback === "function") {
idleId = browserWindow.requestIdleCallback(activate, { timeout: activationDelayMs });
} else {
timeoutId = browserWindow.setTimeout(activate, activationDelayMs);
}
return () => {
if (idleId !== null && typeof browserWindow.cancelIdleCallback === "function") {
browserWindow.cancelIdleCallback(idleId);
}
if (timeoutId !== null) {
browserWindow.clearTimeout(timeoutId);
}
};
}, [activationRank, isActive, isPriority]);
return <div ref={containerRef} className="h-full">{isActive ? renderWidget(type, config, onConfigChange) : <DeferredWidgetFallback />}</div>;
}
export function DashboardClient() {
const [addModalOpen, setAddModalOpen] = useState(false);
const { config, addWidget, removeWidget, updateWidgetConfig, onLayoutChange, resetLayout } =
@@ -52,29 +140,80 @@ export function DashboardClient() {
// Measure grid container width so Responsive knows the column size.
// We can't use WidthProvider (uses findDOMNode, deprecated in React 18).
const containerRef = useRef<HTMLDivElement>(null);
const resizeFrameRef = useRef<number | null>(null);
const lastMeasuredWidthRef = useRef(0);
const [gridWidth, setGridWidth] = useState(1200);
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const updateWidth = (width: number) => {
const roundedWidth = Math.max(0, Math.round(width));
if (roundedWidth === lastMeasuredWidthRef.current) return;
lastMeasuredWidthRef.current = roundedWidth;
setGridWidth((currentWidth) => (currentWidth === roundedWidth ? currentWidth : roundedWidth));
};
const ro = new ResizeObserver(([entry]) => {
if (entry) setGridWidth(entry.contentRect.width);
if (!entry) return;
if (resizeFrameRef.current !== null) cancelAnimationFrame(resizeFrameRef.current);
resizeFrameRef.current = requestAnimationFrame(() => {
resizeFrameRef.current = null;
updateWidth(entry.contentRect.width);
});
});
ro.observe(el);
setGridWidth(el.getBoundingClientRect().width);
return () => ro.disconnect();
updateWidth(el.getBoundingClientRect().width);
return () => {
ro.disconnect();
if (resizeFrameRef.current !== null) cancelAnimationFrame(resizeFrameRef.current);
};
}, []);
const layouts = {
lg: config.widgets.map((w) => ({
i: w.id,
x: w.x,
y: w.y,
w: w.w,
h: w.h,
minW: w.minW ?? 2,
minH: w.minH ?? 2,
})),
};
const layouts = useMemo(
() => ({
lg: config.widgets.map((w) => ({
i: w.id,
x: w.x,
y: w.y,
w: w.w,
h: w.h,
minW: w.minW ?? 2,
minH: w.minH ?? 2,
})),
}),
[config.widgets],
);
const renderedWidgets = useMemo(
() =>
config.widgets.map((widget) => {
const widgetDefinition = getWidget(widget.type);
const isPriorityWidget = widget.y < 3;
return (
<div key={widget.id}>
<WidgetContainer
title={widget.title ?? widgetDefinition.label}
description={widgetDefinition.description}
showDetails={widget.config.showDetails === true}
onToggleDetails={() =>
updateWidgetConfig(widget.id, {
showDetails: widget.config.showDetails !== true,
})
}
onRemove={() => removeWidget(widget.id)}
>
<DeferredWidgetBody
type={widget.type}
config={widget.config}
activationRank={widget.y * 12 + widget.x}
isPriority={isPriorityWidget}
onConfigChange={(update) => updateWidgetConfig(widget.id, update)}
/>
</WidgetContainer>
</div>
);
}),
[config.widgets, removeWidget, updateWidgetConfig],
);
return (
<div className="app-page space-y-6">
@@ -153,25 +292,7 @@ export function DashboardClient() {
draggableHandle=".widget-drag-handle"
margin={[12, 12]}
>
{config.widgets.map((widget) => (
<div key={widget.id}>
<WidgetContainer
title={widget.title ?? getWidget(widget.type).label}
description={getWidget(widget.type).description}
showDetails={widget.config.showDetails === true}
onToggleDetails={() =>
updateWidgetConfig(widget.id, {
showDetails: widget.config.showDetails !== true,
})
}
onRemove={() => removeWidget(widget.id)}
>
{renderWidget(widget.type, widget.config, (update) =>
updateWidgetConfig(widget.id, update),
)}
</WidgetContainer>
</div>
))}
{renderedWidgets}
</AnyGridLayout>
);
})()}
@@ -80,7 +80,7 @@ function SummaryCard({
export function BudgetForecastWidget({ config, onConfigChange }: WidgetProps) {
const showDetails = config.showDetails === true;
const { clients } = useWidgetFilterOptions();
const { clients } = useWidgetFilterOptions({ clients: true });
const filters = useMemo<WidgetFilter[]>(
() => [
@@ -7,6 +7,7 @@ import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { AnimatedNumber } from "~/components/ui/AnimatedNumber.js";
import { WidgetFilterBar, type WidgetFilter } from "~/components/dashboard/WidgetFilterBar.js";
import { useWidgetFilterOptions } from "~/hooks/useWidgetFilterOptions.js";
import { useReferenceData } from "~/hooks/useReferenceData.js";
function UtilizationBar({ percent }: { percent: number }) {
const barColor =
@@ -24,11 +25,6 @@ function UtilizationBar({ percent }: { percent: number }) {
type TopSortKey = "name" | "actual" | "expected";
type WatchSortKey = "name" | "actual" | "target";
type CountryOption = {
id: string;
name: string;
};
type ChargeabilityRow = {
id: string;
displayName: string;
@@ -164,7 +160,8 @@ export function ChargeabilityWidget({ config: _config, onConfigChange }: WidgetP
includeProposed?: boolean;
showDetails?: boolean;
};
const { chapters } = useWidgetFilterOptions();
const { chapters } = useWidgetFilterOptions({ chapters: true });
const { countries } = useReferenceData({ countries: true });
const widgetFilters = useMemo<WidgetFilter[]>(
() => [
@@ -187,15 +184,6 @@ export function ChargeabilityWidget({ config: _config, onConfigChange }: WidgetP
const [topVisibleCount, setTopVisibleCount] = useState(batchSize);
const [watchVisibleCount, setWatchVisibleCount] = useState(batchSize);
const { data: countriesData } = trpc.country.list.useQuery(undefined, { staleTime: 60_000 });
const countries = useMemo(
() =>
((countriesData ?? []) as Array<{ id: string; name: string }>).map((country) => ({
id: country.id,
name: country.name,
})),
[countriesData],
) as CountryOption[];
const selectedCountryLabel = useMemo(() => {
if (selectedCountryIds.length === 0) return "Countries: All";
if (selectedCountryIds.length === 1) {
@@ -71,7 +71,7 @@ function formatLocation(location: {
export function ProjectHealthWidget({ config, onConfigChange }: WidgetProps) {
const showDetails = config.showDetails === true;
const { clients } = useWidgetFilterOptions();
const { clients } = useWidgetFilterOptions({ clients: true });
const filters = useMemo<WidgetFilter[]>(
() => [
@@ -1,9 +1,10 @@
"use client";
import { useState } from "react";
import { useMemo, useState } from "react";
import { trpc } from "~/lib/trpc/client.js";
import type { WidgetProps } from "~/components/dashboard/widget-registry.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { useWidgetFilterOptions } from "~/hooks/useWidgetFilterOptions.js";
interface ResourceRow {
id: string;
@@ -29,8 +30,7 @@ export function ResourceTableWidget({ config, onConfigChange }: WidgetProps) {
{ staleTime: 60_000 },
);
const { data: chapterData } = trpc.resource.chapters.useQuery(undefined, { staleTime: 120_000 });
const chapters = chapterData ?? [];
const { chapters } = useWidgetFilterOptions({ chapters: true });
type SortKey = "eid" | "name" | "chapter" | "bookings" | "utilization" | "target";
const [sortKey, setSortKey] = useState<SortKey>("name");
@@ -44,6 +44,32 @@ export function ResourceTableWidget({ config, onConfigChange }: WidgetProps) {
}
}
const list = useMemo(() => (resources ?? []) as unknown as ResourceRow[], [resources]);
const sorted = useMemo(() => {
const next = [...list];
next.sort((a, b) => {
const mult = sortDir === "asc" ? 1 : -1;
switch (sortKey) {
case "eid":
return mult * a.eid.localeCompare(b.eid);
case "name":
return mult * a.displayName.localeCompare(b.displayName);
case "chapter":
return mult * (a.chapter ?? "").localeCompare(b.chapter ?? "");
case "bookings":
return mult * (a.bookingCount - b.bookingCount);
case "utilization":
return mult * (a.utilizationPercent - b.utilizationPercent);
case "target":
return mult * (a.chargeabilityTarget - b.chargeabilityTarget);
default:
return 0;
}
});
return next;
}, [list, sortDir, sortKey]);
if (isLoading) {
return (
<div className="flex flex-col gap-2 pt-1">
@@ -74,28 +100,6 @@ export function ResourceTableWidget({ config, onConfigChange }: WidgetProps) {
);
}
const list = (resources ?? []) as unknown as ResourceRow[];
const sorted = [...list].sort((a, b) => {
const mult = sortDir === "asc" ? 1 : -1;
switch (sortKey) {
case "eid":
return mult * a.eid.localeCompare(b.eid);
case "name":
return mult * a.displayName.localeCompare(b.displayName);
case "chapter":
return mult * (a.chapter ?? "").localeCompare(b.chapter ?? "");
case "bookings":
return mult * (a.bookingCount - b.bookingCount);
case "utilization":
return mult * (a.utilizationPercent - b.utilizationPercent);
case "target":
return mult * (a.chargeabilityTarget - b.chargeabilityTarget);
default:
return 0;
}
});
return (
<div className="flex flex-col h-full gap-3">
{/* Filter */}
@@ -107,9 +111,9 @@ export function ResourceTableWidget({ config, onConfigChange }: WidgetProps) {
className="app-select w-44 text-xs"
>
<option value="">All Chapters</option>
{chapters.map((c) => (
<option key={c} value={c}>
{c}
{chapters.map((chapterOption) => (
<option key={chapterOption.value} value={chapterOption.value}>
{chapterOption.label}
</option>
))}
</select>
@@ -11,7 +11,7 @@ type SortKey = "eid" | "name" | "chapter" | "score" | "lcr";
export function TopValueWidget({ config, onConfigChange }: WidgetProps) {
const limit = (config.limit as number) || 10;
const { chapters } = useWidgetFilterOptions();
const { chapters } = useWidgetFilterOptions({ chapters: true });
const filters = useMemo<WidgetFilter[]>(
() => [
@@ -424,6 +424,13 @@ export function TimelineProvider({
const { resourceMap, allocsByResource, resources } = useMemo(() => {
const resourceMap = new Map<string, ResourceBrief>();
const allocsByResource = new Map<string, TimelineAssignmentEntry[]>();
const firstAssignmentByResource = new Map<string, TimelineAssignmentEntry>();
const projectIdsByResource = new Map<string, Set<string>>();
const clientIdsByResource = new Map<string, Set<string>>();
const chapterFilter = new Set(filters.chapters);
const eidFilter = new Set(filters.eids);
const projectFilter = new Set(filters.projectIds);
const clientFilter = new Set(filters.clientIds);
if (eidFilterData?.resources) {
for (const r of eidFilterData.resources as {
@@ -445,6 +452,7 @@ export function TimelineProvider({
for (const entry of visibleAssignments) {
if (!entry.resourceId) continue;
firstAssignmentByResource.set(entry.resourceId, entry);
if (!resourceMap.has(entry.resourceId)) {
resourceMap.set(entry.resourceId, {
id: entry.resource!.id,
@@ -456,13 +464,23 @@ export function TimelineProvider({
const arr = allocsByResource.get(entry.resourceId) ?? [];
arr.push(entry);
allocsByResource.set(entry.resourceId, arr);
const projectIds = projectIdsByResource.get(entry.resourceId) ?? new Set<string>();
projectIds.add(entry.projectId);
projectIdsByResource.set(entry.resourceId, projectIds);
if (typeof entry.project.clientId === "string") {
const clientIds = clientIdsByResource.get(entry.resourceId) ?? new Set<string>();
clientIds.add(entry.project.clientId);
clientIdsByResource.set(entry.resourceId, clientIds);
}
}
// Merge cross-project context allocations so they appear during drag
if (isDragging && contextAllocations.length > 0) {
for (const ca of contextAllocations) {
if (!ca.resourceId) continue;
const existing = visibleAssignments.find((entry) => entry.resourceId === ca.resourceId);
const existing = firstAssignmentByResource.get(ca.resourceId);
if (existing && !resourceMap.has(ca.resourceId)) {
resourceMap.set(ca.resourceId, {
id: existing.resource!.id,
@@ -477,32 +495,35 @@ export function TimelineProvider({
let resources = [...resourceMap.values()].sort((a, b) =>
a.displayName.localeCompare(b.displayName),
);
if (filters.chapters.length > 0) {
resources = resources.filter((r) => r.chapter && filters.chapters.includes(r.chapter));
if (chapterFilter.size > 0) {
resources = resources.filter((r) => r.chapter && chapterFilter.has(r.chapter));
}
if (filters.eids.length > 0) {
resources = resources.filter((r) => filters.eids.includes(r.eid));
if (eidFilter.size > 0) {
resources = resources.filter((r) => eidFilter.has(r.eid));
}
if (filters.projectIds.length > 0) {
resources = resources.filter((r) =>
visibleAssignments.some(
(e) => e.resourceId === r.id && filters.projectIds.includes(e.projectId),
),
);
if (projectFilter.size > 0) {
resources = resources.filter((r) => {
const projectIds = projectIdsByResource.get(r.id);
if (!projectIds) return false;
for (const projectId of projectIds) {
if (projectFilter.has(projectId)) {
return true;
}
}
return false;
});
}
if (filters.clientIds.length > 0) {
resources = resources.filter((r) =>
visibleAssignments.some(
(entry) => {
const clientId = entry.project.clientId;
return (
entry.resourceId === r.id &&
typeof clientId === "string" &&
filters.clientIds.includes(clientId)
);
},
),
);
if (clientFilter.size > 0) {
resources = resources.filter((r) => {
const clientIds = clientIdsByResource.get(r.id);
if (!clientIds) return false;
for (const clientId of clientIds) {
if (clientFilter.has(clientId)) {
return true;
}
}
return false;
});
}
return { resourceMap, allocsByResource, resources };
@@ -520,6 +541,14 @@ export function TimelineProvider({
// ─── Project groups (for project view) ────────────────────────────────────
const projectGroups = useMemo(() => {
const projectGroupMap = new Map<string, ProjectGroup>();
const resourceRowMapByProject = new Map<
string,
Map<string, ProjectGroup["resourceRows"][number]>
>();
const chapterFilter = new Set(filters.chapters);
const eidFilter = new Set(filters.eids);
const clientFilter = new Set(filters.clientIds);
const projectFilter = new Set(filters.projectIds);
const allGroupEntries: TimelineProjectEntry[] = [...visibleAssignments, ...visibleDemands];
for (const entry of allGroupEntries) {
let group = projectGroupMap.get(entry.projectId);
@@ -537,43 +566,37 @@ export function TimelineProvider({
resourceRows: [],
};
projectGroupMap.set(entry.projectId, group);
resourceRowMapByProject.set(entry.projectId, new Map());
}
const currentGroup = group;
if (!currentGroup) continue;
if (entry.kind === "assignment" && entry.resourceId) {
const existingRow = currentGroup.resourceRows.find(
(r) => r.resource.id === entry.resourceId,
);
const rowMap = resourceRowMapByProject.get(entry.projectId);
const existingRow = rowMap?.get(entry.resourceId);
if (existingRow) {
existingRow.allocs.push(entry);
} else {
const res = resourceMap.get(entry.resourceId);
if (res) {
currentGroup.resourceRows.push({ resource: res, allocs: [entry] });
const row = { resource: res, allocs: [entry] };
currentGroup.resourceRows.push(row);
rowMap?.set(entry.resourceId, row);
}
}
}
}
for (const group of projectGroupMap.values()) {
group.resourceRows = group.resourceRows.filter(({ resource, allocs }) => {
if (filters.chapters.length > 0) {
if (!resource.chapter || !filters.chapters.includes(resource.chapter)) {
group.resourceRows = group.resourceRows.filter(({ resource }) => {
if (chapterFilter.size > 0) {
if (!resource.chapter || !chapterFilter.has(resource.chapter)) {
return false;
}
}
if (filters.eids.length > 0 && !filters.eids.includes(resource.eid)) {
if (eidFilter.size > 0 && !eidFilter.has(resource.eid)) {
return false;
}
if (filters.clientIds.length > 0) {
const matchesClient = allocs.some(
(alloc) => {
const clientId = alloc.project.clientId;
return typeof clientId === "string" && filters.clientIds.includes(clientId);
},
);
if (!matchesClient) {
return false;
}
if (clientFilter.size > 0 && (!group.clientId || !clientFilter.has(group.clientId))) {
return false;
}
return true;
});
@@ -584,18 +607,18 @@ export function TimelineProvider({
return [...projectGroupMap.values()]
.sort((a, b) => a.startDate.getTime() - b.startDate.getTime())
.filter((pg) => {
if (filters.projectIds.length > 0 && !filters.projectIds.includes(pg.id)) return false;
if (projectFilter.size > 0 && !projectFilter.has(pg.id)) return false;
if (
filters.clientIds.length > 0 &&
(!pg.clientId || !filters.clientIds.includes(pg.clientId))
clientFilter.size > 0 &&
(!pg.clientId || !clientFilter.has(pg.clientId))
)
return false;
if (
filters.chapters.length > 0 &&
chapterFilter.size > 0 &&
pg.resourceRows.length === 0
)
return false;
if (filters.eids.length > 0 && pg.resourceRows.length === 0)
if (eidFilter.size > 0 && pg.resourceRows.length === 0)
return false;
return true;
});
@@ -4,6 +4,7 @@ import { createPortal } from "react-dom";
import { useMemo, useState, type ReactNode } from "react";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { useAnchoredOverlay } from "~/hooks/useAnchoredOverlay.js";
import { useReferenceData } from "~/hooks/useReferenceData.js";
import { trpc } from "~/lib/trpc/client.js";
import type { TimelineFilters } from "./TimelineFilter.js";
@@ -105,6 +106,7 @@ interface TimelineQuickFiltersProps {
export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFiltersProps) {
const [eidSearch, setEidSearch] = useState("");
const { clients, countries } = useReferenceData({ clients: true, countries: true });
const { data: resourceData } = trpc.resource.list.useQuery(
{ isActive: true, limit: 500 },
{ staleTime: 60_000 },
@@ -113,15 +115,6 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
{ isActive: true, search: eidSearch, limit: 100 },
{ staleTime: 15_000 },
);
const { data: clientsData } = trpc.clientEntity.list.useQuery(
{ isActive: true },
{ staleTime: 60_000 },
);
const { data: countriesData } = trpc.country.list.useQuery(
{ isActive: true },
{ staleTime: 60_000 },
);
const resources = ((resourceData?.resources as ResourceOption[] | undefined) ?? []).slice();
const eidSuggestions = (
(eidSearchData?.resources as ResourceOption[] | undefined) ??
@@ -140,22 +133,6 @@ export function TimelineQuickFilters({ filters, onChange }: TimelineQuickFilters
[resources],
);
const clients = useMemo(
() =>
((clientsData ?? []) as ClientOption[])
.filter((client) => client.isActive !== false)
.map((client) => ({ id: client.id, name: client.name, code: client.code })),
[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(
() => new Map(resources.map((resource) => [resource.eid, resource])),
[resources],