diff --git a/app/sait-staff/login/page.js b/app/sait-staff/login/page.js index c977e91..83b1b0e 100644 --- a/app/sait-staff/login/page.js +++ b/app/sait-staff/login/page.js @@ -32,16 +32,15 @@ const SignIn = () => { const user = auth.currentUser; if (user) { const uid = user.uid; + console.log('user ',uid) const q = query(collection(db, "saitStaff"), where("uid", "==", uid)); const querySnapshot = await getDocs(q); const employeeData = querySnapshot.docs.map((doc) => doc.data().name); - console.log('name: ',employeeData); if (!employeeData.empty) { const saitStaffData = employeeData[0]; const name = saitStaffData || "SAIT Staff"; // Use default name if 'name' is not available setSaitStaffName(name); - console.log("user name: ",name) } else { console.log("No SAIT Staff data found for current user"); setSaitStaffName("SAIT Staff"); // Set default name @@ -58,7 +57,6 @@ const SignIn = () => { try { const userCredential = await signInWithEmailAndPassword(email, password); const user = userCredential.user; - console.log(user); // Update display name with SAIT Staff name await updateProfile(user, { displayName: saitStaffName }); @@ -67,12 +65,10 @@ const SignIn = () => { sessionStorage.setItem("name", saitStaffName); sessionStorage.setItem("email", user.email || ""); // Store the user's email sessionStorage.setItem("uid", user.uid || ""); // Store the user's UID - console.log(saitStaffName); + router.push("/sait-staff"); // Redirect after successful sign-in setEmail(""); setPassword(""); setLoginError(""); - //setLoading(false); - router.push("/sait-staff"); // Redirect after successful sign-in } catch (error) { setLoading(false); setLoginError("Invalid email or password"); diff --git a/app/sait-staff/overviewDash/Add.js b/app/sait-staff/overviewDash/Add.js index 079866d..8264d89 100644 --- a/app/sait-staff/overviewDash/Add.js +++ b/app/sait-staff/overviewDash/Add.js @@ -14,14 +14,6 @@ const Add = ({ admin, setAdmins, setIsAdding }) => { const [email, setEmail] = useState(""); const [phoneNumber, setPhoneNumber] = useState(""); const [address, setAddress] = useState(""); - - const currentDate = new Date(); - - const day = currentDate.getDate(); - const month = currentDate.getMonth(); // Remember, month is zero-indexed - const year = currentDate.getFullYear(); - - const newDate = [day, month, year]; let firstWord = name.split(" "); //generic password will be first name of student or restaurant + last three digits of mobile number + "!" @@ -54,6 +46,7 @@ const Add = ({ admin, setAdmins, setIsAdding }) => { genericPassword ); const user = userCredential.user; + const date = new Date(); // Add restaurant to Firestore const newAdmin = { @@ -63,7 +56,7 @@ const Add = ({ admin, setAdmins, setIsAdding }) => { phoneNumber, address, uid: user.uid, - acountCreated: newDate, // link with user ID + accountCreated: date, // link with user ID active: true, }; @@ -168,9 +161,9 @@ const Add = ({ admin, setAdmins, setIsAdding }) => { value={role} > - - - + + +
diff --git a/app/sait-staff/overviewDash/Edit.js b/app/sait-staff/overviewDash/Edit.js new file mode 100644 index 0000000..085e117 --- /dev/null +++ b/app/sait-staff/overviewDash/Edit.js @@ -0,0 +1,174 @@ +import React, { useState } from "react"; +import { formatPhoneNumber } from "@/Constant/formated"; +import Swal from "sweetalert2"; + +import { doc, setDoc, updateDoc } from "firebase/firestore"; +import { db } from "@/app/firebase/config"; + +const Edit = ({ employeeData, setIsEditing, getData, userData }) => { + const [name, setName] = useState(employeeData.name); + const [email, setEmail] = useState(employeeData.email); + const [mobileNumber, setMobileNumber] = useState(employeeData.phoneNumber); + const id = employeeData.id; + const [role, setRole] = useState(employeeData.role); + const [userRole, setUserRole] = useState(userData[0].role); + const [address, setAddress] = useState(employeeData.address); + + const handleChangeRole = (e) => { + setRole(e.target.value); + }; + + const handleUpdate = async (e) => { + e.preventDefault(); + + if (!name || !email || !mobileNumber) { + return Swal.fire({ + icon: "error", + title: "Error!", + text: "All fields are required.", + showConfirmButton: true, + }); + } + + const employee = { + id, + name, + email, + mobileNumber, + role, + address + }; + + const dataForUpdate = doc(db, "saitStaff", id); + await updateDoc(dataForUpdate, employee); + getData(); + setIsEditing(false); + + Swal.fire({ + icon: "success", + title: "Updated!", + text: `${employeeData.name}'s data has been updated.`, + showConfirmButton: false, + timer: 1500, + }); + }; + + return ( +
+
+

+ Edit Employee +

+
+ + setName(e.target.value)} + className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" + /> +
+ +
+ + setEmail(e.target.value)} + className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none sm:text-sm cursor-not-allowed bg-black/20" + /> +
+
+ + setMobileNumber(formatPhoneNumber(e.target.value))} + className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" + /> +
+
+ + {userRole == "Admin" && ( + + )} + {userRole !== "Admin" && ( + + )} +
+
+ + setAddress(e.target.value)} + className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" + /> +
+ +
+ + +
+
+
+ ); +}; + +export default Edit; diff --git a/app/sait-staff/overviewDash/index.js b/app/sait-staff/overviewDash/index.js index 77ee184..ea4750d 100644 --- a/app/sait-staff/overviewDash/index.js +++ b/app/sait-staff/overviewDash/index.js @@ -1,47 +1,69 @@ -import Head from 'next/head'; -import Overview from './overview'; -import Table from './table'; -import { useState } from 'react'; -import Add from './Add'; +import Head from "next/head"; +import Overview from "./overview"; +import Table from "./table"; +import { useState, useEffect } from "react"; +import Add from "./Add"; +import Edit from "./Edit"; +import { + getSaitData, + getSaitDataByUser, +} from "@/services/GetRequest/getRequest"; +import { useUserAuth } from "@/services/utils"; +import { updateSaitEmployeeStatus } from "@/services/PostRequest/postRequest"; export default function Dash() { + const [userData, setUserData] = useState(null); + const [editEmployeData, setEditEmployeData] = useState(null); const [isAdding, setIsAdding] = useState(false); + const { user } = useUserAuth(); + const [admin, setAdmin] = useState(null); + const [isEditing, setIsEditing] = useState(false); + async function fetchData() { + const data = await getSaitData(); + console.log(data); + setAdmin(data); + } + async function fetchDataByUser() { + const data = await getSaitDataByUser(user); + setUserData(data); + console.log(data); + } - // Random data - const [admin, setAdmin] = useState([ - { - id: 1, - name: 'Vera Carpenter', - imageUrl: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2.2&w=160&h=160&q=80', - role: 'Admin', - createdAt: 'Jan 21, 2020', - status: 'Active', - statusColor: 'text-green-900', - statusBgColor: 'bg-green-200' - }, - { - id: 2, - name: 'Blake Bowman', - imageUrl: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2.2&w=160&h=160&q=80', - role: 'Editor', - createdAt: 'Jan 01, 2020', - status: 'Active', - statusColor: 'text-green-900', - statusBgColor: 'bg-green-200' - }, - // Add more data as needed - ]); + useEffect(() => { + if (user) { + fetchData(); + fetchDataByUser(user); + } + console.log(user); + }, [user]); - const handleEdit = (id) => { - // Handle edit logic - console.log(`Edit user with id: ${id}`); + useEffect(() => { + if (admin) { + } + }, [admin]); + + const handleEditRequest = (user) => { + console.log(user); + setEditEmployeData(user); + setIsEditing(true); }; const handleDelete = (id) => { // Handle delete logic console.log(`Delete user with id: ${id}`); - setAdmin(admin.filter(user => user.id !== id)); + setAdmin(admin.filter((user) => user.id !== id)); + }; + + const handleChangeStatus = async (id, status) => { + if (userData[0].role === "Admin" || userData[0].role === "Editor") { + await updateSaitEmployeeStatus(id, status).then(() => { + alert("Status for given user has been changed"); + fetchData(); + }); + } else { + alert("You are not authorized to change the status"); + } }; return ( @@ -51,12 +73,39 @@ export default function Dash() {
- {isAdding? <>:<>} + {isAdding ? ( + <> + + + ) : ( + <> + {isEditing ? ( + <> + {" "} + + + ) : ( + <> +
+ + )} + + )} diff --git a/app/sait-staff/overviewDash/table.js b/app/sait-staff/overviewDash/table.js index 573ab28..71c387f 100644 --- a/app/sait-staff/overviewDash/table.js +++ b/app/sait-staff/overviewDash/table.js @@ -1,12 +1,21 @@ -import React from 'react'; -import { LuPencil, LuTrash } from 'react-icons/lu'; -import { IoMdPersonAdd } from 'react-icons/io'; +import React, { useState } from "react"; +import { LuPencil, LuTrash } from "react-icons/lu"; +import { IoMdPersonAdd } from "react-icons/io"; +import Modal from "@/Components/Modal"; -const Table = ({ admin, handleEdit, handleDelete, setIsAdding }) => { +const Table = ({ + admin, + handleEdit, + setIsAdding, + handleChangeStatus, +}) => { + const [isVisible, setIsVisisble] = useState(false); + const [isActive, setIsActive] = useState(null); + const [email, setEmail] = useState(""); + const [docId, setDocId] = useState(""); return (
-
- )) ) : ( - @@ -92,6 +122,39 @@ const Table = ({ admin, handleEdit, handleDelete, setIsAdding }) => {
- +
-

{user.name}

+

+ {user.name} +

-

{user.role}

+

+ {user.role} +

-

{user.createdAt}

+

+ {user.accountCreated.toDate().toDateString()} +

- - - {user.status} + { + setIsVisisble(true); + setIsActive(user.active), + setEmail(user.email), + setDocId(user.id); + }} + className={`relative inline-block px-3 py-1 font-semibold leading-tight rounded ${ + user.active ? "bg-green-400" : "bg-red-400" + }`} + > + + + {user.active ? "Active" : "InActive"} + + -
+ No data available
+ setIsVisisble(false)}> +
+

+ {isActive ? "Deactivate User" : "Activate User"} +

+ +

+ Are you sure you want to {isActive ? "deactivate" : "activate"}{" "} + email

{email}?

This will make + it{" "} +

+ {isActive ? "unavailable" : "available"} +

+

to users.

+

+
+
+ + +
+
+
); }; diff --git a/services/GetRequest/getRequest.js b/services/GetRequest/getRequest.js index 02bac4d..0bb5736 100644 --- a/services/GetRequest/getRequest.js +++ b/services/GetRequest/getRequest.js @@ -81,6 +81,37 @@ export async function getMenuInformation(userId) { return []; } } +// get sait data for sait staff home page +export async function getSaitData() { + try{ + const q = query(collection(db, "saitStaff")); + const querySnapshot = await getDocs(q); + const saitItems = querySnapshot.docs.map((doc) => { + return { id: doc.id, ...doc.data() }; + }); + return saitItems; + } + catch(error){ + console.error("Error getting sait information: ", error); + return []; + } +} + +export async function getSaitDataByUser(uid){ + try{ + const q = query(collection(db, "saitStaff"),where("uid","==",uid)); + const querySnapshot = await getDocs(q); + const saitItems = querySnapshot.docs.map((doc) => { + return { id: doc.id, ...doc.data() }; + }); + return saitItems; + } + catch(error){ + console.error("Error getting sait information: ", error); + return []; + } +} + export async function getStudentEmailWithStatus() { try { const q = query( diff --git a/services/PostRequest/postRequest.js b/services/PostRequest/postRequest.js index bc4fb31..3fa67eb 100644 --- a/services/PostRequest/postRequest.js +++ b/services/PostRequest/postRequest.js @@ -19,6 +19,9 @@ import { } from "firebase/storage"; import { deleteUser } from "firebase/auth"; +// students + +// to add student information in database export async function addStudentInformation(userId, userInformation, email) { const studentInformation = { studentId: userId, @@ -32,6 +35,9 @@ export async function addStudentInformation(userId, userInformation, email) { console.error("Error adding document: ", e); } } +//restaurants + +// to add restaurant information in database export async function addRestaurantInformation( user, name, @@ -83,6 +89,7 @@ export async function addRestaurantInformation( ); } +// to add restaurant menu in database export async function addRestaurantMenu(user, name, price, description, image,userId) { const storageRef = ref(storage, `menu/${userId}/${image.name}`); const uploadTask = uploadBytesResumable(storageRef, image); @@ -126,7 +133,7 @@ export async function addRestaurantMenu(user, name, price, description, image,us } ); } -export let integer = 0; + export default async function addStudentEmailStatus(prop) { let { email, active } = prop; let data = { studentEmail: email, active: active }; @@ -217,6 +224,19 @@ export async function updateStudent(id, prop) { console.error("Error updating document: ", error); } } +// to update status of sait staff employee +export async function updateSaitEmployeeStatus(id , active){ + try{ + const docRef = doc(db,"saitStaff",id); + await updateDoc(docRef,{ + active:!active + }); + }catch(error){ + console.error("Error updating document: ", error); + + } +} + export async function existingStudentData(email) { try { const q = query(collection(db, "students"), where("email", "==", email));