From 4a28eb6d8a0919be45b6895034f3720bdbf956ae Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Fri, 5 Apr 2024 18:59:59 +0200 Subject: [PATCH 01/19] feat: FamilyForm --- src/screens/App.js | 7 +- src/screens/families/FamilyForm.js | 154 +++++++++++++++++++ src/screens/families/KidForm.js | 237 +++++++++++++++++++++++++++++ 3 files changed, 397 insertions(+), 1 deletion(-) create mode 100644 src/screens/families/FamilyForm.js create mode 100644 src/screens/families/KidForm.js diff --git a/src/screens/App.js b/src/screens/App.js index 6e733058..346a2f5a 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -62,6 +62,9 @@ import VolunteerForm from './volunteers/VolunteerForm'; //import PartnerProfile from './partners/PartnerProfile'; import PartnersCalendar from './partners/PartnersCalendar'; +// FAMILIES +import FamilyForm from './families/FamilyForm'; +import KidForm from './families/KidForm'; function App() { return ( @@ -151,7 +154,9 @@ function App() { } /> {/* FAMILIES ROUTES */} - } /> + } /> + } /> + }/> diff --git a/src/screens/families/FamilyForm.js b/src/screens/families/FamilyForm.js new file mode 100644 index 00000000..38f4b41f --- /dev/null +++ b/src/screens/families/FamilyForm.js @@ -0,0 +1,154 @@ +import React, { useEffect, useState } from 'react'; +import { ToastContainer, toast } from 'react-toastify'; +import 'react-toastify/dist/ReactToastify.css'; +import '../../styles/styles.css'; +import axios from 'axios'; +import {useNavigate} from 'react-router-dom'; +import LayoutProfiles from '../../components/LayoutProfiles'; + + +const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; + + +const FamilyForm = () => { + + + const [valoresList, setValores] = useState([]); + + const navigate = useNavigate(); + + //Traemos los datos del usuario + useEffect(() => { + + axios.get(`${API_ENDPOINT}auth/users/me/`) + .then(response => { + setValores(response.data); + }) + .catch(error => { + console.error(error); + }); + + }, []); + + //Atributos + + const [familia, setFamilia] = useState(""); + const [password, setPassword] = useState(""); + + const [surname1, setSurname1] = useState(""); + const [surname2, setSurname2] = useState(""); + + //Atributos son correctos + + const updatePut = async () => { + + try { + const postFam = { + + name: "Familia " + surname1 + " " + surname2, + + }; + + const post = await axios.post(`${API_ENDPOINT}family/`, postFam); + + + + const { data } = post; + if (data.message) { + window.alert(data.message); + } else { + } + } catch (error) { + toast.error("Datos no válidos."); + } + + axios.get(`${API_ENDPOINT}family/`) + .then(response => { + setFamilia(response.data.filter(x=>x.name==="Familia " + surname1 + " " + surname2)); + }) + .catch(error => { + console.error(error); + }); + + try { + const updatedData = { //En el caso de no darle un valor, se coge el original + last_login: valoresList.last_login, + is_superuser: valoresList.is_superuser, + first_name: valoresList.first_name, + last_name: valoresList.last_name, + is_staff: valoresList.is_staff, + is_active: valoresList.is_active, + date_joined: valoresList.date_joined, + username: valoresList.username, + id_number: valoresList.id_number, + phone: valoresList.phone, + password: password, + email: valoresList.email, + role: valoresList.role, + is_enabled: valoresList.is_enabled, + family: familia || valoresList.family, + partner: valoresList.partner, + volunteer: valoresList.volunteer, + education_center: valoresList.education_center, + educator: valoresList.educator, + groups: valoresList.groups, + user_permissions: valoresList.user_permissions, + + }; + + const update = await axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData); + + const { data } = update; + if (data.message) { + window.alert(data.message); + } else { + navigate(`/familia/perfil`); + } + } catch (error) { + toast.error("Datos no válidos."); + } + }; + + + return ( + <> + + +
+ +

Apellido 1

+ setSurname1(e.target.value)} + type='text' + placeholder='Primer Apellido' + > + +

Apellido 2

+ setSurname2(e.target.value)} + type='text' + placeholder='Segundo Apellido' + > + +

Contraseña

+ setPassword(e.target.value)} + type='password' + placeholder='Contraseña' + > + + +
+
+ + + ) + + }; + + export default FamilyForm; \ No newline at end of file diff --git a/src/screens/families/KidForm.js b/src/screens/families/KidForm.js new file mode 100644 index 00000000..66da50fb --- /dev/null +++ b/src/screens/families/KidForm.js @@ -0,0 +1,237 @@ +import '../../styles/styles.css'; +import React, { useState } from 'react'; +import axios from 'axios'; +import LayoutProfiles from '../../components/LayoutProfiles'; +import { ToastContainer, toast } from 'react-toastify'; + + +const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; + +function KidForm() { + // Se ponen todas las variables de estado de los archivos que se van a subir como null ya que son tipos especiales, al igual que imagenes, videos.... + //En un principio lo probe como "" o [] , pero esto provocaba error, pd gracias chatgpt + const [academicFormation, setAcademicFormation] = useState(""); + const [motivation, setMotivation] = useState(""); + const [address, setAddress] = useState(""); + const [postalCode, setpostalCode] = useState(""); + const [enrollmentDocument, setEnrollmentDocument] = useState(null); + const [registrySheet, setRegistrySheet] = useState(null); + const [sexualOffensesDocument, setSexualOffensesDocument] = useState(null); + const [scannedId, setScannedId] = useState(null); + const [minorAuthorization, setMinorAuthorization] = useState(null); + const [scannedAuthorizerId, setScannedAuthorizerId] = useState(null); + const [birthdate, setBirthdate] = useState(""); + const [startDate, setStartDate] = useState(""); + + const aceptarSolicitud = async (e) => { + e.preventDefault(); // Prevenir la recarga de la página + //En todos estos condicionales se comprueban que no se haga post sin introduccir todos los datos, si esto ocurre, se lanza excepción. + if (!academicFormation || academicFormation === '') { + toast.error("Debe de insertar su formación academica", { autoClose: 5000 }) + } else if (!motivation || motivation === '') { + toast.error("Debe de insertar su motivación", { autoClose: 5000 }) + } else if (!address || address === '') { + toast.error("Debe de insertar su dirección", { autoClose: 5000 }) + } else if (!postalCode || postalCode === '') { + toast.error("Debe de insertar su código postal", { autoClose: 5000 }) + } else if (!enrollmentDocument) { + toast.error("Debe de insertar el documento de enlistamiento", { autoClose: 5000 }) + } else if (!registrySheet) { + toast.error("Debe de insertar la hoja de registro", { autoClose: 5000 }) + } else if (!sexualOffensesDocument) { + toast.error("Debe de insertar el documento de ofensas sexuales", { autoClose: 5000 }) + } else if (!scannedId) { + toast.error("Debe de insertar su DNI escaneado", { autoClose: 5000 }) + } else if (!minorAuthorization) { + toast.error("Debe de insertar la documentación del menor", { autoClose: 5000 }) + } else if (!scannedAuthorizerId) { + toast.error("Debe de insertar el DNI escaneado del menor", { autoClose: 5000 }) + } else if (!birthdate || birthdate === '') { + toast.error("Debe de insertar su fecha de cumpleaños", { autoClose: 5000 }) + } else if (!startDate || startDate === '') { + toast.error("Debe de insertar la fecha de inscripción", { autoClose: 5000 }) + } else { + + //Como los archivos son tipos de datos especiales, al hacer post debemos de crear una lista de tipo form data en la que añadiremos + //todos los datos antes de enviarlos, ya que si no da error 400. + + const formData = new FormData(); + formData.append('academic_formation', academicFormation); + formData.append('motivation', motivation); + formData.append('status', 'ACEPTADO'); + formData.append('address', address); + formData.append('postal_code', postalCode); + formData.append('enrollment_document', enrollmentDocument); + formData.append('registry_sheet', registrySheet); + formData.append('sexual_offenses_document', sexualOffensesDocument); + formData.append('scanned_id', scannedId); + formData.append('minor_authorization', minorAuthorization); + formData.append('scanned_authorizer_id', scannedAuthorizerId); + formData.append('birthdate', birthdate); + formData.append('start_date', startDate); + formData.append('end_date', ''); + + try { + const update = await axios.post(`${API_ENDPOINT}volunteer/`, formData, { + headers: { + 'Content-Type': 'multipart/form-data' + // 'multipart/form-data' se pone para señalar que es el tipo especial de form en el que se subiran objetos de tipo video, archivo.... + } + }); + console.log('update', update); + const { data } = update; + if (data.message) { + toast.error(data.message); + } else { + toast.success("Usuario creado con éxito.", { autoClose: 5000 }) + } + } catch (error) { + toast.error('Error creando voluntario', { autoClose: 5000 }); + } + } + } + + const handleFileChange = (event, setStateFunc) => { + const file = event.target.files[0]; + setStateFunc(file); + } + + return ( + + + +
+
+ Formulario de Voluntarios +
+
+ Complete este breve formulario y nos pondremos en contacto con usted. +
+
+
+
+

Formación

+ setAcademicFormation(e.target.value)} + > +
+
+

