All files / src/app/patient page.tsx

81.53% Statements 53/65
60% Branches 45/75
85% Functions 17/20
90.74% Lines 49/54

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                                                                                          1x                                                                                   42x                                         15x 15x 15x 15x 15x 15x 15x   15x 7x   4x 4x     4x 4x 4x 4x     4x     1x 1x       15x 8x 1x 1x   1x 1x     1x 1x               15x       15x 8x 8x 8x   8x 8x 1x 1x 1x       1x 1x     1x                     8x     8x     15x                                                                                                                                     1x             14x                                                                                                                               1x                   1x 1x                                                                                                                    
"use client";
 
import { fetchApi } from "@/lib/api";
import { useEffect, useMemo, useState } from "react";
import {
  Activity,
  Heart,
  Stethoscope,
  FlaskConical,
  Pill,
  Scissors,
  Users,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import { SignInRequired } from "@/components/SignInRequired";
 
interface PatientListItem {
  id: string;
  name: string;
  gender: string;
  birthDate: string;
}
 
interface CohortStats {
  patients: number;
  encounters: number;
  conditions: number;
  observations: number;
  medications: number;
  procedures: number;
}
 
interface TimelineEntry {
  fhirType: string;
  fhirId: string;
  date: string;
  display: string;
  omopType: string;
  omopId: string;
}
 
/* WCAG-safe FHIR type colours — ≥4.5:1 on white (light) and on #0b1326 (dark) */
const FHIR_TYPE_TOKENS: Record<
  string,
  { text: string; bg: string; icon: React.ReactNode }
> = {
  Encounter: {
    text: "var(--fhir-encounter)",
    bg: "var(--role-holder-bg)",
    icon: <Stethoscope size={12} />,
  },
  Condition: {
    text: "var(--fhir-condition)",
    bg: "var(--role-user-bg)",
    icon: <Activity size={12} />,
  },
  Observation: {
    text: "var(--fhir-observation)",
    bg: "var(--role-user-bg)",
    icon: <FlaskConical size={12} />,
  },
  MedicationRequest: {
    text: "var(--fhir-medication)",
    bg: "var(--role-hdab-bg)",
    icon: <Pill size={12} />,
  },
  Procedure: {
    text: "var(--fhir-procedure)",
    bg: "var(--role-trust-bg)",
    icon: <Scissors size={12} />,
  },
};
 
/* Metric orb stat card — Stitch patient_dashboard_day pattern */
function MetricCard({
  label,
  value,
  isOrb = false,
  icon,
  sub,
}: {
  label: string;
  value?: number;
  isOrb?: boolean;
  icon: React.ReactNode;
  sub?: string;
}) {
  return (
    <div className="surface-card p-5 flex items-start justify-between gap-3 border border-[var(--border)]">
      <div className="min-w-0 flex-1">
        <p className="section-label mb-1 break-words">{label}</p>
        <p className="text-3xl font-black text-[var(--text-primary)] leading-none tracking-tight">
          {value != null ? value.toLocaleString() : "—"}
        </p>
        {sub && (
          <p className="text-xs text-[var(--text-secondary)] mt-1">{sub}</p>
        )}
      </div>
      {isOrb ? (
        <div className="metric-orb">{icon}</div>
      ) : (
        <div className="icon-orb">{icon}</div>
      )}
    </div>
  );
}
 
export default function PatientPage() {
  const [patients, setPatients] = useState<PatientListItem[]>([]);
  const [stats, setStats] = useState<CohortStats | null>(null);
  const [selected, setSelected] = useState<string>("");
  const [timeline, setTimeline] = useState<TimelineEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [restricted, setRestricted] = useState(false);
  const [unauthenticated, setUnauthenticated] = useState(false);
 
  useEffect(() => {
    fetchApi("/api/patient")
      .then(async (r) => {
        Iif (r.status === 401) throw new Error("UNAUTHENTICATED");
        return r.json();
      })
      .then((d) => {
        setPatients(d.patients ?? []);
        setStats(d.stats ?? null);
        setRestricted(d.restricted === true);
        Iif (d.restricted && d.patients?.length === 1) {
          setSelected(d.patients[0].id);
        }
        setLoading(false);
      })
      .catch((e: Error) => {
        Iif (e.message === "UNAUTHENTICATED") setUnauthenticated(true);
        setLoading(false);
      });
  }, []);
 
  useEffect(() => {
    if (!selected) return;
    setLoading(true);
    fetchApi(`/api/patient?patientId=${encodeURIComponent(selected)}`)
      .then(async (r) => {
        Iif (r.status === 401) throw new Error("UNAUTHENTICATED");
        return r.json();
      })
      .then((d) => {
        setTimeline(d.timeline ?? []);
        setLoading(false);
      })
      .catch((e: Error) => {
        if (e.message === "UNAUTHENTICATED") setUnauthenticated(true);
        setLoading(false);
      });
  }, [selected]);
 
  const selectedPatient = patients.find((p) => p.id === selected);
 
  /* Group timeline entries by year+month, newest first. Events within each
     month are also sorted newest first so the reader scans most recent → oldest. */
  const timelineGroups = useMemo(() => {
    const dated = timeline.filter((e) => !!e.date);
    const undated = timeline.filter((e) => !e.date);
    dated.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
 
    const groups: { key: string; label: string; items: TimelineEntry[] }[] = [];
    for (const entry of dated) {
      const d = new Date(entry.date);
      Iif (Number.isNaN(d.getTime())) continue;
      const key = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(
        2,
        "0",
      )}`;
      const existing = groups.find((g) => g.key === key);
      Iif (existing) {
        existing.items.push(entry);
      } else {
        groups.push({
          key,
          label: d.toLocaleString("en-US", {
            month: "long",
            year: "numeric",
            timeZone: "UTC",
          }),
          items: [entry],
        });
      }
    }
    Iif (undated.length) {
      groups.push({ key: "undated", label: "Undated", items: undated });
    }
    return groups;
  }, [timeline]);
 
  return (
    <div className="min-h-screen bg-[var(--bg)]">
      <div className="max-w-4xl mx-auto px-6 py-10">
        <PageIntro
          title="Patient Journey"
          icon={Activity}
          description="View individual FHIR R4 clinical events mapped to OMOP CDM concepts. Select a patient to see their encounters, conditions, observations, medications, and procedures in chronological order."
          prevStep={{ href: "/catalog", label: "Dataset Catalog" }}
          nextStep={{ href: "/analytics", label: "OMOP Analytics" }}
          infoText="Patient data is generated by Synthea and loaded into Neo4j as FHIR R4 resources. The OMOP CDM mapping (Layer 4) enables cross-site cohort analysis under EHDS Art. 53."
          docLink={{ href: "/docs/architecture", label: "Architecture Docs" }}
        />
 
        {unauthenticated ? (
          <SignInRequired description="The Patient Journey view is restricted to authenticated users. Sign in with one of the demo personas to explore FHIR R4 clinical timelines mapped to OMOP CDM concepts." />
        ) : (
          <>
            {/* Cohort metric orb cards — Stitch patient_dashboard_day bento */}
            {stats && (
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
                <MetricCard
                  label="Patients"
                  value={stats.patients}
                  isOrb
                  icon={<Heart size={20} className="text-white" />}
                  sub="Synthea cohort"
                />
                <MetricCard
                  label="Encounters"
                  value={stats.encounters}
                  icon={<Stethoscope size={18} />}
                />
                <MetricCard
                  label="Conditions"
                  value={stats.conditions}
                  icon={<Activity size={18} />}
                />
                <MetricCard
                  label="Observations"
                  value={stats.observations}
                  icon={<FlaskConical size={18} />}
                />
                <MetricCard
                  label="Medications"
                  value={stats.medications}
                  icon={<Pill size={18} />}
                />
                <MetricCard
                  label="Procedures"
                  value={stats.procedures}
                  icon={<Scissors size={18} />}
                />
              </div>
            )}
 
            {/* Patient selector */}
            {restricted ? (
              <div className="mb-4 px-4 py-3 bg-[var(--role-patient-bg)] border border-[var(--role-patient-border)] rounded-xl text-sm text-[var(--role-patient-text)] flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-[var(--role-patient-text)] inline-block animate-pulse" />
                Showing your personal health record (EHDS Art. 3 / GDPR Art. 15)
              </div>
            ) : (
              <div className="mb-6">
                <label className="section-label block">
                  Select patient
                  <select
                    value={selected}
                    onChange={(e) => setSelected(e.target.value)}
                    className="mt-1 px-3 py-2.5 bg-[var(--surface-card)] border border-[var(--border-ui)] rounded-xl text-sm outline-none focus:border-[var(--accent)] w-full text-[var(--text-primary)] block"
                  >
                    <option value="">
                      — select patient ({patients.length} loaded) —
                    </option>
                    {patients.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.name ?? p.id}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
            )}
 
            {/* Patient demographics header */}
            {selectedPatient && (
              <div className="surface-card p-4 mb-6 flex items-center gap-6 border border-[var(--border)]">
                <div className="metric-orb shrink-0">
                  <Users size={20} className="text-white" />
                </div>
                <div className="flex gap-6 flex-wrap text-sm">
                  <div>
                    <p className="section-label mb-0.5">Name</p>
                    <p className="font-semibold text-[var(--text-primary)]">
                      {selectedPatient.name ?? selectedPatient.id}
                    </p>
                  </div>
                  <div>
                    <p className="section-label mb-0.5">Gender</p>
                    <p className="font-semibold text-[var(--text-primary)]">
                      {selectedPatient.gender ?? "—"}
                    </p>
                  </div>
                  <div>
                    <p className="section-label mb-0.5">Born</p>
                    <p className="font-semibold text-[var(--text-primary)]">
                      {selectedPatient.birthDate ?? "—"}
                    </p>
                  </div>
                  <div>
                    <p className="section-label mb-0.5">Events</p>
                    <p className="font-semibold text-[var(--text-primary)]">
                      {timeline.length}
                    </p>
                  </div>
                </div>
              </div>
            )}
 
            {loading && (
              <p className="text-[var(--text-secondary)] text-sm">Loading…</p>
            )}
 
            {!loading && selected && timeline.length === 0 && (
              <p className="text-[var(--text-secondary)] text-sm">
                No timeline events found for this patient.
              </p>
            )}
 
            {/* Clinical timeline — grouped by year+month, newest first */}
            {timeline.length > 0 && (
              <div>
                <div className="flex items-baseline justify-between mb-4">
                  <p className="section-label">Clinical timeline</p>
                  <p className="text-xs text-[var(--text-secondary)]">
                    Newest first
                  </p>
                </div>
                {timelineGroups.map((group) => (
                  <section key={group.key} className="mb-6 last:mb-0">
                    <h3 className="text-sm font-bold text-[var(--text-primary)] mb-3 pb-1 border-b border-[var(--border)] uppercase tracking-wider">
                      {group.label}
                      <span className="ml-2 text-xs font-normal text-[var(--text-secondary)] normal-case tracking-normal">
                        {group.items.length}{" "}
                        {group.items.length === 1 ? "event" : "events"}
                      </span>
                    </h3>
                    <ol className="activity-timeline space-y-5 pl-8">
                      {group.items.map((e, i) => {
                        const token = FHIR_TYPE_TOKENS[e.fhirType];
                        return (
                          <li key={`${group.key}-${i}`} className="relative">
                            {/* Timeline dot */}
                            <span
                              className="absolute -left-[1.75rem] top-1 w-3.5 h-3.5 rounded-full border-2 border-[var(--surface-card)] z-10"
                              style={{
                                background:
                                  token?.text ?? "var(--text-secondary)",
                              }}
                            />
                            <div className="surface-card p-4 border border-[var(--border)] hover:shadow-md transition-shadow">
                              <div className="flex items-start justify-between gap-3 mb-1">
                                <div className="flex items-center gap-2">
                                  {/* FHIR type badge */}
                                  <span
                                    className="inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full"
                                    style={{
                                      color:
                                        token?.text ?? "var(--text-secondary)",
                                      background:
                                        token?.bg ?? "var(--surface-2)",
                                    }}
                                  >
                                    {token?.icon}
                                    {e.fhirType}
                                  </span>
                                  <span className="text-xs text-[var(--text-secondary)]">
                                    {e.date ?? "—"}
                                  </span>
                                </div>
                              </div>
                              <p className="text-sm font-medium text-[var(--text-primary)]">
                                {e.display || (
                                  <span className="font-mono text-xs text-[var(--text-secondary)]">
                                    {e.fhirId}
                                  </span>
                                )}
                              </p>
                              {e.omopType && (
                                <p className="text-xs text-[var(--layer4-text)] mt-1">
                                  ↳ OMOP {e.omopType}: {e.omopId}
                                </p>
                              )}
                            </div>
                          </li>
                        );
                      })}
                    </ol>
                  </section>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}