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

87.2% Statements 109/125
75.86% Branches 66/87
85.71% Functions 18/21
87.82% Lines 101/115

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                                                                                                          1x         1x               147x 147x 147x 84x 147x   84x 84x 84x   84x             84x   84x 84x   84x                                 84x 84x 84x 84x       84x 84x       84x                     84x               84x   84x 9x     84x 7x                             7x 1x 1x     6x 6x 6x 3x 3x   3x 1x 1x     1x 1x 1x     2x 2x 2x 1x   2x 2x 1x     3x 3x   3x 3x   3x 2x 2x     2x 2x             6x       84x         84x       84x 35x     84x 2x     84x 84x   82x   1x   1x                   84x 84x   27x                 15x       11x   31x           84x 44x   14x 14x 14x   11x 11x 11x   10x 10x 10x   9x 9x           84x 25x     84x 25x 19x 1x     1x 1x       84x                                                                                                   336x 336x 336x                          
/**
 * Modified by Allan Ninal — 2026-08-12: the shared half of the save payload moved to
 * utils/helpers/assignmentSavePayload.js (buildAssignmentCorePayload) so it is unit
 * tested once for both NewAssignment wizards. The instructions/rubric handling stays
 * here — it differs deliberately from the reuse flow.
 */
 
import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import BreadcrumbsComponent from "@/utils/components/breadcrumbs/dynamic-breadcrumbs/Breadcrumbs";
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import { useMemo, useState } from "react";
import Step1 from "./Step1";
import Step2 from "./Step2";
import Step3 from "./Step3";
import Step4 from "./Step4";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { Button } from "@mui/material";
import {
    _updateStep1,
    _updateStep2,
    _updateStep3,
    _resetAllFields,
} from "@/store/slices/teacher/TeacherCreateAssignment";
import { _teacherCreateNewAssignment, _teacherUpdateAssignment } from "@/store/slices/teacher/TeacherAssignments";
// Used in saveOperation but never imported: saving threw
// "buildAssignmentCorePayload is not defined" before dispatching anything, so
// Create/Update on this wizard did nothing at all. The sibling tests wizard has
// always imported it. Modified by Allan Ninal.
import { buildAssignmentCorePayload } from "@/utils/helpers/assignmentSavePayload";
import { useDispatch } from "react-redux";
import { enqueueSnackbar } from "notistack";
import { useSelector } from "react-redux";
import useTeacherMadeAssignmentQuota from "@/utils/hooks/useTeacherMadeAssignmentQuota";
import {
    countClassTeacherMadeAssignments,
    parseTeacherMadeAssignmentError,
} from "@/utils/features/teacherMadeAssignmentQuota";
import AssignmentViewAsStudent from "./student-preview/StudentPreviewPage";
import { _teacherFetchSpecificAssignment } from "@/store/slices/teacher/TeacherSpecificAssignment";
import BasicBreadcrumbs from "@/utils/components/breadcrumbs/basic-breadcrumbs/BasicBreadcrumbs";
import { _fetchSpecificClassByCode } from "@/store/slices/teacher/TeacherSpecificClass";
import { useUnsavedChangesWarning } from "@/utils/hooks/useUnsavedChangesWarning";
import UnsavedChangesDialog from "@/utils/components/UnsavedChangesDialog";
import { useEffect } from "react";
import PageError from "@/utils/components/page-error/PageError";
 
const steps = ["Title and Description", "Questions", "Test Settings", "Preview"];
 
// EI-1218 — surface backend validation errors to the user (the create/update flow previously
// only handled the success branch, so a rejected save showed no toast). Pulls the first FastAPI
// 422 detail message, or a 400 string detail, with a sensible fallback.
const assignmentErrorMessage = (response) => {
    const detail = response?.payload?.detail;
    if (Array.isArray(detail)) return detail[0]?.msg || "Please check the assignment details and try again.";
    if (typeof detail === "string") return detail;
    return "Could not save the assignment. Please check the details and try again.";
};
 