Motivación

+ setMotivation(e.target.value)} + > +
+
+

Dirección

+ setAddress(e.target.value)} + > +
+
+

Código postal

+ setpostalCode(e.target.value)} + > +
+
+

Documeto de enlistamiento

+ handleFileChange(e, setEnrollmentDocument)} + > +
+
+

Hoja de registro

+ handleFileChange(e, setRegistrySheet)} + > +
+
+

Certificado de Delitos de Naturaleza Sexual

+ handleFileChange(e, setSexualOffensesDocument)} + > +
+
+

DNI escaneado

+ handleFileChange(e, setScannedId)} + > +
+
+

Autorización del menor

+ handleFileChange(e, setMinorAuthorization)} + > +
+
+

DNI del menor

+ handleFileChange(e, setScannedAuthorizerId)} + > +
+
+

Fecha de nacimiento

+ setBirthdate(e.target.value)} + > +
+
+

Hora de comienzo

+ setStartDate(e.target.value)} + > +
+
+ +
+
+
+
+ +
+ ); +} + +export default KidForm; \ No newline at end of file From 7ac292af7a952a9db9556dc46a32f706c523a3d6 Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Fri, 5 Apr 2024 19:00:21 +0200 Subject: [PATCH 02/19] fix: Profile --- src/components/Profile.js | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/components/Profile.js b/src/components/Profile.js index 1d31622d..e6116180 100644 --- a/src/components/Profile.js +++ b/src/components/Profile.js @@ -8,37 +8,42 @@ const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const Profile = ({usuario}) => { const [valores, setValores] = useState([]); + const [name, setName] = useState("") //Traemos los datos del usuario que ha iniciado sesión useEffect(() => { - axios.get(`${API_ENDPOINT}user/`) + axios.get(`${API_ENDPOINT}auth/users/me`) .then(response => { - setValores(response.data.filter(x=>x.id===parseInt(localStorage.getItem('userId'),10))); + setValores(response.data); }) .catch(error => { console.error(error); }); + setTimeout(setName(valores.first_name + " " + valores.last_name),900); }, []); + + //Mostramos los datos en inputs para censurar la contraseña return (
- {valores.map((profile, index) => ( -
- {"imagen"} + {"imagen"} + +
{valores.username}
-
{profile.username}
+

Usuario

+

Email

- +

Teléfono

- + -

Contraseña

- +

DNI/NIE/Pasaporte

+
- ))} -
); }; From fa1c826a21882dc6b702163d980255fd621edcaf Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Mon, 8 Apr 2024 14:34:01 +0200 Subject: [PATCH 03/19] fix: Profile GET & PUT --- src/components/Profile.js | 6 +----- src/components/UpdateProfile.js | 17 ++++++++++------- src/screens/App.js | 5 ++++- src/screens/families/FamilyProfile.js | 14 ++++++++++++++ src/screens/families/FamilyUpdate.js | 17 +++++++++++++++++ 5 files changed, 46 insertions(+), 13 deletions(-) create mode 100644 src/screens/families/FamilyProfile.js create mode 100644 src/screens/families/FamilyUpdate.js diff --git a/src/components/Profile.js b/src/components/Profile.js index e6116180..f00a7c21 100644 --- a/src/components/Profile.js +++ b/src/components/Profile.js @@ -8,7 +8,6 @@ const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const Profile = ({usuario}) => { const [valores, setValores] = useState([]); - const [name, setName] = useState("") //Traemos los datos del usuario que ha iniciado sesión useEffect(() => { @@ -21,7 +20,6 @@ const Profile = ({usuario}) => { console.error(error); }); - setTimeout(setName(valores.first_name + " " + valores.last_name),900); }, []); @@ -31,10 +29,8 @@ const Profile = ({usuario}) => {
{"imagen"} -
{valores.username}
-

Usuario

- +

Email

diff --git a/src/components/UpdateProfile.js b/src/components/UpdateProfile.js index 5f2cb2d2..c4bdf17b 100644 --- a/src/components/UpdateProfile.js +++ b/src/components/UpdateProfile.js @@ -12,7 +12,6 @@ const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const UpdateProfile = ({tipo}) => { const id = localStorage.getItem('userId'); - const [avatar, setAvatar] = useState(""); const [valoresList, setValores] = useState([]); @@ -21,11 +20,10 @@ const UpdateProfile = ({tipo}) => { //Traemos los datos del usuario useEffect(() => { - axios.get(`${API_ENDPOINT}user/`) + axios.get(`${API_ENDPOINT}auth/users/me/`) .then(response => { - setValores(response.data.find(x=>x.id==parseInt(id,10))); + setValores(response.data); console.log("name", name) - setAvatar(valoresList.avatar) }) .catch(error => { console.error(error); @@ -72,7 +70,7 @@ const UpdateProfile = ({tipo}) => { }; - const update = await axios.put(`${API_ENDPOINT}user/${id}/`, updatedData); + const update = await axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData); const { data } = update; if (data.message) { @@ -138,12 +136,17 @@ const UpdateProfile = ({tipo}) => { placeholder='ejemplo@gmail.com' > -

Contraseña

+ +

+ + Contraseña (obligatorio) + +

setPassword(e.target.value)} type='password' - placeholder='Contraseña' + placeholder='Contraseña de tu cuenta' > diff --git a/src/screens/App.js b/src/screens/App.js index 346a2f5a..5f5226f1 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -65,6 +65,8 @@ import PartnersCalendar from './partners/PartnersCalendar'; // FAMILIES import FamilyForm from './families/FamilyForm'; import KidForm from './families/KidForm'; +import FamilyProfile from './families/FamilyProfile'; +import FamilyUpdate from './families/FamilyUpdate'; function App() { return ( @@ -156,7 +158,8 @@ function App() { {/* FAMILIES ROUTES */} } /> } /> - }/> + }/> + }/> diff --git a/src/screens/families/FamilyProfile.js b/src/screens/families/FamilyProfile.js new file mode 100644 index 00000000..d843cde7 --- /dev/null +++ b/src/screens/families/FamilyProfile.js @@ -0,0 +1,14 @@ +import '../../styles/styles.css'; +import Profile from '../../components/Profile'; +import LayoutProfiles from '../../components/LayoutProfiles'; + +const VolunteerProfile = () => { + + return ( + + + + ); +}; + +export default VolunteerProfile; \ No newline at end of file diff --git a/src/screens/families/FamilyUpdate.js b/src/screens/families/FamilyUpdate.js new file mode 100644 index 00000000..ad06548e --- /dev/null +++ b/src/screens/families/FamilyUpdate.js @@ -0,0 +1,17 @@ +import '../../styles/styles.css'; +import UpdateProfile from '../../components/UpdateProfile'; +import LayoutProfiles from '../../components/LayoutProfiles'; + +const VolunteerProfileUpdate = () => { + + return ( + + + + + + ) + + }; + + export default VolunteerProfileUpdate; \ No newline at end of file From 6719e05ade1f32d86af33bacf2d0dd4e631de20c Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Mon, 8 Apr 2024 14:43:53 +0200 Subject: [PATCH 04/19] fix: unused constants --- src/components/UpdateProfile.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/components/UpdateProfile.js b/src/components/UpdateProfile.js index c4bdf17b..72182303 100644 --- a/src/components/UpdateProfile.js +++ b/src/components/UpdateProfile.js @@ -11,8 +11,6 @@ const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const UpdateProfile = ({tipo}) => { - const id = localStorage.getItem('userId'); - const [valoresList, setValores] = useState([]); const navigate = useNavigate(); From e5cc1e106a0487034149bb29a54c0c31b3582329 Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Mon, 8 Apr 2024 17:08:44 +0200 Subject: [PATCH 05/19] fix: Kid route --- src/screens/families/FamilyForm.js | 54 +++++++++++++----------------- 1 file changed, 23 insertions(+), 31 deletions(-) diff --git a/src/screens/families/FamilyForm.js b/src/screens/families/FamilyForm.js index 38f4b41f..5af9e366 100644 --- a/src/screens/families/FamilyForm.js +++ b/src/screens/families/FamilyForm.js @@ -51,48 +51,34 @@ const FamilyForm = () => { const post = await axios.post(`${API_ENDPOINT}family/`, postFam); + const { data } = post; + console.log("datos",data); + + setFamilia(data); - const { data } = post; if (data.message) { window.alert(data.message); - } else { } } catch (error) { toast.error("Datos no válidos."); } - axios.get(`${API_ENDPOINT}family/`) - .then(response => { - setFamilia(response.data.filter(x=>x.name==="Familia " + surname1 + " " + surname2)); - }) - .catch(error => { - console.error(error); - }); + + }; + + + const updateFam = async () => { + + console.log("familia",familia); try { const updatedData = { //En el caso de no darle un valor, se coge el original - last_login: valoresList.last_login, - is_superuser: valoresList.is_superuser, - first_name: valoresList.first_name, - last_name: valoresList.last_name, - is_staff: valoresList.is_staff, - is_active: valoresList.is_active, - date_joined: valoresList.date_joined, - username: valoresList.username, - id_number: valoresList.id_number, - phone: valoresList.phone, - password: password, + email: valoresList.email, - role: valoresList.role, - is_enabled: valoresList.is_enabled, - family: familia || valoresList.family, - partner: valoresList.partner, - volunteer: valoresList.volunteer, - education_center: valoresList.education_center, - educator: valoresList.educator, - groups: valoresList.groups, - user_permissions: valoresList.user_permissions, + password: password, + family: familia, + is_agreed: 'true', }; @@ -102,13 +88,19 @@ const FamilyForm = () => { if (data.message) { window.alert(data.message); } else { - navigate(`/familia/perfil`); + navigate(`/familia/registro/niños`); } } catch (error) { toast.error("Datos no válidos."); } }; + const update = () => { + + setTimeout(updatePut,1); + setTimeout(updateFam,1); + }; + return ( <> @@ -140,7 +132,7 @@ const FamilyForm = () => { placeholder='Contraseña' > -
From 8cd4b996188ac11aca579d0ef091b95a3259b1f6 Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Mon, 8 Apr 2024 18:10:51 +0200 Subject: [PATCH 06/19] fix: put fam id --- src/screens/families/FamilyForm.js | 81 ++++++++++++++---------------- 1 file changed, 37 insertions(+), 44 deletions(-) diff --git a/src/screens/families/FamilyForm.js b/src/screens/families/FamilyForm.js index 5af9e366..95c1569a 100644 --- a/src/screens/families/FamilyForm.js +++ b/src/screens/families/FamilyForm.js @@ -32,7 +32,7 @@ const FamilyForm = () => { //Atributos - const [familia, setFamilia] = useState(""); + const [familia, setFamilia] = useState("") const [password, setPassword] = useState(""); const [surname1, setSurname1] = useState(""); @@ -41,65 +41,58 @@ const FamilyForm = () => { //Atributos son correctos const updatePut = async () => { - try { const postFam = { - name: "Familia " + surname1 + " " + surname2, - }; const post = await axios.post(`${API_ENDPOINT}family/`, postFam); - const { data } = post; - - console.log("datos",data); - - setFamilia(data); - - if (data.message) { - window.alert(data.message); - } - } catch (error) { - toast.error("Datos no válidos."); - } - - - }; - - - const updateFam = async () => { - - console.log("familia",familia); - - try { - const updatedData = { //En el caso de no darle un valor, se coge el original - - email: valoresList.email, - password: password, - family: familia, - is_agreed: 'true', - - }; - const update = await axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData); + console.log("datos", data); + + const firstKey = Object.values(data)[0]; + console.log("Primera clave de 'data':", firstKey); - const { data } = update; if (data.message) { window.alert(data.message); } else { - navigate(`/familia/registro/niños`); + axios.get(`${API_ENDPOINT}family/${firstKey}`) + .then(response => { + const familiaData = response.data; + console.log("fam", familiaData.id); + + const updatedData = { + email: valoresList.email, + password: password, + family: familiaData.id, // Aquí se pasa el pk de la familia + is_agreed: 'true', + }; + + axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData) + .then(update => { + const { data: updatedUserData } = update; + if (updatedUserData.message) { + window.alert(updatedUserData.message); + } else { + navigate(`/familia/registro/niños`); + } + }) + .catch(error => { + toast.error("Error al actualizar los datos del usuario."); + }); + }) + .catch(error => { + console.error(error); + toast.error("Error al obtener detalles de la familia."); + }); } } catch (error) { toast.error("Datos no válidos."); } }; - - const update = () => { - - setTimeout(updatePut,1); - setTimeout(updateFam,1); - }; + + return ( @@ -132,7 +125,7 @@ const FamilyForm = () => { placeholder='Contraseña' > - From 19282216fe271c3275a2a7bc2cd57a1f0168b0e5 Mon Sep 17 00:00:00 2001 From: fracalrod3 Date: Tue, 9 Apr 2024 10:46:00 +0200 Subject: [PATCH 07/19] fix: unused constant --- src/screens/families/FamilyForm.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/screens/families/FamilyForm.js b/src/screens/families/FamilyForm.js index 95c1569a..5cdb651e 100644 --- a/src/screens/families/FamilyForm.js +++ b/src/screens/families/FamilyForm.js @@ -32,7 +32,6 @@ const FamilyForm = () => { //Atributos - const [familia, setFamilia] = useState("") const [password, setPassword] = useState(""); const [surname1, setSurname1] = useState(""); From d5602198541f5719a7b4c49223208565d485bba7 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 13 Apr 2024 16:27:31 +0200 Subject: [PATCH 08/19] fix: merge problems --- src/screens/App.js | 7 +++---- src/screens/families/FamilyProfile.js | 14 -------------- src/screens/{families => family}/FamilyForm.js | 0 src/screens/{families => family}/FamilyUpdate.js | 0 src/screens/{families => family}/KidForm.js | 0 5 files changed, 3 insertions(+), 18 deletions(-) delete mode 100644 src/screens/families/FamilyProfile.js rename src/screens/{families => family}/FamilyForm.js (100%) rename src/screens/{families => family}/FamilyUpdate.js (100%) rename src/screens/{families => family}/KidForm.js (100%) diff --git a/src/screens/App.js b/src/screens/App.js index fd04ab11..20cd514f 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -64,11 +64,10 @@ import VolunteerFormation from './volunteers/VolunteerFormation'; import PartnersCalendar from './partners/PartnersCalendar'; // FAMILIES -import FamilyForm from './families/FamilyForm'; -import KidForm from './families/KidForm'; -import FamilyProfile from './families/FamilyProfile'; -import FamilyUpdate from './families/FamilyUpdate'; +import FamilyForm from './family/FamilyForm'; +import KidForm from './family/KidForm'; import FamilyProfile from './family/FamilyProfile'; +import FamilyUpdate from './family/FamilyUpdate'; import FamilyAuths from './family/FamilyAuths'; import FamilyAuthsPending from './family/FamilyAuthsPending'; diff --git a/src/screens/families/FamilyProfile.js b/src/screens/families/FamilyProfile.js deleted file mode 100644 index d843cde7..00000000 --- a/src/screens/families/FamilyProfile.js +++ /dev/null @@ -1,14 +0,0 @@ -import '../../styles/styles.css'; -import Profile from '../../components/Profile'; -import LayoutProfiles from '../../components/LayoutProfiles'; - -const VolunteerProfile = () => { - - return ( - - - - ); -}; - -export default VolunteerProfile; \ No newline at end of file diff --git a/src/screens/families/FamilyForm.js b/src/screens/family/FamilyForm.js similarity index 100% rename from src/screens/families/FamilyForm.js rename to src/screens/family/FamilyForm.js diff --git a/src/screens/families/FamilyUpdate.js b/src/screens/family/FamilyUpdate.js similarity index 100% rename from src/screens/families/FamilyUpdate.js rename to src/screens/family/FamilyUpdate.js diff --git a/src/screens/families/KidForm.js b/src/screens/family/KidForm.js similarity index 100% rename from src/screens/families/KidForm.js rename to src/screens/family/KidForm.js From b787dbebde4d83f8a78f65544f6011bed0f5a322 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 13 Apr 2024 16:46:32 +0200 Subject: [PATCH 09/19] feat: kid forms --- src/screens/App.js | 4 +- src/screens/family/KidForm.js | 350 ++++++++++++---------------------- 2 files changed, 127 insertions(+), 227 deletions(-) diff --git a/src/screens/App.js b/src/screens/App.js index 20cd514f..42b3cfeb 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -199,13 +199,13 @@ function App() { )} {/* FAMILIES ROUTES */} + } /> + } /> {role === 'FAMILIA' && ( <> } /> } /> } /> - } /> - } /> }/> }/> diff --git a/src/screens/family/KidForm.js b/src/screens/family/KidForm.js index 66da50fb..3f4d55ff 100644 --- a/src/screens/family/KidForm.js +++ b/src/screens/family/KidForm.js @@ -1,237 +1,137 @@ +import React, { useEffect, useState } from 'react'; +import { ToastContainer, toast } from 'react-toastify'; +import 'react-toastify/dist/ReactToastify.css'; import '../../styles/styles.css'; -import React, { useState } from 'react'; import axios from 'axios'; +import {useNavigate} from 'react-router-dom'; import LayoutProfiles from '../../components/LayoutProfiles'; -import { ToastContainer, toast } from 'react-toastify'; const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; -function KidForm() { - // Se ponen todas las variables de estado de los archivos que se van a subir como null ya que son tipos especiales, al igual que imagenes, videos.... - //En un principio lo probe como "" o [] , pero esto provocaba error, pd gracias chatgpt - const [academicFormation, setAcademicFormation] = useState(""); - const [motivation, setMotivation] = useState(""); - const [address, setAddress] = useState(""); - const [postalCode, setpostalCode] = useState(""); - const [enrollmentDocument, setEnrollmentDocument] = useState(null); - const [registrySheet, setRegistrySheet] = useState(null); - const [sexualOffensesDocument, setSexualOffensesDocument] = useState(null); - const [scannedId, setScannedId] = useState(null); - const [minorAuthorization, setMinorAuthorization] = useState(null); - const [scannedAuthorizerId, setScannedAuthorizerId] = useState(null); - const [birthdate, setBirthdate] = useState(""); - const [startDate, setStartDate] = useState(""); - - const aceptarSolicitud = async (e) => { - e.preventDefault(); // Prevenir la recarga de la página - //En todos estos condicionales se comprueban que no se haga post sin introduccir todos los datos, si esto ocurre, se lanza excepción. - if (!academicFormation || academicFormation === '') { - toast.error("Debe de insertar su formación academica", { autoClose: 5000 }) - } else if (!motivation || motivation === '') { - toast.error("Debe de insertar su motivación", { autoClose: 5000 }) - } else if (!address || address === '') { - toast.error("Debe de insertar su dirección", { autoClose: 5000 }) - } else if (!postalCode || postalCode === '') { - toast.error("Debe de insertar su código postal", { autoClose: 5000 }) - } else if (!enrollmentDocument) { - toast.error("Debe de insertar el documento de enlistamiento", { autoClose: 5000 }) - } else if (!registrySheet) { - toast.error("Debe de insertar la hoja de registro", { autoClose: 5000 }) - } else if (!sexualOffensesDocument) { - toast.error("Debe de insertar el documento de ofensas sexuales", { autoClose: 5000 }) - } else if (!scannedId) { - toast.error("Debe de insertar su DNI escaneado", { autoClose: 5000 }) - } else if (!minorAuthorization) { - toast.error("Debe de insertar la documentación del menor", { autoClose: 5000 }) - } else if (!scannedAuthorizerId) { - toast.error("Debe de insertar el DNI escaneado del menor", { autoClose: 5000 }) - } else if (!birthdate || birthdate === '') { - toast.error("Debe de insertar su fecha de cumpleaños", { autoClose: 5000 }) - } else if (!startDate || startDate === '') { - toast.error("Debe de insertar la fecha de inscripción", { autoClose: 5000 }) - } else { - - //Como los archivos son tipos de datos especiales, al hacer post debemos de crear una lista de tipo form data en la que añadiremos - //todos los datos antes de enviarlos, ya que si no da error 400. - - const formData = new FormData(); - formData.append('academic_formation', academicFormation); - formData.append('motivation', motivation); - formData.append('status', 'ACEPTADO'); - formData.append('address', address); - formData.append('postal_code', postalCode); - formData.append('enrollment_document', enrollmentDocument); - formData.append('registry_sheet', registrySheet); - formData.append('sexual_offenses_document', sexualOffensesDocument); - formData.append('scanned_id', scannedId); - formData.append('minor_authorization', minorAuthorization); - formData.append('scanned_authorizer_id', scannedAuthorizerId); - formData.append('birthdate', birthdate); - formData.append('start_date', startDate); - formData.append('end_date', ''); - - try { - const update = await axios.post(`${API_ENDPOINT}volunteer/`, formData, { - headers: { - 'Content-Type': 'multipart/form-data' - // 'multipart/form-data' se pone para señalar que es el tipo especial de form en el que se subiran objetos de tipo video, archivo.... - } + +const KidForm = () => { + + + const [valoresList, setValores] = useState([]); + + const navigate = useNavigate(); + + useEffect(() => { + + axios.get(`${API_ENDPOINT}auth/users/me/`) + .then(response => { + setValores(response.data); + }) + .catch(error => { + console.error(error); }); - console.log('update', update); - const { data } = update; - if (data.message) { - toast.error(data.message); - } else { - toast.success("Usuario creado con éxito.", { autoClose: 5000 }) + + }, []); + + //Atributos + + const [password, setPassword] = useState(""); + + const [surname1, setSurname1] = useState(""); + const [surname2, setSurname2] = useState(""); + + //Atributos son correctos + + const updatePut = async () => { + try { + const postFam = { + name: "Familia " + surname1 + " " + surname2, + }; + + const post = await axios.post(`${API_ENDPOINT}family/`, postFam); + const { data } = post; + + console.log("datos", data); + + const firstKey = Object.values(data)[0]; + console.log("Primera clave de 'data':", firstKey); + + if (data.message) { + window.alert(data.message); + } else { + axios.get(`${API_ENDPOINT}family/${firstKey}`) + .then(response => { + const familiaData = response.data; + console.log("fam", familiaData.id); + + const updatedData = { + email: valoresList.email, + password: password, + family: familiaData.id, + is_agreed: 'true', + }; + + axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData) + .then(update => { + const { data: updatedUserData } = update; + if (updatedUserData.message) { + window.alert(updatedUserData.message); + } else { + navigate(`/familia/registro/niños`); + } + }) + .catch(error => { + toast.error("Error al actualizar los datos del usuario."); + }); + }) + .catch(error => { + console.error(error); + toast.error("Error al obtener detalles de la familia."); + }); + } + } catch (error) { + toast.error("Datos no válidos."); } - } catch (error) { - toast.error('Error creando voluntario', { autoClose: 5000 }); - } - } - } - - const handleFileChange = (event, setStateFunc) => { - const file = event.target.files[0]; - setStateFunc(file); - } - - return ( - - - -
-
- Formulario de Voluntarios -
-
- Complete este breve formulario y nos pondremos en contacto con usted. -
-
-
-
-

Formación

- setAcademicFormation(e.target.value)} - > -
-
-

Motivación

- setMotivation(e.target.value)} - > -
-
-

Dirección

- setAddress(e.target.value)} - > -
-
-

