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

65.04% Statements 67/103
64.04% Branches 57/89
41.66% Functions 20/48
70.45% Lines 62/88

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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507                                                                        2x           70x 68x             57x   56x     2x 159x                             136x                     136x 136x 136x         136x 24x             24x 24x   24x                                     136x 47x 46x 47x 47x 47x     136x   11x 22x     11x   11x     136x 21x 21x 21x     136x 21x 21x 21x           136x 2x 2x     136x       136x       136x                   136x           136x                               136x 13x 2x           2x   11x 11x     11x 11x   13x   4x                 136x         136x                               1x                                             12x 12x                                   9x 9x                                                                         5x   5x                                                                                                                                                                                                                                                                                                                                                                  
import {
    Alert,
    Box,
    Button,
    Card,
    CardContent,
    Divider,
    IconButton,
    TextField,
    Tooltip,
    Typography,
} from "@mui/material";
import React, { useEffect, useState } from "react";
import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos";
import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos";
import AddIcon from "@mui/icons-material/Add";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { useDispatch } from "react-redux";
import { _updateStep1 } from "@/store/slices/teacher/TeacherCreateAssignment";
import { useSelector } from "react-redux";
import { useFormik } from "formik";
import * as yup from "yup";
import {
    buildRubricPayload,
    emptyCriterion,
    emptyLevel,
    isRubricValid,
    resolveBridgeFields,
    rubricValidationErrors,
    MAX_CRITERIA,
    MAX_LEVELS_PER_CRITERION,
} from "./assignmentRubricUtils";
 
// EI-1218 — reject whitespace-only AND special-characters-only Title/Description (mirrors the
// EI-1216 Class fix): `.required()` alone lets "   " (>=3 chars) and "!!!" through. `has-alphanumeric`
// requires at least one letter/number; `no-trailing-space` blocks a trailing space. Exported for unit tests.
export const step1ValidationSchema = yup.object({
    title: yup
        .string()
        .min(3, "Title must be at least 3 characters long")
        .max(50, "Title must be no more than 50 characters long")
        .required("Title is required")
        .test("has-alphanumeric", "Title must contain a letter or number", (value) => /[a-zA-Z0-9]/.test(value || ""))
        .test("no-trailing-space", "Title cannot end with a space", (value) => value?.trimEnd() === value),
    description: yup
        .string()
        .min(3, "Description must be at least 3 characters long")
        .max(100, "Description must be no more than 100 characters long")
        .required("Description is required")
        .test("has-alphanumeric", "Description must contain a letter or number", (value) =>
            /[a-zA-Z0-9]/.test(value || "")
        )
        .test("no-trailing-space", "Description cannot end with a space", (value) => value?.trimEnd() === value),
});
 
