All files / src/app/overview page.tsx

87.12% Statements 88/101
74.52% Branches 79/106
76.66% Functions 23/30
92.3% Lines 84/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 4641x                                                                                 1x               1x                 1x             1x               17x 17x 17x 17x 17x 17x     17x     17x 17x 17x   17x 68x         17x 17x   17x 17x   17x 17x       17x 17x 17x 17x 17x   17x 4x 4x 4x 4x 4x 4x           17x     4x 4x 4x 4x 4x 4x 4x 4x 4x         4x   4x 4x 4x 1x       1x   3x 3x                       4x   4x 4x         17x     17x 7x 7x 132x 144x   7x     17x 1x 1x       17x   1x 1x         17x         17x   7x   12x               17x                                                                             68x                                                                                                                                                     96x     1x                                                                   36x                                     18x   24x                     1x                                                                                 1x                       4x 4x                        
"use client";
 
/**
 * /overview: one state-first view per persona (issue #271, discussion #265).
 *
 * Left: the question, and the signals sorted worst first. Centre: the
 * layered 3D scene, an enhancement that is left out under reduced motion.
 * Right: one node in detail, with trend, chart, description and links to
 * the page that owns the record. Everything in the scene is also in the
 * list and the panel.
 */
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { Loader2 } from "lucide-react";
import OverviewDetail from "@/components/overview/OverviewDetail";
import { fetchApi } from "@/lib/api";
import { derivePersonaId } from "@/lib/auth";
import { useDemoPersona } from "@/lib/use-demo-persona";
import type {
  OverviewNode,
  OverviewView,
  Severity,
} from "@/lib/overview/types";
import { IS_STATIC } from "@/lib/static-export";
import { importOverview, type ImportGraph } from "@/lib/overview/import";
import { T, translate, useT } from "@/lib/i18n/translate";
import { useLanguage } from "@/lib/use-language";
 
function SceneLoading() {
  const t = useT("explore");
  return (
    <div className="flex h-full items-center justify-center text-sm text-(--text-secondary)">
      <Loader2 className="animate-spin mr-2" size={16} />{" "}
      {t("Loading the scene")}
    </div>
  );
}
 
const OverviewScene = dynamic(
  () => import("@/components/overview/OverviewScene"),
  {
    ssr: false,
    loading: () => <SceneLoading />,
  },
);
 
const PERSONAS = [
  { id: "patient", label: "Patient" },
  { id: "researcher", label: "Researcher" },
  { id: "hdab", label: "Access body" },
  { id: "hospital", label: "Data holder" },
] as const;
type Persona = (typeof PERSONAS)[number]["id"];
 
/** What a signal's dot means, for a screen reader. */
const SEVERITY_LABEL: Record<Severity, string> = {
  bad: "Not in order",
  warn: "At risk or due",
  info: "Information",
  ok: "In order",
};
 
const BADGE: Record<Severity, string> = {
  bad: "bg-red-500",
  warn: "bg-amber-500",
  info: "bg-sky-500",
  ok: "bg-emerald-500",
};
 
