"use client"; /** * Review-then-confirm for a document's staged facts, ON the document detail — * the UI leg of a server chain that already existed end to end (extract → * PENDING `ExtractedFact` → per-fact edit → confirm) but had no control on * this surface: the sheet counted observation facts and offered nothing, so a * skipped automatic run forced a re-upload through Labs → Scan a report. * * Three honest states, all docked onto the existing sheet (no new menu item): * * - PENDING facts exist → "Review extracted values (N)" opens the inline * review: approve/reject per fact, a low-confidence fact is checked and * saved first (the existing per-fact edit, which clears `needsReview`). * - No facts yet, but the document is filed as a lab result and has stored * extracted text → "Extract lab values" runs the SAME text-structuring * pass the automatic worker uses ({ mode: "stored" }) — reusing the * stored text, never asking for a re-upload — and opens the review. * - Neither → nothing renders; the surface stays calm. * * HARD RULE: nothing here writes into Labs / conditions / medications on its * own. The confirm mutation carries the person's explicit decisions and the * server's confirm route remains the only write path. Unchecked values are * rejected (stated in the copy); an unverified low-confidence fact gets NO * decision and stays pending rather than being silently discarded. */ import { useCalendarDate } from "@/hooks/use-calendar-date"; import { useState } from "react"; import { FlaskConical, Loader2, ScanSearch } from "lucide-react"; import { toast } from "sonner"; import { toastWrittenOutcome } from "@/components/outcome/outcome-toast"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DateField } from "@/components/ui/date-field"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTranslations } from "@/lib/i18n/context"; import { cn } from "@/lib/utils"; import type { ConditionFactData, ExtractedFactDto, InboundDocumentDetailDto, InboundFactEdit, MedicationStatementFactData, ObservationFactData, } from "@/lib/validations/inbound-documents"; import { AiRunPhaseNote } from "./document-ai-panels"; import { useDocumentAiErrorText } from "./use-document-assist"; import { useConfirmFacts, useEditFact, useStoredExtract, } from "./use-document-facts"; /** Map a per-fact commit refusal to its translated sentence. */ function commitFailureKey(reason: string): string { switch (reason) { case "observation.unitRequired": return "documents.review.failUnitRequired"; case "observation.unitMismatch": return "documents.review.failUnitMismatch"; default: return "documents.review.failGeneric"; } } /** The headline line of a fact (what the document stated). */ function factHeadline(fact: ExtractedFactDto): string { if (fact.factType === "OBSERVATION") { const data = fact.data as ObservationFactData; const value = typeof data.value === "number" ? `${data.value}${data.unit ? ` ${data.unit}` : ""}` : (data.valueText ?? ""); return value ? `${data.label}: ${value}` : data.label; } if (fact.factType === "CONDITION") { return (fact.data as ConditionFactData).label; } const data = fact.data as MedicationStatementFactData; return data.dose ? `${data.name} ${data.dose}` : data.name; } /** The date the fact states, if any (YYYY-MM-DD). */ function factDate(fact: ExtractedFactDto): string | null { if (fact.factType === "OBSERVATION") { return (fact.data as ObservationFactData).effectiveDate; } if (fact.factType === "CONDITION") { return (fact.data as ConditionFactData).onsetDate; } return (fact.data as MedicationStatementFactData).effectiveDate; } /** Build the full edit payload for a fact from its data + the form draft. */ function buildEdit( fact: ExtractedFactDto, draft: VerifyDraft, ): InboundFactEdit | null { if (fact.factType === "OBSERVATION") { const data = fact.data as ObservationFactData; const label = draft.label.trim(); if (!label) return null; const numeric = draft.value.trim(); const qualitative = draft.valueText.trim(); // Numeric XOR qualitative, mirroring the server schema. if (numeric && qualitative) return null; const value = numeric ? Number(numeric.replace(",", ".")) : null; if (numeric && !Number.isFinite(value)) return null; return { factType: "OBSERVATION", label, code: data.code, codeSystem: data.codeSystem, value, valueText: qualitative || null, unit: draft.unit.trim() || null, referenceLow: data.referenceLow, referenceHigh: data.referenceHigh, referenceText: data.referenceText ?? null, effectiveDate: draft.date || null, }; } if (fact.factType === "CONDITION") { const data = fact.data as ConditionFactData; const label = draft.label.trim(); if (!label) return null; return { factType: "CONDITION", label, code: data.code, codeSystem: data.codeSystem, clinicalStatus: data.clinicalStatus, verificationStatus: data.verificationStatus, onsetDate: draft.date || null, }; } const data = fact.data as MedicationStatementFactData; const name = draft.label.trim(); if (!name) return null; return { factType: "MEDICATION_STATEMENT", name, dose: draft.unit.trim() || null, rxNormCode: data.rxNormCode, atcCode: data.atcCode, statusStated: data.statusStated, effectiveDate: draft.date || null, }; } interface VerifyDraft { /** Observation/condition label, or the medication name. */ label: string; /** Observation numeric value as typed; unused for the other types. */ value: string; /** Observation qualitative result; unused for the other types. */ valueText: string; /** Observation unit, or the medication dose. */ unit: string; /** Effective/onset date (YYYY-MM-DD) or "". */ date: string; } function draftFor(fact: ExtractedFactDto): VerifyDraft { if (fact.factType === "OBSERVATION") { const data = fact.data as ObservationFactData; return { label: data.label, value: typeof data.value === "number" ? String(data.value) : "", valueText: data.valueText ?? "", unit: data.unit ?? "", date: data.effectiveDate ?? "", }; } if (fact.factType === "CONDITION") { const data = fact.data as ConditionFactData; return { label: data.label, value: "", valueText: "", unit: "", date: data.onsetDate ?? "", }; } const data = fact.data as MedicationStatementFactData; return { label: data.name, value: "", valueText: "", unit: data.dose ?? "", date: data.effectiveDate ?? "", }; } /** One pending fact: include-toggle, stated values, verify-first when low-confidence. */ function FactRow({ documentId, fact, checked, onCheckedChange, failure, }: { documentId: string; fact: ExtractedFactDto; checked: boolean; onCheckedChange: (checked: boolean) => void; /** A per-fact commit refusal from the last confirm attempt, or null. */ failure: string | null; }) { const { t } = useTranslations(); const calendarDate = useCalendarDate(); const editFact = useEditFact(); const [verifying, setVerifying] = useState(false); const [draft, setDraft] = useState(() => draftFor(fact)); const [draftInvalid, setDraftInvalid] = useState(false); const date = factDate(fact); const typeLabel = t(`documents.review.type.${fact.factType}`); const isObservation = fact.factType === "OBSERVATION"; const saveVerification = () => { const edit = buildEdit(fact, draft); if (!edit) { setDraftInvalid(true); return; } setDraftInvalid(false); editFact.mutate( { documentId, factId: fact.id, edit }, { onSuccess: () => { setVerifying(false); // The refetched fact arrives with needsReview cleared; include it — // the person just asserted these values. onCheckedChange(true); }, }, ); }; return (
  • onCheckedChange(state === true)} disabled={fact.needsReview} aria-label={t("documents.review.includeAria", { value: factHeadline(fact), })} className="mt-0.5" />

    {factHeadline(fact)}

    {typeLabel} {date ? `, ${calendarDate(date)}` : ""}

    {isObservation && (fact.data as ObservationFactData).referenceText ? (

    {t("documents.review.statedRange", { range: (fact.data as ObservationFactData) .referenceText as string, })}

    ) : null} {fact.provenance.anchored && fact.provenance.sourceText ? (

    “{fact.provenance.sourceText}”

    ) : null} {failure ? (

    {t(commitFailureKey(failure))}

    ) : null}
    {fact.needsReview && !verifying ? ( ) : null}
    {fact.needsReview && !verifying ? (

    {t("documents.review.needsCheck")}

    ) : null} {verifying ? (
    setDraft((d) => ({ ...d, label: e.target.value })) } maxLength={fact.factType === "MEDICATION_STATEMENT" ? 200 : 300} />
    setDraft((d) => ({ ...d, date: value }))} aria-label={t("documents.review.fieldDate")} />
    {isObservation ? ( <>
    setDraft((d) => ({ ...d, value: e.target.value, // Numeric XOR qualitative — typing a number clears text. valueText: e.target.value ? "" : d.valueText, })) } />
    setDraft((d) => ({ ...d, valueText: e.target.value, value: e.target.value ? "" : d.value, })) } maxLength={300} />
    ) : null} {isObservation || fact.factType === "MEDICATION_STATEMENT" ? (
    setDraft((d) => ({ ...d, unit: e.target.value })) } maxLength={isObservation ? 80 : 120} />
    ) : null}
    {draftInvalid ? (

    {t("documents.review.verifyInvalid")}

    ) : null} {editFact.isError ? (

    {t("documents.review.verifyFailed")}

    ) : null}
    ) : null}
  • ); } /** * The staged-facts block of the document detail. Renders the review (pending * facts), the stored-text extract action (lab document, nothing staged yet), * or nothing. Owner-only: staging and confirming write to the caller's own * record, so a delegate never sees these controls. */ export function DocumentFactsSection({ doc, canManage, aiEnabled, labsModuleEnabled, }: { doc: InboundDocumentDetailDto; canManage: boolean; aiEnabled: boolean; labsModuleEnabled: boolean; }) { const { t, tCount } = useTranslations(); const storedExtract = useStoredExtract(); const confirmFacts = useConfirmFacts(); const aiErrorText = useDocumentAiErrorText(); const [open, setOpen] = useState(false); // Approve-set as explicit state, seeded per fact on first sight: a // confident fact starts included, a low-confidence one starts excluded // until it is verified (which checks it). const [included, setIncluded] = useState>({}); const [failures, setFailures] = useState>({}); const pending = doc.facts.filter((fact) => fact.status === "PENDING"); const approvedCount = doc.facts.filter( (fact) => fact.status === "APPROVED", ).length; if (!canManage) return null; const isChecked = (fact: ExtractedFactDto): boolean => included[fact.id] ?? !fact.needsReview; const setChecked = (factId: string, checked: boolean) => setIncluded((prev) => ({ ...prev, [factId]: checked })); const finishReview = () => { // A still-unverified low-confidence fact gets NO decision — it stays // pending instead of being silently discarded. const decidable = pending.filter((fact) => !fact.needsReview); if (decidable.length === 0) return; const decisions = decidable.map((fact) => ({ factId: fact.id, action: isChecked(fact) ? ("approve" as const) : ("reject" as const), })); confirmFacts.mutate( { documentId: doc.id, decisions }, { onSuccess: (result) => { setFailures( Object.fromEntries( result.failed.map((entry) => [entry.factId, entry.reason]), ), ); // The outcome module owns the affordance: green only for a run // that actually wrote, neutral for an all-rejected review (an // honest non-event), a warning when some values were refused. if (result.approved.length > 0) { toastWrittenOutcome( result.failed.length > 0 ? "partial" : "success", tCount("documents.review.savedToast", result.approved.length), ); } else if (result.failed.length === 0) { toastWrittenOutcome( "empty", t("documents.review.nothingSavedToast"), ); } if (result.failed.length === 0) setOpen(false); }, }, ); }; // The stored-text extract offer: a lab-filed, already-read document with // nothing staged and nothing confirmed yet. `alreadyPartlyConfirmed` is the // server's refusal once anything is APPROVED, so the offer withdraws then. const canExtract = labsModuleEnabled && aiEnabled && doc.kind === "LAB_RESULT" && doc.hasContentIndex && doc.status !== "CONFIRMED" && pending.length === 0 && approvedCount === 0; if (pending.length === 0 && !canExtract) return null; const unverified = pending.filter((fact) => fact.needsReview).length; return (
    {pending.length > 0 ? ( <> {!open ? ( ) : (

    {t("documents.review.title")}

    {t("documents.review.hint")}

      {pending.map((fact) => ( setChecked(fact.id, checked)} failure={failures[fact.id] ?? null} /> ))}
    {unverified > 0 ? (

    {tCount("documents.review.unverifiedNote", unverified)}

    ) : null} {confirmFacts.isError ? (

    {t("documents.review.confirmFailed")}

    ) : null}
    )} ) : (
    {storedExtract.runPhase === "idle" ? (

    {t("documents.review.extractHint")}

    ) : ( // While the read runs, the hint gives way to where it stands: // one muted line, the same one every document read shows. )}
    )}
    ); }