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 | 1x 203x 184x 184x 184x 184x 184x 184x 184x 184x 169x 143x 189x 184x 13x 91x 13x 13x 184x 7x 49x 7x 7x 7x 184x 39x 39x 39x 184x 39x 39x 39x 184x 183x 77x 106x 184x 184x 40x 13x 44x 44x 44x 44x 44x 13x 11x 13x 13x 13x 11x 10x 10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 10x 10x 8x 8x 8x 8x 8x 6x 6x 10x 13x 184x 13x 13x 13x 13x 3x 3x 10x 3x 3x 7x 7x 7x 7x 7x 7x 184x 13x 13x 13x 13x 13x 13x 13x | import * as React from "react";
import AddIcon from "@mui/icons-material/Add";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import TextField from "@mui/material/TextField";
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 { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import { useSnackbar } from "notistack";
import { DemoContainer } from "@mui/x-date-pickers/internals/demo";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { _createNewClass, _clearErrorMessage } from "@/store/slices/teacher/TeacherClasses";
import { useState } from "react";
import CreateNewSched from "./CreateNewSched";
import { Alert, AlertTitle, Typography } from "@mui/material";
const NewClass = () => {
const { classData, hasErrors, classLimit, activeClassCount } = useSelector((state) => state.TeacherClasses);
// Disable the Create button when the teacher is at the 10-class backend cap
// so we never let them submit a request that's guaranteed to be rejected.
// Older backends omit `class_limit`/`active_class_count` → button stays
// enabled (no behaviour change in that case).
const hasCapInfo = typeof classLimit === "number" && typeof activeClassCount === "number";
const isAtClassCap = hasCapInfo && activeClassCount >= classLimit;
const dispatch = useDispatch();
const { enqueueSnackbar } = useSnackbar();
const [schedules, setSchedules] = useState([]);
const [openDialog, setDialog] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const { values, touched, errors, handleChange, handleBlur, setFieldTouched, setFieldError, setFieldValue } =
useFormik({
initialValues: {
semester: "",
title: "",
section: "",
description: "",
day: "",
timeStart: "",
timeEnd: "",
},
validationSchema: yup.object({
semester: yup.string().required("Semester is required"),
title: yup
.string()
.min(1, "Title must be at least 1 character long")
.max(25, "Title must be no more than 25 characters long")
.required("Title is required")
.test("no-trailing-space", "Title cannot end with a space", (value) => value?.trimEnd() === value),
section: yup
.string()
.min(1, "Section/Period must be at least 1 character long")
.max(25, "Section/Period must be no more than 25 characters long")
.required("Section/Period is required")
.test(
"no-trailing-space",
"Section/Period cannot end with a space",
(value) => value?.trimEnd() === value
),
description: yup
.string()
.min(1, "Description must be at least 1 character long")
.max(60, "Description must be no more than 60 characters long")
.test(
"no-trailing-space",
"Description cannot end with a space",
(value) => value?.trimEnd() === value
)
.max(60, "Description must be no more than 60 characters long"),
}),
});
const isValidated = () => {
// touch all fields
Object.keys(values).forEach((fieldName) => {
setFieldTouched(fieldName, true);
});
// check if there are errors
Eif (Object.keys(errors).length === 0) {
return true;
}
return false;
};
const resetAllFieldValues = () => {
Object.keys(values).forEach((key) => {
values[key] = "";
});
// remove all field errors
Object.keys(errors).forEach((fieldName) => {
setFieldError(fieldName, "");
});
setSchedules([]);
setErrorMessage("");
};
const sanitizeString = (input) => {
let sanitized = input.replace(/\s+/g, " ").trimStart();
Iif (sanitized.endsWith(" ")) sanitized = sanitized.slice(0, -1);
return sanitized;
};
const handleSanitizedChange = (event) => {
const { name, value } = event.target;
const sanitizedValue = sanitizeString(value);
setFieldValue(name, sanitizedValue, true);
};
const hasChanges = () => {
if (values.semester && values.title && values.section) {
return false;
}
return true;
};
const handleCancel = () => {
resetAllFieldValues();
dispatch(_clearErrorMessage());
setDialog(false);
};
const checkClassValidation = (classList, newClass) => {
const normalize = (str) => str.trim().toLowerCase();
const toMinutes = (timeStr) => {
const [time, modifier] = timeStr.split(" ");
let [hours, minutes] = time.split(":").map(Number);
if (modifier === "PM" && hours !== 12) hours += 12;
if (modifier === "AM" && hours === 12) hours = 0;
return hours * 60 + minutes;
};
const isTimeOverlap = (start1, end1, start2, end2) => {
return start1 < end2 && start2 < end1;
};
let hasDuplicate = false;
let hasScheduleConflict = false;
for (const existing of classList) {
if (existing.semester !== newClass.semester) continue;
const isSameTitle = normalize(existing.title) === normalize(newClass.title);
const isSameSection = normalize(existing.section) === normalize(newClass.section);
// Check for duplicate: same semester, same title, same section
if (isSameTitle && isSameSection) {
for (const eSched of existing.schedules) {
for (const nSched of newClass.schedules) {
Eif (eSched.day === nSched.day) {
const eStart = toMinutes(eSched.time_start);
const eEnd = toMinutes(eSched.time_end);
const nStart = toMinutes(nSched.time_start);
const nEnd = toMinutes(nSched.time_end);
Eif (isTimeOverlap(eStart, eEnd, nStart, nEnd)) {
hasDuplicate = true;
break;
}
}
}
Eif (hasDuplicate) break;
}
}
// General schedule conflict (regardless of title/section)
for (const eSched of existing.schedules) {
for (const nSched of newClass.schedules) {
if (eSched.day === nSched.day) {
const eStart = toMinutes(eSched.time_start);
const eEnd = toMinutes(eSched.time_end);
const nStart = toMinutes(nSched.time_start);
const nEnd = toMinutes(nSched.time_end);
if (isTimeOverlap(eStart, eEnd, nStart, nEnd)) {
hasScheduleConflict = true;
break;
}
}
}
if (hasScheduleConflict) break;
}
}
return { hasDuplicate, hasScheduleConflict };
};
const handleSave = () => {
Iif (!isValidated()) return;
const payload = {
semester: values.semester,
title: values.title,
section: values.section,
description: values.description,
schedules: [...schedules],
};
const { hasDuplicate, hasScheduleConflict } = checkClassValidation(classData, payload);
if (hasDuplicate) {
setErrorMessage("Class already exists.");
return;
}
if (hasScheduleConflict) {
setErrorMessage("Schedule conflict with existing class.");
return;
}
Eif (!hasDuplicate && !hasScheduleConflict) {
dispatch(_createNewClass(payload)).then((response) => {
Eif (!response.error) {
resetAllFieldValues();
setDialog(false);
enqueueSnackbar("Class successfully created", { variant: "success" });
}
});
}
};
return (
<>
<Button
id="teacher-classes-page-create-new-class-btn"
variant="contained"
color="primary"
startIcon={<AddIcon />}
fullWidth
disabled={isAtClassCap}
title={
isAtClassCap
? `You've reached the limit of ${classLimit} classes. Delete an existing class to create a new one.`
: undefined
}
onClick={() => {
setDialog(true);
}}
>
{isAtClassCap
? `Class limit reached (${activeClassCount}/${classLimit})`
: "Create New Class"}
</Button>
<Dialog
open={openDialog}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
fullWidth
>
<DialogTitle id="alert-dialog-title">Create New Class</DialogTitle>
<DialogContent dividers>
{errorMessage && (
<Alert severity="error" sx={{ mb: 2.5 }}>
{errorMessage}
</Alert>
)}
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={["TimePicker"]}>
<div
className="teacher-edit-class"
style={{
width: "100%",
display: "flex",
flexDirection: "column",
gap: 25,
}}
>
{hasErrors && (
<Alert sx={{ borderRadius: 0 }} severity="error">
{hasErrors}
</Alert>
)}
<FormControl fullWidth error={touched.semester && Boolean(errors.semester)}>
<InputLabel>Semester</InputLabel>
<Select
id="semester"
name="semester"
value={values.semester}
onChange={handleChange}
onBlur={handleBlur}
label="Semester"
fullWidth
required
>
<MenuItem id="semester-item-fall" value="fall">
Fall
</MenuItem>
<MenuItem id="semester-item-summer1" value="summer 1">
Summer 1
</MenuItem>
<MenuItem id="semester-item-summer2" value="summer 2">
Summer 2
</MenuItem>
<MenuItem id="semester-item-spring" value="spring">
Spring
</MenuItem>
</Select>
<FormHelperText>{touched.semester && errors.semester}</FormHelperText>
</FormControl>
<TextField
variant="outlined"
label="Title"
fullWidth
id="new-class-title"
name="title"
value={values.title}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.title && Boolean(errors.title)}
helperText={touched.title && errors.title}
/>
<TextField
variant="outlined"
label="Section/Period"
fullWidth
id="new-class-section"
name="section"
value={values.section}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.section && Boolean(errors.section)}
helperText={touched.section && errors.section}
/>
<TextField
label="Description"
fullWidth
multiline
id="new-class-description"
name="description"
value={values.description}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.description && Boolean(errors.description)}
helperText={touched.description && errors.description}
/>
<CreateNewSched schedules={schedules} setSchedules={setSchedules} />
</div>
</DemoContainer>
</LocalizationProvider>
</DialogContent>
<DialogActions sx={{ display: "flex", justifyContent: "space-between" }}>
<Button
id="class-create-cancel-button"
sx={{ width: "150px" }}
variant="inherit"
onClick={handleCancel}
>
Cancel
</Button>
<Button
id="class-create-save-button"
sx={{ width: "150px" }}
variant="contained"
color="primary"
onClick={handleSave}
disabled={hasChanges()}
>
Save
</Button>
</DialogActions>
</Dialog>
</>
);
};
export default NewClass;
|