diff --git a/sanitas_frontend/src/views/History/Psichiatric/index.jsx b/sanitas_frontend/src/views/History/Psichiatric/index.jsx index 67523cd8..f5a65caa 100644 --- a/sanitas_frontend/src/views/History/Psichiatric/index.jsx +++ b/sanitas_frontend/src/views/History/Psichiatric/index.jsx @@ -1,10 +1,12 @@ import { Suspense, useEffect, useState } from "react"; import "react-toastify/dist/ReactToastify.css"; import { toast } from "react-toastify"; +import CheckIcon from "@tabler/icons/outline/check.svg"; +import EditIcon from "@tabler/icons/outline/edit.svg"; +import CancelIcon from "@tabler/icons/outline/x.svg"; import BaseButton from "src/components/Button/Base/index"; import DashboardSidebar from "src/components/DashboardSidebar"; -import DropdownMenu from "src/components/DropdownMenu"; -import InformationCard from "src/components/InformationCard"; +import IconButton from "src/components/Button/Icon"; import { BaseInput, RadioInput } from "src/components/Input/index"; import Throbber from "src/components/Throbber"; import { colors, fonts, fontSize } from "src/theme.mjs"; @@ -31,6 +33,11 @@ export function PsichiatricHistory({ }) { const id = useStore((s) => s.selectedPatientId); const psichiatricHistoryResource = WrapPromise(getPsichiatricHistory(id)); + const [_reload, setReload] = useState(false); // Controls reload toggling for refetching data + + const triggerReload = () => { + setReload((prev) => !prev); + }; const LoadingView = () => { return ( @@ -116,6 +123,7 @@ export function PsichiatricHistory({ id={id} psichiatricHistoryResource={psichiatricHistoryResource} updatePsichiatricHistory={updatePsichiatricHistory} + triggerReload={triggerReload} /> @@ -130,9 +138,10 @@ export function PsichiatricHistory({ * @property {number} id - The patient's ID. * @property {Object} psichiatricHistoryResource - Wrapped resource for fetching psichiatric history data. * @property {Function} updatePsichiatricHistory - Function to update the Allergic history. - * + * @property {Function} triggerReload - Function to trigger reloading of data. * Internal view component for managing the display and modification of a patient's psichiatric history, with options to add or edit records. * + * * @param {PsichiatricViewProps} props - Specific props for the PsichiatricViewiew component. * @returns {JSX.Element} - A detailed view for managing Psichiatric history with interactivity to add or edit records. */ @@ -141,14 +150,264 @@ function PsichiatricView({ id, psichiatricHistoryResource, updatePsichiatricHistory, + triggerReload, }) { - const [selectedHistory, setSelectedHistory] = useState(null); - const [addingNew, setAddingNew] = useState(false); + const psichiatricHistoryResult = psichiatricHistoryResource.read(); + const psichiatricHistoryData = psichiatricHistoryResult.result || {}; - const [showOtherInput, setShowOtherInput] = useState(false); + const [depressionMedications, setDepressionMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); - const psichiatricHistoryResult = psichiatricHistoryResource.read(); + const addDepressionMedication = () => { + setDepressionMedications([ + ...depressionMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const removeLastDepressionMedication = () => { + setDepressionMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + const removeLastAnxietyMedication = () => { + setAnxietyMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + + const removeLastTOCMedication = () => { + setTOCMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + + const removeLastTDAHMedication = () => { + setTDAHMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + + const removeLastBipolarMedication = () => { + setBipolarMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + + const removeLastOtherMedication = () => { + setOtherMedications((prevMedications) => prevMedications.slice(0, -1)); + }; + + const handleDepressionMedicationChange = (index, field, value) => { + const newMedications = [...depressionMedications]; + newMedications[index][field] = value; + setDepressionMedications(newMedications); + }; + + const [anxietyMedications, setAnxietyMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); + + const addAnxietyMedication = () => { + setAnxietyMedications([ + ...anxietyMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const [TOCMedications, setTOCMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); + + const addTOCMedication = () => { + setTOCMedications([ + ...TOCMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const handleTOCMedicationChange = (index, field, value) => { + const newMedications = [...TOCMedications]; + newMedications[index][field] = value; + setTOCMedications(newMedications); + }; + + const handleAnxietyMedicationChange = (index, field, value) => { + const newMedications = [...anxietyMedications]; + newMedications[index][field] = value; + setAnxietyMedications(newMedications); + }; + + const [TDAHMedications, setTDAHMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); + + const addTDAHMedication = () => { + setTDAHMedications([ + ...TDAHMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const handleTDAHMedicationChange = (index, field, value) => { + const newMedications = [...TDAHMedications]; + newMedications[index][field] = value; + setTDAHMedications(newMedications); + }; + + const [bipolarMedications, setBipolarMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); + + const addBipolarMedication = () => { + setBipolarMedications([ + ...bipolarMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const handleBipolarMedicationChange = (index, field, value) => { + const newMedications = [...bipolarMedications]; + newMedications[index][field] = value; + setBipolarMedications(newMedications); + }; + + const [otherMedications, setOtherMedications] = useState([ + { medication: "", dose: "", frequency: "" }, + ]); + + const addOtherMedication = () => { + setOtherMedications([ + ...otherMedications, + { medication: "", dose: "", frequency: "" }, + ]); + }; + + const handleOtherMedicationChange = (index, field, value) => { + const newMedications = [...otherMedications]; + newMedications[index][field] = value; + setOtherMedications(newMedications); + }; + + const medicalHistory = psichiatricHistoryData?.medicalHistory || { + depression: { data: [] }, + anxiety: { data: [] }, + ocd: { data: [] }, + adhd: { data: [] }, + bipolar: { data: [] }, + other: { data: [] }, + }; + + const { + depression = { + data: [{ medication: "", dose: "", frequency: "", ube: false }], + }, + anxiety = { + data: [{ medication: "", dose: "", frequency: "", ube: false }], + }, + ocd = { data: [{ medication: "", dose: "", frequency: "", ube: false }] }, + adhd = { data: [{ medication: "", dose: "", frequency: "", ube: false }] }, + bipolar = { + data: [{ medication: "", dose: "", frequency: "", ube: false }], + }, + other = { + data: [ + { illness: "", medication: "", dose: "", frequency: "", ube: false }, + ], + }, + } = medicalHistory; + + const [depressionStatus, setDepressionStatus] = useState( + depression.data.length > 0, + ); + const [anxietyStatus, setAnxietyStatus] = useState(anxiety.data.length > 0); + const [TOCStatus, setTOCStatus] = useState(ocd.data.length > 0); + const [TDAHStatus, setTDAHStatus] = useState(adhd.data.length > 0); + const [BipolarStatus, setBipolarStatus] = useState(bipolar.data.length > 0); + const [OtherStatus, setOtherStatus] = useState(bipolar.data.length > 0); + + // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Ignoring complexity for this function + useEffect(() => { + setDepressionMedications( + depression.data.length > 0 && + depression.data.some((item) => item.medication) + ? depression.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ medication: "", dose: "", frequency: "" }], + ); + setDepressionStatus( + depression.data.length > 0 && + depression.data.some((item) => item.medication), + ); + + setAnxietyMedications( + anxiety.data.length > 0 && anxiety.data.some((item) => item.medication) + ? anxiety.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ medication: "", dose: "", frequency: "" }], + ); + setAnxietyStatus( + anxiety.data.length > 0 && anxiety.data.some((item) => item.medication), + ); + + setTOCMedications( + ocd.data.length > 0 && ocd.data.some((item) => item.medication) + ? ocd.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ medication: "", dose: "", frequency: "" }], + ); + setTOCStatus( + ocd.data.length > 0 && ocd.data.some((item) => item.medication), + ); + + setTDAHMedications( + adhd.data.length > 0 && adhd.data.some((item) => item.medication) + ? adhd.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ medication: "", dose: "", frequency: "" }], + ); + setTDAHStatus( + adhd.data.length > 0 && adhd.data.some((item) => item.medication), + ); + + setBipolarMedications( + bipolar.data.length > 0 && bipolar.data.some((item) => item.medication) + ? bipolar.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ medication: "", dose: "", frequency: "" }], + ); + setBipolarStatus( + bipolar.data.length > 0 && bipolar.data.some((item) => item.medication), + ); + + setOtherMedications( + other.data.length > 0 && other.data.some((item) => item.medication) + ? other.data.map((item) => ({ + illness: item.illness || "", + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })) + : [{ illness: "", medication: "", dose: "", frequency: "" }], + ); + setOtherStatus( + other.data.length > 0 && other.data.some((item) => item.medication), + ); + }, [depression, anxiety, ocd, adhd, bipolar, other]); + + const isFirstTime = !( + depression.data.length || + anxiety.data.length || + ocd.data.length + ); + const [isEditable, setIsEditable] = useState(isFirstTime); let errorMessage = ""; if (psichiatricHistoryResult.error) { @@ -170,158 +429,518 @@ function PsichiatricView({ } } - const psichiatricHistoryData = psichiatricHistoryResult.result; + // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Ignoring complexity for this function + const validateInputs = () => { + // Validar Depresión + if (depressionStatus) { + for (let i = 0; i < depressionMedications.length; i++) { + if (!depressionMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para la depresión (${i + 1}).`, + ); + return false; + } + if (!depressionMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para la depresión (${i + 1}).`, + ); + return false; + } + } + } + + // Validar Ansiedad + if (anxietyStatus) { + for (let i = 0; i < anxietyMedications.length; i++) { + if (!anxietyMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para la ansiedad (${i + 1}).`, + ); + return false; + } + if (!anxietyMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para la ansiedad (${i + 1}).`, + ); + return false; + } + } + } - const [PsichiatricHistory, setPsichiatricHistory] = useState( - psichiatricHistoryData?.medicalHistory || {}, - ); + // Validar TOC (Trastorno Obsesivo Compulsivo) + if (TOCStatus) { + for (let i = 0; i < TOCMedications.length; i++) { + if (!TOCMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para el TOC (${i + 1}).`, + ); + return false; + } + if (!TOCMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para el TOC (${i + 1}).`, + ); + return false; + } + } + } - // No allergic data in API + // Validar TDAH (Trastorno por Déficit de Atención e Hiperactividad) + if (TDAHStatus) { + for (let i = 0; i < TDAHMedications.length; i++) { + if (!TDAHMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para el TDAH (${i + 1}).`, + ); + return false; + } + if (!TDAHMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para el TDAH (${i + 1}).`, + ); + return false; + } + } + } - const noPsichiatricData = !Object.values(PsichiatricHistory).some( - (category) => category?.data?.medication, - ); + // Validar Trastorno Bipolar + if (BipolarStatus) { + for (let i = 0; i < bipolarMedications.length; i++) { + if (!bipolarMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para el trastorno bipolar (${i + 1}).`, + ); + return false; + } + if (!bipolarMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para el trastorno bipolar (${i + 1}).`, + ); + return false; + } + } + } - useEffect(() => {}, []); - - // Event handlers for adding, editing, and saving allergic history records - const handleOpenNewForm = () => { - setShowOtherInput(false); - setSelectedHistory({ - selectedIll: "depression", - medication: "", - ill: "", - dose: "", - frecuency: "", - ube: false, - whichHistory: "", - }); - setAddingNew(true); + // Validar Otros + if (OtherStatus) { + if (!otherIllness) { + toast.error("Por favor, ingresa la condición en Otros."); + return false; + } + for (let i = 0; i < otherMedications.length; i++) { + if (!otherMedications[i].medication) { + toast.error( + `Por favor, ingresa el medicamento para la condición en Otros (${i + 1}).`, + ); + return false; + } + if (!otherMedications[i].frequency) { + toast.error( + `Por favor, ingresa la frecuencia para la condición en Otros (${i + 1}).`, + ); + return false; + } + } + } + + // Si todas las validaciones pasan, retornar true + return true; }; // Save the new Allergic record to the database - // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Ignoring complexity for this function const handleSaveNewHistory = async () => { - setShowOtherInput(false); - if (selectedHistory.selectedIll === "other") { - if (!selectedHistory.ill) { - toast.error("Complete todos los campos requeridos."); - setShowOtherInput(true); - return; + // Validación de entradas antes de intentar guardar + if (!validateInputs()) return; + + // Mostrar mensaje de carga + toast.info("Guardando antecedentes psiquiátricos..."); + + // Construir el objeto newHistoryData usando los estados actuales + const newHistoryData = { + depression: { + version: medicalHistory.depression.version || 1, + data: depressionMedications.map((medication) => ({ + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: depressionUBE, + })), + }, + anxiety: { + version: medicalHistory.anxiety.version || 1, + data: anxietyMedications.map((medication) => ({ + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: anxietyUBE, + })), + }, + ocd: { + version: medicalHistory.ocd.version || 1, + data: TOCMedications.map((medication) => ({ + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: TOCUBE, + })), + }, + adhd: { + version: medicalHistory.adhd.version || 1, + data: TDAHMedications.map((medication) => ({ + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: TDAHUBE, + })), + }, + bipolar: { + version: medicalHistory.bipolar.version || 1, + data: bipolarMedications.map((medication) => ({ + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: bipolarUBE, + })), + }, + other: { + version: medicalHistory.other.version || 1, + data: otherMedications.map((medication) => ({ + illness: otherIllness, + medication: medication.medication, + dose: medication.dose, + frequency: medication.frequency, + ube: otherUBE, + })), + }, + }; + + try { + const result = await updatePsichiatricHistory(id, newHistoryData); + if (!result.error) { + toast.success("Antecedentes psiquiátricos guardados con éxito."); + setIsEditable(false); + triggerReload(); + } else { + toast.error(`Error al guardar los antecedentes: ${result.error}`); } + } catch (error) { + toast.error(`Error en la operación: ${error.message}`); } - if ( - !( - selectedHistory.selectedIll && - selectedHistory.medication && - selectedHistory.frecuency - ) - ) { - if (selectedHistory.selectedIll === "other") { - toast.error("Complete todos los campos requeridos."); - setShowOtherInput(true); - return; + }; + + const [depressionUBE, setDepressionUBE] = useState( + depression.data.length > 0 && depression.data[0].ube != null + ? depression.data[0].ube + : false, + ); + + const [anxietyUBE, setAnxietyUBE] = useState( + anxiety.data.length > 0 && anxiety.data[0].ube != null + ? anxiety.data[0].ube + : false, + ); + + const [TOCUBE, setTOCUBE] = useState( + ocd.data.length > 0 && ocd.data[0].ube != null ? ocd.data[0].ube : false, + ); + + const [TDAHUBE, setTDAHUBE] = useState( + adhd.data.length > 0 && adhd.data[0].ube != null ? adhd.data[0].ube : false, + ); + + const [bipolarUBE, setBipolarUBE] = useState( + bipolar.data.length > 0 && bipolar.data[0].ube != null + ? bipolar.data[0].ube + : false, + ); + + const [otherIllness, setOtherIllness] = useState( + other.data.length > 0 && other.data[0].illness != null + ? other.data[0].illness + : "", + ); + + const [otherUBE, setOtherUBE] = useState( + other.data.length > 0 && other.data[0].ube != null + ? other.data[0].ube + : false, + ); + + const [originalDepressionMedications, setOriginalDepressionMedications] = + useState([]); + const [originalAnxietyMedications, setOriginalAnxietyMedications] = useState( + [], + ); + const [originalTOCMedications, setOriginalTOCMedications] = useState([]); + const [originalTDAHMedications, setOriginalTDAHMedications] = useState([]); + const [originalBipolarMedications, setOriginalBipolarMedications] = useState( + [], + ); + const [originalOtherMedications, setOriginalOtherMedications] = useState([]); + const [originalDepressionUBE, setOriginalDepressionUBE] = useState(false); + const [originalAnxietyUBE, setOriginalAnxietyUBE] = useState(false); + const [originalTOCUBE, setOriginalTOCUBE] = useState(false); + const [originalTDAHUBE, setOriginalTDAHUBE] = useState(false); + const [originalBipolarUBE, setOriginalBipolarUBE] = useState(false); + const [originalOtherUBE, setOriginalOtherUBE] = useState(false); + const [originalOtherIllness, setOriginalOtherIllness] = useState(""); + + // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Ignoring complexity for this function + useEffect(() => { + if (!isFirstTime) { + // Guardar los medicamentos para Depresión + const initialDepressionMedications = depression.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialDepressionMedications) !== + JSON.stringify(originalDepressionMedications) + ) { + setDepressionMedications(initialDepressionMedications); + setOriginalDepressionMedications( + JSON.parse(JSON.stringify(initialDepressionMedications)), + ); } - toast.error("Complete todos los campos requeridos."); - return; - } + // Guardar los medicamentos para Ansiedad + const initialAnxietyMedications = anxiety.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialAnxietyMedications) !== + JSON.stringify(originalAnxietyMedications) + ) { + setAnxietyMedications(initialAnxietyMedications); + setOriginalAnxietyMedications( + JSON.parse(JSON.stringify(initialAnxietyMedications)), + ); + } - toast.info("Guardando antecedente psiquiátrico..."); + // Guardar los medicamentos para TOC + const initialTOCMedications = ocd.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialTOCMedications) !== + JSON.stringify(originalTOCMedications) + ) { + setTOCMedications(initialTOCMedications); + setOriginalTOCMedications( + JSON.parse(JSON.stringify(initialTOCMedications)), + ); + } - // Crear el nuevo registro de alergia - const newHistoryData = { - ill: selectedHistory.ill, - medication: selectedHistory.medication, - dose: selectedHistory.dose, - frecuency: selectedHistory.frecuency, - ube: selectedHistory.ube, - }; + // Guardar los medicamentos para TDAH + const initialTDAHMedications = adhd.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialTDAHMedications) !== + JSON.stringify(originalTDAHMedications) + ) { + setTDAHMedications(initialTDAHMedications); + setOriginalTDAHMedications( + JSON.parse(JSON.stringify(initialTDAHMedications)), + ); + } - // Obtener la categoría actual (ej. medicamento, comida, etc.) - const currentCategoryData = - PsichiatricHistory[selectedHistory.selectedIll]?.data || {}; + // Guardar los medicamentos para Trastorno Bipolar + const initialBipolarMedications = bipolar.data.map((item) => ({ + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialBipolarMedications) !== + JSON.stringify(originalBipolarMedications) + ) { + setBipolarMedications(initialBipolarMedications); + setOriginalBipolarMedications( + JSON.parse(JSON.stringify(initialBipolarMedications)), + ); + } - // Si la categoría ya tiene datos, usamos su versión, de lo contrario, establecemos la versión en 1 - const currentVersion = - PsichiatricHistory[selectedHistory.selectedIll]?.version || 1; + // Guardar los medicamentos para Otros + const initialOtherMedications = other.data.map((item) => ({ + illness: item.illness || "", + medication: item.medication || "", + dose: item.dose || "", + frequency: item.frequency || "", + })); + if ( + JSON.stringify(initialOtherMedications) !== + JSON.stringify(originalOtherMedications) + ) { + setOtherMedications(initialOtherMedications); + setOriginalOtherMedications( + JSON.parse(JSON.stringify(initialOtherMedications)), + ); + } - // Actualizar la categoría con el nuevo registro - const updatedCategory = { - version: currentVersion, - data: { ...currentCategoryData, ...newHistoryData }, - }; + // Guardar las opciones UBE para Depresión + if (depression.data[0].ube !== originalDepressionUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setDepressionUBE(depression.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalDepressionUBE(depression.data[0].ube || false); + } - // Actualizar el historial médico con la nueva categoría - const updatedMedicalHistory = { - ...PsichiatricHistory, - [selectedHistory.selectedIll]: updatedCategory, - }; + // Guardar las opciones UBE para Ansiedad + if (anxiety.data[0].ube !== originalAnxietyUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setAnxietyUBE(anxiety.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalAnxietyUBE(anxiety.data[0].ube || false); + } - try { - const response = await updatePsichiatricHistory( - id, - updatedMedicalHistory, - ); - if (!response.error) { - setPsichiatricHistory(updatedMedicalHistory); - setAddingNew(false); - setSelectedHistory(null); - toast.success("Antecedente psiquiátrico guardado con éxito."); - } else { - toast.error(`Error al guardar: ${response.error}`); + // Guardar las opciones UBE para TOC + if (ocd.data[0].ube !== originalTOCUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setTOCUBE(ocd.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalTOCUBE(ocd.data[0].ube || false); } - } catch (error) { - toast.error(`Error en la operación: ${error.message}`); + + // Guardar las opciones UBE para TDAH + if (adhd.data[0].ube !== originalTDAHUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setTDAHUBE(adhd.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalTDAHUBE(adhd.data[0].ube || false); + } + + // Guardar las opciones UBE para Trastorno Bipolar + if (bipolar.data[0].ube !== originalBipolarUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setBipolarUBE(bipolar.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalBipolarUBE(bipolar.data[0].ube || false); + } + + // Guardar las opciones UBE para Otros + if (other.data[0].ube !== originalOtherUBE) { + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOtherUBE(other.data[0].ube || false); + // biome-ignore lint/complexity/useSimplifiedLogicExpression: Ignoring simplified logic suggestion for this line + setOriginalOtherUBE(other.data[0].ube || false); + } + + // Guardar la condición en Otros + if (other.data[0].illness !== originalOtherIllness) { + setOtherIllness(other.data[0].illness || ""); + + setOriginalOtherIllness(other.data[0].illness || ""); + } + } + }, [ + depression.data, + anxiety.data, + ocd.data, + adhd.data, + bipolar.data, + other.data, + originalAnxietyMedications, + originalBipolarMedications, + originalOtherIllness, + originalTOCUBE, + originalTOCMedications, + originalTDAHUBE, + originalTDAHMedications, + originalOtherUBE, + originalDepressionUBE, + originalAnxietyUBE, + originalBipolarUBE, + originalDepressionMedications, + originalOtherMedications, + isFirstTime, + ]); + + const handleCancel = () => { + // Restaurar los valores originales desde los estados guardados + setDepressionMedications( + JSON.parse(JSON.stringify(originalDepressionMedications)), + ); + setAnxietyMedications( + JSON.parse(JSON.stringify(originalAnxietyMedications)), + ); + setTOCMedications(JSON.parse(JSON.stringify(originalTOCMedications))); + setTDAHMedications(JSON.parse(JSON.stringify(originalTDAHMedications))); + setBipolarMedications( + JSON.parse(JSON.stringify(originalBipolarMedications)), + ); + setOtherMedications(JSON.parse(JSON.stringify(originalOtherMedications))); + + setDepressionUBE(originalDepressionUBE); + setAnxietyUBE(originalAnxietyUBE); + setTOCUBE(originalTOCUBE); + setTDAHUBE(originalTDAHUBE); + setBipolarUBE(originalBipolarUBE); + setOtherUBE(originalOtherUBE); + + setOtherIllness(originalOtherIllness); + + // Salir del modo de edición + setIsEditable(false); + toast.info("Edición cancelada."); + }; + + const handleDepressionChange = (newStatus) => { + setDepressionStatus(newStatus); + if (!newStatus) { + setDepressionMedications([{ medication: "", dose: "", frequency: "" }]); // Limpiar todos los medicamentos + setDepressionUBE(false); // Limpiar UBE } }; - const handleFieldChange = (fieldName, value) => { - setSelectedHistory((prevHistory) => ({ - ...prevHistory, - [fieldName]: value, - })); - - // Handling the "Otros" option to show the additional input - if (fieldName === "selectedIll" && value === "other") { - setShowOtherInput(true); - } else if (fieldName === "selectedIll") { - setShowOtherInput(false); + const handleAnxietyChange = (newStatus) => { + setAnxietyStatus(newStatus); + if (!newStatus) { + setAnxietyMedications([{ medication: "", dose: "", frequency: "" }]); // Limpiar todos los medicamentos + setAnxietyUBE(false); // Limpiar UBE } }; - const handleCancel = () => { - setSelectedHistory(null); - setAddingNew(false); + + const handleTOCChange = (newStatus) => { + setTOCStatus(newStatus); + if (!newStatus) { + setTOCMedications([{ medication: "", dose: "", frequency: "" }]); // Limpiar todos los medicamentos + setTOCUBE(false); // Limpiar UBE + } }; - const handleOnClickCard = (category, historyData) => { - if (category === "other") { - setShowOtherInput(true); - } else { - setShowOtherInput(false); + const handleTDAHChange = (newStatus) => { + setTDAHStatus(newStatus); + if (!newStatus) { + setTDAHMedications([{ medication: "", dose: "", frequency: "" }]); // Limpiar todos los medicamentos + setTDAHUBE(false); // Limpiar UBE } - setSelectedHistory({ selectedIll: category, ...historyData }); }; - const medicalHistoryOptions = [ - { label: "Depresión", value: "depression" }, - { label: "Ansiedad", value: "anxiety" }, - { label: "TOC (Trastorno Obsesivo Compulsivo)", value: "ocd" }, - { - label: "TDAH (Trastorno por Déficit de Atención e Hiperactividad)", - value: "adhd", - }, - { label: "Trastorno Bipolar", value: "bipolar" }, - { label: "Otros", value: "other" }, - ]; - - const categoryTranslations = { - depression: "Depresión", - anxiety: "Ansiedad", - ocd: "TOC (Trastorno Obsesivo Compulsivo)", - adhd: "TDAH (Trastorno por Déficit de Atención e Hiperactividad)", - bipolar: "Trastorno Bipolar", - other: "Otros", + const handleBipolarChange = (newStatus) => { + setBipolarStatus(newStatus); + if (!newStatus) { + setBipolarMedications([{ medication: "", dose: "", frequency: "" }]); // Limpiar todos los medicamentos + setBipolarUBE(false); // Limpiar UBE + } + }; + + const handleOtherChange = (newStatus) => { + setOtherStatus(newStatus); + if (!newStatus) { + setOtherMedications([ + { illness: "", medication: "", dose: "", frequency: "" }, + ]); // Limpiar todos los medicamentos y la condición + setOtherUBE(false); // Limpiar UBE + setOtherIllness(""); // Limpiar la condición + } }; return ( @@ -344,19 +963,7 @@ function PsichiatricView({ overflowY: "auto", }} > -
- -
- - {errorMessage && ( + {errorMessage ? (
{errorMessage}
- )} - - {noPsichiatricData && !errorMessage ? ( -

- ¡Parece que no hay antecedentes psiquiátricos! Agrega uno en el - botón de arriba. -

) : ( - Object.keys(PsichiatricHistory || {}).map((category) => { - const historyData = PsichiatricHistory[category]?.data; - - // Verifica si hay datos válidos en los campos antes de renderizar la tarjeta - if ( - historyData?.medication || - historyData?.dose || - historyData?.frecuency - ) { - if (!(historyData?.ill === "")) { - return ( - handleOnClickCard(category, historyData)} + <> + {isFirstTime && ( +
+ Por favor, ingrese los datos del paciente. Parece que es su + primera visita aquí. +
+ )} +
+ {!isFirstTime && + (isEditable ? ( +
+ + +
+ ) : ( + setIsEditable(true)} /> - ); - } - - return ( - handleOnClickCard(category, historyData)} - /> - ); - } + ))} +
+
+
+

