IntroductionBackendAdmin Content

Admin Module Documentation

Filename:src\app\contexts\AdminContext.tsx


File imports

"use client";
import { useRouter } from "next/navigation";
import { createContext, ReactNode, useContext, useState, useEffect } from "react";
import { doc, setDoc, updateDoc, getDoc,getDocs, query, where, collection } from "firebase/firestore";
import { db } from "../firebase";
import { toast } from "sonner";
import { useAuth } from "./AuthContext";

Props Interface

interface ChildProps {
    children: ReactNode;
}

Context creation

const ConsoleContext = createContext<any | undefined>(undefined);

Create School component

    const createSchool = async (
        newSchool: any, 
        incomeField: any, 
        transportField: any, 
        classField: any, 
        paymentOption: any, 
        adminDetails: any
      ) => {
        try {
          if (!newSchool.sName) {
            toast("School name is not defined");
            return;
          }
          
          if (!userInfo || !userInfo.email) {
            toast("User info is not defined");
            return;
          }
          
          const schoolOwner = userInfo.email;
      
          // Generate a unique ID for the school
          const schoolRef = doc(collection(db, "school")); // Automatically generates a unique ID
          const schoolId = schoolRef.id;
 
          const today = new Date();
          const formattedDate = today.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' });
      
          await setDoc(schoolRef, { 
            formattedDate,
            schoolId,
            schoolName: newSchool.sName,
            schoolUsername: newSchool.sUsername,
            schoolDescription: newSchool.sDescription,
            schoolAddress: newSchool.sAddress,
            schoolContact: newSchool.sContact,
            schoolEmail: newSchool.sEmail,
            schoolType: newSchool.sType,
            schoolOwner,
            incomeField,
            transportField,
            classField,
            paymentOption,
            adminDetails
          });
          
          // Fetch school data after creation
          await fetchSchoolData(schoolOwner);
          toast("School created successfully");
        } catch (error) {
          console.error("Error creating school:", error);
          toast.error("Something went wrong creating the school");
        }
      };
      

Update School Component

 ```javascript
 const updateSchool = async (
    newSchool: any,
    incomeField: any[],
    transportField: any[],
    classField: any[],
    paymentOption: any[],
    adminDetails: any[]
  ) => {
    try {
      if (!school || !school.schoolId) {
        throw new Error("School ID is missing");
      }

      const schoolRef = doc(db, "school", school.schoolId);

      // Prepare data for the update
      const updateData: any = {
        schoolName: newSchool.sName,
        schoolUsername: newSchool.sUsername,
        schoolDescription: newSchool.sDescription,
        schoolAddress: newSchool.sAddress,
        schoolContact: newSchool.sContact,
        schoolEmail: newSchool.sEmail,
        schoolType: newSchool.sType,
        incomeField,
        transportField,
        classField,
        paymentOption,
        adminDetails
      };

      // Update the document in Firestore
      await updateDoc(schoolRef, updateData);

      // Fetch the updated school data
      const schoolSnap = await getDoc(schoolRef);
      if (schoolSnap.exists()) {
        const updatedSchoolData = schoolSnap.data();

        // Update the school state with the updated data
        setSchool(updatedSchoolData);

        
        toast("School updated successfully");
        //router.push("/dashboard"); // Redirect after successful update
      } else {
        console.error("No such document after update!");
      }
    } catch (error: any) {
      console.error("Error updating school:", error.message || error);
      toast.error(`Something went wrong updating the school: ${error.message || "Unknown error"}`);
    }
  };
---
## Fetch Component 
```javascript
const fetchSchoolData = async (schoolOwner: string): Promise<void> => {
      try {
          const q = query(collection(db, "school"), where("schoolOwner", "==", schoolOwner));
          const querySnapshot = await getDocs(q);

          if (!querySnapshot.empty) {
              const schoolData = querySnapshot.docs.map((doc) => doc.data()); // Extract the data from each document
              setSchool(schoolData[0]); // Assuming only one school per owner
              console.log(schoolData[0]); // Log the school data to check
          } else {
              setSchool(null);
          }
      } catch (err: any) {
          console.error("Error retrieving school:", err);
          toast.error("Error retrieving school");
      }
  };

  useEffect(() => {
      if (userInfo?.email) {
          fetchSchoolData(userInfo.email);
      }
  }, [userInfo]);
  
  if(school){
  if (school["adminDetails"]) {
      const adminDetails = school["adminDetails"];
      admin = adminDetails.reduce((acc: any, key: any) => {
        acc[key.role] = key.individual;
        return acc;
      }, {});
    }

    if (school["incomeField"]) {
      const adminDetails = school["incomeField"];
      incomes = adminDetails.reduce((acc: any, key: any) => {
        acc[key.incDesc] = key.limit;
        return acc;
      }, {});
    }

    if (school["paymentOption"]) {
      const adminDetails = school["paymentOption"];
      pay = adminDetails.reduce((acc: any, key: any) => {
        acc[key.method] = key.accNum;
        return acc;
      }, {});
    }

    if (school["classField"]) {
      const adminDetails = school["classField"];
      classes = adminDetails.reduce((acc: any, key: any) => {
        acc[key.method] = key.accNum;
        return acc;
      }, {});
    }
  }

Main Component

export const ConsoleProvider = ({ children }: ChildProps) => {
  const { userInfo } = useAuth();
  const [school, setSchool] = useState<any>({});
  const router = useRouter();
  const [isloading , setIsloading] = useState<boolean>(false)
  let admin : {} = {}
  let incomes : {} = {}
  let pay : {} = {}
  let classes : {} = {}
 
   // insert components 
 
  const values = {
      createSchool,
      updateSchool,
      school,
      isloading,
      admin,
      incomes,
      pay,
      classes
  };
 
  return (
      <ConsoleContext.Provider value={values}>
          {children}
      </ConsoleContext.Provider>
  );
};
 

Context component

export const useConsole = () => {
  const context = useContext(ConsoleContext);
  if (!context) {
      throw new Error("Error in useConsole");
  }
  return context;
};