Skip to content

Commit

Permalink
token use at createEvent and added new event parameter. *Check faulty…
Browse files Browse the repository at this point in the history
… server connection front b00tc4mp#252
  • Loading branch information
itsmePo committed Jan 5, 2025
1 parent 0893f1c commit 78c7651
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 109 deletions.
132 changes: 105 additions & 27 deletions staff/borja-garcia/project/appProject/src/components/Calendar.jsx
Original file line number Diff line number Diff line change
@@ -1,62 +1,136 @@
import { useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Calendar, momentLocalizer } from "react-big-calendar";
import "react-big-calendar/lib/css/react-big-calendar.css";
import moment from "moment";
import "../styles/calendar.css"; // Archivo CSS separado para estilos
import { useAuth } from "../context/AuthContext";
import createEvent from "../logic/createEvent";

const localizer = momentLocalizer(moment);

const CalendarComponent = () => {
const navigate = useNavigate();
const [error, setError] = useState("");
const { userId } = useAuth(); // Obtiene el ID del usuario logueado
useEffect(() => {
if (!userId) {
navigate("/login");
}
}, [userId, navigate]);

const [events, setEvents] = useState([]);
const [newEvent, setNewEvent] = useState({
title: "",
start: "",
end: "",
category: "",
});

const [showForm, setShowForm] = useState(false); //Sabe si está abierto el form
const formRef = useRef(null); // Genera una referencia para saber si está abierto el form

const categories = ["Ansiedad", "Ataque de Pánico", "Autolesión", "Otro"];

const createCalendarEvent = async (
eventName,
startDateTime,
duration,
color,
category,
userId
) => {
try {
await createEvent(
eventName,
startDateTime,
duration,
color,
category,
userId
);
console.log("El evento fue creado correctamente");
setNewEvent({
eventName: "",
startDateTime: "",
duration: "",
category: "",
}); // Limpia los campos del formulario después de crear el evento
} catch (err) {
console.error("Error al crear el evento:", err);
setError(err.message || "Error al crear el evento");
}
};

const handleInputChange = (e) => {
const { name, value } = e.target;
setNewEvent((prev) => ({ ...prev, [name]: value }));
};

const handleAddEvent = () => {
if (newEvent.title && newEvent.start && newEvent.end && newEvent.category) {
const start = new Date(newEvent.start);
const end = new Date(newEvent.end);

if (end <= start) {
alert("La fecha de fin debe ser posterior a la fecha de inicio.");
return;
}

// Cálculo de duración
const durationInMs = end - start; // Diferencia en milisegundos
const durationInMinutes = Math.floor(durationInMs / (1000 * 60)); // Total de minutos
const hours = Math.floor(durationInMinutes / 60); // Horas completas
const minutes = durationInMinutes % 60; // Minutos restantes
const duration = `${hours}h ${minutes}m`; // Duración legible

// Añadir evento al estado local
setEvents((prevEvents) => [
...prevEvents,
{
title: `${newEvent.title} (${newEvent.category})`,
start: new Date(newEvent.start),
end: new Date(newEvent.end),
start,
end,
category: newEvent.category,
duration, // Añadir duración al evento
},
]);

setNewEvent({ title: "", start: "", end: "", category: "" });
setShowForm(false); // Oculta el formulario después de añadir un evento

// Crear evento en el backend
if (userId) {
createCalendarEvent(
newEvent.title,
newEvent.start,
durationInMs, // Usar la duración calculada
"red",
newEvent.category,
userId
);
} else {
setError("Inicia sesión para continuar");
}
} else {
alert("Por favor, completa todos los campos.");
}
};

const handleCloseForm = () => {
const handleCloseForm = () => {
setShowForm(false); // Oculta el formulario cuando se cierra
}
};

useEffect(() => {
useEffect(() => {
const handleClickOutside = (event) => {
if (formRef.current && !formRef.current.contains(event.target)) {
setShowForm(false); // Oculta el formulario cuando se hace click fuera del mismo
}
if (formRef.current && !formRef.current.contains(event.target)) {
setShowForm(false); // Oculta el formulario cuando se hace click fuera del mismo
}
};

const handleEscape = (event) => {
if (event.key === "Escape") {
setShowForm(false); // Oculta el formulario cuando se presiona la tecla Esc
}
if (event.key === "Escape") {
setShowForm(false); // Oculta el formulario cuando se presiona la tecla Esc
}
};

document.addEventListener("mousedown", handleClickOutside);
Expand All @@ -68,8 +142,6 @@ useEffect(() => {
};
}, []);



return (
<div style={{ padding: "20px" }}>
<h1>Mi Calendario 📅</h1>
Expand Down Expand Up @@ -155,18 +227,19 @@ useEffect(() => {
Añadir Evento
</button>
<button
onClick={handleCloseForm}
style={{
backgroundColor: "#f44336",
color: "white",
border: "none",
padding: "10px",
borderRadius: "5px",
cursor: "pointer",
}}
>
Cerrar
</button>
onClick={handleCloseForm}
style={{
backgroundColor: "#f44336",
color: "white",
border: "none",
padding: "10px",
borderRadius: "5px",
cursor: "pointer",
}}
>
Cerrar
</button>
{error && <p className="error">{error}</p>}
</div>
</div>
)}
Expand All @@ -177,7 +250,12 @@ useEffect(() => {
events={events}
startAccessor="start"
endAccessor="end"
style={{ height: "40vh", maxWidth: "400px", maxHeight: "400px", margin: "20px 0" }}
style={{
height: "40vh",
maxWidth: "400px",
maxHeight: "400px",
margin: "20px 0",
}}
messages={{
next: "Siguiente",
previous: "Anterior",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ const Login = () => {

const userLogin = async (email, password) => {
try {
const token = userAuth(email, password); // Asegúrate de que userAuth devuelva el token
login(token);
const jsonToken = await userAuth(email, password); // Asegúrate de que userAuth devuelva el token
console.log("Token Login: " + jsonToken.token);
login(jsonToken.token);
navigate("/home");
} catch (err) {
console.error("Error al iniciar sesión:", err);
Expand Down
17 changes: 15 additions & 2 deletions staff/borja-garcia/project/appProject/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,19 @@ export const AuthProvider = ({ children }) => {
sessionStorage.removeItem("token");
};

const userId = token ? jwtDecode(token).userId : null;

let userId = null;

if (token && typeof token === "string") {
try {
const decoded = jwtDecode(token);
userId = decoded.userId; // Asume que el token tiene un campo `userId`
} catch (error) {
console.error("Error al decodificar el token:", error.message);
logout(); // Limpia el token inválido
}
}

console.log(token);
return (
<AuthContext.Provider value={{ token, login, logout, userId }}>
{children}
Expand All @@ -35,3 +46,5 @@ AuthProvider.propTypes = {
export const useAuth = () => {
return useContext(AuthContext);
};

export default AuthProvider;

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import * as Errors from "../../errors";

const createEvent = async (eventName, startDateTime, duration, color, userId) => {
const createEvent = async (eventName, startDateTime, duration, color, category, userId) => {
try {
const response = await fetch(`/api/events/users/${userId}}`, {
const response = await fetch(`/api/events/users/${userId}`, {
method: "POST",
headers: {
"Content-type": "application/json",
"Authorization": `Bearer ${sessionStorage.getItem("token")}`,
},
body: JSON.stringify({ eventName, startDateTime, duration, color }),
body: JSON.stringify({ eventName, startDateTime, duration, color, category }),
});

if (!response.ok) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ router.post("/users/:userId", async (req, res) => {
startDateTime: req.body.startDateTime,
duration: req.body.duration,
color: req.body.color,
userId: req.params.userId,
category: req.body.category,
userId: req.params.userId
};

// Verifica que el usuario exista
Expand All @@ -30,7 +31,7 @@ router.post("/users/:userId", async (req, res) => {
const savedEvent = await createEvent(eventData);
await saveUserEvent(user, savedEvent); // Guarda el evento en la base de datos

res.status(201).json({ message: "Evento creado correctamente" });
res.status(200).json({ message: "Evento creado correctamente" });
} catch (error) {
res.status(500).json({ message: "Error al crear el evento" });
}
Expand Down Expand Up @@ -106,6 +107,7 @@ router.put("/:id", async (req, res) => {
startDateTime: req.body.startDateTime,
duration: req.body.duration,
color: req.body.color,
category: req.body.category
};
const modifyEventById = await updateEventById(req.params.id, updateEvent); // Busca y modifica el usuario por su ID

Expand Down
6 changes: 6 additions & 0 deletions staff/borja-garcia/project/appProjectApi/models/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ const eventSchema = new mongoose.Schema({
default: null, // Campo no requerido
match: /^#([0-9A-F]{3}){1,2}$/i, // Validación para color HEX (opcional)
},
category: {
type: String,
required: true,
enum: ['Ansiedad', 'Ataque de Pánico', 'Autolesión', 'Otro'], // Relación con la categoría del evento
default: 'Otro', // Relación por defecto si no se especifica nada
},
user: { // Relación con el modelo User
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
Expand Down

0 comments on commit 78c7651

Please sign in to comment.