All files / src/app/student-page/page/assignments/take-assignment TakeAssignmentPage.jsx

100% Statements 66/66
100% Branches 29/29
100% Functions 14/14
100% Lines 60/60

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                              1x 3x 3x 2x             1x 1x 1x   1x 47x 47x 47x   47x 47x 47x   47x 47x 47x 47x   47x 32x 31x   31x 7x 7x   7x 1x 1x   6x 6x 6x           24x 24x       47x 32x 31x             47x 1x 1x 1x 1x     47x 8x 15x         8x 8x 8x           5x 4x           3x   8x       47x   38x 38x   34x   3x   1x       38x           1x           1x         3x                                                                                                                
import React, { useEffect, useRef, useState } from "react";
import QuestionsList1 from "./layout-1/QuestionsList";
import PaginatedLayout from "./layout-2/Paginated";
import { AppBar, Box, Button, Toolbar, Typography } from "@mui/material";
import PageHeader from "./components/PageHeader";
import AnswerTracker from "./components/AnswerTracker";
import LockdownGuard from "@/utils/components/LockdownGuard";
// import AssignmentDetails from "./components/AssignmentDetails";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
 
/** Modified by Allan Ninal — keep the server's reason, never axios' wording. */
const saveFailureMessage = (error) => {
    const detail = error?.response?.data?.detail;
    if (typeof detail === "string" && detail.trim()) return detail;
    return "Your answers could not be saved. Please check your connection and try again.";
};
import { API_ENDPOINTS } from "@/api/endpoints";
import SimpleLoading from "@/utils/components/SimpleLoading";
import { _restoreSpecificAssignmentData } from "@/store/slices/student/StudentSpecificAssignment";
import { _restoreQuestionPageSession, _triggerViolationLockout } from "@/store/slices/student/StudentQuestionPage";
 
const SESSION_KEY = "takeAssignmentId";
const SESSION_ASSIGNMENT_DATA_KEY = "takeAssignmentData";
const SESSION_QUESTION_PAGE_KEY = "takeAssignmentQuestionPage";
 
