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

86.86% Statements 86/99
78.26% Branches 36/46
76.47% Functions 13/17
87.09% Lines 81/93

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                                                                                      2x     78x 78x 44x 78x 44x   44x 44x 44x 44x   44x 44x 44x   44x                       44x 44x 44x 44x           44x 44x         44x   44x 4x     44x 3x                     3x         3x 3x 3x   3x 1x 1x     1x 1x 1x     2x 2x 2x 1x   2x 2x 1x       3x       44x         44x       44x 16x     44x       44x 44x   43x           1x               44x 44x   18x                 6x   5x   15x           44x 17x 16x 2x     2x 2x       44x 20x   6x 6x 6x   5x 5x 5x   5x 5x 5x   4x 4x           44x                                                                                                                     176x 176x 176x                          
/**
 * Modified by Allan Ninal — 2026-08-12: the shared half of the save payload moved to
 * buildAssignmentCorePayload, alongside the buildInstructionsRubricFields helper this
 * flow already used.
 */
 
import * as React from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
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 { useState } from "react";
import Step1 from "@/app/teacher-page/page/assignments/new-assignment/Step1";
import Step2 from "@/app/teacher-page/page/assignments/new-assignment/Step2";
import Step3 from "@/app/teacher-page/page/assignments/new-assignment/Step3";
import AssignmentViewAsStudent from "@/app/teacher-page/page/assignments/new-assignment/student-preview/StudentPreviewPage";
import Step4 from "@/app/teacher-page/page/assignments/new-assignment/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 { _teacherCreateStaffAssignment } from "@/store/slices/teacher/TeacherAssignments";
import { buildAssignmentCorePayload, buildInstructionsRubricFields } 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 { useUnsavedChangesWarning } from "@/utils/hooks/useUnsavedChangesWarning";
import UnsavedChangesDialog from "@/utils/components/UnsavedChangesDialog";
import { parseTeacherMadeAssignmentError } from "@/utils/features/teacherMadeAssignmentQuota";
import { _teacherFetchSpecificAssignment } from "@/store/slices/teacher/TeacherSpecificAssignment";
import BasicBreadcrumbs from "@/utils/components/breadcrumbs/basic-breadcrumbs/BasicBreadcrumbs";
import { _fetchSpecificClassByCode } from "@/store/slices/teacher/TeacherSpecificClass";
import { useEffect } from "react";
 
const steps = ["Title and Description", "Questions", "Test Settings", "Preview"];
 
export default function STAARReleasedTest() {
    const { specificClassData } = useSelector((state) => state.TeacherSpecificClass);
    const { assignmentData } = useSelector((state) => state.TeacherCreateAssignment);
    const { classCode, assignmentType, assignmentTitle } = useParams();
    const { classData } = useSelector((state) => state.TeacherClasses);
    const theme = useTheme();
 
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const location = useLocation();
    const { ui, loading: quotaLoading, openUpgradeOnBlock, syncQuota } = useTeacherMadeAssignmentQuota();
 
    const endpoint = location.pathname.split("/").filter(Boolean).pop();
    const isCreateFlow = endpoint === "new";
    const isReuse = !!location.state?.isReuse;
 
    const breadcrumb = [
        {
            name: "Tests",
            isLink: true,
            path: "/teacher/tests",
        },
        {
            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);
 
    // EI-3115 / EI-TC-4562: warn before leaving this (staff-assignment based)
    // create wizard with unsaved work. step1Dirty is a real change signal even
    // when the reuse flow pre-fills Step 1; step2/step3 reflect user selections.
    // Suppressed during save so a successful submit navigates away cleanly.
    const [step1Dirty, setStep1Dirty] = useState(false);
    const hasUnsavedWork = Boolean(
        step1Dirty ||
        (isCreateFlow &&
            (assignmentData?.step2?.selectedQuestions?.length || assignmentData?.step3?.assignedClass?.length))
    );
    const navigationBlocker = useUnsavedChangesWarning(hasUnsavedWork && !isSaving);
 
    const handleSave = () => {
        setDialogSave(true);
    };
 
    const saveOperation = async () => {
        const assignment = {
            ...buildAssignmentCorePayload({ assignmentData, assignmentType, classData }),
            copy_of: assignmentData._id,
            // EI-3182: forward instructions/rubric from the imported global assignment.
            // These fields are stored at the top level of assignmentData by the
            // AssignmentSettings.useAssignment() bridge. Each field is included only
            // when present so assignments without them are unaffected — which is why
            // this flow does NOT use the in-class wizard's explicit-null clearing.
            ...buildInstructionsRubricFields(assignmentData),
        };
 
        Iif (!ui.showCreate) {
            openUpgradeOnBlock();
            return;
        }
 
        setIsSaving(true);
        try {
            const response = await dispatch(_teacherCreateStaffAssignment(assignment));
 
            if (_teacherCreateStaffAssignment.fulfilled.match(response)) {
                setDialogSave(false);
                enqueueSnackbar("Assignment successfully created", {
                    variant: "success",
                });
                dispatch(_resetAllFields());
                navigate(-1);
                return;
            }
 
            Eif (_teacherCreateStaffAssignment.rejected.match(response)) {
                const parsed = parseTeacherMadeAssignmentError(response.payload);
                if (parsed.quota) {
                    syncQuota(parsed.quota);
                }
                enqueueSnackbar(parsed.message, { variant: "error" });
                if (parsed.upgradeRequired) {
                    openUpgradeOnBlock();
                }
            }
        } 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 "TeacherTest":
                return "Teacher Test";
            default:
                return "Invalid";
        }
    };
 
    const stepperContent = () => {
        switch (activeStep) {
            case 0:
                return (
                    <Step1
                        handleCancel={handleCancel}
                        stepController={stepController}
                        isReuse={isReuse}
                        onDirtyChange={setStep1Dirty}
                    />
                );
            case 1:
                return <Step2 handleBack={handleBack} stepController={stepController} isReuse={isReuse} />;
            case 2:
                return <Step3 handleBack={handleBack} stepController={stepController} />;
            case 3:
                return <Step4 handleBack={handleBack} stepController={stepController} />;
            default:
                console.log("Invalid");
        }
    };
 
    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]);
 
    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;
        }
    };
 
    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 Create"
                    message="Do you want to create the assignment?"
                    showDialog={dialogSave}
                    clickNo={setDialogSave}
                    clickYes={saveOperation}
                    yesLoading={isSaving}
                    yesLabel="Create"
                    yesLoadingLabel="Creating…"
                />
                {!assignmentData?.viewAsStudent && (
                    <Box>
                        <div
                            style={{
                                backgroundColor: theme.palette.primary.main,
                                color: "white",
                                minHeight: "64px",
                                display: "flex",
                                alignItems: "center",
                                paddingLeft: "24px",
                                paddingRight: "24px",
                                position: "relative",
                            }}
                        >
                            <Box sx={{ width: "100%", display: "flex", justifyContent: "space-between" }}>
                                <Typography variant="h6">{getPageTitle()}</Typography>
                                <Button variant="contained" color="inherit" onClick={handleCancel}>
                                    Discard
                                </Button>
                            </Box>
                        </div>
                        <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>
    );
}