All files / src/app/analytics page.tsx

94.59% Statements 35/37
85.1% Branches 40/47
92.3% Functions 12/13
97.14% Lines 34/35

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 3481x                                                                                   1x         1x 1x             1x                                     4x 4x 4x                                                                     44x 44x 44x 44x                         8x                             11x 11x 11x 11x 11x   11x 5x   3x 2x     2x 2x     1x 1x       11x   11x                                                                             11x                                                                                                                 66x                                               4x 8x     4x 4x                                                                                                                
"use client";
 
import { fetchApi } from "@/lib/api";
import { useEffect, useState } from "react";
import {
  Activity,
  Pill,
  FlaskConical,
  Users,
  Calendar,
  BarChart2,
  Scissors,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import { useT } from "@/lib/i18n/translate";
 
interface AnalyticsData {
  summary: {
    persons: number;
    conditions: number;
    drugs: number;
    measurements: number;
    procedures: number;
    visits: number;
  };
  topConditions: { label: string; count: number }[];
  topDrugs: { label: string; count: number }[];
  topMeasurements: { label: string; count: number }[];
  topProcedures: { label: string; count: number }[];
  genderBreakdown: { gender: string; count: number }[];
  /** The data permit a data user's analysis ran under (Art. 68); null for exempt roles. */
  permit?: {
    permitId: string | null;
    datasetId: string | null;
    purpose: string | null;
    validUntil: string | null;
    article: string;
  } | null;
}
 
/** The message of a refusal at the permit gate, or the plain status. */
async function describeFailure(r: Response): Promise<string> {
  const body = (await r.json().catch(() => null)) as {
    error?: string;
    reason?: string;
    article?: string;
  } | null;
  Eif (body?.error && body.reason) {
    return `${body.error}. ${body.reason}${
      body.article ? ` (${body.article})` : ""
    }`;
  }
  return body?.error ?? `HTTP ${r.status}`;
}
 
const LAYER_COLORS = {
  condition: "bg-layer3",
  drug: "bg-layer4",
  measurement: "bg-layer5",
  procedure: "bg-layer1",
  neutral: "bg-layer2",
};
 
function HorizontalBar({
  label,
  count,
  maxCount,
  colorClass,
}: {
  label: string;
  count: number;
  maxCount: number;
  colorClass: string;
}) {
  const pct = maxCount > 0 ? Math.round((count / maxCount) * 100) : 0;
  const shortLabel = label.length > 55 ? label.slice(0, 52) + "…" : label;
  return (
    <div className="flex items-center gap-3 py-1">
      <span
        className="text-xs text-(--text-secondary) text-right shrink-0"
        style={{ width: "260px", minWidth: "260px" }}
        title={label}
      >
        {shortLabel}
      </span>
      <div className="flex-1 bg-(--surface-2) rounded-full h-4 overflow-hidden">
        <div
          className={`${colorClass} h-4 rounded-full transition-all`}
          style={{ width: `${pct}%` }}
        />
      </div>
      <span className="text-xs text-(--text-primary) shrink-0 w-12 text-right">
        {count.toLocaleString()}
      </span>
    </div>
  );
}
 
function BarSection({
  title,
  icon: Icon,
  data,
  colorClass,
  loading,
}: {
  title: string;
  icon: React.ElementType;
  data: { label: string; count: number }[];
  colorClass: string;
  loading: boolean;
}) {
  const t = useT("research");
  const tc = useT("common");
  const maxCount = data[0]?.count ?? 1;
  return (
    <section className="bg-(--surface) border border-(--border) rounded-xl p-5">
      <div className="flex items-center gap-2 mb-4">
        <Icon size={16} className="text-(--text-secondary)" />
        <h2 className="font-semibold text-sm text-(--text-primary)">{title}</h2>
      </div>
      {loading ? (
        <div className="text-(--text-secondary) text-xs">{tc("Loading…")}</div>
      ) : data.length === 0 ? (
        <div className="text-(--text-secondary) text-xs">{t("No data")}</div>
      ) : (
        <div className="flex flex-col gap-1">
          {data.map((d, i) => (
            <HorizontalBar
              key={i}
              label={d.label}
              count={d.count}
              maxCount={maxCount}
              colorClass={colorClass}
            />
          ))}
        </div>
      )}
    </section>
  );
}
 
export default function AnalyticsPage() {
  const t = useT("research");
  const tn = useT("nav");
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    fetchApi("/api/analytics")
      .then(async (r) => {
        if (!r.ok) throw new Error(await describeFailure(r));
        return r.json();
      })
      .then((d) => {
        setData(d);
        setLoading(false);
      })
      .catch((e) => {
        setError(e.message);
        setLoading(false);
      });
  }, []);
 
  const summary = data?.summary;
 
  const statCards = [
    {
      label: t("Patients"),
      value: summary?.persons,
      icon: Users,
      color: "text-blue-800 dark:text-blue-300",
    },
    {
      label: t("Conditions"),
      value: summary?.conditions,
      icon: Activity,
      color: "text-green-800 dark:text-green-300",
    },
    {
      label: t("Drug Exposures"),
      value: summary?.drugs,
      icon: Pill,
      color: "text-amber-800 dark:text-amber-300",
    },
    {
      label: t("Procedures"),
      value: summary?.procedures,
      icon: Scissors,
      color: "text-blue-800 dark:text-blue-300",
    },
    {
      label: t("Measurements"),
      value: summary?.measurements,
      icon: FlaskConical,
      color: "text-purple-800 dark:text-purple-300",
    },
    {
      label: t("Visits"),
      value: summary?.visits,
      icon: Calendar,
      color: "text-teal-800 dark:text-teal-300",
    },
  ];
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="max-w-5xl mx-auto px-6 py-10">
        <PageIntro
          title={t("OMOP Research Analytics")}
          icon={BarChart2}
          description={t(
            "Layer 4: OMOP CDM cohort statistics from the Synthea-generated dataset, supporting EHDS Art. 53 secondary-use research. View aggregate counts for persons, conditions, drugs, measurements, and procedures.",
          )}
          prevStep={{ href: "/patient", label: tn("Patient Journey") }}
          nextStep={{ href: "/query", label: t("Natural Language Query") }}
          infoText={t(
            "Analytics are computed from OMOP CDM nodes in Neo4j. The OMOP Common Data Model standardises clinical data across institutions, enabling federated cohort analysis without moving patient-level data.",
          )}
          docLink={{
            href: "https://ohdsi.github.io/CommonDataModel/",
            label: t("OMOP CDM Documentation"),
            external: true,
          }}
        />
 
        {error && (
          <div
            className="mb-6 p-3 rounded-sm bg-(--role-admin-bg) border border-(--role-admin-border) text-(--role-admin-text) text-sm"
            data-testid="analytics-error"
          >
            {error}
          </div>
        )}
 
        {data?.permit && (
          <div
            className="mb-6 p-3 rounded-sm bg-(--surface) border border-(--border) text-xs text-(--text-secondary)"
            data-testid="analytics-permit"
          >
            {t("Under data permit")}{" "}
            <span className="font-mono text-(--text-primary)">
              {data.permit.permitId}
            </span>
            {data.permit.datasetId && (
              <> {t("for {dataset}", { dataset: data.permit.datasetId })}</>
            )}
            {data.permit.validUntil && (
              <>
                ,{" "}
                {t("valid until {date}", {
                  date: data.permit.validUntil.slice(0, 10),
                })}
              </>
            )}{" "}
            ({data.permit.article})
          </div>
        )}
 
        {/* Stat cards */}
        <div className="grid grid-cols-3 sm:grid-cols-6 gap-3 mb-8">
          {statCards.map(({ label, value, icon: Icon, color }) => (
            <div
              key={label}
              className="bg-(--surface) border border-(--border) rounded-xl p-4 flex flex-col gap-1"
            >
              <Icon size={16} className={color} />
              <span className="text-2xl font-bold">
                {loading ? "—" : (value ?? 0).toLocaleString()}
              </span>
              <span className="text-xs text-(--text-secondary)">{label}</span>
            </div>
          ))}
        </div>
 
        {/* Gender breakdown */}
        {!loading && data?.genderBreakdown && (
          <div className="mb-8 bg-(--surface) border border-(--border) rounded-xl p-5">
            <div className="flex items-center gap-2 mb-3">
              <Users size={16} className="text-(--text-secondary)" />
              <h2 className="font-semibold text-sm text-(--text-primary)">
                {t("Gender Distribution")}
              </h2>
            </div>
            <div className="flex gap-6">
              {data.genderBreakdown.map((g) => {
                const total = data.genderBreakdown.reduce(
                  (s, x) => s + x.count,
                  0,
                );
                const pct = total > 0 ? Math.round((g.count / total) * 100) : 0;
                return (
                  <div
                    key={g.gender}
                    className="flex items-center gap-2 text-sm"
                  >
                    <span
                      className={`inline-block w-3 h-3 rounded-full ${
                        g.gender === "Female" ? "bg-layer3" : "bg-layer4"
                      }`}
                    />
                    <span className="text-(--text-primary)">{t(g.gender)}</span>
                    <span className="text-(--text-secondary)">
                      {g.count.toLocaleString()} ({pct}%)
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
 
        {/* Bar chart sections */}
        <div className="flex flex-col gap-6">
          <BarSection
            title={t("Top Conditions (OMOPConditionOccurrence)")}
            icon={Activity}
            data={data?.topConditions ?? []}
            colorClass={LAYER_COLORS.condition}
            loading={loading}
          />
          <BarSection
            title={t("Top Drug Exposures (OMOPDrugExposure)")}
            icon={Pill}
            data={data?.topDrugs ?? []}
            colorClass={LAYER_COLORS.drug}
            loading={loading}
          />
          <BarSection
            title={t("Top Measurements (OMOPMeasurement)")}
            icon={FlaskConical}
            data={data?.topMeasurements ?? []}
            colorClass={LAYER_COLORS.measurement}
            loading={loading}
          />
          <BarSection
            title={t("Top Procedures (OMOPProcedureOccurrence)")}
            icon={Scissors}
            data={data?.topProcedures ?? []}
            colorClass={LAYER_COLORS.procedure}
            loading={loading}
          />
        </div>
      </div>
    </div>
  );
}