Skip to content

Commit

Permalink
Merge pull request #134 from 202306-NEA-DZ-FEW/features/matching
Browse files Browse the repository at this point in the history
Features/matching
  • Loading branch information
Amel7400 authored Nov 22, 2023
2 parents a2ea12d + b784742 commit ef7929e
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 50 deletions.
9 changes: 7 additions & 2 deletions src/components/User/UserProfile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,18 @@ export default function UserProfile({ user }) {
formData.append("file", file);
formData.append("upload_preset", "hopehub");

//store the image in cloudinary
axios
.post(
"https://api.cloudinary.com/v1_1/dxic1agza/image/upload",
formData
)
.then((response) => {
//add the photourl to the user object

setCloudinaryImage(response.data.secure_url);
setUser({ ...user, photoURL: response.data.secure_url });
handlePhotoChange();
handlePhotoChange(); // to update user infos in firebase
})
.catch((error) => {
console.error("cloudinary err", error);
Expand Down Expand Up @@ -132,6 +135,7 @@ export default function UserProfile({ user }) {
"dark:bg-slate-800 dark:text-NeutralWhite text-NeutralBlack bg-NeutralWhite",
});
} else {
// change the user infos locally
console.log("after update");
setUser({
...user,
Expand All @@ -147,7 +151,7 @@ export default function UserProfile({ user }) {
photoURL: cloudinaryImage,
idcard: idcard,
});
await updateUserProfile();
await updateUserProfile(); // change the data in firebase
toast.success("profile updated", {
position: toast.POSITION.BOTTOM_CENTER,
autoClose: 2500,
Expand Down Expand Up @@ -212,6 +216,7 @@ export default function UserProfile({ user }) {
if (phone !== auth.currentUser.phoneNumber) handlePhoneChange();
if (cloudinaryImage !== auth.currentUser.photoURL)
handlePhotoChange();
// update the user collection in firestore
await updateDoc(doc(db, "users", user.uid), {
...user,
name: fullName,
Expand Down
1 change: 1 addition & 0 deletions src/components/UserAuth/login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function Login({ isChecked, setChecked }) {
return;
}
try {
// firebase function for sign in
const userCredential = await signInWithEmailAndPassword(
auth,
email,
Expand Down
11 changes: 6 additions & 5 deletions src/components/UserAuth/signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ function Signup({ isChecked, setChecked }) {
}

try {
// create the user in firebase
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
);

//this data will be stored in firestore
const userData = {
uid: userCredential.user.uid, // Save the UID
birthDate: bdate,
Expand All @@ -58,13 +59,13 @@ function Signup({ isChecked, setChecked }) {
name: `${firstname} ${lastname}`,
email: email,
};

// we update the user name
await updateProfile(userCredential.user, {
displayName: `${firstname} ${lastname}`,
});

// we save the user infos in firestore
await addUserToFirestore(userCredential, userData);

//we store the uid in cookie to keep him logged in
Cookie.set("loggedInUser", userCredential.user.uid, { expires: 7 });
router.push(`/thanks?from=${pathname}`);
authChange();
Expand All @@ -80,7 +81,7 @@ function Signup({ isChecked, setChecked }) {
autoClose: 2500,
});
} finally {
// >>>>>>> develop
// reste all the fields
setEmail("");
setLastname("");
setConfirmemail("");
Expand Down
70 changes: 67 additions & 3 deletions src/components/booking/7Submission.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { doc, getDoc, setDoc, updateDoc } from "firebase/firestore";
import {
collection,
doc,
getDoc,
getDocs,
setDoc,
updateDoc,
where,
} from "firebase/firestore";
import Head from "next/head";
import { useTranslation } from "next-i18next";
import React from "react";
Expand All @@ -9,8 +17,6 @@ export default function Submission({ OnNext, OnPrevious }) {
const { bookingInfos, user, setUser } = useAppcontext();
const { t } = useTranslation("common");
async function handleSubmit() {
// send request to save the data
// ...
const appointment = {
date: bookingInfos.date,
time: bookingInfos.start,
Expand Down Expand Up @@ -89,6 +95,64 @@ export default function Submission({ OnNext, OnPrevious }) {
`,
}),
});

const userId = user.uid;

async function assignTherapist() {
if (!userId) {
console.error("User ID is undefined or null.");
return;
}

try {
const usersRef = collection(db, "users");
const usersSnapshot = await getDocs(usersRef);
const therapists = [];

usersSnapshot.forEach((doc) => {
const userData = doc.data();
if (userData.isTherapist === true) {
therapists.push({ id: doc.id, data: userData });
}
});

if (therapists.length > 0) {
const randomIndex = Math.floor(
Math.random() * therapists.length
);
const selectedTherapist = therapists[randomIndex];

// Update the user's document with the assigned therapist
await updateDoc(doc(db, "users", userId), {
hasTherapist: true,
therapistId: selectedTherapist.id,
});

// Add patient's ID to therapist's document
const therapistRef = doc(db, "users", selectedTherapist.id);
const therapistDoc = await getDoc(therapistRef);
const therapistData = therapistDoc.data();

if (!therapistData.patients) {
therapistData.patients = [userId];
} else {
therapistData.patients.push(userId);
}

await updateDoc(therapistRef, {
patients: therapistData.patients,
});

console.log("Therapist assigned:", selectedTherapist);
} else {
console.log("No therapists available.");
}
} catch (error) {
console.error("Error assigning therapist:", error);
}
}

assignTherapist();
OnNext();
}

Expand Down
5 changes: 4 additions & 1 deletion src/components/calendarEvents/EventModal.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import Link from "next/link";
import React from "react";

function EventModal({ event, position, closeModal, userId }) {
function EventModal({ eventData, position, closeModal, userId }) {
console.log("info event", eventData._def.extendedProps);
const event = { ...eventData._def.extendedProps, date: eventData.startStr };
console.log("event DAta nnennenen", event);
return (
<>
<div
Expand Down
3 changes: 1 addition & 2 deletions src/pages/booking/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ function BookingPage({ dates, user }) {
const { t } = useTranslation("common");
const [step, setStep] = useState(1);
const { bookingInfos } = useAppcontext();
// console.log('dates', dates)

function OnNext() {
setStep(step + 1);
// console.log(bookingInfos);
}
function OnPrevious() {
setStep(step - 1);
Expand Down
72 changes: 35 additions & 37 deletions src/pages/calendar/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Head from "next/head";
import { useRouter } from "next/navigation";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";

import EventModal from "@/components/calendarEvents/EventModal";

Expand All @@ -17,65 +17,59 @@ import { db } from "@/util/firebase";
function Calendar({ appointments, user }) {
const router = useRouter();
const { t } = useTranslation("common");
const events = user.isTherapist
? appointments /* .map((ev)=>{
return { title: ev.time, id: ev.uid, ...ev };
}) */
: user?.appointments?.map((d) => ({ title: d.time, ...d }));
console.log("calender ave", events);
// console.log("appointments", appointments);
// if(user.isTherapist){
// appointments.forEach((obj, id) => {
// const key = Object.keys(obj)[id];
// // console.log('objjjj',obj[key])
// return { title: obj[key]?.time, id: key, ...obj[key] };
// })
// }
// const [filteredAppointments, setFilteredAppointments] = useState([]);

const [modalOpen, setModalOpen] = useState(false);
const [eventData, setEventData] = useState(null);
const [modalPosition, setModalPosition] = useState({
left: "0px",
top: "0px",
});

const events = user.isTherapist
? appointments.filter(
(appointment) => user?.patients.includes(appointment.id) // we filter only the patients assigned to this therapist
)
: user?.appointments?.map((appointment) => ({
title: appointment.time,
...appointment,
})); // return the evens array in format accepted by FullCalndar

function handleEventClick(info) {
if (user.isTherapist) {
const event = events.filter((obj) => {
return obj.id === info.event.id;
});
setEventData(event[0]);
const click = info.jsEvent.clientX;
setEventData(info.event);
const click = info.jsEvent.clientX; // the mouse position
let horizontal = 0;
const modalWidth = window.innerWidth > 700 ? 390 : 240;
const rect = info.el.getBoundingClientRect();
const modalWidth = window.innerWidth > 700 ? 390 : 240; //specify the modal widt, small or bigger screens
const rect = info.el.getBoundingClientRect(); // get the event rectangle to use its coordinates to calculate the modal postion
if (click + modalWidth + rect.width > window.innerWidth) {
horizontal = rect.left - modalWidth;
// if(horizontal-240<0){
// horizontal= rect.left}
} else {
horizontal = rect.left + rect.width;
}
// console.log('horiiiiiiiii______window',click+modalWidth+rect.width, horizontal, window.innerWidth)
setModalPosition({
left: `${horizontal}px`,
top: `${rect.top - rect.height}px`,
});
setModalOpen(!modalOpen);
setModalOpen((prevModalOpen) => !prevModalOpen);
}
return;
}
useEffect(() => {}, []);
return (
<Layout user={user} className='max-w-screen'>
<Head>
<title>{t("Calender")}</title>
</Head>
{modalOpen && (
<EventModal
event={eventData}
eventData={eventData}
position={modalPosition}
closeModal={() => {
setModalOpen(false);
setModalOpen((prevModalOpen) => !prevModalOpen);
setEventData(null); // Reset event data when closing the modal
// console.log("im in here", events);
}}
userId={user.uid}
/>
Expand All @@ -101,14 +95,20 @@ function Calendar({ appointments, user }) {
center: "",
end: "",
}}
customButtons={{
bookApp: {
text: "Book appointment",
click: function () {
router.push(`/booking?userid=${user.uid}`);
},
},
}}
customButtons={
user.isTherapist
? {}
: {
bookApp: {
text: "Book appointment",
click: function () {
router.push(
`/booking?userid=${user.uid}`
);
},
},
}
}
nowIndicator={true}
/>
</div>
Expand Down Expand Up @@ -147,10 +147,8 @@ export async function getServerSideProps({ locale, query }) {
});
}
}
console.log("appointments..............", appointments);

const userDoc = await getDoc(doc(db, "users", userId));
console.log("im userdoc in serverside", userDoc.exists());
if (!userDoc.exists()) {
// Handle the case when the user with the specified ID is not found
return { notFound: true };
Expand Down

0 comments on commit ef7929e

Please sign in to comment.