function OverviewContent() {
  const t = useT("explore");
  const lang = useLanguage();
  const searchParams = useSearchParams();
  const { data: session, status: sessionStatus } = useSession();
  const demoPersona = useDemoPersona();
  const roles: string[] = IS_STATIC
    ? [...(demoPersona?.roles ?? [])]
    : (session as { roles?: string[] } | null)?.roles ?? [];
  const username = IS_STATIC
    ? demoPersona?.username ?? null
    : session?.user?.name ?? null;
  const isAdmin = roles.includes("EDC_ADMIN");
  const derived = derivePersonaId(roles, username);
  const urlPersona = searchParams.get("persona") as Persona | null;
  const persona: Persona =
    urlPersona ??
    (PERSONAS.some((p) => p.id === derived)
      ? (derived as Persona)
      : roles.includes("TRUST_CENTER_OPERATOR") || isAdmin
        ? "hdab"
        : "patient");
  const patientId = searchParams.get("patientId");
  const sceneParam = searchParams.get("scene");
  // One imported transfer instead of the persona view (#876).
  const importId = searchParams.get("import");
  const importSpe = searchParams.get("spe") ?? "SPE-1";
 
  const [view, setView] = useState<OverviewView | null>(null);
  const [error, setError] = useState<{
    message: string;
    issue?: string;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [expandedIds, setExpandedIds] = useState<string[]>([]);
  const [reducedMotion, setReducedMotion] = useState(false);
  const [sceneOn, setSceneOn] = useState<boolean | null>(null);
 
  useEffect(() => {
    try {
      const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
      setReducedMotion(mq.matches);
      const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches);
      mq.addEventListener("change", onChange);
      return () => mq.removeEventListener("change", onChange);
    } catch {
      /* no matchMedia in this environment */
    }
  }, []);
 
  useEffect(() => {
    // Until the session is known the persona is a guess; a fetch made then
    // can come back 403 after the real one and leave a stale banner.
    Iif (!IS_STATIC && sessionStatus === "loading") return;
    let cancelled = false;
    setLoading(true);
    setError(null);
    setSelectedId(null);
    setExpandedIds([]);
    const qs = new URLSearchParams({ persona });
    Iif (patientId) qs.set("patientId", patientId);
    const url = importId
      ? `/api/spe-imports/${encodeURIComponent(
          importId,
        )}/graph?spe=${encodeURIComponent(importSpe)}`
      : `/api/overview?${qs.toString()}`;
    fetchApi(url)
      .then(async (r) => {
        const data = await r.json();
        Iif (cancelled) return;
        if (!r.ok || data?.error) {
          setError({
            message: data?.error ?? `HTTP ${r.status}`,
            issue: data?.issue,
          });
          setView(null);
        } else {
          setError(null);
          setView(
            importId
              ? importOverview(data as ImportGraph)
              : (data as OverviewView),
          );
        }
      })
      .catch((e) => {
        if (cancelled) return;
        setError({ message: e instanceof Error ? e.message : String(e) });
      })
      .finally(() => {
        Eif (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [persona, patientId, sessionStatus, importId, importSpe]);
 
  const showScene =
    sceneOn ??
    (sceneParam === "on" || (!reducedMotion && sceneParam !== "off"));
 
  const nodeById = useMemo(() => {
    const m = new Map<string, OverviewNode>();
    for (const n of view?.nodes ?? []) {
      m.set(n.id, n);
      for (const x of n.expand?.nodes ?? []) m.set(x.id, x);
    }
    return m;
  }, [view]);
 
  const toggleExpand = useCallback((id: string) => {
    setExpandedIds((cur) =>
      cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id],
    );
  }, []);
 
  const select = useCallback(
    (id: string | null) => {
      setSelectedId(id);
      Eif (id && nodeById.get(id)?.expand) toggleExpand(id);
    },
    [nodeById, toggleExpand],
  );
 
  const selected = selectedId ? nodeById.get(selectedId) ?? null : null;
 
  // The view's fixed texts (title, question, layers, legend) are the
  // builders' (lib/overview) and are translated here; signals and node
  // details carry values and stay as the API words them.
  const shown = useMemo(
    () =>
      view && {
        ...view,
        layers: view.layers.map((l) => ({
          ...l,
          name: translate(lang, "explore", l.name),
        })),
      },
    [view, lang],
  );
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="w-full px-4 py-3">
        <header
          className="mb-3 flex flex-wrap items-baseline gap-x-4 gap-y-1"
          title={t(
            "The list on the left is the complete view; the scene is the same information in three dimensions and can be switched off. Article numbers follow Regulation (EU) 2025/327 as adopted.",
          )}
        >
          <h1 className="text-lg font-semibold leading-tight">
            {t(view?.title ?? "In one view")}
          </h1>
          <p className="text-sm text-(--text-secondary)">
            {view?.question
              ? t(view.question)
              : t(
                  "Each persona sees the state that matters to them: what is out of range, what is due, what is broken, and what to do next.",
                )}
          </p>
        </header>
 
        {importId && (
          <p className="mb-3 text-sm">
            <Link
              href="/data/transfer"
              className="text-(--accent) underline"
              data-testid="overview-import-back"
            >
              {t("Back to my data")}
            </Link>
          </p>
        )}
 
        {isAdmin && !importId && (
          <nav
            className="mb-4 flex flex-wrap gap-2 text-sm"
            aria-label={t("Persona")}
          >
            {PERSONAS.map((p) => (
              <Link
                key={p.id}
                href={`/overview?persona=${p.id}`}
                className={`px-3 py-1 rounded-full border ${
                  p.id === persona
                    ? "border-(--accent) text-(--accent)"
                    : "border-(--border) text-(--text-secondary)"
                }`}
                aria-current={p.id === persona ? "page" : undefined}
              >
                {t(p.label)}
              </Link>
            ))}
          </nav>
        )}
 
        {loading && (
          <div
            className="flex items-center gap-2 text-sm text-(--text-secondary)"
            data-testid="overview-loading"
          >
            <Loader2 className="animate-spin" size={16} />{" "}
            {t("Computing the view")}
          </div>
        )}
 
        {error && !loading && (
          <div
            className="rounded-lg border border-amber-400 bg-amber-50 dark:bg-amber-900/20 p-4 text-sm"
            data-testid="overview-error"
          >
            <p>{error.message}</p>
            {error.issue && (
              <p className="mt-1">
                <T
                  area="explore"
                  tags={{
                    a: (
                      <a
                        href={error.issue}
                        className="underline"
                        target="_blank"
                        rel="noopener noreferrer"
                      />
                    ),
                  }}
                >
                  {"Tracked in <a>issue #271</a>."}
                </T>
              </p>
            )}
          </div>
        )}
 
        {view && shown && !loading && (
          <div
            className={`grid gap-4 ${
              selected
                ? "lg:grid-cols-[300px_minmax(0,1fr)_360px]"
                : "lg:grid-cols-[300px_minmax(0,1fr)]"
            }`}
          >
            {/* ── left: the view as a list ───────────────────────────────── */}
            <aside className="rounded-lg border border-(--border) bg-(--surface-2) p-4 text-sm lg:max-h-[calc(100vh-120px)] lg:overflow-auto">
              <p className="font-medium" data-testid="overview-question">
                {t(view.question)}
              </p>
              <p className="mt-1 text-xs text-(--text-secondary)">
                {view.article}
              </p>
              <h2 className="mt-4 mb-2 text-xs uppercase tracking-wide text-(--text-secondary)">
                {t("In one view")}
              </h2>
              <ul className="space-y-1" data-testid="overview-signals">
                {view.signals.map((s, i) => (
                  <li key={`${s.code}-${i}`}>
                    <button
                      type="button"
                      onClick={() => select(s.nodeId)}
                      className={`w-full text-left flex gap-2 items-start rounded-md px-2 py-1.5 border ${
                        selectedId === s.nodeId
                          ? "border-(--accent) bg-(--bg)"
                          : "border-transparent hover:bg-(--bg)"
                      }`}
                      data-testid="overview-signal"
                      data-severity={s.severity}
                      data-node={s.nodeId}
                      data-code={s.code}
                    >
                      <span
                        className={`mt-1.5 inline-block h-2.5 w-2.5 shrink-0 rounded-full ${
                          BADGE[s.severity]
                        }`}
                        aria-label={t(SEVERITY_LABEL[s.severity])}
                      />
                      <span>
                        <span className="block">{s.text}</span>
                        {s.article && (
                          <span className="block text-xs text-(--text-secondary)">
                            {s.article}
                          </span>
                        )}
                      </span>
                    </button>
                  </li>
                ))}
              </ul>
              <h2 className="mt-4 mb-2 text-xs uppercase tracking-wide text-(--text-secondary)">
                {t("Legend")}
              </h2>
              <div className="grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-(--text-secondary)">
                {view.legend.map((l) => (
                  <span key={l.text} className="flex items-center gap-1.5">
                    <span
                      className="inline-block h-2.5 w-2.5 rounded-full"
                      style={{ background: l.color }}
                    />
                    {t(l.text)}
                  </span>
                ))}
              </div>
              <p className="mt-4 text-xs text-(--text-secondary)">
                {t("As of {date}.", { date: view.asOf })}{" "}
                {view.dataNote ? t(view.dataNote) : ""}
              </p>
            </aside>
 
            {/* ── centre: the scene ──────────────────────────────────────── */}
            <section className="relative min-h-[520px] lg:h-[calc(100vh-120px)] rounded-lg border border-(--border) overflow-hidden bg-[#0b1220]">
              <div className="absolute left-3 top-3 z-10 flex flex-col gap-1 pointer-events-none">
                {[...shown.layers]
                  .sort((a, b) => b.z - a.z)
                  .map((l) => (
                    <span
                      key={l.id}
                      className="text-[11px] text-slate-300 bg-slate-900/70 rounded-r px-2 py-0.5 border-l-2"
                      style={{ borderColor: l.color }}
                    >
                      {l.name}
                    </span>
                  ))}
              </div>
              <button
                type="button"
                onClick={() => setSceneOn(!showScene)}
                className="absolute right-3 top-3 z-10 text-[11px] px-2 py-0.5 rounded-sm border border-slate-600 text-slate-300 bg-slate-900/70"
                data-testid="overview-scene-toggle"
                aria-pressed={showScene}
              >
                {showScene ? t("Scene off") : t("Scene on")}
              </button>
              {showScene ? (
                <OverviewScene
                  view={shown}
                  selectedId={selectedId}
                  expandedIds={expandedIds}
                  onSelect={select}
                  className="absolute inset-0"
                />
              ) : (
                <div
                  className="flex h-full min-h-[520px] items-center justify-center p-6 text-center text-sm text-slate-300"
                  data-testid="overview-scene-off"
                >
                  {reducedMotion
                    ? t(
                        "The animated scene is off because your system asks for reduced motion. The list on the left is the full view.",
                      )
                    : t(
                        "The scene is off. The list on the left is the full view.",
                      )}
                </div>
              )}
              <div className="absolute bottom-2 right-3 z-10 text-[11px] text-slate-400 pointer-events-none">
                {t(
                  "drag to orbit · wheel to zoom · click a node · arrows move · shift + arrows rotate · + and - zoom · space pauses · orbits on its own after 30 s",
                )}
              </div>
            </section>
 
            {/* ── right: one node in detail ──────────────────────────────── */}
            {selected && (
              <OverviewDetail
                node={selected}
                expanded={expandedIds.includes(selected.id)}
                onClose={() => setSelectedId(null)}
                onToggleExpand={() => toggleExpand(selected.id)}
              />
            )}
          </div>
        )}
      </div>
    </div>
  );
}
 
export default function OverviewPage() {
  const tc = useT("common");
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-(--bg) p-6 text-sm text-(--text-secondary)">
          {tc("Loading…")}
        </div>
      }
    >
      <OverviewContent />
    </Suspense>
  );
}