"use client"; import { useMemo } from "react"; import Link from "next/link"; import { useQuery } from "@tanstack/react-query"; import { ChevronRight, FlaskConical } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle, } from "@/components/ui/card"; import { EmptyState } from "@/components/ui/empty-state"; import { Skeleton } from "@/components/ui/skeleton"; import { apiGet } from "@/lib/api/api-fetch"; import { formatDate } from "@/lib/format"; import { formatReferenceRange } from "@/lib/labs/reference-range"; import { formatLabValue } from "@/lib/labs/format-value"; import { useTranslations } from "@/lib/i18n/context"; import { queryKeys } from "@/lib/query-keys"; import { applyOrder, useModuleListPrefs } from "@/lib/module-list-prefs"; import { LabTrendSparkline } from "./lab-trend-sparkline"; import { ReferenceRangeBadge } from "./reference-range-badge"; import type { LabResultDto, LabResultListResponse } from "./types"; interface MarkerGroup { /** Stable group key: the biomarker id, or `analyte:` for legacy rows. */ key: string; /** Link target when the group is catalog-linked; null for legacy rows. */ biomarkerId: string | null; analyte: string; panel: string | null; unit: string; readings: LabResultDto[]; latest: LabResultDto; } /** * Group readings by their linked biomarker (or, for legacy un-linked rows, * case-insensitively by analyte). A catalog-linked group deep-links to its * detail chart; legacy groups render inert until the backfill links them. */ function groupReadings(results: LabResultDto[]): MarkerGroup[] { const byKey = new Map(); for (const r of results) { const key = r.biomarkerId ? `bm:${r.biomarkerId}` : `analyte:${r.analyte.toLowerCase()}`; const bucket = byKey.get(key); if (bucket) bucket.push(r); else byKey.set(key, [r]); } const groups: MarkerGroup[] = []; for (const [key, readings] of byKey.entries()) { const ordered = [...readings].sort( (a, b) => new Date(a.takenAt).getTime() - new Date(b.takenAt).getTime(), ); const latest = ordered[ordered.length - 1]; groups.push({ key, biomarkerId: latest.biomarkerId, analyte: latest.analyte, panel: latest.panel, unit: latest.unit, readings: ordered, latest, }); } return groups.sort( (a, b) => new Date(b.latest.takenAt).getTime() - new Date(a.latest.takenAt).getTime(), ); } export function LabList({ onAddFirst }: { onAddFirst?: () => void } = {}) { const { t } = useTranslations(); const { prefs } = useModuleListPrefs("labs"); const listKey = queryKeys.labResultsList({ biomarkerId: undefined, analyte: undefined, panel: undefined, from: undefined, to: undefined, page: 0, sortDir: "desc", }); const { data, isLoading, isError } = useQuery({ queryKey: listKey, queryFn: () => apiGet("/api/labs?limit=500&sortDir=desc"), }); const groups = useMemo(() => { const base = groupReadings(data?.results ?? []); // v1.18.6 (MOD-04) — honour the user's Labs sort choice. `groupReadings` // already returns most-recent-first; `recentAsc` reverses, and `manual` // applies the persisted biomarker order (legacy un-linked groups, which // carry no biomarkerId, sort after the ordered block). if (prefs.sortDir === "recentAsc") return [...base].reverse(); if (prefs.sortDir === "manual") { return applyOrder(base, prefs.order, (g) => g.biomarkerId ?? g.key); } return base; }, [data?.results, prefs.sortDir, prefs.order]); // The list caps at 500 rows server-side (the `limit` ceiling). Surface a // calm "showing latest N of M" hint when the cap truncates so the count is // never silently wrong — proper cursor paging is a later iteration. const total = data?.meta?.total ?? 0; const shown = data?.results?.length ?? 0; const truncated = total > shown; if (isLoading) { return (
{Array.from({ length: 3 }, (_, i) => ( ))}
); } if (isError) { return (

{t("labs.loadError")}

); } if (groups.length === 0) { return ( } title={t("labs.emptyTitle")} description={t("labs.emptyDescription")} action={ onAddFirst ? ( ) : undefined } /> ); } // v1.18.6 (MOD-03) — compact list view: one bordered card holding tight // divided rows instead of a card per biomarker. The card view stays the // default; this is the denser alternative the settings toggle selects. if (prefs.view === "list") { return (
{truncated ? (

{t("labs.showingLatestOf", { shown, total })}

) : null} {groups.map((group) => { const row = (
{group.analyte}
{formatLabValue(group.latest.value)}{" "} {group.latest.unit} {formatDate(group.latest.takenAt)}
r.value)} /> {group.biomarkerId ? ( ) : null}
); return group.biomarkerId ? ( {row} ) : (
{row}
); })}
); } return (
{truncated ? (

{t("labs.showingLatestOf", { shown, total })}

) : null} {groups.map((group) => { const body = ( <> {group.analyte} {group.panel ? ( {group.panel} ) : null}
{formatLabValue(group.latest.value)} {group.latest.unit} {group.latest.referenceLow !== null || group.latest.referenceHigh !== null ? ( {t("labs.referenceLabel")}{" "} {formatReferenceRange( group.latest.referenceLow, group.latest.referenceHigh, formatLabValue, )} ) : null} {formatDate(group.latest.takenAt)} {group.readings.length > 1 ? ( {t("labs.readingsCount", { count: group.readings.length, })} ) : null}
r.value)} /> {group.biomarkerId ? ( ) : null}
); // Catalog-linked groups deep-link to the per-biomarker detail chart. // Legacy un-linked groups render as a plain card until the backfill // links them (or the user re-adds via the structured path). return group.biomarkerId ? ( {body} ) : ( {body} ); })}
); }