All files / src/app/teacher-page/page/assignments/new-assignment Step3.jsx

73.91% Statements 68/92
69.35% Branches 43/62
51.85% Functions 14/27
73.03% Lines 65/89

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394                                                                1x                       1x   1x 58x 58x   81x 81x   58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x   58x               58x                   58x   58x 15x 15x   15x 1x 14x 2x   12x       58x 12x                                   12x     58x 24x 24x 24x               24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x     58x 24x     58x                                     1x     1x 1x                                                                                                 50x     114x                                                                                                                                                                                                                           285x                                                     4x 3x   1x                                                
/**
 * Modified by Allan Ninal — 2026-08-11
 *
 * Extracted the time_allowed + past-date rules into utils/helpers/assignmentTimeAllowed.js
 * and dropped the `moment` dependency (dayjs already covers `startOf("day")`).
 */
 
import {
    Box,
    Button,
    Card,
    CardContent,
    Checkbox,
    Chip,
    FormControl,
    FormControlLabel,
    FormGroup,
    FormHelperText,
    InputLabel,
    ListItemText,
    MenuItem,
    OutlinedInput,
    Select,
    Stack,
    TextField,
} from "@mui/material";
import React, { useEffect, useState } from "react";
import { DatePicker } from "antd";
import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos";
import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos";
import { useSelector } from "react-redux";
import { useParams } from "react-router-dom";
const { RangePicker } = DatePicker;
import { _fetchAllClasses } from "@/store/slices/teacher/TeacherClasses";
import { useDispatch } from "react-redux";
import dayjs from "dayjs";
import {
    isDateDisabledForRange,
    isUnlimitedTimeAllowed,
    minutesToTimeAllowed,
    timeAllowedToMinutes,
} from "@/utils/helpers/assignmentTimeAllowed";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
 
const dateTimeFormat = "MM/DD/YYYY hh:mm A";
 
