All files / hooks useInstructorClasses.ts

75.82% Statements 69/91
64% Branches 32/50
70% Functions 14/20
82.43% Lines 61/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 2031x 1x   1x 1x             1x 40x 40x 40x 40x     40x 40x   40x 21x                       40x 48x       40x 13x 13x   12x 12x   11x 11x   11x 11x   9x 1x 1x   8x   8x   2x   11x       12x     40x   7x     7x         40x 40x                 4x                                       1x 4x 4x 4x 4x 4x   4x 2x   1x 1x   1x 1x           1x     1x   1x                                                                             1x 1x 1x           1x       4x 2x     4x       4x                  
import { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "./useAuth";
import { UserClass, UserData } from "../api/types/user";
import { getClassesByInstructor } from "../api/classes";
import { supabase } from "../supabaseClient";
 
/**
 * Custom hook to fetch instructor classes based on user ID or authenticated user.
 * @param {string} userID - Optional user ID to fetch specific instructor classes.
 * @returns {Object} - Contains classes, loading state, error message, and selected class information.
 */
export const useInstructorClasses = (userID?: string | null) => {
  const { user } = useAuth();
  const [classes, setClasses] = useState<UserClass[]>([]);
  const [selectedClassId, setSelectedClassId] = useState<string | null>(null);
  const [selectedClassType, setSelectedClassType] = useState<
    "all" | "class" | "non-class"
  >("all");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  const modifiedClasses = useMemo(
    () => [
      {
        id: "all",
        classTitle: "All",
        classCode: "",
        classHexColor: "#e5e5e5",
      },
      ...classes,
    ],
    [classes]
  );
 
  const selectedClass = useMemo(
    () => modifiedClasses.find((c) => c.id === selectedClassId),
    [modifiedClasses, selectedClassId]
  );
 
  useEffect(() => {
    const currentUserId = userID ?? user?.id;
    if (!currentUserId) return;
 
    const fetchClasses = async () => {
      if (!user?.id) return;
 
      setLoading(true);
      setError(null);
 
      try {
        const { data, error } = await getClassesByInstructor(currentUserId);
 
        if (error) {
          setError(error);
          return;
        }
        console.log("Fetched Classes:", data);
 
        setClasses(data || []);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Unknown error occurred");
      } finally {
        setLoading(false);
      }
    };
 
    fetchClasses();
  }, [userID, user?.id]);
 
  const handleClassSelect = useCallback(
    (selection: { id: string | null; type: "all" | "class" | "non-class" }) => {
      setSelectedClassId(
        selection.type === "class" ? selection.id : selection.type
      );
      setSelectedClassType(selection.type);
    },
    []
  );
 
  return useMemo(
    () => ({
      classes: modifiedClasses,
      originalClasses: classes,
      selectedClassId:
        selectedClassType === "class" ? selectedClassId : selectedClassType,
      selectedClassType,
      loading,
      error,
      handleClassSelect,
      getSelectedClass: () => selectedClass,
    }),
    [
      modifiedClasses,
      classes,
      selectedClassId,
      selectedClassType,
      loading,
      error,
      handleClassSelect,
      selectedClass,
    ]
  );
};
 
/**
 * Custom hook to fetch students enrolled and waitlisted in a class.
 * @param classId - The ID of the class to fetch students for.
 * @returns {Object} - Contains enrolled and waitlisted students, loading state, error message, and refetch function.
 */
export const useClassStudentsInfo = (classId: string | null) => {
  const [enrolledStudents, setEnrolledStudents] = useState<UserData[]>([]);
  const [waitlistedStudents, setWaitlistedStudents] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [refreshFlag, setRefreshFlag] = useState(false);
 
  const fetchClassStudentsInfo = useCallback(async () => {
    if (!classId) return;
 
    setLoading(true);
    setError(null);
 
    try {
      const { data: enrolledData, error: enrolledError } = await supabase
        .from("class_users")
        .select("student_id")
        .eq("class_id", classId)
        .eq("enrollment_status", "ENROLLED");
 
      Iif (enrolledError) throw enrolledError;
 
      const enrolledUserIds =
        enrolledData?.map((item) => item.student_id) || [];
 
      const { data: enrolledUsers, error: enrolledUsersError } = await supabase
        .from("users")
        .select("*")
        .in("id", enrolledUserIds);
 
      Iif (enrolledUsersError) throw enrolledUsersError;
 
      const normalizedEnrolled = (enrolledUsers || []).map((user) => ({
        ...user,
        firstName: user.first_name,
        lastName: user.last_name,
      }));
 
      setEnrolledStudents(normalizedEnrolled);
 
      const { data: waitlistedData, error: waitlistedError } = await supabase
        .from("class_users")
        .select("student_id")
        .eq("class_id", classId)
        .eq("enrollment_status", "WAITLISTED");
 
      Iif (waitlistedError) throw waitlistedError;
 
      const waitlistedUserIds =
        waitlistedData?.map((item) => item.student_id) || [];
 
      const { data: waitlistedUsers, error: waitlistedUsersError } =
        await supabase.from("users").select("*").in("id", waitlistedUserIds);
 
      Iif (waitlistedUsersError) throw waitlistedUsersError;
 
      const normalizedWaitlisted = (waitlistedUsers || []).map((user) => ({
        ...user,
        firstName: user.first_name,
        lastName: user.last_name,
      }));
 
      setWaitlistedStudents(normalizedWaitlisted);
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message);
        console.error(err.message);
      } else E{
        setError("Unknown error occurred");
        console.error("Unknown error occurred");
      }
    } finally {
      setLoading(false);
    }
  }, [classId]);
 
  useEffect(() => {
    fetchClassStudentsInfo();
  }, [classId, fetchClassStudentsInfo, refreshFlag]);
 
  const refetch = useCallback(() => {
    setRefreshFlag((prev) => !prev);
  }, []);
 
  return {
    enrolledStudents,
    waitlistedStudents,
    totalStudents: enrolledStudents.length,
    loading,
    error,
    refetch,
  };
};