Código postal

- setpostalCode(e.target.value)} - > -
-
-

Documeto de enlistamiento

- handleFileChange(e, setEnrollmentDocument)} - > -
-
-

Hoja de registro

- handleFileChange(e, setRegistrySheet)} - > -
-
-

Certificado de Delitos de Naturaleza Sexual

- handleFileChange(e, setSexualOffensesDocument)} - > -
-
-

DNI escaneado

- handleFileChange(e, setScannedId)} - > -
-
-

Autorización del menor

- handleFileChange(e, setMinorAuthorization)} - > -
-
-

DNI del menor

- handleFileChange(e, setScannedAuthorizerId)} + }; + + + + + return ( + <> + + +
+ +

Apellido 1

+ setSurname1(e.target.value)} + type='text' + placeholder='Primer Apellido' > -
-
-

Fecha de nacimiento

- setBirthdate(e.target.value)} + +

Apellido 2

+ setSurname2(e.target.value)} + type='text' + placeholder='Segundo Apellido' > -
-
-

Hora de comienzo

- setStartDate(e.target.value)} + +

Contraseña

+ setPassword(e.target.value)} + type='password' + placeholder='Contraseña' > -
-
- -
- -
-
- - - ); -} - -export default KidForm; \ No newline at end of file + + +
+
+ + + ) + + }; + + export default KidForm; \ No newline at end of file From e5f75f223dcd7f9c4a75441e7b6abbfafb4a116c Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 13 Apr 2024 17:03:08 +0200 Subject: [PATCH 10/19] fix: kid form --- src/screens/family/KidForm.js | 399 +++++++++++++++++++++++----------- 1 file changed, 277 insertions(+), 122 deletions(-) diff --git a/src/screens/family/KidForm.js b/src/screens/family/KidForm.js index 3f4d55ff..44f35b2a 100644 --- a/src/screens/family/KidForm.js +++ b/src/screens/family/KidForm.js @@ -1,137 +1,292 @@ -import React, { useEffect, useState } from 'react'; -import { ToastContainer, toast } from 'react-toastify'; -import 'react-toastify/dist/ReactToastify.css'; import '../../styles/styles.css'; +import React, { useEffect, useState } from 'react'; import axios from 'axios'; -import {useNavigate} from 'react-router-dom'; +import { toast, ToastContainer } from 'react-toastify'; +import 'react-toastify/dist/ReactToastify.css'; +import { useNavigate } from 'react-router-dom'; +import useToken from '../../components/useToken'; import LayoutProfiles from '../../components/LayoutProfiles'; - +import { fetchMyFamilyId } from '../../components/useFetchData'; const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; +function KidForm() { + const [token, updateToken] = useToken(); + const config = { + headers: { + 'Content-Type': 'multipart/form-data', + 'Authorization': `Bearer ${token}`, + } + }; -const KidForm = () => { + useEffect(() => { + window.scrollTo(0, 0); + }, []); + const navigate = useNavigate(); - const [valoresList, setValores] = useState([]); + const [formData, setFormData] = useState({ + name: '', + surname: '', + currentEducationYear: '', + tutor: '', + nationality: '', + birthdate: '', + isMorning: '', + enrollmentDoc: null, + sanitaryCard: null + }); - const navigate = useNavigate(); + const errorsDefault = { + name: '', + surname: '', + currentEducationYear: '', + tutor: '', + nationality: '', + birthdate: '', + isMorning: '', + enrollmentDoc: '', + sanitaryCard: '' + } + const [formDataErrors, setFormDataErrors] = useState(errorsDefault); - useEffect(() => { + const validateFormData = () => { + let errorsMsg = errorsDefault; + let errors = false; - axios.get(`${API_ENDPOINT}auth/users/me/`) - .then(response => { - setValores(response.data); - }) - .catch(error => { - console.error(error); - }); + Object.keys(formData).forEach((key) => { + if (formData[key] === '' || formData[key] === null) { + errors = true; + errorsMsg = { + ...errorsMsg, + [key]: `${key} es obligatorio` + } + } + }); - }, []); - - //Atributos - - const [password, setPassword] = useState(""); - - const [surname1, setSurname1] = useState(""); - const [surname2, setSurname2] = useState(""); - - //Atributos son correctos - - const updatePut = async () => { - try { - const postFam = { - name: "Familia " + surname1 + " " + surname2, - }; - - const post = await axios.post(`${API_ENDPOINT}family/`, postFam); - const { data } = post; - - console.log("datos", data); - - const firstKey = Object.values(data)[0]; - console.log("Primera clave de 'data':", firstKey); - - if (data.message) { - window.alert(data.message); - } else { - axios.get(`${API_ENDPOINT}family/${firstKey}`) - .then(response => { - const familiaData = response.data; - console.log("fam", familiaData.id); - - const updatedData = { - email: valoresList.email, - password: password, - family: familiaData.id, - is_agreed: 'true', - }; - - axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData) - .then(update => { - const { data: updatedUserData } = update; - if (updatedUserData.message) { - window.alert(updatedUserData.message); - } else { - navigate(`/familia/registro/niños`); - } - }) - .catch(error => { - toast.error("Error al actualizar los datos del usuario."); - }); - }) - .catch(error => { - console.error(error); - toast.error("Error al obtener detalles de la familia."); - }); - } - } catch (error) { - toast.error("Datos no válidos."); + if (formData.birthdate !== '') { + const actualDate = new Date(); + const date = new Date(formData.birthdate); + if (date >= actualDate) { + errors = true; + errorsMsg = { + ...errorsMsg, + birthdate: 'La fecha de nacimiento debe ser anterior a la fecha actual' } - }; - - - - - return ( - <> - - -
- -

Apellido 1

- setSurname1(e.target.value)} - type='text' - placeholder='Primer Apellido' - > - -

Apellido 2

- setSurname2(e.target.value)} - type='text' - placeholder='Segundo Apellido' - > - -

Contraseña

- setPassword(e.target.value)} - type='password' - placeholder='Contraseña' - > - - -
-
- - - ) - + } + } + + return { errors, errorsMsg }; + } + + const createKidData = () => { + const kidData = new FormData(); + Object.keys(formData).forEach((key) => { + kidData.append(key, formData[key]); + }); + kidData.append('is_morning_student', formData.isMorning === 'TARDE' ? false: true); + return kidData; + } + + const handleSubmit = async (e) => { + e.preventDefault(); + + setFormDataErrors(errorsDefault); + + const { errors, errorsMsg } = validateFormData(); + + if(errors) { + setFormDataErrors(errorsMsg); + return; + } + + const kidData = createKidData(); + + let id = localStorage.getItem('familyId'); + + if (id === null) { + console.log("Fetching family id...") + const response = await fetchMyFamilyId(API_ENDPOINT, null); + + if (response !== null) { + localStorage.setItem('familyId', response); + console.log("Family id:",response); + id = response; + } + else { + console.error("Failed to get family id"); + } + } + + kidData.append('family', id); + + try { + console.log(formData); + const response = await axios.post(`${API_ENDPOINT}student/`, kidData, config); + console.log(response.data); + toast.success('Hijo registrado con éxito'); + + setTimeout(() => { + navigate('/familia/niños'); + }, 2000); + } catch (error) { + if (error.response && error.response.data) { + // If the error response and data exist, show the error message from the backend + Object.entries(error.response.data).forEach(([key, value]) => { + toast.error(`${value}`); + }); + } else { + // If the error response or data doesn't exist, show a generic error message + toast.error('Error creating student'); + } + + //Delete localstorage in case its not valid + localStorage.removeItem('familyId'); + } }; - - export default KidForm; \ No newline at end of file + + return ( + + +
+ + + setFormData({ + ...formData, + name: e.target.value + })} + /> + {formDataErrors.name &&
{formDataErrors.name}
} + + + setFormData({ + ...formData, + surname: e.target.value + })} + /> + {formDataErrors.surname &&
{formDataErrors.surname}
} + + + setFormData({ + ...formData, + birthdate: e.target.value + })} + /> + {formDataErrors.birthdate &&
{formDataErrors.birthdate}
} + + + setFormData({ + ...formData, + tutor: e.target.value + })} + /> + {formDataErrors.tutor &&
{formDataErrors.tutor}
} + + + + {formDataErrors.currentEducationYear &&
{formDataErrors.currentEducationYear}
} + + + setFormData({ + ...formData, + nationality: e.target.value + })} + /> + {formDataErrors.nationality &&
{formDataErrors.nationality}
} + + + + {formDataErrors.isMorning &&
{formDataErrors.isMorning}
} + + +
+ setFormData({ + ...formData, + enrollmentDoc: e.target.files[0] + })} + /> +
+ {formDataErrors.enrollmentDoc &&
{formDataErrors.enrollmentDoc}
} + + +
+ setFormData({ + ...formData, + sanitaryCard: e.target.files[0] + })} + /> +
+ {formDataErrors.sanitaryCard &&
{formDataErrors.sanitaryCard}
} + + +
+
+ ); +} + +export default KidForm; \ No newline at end of file From 4fce451805688fed35357e19f25f6075af820e32 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Thu, 18 Apr 2024 13:15:03 +0200 Subject: [PATCH 11/19] fix: urls --- src/screens/App.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/screens/App.js b/src/screens/App.js index 379dfbdb..f03ddb24 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -212,14 +212,13 @@ function App() { )} {/* FAMILIES ROUTES */} - } /> - } /> {role === 'FAMILIA' && ( <> + } /> + } /> } /> } /> } /> - }/> }/> } /> From 0b05cc3341c39b1f59332bf7a1d382b1e05726c7 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Fri, 19 Apr 2024 19:27:37 +0200 Subject: [PATCH 12/19] fix: Redirection to registry --- src/screens/family/FamilyForm.js | 14 +++++++++++--- src/screens/homepage/LogIn.js | 12 ++++++------ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index 5cdb651e..bf451de1 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -5,6 +5,7 @@ import '../../styles/styles.css'; import axios from 'axios'; import {useNavigate} from 'react-router-dom'; import LayoutProfiles from '../../components/LayoutProfiles'; +import useToken from '../../components/useToken'; const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; @@ -12,6 +13,13 @@ const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const FamilyForm = () => { + const [token, updateToken] = useToken(); + const config = { + headers: { + 'Authorization': `Bearer ${token}`, + } + }; + const [valoresList, setValores] = useState([]); @@ -20,7 +28,7 @@ const FamilyForm = () => { //Traemos los datos del usuario useEffect(() => { - axios.get(`${API_ENDPOINT}auth/users/me/`) + axios.get(`${API_ENDPOINT}auth/users/me/`, config) .then(response => { setValores(response.data); }) @@ -45,7 +53,7 @@ const FamilyForm = () => { name: "Familia " + surname1 + " " + surname2, }; - const post = await axios.post(`${API_ENDPOINT}family/`, postFam); + const post = await axios.post(`${API_ENDPOINT}family/`, config, postFam); const { data } = post; console.log("datos", data); @@ -68,7 +76,7 @@ const FamilyForm = () => { is_agreed: 'true', }; - axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData) + axios.put(`${API_ENDPOINT}auth/users/me/`, config, updatedData) .then(update => { const { data: updatedUserData } = update; if (updatedUserData.message) { diff --git a/src/screens/homepage/LogIn.js b/src/screens/homepage/LogIn.js index 5374f916..4fa43a25 100644 --- a/src/screens/homepage/LogIn.js +++ b/src/screens/homepage/LogIn.js @@ -8,6 +8,7 @@ import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import useToken from '../../components/useToken'; import RoleContext from '../../components/RoleContext'; +import { Api } from '@mui/icons-material'; const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT @@ -134,12 +135,11 @@ function LogIn() { } else if (user.role === 'FAMILIA') { localStorage.setItem('role', 'FAMILIA') setRole(user.role) - - //TODO Aqui formulario para educador, una cosa así: - //if (user.educador === null) { - // navigate('/educador/formulario');} - navigate('/familia/evaluacion/diaria/0'); - + if(user.family === null){ + navigate('/familia/registro'); + } else { + navigate('/familia/evaluacion/diaria/0'); + } } else if (user.role === 'SOCIO') { localStorage.setItem('role', 'SOCIO') From fd5d45f59459fa1e5c2005ea14a0264c7c20a981 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Fri, 19 Apr 2024 19:32:11 +0200 Subject: [PATCH 13/19] fix: duplicated file --- src/screens/family/KidForm.js | 292 ---------------------------------- 1 file changed, 292 deletions(-) delete mode 100644 src/screens/family/KidForm.js diff --git a/src/screens/family/KidForm.js b/src/screens/family/KidForm.js deleted file mode 100644 index 44f35b2a..00000000 --- a/src/screens/family/KidForm.js +++ /dev/null @@ -1,292 +0,0 @@ -import '../../styles/styles.css'; -import React, { useEffect, useState } from 'react'; -import axios from 'axios'; -import { toast, ToastContainer } from 'react-toastify'; -import 'react-toastify/dist/ReactToastify.css'; -import { useNavigate } from 'react-router-dom'; -import useToken from '../../components/useToken'; -import LayoutProfiles from '../../components/LayoutProfiles'; -import { fetchMyFamilyId } from '../../components/useFetchData'; - -const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; - -function KidForm() { - const [token, updateToken] = useToken(); - const config = { - headers: { - 'Content-Type': 'multipart/form-data', - 'Authorization': `Bearer ${token}`, - } - }; - - useEffect(() => { - window.scrollTo(0, 0); - }, []); - - const navigate = useNavigate(); - - const [formData, setFormData] = useState({ - name: '', - surname: '', - currentEducationYear: '', - tutor: '', - nationality: '', - birthdate: '', - isMorning: '', - enrollmentDoc: null, - sanitaryCard: null - }); - - const errorsDefault = { - name: '', - surname: '', - currentEducationYear: '', - tutor: '', - nationality: '', - birthdate: '', - isMorning: '', - enrollmentDoc: '', - sanitaryCard: '' - } - const [formDataErrors, setFormDataErrors] = useState(errorsDefault); - - const validateFormData = () => { - let errorsMsg = errorsDefault; - let errors = false; - - Object.keys(formData).forEach((key) => { - if (formData[key] === '' || formData[key] === null) { - errors = true; - errorsMsg = { - ...errorsMsg, - [key]: `${key} es obligatorio` - } - } - }); - - if (formData.birthdate !== '') { - const actualDate = new Date(); - const date = new Date(formData.birthdate); - if (date >= actualDate) { - errors = true; - errorsMsg = { - ...errorsMsg, - birthdate: 'La fecha de nacimiento debe ser anterior a la fecha actual' - } - } - } - - return { errors, errorsMsg }; - } - - const createKidData = () => { - const kidData = new FormData(); - Object.keys(formData).forEach((key) => { - kidData.append(key, formData[key]); - }); - kidData.append('is_morning_student', formData.isMorning === 'TARDE' ? false: true); - return kidData; - } - - const handleSubmit = async (e) => { - e.preventDefault(); - - setFormDataErrors(errorsDefault); - - const { errors, errorsMsg } = validateFormData(); - - if(errors) { - setFormDataErrors(errorsMsg); - return; - } - - const kidData = createKidData(); - - let id = localStorage.getItem('familyId'); - - if (id === null) { - console.log("Fetching family id...") - const response = await fetchMyFamilyId(API_ENDPOINT, null); - - if (response !== null) { - localStorage.setItem('familyId', response); - console.log("Family id:",response); - id = response; - } - else { - console.error("Failed to get family id"); - } - } - - kidData.append('family', id); - - try { - console.log(formData); - const response = await axios.post(`${API_ENDPOINT}student/`, kidData, config); - console.log(response.data); - toast.success('Hijo registrado con éxito'); - - setTimeout(() => { - navigate('/familia/niños'); - }, 2000); - } catch (error) { - if (error.response && error.response.data) { - // If the error response and data exist, show the error message from the backend - Object.entries(error.response.data).forEach(([key, value]) => { - toast.error(`${value}`); - }); - } else { - // If the error response or data doesn't exist, show a generic error message - toast.error('Error creating student'); - } - - //Delete localstorage in case its not valid - localStorage.removeItem('familyId'); - } - }; - - return ( - - -
- - - setFormData({ - ...formData, - name: e.target.value - })} - /> - {formDataErrors.name &&
{formDataErrors.name}
} - - - setFormData({ - ...formData, - surname: e.target.value - })} - /> - {formDataErrors.surname &&
{formDataErrors.surname}
} - - - setFormData({ - ...formData, - birthdate: e.target.value - })} - /> - {formDataErrors.birthdate &&
{formDataErrors.birthdate}
} - - - setFormData({ - ...formData, - tutor: e.target.value - })} - /> - {formDataErrors.tutor &&
{formDataErrors.tutor}
} - - - - {formDataErrors.currentEducationYear &&
{formDataErrors.currentEducationYear}
} - - - setFormData({ - ...formData, - nationality: e.target.value - })} - /> - {formDataErrors.nationality &&
{formDataErrors.nationality}
} - - - - {formDataErrors.isMorning &&
{formDataErrors.isMorning}
} - - -
- setFormData({ - ...formData, - enrollmentDoc: e.target.files[0] - })} - /> -
- {formDataErrors.enrollmentDoc &&
{formDataErrors.enrollmentDoc}
} - - -
- setFormData({ - ...formData, - sanitaryCard: e.target.files[0] - })} - /> -
- {formDataErrors.sanitaryCard &&
{formDataErrors.sanitaryCard}
} - - -
-
- ); -} - -export default KidForm; \ No newline at end of file From 401cc26858fbb5e0f61fa37739a106a03feb6987 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Fri, 19 Apr 2024 19:33:21 +0200 Subject: [PATCH 14/19] fix: route duplicated --- src/screens/App.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/screens/App.js b/src/screens/App.js index d0073933..3b0f9d36 100644 --- a/src/screens/App.js +++ b/src/screens/App.js @@ -68,7 +68,6 @@ import PartnersCalendar from './partners/PartnersCalendar'; // FAMILIES import FamilyForm from './family/FamilyForm'; -import KidForm from './family/KidForm'; import FamilyProfile from './family/FamilyProfile'; import FamilyUpdate from './family/FamilyUpdate'; import FamilyChildren from './family/FamilyChildren'; @@ -226,7 +225,6 @@ function App() { {role === 'FAMILIA' && ( <> } /> - } /> } /> } /> } /> From 5940cc566566433a7c6adf1de149b5b9c88b6828 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 20 Apr 2024 12:33:26 +0200 Subject: [PATCH 15/19] fix: add correct tokens --- src/screens/family/FamilyForm.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index bf451de1..bb9b5c67 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -53,7 +53,7 @@ const FamilyForm = () => { name: "Familia " + surname1 + " " + surname2, }; - const post = await axios.post(`${API_ENDPOINT}family/`, config, postFam); + const post = await axios.post(`${API_ENDPOINT}family/`, postFam, config); const { data } = post; console.log("datos", data); @@ -64,7 +64,7 @@ const FamilyForm = () => { if (data.message) { window.alert(data.message); } else { - axios.get(`${API_ENDPOINT}family/${firstKey}`) + axios.get(`${API_ENDPOINT}family/${firstKey}`, config) .then(response => { const familiaData = response.data; console.log("fam", familiaData.id); @@ -76,14 +76,11 @@ const FamilyForm = () => { is_agreed: 'true', }; - axios.put(`${API_ENDPOINT}auth/users/me/`, config, updatedData) + axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData, config) .then(update => { const { data: updatedUserData } = update; - if (updatedUserData.message) { - window.alert(updatedUserData.message); - } else { - navigate(`/familia/registro/niños`); - } + window.alert(updatedUserData.message); + navigate('/familia/perfil'); }) .catch(error => { toast.error("Error al actualizar los datos del usuario."); @@ -97,6 +94,7 @@ const FamilyForm = () => { } catch (error) { toast.error("Datos no válidos."); } + navigate('/familia/perfil'); }; From 2bc7fe6f21c7450ad586f468877ce3e7b83b75c0 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 20 Apr 2024 16:33:42 +0200 Subject: [PATCH 16/19] fix: password and message --- src/screens/family/FamilyForm.js | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index bb9b5c67..fa81d479 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -39,9 +39,6 @@ const FamilyForm = () => { }, []); //Atributos - - const [password, setPassword] = useState(""); - const [surname1, setSurname1] = useState(""); const [surname2, setSurname2] = useState(""); @@ -56,13 +53,10 @@ const FamilyForm = () => { const post = await axios.post(`${API_ENDPOINT}family/`, postFam, config); const { data } = post; - console.log("datos", data); - const firstKey = Object.values(data)[0]; - console.log("Primera clave de 'data':", firstKey); if (data.message) { - window.alert(data.message); + console.error(data.message); } else { axios.get(`${API_ENDPOINT}family/${firstKey}`, config) .then(response => { @@ -71,7 +65,6 @@ const FamilyForm = () => { const updatedData = { email: valoresList.email, - password: password, family: familiaData.id, // Aquí se pasa el pk de la familia is_agreed: 'true', }; @@ -79,7 +72,6 @@ const FamilyForm = () => { axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData, config) .then(update => { const { data: updatedUserData } = update; - window.alert(updatedUserData.message); navigate('/familia/perfil'); }) .catch(error => { @@ -122,14 +114,6 @@ const FamilyForm = () => { placeholder='Segundo Apellido' > -

