feat(medications): research-mode MDR acknowledgment dialog

Opt-in modal that gates the GLP-1 drug-level chart behind an MDR-aware
disclaimer. Reads the live disclaimer version from the server and posts
it back on acknowledge so a server-side bump forces re-acknowledgment.
Sections cover what the chart is, what it isn't, why population PK is
an estimate, the EU 2017/745 + MDCG 2021-24 boundary, and EMA + ASCPT
psp4.13099 citations. Stale-version 400 surfaces a localised error
toast and keeps the dialog open.
This commit is contained in:
Marc-André Bombeck committed 2026-05-14 20:19:25 +02:00
1 parent 6d748de389
commit 3502f57694
8 files changed
+694

No files matched your search

+22
View File
@@ -717,6 +717,28 @@
"ema": "EMA-Quelle",
"psp4": "Peer-Reviewed Pharmakometrik"
}
},
"researchMode": {
"dialog": {
"title": "Forschungsmodus aktivieren",
"intro": "Der Forschungsmodus ergänzt deine GLP-1-Medikamentenseite um eine geschätzte Wirkstoff-Verlaufskurve. Lies die Abgrenzung unten, bevor du den Modus einschaltest — die Kurve ist eine Lernhilfe, niemals eine Messung und nie ein medizinischer Rat.",
"whatItIsHeader": "Was das ist",
"whatItIs": "Eine Sägezahnkurve, die die Überlagerung deiner protokollierten Dosen über die Zeit simuliert. Grundlage ist das Ein-Kompartment-Modell nach Bateman mit Absorptions- und Halbwertszeit-Parametern aus den EMA-EPARs der zugelassenen GLP-1-Rezeptoragonisten. Die Y-Achse ist einheitenlos und ohne Beschriftung. Die Form, nicht der Zahlenwert, ist die Aussage der Kurve.",
"whatItIsntHeader": "Was das nicht ist",
"whatItIsnt": "Kein Blutspiegel. Keine Messung. Keine Vorhersage, wie dein Körper tatsächlich reagiert. Keine Grundlage für Dosierungs-, Zeitpunkt- oder Eskalationsentscheidungen. Für alles, was deine Therapie betrifft, sprich mit deiner verschreibenden Ärztin oder deinem Arzt.",
"whyEstimateHeader": "Warum es eine Schätzung ist",
"whyEstimate": "Populations-Pharmakokinetik beschreibt den typischen Patienten. Die individuelle Streuung ist groß — das Tirzepatid-Modell Schneck/Urva 2024 weist rund 22 % interindividuelle Variabilität bei der Absorption und rund 49 % beim Verteilungsvolumen aus. Eine Lehrbuchkurve kann weder dein Gewicht, deine Nierenfunktion, deine Injektionstechnik noch deine Zeitgenauigkeit abbilden. Lies die Kurve als Rhythmus deiner Dosierung, nicht als deinen Spiegel.",
"mdrBoundaryHeader": "Regulatorische Abgrenzung",
"mdrBoundary": "HealthLog stellt öffentliche regulatorische Daten und deine eigenen Einträge dar. Die App stellt keine Prognose, Diagnose, Behandlung oder Therapieempfehlung. Die EU-Verordnung 2017/745 (Medical Device Regulation, MDR) und das Leitfadenpapier MDCG 2021-24 ziehen die Grenze bei Software, die Daten für medizinische Zwecke interpretiert — diese Kurve bleibt klar auf der edukativen Seite dieser Linie. Wenn du das Gefühl hast, die Kurve dränge dich zu einer klinischen Entscheidung, schließe sie.",
"citationsHeader": "Quellen",
"citations": "EMA European Public Assessment Reports für Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta und Bydureon (Abschnitt 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Disclaimer-Version: {version}",
"acknowledgeCta": "Verstanden — aktivieren",
"cancelCta": "Abbrechen",
"successToast": "Forschungsmodus aktiviert. Die Wirkstoff-Verlaufskurve ist jetzt auf deiner GLP-1-Medikamentenseite sichtbar.",
"errorToast": "Forschungsmodus konnte nicht aktiviert werden. Bitte erneut versuchen.",
"staleVersionToast": "Der Disclaimer wurde aktualisiert, seit diese Seite geladen wurde. Lade die Seite neu, um die aktuelle Fassung zu lesen."
}
}
},
"charts": {
+22
View File
@@ -717,6 +717,28 @@
"ema": "EMA source",
"psp4": "Peer-reviewed pharmacometrics"
}
},
"researchMode": {
"dialog": {
"title": "Enable Research Mode",
"intro": "Research Mode adds an estimated drug-level chart to your GLP-1 medication page. Read the boundary below before turning it on — the chart is a learning aid, never a measurement, never medical advice.",
"whatItIsHeader": "What this is",
"whatItIs": "A sawtooth curve simulating how your logged doses superimpose over time, using the one-compartment Bateman model with absorption and half-life parameters published in the EMA EPAR for each approved GLP-1 receptor agonist. The vertical axis is unit-less and unlabeled. The shape, not the number, is what the chart shows.",
"whatItIsntHeader": "What this isn't",
"whatItIsnt": "Not a blood level. Not a measurement. Not a forecast of how your body actually responds. Not a basis for any dose, timing, or escalation decision. Talk to your prescribing clinician for anything that affects how you take your medication.",
"whyEstimateHeader": "Why it's an estimate",
"whyEstimate": "Population pharmacokinetics describe the typical patient. Individual variation is large — tirzepatide's Schneck/Urva 2024 model reports ~22% inter-individual variability on absorption and ~49% on volume of distribution. A textbook curve cannot capture your weight, kidney function, injection technique, or timing accuracy. Read the curve as the rhythm of dosing, not as your level.",
"mdrBoundaryHeader": "Regulatory boundary",
"mdrBoundary": "HealthLog displays public regulatory data and your own log entries. It does not predict, diagnose, treat, or recommend any therapy. EU Regulation 2017/745 (the Medical Device Regulation, MDR) and guidance document MDCG 2021-24 draw the line at software that interprets data for medical purposes — this chart stays decisively on the educational side of that line. If you ever feel it's nudging you toward a clinical decision, close it.",
"citationsHeader": "Sources",
"citations": "EMA European Public Assessment Reports for Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta, and Bydureon (Section 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Disclaimer version: {version}",
"acknowledgeCta": "I understand — enable",
"cancelCta": "Cancel",
"successToast": "Research Mode enabled. The drug-level chart is now visible on your GLP-1 medication page.",
"errorToast": "Could not enable Research Mode. Please try again.",
"staleVersionToast": "The disclaimer was updated since this page loaded. Reload to read the current version."
}
}
},
"charts": {
+22
View File
@@ -717,6 +717,28 @@
"ema": "Fuente EMA",
"psp4": "Farmacometría revisada por pares"
}
},
"researchMode": {
"dialog": {
"title": "Activar el modo Investigación",
"intro": "El modo Investigación añade un gráfico estimado del nivel de fármaco a tu página de GLP-1. Lee el límite a continuación antes de activarlo: el gráfico es una ayuda de aprendizaje, nunca una medición, nunca un consejo médico.",
"whatItIsHeader": "Qué es esto",
"whatItIs": "Una curva en diente de sierra que simula la superposición de tus dosis registradas a lo largo del tiempo, usando el modelo de Bateman de un compartimento con los parámetros de absorción y semivida publicados en el EPAR de la EMA de cada agonista GLP-1 aprobado. El eje vertical es adimensional y sin etiquetas. La forma, no el número, es lo que muestra el gráfico.",
"whatItIsntHeader": "Qué no es",
"whatItIsnt": "No es un nivel en sangre. No es una medición. No es una predicción de cómo responde realmente tu cuerpo. No es base para ninguna decisión de dosis, tiempo o escalado. Para cualquier cosa que afecte cómo tomas tu medicación, habla con tu médico prescriptor.",
"whyEstimateHeader": "Por qué es una estimación",
"whyEstimate": "La farmacocinética poblacional describe al paciente típico. La variación individual es grande: el modelo Schneck/Urva 2024 de tirzepatida reporta aproximadamente un 22 % de variabilidad interindividual en la absorción y aproximadamente un 49 % en el volumen de distribución. Una curva de manual no puede capturar tu peso, tu función renal, tu técnica de inyección ni la precisión de tus horarios. Lee la curva como el ritmo de tu dosificación, no como tu nivel.",
"mdrBoundaryHeader": "Límite regulatorio",
"mdrBoundary": "HealthLog muestra datos regulatorios públicos y tus propios registros. La aplicación no predice, no diagnostica, no trata y no recomienda ninguna terapia. El Reglamento UE 2017/745 (Medical Device Regulation, MDR) y el documento de orientación MDCG 2021-24 trazan la línea con el software que interpreta datos con fines médicos: este gráfico se queda decididamente del lado educativo de esa línea. Si en algún momento sientes que te empuja hacia una decisión clínica, ciérralo.",
"citationsHeader": "Fuentes",
"citations": "European Public Assessment Reports de la EMA para Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta y Bydureon (Sección 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Versión del disclaimer: {version}",
"acknowledgeCta": "Entiendo — activar",
"cancelCta": "Cancelar",
"successToast": "Modo Investigación activado. La curva de nivel de fármaco es ahora visible en tu página de GLP-1.",
"errorToast": "No se pudo activar el modo Investigación. Inténtalo de nuevo.",
"staleVersionToast": "El disclaimer se actualizó desde que cargó esta página. Recarga para leer la versión actual."
}
}
},
"charts": {
+22
View File
@@ -717,6 +717,28 @@
"ema": "Source EMA",
"psp4": "Pharmacométrie évaluée par les pairs"
}
},
"researchMode": {
"dialog": {
"title": "Activer le mode Recherche",
"intro": "Le mode Recherche ajoute un graphique estimé du niveau de médicament à votre page GLP-1. Lisez la limite ci-dessous avant de l'activer — le graphique est un outil d'apprentissage, jamais une mesure, jamais un conseil médical.",
"whatItIsHeader": "Ce que c'est",
"whatItIs": "Une courbe en dents de scie qui simule la superposition de vos doses enregistrées dans le temps, à partir du modèle Bateman à un compartiment avec les paramètres d'absorption et de demi-vie publiés dans l'EPAR EMA de chaque agoniste GLP-1 approuvé. L'axe vertical est sans unité et non étiqueté. C'est la forme, pas la valeur, qui est l'information de la courbe.",
"whatItIsntHeader": "Ce que ce n'est pas",
"whatItIsnt": "Pas un taux sanguin. Pas une mesure. Pas une prévision de la réponse réelle de votre corps. Pas une base pour une décision de dose, de timing ou d'escalade. Pour tout ce qui touche à votre traitement, parlez-en à votre médecin prescripteur.",
"whyEstimateHeader": "Pourquoi c'est une estimation",
"whyEstimate": "La pharmacocinétique de population décrit le patient typique. La variabilité individuelle est grande — le modèle Schneck/Urva 2024 du tirzépatide rapporte environ 22 % de variabilité interindividuelle sur l'absorption et environ 49 % sur le volume de distribution. Une courbe de manuel ne peut capturer ni votre poids, ni votre fonction rénale, ni votre technique d'injection, ni la précision de vos horaires. Lisez la courbe comme le rythme de votre dosage, pas comme votre niveau.",
"mdrBoundaryHeader": "Limite réglementaire",
"mdrBoundary": "HealthLog affiche des données réglementaires publiques et vos propres enregistrements. L'application ne prédit, ne diagnostique, ne traite et ne recommande aucune thérapie. Le règlement UE 2017/745 (Medical Device Regulation, MDR) et le document de guidance MDCG 2021-24 tracent la limite à partir des logiciels qui interprètent des données à des fins médicales — cette courbe reste résolument du côté éducatif de cette limite. Si vous avez le sentiment qu'elle vous pousse vers une décision clinique, fermez-la.",
"citationsHeader": "Sources",
"citations": "Rapports européens publics d'évaluation (EPAR) de l'EMA pour Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta et Bydureon (section 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Version du disclaimer : {version}",
"acknowledgeCta": "J'ai compris — activer",
"cancelCta": "Annuler",
"successToast": "Mode Recherche activé. La courbe de niveau de médicament est maintenant visible sur votre page GLP-1.",
"errorToast": "Impossible d'activer le mode Recherche. Veuillez réessayer.",
"staleVersionToast": "Le disclaimer a été mis à jour depuis le chargement de cette page. Rechargez pour lire la version actuelle."
}
}
},
"charts": {
+22
View File
@@ -717,6 +717,28 @@
"ema": "Fonte EMA",
"psp4": "Farmacometria peer-reviewed"
}
},
"researchMode": {
"dialog": {
"title": "Attiva la modalità Ricerca",
"intro": "La modalità Ricerca aggiunge un grafico stimato del livello del farmaco alla tua pagina GLP-1. Leggi il limite qui sotto prima di attivarla: il grafico è uno strumento di apprendimento, mai una misura, mai un consiglio medico.",
"whatItIsHeader": "Cosa è",
"whatItIs": "Una curva a dente di sega che simula la sovrapposizione delle dosi registrate nel tempo, usando il modello Bateman a un compartimento con i parametri di assorbimento e di emivita pubblicati nell'EPAR EMA di ogni agonista GLP-1 approvato. L'asse verticale è privo di unità ed etichette. La forma, non il numero, è ciò che il grafico mostra.",
"whatItIsntHeader": "Cosa non è",
"whatItIsnt": "Non è un livello ematico. Non è una misura. Non è una previsione della risposta reale del tuo corpo. Non è una base per alcuna decisione di dose, di tempistica o di escalation. Per qualunque cosa riguardi come assumi il tuo farmaco, parla con il medico che te lo prescrive.",
"whyEstimateHeader": "Perché è una stima",
"whyEstimate": "La farmacocinetica di popolazione descrive il paziente tipico. La variabilità individuale è ampia: il modello Schneck/Urva 2024 del tirzepatide riporta circa il 22 % di variabilità interindividuale sull'assorbimento e circa il 49 % sul volume di distribuzione. Una curva da manuale non può catturare il tuo peso, la tua funzione renale, la tua tecnica di iniezione o la precisione degli orari. Leggi la curva come il ritmo del tuo dosaggio, non come il tuo livello.",
"mdrBoundaryHeader": "Limite regolatorio",
"mdrBoundary": "HealthLog mostra dati regolatori pubblici e le tue registrazioni. L'app non predice, non diagnostica, non tratta e non raccomanda alcuna terapia. Il Regolamento UE 2017/745 (Medical Device Regulation, MDR) e il documento di orientamento MDCG 2021-24 tracciano la linea sul software che interpreta dati per scopi medici: questa curva rimane decisamente sul lato educativo di quella linea. Se in qualunque momento ti sembra spingere verso una decisione clinica, chiudila.",
"citationsHeader": "Fonti",
"citations": "European Public Assessment Reports EMA per Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta e Bydureon (Sezione 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Versione del disclaimer: {version}",
"acknowledgeCta": "Ho capito — attiva",
"cancelCta": "Annulla",
"successToast": "Modalità Ricerca attivata. La curva del livello del farmaco è ora visibile sulla tua pagina GLP-1.",
"errorToast": "Impossibile attivare la modalità Ricerca. Riprova.",
"staleVersionToast": "Il disclaimer è stato aggiornato dal caricamento di questa pagina. Ricarica per leggere la versione attuale."
}
}
},
"charts": {
+22
View File
@@ -717,6 +717,28 @@
"ema": "Źródło EMA",
"psp4": "Farmakometria recenzowana"
}
},
"researchMode": {
"dialog": {
"title": "Włącz tryb Badawczy",
"intro": "Tryb Badawczy dodaje szacowany wykres poziomu leku do twojej strony GLP-1. Przed jego włączeniem przeczytaj granicę poniżej — wykres jest pomocą edukacyjną, nigdy pomiarem i nigdy poradą medyczną.",
"whatItIsHeader": "Czym to jest",
"whatItIs": "Piłokształtną krzywą, która symuluje nakładanie się twoich zarejestrowanych dawek w czasie, na podstawie jednokompartmentowego modelu Batemana z parametrami absorpcji i okresu półtrwania opublikowanymi w EPAR EMA dla każdego zatwierdzonego agonisty GLP-1. Oś pionowa jest bezjednostkowa i nieopisana. To kształt, a nie liczba, jest tym, co pokazuje wykres.",
"whatItIsntHeader": "Czym to nie jest",
"whatItIsnt": "Nie jest poziomem we krwi. Nie jest pomiarem. Nie jest prognozą faktycznej reakcji twojego organizmu. Nie jest podstawą żadnej decyzji o dawce, czasie ani eskalacji. We wszystkim, co dotyczy sposobu przyjmowania leku, porozmawiaj z lekarzem prowadzącym.",
"whyEstimateHeader": "Dlaczego to oszacowanie",
"whyEstimate": "Farmakokinetyka populacyjna opisuje typowego pacjenta. Zmienność osobnicza jest duża — model Schneck/Urva 2024 dla tirzepatydu raportuje około 22 % międzyosobniczej zmienności absorpcji i około 49 % objętości dystrybucji. Krzywa z podręcznika nie uchwyci ani twojej masy ciała, ani funkcji nerek, ani techniki iniekcji, ani precyzji czasu. Czytaj krzywą jako rytm dawkowania, a nie twój poziom.",
"mdrBoundaryHeader": "Granica regulacyjna",
"mdrBoundary": "HealthLog wyświetla publiczne dane regulacyjne i twoje własne wpisy. Aplikacja nie prognozuje, nie diagnozuje, nie leczy i nie rekomenduje żadnej terapii. Rozporządzenie UE 2017/745 (Medical Device Regulation, MDR) oraz dokument MDCG 2021-24 wyznaczają granicę przy oprogramowaniu interpretującym dane do celów medycznych — ten wykres pozostaje zdecydowanie po edukacyjnej stronie tej granicy. Jeśli kiedykolwiek poczujesz, że kieruje cię w stronę decyzji klinicznej, zamknij go.",
"citationsHeader": "Źródła",
"citations": "European Public Assessment Reports EMA dla Mounjaro, Ozempic, Wegovy, Saxenda, Trulicity, Byetta i Bydureon (Sekcja 5.2). Schneck K, Urva S. Population pharmacokinetics of the GIP/GLP receptor agonist tirzepatide. CPT Pharmacometrics Syst Pharmacol 2024;13(3):494-503 (DOI 10.1002/psp4.13099).",
"versionLine": "Wersja disclaimera: {version}",
"acknowledgeCta": "Rozumiem — włącz",
"cancelCta": "Anuluj",
"successToast": "Tryb Badawczy włączony. Krzywa poziomu leku jest teraz widoczna na twojej stronie GLP-1.",
"errorToast": "Nie udało się włączyć trybu Badawczego. Spróbuj ponownie.",
"staleVersionToast": "Disclaimer został zaktualizowany od czasu wczytania tej strony. Odśwież, aby przeczytać aktualną wersję."
}
}
},
"charts": {
@@ -0,0 +1,275 @@
"use client";
/**
* v1.4.25 W19c-Frontend — Research-mode MDR acknowledgment dialog.
*
* Opt-in gate in front of the GLP-1 drug-level chart. The chart paints
* a unit-less Bateman PK curve over the user's logged intakes (research
* §2.3 / §9.6.7). Because a "drug-level" surface is the brightest EU
* MDR Class IIa edge in HealthLog's surface area (research §11 + §12.4),
* the chart never paints until the user has explicitly read and
* acknowledged the disclaimer below. The acknowledgment record is
* server-stamped with `RESEARCH_MODE_DISCLAIMER_VERSION`; if the copy
* changes the user re-acknowledges before the chart unhides.
*
* The dialog is rendered controlled by the Settings toggle and the
* "re-prompt" banner (commit 3 of this phase). It accepts:
* - `open` / `onOpenChange` for full external control
* - `currentDisclaimerVersion` — the server's authoritative version
* string. Acknowledgment posts THIS value, not the imported
* constant — server redeploys that bump the constant must be
* reflected without a client reload (W19c-Backend phase report).
* - `onAcknowledged()` — fires after a successful 200; the caller
* re-fetches the research-mode state and renders the toggle in
* the new state.
*
* Copy direction (Marc-Voice, English, no AI/phase/wave mentions):
* - "What this is" — single-paragraph framing: the chart is an
* estimate from EMA-published population PK.
* - "What this isn't" — explicit boundary: not a measurement, not
* personalised, not medical advice.
* - "Why it's an estimate" — population PK + IIV; per-patient
* variation is large.
* - "MDR boundary" — cite EU 2017/745 and MDCG 2021-24 verbatim.
* - "Citations" — EMA EPAR + Schneck/Urva 2024 (ASCPT psp4.13099).
*
* Toast surface uses sonner (the project convention) so the user gets
* a transient confirmation on either success or rejection.
*/
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { AlertTriangle, BookOpenCheck, Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
export interface ResearchModeAcknowledgmentDialogProps {
open: boolean;
onOpenChange: (next: boolean) => void;
/**
* The version string from `GET /api/auth/me/research-mode`. The
* server compares it byte-for-byte against the current constant; a
* stale value forces a 400 from the API which we surface as an
* error toast and keep the dialog open. Pass `null` while the
* GET is in flight; the Acknowledge CTA stays disabled.
*/
currentDisclaimerVersion: string | null;
/**
* Fires after the POST returns 200. Caller invalidates the
* `research-mode` query so the toggle reflects the new state.
*/
onAcknowledged?: () => void;
}
export function ResearchModeAcknowledgmentDialog({
open,
onOpenChange,
currentDisclaimerVersion,
onAcknowledged,
}: ResearchModeAcknowledgmentDialogProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const mutation = useMutation({
mutationFn: async (version: string) => {
const res = await fetch("/api/auth/me/research-mode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ acknowledged: true, version }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
const code =
typeof json?.error === "string"
? json.error
: `http-${res.status}`;
throw new Error(code);
}
return json?.data ?? null;
},
onSuccess: () => {
setErrorMessage(null);
toast.success(t("medications.researchMode.dialog.successToast"));
queryClient.invalidateQueries({ queryKey: ["research-mode"] });
onAcknowledged?.();
onOpenChange(false);
},
onError: (err: unknown) => {
// The 400 stale-version path is the only one we surface
// explicitly — every other failure mode (401, 429, 500, network)
// collapses to a generic error so the dialog stays open but the
// user knows the acknowledgment didn't persist.
const code = err instanceof Error ? err.message : "unknown";
const isStale = code === "research-mode.version.stale";
const message = isStale
? t("medications.researchMode.dialog.staleVersionToast")
: t("medications.researchMode.dialog.errorToast");
setErrorMessage(message);
toast.error(message);
},
});
function handleAcknowledge() {
if (!currentDisclaimerVersion) return;
mutation.mutate(currentDisclaimerVersion);
}
function handleCancel() {
setErrorMessage(null);
onOpenChange(false);
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
data-slot="research-mode-acknowledgment-dialog"
className="max-h-[90vh] overflow-y-auto sm:max-w-xl"
>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<BookOpenCheck className="text-dracula-purple h-5 w-5 shrink-0" />
{t("medications.researchMode.dialog.title")}
</DialogTitle>
<DialogDescription>
{t("medications.researchMode.dialog.intro")}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 text-sm">
<section
aria-labelledby="research-mode-what-it-is"
data-slot="research-mode-what-it-is"
>
<h3
id="research-mode-what-it-is"
className="text-foreground font-medium"
>
{t("medications.researchMode.dialog.whatItIsHeader")}
</h3>
<p className="text-muted-foreground mt-1">
{t("medications.researchMode.dialog.whatItIs")}
</p>
</section>
<section
aria-labelledby="research-mode-what-it-isnt"
data-slot="research-mode-what-it-isnt"
>
<h3
id="research-mode-what-it-isnt"
className="text-foreground font-medium"
>
{t("medications.researchMode.dialog.whatItIsntHeader")}
</h3>
<p className="text-muted-foreground mt-1">
{t("medications.researchMode.dialog.whatItIsnt")}
</p>
</section>
<section
aria-labelledby="research-mode-why-estimate"
data-slot="research-mode-why-estimate"
>
<h3
id="research-mode-why-estimate"
className="text-foreground font-medium"
>
{t("medications.researchMode.dialog.whyEstimateHeader")}
</h3>
<p className="text-muted-foreground mt-1">
{t("medications.researchMode.dialog.whyEstimate")}
</p>
</section>
<section
aria-labelledby="research-mode-mdr"
data-slot="research-mode-mdr-boundary"
className="bg-warning/10 border-warning/30 rounded-md border-l-4 px-3 py-2"
>
<h3
id="research-mode-mdr"
className="text-foreground flex items-center gap-2 font-medium"
>
<AlertTriangle
className="text-warning h-4 w-4 shrink-0"
aria-hidden="true"
/>
{t("medications.researchMode.dialog.mdrBoundaryHeader")}
</h3>
<p className="text-foreground/85 mt-1">
{t("medications.researchMode.dialog.mdrBoundary")}
</p>
</section>
<section
aria-labelledby="research-mode-citations"
data-slot="research-mode-citations"
>
<h3
id="research-mode-citations"
className="text-foreground font-medium"
>
{t("medications.researchMode.dialog.citationsHeader")}
</h3>
<p className="text-muted-foreground mt-1">
{t("medications.researchMode.dialog.citations")}
</p>
</section>
{currentDisclaimerVersion && (
<p
className="text-muted-foreground text-xs italic"
data-slot="research-mode-version"
>
{t("medications.researchMode.dialog.versionLine", {
version: currentDisclaimerVersion,
})}
</p>
)}
{errorMessage && (
<p
role="alert"
className="text-destructive text-sm"
data-slot="research-mode-error"
>
{errorMessage}
</p>
)}
</div>
<DialogFooter className="gap-2 sm:gap-2">
<Button
variant="outline"
onClick={handleCancel}
disabled={mutation.isPending}
data-slot="research-mode-cancel"
>
{t("medications.researchMode.dialog.cancelCta")}
</Button>
<Button
onClick={handleAcknowledge}
disabled={mutation.isPending || !currentDisclaimerVersion}
data-slot="research-mode-acknowledge"
>
{mutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("medications.researchMode.dialog.acknowledgeCta")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,287 @@
/**
* v1.4.25 W19c-Frontend — Research-mode acknowledgment dialog tests.
*
* The dialog is rendered controlled by Settings (commit 3) and gates
* the GLP-1 drug-level chart (commit 2). The contract is:
*
* 1. Multi-section MDR copy renders (what-is, what-isn't, why,
* MDR boundary, citations).
* 2. Acknowledge CTA fires a `POST /api/auth/me/research-mode` with
* the exact server-supplied version string.
* 3. Cancel CTA fires `onOpenChange(false)` without an API call.
* 4. The stale-version error (server 400 with
* `research-mode.version.stale`) surfaces a localised error toast
* and keeps the dialog open.
*
* Setup mirrors the existing `coach-settings-sheet.test.tsx` pattern:
* SSR via `renderToStaticMarkup` so the Radix Dialog primitives are
* mocked to plain wrappers (Portals don't materialise under SSR), and
* the TanStack Query mutation is captured so we can drive the
* onSuccess / onError branches by hand.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { toast } from "sonner";
import { I18nProvider } from "@/lib/i18n/context";
const mutationCallbacks: {
mutationFn: ((version: string) => Promise<unknown>) | null;
onSuccess: ((data: unknown) => void) | null;
onError: ((err: unknown) => void) | null;
} = { mutationFn: null, onSuccess: null, onError: null };
const lastMutateCall: { args: unknown[] } = { args: [] };
vi.mock("@tanstack/react-query", () => ({
useMutation: (opts: {
mutationFn: (version: string) => Promise<unknown>;
onSuccess?: (data: unknown) => void;
onError?: (err: unknown) => void;
}) => {
mutationCallbacks.mutationFn = opts.mutationFn;
mutationCallbacks.onSuccess = opts.onSuccess ?? null;
mutationCallbacks.onError = opts.onError ?? null;
return {
mutate: (version: string) => {
lastMutateCall.args = [version];
},
isPending: false,
};
},
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
vi.mock("sonner", () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
// Radix Dialog uses Portals which `renderToStaticMarkup` does not
// realise. We collapse the primitives to plain wrappers so the body of
// the dialog is reachable in the static markup.
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({
open,
children,
}: {
open: boolean;
children: React.ReactNode;
}) => (open ? <div data-slot="mock-dialog">{children}</div> : null),
DialogContent: ({
children,
...rest
}: React.ComponentProps<"div"> & { children: React.ReactNode }) => (
<div data-slot="mock-dialog-content" {...rest}>
{children}
</div>
),
DialogHeader: ({ children }: { children: React.ReactNode }) => (
<div data-slot="mock-dialog-header">{children}</div>
),
DialogTitle: ({ children }: { children: React.ReactNode }) => (
<h2 data-slot="mock-dialog-title">{children}</h2>
),
DialogDescription: ({ children }: { children: React.ReactNode }) => (
<p data-slot="mock-dialog-description">{children}</p>
),
DialogFooter: ({ children }: { children: React.ReactNode }) => (
<div data-slot="mock-dialog-footer">{children}</div>
),
}));
import { ResearchModeAcknowledgmentDialog } from "../ResearchModeAcknowledgmentDialog";
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
beforeEach(() => {
mutationCallbacks.mutationFn = null;
mutationCallbacks.onSuccess = null;
mutationCallbacks.onError = null;
lastMutateCall.args = [];
vi.mocked(toast.success).mockClear();
vi.mocked(toast.error).mockClear();
});
describe("<ResearchModeAcknowledgmentDialog>", () => {
it("renders nothing while `open === false`", () => {
const html = render(
<ResearchModeAcknowledgmentDialog
open={false}
onOpenChange={() => {}}
currentDisclaimerVersion="2026-05-14.1"
/>,
);
expect(html).toBe("");
});
it("renders the title + the five MDR-copy sections while open", () => {
const html = render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={() => {}}
currentDisclaimerVersion="2026-05-14.1"
/>,
);
// Title + primary CTAs.
expect(html).toContain("Enable Research Mode");
expect(html).toContain("I understand — enable");
expect(html).toContain("Cancel");
// Each of the five sections renders its own headline.
expect(html).toContain("What this is");
expect(html).toContain("What this isn&#x27;t");
expect(html).toContain("Why it&#x27;s an estimate");
expect(html).toContain("Regulatory boundary");
expect(html).toContain("Sources");
// Cited regulatory references must appear verbatim in the
// user-facing copy (Marc-Voice + research §11 + §12.4).
expect(html).toContain("2017/745");
expect(html).toContain("MDCG 2021-24");
// Peer-reviewed citation.
expect(html).toContain("10.1002/psp4.13099");
// Version line surfaces the live server value.
expect(html).toContain("Disclaimer version: 2026-05-14.1");
});
it("acknowledge CTA invokes the mutation with the supplied version", async () => {
render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={() => {}}
currentDisclaimerVersion="2026-05-14.1"
/>,
);
// SSR markup can't fire DOM events; invoke the mutation directly
// (the production component calls `mutation.mutate(version)` from
// the click handler with `currentDisclaimerVersion`).
expect(mutationCallbacks.mutationFn).not.toBeNull();
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { enabled: true } }),
});
vi.stubGlobal("fetch", fetchMock);
await mutationCallbacks.mutationFn?.("2026-05-14.1");
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("/api/auth/me/research-mode");
expect(init.method).toBe("POST");
expect(JSON.parse(init.body as string)).toEqual({
acknowledged: true,
version: "2026-05-14.1",
});
vi.unstubAllGlobals();
});
it("onSuccess fires the localised success toast", () => {
const onAcknowledged = vi.fn();
const onOpenChange = vi.fn();
render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={onOpenChange}
currentDisclaimerVersion="2026-05-14.1"
onAcknowledged={onAcknowledged}
/>,
);
mutationCallbacks.onSuccess?.({ enabled: true });
expect(vi.mocked(toast.success)).toHaveBeenCalledTimes(1);
expect(vi.mocked(toast.success).mock.calls[0][0]).toContain(
"Research Mode enabled",
);
expect(onAcknowledged).toHaveBeenCalledTimes(1);
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it("stale-version error surfaces the localised error toast and keeps the dialog open", () => {
const onOpenChange = vi.fn();
render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={onOpenChange}
currentDisclaimerVersion="2026-05-14.1"
/>,
);
mutationCallbacks.onError?.(new Error("research-mode.version.stale"));
expect(vi.mocked(toast.error)).toHaveBeenCalledTimes(1);
expect(vi.mocked(toast.error).mock.calls[0][0]).toContain(
"disclaimer was updated",
);
// The error path never closes the dialog — the caller stays put
// so the user can reload and re-read the new copy.
expect(onOpenChange).not.toHaveBeenCalled();
});
it("generic error path surfaces the generic error toast", () => {
render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={() => {}}
currentDisclaimerVersion="2026-05-14.1"
/>,
);
mutationCallbacks.onError?.(new Error("http-500"));
expect(vi.mocked(toast.error)).toHaveBeenCalledTimes(1);
expect(vi.mocked(toast.error).mock.calls[0][0]).toContain(
"Could not enable Research Mode",
);
});
it("acknowledge CTA is disabled until the server-supplied version arrives", () => {
const html = render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={() => {}}
currentDisclaimerVersion={null}
/>,
);
// The disabled flag stamps as `disabled=""` on a server-rendered button.
// The acknowledge button carries `data-slot="research-mode-acknowledge"`.
const acknowledgeFragment = html.match(
/<button[^>]*data-slot="research-mode-acknowledge"[^>]*>/,
)?.[0];
expect(acknowledgeFragment).toBeDefined();
expect(acknowledgeFragment).toMatch(/\sdisabled(="|\s|>)/);
// The version line is hidden when null — guard against leaking
// `version: null` text into the UI.
expect(html).not.toContain("Disclaimer version:");
});
it("renders German copy when locale='de'", () => {
const html = render(
<ResearchModeAcknowledgmentDialog
open={true}
onOpenChange={() => {}}
currentDisclaimerVersion="2026-05-14.1"
/>,
"de",
);
expect(html).toContain("Forschungsmodus aktivieren");
expect(html).toContain("Verstanden — aktivieren");
expect(html).toContain("Abbrechen");
expect(html).toContain("2017/745");
});
});