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

96.66% Statements 58/60
100% Branches 19/19
92.59% Functions 25/27
96.42% Lines 54/56

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                                            1x 164x 21x     164x 164x 164x   164x                       63x           96x 96x           96x 96x         164x 29x             164x 11x 33x   11x 11x     164x 1x 1x     164x 2x 2x 2x 2x       164x 1x         1x 1x 1x 1x     164x 11x 9x         9x 9x 9x 9x 3x   6x 6x 6x 6x         164x         1x                             94x                                                               2x                                                 588x   574x                           5x                                             5x                                                                                                         15x                        
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"];
    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-unique", "This day already has a schedule", function (value) {
                    return !schedules.some((s) => s.day === value);
                }),
            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);
                }),
            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);
                }),
        }),
    });
 
    const defaultValues = () => {
        setValues({
            day: "",
            timeStart: dayjs("8:00 AM", "h:mm A"),
            timeEnd: dayjs("9:00 AM", "h:mm A"),
        });
    };
 
    const schedIsValid = async () => {
        Object.keys(values).forEach((fieldName) => {
            setFieldTouched(fieldName, true);
        });
        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
                                id={`schedule-${entry.day}-${entry.time_start}-${entry.time_end}`}
                                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
                                        .filter((day) => !schedules.some((s) => s.day === day))
                                        .map((day, index) => (
                                            <MenuItem id={`day-${day}`} key={index} value={day}>
                                                {day}
                                            </MenuItem>
                                        ))}
                                </Select>
                                <FormHelperText>{touched.day && errors.day}</FormHelperText>
                            </FormControl>
                        </Grid>
                        <Grid size={{ xs: 4 }}>
                            <TimePicker
                                id="schedule-timeStart"
                                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
                                id="schedule-timeEnd"
                                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
                                id="schedule-cancel-button"
                                size="small"
                                variant="outlined"
                                color="primary"
                                onClick={cancelSchedule}
                            >
                                Cancel
                            </Button>
                            <Button
                                id="schedule-add-button"
                                size="small"
                                variant="contained"
                                color="primary"
                                onClick={saveSchedule}
                            >
                                Add
                            </Button>
                        </Grid>
                    </Grid>
                )}
                {!openNewSchedule && schedules.length < 7 && (
                    <Button
                        id="add-new-schedule-button"
                        variant="text"
                        startIcon={<AddIcon />}
                        onClick={() => {
                            setOpenNewSchedule(!openNewSchedule);
                        }}
                    >
                        Add new schedule
                    </Button>
                )}
            </div>
        </>
    );
};
 
export default CreateNewSched;