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
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next-e2e/types/routes.d.ts" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+3 -3
View File
@@ -1,6 +1,6 @@
/// <reference lib="webworker" />
const CACHE_NAME = "planarchy-v1";
const CACHE_NAME = "capakraken-v2";
const STATIC_EXTENSIONS = /\.(js|css|png|jpg|jpeg|svg|gif|ico|woff2?|ttf|eot)$/;
// Offline fallback page (simple inline HTML)
@@ -9,7 +9,7 @@ const OFFLINE_HTML = `<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Planarchy — Offline</title>
<title>CapaKraken - Offline</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
@@ -31,7 +31,7 @@ const OFFLINE_HTML = `<!DOCTYPE html>
<body>
<div class="container">
<h1>You are offline</h1>
<p>Planarchy requires an internet connection. Please check your network and try again.</p>
<p>CapaKraken requires an internet connection. Please check your network and try again.</p>
<button onclick="location.reload()">Retry</button>
</div>
</body>
+2 -2
View File
@@ -5,10 +5,10 @@ import { auth } from "~/server/auth.js";
export default async function AppLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
if (!session) {
if (!session?.user) {
redirect("/auth/signin");
}
const userRole = (session.user as { role?: string }).role ?? "USER";
const userRole = (session.user as { role?: string } | undefined)?.role ?? "USER";
return <AppShell userRole={userRole}>{children}</AppShell>;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export const runtime = "nodejs";
export async function GET() {
const session = await auth();
if (!session) {
if (!session?.user) {
return new Response("Unauthorized", { status: 401 });
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { auth } from "~/server/auth.js";
export default async function HomePage() {
const session = await auth();
if (!session) {
if (!session?.user) {
redirect("/auth/signin");
}
@@ -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],
+4 -2
View File
@@ -108,8 +108,10 @@ export function useDashboardLayout() {
const onLayoutChange = useCallback(
(layout: { i: string; x: number; y: number; w: number; h: number }[]) => {
setConfig((prev) => {
const layoutMap = new Map(layout.map((item) => [item.i, item]));
const previousWidgetMap = new Map(prev.widgets.map((widget) => [widget.id, widget]));
const updatedWidgets = prev.widgets.map((w) => {
const item = layout.find((l) => l.i === w.id);
const item = layoutMap.get(w.id);
if (!item) return w;
return { ...w, x: item.x, y: item.y, w: item.w, h: item.h };
});
@@ -118,7 +120,7 @@ export function useDashboardLayout() {
// react-grid-layout fires onLayoutChange on mount too — we skip that
// to avoid overwriting saved positions with compacted coordinates.
const changed = updatedWidgets.some((w) => {
const orig = prev.widgets.find((o) => o.id === w.id);
const orig = previousWidgetMap.get(w.id);
return orig && (w.x !== orig.x || w.y !== orig.y || w.w !== orig.w || w.h !== orig.h);
});
+99
View File
@@ -0,0 +1,99 @@
"use client";
import { useMemo } from "react";
import { trpc } from "~/lib/trpc/client.js";
export interface ClientReference {
id: string;
name: string;
code: string | null;
isActive?: boolean;
}
export interface CountryReference {
id: string;
name: string;
code: string;
isActive?: boolean;
}
export interface RoleReference {
id: string;
name: string;
isActive?: boolean;
}
export interface ReferenceDataSelection {
clients?: boolean;
countries?: boolean;
roles?: boolean;
chapters?: boolean;
}
const LOOKUP_STALE_TIME_MS = 300_000;
export function useReferenceData(selection: ReferenceDataSelection = {}) {
const shouldLoadClients = selection.clients === true;
const shouldLoadCountries = selection.countries === true;
const shouldLoadRoles = selection.roles === true;
const shouldLoadChapters = selection.chapters === true;
const { data: clientsRaw } = trpc.clientEntity.list.useQuery(
{ isActive: true },
{ staleTime: LOOKUP_STALE_TIME_MS, enabled: shouldLoadClients },
);
const { data: countriesRaw } = trpc.country.list.useQuery(
{ isActive: true },
{ staleTime: LOOKUP_STALE_TIME_MS, enabled: shouldLoadCountries },
);
const { data: rolesRaw } = trpc.role.list.useQuery(
{ isActive: true },
{ staleTime: LOOKUP_STALE_TIME_MS, enabled: shouldLoadRoles },
);
const { data: chaptersRaw } = trpc.resource.chapters.useQuery(undefined, {
staleTime: LOOKUP_STALE_TIME_MS,
enabled: shouldLoadChapters,
});
const clients = useMemo<ClientReference[]>(() => {
if (!shouldLoadClients) return [];
const list = (
Array.isArray(clientsRaw) ? clientsRaw : ((clientsRaw as { clients?: ClientReference[] } | undefined)?.clients ?? [])
) as ClientReference[];
return [...list]
.filter((client) => client.isActive !== false)
.sort((left, right) => left.name.localeCompare(right.name));
}, [clientsRaw, shouldLoadClients]);
const countries = useMemo<CountryReference[]>(() => {
if (!shouldLoadCountries) return [];
const list = (Array.isArray(countriesRaw) ? countriesRaw : []) as CountryReference[];
return [...list]
.filter((country) => country.isActive !== false)
.sort((left, right) => left.name.localeCompare(right.name));
}, [countriesRaw, shouldLoadCountries]);
const roles = useMemo<RoleReference[]>(() => {
if (!shouldLoadRoles) return [];
const list = (Array.isArray(rolesRaw) ? rolesRaw : []) as RoleReference[];
return [...list]
.filter((role) => role.isActive !== false)
.sort((left, right) => left.name.localeCompare(right.name));
}, [rolesRaw, shouldLoadRoles]);
const chapters = useMemo<string[]>(() => {
if (!shouldLoadChapters) return [];
const list = (Array.isArray(chaptersRaw) ? chaptersRaw : []) as string[];
return [...list].sort((left, right) => left.localeCompare(right));
}, [chaptersRaw, shouldLoadChapters]);
return {
clients,
countries,
roles,
chapters,
};
}
+13 -36
View File
@@ -1,59 +1,36 @@
/**
* Shared hook for loading filter options used across dashboard widgets.
* Loads clients, countries, roles, and chapters once with long cache TTL.
* Loads only the requested lookup sets and exposes them as filter options.
*/
"use client";
import { useMemo } from "react";
import { trpc } from "~/lib/trpc/client.js";
import { useReferenceData, type ReferenceDataSelection } from "~/hooks/useReferenceData.js";
export interface FilterOption {
value: string;
label: string;
}
export function useWidgetFilterOptions() {
const { data: clientsRaw } = trpc.clientEntity.list.useQuery(
{ isActive: true },
{ staleTime: 300_000 },
);
const { data: countriesRaw } = trpc.country.list.useQuery(
{ isActive: true },
{ staleTime: 300_000 },
);
const { data: rolesRaw } = trpc.role.list.useQuery(
{ isActive: true },
{ staleTime: 300_000 },
);
export function useWidgetFilterOptions(selection: ReferenceDataSelection = {}) {
const { clients: clientRows, countries: countryRows, roles: roleRows, chapters: chapterRows } =
useReferenceData(selection);
const clients = useMemo<FilterOption[]>(() => {
const list = (Array.isArray(clientsRaw) ? clientsRaw : (clientsRaw as any)?.clients ?? []) as Array<{ id: string; name: string }>;
return list.map((c) => ({ value: c.id, label: c.name }));
}, [clientsRaw]);
return clientRows.map((client) => ({ value: client.id, label: client.name }));
}, [clientRows]);
const countries = useMemo<FilterOption[]>(() => {
const list = (Array.isArray(countriesRaw) ? countriesRaw : []) as Array<{ id: string; name: string }>;
return list.map((c) => ({ value: c.id, label: c.name }));
}, [countriesRaw]);
return countryRows.map((country) => ({ value: country.id, label: country.name }));
}, [countryRows]);
const roles = useMemo<FilterOption[]>(() => {
const list = (Array.isArray(rolesRaw) ? rolesRaw : []) as Array<{ id: string; name: string }>;
return list.map((r) => ({ value: r.id, label: r.name }));
}, [rolesRaw]);
return roleRows.map((role) => ({ value: role.id, label: role.name }));
}, [roleRows]);
// Chapters are derived from roles or can be hardcoded common ones
const chapters = useMemo<FilterOption[]>(() => {
const common = [
"Digital Content Production",
"Project Management",
"Art Direction",
"CGI-Dev",
"Product Data Management",
];
return common.map((c) => ({ value: c, label: c }));
}, []);
return chapterRows.map((chapter) => ({ value: chapter, label: chapter }));
}, [chapterRows]);
return { clients, countries, roles, chapters };
}
+1
View File
@@ -14,6 +14,7 @@ const LoginSchema = z.object({
});
const authConfig = {
trustHost: true,
providers: [
Credentials({
name: "credentials",