+ ¿Tiene depresion? +

+
+ handleDepressionChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleDepressionChange(false)} + label="No" + disabled={!isEditable} + /> +
+
- return null; // Si no hay datos válidos, no renderiza nada - }) - )} -
+ {depressionStatus && ( +
+ {depressionMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleDepressionMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleDepressionMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Frecuencia {index + 1}: +

+ + handleDepressionMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setDepressionUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setDepressionUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+
+ {isEditable && ( + + )} +
+ {isEditable && depressionMedications.length > 1 && ( + + )} +
+
+ )} +
- {addingNew || selectedHistory ? ( -
-

- Seleccione la enfermedad: -

- handleFieldChange("selectedIll", e.target.value)} - style={{ - container: { width: "80%" }, - select: {}, - option: {}, - indicator: {}, - }} - /> - {showOtherInput && ( -
-

+

- Nombre de la enfermedad: -

- handleFieldChange("ill", e.target.value)} - placeholder="Ingrese el nombre de la enfermedad" +

+ ¿Tiene ansiedad? +

+
+ handleAnxietyChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleAnxietyChange(false)} + label="No" + disabled={!isEditable} + /> +
+
+ + {anxietyStatus && ( +
+ {anxietyMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleAnxietyMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleAnxietyMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + /> +

+ Frecuencia {index + 1}: +

+ + handleAnxietyMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setAnxietyUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setAnxietyUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+
+ {isEditable && ( + + )} +
+ {isEditable && anxietyMedications.length > 1 && ( + + )} +
+
+ )} +
+ +
+
+ > +

+ ¿Tiene trastorno obsesivo compulsivo? +

+
+ handleTOCChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleTOCChange(false)} + label="No" + disabled={!isEditable} + /> +
+
+ + {TOCStatus && ( +
+ {TOCMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleTOCMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleTOCMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Frecuencia {index + 1}: +

+ + handleTOCMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setTOCUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setTOCUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+
+ {isEditable && ( + + )} +
+ {isEditable && TOCMedications.length > 1 && ( + + )} +
+
+ )}
- )} -

- Medicamento: -

- handleFieldChange("medication", e.target.value)} - placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" - style={{ - width: "80%", - height: "2.5rem", - fontFamily: fonts.textFont, - fontSize: "1rem", - }} - /> -

