All files / src/app/teacher-page/components/class-details CreateNewSched.jsx

97.05% Statements 66/68
100% Branches 20/20
93.1% Functions 27/29
96.96% Lines 64/66

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                                                              4x 166x 20x     166x               166x 244x 126x   63x 63x 63x         166x 166x                       166x                     62x 62x           91x 91x     91x 91x           91x 91x     91x 91x         166x     25x             166x   10x 30x       10x 10x     166x 1x 1x     166x 2x 2x 2x 2x       166x 1x         1x 1x 1x 1x     166x 10x 6x         6x 6x 6x 6x 3x   3x 3x 3x 3x         166x         1x                             111x                                                             2x                                                 602x                         7x                                           7x                                                                               13x                        
/**
 * Schedule builder for the edit-class form.
 *
 * Modified by Allan Ninal: the overlap check only ever inspected the most recent
 * schedule, and `schedIsValid` read a stale error map so none of the yup rules could
 * block a save on the first click. See the header of
 * tests/unit/components/teacher/createNewSched.test.jsx.
 */
 
import React, { useEffect } from "react";
import { Box } from "@mui/material";
import Button from "@mui/material/Button";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import FormHelperText from "@mui/material/FormHelperText";
import { TimePicker } from "@mui/x-date-pickers/TimePicker";
import Grid from "@mui/material/Grid";
import AddIcon from "@mui/icons-material/Add";
import Paper from "@mui/material/Paper";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/Delete";
import AccessTimeIcon from "@mui/icons-material/AccessTime";
import { _updateClass } from "@/store/slices/teacher/TeacherSpecificClass";
import { useState } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import dayjs from "dayjs";
import WarningMessage from "./WarningMessage";
 