export default function STAARReleasedTest() {
    const { specificClassData } = useSelector((state) => state.TeacherSpecificClass);
    const { assignmentData } = useSelector((state) => state.TeacherCreateAssignment);
    const { assignmentData: classAssignments } = useSelector((state) => state.TeacherAssignments);
    const { classCode, assignmentType, assignmentTitle } = useParams();
    const { classData } = useSelector((state) => state.TeacherClasses);
 
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const location = useLocation();
 
    const classAssignmentCount = useMemo(() => countClassTeacherMadeAssignments(classAssignments), [classAssignments]);
 
    const {
        ui,
        loading: quotaLoading,
        openUpgradeOnBlock,
        syncQuota,
    } = useTeacherMadeAssignmentQuota(classAssignmentCount);
 
    const endpoint = location.pathname.split("/").filter(Boolean).pop();
    const isCreateFlow = endpoint === "new";
 
    const breadcrumb = [
        {
            name: "Classes",
            isLink: true,
            path: "/teacher/classes",
        },
        {
            name: specificClassData?.title,
            isLink: true,
            path: `/teacher/classes/${classCode}`,
        },
        {
            name: endpoint == "new" ? "New Assignment" : "Update Assignment",
            isLink: false,
        },
    ];
 
    const [activeStep, setActiveStep] = useState(0);
    const [showYesNoOption, setShowYesNoOption] = useState(false);
    const [dialogSave, setDialogSave] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    // Step 1 keeps its Title/Description in local Formik state and only commits
    // them to Redux on "Next"; this flag lets Step 1 report typed-but-unsaved
    // edits up so the Back-button guard arms while the user is still on Step 1.
    const [step1Dirty, setStep1Dirty] = useState(false);
    const isUpdateFlow = endpoint === "update";
    // Staff-created assignments stay editable, but Step 1 (title/description) and
    // Step 2 (questions) are locked to teachers — only Step 3 (test settings) can
    // change. Reuses the same lock UI Step1/Step2 already render for the reuse flow.
    const isStaffAssignmentLocked = isUpdateFlow && Boolean(assignmentData?.isStaffAssignment);
 
    // EI-3115 / EI-TC-4562: warn before leaving the assignment wizard (incl. the
    // browser Back button) when the user has entered data but hasn't saved. The
    // guard is suppressed during save (isSaving) so a successful submit navigates
    // away without prompting.
    //
    // In the UPDATE flow the store is pre-loaded with the existing assignment, so
    // the Redux snapshot would falsely arm the guard on a clean open. Count it
    // only in the create flow; edit-assignment still gets a real change signal
    // via step1Dirty (Step 1 reports values that differ from the stored ones).
    const hasUnsavedWork = Boolean(
        step1Dirty ||
        (!isUpdateFlow &&
            (assignmentData?.step1?.title?.trim() ||
                assignmentData?.step1?.description?.trim() ||
                assignmentData?.step2?.selectedQuestions?.length ||
                assignmentData?.step3?.assignedClass?.length))
    );
    const navigationBlocker = useUnsavedChangesWarning(hasUnsavedWork && !isSaving);
 
    const handleSave = () => {
        setDialogSave(true);
    };
 
    const saveOperation = async () => {
        const assignment = {
            _id: assignmentData._id,
            ...buildAssignmentCorePayload({ assignmentData, assignmentType, classData }),
            // Always send instructions and rubric explicitly so clearing them
            // (empty string / no criteria) persists to the backend.  The backend
            // uses $set with exclude_unset=False, so sending null clears the field.
            instructions: (assignmentData.instructions || "").trim() || null,
            rubric:
                assignmentData.rubric &&
                Array.isArray(assignmentData.rubric.criteria) &&
                assignmentData.rubric.criteria.length > 0
                    ? assignmentData.rubric
                    : null,
        };
 
        if (isCreateFlow && !ui.showCreate) {
            openUpgradeOnBlock();
            return;
        }
 
        setIsSaving(true);
        try {
            if (isCreateFlow) {
                delete assignment["_id"];
                const response = await dispatch(_teacherCreateNewAssignment(assignment));
 
                if (_teacherCreateNewAssignment.fulfilled.match(response)) {
                    setDialogSave(false);
                    enqueueSnackbar("Assignment successfully created", {
                        variant: "success",
                    });
                    dispatch(_resetAllFields());
                    navigate(-1);
                    return;
                }
 
                Eif (_teacherCreateNewAssignment.rejected.match(response)) {
                    const parsed = parseTeacherMadeAssignmentError(response.payload);
                    if (parsed.quota) {
                        syncQuota(parsed.quota);
                    }
                    enqueueSnackbar(parsed.message || assignmentErrorMessage(response), { variant: "error" });
                    if (parsed.upgradeRequired) {
                        openUpgradeOnBlock();
                    }
                }
            E} else if (isUpdateFlow) {
                const response = await dispatch(_teacherUpdateAssignment(assignment));
 
                if (_teacherUpdateAssignment.fulfilled.match(response)) {
                    const fetchResponse = await dispatch(_teacherFetchSpecificAssignment(assignmentData._id));
 
                    if (_teacherFetchSpecificAssignment.fulfilled.match(fetchResponse)) {
                        setDialogSave(false);
                        enqueueSnackbar("Assignment successfully updated", {
                            variant: "success",
                        });
                        dispatch(_resetAllFields());
                        navigate(-1);
                    }
                E} else if (_teacherUpdateAssignment.rejected.match(response)) {
                    enqueueSnackbar(assignmentErrorMessage(response), { variant: "error" });
                }
            }
        } finally {
            setIsSaving(false);
        }
    };
 
    const handleCancelOperation = () => {
        dispatch(_resetAllFields());
        navigate(-1);
    };
 
    const handleCancel = () => {
        setShowYesNoOption(true);
    };
 
    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };
 
    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };
 
    const getPageTitle = () => {
        switch (assignmentType) {
            case "STAAR":
                return "State of Texas Assessments of Academic Readiness (STAAR)";
            case "TSI":
                return "Texas Success Initiative (TSI)";
            case "SAT":
                return "Scholastic Aptitude Test (SAT)";
            case "ACT":
                return "American College Test (ACT)";
            case "TEACHER-TEST":
                return "Teacher Test";
            default:
                return "Invalid";
        }
    };
 
    const stepperContent = () => {
        switch (activeStep) {
            case 0:
                return (
                    <Step1
                        handleCancel={handleCancel}
                        stepController={stepController}
                        isReuse={isStaffAssignmentLocked}
                        onDirtyChange={setStep1Dirty}
                    />
                );
            case 1:
                return (
                    <Step2 handleBack={handleBack} stepController={stepController} isReuse={isStaffAssignmentLocked} />
                );
            case 2:
                return <Step3 handleBack={handleBack} stepController={stepController} />;
            case 3:
                return <Step4 handleBack={handleBack} stepController={stepController} />;
            default:
                console.log("Invalid");
        }
    };
 
    const stepController = (step, data) => {
        switch (step) {
            case 0:
                dispatch(_updateStep1(data));
                handleNext();
                break;
            case 1:
                dispatch(_updateStep2(data));
                handleNext();
                break;
            case 2:
                dispatch(_updateStep3(data));
                handleNext();
                break;
            case 3:
                handleSave();
                break;
            default:
                break;
        }
    };
 
    useEffect(() => {
        dispatch(_fetchSpecificClassByCode(classCode));
    }, []);
 
    useEffect(() => {
        if (!isCreateFlow || quotaLoading) return;
        if (!ui.showCreate) {
            enqueueSnackbar(ui.message || "You cannot create more assignments on your current plan.", {
                variant: "warning",
            });
            openUpgradeOnBlock();
            navigate(-1);
        }
    }, [isCreateFlow, quotaLoading, ui.showCreate]);
 
    return (
        <Box sx={{ width: "100%" }}>
            <UnsavedChangesDialog blocker={navigationBlocker} />
            <Box sx={{ top: 0, position: "sticky", bgcolor: "background.paper", zIndex: 2 }}>
                <YesNoOption
                    title="Discard changes"
                    message="Do you want to cancel the operation? Changes may not be saved."
                    showDialog={showYesNoOption}
                    clickNo={setShowYesNoOption}
                    clickYes={handleCancelOperation}
                />
                <YesNoOption
                    title={`Confirm ${isUpdateFlow ? "Update" : "Create"}`}
                    message={`Do you want to ${isUpdateFlow ? "update" : "create"} the assignment?`}
                    showDialog={dialogSave}
                    clickNo={setDialogSave}
                    clickYes={saveOperation}
                    yesLoading={isSaving}
                    yesLabel={isUpdateFlow ? "Update" : "Create"}
                    yesLoadingLabel={isUpdateFlow ? "Updating…" : "Creating…"}
                />
                {!assignmentData?.viewAsStudent && (
                    <Box>
                        <AppBar position="relative" color="primary">
                            <Toolbar>
                                <Box sx={{ width: "100%", display: "flex", justifyContent: "space-between" }}>
                                    <Typography variant="h6">{getPageTitle()}</Typography>
                                    <Button variant="contained" color="inherit" onClick={handleCancel}>
                                        Discard
                                    </Button>
                                </Box>
                            </Toolbar>
                        </AppBar>
                        <BasicBreadcrumbs links={breadcrumb} />
                    </Box>
                )}
            </Box>
            {assignmentData?.viewAsStudent ? (
                <AssignmentViewAsStudent />
            ) : (
                <Box
                    sx={{
                        padding: "2% 2% 0 2%",
                        display: "flex",
                        rowGap: "20px",
                        flexDirection: "column",
                    }}
                >
                    <Stepper activeStep={activeStep}>
                        {steps.map((label, index) => {
                            const stepProps = {};
                            const labelProps = {};
                            return (
                                <Step key={label} {...stepProps}>
                                    <StepLabel {...labelProps}>{label}</StepLabel>
                                </Step>
                            );
                        })}
                    </Stepper>
                    <Box sx={{ width: "100%" }}>{stepperContent()}</Box>
                </Box>
            )}
        </Box>
    );
}