All files / src/app/teacher-page/page/dashboard Dashboard.jsx

100% Statements 67/67
100% Branches 42/42
100% Functions 14/14
100% Lines 63/63

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 203 204                                          76x 72x 24x 16x         16x 16x 16x 16x 16x   16x 5x 5x 5x 5x 5x     16x                       38x 38x 38x   38x 38x   38x 38x 38x 38x 38x 38x 38x   38x 19x 19x 19x     38x 19x 19x 16x 15x     3x   19x       38x 19x 19x 17x 16x 16x 16x 16x 16x 16x 5x 5x   16x 16x     2x   19x       38x 38x 38x 38x   38x                                                             38x   38x               152x                                                                                          
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useTheme } from "@mui/material/styles";
import { Box, Grid, Stack, useMediaQuery } from "@mui/material";
import SchoolIcon from "@mui/icons-material/School";
import PeopleIcon from "@mui/icons-material/People";
import HourglassEmptyIcon from "@mui/icons-material/HourglassEmpty";
import StarIcon from "@mui/icons-material/Star";
import axios from "axios";
 
import { API_ENDPOINTS } from "@/api/endpoints";
import { _fetchAllClasses } from "@/store/slices/teacher/TeacherClasses";
 
import StatCard from "./components/StatCard";
import QuickActionsPanel from "./components/QuickActionsPanel";
import SearchProfileWidget from "./components/SearchProfileWidget";
import AssignmentSubmissionsChart from "./components/AssignmentSubmissionsChart";
import PassedVsFailedCard from "./components/PassedVsFailedCard";
import WelcomeBanner from "./components/WelcomeBanner";
 
function countStudents(classData, status) {
    if (!classData) return 0;
    return classData.reduce((sum, cls) => {
        const count = cls.students?.filter((s) => s.status === status).length ?? 0;
        return sum + count;
    }, 0);
}
 
function transformSubmissionStats(response) {
    const categories = [];
    const totalAssignments = [];
    const totalSubmissions = [];
    const passedSubmissions = [];
    const failedSubmissions = [];
 
    response.data.forEach((classItem) => {
        categories.push(classItem.class_title);
        totalAssignments.push(classItem.total_assignments || 0);
        totalSubmissions.push(classItem.total_submissions || 0);
        passedSubmissions.push(classItem.total_passed_submissions || 0);
        failedSubmissions.push(classItem.total_failed_submissions || 0);
    });
 
    return {
        categories,
        data: [
            { name: "Total Assignments", data: totalAssignments },
            { name: "Total Submissions", data: totalSubmissions },
            { name: "Passed Submissions", data: passedSubmissions },
            { name: "Failed Submissions", data: failedSubmissions },
        ],
    };
}
 
export default function Dashboard() {
    const theme = useTheme();
    const dispatch = useDispatch();
    const isMobile = useMediaQuery("(max-width:450px)");
 
    const { teacherData } = useSelector((state) => state.TeacherData);
    const { classData, isLoading } = useSelector((state) => state.TeacherClasses);
 
    const [chartData, setChartData] = useState([]);
    const [chartCategories, setChartCategories] = useState([]);
    const [chartPassed, setChartPassed] = useState(0);
    const [chartFailed, setChartFailed] = useState(0);
    const [chartLoading, setChartLoading] = useState(true);
    const [activeTests, setActiveTests] = useState(null);
    const [activeTestsLoading, setActiveTestsLoading] = useState(true);
 
    useEffect(() => {
        dispatch(_fetchAllClasses(""));
        fetchSubmissionsStats();
        fetchAssignmentsStats();
    }, [dispatch]);
 
    const fetchAssignmentsStats = async () => {
        try {
            const response = await axios.get(API_ENDPOINTS.teacher.dashboard.assignmentsStatistics);
            if (response.status === 200) {
                setActiveTests(response.data?.total_assignments?.active ?? 0);
            }
        } catch (error) {
            console.error("Error fetching assignment stats:", error.response?.data || error.message);
        } finally {
            setActiveTestsLoading(false);
        }
    };
 
    const fetchSubmissionsStats = async () => {
        try {
            const response = await axios.get(API_ENDPOINTS.teacher.dashboard.submissionsStatistics);
            if (response.status === 200) {
                const { data, categories } = transformSubmissionStats(response.data);
                setChartData(data);
                setChartCategories(categories);
                let passed = 0;
                let failed = 0;
                response.data.data.forEach((c) => {
                    passed += c.total_passed_submissions || 0;
                    failed += c.total_failed_submissions || 0;
                });
                setChartPassed(passed);
                setChartFailed(failed);
            }
        } catch (error) {
            console.error("Error fetching submission stats:", error.response?.data || error.message);
        } finally {
            setChartLoading(false);
        }
    };
 
    const totalClasses = classData?.length ?? 0;
    const totalEnrolled = countStudents(classData, "Enrolled");
    const totalPending = countStudents(classData, "Pending");
    const firstName = teacherData?.first_name ?? "";
 
    const statCards = [
        {
            icon: <SchoolIcon />,
            value: isLoading ? "—" : totalClasses,
            label: "Total Classes",
            color: theme.palette.primary.main,
            loading: isLoading,
        },
        {
            icon: <PeopleIcon />,
            value: isLoading ? "—" : totalEnrolled,
            label: "Enrolled Students",
            color: theme.palette.success.main,
            loading: isLoading,
        },
        {
            icon: <HourglassEmptyIcon />,
            value: isLoading ? "—" : totalPending,
            label: "Pending Enrollments",
            color: theme.palette.warning.main,
            loading: isLoading,
        },
        {
            icon: <StarIcon />,
            value: activeTestsLoading ? "—" : (activeTests ?? 0),
            label: "Active Tests",
            color: theme.palette.info.main,
            loading: activeTestsLoading,
        },
    ];
 
    return (
        <Box
            sx={{ minHeight: "100vh", bgcolor: (t) => (t.palette.mode === "dark" ? "background.default" : "#f8f9fc") }}
        >
            <WelcomeBanner firstName={firstName} isMobile={isMobile} />
 
            <Box sx={{ px: { xs: 2, sm: 3, md: 4 }, mt: -3 }}>
                {/* Stat cards */}
                <Grid container spacing={{ xs: 1.5, sm: 2 }} sx={{ mb: 4 }}>
                    {statCards.map((s) => (
                        <Grid size={{ xs: 6, md: 3 }} key={s.label}>
                            <StatCard {...s} />
                        </Grid>
                    ))}
                </Grid>
 
                {/* Main two-column layout */}
                <Box
                    sx={{
                        display: "flex",
                        gap: 3,
                        alignItems: "flex-start",
                        flexDirection: { xs: "column", md: "row" },
                    }}
                >
                    {/* Left: charts */}
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                        <Stack spacing={3}>
                            <AssignmentSubmissionsChart
                                chartData={chartData}
                                chartCategories={chartCategories}
                                loading={chartLoading}
                            />
                            <PassedVsFailedCard passed={chartPassed} failed={chartFailed} loading={chartLoading} />
                        </Stack>
                    </Box>
 
                    {/* Right panel: fixed 310px */}
                    <Box sx={{ width: { xs: "100%", md: "310px" }, flexShrink: 0 }}>
                        <Stack spacing={3}>
                            <QuickActionsPanel
                                totalClasses={totalClasses}
                                totalEnrolled={totalEnrolled}
                                totalPending={totalPending}
                            />
                            <SearchProfileWidget />
                        </Stack>
                    </Box>
                </Box>
 
                <Box sx={{ height: 40 }} />
            </Box>
        </Box>
    );
}