- Dosis: -

- handleFieldChange("dose", e.target.value)} - placeholder="Ingrese cuánto. Ej. 50mg (Este campo es opcional)" - style={{ - width: "80%", - height: "2.5rem", - fontFamily: fonts.textFont, - fontSize: "1rem", - }} - /> -

- Frecuencia: -

- handleFieldChange("frecuency", e.target.value)} - placeholder="Ingrese cada cuándo administra el medicamento. (Ej. Cada dos días, cada 12 horas...)" - style={{ - width: "80%", - height: "2.5rem", - fontFamily: fonts.textFont, - fontSize: "1rem", - }} - /> -

- ¿Tiene seguimiento en UBE? -

-
- handleFieldChange("ube", true)} - style={{ label: { fontFamily: fonts.textFont } }} - /> - handleFieldChange("ube", false)} - style={{ label: { fontFamily: fonts.textFont } }} - /> -
+
+
+

+ ¿Tiene TDAH (Trastorno por Déficit de Atención e + Hiperactivida)? +

+
+ handleTDAHChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleTDAHChange(false)} + label="No" + disabled={!isEditable} + /> +
+
-
- {addingNew && ( - <> + {TDAHStatus && ( +
+ {TDAHMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleTDAHMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleTDAHMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Frecuencia {index + 1}: +

+ + handleTDAHMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setTDAHUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setTDAHUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+
+ {isEditable && ( + + )} +
+ {isEditable && TDAHMedications.length > 1 && ( + + )} +
+
+ )} +
+ +
+
+

+ ¿Tiene trastorno bipolar? +

+
+ handleBipolarChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleBipolarChange(false)} + label="No" + disabled={!isEditable} + /> +
+
+ + {BipolarStatus && ( +
+ {bipolarMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleBipolarMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleBipolarMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Frecuencia {index + 1}: +

+ + handleBipolarMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setBipolarUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setBipolarUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+ +
+ {isEditable && ( + + )} +
+ {isEditable && bipolarMedications.length > 1 && ( + + )} +
+
+ )} +
+ +
+
+

+ ¿Otro? +

+
+ handleOtherChange(true)} + label="Sí" + disabled={!isEditable} + /> + handleOtherChange(false)} + label="No" + disabled={!isEditable} + /> +
+
+ + {OtherStatus && ( +
+

+ ¿Cuál es la condición? +

+ setOtherIllness(e.target.value)} + placeholder="Ingrese la condición" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> + {otherMedications.map((medication, index) => ( +
+

+ Medicamento {index + 1}: +

+ + handleOtherMedicationChange( + index, + "medication", + e.target.value, + ) + } + placeholder="Ingrese el medicamento administrado (terapia entra en la categoría)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Dosis {index + 1}: +

+ + handleOtherMedicationChange( + index, + "dose", + e.target.value, + ) + } + placeholder="Ingrese cuánto (opcional)" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +

+ Frecuencia {index + 1}: +

+ + handleOtherMedicationChange( + index, + "frequency", + e.target.value, + ) + } + placeholder="Ingrese cada cuánto administra el medicamento" + style={{ + width: "90%", + height: "3rem", + fontFamily: fonts.textFont, + fontSize: "1rem", + }} + disabled={!isEditable} + /> +
+ ))} +

