All files / src/app/student-page/page/class-details ClassDetails.jsx

97.56% Statements 40/41
83.33% Branches 20/24
93.33% Functions 14/15
97.22% Lines 35/36

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260                                      1x 117x               1x 117x                         1x 40x 40x   40x   40x 40x   40x 39x 39x 38x                     40x 5x     5x     40x 8x 8x 3x 2x 2x   1x     5x   8x       40x   39x 39x   39x           1x                                                                                                   39x                                                                                       10x                                                             1x                   39x                                                  
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
import { Box, Button, Chip, Paper, Stack, Typography } from "@mui/material";
import ImageOutlinedIcon from "@mui/icons-material/ImageOutlined";
import PersonIcon from "@mui/icons-material/Person";
import TagIcon from "@mui/icons-material/Tag";
import ArticleIcon from "@mui/icons-material/Article";
import CalendarMonthIcon from "@mui/icons-material/CalendarMonth";
import ScheduleIcon from "@mui/icons-material/Schedule";
import { alpha } from "@mui/material/styles";
import { API_ENDPOINTS } from "@/api/endpoints";
import { formatDate } from "@/utils/helpers/utcToLocalTime";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
import SimpleDialog from "@/utils/components/dialogs/SimpleDialog";
import { _fetchSpecificClassByCode } from "@/store/slices/student/StudentSpecificClass";
import ViewTeacher from "@/app/student-page/components/class-details/ViewTeacher";
 
const SectionCard = ({ title, children }) => (
    <Box sx={{ p: 2.5, borderRadius: 2, bgcolor: "background.paper", border: "1px solid", borderColor: "divider" }}>
        <Typography variant="subtitle2" fontWeight={600} sx={{ mb: 2 }}>
            {title}
        </Typography>
        {children}
    </Box>
);
 
const InfoRow = ({ icon, label, value }) => (
    <Stack direction="row" spacing={2} alignItems="flex-start">
        {icon}
        <Box sx={{ minWidth: 0 }}>
            <Typography variant="caption" color="text.secondary">
                {label}
            </Typography>
            <Typography variant="body2" fontWeight={500} sx={{ wordBreak: "break-word" }}>
                {value}
            </Typography>
        </Box>
    </Stack>
);
 
