Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update feature was added to allergic history #184

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 80 additions & 30 deletions sanitas_frontend/src/views/History/Allergic/index.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Suspense, useEffect, useState } from "react";
import { Suspense, useState } from "react";
import "react-toastify/dist/ReactToastify.css";
import { toast } from "react-toastify";
import BaseButton from "src/components/Button/Base/index";
Expand All @@ -9,6 +9,10 @@ import { BaseInput, RadioInput } from "src/components/Input/index";
import Throbber from "src/components/Throbber";
import { colors, fonts, fontSize } from "src/theme.mjs";
import WrapPromise from "src/utils/promiseWrapper";
import IconButton from "src/components/Button/Icon";
import CheckIcon from "@tabler/icons/outline/check.svg";
import EditIcon from "@tabler/icons/outline/edit.svg";
import CancelIcon from "@tabler/icons/outline/x.svg";

/**
* @typedef {Object} AllergicHistoryProps
Expand Down Expand Up @@ -141,6 +145,9 @@ export function AllergicHistory({
function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
const [selectedAllergie, setSelectedAllergie] = useState(null);
const [addingNew, setAddingNew] = useState(false);
const [isEditable, setIsEditable] = useState(false);

const isFirstTime = addingNew;

const allergicHistoryResult = allergicHistoryResource.read();

Expand Down Expand Up @@ -177,8 +184,6 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
(category) => Array.isArray(category.data) && category.data.length > 0,
);

useEffect(() => {}, []);

// Event handlers for adding, editing, and saving allergic history records
const handleOpenNewForm = () => {
setSelectedAllergie({
Expand All @@ -187,6 +192,7 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
reactionType: "",
});
setAddingNew(true);
setIsEditable(true);
};

// Save the new Allergic record to the database
Expand All @@ -204,39 +210,48 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {

toast.info("Guardando antecedente alérgico...");

// Crear el nuevo registro de alergia
const newAllergy = {
const updatedAllergy = {
name: selectedAllergie.whichAllergie,
severity: selectedAllergie.reactionType,
};

// Obtener la categoría actual (ej. medicamento, comida, etc.)
const currentCategoryData =
AllergicHistory[selectedAllergie.selectedMed]?.data || [];

// Si la categoría ya tiene datos, usamos su versión, de lo contrario, establecemos la versión en 1
const currentVersion =
AllergicHistory[selectedAllergie.selectedMed]?.version || 1;

// Actualizar la categoría con el nuevo registro
const updatedCategory = {
version: currentVersion,
data: [...currentCategoryData, newAllergy],
};

// Actualizar el historial médico con la nueva categoría
const updatedMedicalHistory = {
...AllergicHistory,
[selectedAllergie.selectedMed]: updatedCategory,
};
let updatedMedicalHistory;

if (isFirstTime) {
const currentCategoryData =
AllergicHistory[selectedAllergie.selectedMed]?.data || [];

const currentVersion =
AllergicHistory[selectedAllergie.selectedMed]?.version || 1;

const updatedCategory = {
version: currentVersion,
data: [...currentCategoryData, updatedAllergy],
};

updatedMedicalHistory = {
...AllergicHistory,
[selectedAllergie.selectedMed]: updatedCategory,
};
} else {
const updatedCategory = {
...AllergicHistory[selectedAllergie.selectedMed],
data: [updatedAllergy], // Reemplaza con el nuevo dato actualizado
};

updatedMedicalHistory = {
...AllergicHistory,
[selectedAllergie.selectedMed]: updatedCategory,
};
}

try {
const response = await updateAllergicHistory(id, updatedMedicalHistory);
if (!response.error) {
// Actualizar el estado con el historial médico actualizado
setAllergicHistory(updatedMedicalHistory);
setAddingNew(false);
setSelectedAllergie(null);
setIsEditable(false);
toast.success("Antecedente alérgico guardado con éxito.");
} else {
toast.error(`Error al guardar: ${response.error}`);
Expand All @@ -245,12 +260,15 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
toast.error(`Error en la operación: ${error.message}`);
}
};

const handleSelectAllergie = (allergy) => {
setSelectedAllergie({
selectedMed: allergy.selectedMed || "climateChange", // Este valor debe ser dinámico según el tipo de alergia
selectedMed: allergy.selectedMed || "climateChange",
whichAllergie: allergy.name || allergy.source || allergy.type,
reactionType: allergy.severity,
});
setIsEditable(false);
setAddingNew(false);
};

const handleFieldChange = (fieldName, value) => {
Expand Down Expand Up @@ -332,9 +350,9 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
return (
<InformationCard
key={`${category}-${allergy.name || allergy.id}`}
type="allergy" // Ajusta esto según sea necesario
disease={allergy.name || "Sin Nombre"} // Ajusta esto para reflejar correctamente la alergia
reasonInfo={allergy.severity || "Sin Severidad"} // Ajusta esto para reflejar correctamente la severidad
type="allergy"
disease={allergy.name || "Sin Nombre"}
reasonInfo={allergy.severity || "Sin Severidad"}
onClick={() =>
handleSelectAllergie({ ...allergy, selectedMed: category })
}
Expand Down Expand Up @@ -371,7 +389,7 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
<DropdownMenu
options={allergyOptions}
value={selectedAllergie?.selectedMed || "medication"}
readOnly={!addingNew}
disabled={!addingNew}
onChange={(e) => handleFieldChange("selectedMed", e.target.value)}
style={{
container: { width: "80%" },
Expand Down Expand Up @@ -401,6 +419,7 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
fontFamily: fonts.textFont,
fontSize: "1rem",
}}
disabled={!isEditable}
/>

<p
Expand All @@ -427,23 +446,54 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
checked={selectedAllergie?.reactionType === "Cutánea"}
onChange={() => handleFieldChange("reactionType", "Cutánea")}
style={{ label: { fontFamily: fonts.textFont } }}
disabled={!isEditable}
/>
<RadioInput
label="Respiratoria"
name="reactionType"
checked={selectedAllergie?.reactionType === "Respiratoria"}
onChange={() => handleFieldChange("reactionType", "Respiratoria")}
style={{ label: { fontFamily: fonts.textFont } }}
disabled={!isEditable}
/>
<RadioInput
label="Ambos"
name="reactionType"
checked={selectedAllergie?.reactionType === "Ambos"}
onChange={() => handleFieldChange("reactionType", "Ambos")}
style={{ label: { fontFamily: fonts.textFont } }}
disabled={!isEditable}
/>
</div>

<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
}}
>
<div style={{ display: "flex", justifyContent: "flex-end" }}>
{!addingNew &&
(isEditable ? (
<div style={{ display: "flex", gap: "1rem" }}>
<IconButton
icon={CheckIcon}
onClick={handleSaveNewAllergie}
/>
<IconButton
icon={CancelIcon}
onClick={() => setIsEditable(false)}
/>
</div>
) : (
<IconButton
icon={EditIcon}
onClick={() => setIsEditable(true)}
/>
))}
</div>
</div>
<div
style={{
paddingTop: "5rem",
Expand Down