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 3 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
107 changes: 83 additions & 24 deletions sanitas_frontend/src/views/History/Allergic/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,7 +184,7 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
(category) => Array.isArray(category.data) && category.data.length > 0,
);

useEffect(() => {}, []);
useEffect(() => { }, []);
DanielDubon marked this conversation as resolved.
Show resolved Hide resolved

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

// Save the new Allergic record to the database
Expand All @@ -204,39 +212,53 @@ 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],
};
let updatedMedicalHistory;

if (isFirstTime) {
// Si es la primera vez, agrega un nuevo registro
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 {
// Si estamos editando, reemplaza directamente los datos de la categoría seleccionada
const updatedCategory = {
...AllergicHistory[selectedAllergie.selectedMed],
data: [updatedAllergy], // Reemplaza con el nuevo dato actualizado
};

// Actualiza todo el historial médico con la categoría seleccionada actualizada
updatedMedicalHistory = {
...AllergicHistory,
[selectedAllergie.selectedMed]: updatedCategory,
};
}

// Actualizar el historial médico con la nueva categoría
const 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);
setAllergicHistory(updatedMedicalHistory); // Actualiza el estado local
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 +267,17 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
toast.error(`Error en la operación: ${error.message}`);
}
};

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

};

const handleFieldChange = (fieldName, value) => {
Expand Down Expand Up @@ -371,7 +398,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 +428,7 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
fontFamily: fonts.textFont,
fontSize: "1rem",
}}
disabled={!isEditable}
/>

<p
Expand All @@ -427,20 +455,23 @@ 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>

Expand All @@ -451,6 +482,34 @@ function AllergicView({ id, allergicHistoryResource, updateAllergicHistory }) {
justifyContent: "center",
}}
>
<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>
{addingNew && (
<>
<BaseButton
Expand Down
Loading