const Main = () => {
    const { studentData } = useSelector((state) => state.StudentData);
    const { myAnswers, settings, assignmentQuestions } = useSelector((state) => state.StudentQuestionPage);
    const { specificAssignmentData } = useSelector((state) => state.StudentSpecificAssignment);
    // const { classCode } = useParams();
    const dispatch = useDispatch();
    const location = useLocation();
    const navigate = useNavigate();
 
    const [showYesNoOption, setShowYesNoOption] = useState(false);
    const [isLoading, setLoading] = useState(false);
    const [page, setPage] = useState(1);
    const initialCheckDone = useRef(false);
 
    useEffect(() => {
        if (initialCheckDone.current) return;
        initialCheckDone.current = true;
 
        if (!specificAssignmentData) {
            const savedAssignmentData = sessionStorage.getItem(SESSION_ASSIGNMENT_DATA_KEY);
            const savedQuestionPage = sessionStorage.getItem(SESSION_QUESTION_PAGE_KEY);
 
            if (savedAssignmentData && savedQuestionPage) {
                dispatch(_restoreSpecificAssignmentData(JSON.parse(savedAssignmentData)));
                dispatch(_restoreQuestionPageSession(JSON.parse(savedQuestionPage)));
            } else {
                const storedAssignmentId = sessionStorage.getItem(SESSION_KEY);
                const parentPath = location.pathname.replace(/\/answer$/, "");
                navigate(parentPath, {
                    replace: true,
                    state: storedAssignmentId ? { assignmentId: storedAssignmentId } : undefined,
                });
            }
        } else {
            sessionStorage.setItem(SESSION_KEY, specificAssignmentData.details._id);
            sessionStorage.setItem(SESSION_ASSIGNMENT_DATA_KEY, JSON.stringify(specificAssignmentData));
        }
    }, []);
 
    useEffect(() => {
        if (assignmentQuestions?.length > 0) {
            sessionStorage.setItem(
                SESSION_QUESTION_PAGE_KEY,
                JSON.stringify({ assignmentQuestions, myAnswersData: myAnswers.data, settings })
            );
        }
    }, [assignmentQuestions, myAnswers.version, settings]);
 
    const handleYesOption = () => {
        sessionStorage.removeItem(SESSION_KEY);
        sessionStorage.removeItem(SESSION_ASSIGNMENT_DATA_KEY);
        sessionStorage.removeItem(SESSION_QUESTION_PAGE_KEY);
        navigate(-1);
    };
 
    const saveAnswers = async () => {
        let answers = [
            ...myAnswers.data.map(({ questionType, answer, category, ...rest }) => ({
                ...rest,
                studentAnswer: answer ?? "",
            })),
        ];
        setLoading(true);
        try {
            const response = await axios.post(
                API_ENDPOINTS.student.assignment.saveAnswers(specificAssignmentData.details._id),
                {
                    answers,
                }
            );
            if (response.status == 200) {
                enqueueSnackbar(response.data.message, { variant: "success" });
            }
        } catch (error) {
            // Modified by Allan Ninal — a failed save looked exactly like a successful
            // one: nothing happened either way. A student who saves, closes the tab and
            // comes back finds the work gone.
            enqueueSnackbar(saveFailureMessage(error), { variant: "error" });
        } finally {
            setLoading(false);
        }
    };
 
    if (!specificAssignmentData) return null;
 
    const mainDisplay = () => {
        switch (settings.layout) {
            case "1":
                return <QuestionsList1 page={page} />;
            case "2":
                return <PaginatedLayout page={page} setPage={setPage} />;
            default:
                return <Box>Invalid Template</Box>;
        }
    };
 
    return (
        <React.Fragment>
            <SimpleLoading showLoading={isLoading} />
            <LockdownGuard
                onCancel={handleYesOption}
                assignmentId={specificAssignmentData.details._id}
                onThresholdExceeded={(payload) => dispatch(_triggerViolationLockout(payload))}
            />
            <YesNoOption
                title="Confirm Back"
                message="Would you like to return to assignment page?"
                showDialog={showYesNoOption}
                clickNo={() => setShowYesNoOption(false)}
                clickYes={handleYesOption}
            />
            <AppBar position="relative" color="primary">
                <Toolbar sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <Button variant="inherit" onClick={() => setShowYesNoOption(true)}>
                        BACK
                    </Button>
                    <Typography variant="h6">{`${studentData.first_name} ${studentData.middle_name ?? ""} ${studentData.last_name}`}</Typography>
                    <Button variant="contained" color="success" onClick={saveAnswers}>
                        SAVE
                    </Button>
                </Toolbar>
            </AppBar>
            <PageHeader />
            <Box
                sx={{
                    display: "flex",
                    gap: 2,
                    px: 2,
                    pt: 3,
                    pb: 6,
                    minHeight: "calc(100vh - 180px)",
                    alignItems: "flex-start",
                }}
            >
                <Box
                    sx={{
                        flex: 2,
                        overflowWrap: "break-word",
                        wordBreak: "break-word",
                        whiteSpace: "normal",
                        minWidth: 0,
                    }}
                >
                    {mainDisplay()}
                </Box>
                {myAnswers.isShow && (
                    <Box
                        sx={{
                            flex: "0 0 320px",
                            maxWidth: 320,
                            position: "sticky",
                            top: 80,
                            maxHeight: "calc(100vh - 100px)",
                            overflowY: "auto",
                            "&::-webkit-scrollbar": { width: 6 },
                            "&::-webkit-scrollbar-track": { background: "transparent" },
                            "&::-webkit-scrollbar-thumb": { background: "#c0c8d4", borderRadius: 3 },
                            "&::-webkit-scrollbar-thumb:hover": { background: "#a0a8b4" },
                        }}
                    >
                        <AnswerTracker page={page} setPage={setPage} />
                    </Box>
                )}
            </Box>
        </React.Fragment>
    );
};
 
export default Main;