"use client"; /** * v1.43 — a supplement's composition on the medication detail page: what one * tablet or capsule contains, and the editor that sets it. * * The section shows the composition as the server delivered it (labels in * the account language, canonical amounts, the amount as entered beside a * converted one). The editor is a ResponsiveSheet with one row per nutrient, * built from `GET /api/nutrients/catalog`: the units offered are the code's * input units, nothing is converted here. A label photo is offered only when * the server says the `supplementLabel` capability is available; its * proposal fills the rows for the person to check, and nothing is stored * until they save. */ import { useId, useRef, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { Camera, Loader2, Pencil, Plus, Trash2 } from "lucide-react"; import { nutrientUnitLabel } from "@/components/insights/nutrients/unit-label"; import { FieldError } from "@/components/forms/field-error"; import { MedicationDetailSection } from "@/components/medications/medication-detail-section"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { NativeSelect } from "@/components/ui/native-select"; import { ResponsiveSheet } from "@/components/ui/responsive-sheet"; import { useAiRunPhase } from "@/hooks/use-ai-run"; import { useAiCapability } from "@/hooks/use-ai-capability"; import { localizedApiError } from "@/lib/api/localized-error"; import { showErrorToast } from "@/lib/errors/error-toast"; import { useFormatters, useTranslations } from "@/lib/i18n/context"; import { parseDecimalEntry } from "@/lib/measurements/entry-units"; import { readSupplementLabel, saveComposition, useNutrientCatalog, type MedicationIngredientDto, type NutrientCatalogEntryDto, type SupplementLabelProposal, } from "./use-composition"; import { EmptyState } from "@/components/ui/empty-state"; /** The categories the composition is offered for without being asked. */ export const COMPOSITION_CATEGORIES: ReadonlySet = new Set([ "VITAMIN", "SUPPLEMENT", ]); interface EditorRow { key: number; nutrient: string; amount: string; unit: string; /** From a label proposal the model was unsure of. */ check: boolean; } function formatAmount( fmt: { number: (v: number, d?: number) => string }, value: number, ): string { // Up to three decimals: 0.025 mg of a trace element must not read as 0. // Only as many as the value has, so 100 µg never reads "100.000" (which a // German reader takes for a hundred thousand). const rounded = Math.round(value * 1000) / 1000; const digits = [0, 1, 2, 3].find( (d) => Math.abs(rounded * 10 ** d - Math.round(rounded * 10 ** d)) < 1e-9, ); return fmt.number(rounded, digits ?? 3); } /** One composition line: "25 µg (1,000 IU)". */ export function IngredientAmount({ ingredient, }: { ingredient: MedicationIngredientDto; }) { const { t } = useTranslations(); const fmt = useFormatters(); return ( {formatAmount(fmt, ingredient.amountPerUnit)}{" "} {nutrientUnitLabel(ingredient.unit, t)} {ingredient.enteredAmount !== null && ingredient.enteredUnit !== null && ( {" ("} {formatAmount(fmt, ingredient.enteredAmount)}{" "} {nutrientUnitLabel(ingredient.enteredUnit, t)} {")"} )} ); } function rowsFromIngredients( ingredients: ReadonlyArray, ): EditorRow[] { return ingredients.map((ingredient, index) => ({ key: index, nutrient: ingredient.nutrient, amount: String(ingredient.enteredAmount ?? ingredient.amountPerUnit), unit: ingredient.enteredUnit ?? ingredient.unit, check: false, })); } function CompositionEditor({ medicationId, ingredients, open, onOpenChange, labelReadable, }: { medicationId: string; ingredients: ReadonlyArray; open: boolean; onOpenChange: (open: boolean) => void; labelReadable: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const formId = useId(); const catalog = useNutrientCatalog(open); const entries = (catalog.data?.entries ?? []).filter((e) => e.ingredient); const byCode = new Map(entries.map((entry) => [entry.code, entry])); const [rows, setRows] = useState(() => rowsFromIngredients(ingredients), ); const [nextKey, setNextKey] = useState(ingredients.length); const [source, setSource] = useState<"MANUAL" | "LABEL_AI">("MANUAL"); const [proposal, setProposal] = useState( null, ); const [error, setError] = useState(null); const [saving, setSaving] = useState(false); const [reading, setReading] = useState(false); const fileInput = useRef(null); const runPhase = useAiRunPhase(); const chosen = new Set(rows.map((row) => row.nutrient).filter(Boolean)); function update(key: number, patch: Partial) { setRows((current) => current.map((row) => (row.key === key ? { ...row, ...patch } : row)), ); } function addRow() { setRows((current) => [ ...current, { key: nextKey, nutrient: "", amount: "", unit: "", check: false }, ]); setNextKey((key) => key + 1); } function chooseNutrient(key: number, code: string) { const entry = byCode.get(code); update(key, { nutrient: code, unit: entry?.unit ?? "", check: false }); } async function readLabel(file: File) { setReading(true); setError(null); try { const read = await readSupplementLabel(queryClient, medicationId, file, { onQueued: runPhase.onQueued, onProgress: runPhase.onProgress, }); setProposal(read); setSource("LABEL_AI"); setRows( read.ingredients.map((line, index) => ({ key: nextKey + index, nutrient: line.nutrient, amount: String(line.amount), unit: line.unit, check: line.confidence === "low", })), ); setNextKey((key) => key + read.ingredients.length); } catch (err) { showErrorToast( localizedApiError(err, t, "medications.composition.labelError"), { cause: err }, ); } finally { setReading(false); runPhase.reset(); } } async function save() { if (saving) return; const parsed = rows.map((row) => ({ nutrient: row.nutrient, amount: parseDecimalEntry(row.amount), unit: row.unit, })); if ( parsed.some( (row) => !row.nutrient || !row.unit || !(row.amount && row.amount > 0), ) ) { setError(t("medications.composition.invalidRow")); return; } setSaving(true); setError(null); try { await saveComposition( queryClient, medicationId, parsed.map((row) => ({ nutrient: row.nutrient, amount: row.amount as number, unit: row.unit, })), source, ); onOpenChange(false); } catch (err) { setError(localizedApiError(err, t, "medications.composition.saveError")); } finally { setSaving(false); } } const busy = saving || reading; return ( } >
{labelReadable && (
{ const file = event.target.files?.[0]; event.target.value = ""; if (file) void readLabel(file); }} /> {reading && runPhase.phase === "waitingForWorker" && (

{t("medications.composition.labelWaiting")}

)}
)} {proposal && (

{t("medications.composition.labelReviewNote")}

{proposal.servingNote && (

{t("medications.composition.servingNote", { note: proposal.servingNote, })}

)} {proposal.unmatched.length > 0 && (

{t("medications.composition.unmatchedTitle")}

    {proposal.unmatched.map((line, index) => (
  • {line.printedText}
  • ))}
)}
)} {rows.length === 0 && (

{t("medications.composition.editorEmpty")}

)}
    {rows.map((row) => { const entry = byCode.get(row.nutrient); const name = entry?.label ?? row.nutrient; return (
  • chooseNutrient(row.key, event.target.value) } disabled={busy} > {entries.map((option: NutrientCatalogEntryDto) => ( ))}
    update(row.key, { amount: event.target.value, check: false, }) } aria-invalid={row.check || undefined} disabled={busy} />
    update(row.key, { unit: event.target.value }) } disabled={busy || !entry} > {(entry?.inputUnits ?? []).map((option) => ( ))}
    {row.check && (

    {t("medications.composition.lowConfidence")}

    )}
  • ); })}
); } /** * The composition section on the Übersicht tab. Rendered for a vitamin or a * supplement, and for any medication that already has a composition. */ export function CompositionSection({ medicationId, ingredients, canEdit, ownRecord, }: { medicationId: string; ingredients: ReadonlyArray; canEdit: boolean; /** Reading a label is provider work, never offered inside another record. */ ownRecord: boolean; }) { const { t } = useTranslations(); const [open, setOpen] = useState(false); const labelCapability = useAiCapability("supplementLabel"); return ( setOpen(true)} data-slot="medication-composition-edit" > {ingredients.length > 0 ? ( ); } /** * The same editor for any other medication, as a row in the Erweitert tab's * lifecycle group: the composition is possible for every medication and * offered up front only for vitamins and supplements. */ export function CompositionRow({ medicationId, ownRecord, }: { medicationId: string; ownRecord: boolean; }) { const { t } = useTranslations(); const [open, setOpen] = useState(false); const labelCapability = useAiCapability("supplementLabel"); return (

{t("medications.composition.title")}

{t("medications.composition.rowHelper")}

{open && ( )}
); }