const ClassDetails = () => {
    const { specificClassData } = useSelector((state) => state.StudentSpecificClass);
    const { studentData } = useSelector((state) => state.StudentData);
 
    const dispatch = useDispatch();
 
    const [showYesNoOption, setShowYesNoOption] = useState(false);
    const [showTeacher, setShowTeacher] = useState(false);
 
    const isStudentRequestingToLeave = (classData, studentEmail) => {
        if (!classData || !Array.isArray(classData.students)) return false;
        const student = classData.students.find((s) => s.email === studentEmail);
        return student ? student.is_requesting_to_leave === true : false;
    };
 
    /**
     * Modified by Allan Ninal — a failed leave request said nothing at all.
     *
     * The only handling was a console.error, and the confirmation dialog stayed open,
     * so a student who pressed Yes had no way to tell whether they had asked to leave
     * the class or not. Any status other than 200 fell through the same way, in
     * silence. Now every outcome is reported and the dialog always closes.
     */
    const leaveErrorMessage = (error) => {
        const detail = error?.response?.data?.detail;
        // Keep the server's reason when it gives one; axios' own wording is not
        // something to put in front of a student.
        return typeof detail === "string" && detail.trim() ? detail : "Could not send your request. Please try again.";
    };
 
    const clickYesLeaveOption = async () => {
        try {
            const response = await axios.patch(API_ENDPOINTS.student.class.leave(specificClassData.class_code));
            if (response.status === 200) {
                enqueueSnackbar(`${response.data.detail}`, { variant: "success" });
                dispatch(_fetchSpecificClassByCode(specificClassData.class_code));
            } else {
                enqueueSnackbar("Could not send your request. Please try again.", { variant: "error" });
            }
        } catch (error) {
            enqueueSnackbar(leaveErrorMessage(error), { variant: "error" });
        } finally {
            setShowYesNoOption(false);
        }
    };
 
    if (!specificClassData) return null;
 
    const semesterLabel = specificClassData.semester.charAt(0).toUpperCase() + specificClassData.semester.slice(1);
    const requestingToLeave = isStudentRequestingToLeave(specificClassData, studentData.email);
 
    return (
        <>
            <YesNoOption
                title="Confirm Leave Class"
                message="Do you want to leave in this class? You are attempting to leave the class. Your request must be approved by the teacher before you can successfully exit."
                showDialog={showYesNoOption}
                clickNo={() => setShowYesNoOption(false)}
                clickYes={clickYesLeaveOption}
            />
            <SimpleDialog
                open={showTeacher}
                title="Teacher Profile"
                children={<ViewTeacher />}
                actions={
                    <Button variant="contained" onClick={() => setShowTeacher(false)}>
                        Close
                    </Button>
                }
            />
 
            <Stack spacing={2.5}>
                {/* Cover photo, title, and leave-class action */}
                <Paper
                    elevation={0}
                    sx={{ borderRadius: 2, border: "1px solid", borderColor: "divider", overflow: "hidden" }}
                >
                    <Box sx={{ position: "relative" }}>
                        {specificClassData.class_photo ? (
                            <Box
                                component="img"
                                src={specificClassData.class_photo}
                                alt="Class cover"
                                sx={{ width: "100%", height: 200, objectFit: "cover", display: "block" }}
                            />
                        ) : (
                            <Box
                                sx={{
                                    width: "100%",
                                    height: 200,
                                    bgcolor: "action.hover",
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                }}
                            >
                                <ImageOutlinedIcon sx={{ fontSize: 48, color: "action.disabled" }} />
                            </Box>
                        )}
 
                        <Chip
                            label={semesterLabel}
                            size="small"
                            sx={{
                                position: "absolute",
                                top: 12,
                                right: 12,
                                bgcolor: (t) => alpha(t.palette.background.paper, 0.92),
                                color: "text.primary",
                                fontWeight: 700,
                                backdropFilter: "blur(4px)",
                            }}
                        />
                    </Box>
 
                    <Box sx={{ p: 2.5 }}>
                        <Stack
                            direction={{ xs: "column", sm: "row" }}
                            justifyContent="space-between"
                            alignItems={{ xs: "flex-start", sm: "center" }}
                            spacing={1.5}
                        >
                            <Box sx={{ minWidth: 0 }}>
                                <Typography variant="h6" fontWeight={700} sx={{ wordBreak: "break-word" }}>
                                    {specificClassData.title}{" "}
                                    <Typography
                                        component="span"
                                        variant="inherit"
                                        color="text.secondary"
                                        fontWeight={400}
                                    >
                                        ({specificClassData.section})
                                    </Typography>
                                </Typography>
                                <Stack
                                    direction="row"
                                    alignItems="center"
                                    spacing={0.5}
                                    sx={{ mt: 0.5, color: "text.secondary" }}
                                >
                                    <TagIcon sx={{ fontSize: 14 }} />
                                    <Typography variant="body2" sx={{ fontFamily: "monospace" }}>
                                        {specificClassData.class_code}
                                    </Typography>
                                </Stack>
                            </Box>
 
                            <Button
                                variant="outlined"
                                color="error"
                                disabled={requestingToLeave}
                                onClick={() => setShowYesNoOption(true)}
                                sx={{ flexShrink: 0 }}
                            >
                                {requestingToLeave ? "Class Leave Requested" : "Request to Leave Class"}
                            </Button>
                        </Stack>
                    </Box>
                </Paper>
 
                <SectionCard title="Class Information">
                    <Stack spacing={2}>
                        <InfoRow
                            icon={<ArticleIcon color="primary" />}
                            label="Description"
                            value={specificClassData.description || "(No description available)"}
                        />
                        <InfoRow
                            icon={<CalendarMonthIcon color="primary" />}
                            label="Date Created"
                            value={formatDate(specificClassData.created_at)}
                        />
                    </Stack>
                </SectionCard>
 
                <SectionCard title="Teacher">
                    <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={1.5}>
                        <InfoRow
                            icon={<PersonIcon color="primary" />}
                            label="Instructor"
                            value={`${specificClassData.teacher.first_name} ${specificClassData.teacher.middle_name ?? ""} ${specificClassData.teacher.last_name}`}
                        />
                        <Button variant="outlined" color="primary" onClick={() => setShowTeacher(true)}>
                            View Teacher
                        </Button>
                    </Stack>
                </SectionCard>
 
                <SectionCard title="Schedule">
                    {specificClassData.schedules.length > 0 ? (
                        <Stack spacing={1.5}>
                            {specificClassData.schedules.map((item, index) => (
                                <Stack key={index} direction="row" spacing={2} alignItems="center">
                                    <ScheduleIcon color="primary" />
                                    <Box>
                                        <Typography variant="body2" fontWeight={500}>
                                            {item.day}
                                        </Typography>
                                        <Typography variant="caption" color="text.secondary">
                                            {item.time_start} - {item.time_end}
                                        </Typography>
                                    </Box>
                                </Stack>
                            ))}
                        </Stack>
                    ) : (
                        <Typography variant="body2" color="text.disabled">
                            No added schedules
                        </Typography>
                    )}
                </SectionCard>
            </Stack>
        </>
    );
};
 
export default ClassDetails;