const Step1 = ({ handleCancel, stepController, isReuse = false, onDirtyChange }) => {
    const { assignmentData } = useSelector((state) => state.TeacherCreateAssignment);
 
    // ------------------------------------------------------------------
    // Formik — title + description (required, existing validation)
    // ------------------------------------------------------------------
    const {
        values,
        touched,
        errors,
        handleChange,
        handleBlur,
        setFieldTouched,
        validateForm,
        setValues,
        setFieldValue,
    } = useFormik({
        initialValues: {
            title: "",
            description: "",
        },
        validationSchema: step1ValidationSchema,
    });
 
    // ------------------------------------------------------------------
    // Local state — instructions + rubric criteria (optional, EI-3182)
    // ------------------------------------------------------------------
    const [instructions, setInstructions] = useState("");
    const [criteria, setCriteria] = useState([]);
    const [rubricTouched, setRubricTouched] = useState(false);
 
    // ------------------------------------------------------------------
    // Sync from Redux store on mount / store change
    // ------------------------------------------------------------------
    useEffect(() => {
        setValues({
            title: assignmentData.step1?.title ?? "",
            description: assignmentData.step1?.description ?? "",
        });
        // EI-3182: resolve instructions/rubric from step1 OR the assignmentData
        // root — the reuse/import flow carries them at root, so a step1-only read
        // dropped the rubric from the create POST (see resolveBridgeFields).
        const { instructions: bridgeInstructions, rubric: storedRubric } = resolveBridgeFields(assignmentData);
        setInstructions(bridgeInstructions);
        // Restore rubric criteria from stored payload shape.
        Iif (storedRubric && Array.isArray(storedRubric.criteria)) {
            setCriteria(
                storedRubric.criteria.map((c) => ({
                    name: c.name ?? "",
                    levels: Array.isArray(c.levels)
                        ? c.levels.map((l) => ({
                              label: l.label ?? "",
                              points: l.points !== undefined ? String(l.points) : "",
                              description: l.description ?? "",
                          }))
                        : [],
                }))
            );
        }
    }, [assignmentData, setValues]);
 
    // EI-3115 / EI-TC-4562: report typed-but-not-yet-committed edits up to the
    // wizard so the Back-button guard arms while the user is still on Step 1
    // (Title/Description live in local Formik state until "Next").
    useEffect(() => {
        if (!onDirtyChange) return;
        const storedTitle = assignmentData.step1?.title ?? "";
        const storedDescription = assignmentData.step1?.description ?? "";
        const dirty = values.title !== storedTitle || values.description !== storedDescription;
        onDirtyChange(dirty);
    }, [values.title, values.description, assignmentData, onDirtyChange]);
 
    const checkFormErrors = async () => {
        // Mark all fields as touched
        Object.keys(values).forEach((fieldName) => {
            setFieldTouched(fieldName, true);
        });
        // Validate the form to update the errors object
        const formErrors = await validateForm();
        // Check if there are any errors
        return Object.keys(formErrors).length > 0;
    };
 
    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);
    };
 
    // ------------------------------------------------------------------
    // Rubric mutation helpers (EI-3182)
    // ------------------------------------------------------------------
    const addCriterion = () => {
        Iif (criteria.length >= MAX_CRITERIA) return;
        setCriteria((prev) => [...prev, emptyCriterion()]);
    };
 
    const removeCriterion = (cIdx) => {
        setCriteria((prev) => prev.filter((_, i) => i !== cIdx));
    };
 
    const updateCriterionName = (cIdx, name) => {
        setCriteria((prev) => prev.map((c, i) => (i === cIdx ? { ...c, name } : c)));
    };
 
    const addLevel = (cIdx) => {
        setCriteria((prev) =>
            prev.map((c, i) => {
                if (i !== cIdx) return c;
                if (c.levels.length >= MAX_LEVELS_PER_CRITERION) return c;
                return { ...c, levels: [...c.levels, emptyLevel()] };
            })
        );
    };
 
    const removeLevel = (cIdx, lIdx) => {
        setCriteria((prev) =>
            prev.map((c, i) => (i === cIdx ? { ...c, levels: c.levels.filter((_, j) => j !== lIdx) } : c))
        );
    };
 
    const updateLevel = (cIdx, lIdx, field, value) => {
        setCriteria((prev) =>
            prev.map((c, i) =>
                i === cIdx
                    ? {
                          ...c,
                          levels: c.levels.map((l, j) => (j === lIdx ? { ...l, [field]: value } : l)),
                      }
                    : c
            )
        );
    };
 
    // ------------------------------------------------------------------
    // Validation + advance
    // ------------------------------------------------------------------
    const clickNextStep = async () => {
        if (isReuse) {
            stepController(0, {
                title: values.title,
                description: values.description,
                instructions: instructions.trim() || undefined,
                rubric: buildRubricPayload(criteria),
            });
            return;
        }
        const hasFormErrors = await checkFormErrors();
        setRubricTouched(true);
 
        // Rubric is optional but must be internally consistent when criteria exist
        const rubricErrs = rubricValidationErrors(criteria);
        const hasRubricErrors = rubricErrs.criteria && rubricErrs.criteria.some((ce) => Object.keys(ce).length > 0);
 
        if (hasFormErrors || hasRubricErrors) return;
 
        stepController(0, {
            title: values.title,
            description: values.description,
            instructions: instructions.trim() || undefined,
            rubric: buildRubricPayload(criteria),
        });
    };
 
    // Compute rubric inline errors (only shown after the user attempts Next)
    const rubricErrors = rubricTouched ? rubricValidationErrors(criteria) : {};
 
    // ------------------------------------------------------------------
    // Render
    // ------------------------------------------------------------------
    return (
        <Box
            sx={{
                mt: 5,
                display: "flex",
                flexDirection: "row",
                justifyContent: "space-between",
                gap: "2%",
            }}
        >
            <Button
                id="teacher-class-assignment-step1-back"
                sx={{ mt: 5, height: 40 }}
                variant="contained"
                color="primary"
                onClick={(e) => {
                    handleCancel();
                }}
            >
                <ArrowBackIosIcon />
            </Button>
            <Card sx={{ width: "100%", p: 5 }}>
                <CardContent>
                    {isReuse && (
                        <Alert severity="info" sx={{ mb: 2 }}>
                            This is a staff assignment. The title and description are read-only and cannot be edited.
                        </Alert>
                    )}
 
                    {/* ---- Title ---- */}
                    <TextField
                        fullWidth
                        required
                        id="teacher-class-assignment-step1-title"
                        margin="normal"
                        name="title"
                        label="Title"
                        value={values.title}
                        onChange={(e) => {
                            handleChange(e);
                            handleSanitizedChange(e);
                        }}
                        onBlur={handleBlur}
                        error={!isReuse && touched.title && Boolean(errors.title)}
                        helperText={!isReuse && touched.title && errors.title}
                        disabled={isReuse}
                    />
 
                    {/* ---- Description ---- */}
                    <TextField
                        fullWidth
                        required
                        id="teacher-class-assignment-step1-description"
                        margin="normal"
                        name="description"
                        label="Description"
                        value={values.description}
                        onChange={(e) => {
                            handleChange(e);
                            handleSanitizedChange(e);
                        }}
                        onBlur={handleBlur}
                        error={!isReuse && touched.description && Boolean(errors.description)}
                        helperText={!isReuse && touched.description && errors.description}
                        disabled={isReuse}
                    />
 
                    {/* ---- Instructions (optional, EI-3182) ---- */}
                    <TextField
                        id="teacher-assignment-instructions"
                        fullWidth
                        multiline
                        minRows={3}
                        margin="normal"
                        name="instructions"
                        label="Instructions for Students"
                        placeholder="Provide any additional guidance students should read before starting."
                        value={instructions}
                        inputProps={{ maxLength: 5000 }}
                        onChange={(e) => setInstructions(e.target.value)}
                        helperText={`${instructions.length}/5000 — optional`}
                    />
 
                    {/* ---- Grading Rubric (optional, structured builder, EI-3182) ---- */}
                    <Box sx={{ mt: 4 }}>
                        <Divider sx={{ mb: 2 }} />
                        <Typography variant="subtitle1" fontWeight={600} gutterBottom>
                            Grading Rubric
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                            Optional. Add criteria to guide grading. Each criterion requires at least one performance
                            level.
                        </Typography>
 
                        {/* ---- Criteria list ---- */}
                        {criteria.map((criterion, cIdx) => {
                            const cErr = rubricErrors.criteria?.[cIdx] ?? {};
 
                            return (
                                <Box
                                    key={cIdx}
                                    sx={{
                                        border: "1px solid",
                                        borderColor: cErr.name || cErr.levels ? "error.main" : "divider",
                                        borderRadius: 1,
                                        p: 2,
                                        mb: 2,
                                    }}
                                >
                                    {/* Criterion header row */}
                                    <Box
                                        sx={{
                                            display: "flex",
                                            alignItems: "flex-start",
                                            gap: 1,
                                            mb: 1,
                                        }}
                                    >
                                        <TextField
                                            id={`rubric-criterion-name-${cIdx}`}
                                            label="Criterion Name"
                                            size="small"
                                            required
                                            value={criterion.name}
                                            onChange={(e) => updateCriterionName(cIdx, e.target.value)}
                                            error={Boolean(cErr.name)}
                                            helperText={cErr.name}
                                            inputProps={{ maxLength: 200 }}
                                            sx={{ flex: 1 }}
                                        />
                                        <Tooltip title="Remove criterion">
                                            <IconButton
                                                id={`rubric-remove-criterion-${cIdx}`}
                                                aria-label={`Remove criterion ${cIdx + 1}`}
                                                color="error"
                                                onClick={() => removeCriterion(cIdx)}
                                                size="small"
                                                sx={{ mt: 0.5 }}
                                            >
                                                <DeleteOutlineIcon fontSize="small" />
                                            </IconButton>
                                        </Tooltip>
                                    </Box>
 
                                    {/* Levels error banner */}
                                    {cErr.levels && (
                                        <Typography variant="caption" color="error" sx={{ mb: 1, display: "block" }}>
                                            {cErr.levels}
                                        </Typography>
                                    )}
 
                                    {/* Performance levels */}
                                    {criterion.levels.map((level, lIdx) => {
                                        const lErr = cErr.levelErrors?.[lIdx] ?? {};
                                        return (
                                            <Box
                                                key={lIdx}
                                                sx={{
                                                    display: "flex",
                                                    gap: 1,
                                                    alignItems: "flex-start",
                                                    mb: 1,
                                                    pl: 2,
                                                    borderLeft: "2px solid",
                                                    borderColor: "primary.light",
                                                }}
                                            >
                                                <TextField
                                                    id={`rubric-level-label-${cIdx}-${lIdx}`}
                                                    label="Label"
                                                    size="small"
                                                    required
                                                    value={level.label}
                                                    onChange={(e) => updateLevel(cIdx, lIdx, "label", e.target.value)}
                                                    error={Boolean(lErr.label)}
                                                    helperText={lErr.label}
                                                    inputProps={{ maxLength: 200 }}
                                                    sx={{ flex: 2 }}
                                                />
                                                <TextField
                                                    id={`rubric-level-points-${cIdx}-${lIdx}`}
                                                    label="Points"
                                                    size="small"
                                                    required
                                                    type="number"
                                                    inputProps={{ min: 0 }}
                                                    value={level.points}
                                                    onChange={(e) => updateLevel(cIdx, lIdx, "points", e.target.value)}
                                                    error={Boolean(lErr.points)}
                                                    helperText={lErr.points}
                                                    sx={{ flex: 1 }}
                                                />
                                                <TextField
                                                    id={`rubric-level-desc-${cIdx}-${lIdx}`}
                                                    label="Description (optional)"
                                                    size="small"
                                                    value={level.description}
                                                    onChange={(e) =>
                                                        updateLevel(cIdx, lIdx, "description", e.target.value)
                                                    }
                                                    inputProps={{ maxLength: 2000 }}
                                                    sx={{ flex: 3 }}
                                                />
                                                <Tooltip title="Remove level">
                                                    <IconButton
                                                        id={`rubric-remove-level-${cIdx}-${lIdx}`}
                                                        aria-label={`Remove level ${lIdx + 1} from criterion ${cIdx + 1}`}
                                                        color="error"
                                                        onClick={() => removeLevel(cIdx, lIdx)}
                                                        size="small"
                                                        sx={{ mt: 0.5 }}
                                                    >
                                                        <DeleteOutlineIcon fontSize="small" />
                                                    </IconButton>
                                                </Tooltip>
                                            </Box>
                                        );
                                    })}
 
                                    {/* Add level button — disabled at cap */}
                                    <Tooltip
                                        title={
                                            criterion.levels.length >= MAX_LEVELS_PER_CRITERION
                                                ? `Maximum ${MAX_LEVELS_PER_CRITERION} levels per criterion`
                                                : ""
                                        }
                                    >
                                        <span>
                                            <Button
                                                id={`rubric-add-level-${cIdx}`}
                                                size="small"
                                                startIcon={<AddIcon />}
                                                onClick={() => addLevel(cIdx)}
                                                disabled={criterion.levels.length >= MAX_LEVELS_PER_CRITERION}
                                                sx={{ mt: 0.5 }}
                                            >
                                                Add Level
                                            </Button>
                                        </span>
                                    </Tooltip>
                                </Box>
                            );
                        })}
 
                        {/* Add criterion button — disabled at cap */}
                        <Tooltip title={criteria.length >= MAX_CRITERIA ? `Maximum ${MAX_CRITERIA} criteria` : ""}>
                            <span>
                                <Button
                                    id="rubric-add-criterion"
                                    variant="outlined"
                                    startIcon={<AddIcon />}
                                    onClick={addCriterion}
                                    disabled={criteria.length >= MAX_CRITERIA}
                                    size="small"
                                >
                                    Add Criterion
                                </Button>
                            </span>
                        </Tooltip>
                    </Box>
                </CardContent>
            </Card>
            <Button
                id="teacher-class-assignment-step1-next"
                sx={{ mt: 5, height: 40 }}
                variant="contained"
                onClick={clickNextStep}
            >
                <ArrowForwardIosIcon />
            </Button>
        </Box>
    );
};
 
export default Step1;