const Step3 = ({ stepController, handleBack }) => {
    const dispatch = useDispatch();
    const { classCode } = useParams();
 
    const { assignmentData } = useSelector((state) => state.TeacherCreateAssignment);
    const { classData } = useSelector((state) => state.TeacherClasses);
 
    const [testFormat, setTestFormat] = useState("standard");
    const [selectedClass, setSelectedClass] = useState([]);
    const [dateAssigned, setDateAssigned] = useState([]);
    const [totalAttempts, setTotalAttempts] = useState(1);
    const [timeAllowedMinutes, setTimeAllowedMinutes] = useState(60);
    const [unlimitedTime, setUnlimitedTime] = useState(false);
    const [passingGrade, setPassingGrade] = useState(70);
    const [shuffleQuestions, setShuffleQuestions] = useState(true);
    const [shuffleChoices, setShuffleChoices] = useState(true);
    const [allowCalculator, setAllowCalculator] = useState(true);
    const [displayScore, setDisplayScore] = useState(true);
    const [displayCorrectAnswers, setDisplayCorrectAnswers] = useState(false);
    const [allowFeedback, setAllowFeedback] = useState(true);
    const [allowLateSubmissions, setAllowLateSubmissions] = useState(false);
    const [showError, setShowError] = useState(false);
    const [datesError, setDatesError] = useState(false);
    const [showDisplayAnswersConfirm, setShowDisplayAnswersConfirm] = useState(false);
 
    const rangePick = (dateRange) => {
        if (dateRange && dateRange.length === 2) {
            setDateAssigned([dateRange[0], dateRange[1]]);
        } else {
            setDateAssigned([]);
        }
    };
 
    const handleChange = (event) => {
        const {
            target: { value },
        } = event;
        setSelectedClass(typeof value === "string" ? value.split(",") : value);
        setShowError(false);
    };
 
    // Day-granular and local: the teacher picks a calendar day, not an instant.
    // See isDateDisabledForRange for why the currently loaded dates are exempted.
    const disabledDate = (current) => isDateDisabledForRange(current, dateAssigned);
 
    const clickNextStep = () => {
        const isDateInvalid = !dateAssigned[0] || !dateAssigned[1];
        const isClassInvalid = selectedClass.length === 0;
 
        if (isClassInvalid) {
            setShowError(isClassInvalid);
        } else if (isDateInvalid) {
            setDatesError(isDateInvalid);
        } else {
            proceedNext();
        }
    };
 
    const proceedNext = () => {
        const data = {
            testFormat,
            assignedClass: selectedClass,
            dateAssigned: {
                dateOpen: dateAssigned[0]?.format() || null,
                dateClose: dateAssigned[1]?.format() || null,
            },
            totalAttempts,
            timeAllowed: unlimitedTime ? null : minutesToTimeAllowed(timeAllowedMinutes),
            shuffleQuestions,
            shuffleChoices,
            allowCalculator,
            displayScore,
            displayCorrectAnswers,
            allowFeedback,
            allowLateSubmissions,
            passingGrade: passingGrade || 70,
        };
        stepController(2, data);
    };
 
    useEffect(() => {
        setTestFormat(assignmentData.step3?.testFormat ?? "standard");
        setSelectedClass(assignmentData.step3?.assignedClass ?? []);
        setDateAssigned(
            assignmentData.step3?.dateAssigned?.dateOpen && assignmentData.step3?.dateAssigned?.dateClose
                ? [
                      dayjs(assignmentData.step3.dateAssigned.dateOpen),
                      dayjs(assignmentData.step3.dateAssigned.dateClose),
                  ]
                : []
        );
        setTotalAttempts(assignmentData.step3?.totalAttempts ?? 1);
        setUnlimitedTime(isUnlimitedTimeAllowed(assignmentData.step3?.timeAllowed));
        setTimeAllowedMinutes(timeAllowedToMinutes(assignmentData.step3?.timeAllowed));
        setPassingGrade(assignmentData.step3?.passingGrade);
        setShuffleQuestions(assignmentData.step3?.shuffleQuestions ?? true);
        setShuffleChoices(assignmentData.step3?.shuffleChoices ?? true);
        setAllowCalculator(assignmentData.step3?.allowCalculator ?? true);
        setDisplayScore(assignmentData.step3?.displayScore ?? true);
        setDisplayCorrectAnswers(assignmentData.step3?.displayCorrectAnswers ?? false);
        setAllowFeedback(assignmentData.step3?.allowFeedback ?? true);
        setAllowLateSubmissions(assignmentData.step3?.allowLateSubmissions ?? false);
    }, [assignmentData]);
 
    useEffect(() => {
        dispatch(_fetchAllClasses(""));
    }, []);
 
    return (
        <>
            <YesNoOption
                title="Missing Dates"
                message="Both the open and close dates are empty. Do you want to proceed anyway?"
                showDialog={datesError}
                clickNo={() => {
                    setDatesError(false);
                }}
                clickYes={() => {
                    setDatesError(false);
                    proceedNext();
                }}
            />
            <YesNoOption
                title="Display Correct Answers"
                message="Are you sure you want to display the correct answers to students after they submit?"
                showDialog={showDisplayAnswersConfirm}
                clickNo={() => {
                    setShowDisplayAnswersConfirm(false);
                }}
                clickYes={() => {
                    setDisplayCorrectAnswers(true);
                    setShowDisplayAnswersConfirm(false);
                }}
            />
            <Box
                sx={{
                    mt: 5,
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "space-between",
                    gap: "2%",
                }}
            >
                <Button
                    id="teacher-class-assignment-step3-back"
                    sx={{ mt: 5, height: 40 }}
                    variant="contained"
                    color="primary"
                    onClick={handleBack}
                >
                    <ArrowBackIosIcon />
                </Button>
                <Card sx={{ width: "100%", p: 5, mb: 10 }}>
                    <CardContent sx={{ width: "50%", display: "flex", flexDirection: "column", gap: 2 }}>
                        <FormControl fullWidth required sx={{ mb: 1 }}>
                            <InputLabel>Assignment</InputLabel>
                            <Select
                                required
                                value={testFormat}
                                onChange={(e) => {
                                    setTestFormat(e.target.value);
                                }}
                                fullWidth
                                id="testFormat"
                                name="testFormat"
                                label="Assignment"
                            >
                                <MenuItem value="standard">Class Assignment</MenuItem>
                                <MenuItem value="special">Individual Assignment</MenuItem>
                                <MenuItem value="practice">Non-Graded Assignment</MenuItem>
                            </Select>
                        </FormControl>
                        <FormControl fullWidth required margin="normal" error={showError}>
                            <InputLabel size="small">Assigned to</InputLabel>
                            <Select
                                label="Assigned to"
                                multiple
                                value={selectedClass}
                                onChange={handleChange}
                                input={<OutlinedInput label="Assigned to" />}
                                renderValue={(selected) => selected.join(", ")}
                            >
                                {classData?.map((classItem) => (
                                    <MenuItem
                                        key={classItem?._id}
                                        value={`${classItem.title} (${classItem.class_code})`}
                                    >
                                        <Checkbox
                                            checked={
                                                selectedClass.indexOf(`${classItem.title} (${classItem.class_code})`) >
                                                -1
                                            }
                                        />
                                        <ListItemText primary={`${classItem.title} (${classItem.class_code})`} />
                                        {classItem.class_code === classCode && (
                                            <Chip label="Current Class" size="small" color="primary" sx={{ ml: 1 }} />
                                        )}
                                    </MenuItem>
                                ))}
                            </Select>
                            {showError && <FormHelperText>Assigned class is required</FormHelperText>}
                        </FormControl>
                        <FormControl fullWidth margin="normal" sx={{ mb: 3 }}>
                            <RangePicker
                                value={dateAssigned}
                                style={{
                                    // border: showError ? "1px solid red" : "",
                                    height: "3.5rem",
                                }}
                                onChange={rangePick}
                                disabledDate={disabledDate}
                                showTime={{ format: "hh:mm A", use12Hours: true }}
                                format={dateTimeFormat}
                                size="large"
                            />
                        </FormControl>
                        <FormControl fullWidth sx={{ mb: 5 }}>
                            <InputLabel>No. of Attempts</InputLabel>
                            <Select
                                value={totalAttempts}
                                onChange={(e) => {
                                    setTotalAttempts(e.target.value);
                                }}
                                fullWidth
                                label="No. of Attempts"
                            >
                                <MenuItem value="1">1</MenuItem>
                                <MenuItem value="2">2</MenuItem>
                                <MenuItem value="3">3</MenuItem>
                            </Select>
                        </FormControl>
                        <TextField
                            variant="outlined"
                            label="Passing Grade"
                            type="number"
                            value={passingGrade}
                            onChange={(e) => {
                                const value = e.target.value;
                                if (/^\d{0,2}$/.test(value)) {
                                    setPassingGrade(value);
                                }
                            }}
                            onBlur={() => {
                                if (passingGrade === "") {
                                    setPassingGrade(70);
                                }
                            }}
                            InputLabelProps={{ shrink: true }}
                            sx={{ mb: 5 }}
                        />
                        <TextField
                            variant="outlined"
                            label="Allowed Time (minutes)"
                            type="number"
                            value={timeAllowedMinutes}
                            disabled={unlimitedTime}
                            onChange={(e) => {
                                const value = e.target.value;
                                if (/^\d{0,4}$/.test(value)) {
                                    setTimeAllowedMinutes(value);
                                }
                            }}
                            onBlur={() => {
                                if (timeAllowedMinutes === "" || Number(timeAllowedMinutes) <= 0) {
                                    setTimeAllowedMinutes(60);
                                }
                            }}
                            helperText={
                                unlimitedTime ? "Students will have no time limit" : "e.g. 90 for 1 hour 30 minutes"
                            }
                            InputLabelProps={{ shrink: true }}
                            sx={{ mb: 1 }}
                        />
                        <Box sx={{ mb: 5 }}>
                            <FormControlLabel
                                control={
                                    <Checkbox
                                        id="teacher-assignment-setting-unlimited-time"
                                        data-testid="unlimited-time-checkbox"
                                        checked={unlimitedTime}
                                        onChange={(e) => setUnlimitedTime(e.target.checked)}
                                    />
                                }
                                label="Unlimited Time"
                            />
                        </Box>
                        {[
                            ["Shuffle Questions", shuffleQuestions, setShuffleQuestions],
                            ["Shuffle Choices", shuffleChoices, setShuffleChoices],
                            ["Allow Calculator", allowCalculator, setAllowCalculator],
                            ["Display Score After Submit", displayScore, setDisplayScore],
                            ["Allow Feedback", allowFeedback, setAllowFeedback],
                        ].map(([label, value, setter]) => (
                            <Box key={label}>
                                <FormControlLabel
                                    control={<Checkbox checked={value} onChange={(e) => setter(e.target.checked)} />}
                                    label={label}
                                />
                            </Box>
                        ))}
                        {/* EI-1210: late-submission teacher-approval toggle */}
                        <Box>
                            <FormControlLabel
                                control={
                                    <Checkbox
                                        id="teacher-assignment-setting-allow-late-submissions"
                                        data-testid="allow-late-submissions-checkbox"
                                        checked={allowLateSubmissions}
                                        onChange={(e) => setAllowLateSubmissions(e.target.checked)}
                                    />
                                }
                                label="Allow late submissions (teacher approval)"
                            />
                        </Box>
                        <Box>
                            <FormControlLabel
                                control={
                                    <Checkbox
                                        checked={displayCorrectAnswers}
                                        onChange={(e) => {
                                            if (e.target.checked) {
                                                setShowDisplayAnswersConfirm(true);
                                            } else {
                                                setDisplayCorrectAnswers(false);
                                            }
                                        }}
                                    />
                                }
                                label="Display Correct Answers After Submit"
                            />
                        </Box>
                    </CardContent>
                </Card>
                <Button
                    id="teacher-class-assignment-step3-next"
                    sx={{ mt: 5, height: 40 }}
                    variant="contained"
                    onClick={clickNextStep}
                >
                    <ArrowForwardIosIcon />
                </Button>
            </Box>
        </>
    );
};
 
export default Step3;