Skip to content
Open
Show file tree
Hide file tree
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
22 changes: 7 additions & 15 deletions app/src/components/pages/CalendarioIncontri.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// Updated CalendarioIncontri.js with Edit and Delete
import React, { useState, useEffect } from 'react';
import Header from "@/components/ui/header";
import { Link } from 'react-router-dom';
import { Button } from "@/components/ui/button";
import { fetchMeetingsForMentor, filterDaysWithMeetings, updateMeeting, deleteMeeting } from "@/dao/meetingsDAO"
import { useParams } from 'react-router-dom';
import { useAuth } from '@/auth/auth-context';

const CalendarioIncontri = () => {
Expand All @@ -13,12 +11,10 @@ const CalendarioIncontri = () => {
const [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [currentYear, setCurrentYear] = useState(new Date().getFullYear());
const [editingMeeting, setEditingMeeting] = useState(null);
const { meetingId } = useParams();
const {userId} = useAuth();
const {userId,nome,cognome} = useAuth();
const fetchMeetings = async () => {
try {
const fetchedMeetings = await fetchMeetingsForMentor(userId);
console.log('Incontri recuperati:', fetchedMeetings);
setMeetings(fetchedMeetings);
} catch (error) {
alert("Errore durante il recupero degli incontri.");
Expand All @@ -31,27 +27,23 @@ const CalendarioIncontri = () => {
};

const handleSaveEdit = async (updatedMeeting) => {
console.log("Tentativo di aggiornamento:", updatedMeeting);
try {
await updateMeeting(updatedMeeting.id, updatedMeeting);
await updateMeeting(updatedMeeting, updatedMeeting.menteeId,userId,nome,cognome);
setMeetings((prevMeetings) =>
prevMeetings.map((m) => (m.id === updatedMeeting.id ? updatedMeeting : m))
);
setEditingMeeting(null);
console.log("Incontro aggiornato con successo.");
} catch (error) {
console.error("Errore:", error);
alert("Errore durante la modifica degli incontri.");
}
};

const handleDelete = async (meetingId) => {
console.log("Tentativo di eliminazione incontro con ID:", meetingId);
const handleDelete = async (meetingId,menteeId) => {
try {
await deleteMeeting(meetingId);
console.log("Incontro eliminato con successo.");
await deleteMeeting(meetingId,menteeId,userId,nome,cognome);
setMeetings((prevMeetings) => prevMeetings.filter((m) => m.id !== meetingId));
} catch (error) {
console.error("Errore:", error);
alert("Errore durante l'eliminazione degli incontri.");
}
};

Expand Down Expand Up @@ -262,7 +254,7 @@ const CalendarioIncontri = () => {
Modifica
</Button>
<Button
onClick={() => handleDelete(meeting.id)}
onClick={() => handleDelete(meeting.id,meeting.menteeId)}
style={{
backgroundColor: '#EF4444',
color: 'white',
Expand Down
2 changes: 0 additions & 2 deletions app/src/components/pages/CalendarioIncontriMentee.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ const CalendarioIncontri = () => {
try {
// Recuperiamo i meeting per il mentee
const fetchedMeetings = await fetchMeetingsForMentee(userId);
console.log("Dati recuperati:", fetchedMeetings); // 👀 Debug
setMeetings(fetchedMeetings);
} catch (error) {
alert("Errore durante il recupero degli incontri.");
console.error(error);
}
};

Expand Down
15 changes: 3 additions & 12 deletions app/src/components/pages/MeetingScheduler.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { getMentees, createMeeting } from "@/dao/meetingsDAO";
import Header from "@/components/ui/header";
import { useAuth } from '@/auth/auth-context';
const MeetingScheduler = () => {
const [user, setUser] = useState(null);
const [mentees, setMentees] = useState([]);
const [formData, setFormData] = useState({
date: '',
Expand All @@ -15,23 +14,19 @@ const MeetingScheduler = () => {
});
const {userId} = useAuth();
const {nome} = useAuth();
const {cognome} = useAuth();
// Controllo se l'utente è un mentor e recupero i partecipanti (mentees)
useEffect(() => {
const fetchMenteesData = async () => {
try {
const menteesList = await getMentees();
setMentees(menteesList);
} catch (error) {
console.error('Errore durante il recupero dei mentee:', error);
allert('Errore durante il recupero dei mentee:');
}
};

fetchMenteesData();

// Se non c'è nessun listener da disattivare, rimuovi il return
return () => {
console.log("Cleanup eseguito, ma non c'è nessun listener da disattivare.");
};
}, []);

// Funzione per convalidare il form
Expand Down Expand Up @@ -65,10 +60,6 @@ const MeetingScheduler = () => {
alert('Partecipante non trovato');
return;
}

// Log dei dati del partecipante per debug
console.log('Dati del partecipante selezionato:', selectedParticipant);

// Verifica che tutti i dati necessari siano disponibili
if (!selectedParticipant.nome || !selectedParticipant.email) {
alert('I dati del partecipante sono incompleti');
Expand All @@ -86,6 +77,7 @@ const MeetingScheduler = () => {
description: formData.description,
mentorId: userId, // Assicurati che `user.uid` sia definito
mentorName: nome,
mentorSurname: cognome,
menteeId: selectedParticipant.id, // Questo dovrebbe essere l'ID del mentee
menteeName: selectedParticipant.nome, // Usa 'nome' invece di 'name'
menteeEmail: selectedParticipant.email,
Expand All @@ -95,7 +87,6 @@ const MeetingScheduler = () => {
await createMeeting(newMeeting);
alert('Incontro programmato con successo');
} catch (error) {
console.error('Errore nella programmazione dell\'incontro: ', error);
alert('Impossibile programmare l\'incontro');
}
} else {
Expand Down
6 changes: 1 addition & 5 deletions app/src/components/pages/meeting-summary.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,16 @@ import { Button } from "@/components/ui/button";

function MeetingSummary() {
const { meetingid } = useParams(); // Ottiene l'ID del meeting dai parametri dell'URL
console.log("ID:" + meetingid)
const [meeting, setMeeting] = useState(null); // Stato per i dati del meeting
const [loading, setLoading] = useState(true); // Stato per il caricamento
const [error, setError] = useState(null); // Stato per eventuali errori
const [successMessage, setSuccessMessage] = useState(""); // Stato per il messaggio di successo

const location = useLocation();
console.log('Location:', location); // Stampa l'intero URL e il pathname

useEffect(() => {
const fetchMeeting = async () => {
try {
const meetingData = await fetchMeetingDetails(meetingid); // Recupera i dettagli del meeting
console.log("ID:" + meetingid)
setMeeting(meetingData); // Aggiorna lo stato con i dati del meeting
} catch (err) {
setError(err.message); // Gestisce eventuali errori
Expand All @@ -36,7 +32,7 @@ function MeetingSummary() {
await updateMeetingMinutes(meetingid, minuta); // Aggiorna le note del meeting
setSuccessMessage("Informazioni salvate con successo!");
} catch (err) {
console.error("Errore nel salvataggio delle note:", err);
alert("Errore nel salvataggio delle note.");
}
};

Expand Down
2 changes: 1 addition & 1 deletion app/src/components/pages/meeting-summaryformentee.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,4 @@ function MeetingSummaryMentee() {
);
}

export default MeetingSummaryMentee;
export default MeetingSummaryMentee;
5 changes: 2 additions & 3 deletions app/src/components/pages/mentee-statistics.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { useAuth } from "@/auth/auth-context";
export default function Statistics() {
const [user, setUser] = useState(null);
const [meetingsCount, setMeetingsCount] = useState(0);
const navigate = useNavigate();
const { userId } = useAuth();

useEffect(() => {
Expand All @@ -18,7 +17,7 @@ export default function Statistics() {
setUser(userData); // Salva i dati dell'utente
setMeetingsCount(userData.meetingsCount || 0); // Ottieni il meetingsCount (default a 0 se non esiste)
} catch (error) {
console.error("Errore durante il recupero dei dati dell'utente:", error);
allert("Errore durante il recupero dei dati dell'utente:");
}
};

Expand Down Expand Up @@ -70,4 +69,4 @@ export default function Statistics() {
</div>
</div>
);
}
}
74 changes: 53 additions & 21 deletions app/src/dao/meetingsDAO.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { db } from "@/firebase/firebase";
import { getFirestore, collection, query, where, getDocs, doc, updateDoc, deleteDoc, addDoc , getDoc , increment} from 'firebase/firestore';

import {createNotificationMeeting, updateNotificationMeeting, removeNotificationMeeting} from "@/dao/notificaDAO";
/**
* Recupera tutti gli incontri di un mentor dal database.
* @param {string} mentorId - ID del mentor autenticato.
Expand All @@ -21,6 +21,7 @@ export const fetchMeetingsForMentor = async (mentorId) => {
return {
id: doc.id,
menteeName: data.menteeName,
menteeId: data.menteeId,
date: data.date.toDate(),
time: data.time,
description: data.description,
Expand Down Expand Up @@ -127,12 +128,12 @@ export const updateMeetingMinutes = async (meetingId, minuta) => {
export const createMeeting = async (meetingData) => {
try {
// Verifica che userType sia mentee
if (meetingData.userType !== 'mentee') {
throw new Error('Il tipo di utente deve essere mentee');
if (meetingData.userType !== "mentee") {
throw new Error("Il tipo di utente deve essere mentee");
}

// Recupera il riferimento al documento del mentee nella collezione utenti
const menteeRef = doc(db, 'utenti', meetingData.menteeId);
// Recupera il riferimento al documento del mentee
const menteeRef = doc(db, "utenti", meetingData.menteeId);
const menteeSnap = await getDoc(menteeRef);

if (!menteeSnap.exists()) {
Expand All @@ -141,12 +142,40 @@ export const createMeeting = async (meetingData) => {

const menteeData = menteeSnap.data();

// Se il campo meetingsCount esiste, incrementalo, altrimenti crealo e impostalo a 1
if (typeof menteeData.meetingsCount === 'number') {
// Incrementa meetingsCount
// Converte la data in Timestamp Firestore
const meetingDate = meetingData.date instanceof Timestamp
? meetingData.date
: Timestamp.fromDate(new Date(meetingData.date));

// Converte l'orario in minuti totali
const [hours, minutes] = meetingData.time.split(":").map(Number);
const meetingMinutes = hours * 60 + minutes;

// Query per trovare incontri nello stesso giorno con lo stesso mentor
const meetingsRef = collection(db, "meetings");
const existingMeetingsQuery = query(
meetingsRef,
where("mentorId", "==", meetingData.mentorId),
where("date", "==", meetingDate)
);

const existingMeetingsSnapshot = await getDocs(existingMeetingsQuery);

for (const doc of existingMeetingsSnapshot.docs) {
const existingMeeting = doc.data();
const [existingHours, existingMinutes] = existingMeeting.time.split(":").map(Number);
const existingMeetingMinutes = existingHours * 60 + existingMinutes;

// Controllo intervallo di 10 minuti
if (Math.abs(meetingMinutes - existingMeetingMinutes) < 10) {
throw new Error("Non è possibile schedulare un meeting a meno di 10 minuti di distanza da un altro.");
}
}

// Aggiorna il contatore di meeting del mentee
if (typeof menteeData.meetingsCount === "number") {
await updateDoc(menteeRef, { meetingsCount: increment(1) });
} else {
// Crea meetingsCount e imposta a 1
await updateDoc(menteeRef, { meetingsCount: 1 });
}

Expand All @@ -155,20 +184,24 @@ export const createMeeting = async (meetingData) => {
mentorId: meetingData.mentorId,
menteeId: meetingData.menteeId,
mentorName: meetingData.mentorName,
date: meetingData.date,
mentorSurname: meetingData.mentorSurname,
date: meetingDate,
time: meetingData.time,
topic: meetingData.topic,
description: meetingData.description,
menteeName: meetingData.menteeName,
menteeEmail: meetingData.menteeEmail,
minuta: null, // Il campo MINUTA inizialmente è null
minuta: null,
};

// Aggiungi il nuovo incontro al database
const docRef = await addDoc(collection(db, 'meetings'), newMeeting);
return docRef.id; // Restituisce l'ID del documento appena creato
// Aggiungi il nuovo meeting al database
const docRef = await addDoc(collection(db, "meetings"), newMeeting);

// Crea la notifica per il meeting
await createNotificationMeeting(newMeeting.mentorId, newMeeting.menteeId, newMeeting.mentorName, newMeeting.mentorSurname);

return docRef.id;
} catch (error) {
console.error('Errore durante la creazione dell\'incontro:', error);
throw error;
}
};
Expand All @@ -179,12 +212,12 @@ export const createMeeting = async (meetingData) => {
* @param {Object} updatedData - I dati da aggiornare.
* @returns {Promise<void>}
*/
export const updateMeeting = async (meetingId, updatedData) => {
export const updateMeeting = async (updatedData, menteeId, mittenteId,nome,cognome) => {
try {
const meetingRef = doc(db, 'meetings', meetingId);
const meetingRef = doc(db, 'meetings', updatedData.id);
await updateDoc(meetingRef, updatedData);
await updateNotificationMeeting(mittenteId,menteeId,nome,cognome);
} catch (error) {
console.error('Errore durante la modifica dell\'incontro:', error);
throw error;
}
};
Expand All @@ -194,12 +227,12 @@ export const updateMeeting = async (meetingId, updatedData) => {
* @param {string} meetingId - ID dell'incontro da eliminare.
* @returns {Promise<void>}
*/
export const deleteMeeting = async (meetingId) => {
export const deleteMeeting = async (meetingId,menteeId,userId,nome,cognome) => {
try {
const meetingRef = doc(db, 'meetings', meetingId);
await deleteDoc(meetingRef);
await removeNotificationMeeting(userId,menteeId,nome, cognome);
} catch (error) {
console.error('Errore durante l\'eliminazione dell\'incontro:', error);
throw error;
}
};
Expand Down Expand Up @@ -238,7 +271,6 @@ export const getMentees = async () => {
...doc.data(),
}));
} catch (error) {
console.error('Errore durante il recupero dei mentee:', error);
throw error;
}
};