const CreateNewSched = ({ schedules, setSchedules }) => {
    useEffect(() => {
        defaultValues();
    }, []);
 
    const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
 
    /**
     * Does the proposed slot overlap ANY schedule already on that day?
     *
     * This used to look at `[...schedules].reverse()[0]` only — the most recently added
     * entry — so a clash with any earlier one was accepted.
     */
    const hasTimeConflict = (day, timeStart, timeEnd) =>
        schedules
            .filter((entry) => entry.day === day)
            .some((entry) => {
                const schedTimeStart = dayjs(entry.time_start, "hh:mm A");
                const schedTimeEnd = dayjs(entry.time_end, "hh:mm A");
                return (
                    schedTimeStart.isBetween(timeStart, timeEnd, null, "[]") ||
                    schedTimeEnd.isBetween(timeStart, timeEnd, null, "[]")
                );
            });
    const [openNewSchedule, setOpenNewSchedule] = useState(false);
    const [showWarning, setWarning] = useState(false);
 
    const {
        values,
        touched,
        errors,
        handleChange,
        handleBlur,
        setFieldTouched,
        setFieldValue,
        setValues,
        validateForm,
    } = useFormik({
        initialValues: {
            day: "",
            timeStart: "",
            timeEnd: "",
        },
        validationSchema: yup.object({
            day: yup
                .string()
                .required("Day is required")
                .test("day-is-invalid", "Day has conflict", function () {
                    const { day, timeStart, timeEnd } = this.parent;
                    return !hasTimeConflict(day, timeStart, timeEnd);
                }),
            timeStart: yup
                .string()
                .required("Time start is required")
                .test("time-is-invalid", "Start Time must be before Time End", function (value) {
                    const { timeEnd } = this.parent;
                    return new Date(timeEnd) > new Date(value);
                })
                .test("day-is-invalid", "Time start has conflict", function () {
                    const { day, timeStart, timeEnd } = this.parent;
                    return !hasTimeConflict(day, timeStart, timeEnd);
                }),
            timeEnd: yup
                .string()
                .required("Time end is required")
                .test("time-is-invalid", "Time End must be after Time Start", function (value) {
                    const { timeStart } = this.parent;
                    return new Date(timeStart) < new Date(value);
                })
                .test("day-is-invalid", "Time end has conflict", function () {
                    const { day, timeStart, timeEnd } = this.parent;
                    return !hasTimeConflict(day, timeStart, timeEnd);
                }),
        }),
    });
 
    const defaultValues = () => {
        // Through setValues, not by assigning to `values` — Formik never sees a direct
        // mutation, so the day stayed selected after an add.
        setValues({
            day: "",
            timeStart: dayjs("8:00 AM", "h:mm A"),
            timeEnd: dayjs("9:00 AM", "h:mm A"),
        });
    };
 
    const schedIsValid = async () => {
        // touch all fields
        Object.keys(values).forEach((fieldName) => {
            setFieldTouched(fieldName, true);
        });
        // Re-validate rather than reading `errors`, which is empty until something has
        // validated — so every rule here was inert on the first click.
        const validationErrors = await validateForm();
        return Object.keys(validationErrors).length === 0;
    };
 
    const cancelSchedule = () => {
        defaultValues();
        setOpenNewSchedule(false);
    };
 
    const removeSched = (indexToRemove) => {
        setSchedules((prevSchedules) => {
            const newSchedules = [...prevSchedules];
            newSchedules.splice(indexToRemove, 1);
            return newSchedules;
        });
    };
 
    const handleProceed = () => {
        const newSchedule = {
            day: values.day,
            time_start: dayjs(values.timeStart).format("hh:mm A"),
            time_end: dayjs(values.timeEnd).format("hh:mm A"),
        };
        setSchedules((prevSchedules) => [...prevSchedules, newSchedule]);
        defaultValues();
        setOpenNewSchedule(false);
        setWarning(false);
    };
 
    const saveSchedule = async () => {
        if (await schedIsValid()) {
            const newSchedule = {
                day: values.day,
                time_start: dayjs(values.timeStart).format("hh:mm A"),
                time_end: dayjs(values.timeEnd).format("hh:mm A"),
            };
            const timeStart = dayjs(newSchedule.time_start, "hh:mm A");
            const workingStartTime = dayjs("7:00 AM", "hh:mm A");
            const workingEndTime = dayjs("5:00 PM", "hh:mm A");
            if (!timeStart.isBetween(workingStartTime, workingEndTime, null, "[]")) {
                setWarning(true);
            } else {
                setSchedules((prevSchedules) => [...prevSchedules, newSchedule]);
                defaultValues();
                setOpenNewSchedule(false);
                setWarning(false);
            }
        }
    };
 
    return (
        <>
            <WarningMessage
                showDialog={showWarning}
                clickNo={() => {
                    setWarning(false);
                }}
                clickYes={handleProceed}
            />
            <div
                style={{
                    width: "100%",
                    display: "flex",
                    flexDirection: "column",
                    gap: 25,
                }}
            >
                {schedules.length > 0 && (
                    <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                        {schedules.map((entry, index) => (
                            <Paper
                                key={index}
                                variant="outlined"
                                sx={{
                                    padding: 2,
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "space-between",
                                }}
                            >
                                <Box
                                    sx={{
                                        display: "flex",
                                        flexDirection: "column",
                                        alignItems: "start",
                                        gap: 1,
                                    }}
                                >
                                    <span>{entry.day}</span>
                                    <Box sx={{ display: "flex", alignItems: "center" }}>
                                        <AccessTimeIcon />
                                        <span>{entry.time_start}</span>
                                        <span> - </span>
                                        <span>{entry.time_end}</span>
                                    </Box>
                                </Box>
                                <Box>
                                    <IconButton
                                        aria-label="delete"
                                        size="small"
                                        onClick={() => {
                                            removeSched(index);
                                        }}
                                    >
                                        <DeleteIcon />
                                    </IconButton>
                                </Box>
                            </Paper>
                        ))}
                    </Box>
                )}
                {openNewSchedule && (
                    <Grid container spacing={2}>
                        <Grid size={{ xs: 4 }}>
                            <FormControl fullWidth error={touched.day && Boolean(errors.day)}>
                                <InputLabel>Day</InputLabel>
                                <Select
                                    id="day"
                                    name="day"
                                    value={values.day}
                                    onChange={handleChange}
                                    onBlur={handleBlur}
                                    label="Day"
                                    fullWidth
                                >
                                    {days.map((day, index) => (
                                        <MenuItem key={index} value={day}>
                                            {day}
                                        </MenuItem>
                                    ))}
                                </Select>
                                <FormHelperText>{touched.day && errors.day}</FormHelperText>
                            </FormControl>
                        </Grid>
                        <Grid size={{ xs: 4 }}>
                            <TimePicker
                                ampm={true}
                                value={values.timeStart}
                                onChange={(value) => {
                                    setFieldValue("timeStart", value);
                                }}
                                onBlur={handleBlur}
                                label="Time Start"
                                name="timeStart"
                                fullWidth
                                slotProps={{
                                    textField: {
                                        error: errors.timeStart && Boolean(errors.timeStart),
                                        helperText: errors.timeStart,
                                        onKeyDown: (e) => {
                                            e.preventDefault();
                                        },
                                    },
                                }}
                            />
                        </Grid>
                        <Grid size={{ xs: 4 }}>
                            <TimePicker
                                ampm={true}
                                value={values.timeEnd}
                                onChange={(value) => {
                                    setFieldValue("timeEnd", value);
                                }}
                                onBlur={handleBlur}
                                label="Time End"
                                name="timeEnd"
                                fullWidth
                                slotProps={{
                                    textField: {
                                        error: errors.timeEnd && Boolean(errors.timeEnd),
                                        helperText: errors.timeEnd,
                                        onKeyDown: (e) => {
                                            e.preventDefault();
                                        },
                                    },
                                }}
                            />
                        </Grid>
                        <Grid
                            size={{ xs: 12 }}
                            style={{
                                display: "flex",
                                alignItems: "center",
                                gap: 10,
                                justifyContent: "end",
                            }}
                        >
                            <Button size="small" variant="outlined" color="primary" onClick={cancelSchedule}>
                                Cancel
                            </Button>
                            <Button size="small" variant="contained" color="primary" onClick={saveSchedule}>
                                Add
                            </Button>
                        </Grid>
                    </Grid>
                )}
                {!openNewSchedule && (
                    <Button
                        variant="text"
                        startIcon={<AddIcon />}
                        onClick={() => {
                            setOpenNewSchedule(!openNewSchedule);
                        }}
                    >
                        Add new schedule
                    </Button>
                )}
            </div>
        </>
    );
};
 
export default CreateNewSched;