+ ¿Tiene seguimiento en UBE? +

+
+ setOtherUBE(true)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> + setOtherUBE(false)} + style={{ label: { fontFamily: fonts.textFont } }} + disabled={!isEditable} + /> +
+ +
+ {isEditable && ( + + )} +
+ {isEditable && otherMedications.length > 1 && ( + + )} +
+
+ )} +
+ + {isFirstTime && ( +
-
- - +
)} -
-
- ) : null} + + )} +
); } diff --git a/sanitas_frontend/src/views/History/Psichiatric/index.test.jsx b/sanitas_frontend/src/views/History/Psichiatric/index.test.jsx index 98b3b569..d8286792 100644 --- a/sanitas_frontend/src/views/History/Psichiatric/index.test.jsx +++ b/sanitas_frontend/src/views/History/Psichiatric/index.test.jsx @@ -1,8 +1,8 @@ -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { MemoryRouter } from "react-router-dom"; -import { toast } from "react-toastify"; +import { render, screen, waitFor } from "@testing-library/react"; +import { Suspense } from "react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; import { describe, expect, test, vi } from "vitest"; -import { PsichiatricHistory } from "."; // Ajusta la ruta según sea necesario +import { PsichiatricHistory } from "."; vi.mock("react-toastify", () => { return { @@ -14,171 +14,61 @@ vi.mock("react-toastify", () => { }; }); -const mockGetPsichiatricHistoryWithData = async (_id) => ({ - result: { - medicalHistory: { - depression: { - data: { - medication: "Antidepressants", - dose: "20mg", - frequency: "Daily", - ube: true, - }, - version: 1, - }, - anxiety: { - data: { - medication: "Anxiolytics", - dose: "10mg", - frequency: "As needed", - ube: false, - }, - version: 1, - }, - ocd: { - data: { - medication: "SSRIs", - dose: "50mg", - frequency: "Daily", - ube: false, - }, - version: 1, - }, - adhd: { - data: { - medication: "Stimulants", - dose: "30mg", - frequency: "Morning", - ube: true, - }, - version: 1, - }, - bipolar: { - data: { - medication: "Mood Stabilizers", - dose: "150mg", - frequency: "Twice daily", - ube: false, - }, - version: 1, - }, - other: { - data: { - ill: "Schizophrenia", - medication: "Antipsychotics", - dose: "200mg", - frequency: "Night", - ube: true, - }, - version: 1, - }, - }, - }, -}); - -const mockUpdatePsichiatricHistory = vi.fn(() => - Promise.resolve({ success: true }), -); +const mockGetPsichiatricHistory = vi.fn(); +const mockUpdatePsichiatricHistory = vi.fn(); const mockUseStore = vi.fn().mockReturnValue({ selectedPatientId: "123" }); const sidebarConfig = { userInformation: { displayName: "User Testing" }, }; -const Wrapper = ({ children }) => {children}; - -describe("PsichiatricHistory Component Tests", () => { - test("opens new form on button click", async () => { - render( - - - , - ); - - await waitFor(() => screen.getByText("Agregar antecedente psiquiátrico")); +const LoadingComponent = () =>
Loading...
; - const addButton = screen.getByText("Agregar antecedente psiquiátrico"); - fireEvent.click(addButton); - await waitFor(() => { - expect(screen.getByText("Guardar")).toBeInTheDocument(); - }); - }); +const Wrapper = ({ children }) => ( + + }> + + + + + +); - test("displays empty state message when there is no data", async () => { - const mockGetPsichiatricHistoryEmpty = vi.fn(() => - Promise.resolve({ - result: { - medicalHistory: { - depression: { data: {}, version: 1 }, - anxiety: { data: {}, version: 1 }, - ocd: { data: {}, version: 1 }, - adhd: { data: {}, version: 1 }, - bipolar: { data: {}, version: 1 }, - other: { data: {}, version: 1 }, +describe("PsichiatricHistory Component Tests", () => { + test("initial render and data fetching", async () => { + mockGetPsichiatricHistory.mockResolvedValue({ + result: { + medicalHistory: { + depression: { + data: [ + { + medication: "Antidepressants", + dose: "20mg", + frequency: "Daily", + ube: true, + }, + ], + version: 1, }, - }, - }), - ); - - render( - - - , - ); - - await waitFor(() => - screen.getByText( - "¡Parece que no hay antecedentes psiquiátricos! Agrega uno en el botón de arriba.", - ), - ); - }); - - test("displays error message when there is an error fetching data", async () => { - const mockGetPsichiatricHistoryError = vi.fn(() => - Promise.resolve({ - error: { - response: { - status: 400, - statusText: "Bad Request", - data: "Invalid request parameters.", + anxiety: { + data: [ + { + medication: "Anxiolytics", + dose: "10mg", + frequency: "As needed", + ube: false, + }, + ], + version: 1, }, }, - }), - ); - - render( - - - , - ); - - await waitFor(() => - screen.getByText( - "Ha ocurrido un error en la búsqueda, ¡Por favor vuelve a intentarlo!", - ), - ); - }); + }, + }); - test("adds a new psichiatric history record", async () => { render( { , ); - await waitFor(() => screen.getByText("Agregar antecedente psiquiátrico")); - fireEvent.click(screen.getByText("Agregar antecedente psiquiátrico")); - - await waitFor(() => screen.getByText("Guardar")); - - // Completa todos los campos necesarios antes de guardar - fireEvent.change( - screen.getByPlaceholderText( - "Ingrese el medicamento administrado (terapia entra en la categoría)", - ), - { - target: { value: "New Medication" }, - }, - ); - fireEvent.change( - screen.getByPlaceholderText( - "Ingrese cuánto. Ej. 50mg (Este campo es opcional)", - ), - { - target: { value: "50mg" }, - }, - ); - fireEvent.change( - screen.getByPlaceholderText( - "Ingrese cada cuándo administra el medicamento. (Ej. Cada dos días, cada 12 horas...)", - ), - { - target: { value: "Twice daily" }, - }, - ); - fireEvent.click(screen.getByText("Si")); - - // Guarda el nuevo registro de antecedentes psiquiátricos - fireEvent.click(screen.getByText("Guardar")); - await waitFor(() => - expect(toast.success).toHaveBeenCalledWith( - "Antecedente psiquiátrico guardado con éxito.", - ), + expect( + screen.getByText("Antecedentes Psiquiátricos"), + ).toBeInTheDocument(), ); }); });