Contraseña

- setPassword(e.target.value)} - type='password' - placeholder='Contraseña' - > - From 33d18ea7283eba54c4e16d937133a4c75c867333 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 20 Apr 2024 18:01:59 +0200 Subject: [PATCH 17/19] fix: first last name, second last name and title added --- src/screens/family/FamilyForm.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index fa81d479..f5167f48 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -97,8 +97,10 @@ const FamilyForm = () => {
+ +

Formulario de Familiares

-

Apellido 1

+

Primer Apellido

setSurname1(e.target.value)} @@ -106,7 +108,7 @@ const FamilyForm = () => { placeholder='Primer Apellido' > -

Apellido 2

+

Segundo Apellido

setSurname2(e.target.value)} From 2799538639ccf096b06ba73b949f0a11d4300946 Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 20 Apr 2024 18:24:43 +0200 Subject: [PATCH 18/19] fix: error password required in update user --- src/screens/family/FamilyForm.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index f5167f48..60069b85 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -6,13 +6,13 @@ import axios from 'axios'; import {useNavigate} from 'react-router-dom'; import LayoutProfiles from '../../components/LayoutProfiles'; import useToken from '../../components/useToken'; +import { Password } from '@mui/icons-material'; const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT; const FamilyForm = () => { - const [token, updateToken] = useToken(); const config = { headers: { @@ -20,8 +20,7 @@ const FamilyForm = () => { } }; - - const [valoresList, setValores] = useState([]); + const [user, setUser] = useState([]); const navigate = useNavigate(); @@ -30,7 +29,7 @@ const FamilyForm = () => { axios.get(`${API_ENDPOINT}auth/users/me/`, config) .then(response => { - setValores(response.data); + setUser(response.data); }) .catch(error => { console.error(error); @@ -64,17 +63,22 @@ const FamilyForm = () => { console.log("fam", familiaData.id); const updatedData = { - email: valoresList.email, + password: user.password, family: familiaData.id, // Aquí se pasa el pk de la familia - is_agreed: 'true', + email: user.email, }; - + + console.log("fam", familiaData.id); + console.log("updatedData", updatedData); + console.log("config", config); + axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData, config) .then(update => { const { data: updatedUserData } = update; navigate('/familia/perfil'); }) .catch(error => { + console.log(error); toast.error("Error al actualizar los datos del usuario."); }); }) From 51b40172ea2c8a49f7ec645ca3f52ea8c300f54f Mon Sep 17 00:00:00 2001 From: manbarjim2 <80253313+manbarjim2@users.noreply.github.com> Date: Sat, 20 Apr 2024 19:06:24 +0200 Subject: [PATCH 19/19] =?UTF-8?q?fix:=20toast=20success,=20screen=20withou?= =?UTF-8?q?t=20headers=20and=20side=20menu,=20redirect=20to=20"ni=C3=B1os"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/screens/family/FamilyForm.js | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/screens/family/FamilyForm.js b/src/screens/family/FamilyForm.js index 60069b85..7e693c1b 100644 --- a/src/screens/family/FamilyForm.js +++ b/src/screens/family/FamilyForm.js @@ -67,20 +67,18 @@ const FamilyForm = () => { family: familiaData.id, // Aquí se pasa el pk de la familia email: user.email, }; - - console.log("fam", familiaData.id); - console.log("updatedData", updatedData); - console.log("config", config); axios.put(`${API_ENDPOINT}auth/users/me/`, updatedData, config) - .then(update => { - const { data: updatedUserData } = update; - navigate('/familia/perfil'); - }) - .catch(error => { - console.log(error); - toast.error("Error al actualizar los datos del usuario."); - }); + .then(update => { + const { data: updatedUserData } = update; + navigate('/familia/niños'); + toast.success("Familia creada correctamente."); + }) + .catch(error => { + console.log(error); + toast.error("Error al actualizar los datos del usuario."); + }); + }) .catch(error => { console.error(error); @@ -90,7 +88,6 @@ const FamilyForm = () => { } catch (error) { toast.error("Datos no válidos."); } - navigate('/familia/perfil'); }; @@ -98,7 +95,6 @@ const FamilyForm = () => { return ( <> -
@@ -124,7 +120,6 @@ const FamilyForm = () => { Proceder
-
)