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 | 1x 1x 1x 1x 43x 43x 43x 43x 69x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 21x 1x 1x 43x 21x 5x 43x 43x 43x 43x 43x 172x 224x 128x 320x 96x 5x 1x 11x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x | import * as React from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { useSnackbar } from "notistack";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack";
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import MenuItem from "@mui/material/MenuItem";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import TextField from "@mui/material/TextField";
import LinearProgress from "@mui/material/LinearProgress";
import Alert from "@mui/material/Alert";
import AlertTitle from "@mui/material/AlertTitle";
import {
_teacherUploadQuestionFile,
_teacherPasteQuestion,
_teacherFetchImportStatus,
_teacherFetchImportQuestions,
_teacherCommitImport,
resetImport,
} from "@/store/slices/teacher/TeacherQuestionImport";
import { subjects, gradeLevels, difficultyOptions } from "@/utils/components/question-bank/utils/constants";
import ImportReview from "./ImportReview";
import ImportResults from "./ImportResults";
/**
* Bulk question import: choose a type, upload a file, review what came out, save.
*
* Nothing reaches the question bank until the final step. The service and the API both
* enforce that too — this screen makes it visible.
*
* Developer: Allan Ninal
*/
// Capitalisation is load-bearing: these strings are compared verbatim by the API, whose
// enum uses "Drag-and-Drop" and "Drop-down-Menu". The CSV design doc writes them
// lowercase in one place; the API is what validates.
// Not a question type — a statement that the FILE decides. A STAAR released-item PDF
// holds six different item types in one document, so any single choice is wrong for most
// of it. Accepted for PDFs only, which is where per-item types exist.
export const AUTO_DETECT = "Auto-detect";
const QUESTION_TYPES = [
{ value: AUTO_DETECT, label: "Auto-detect from the file (PDF)" },
{ value: "Multiple-choice", label: "Multiple choice" },
{ value: "Checkbox", label: "Checkbox (more than one answer)" },
{ value: "Free-response", label: "Free response" },
{ value: "Graph", label: "Graph" },
{ value: "Drag-and-Drop", label: "Drag and drop" },
{ value: "Drop-down-Menu", label: "Drop-down menu" },
];
const STEPS = ["Choose a type", "Upload your file", "Review", "Done"];
// States the job passes through while work is still happening.
const IN_FLIGHT = ["queued", "scanning", "parsing", "extracting"];
export default function ImportWizard({ role = "teacher" }) {
const dispatch = useDispatch();
const navigate = useNavigate();
const { enqueueSnackbar } = useSnackbar();
// `committing` is intentionally not read here — ImportReview subscribes to it
// directly for its own button state.
const { jobId, state, uploading, error, rowErrors, questionsFound, committed, duplicates } = useSelector(
(s) => s.TeacherQuestionImport
);
const [questionType, setQuestionType] = React.useState("Multiple-choice");
const [file, setFile] = React.useState(null);
// "file" or "paste". A teacher adding ONE question should not have to build a
// document around it, which is the whole point of the paste path.
const [mode, setMode] = React.useState("file");
// The API requires questionSubject on every question. A CSV carries it per row, but
// a Word document, PDF or pasted question has no such field — so without collecting
// it here, Save fails for every one of those formats.
const [subject, setSubject] = React.useState("Math");
const [topic, setTopic] = React.useState("General");
// A document states neither. A STAAR released-item PDF names the TEKS, the points and
// the answer for every item, but a grade appears nowhere in it and difficulty is a
// judgement. Without them every question arrives unsaveable, and the reviewer has to
// set them one at a time on the review screen.
const [gradeLevel, setGradeLevel] = React.useState("");
const [difficulty, setDifficulty] = React.useState("");
const [pasted, setPasted] = React.useState("");
// Advance when work has actually STARTED — a job exists, or one is being created.
// This previously advanced as soon as a file was CHOSEN, which unmounted this panel
// and took the "Start import" button with it, so the import could never be
// triggered from the UI at all. Every verification of this feature had gone through
// the API directly, which is why it survived.
// A job that FAILED keeps its jobId, so without the `failed` branch `jobId ||
// uploading` held the wizard on step 1 — "Reading your questions…" for ever, with no
// error and no way forward. Someone who uploaded a file that could not be read simply
// waited. Back to step 0 so the file can be replaced, with the reason shown above.
const failed = state === "failed";
const step = committed ? 3 : failed ? 0 : state === "awaiting_review" ? 2 : jobId || uploading ? 1 : 0;
// Poll while the job is in flight. Cleared on unmount so a teacher who navigates
// away does not leave a timer running against a job they abandoned.
React.useEffect(() => {
if (!jobId || !IN_FLIGHT.includes(state)) return undefined;
const timer = setInterval(() => dispatch(_teacherFetchImportStatus(jobId)), 2000);
return () => clearInterval(timer);
}, [jobId, state, dispatch]);
// Once parsing finishes, pull the proposed questions for review.
React.useEffect(() => {
if (jobId && state === "awaiting_review") {
dispatch(_teacherFetchImportQuestions(jobId));
}
}, [jobId, state, dispatch]);
React.useEffect(() => () => dispatch(resetImport()), [dispatch]);
const handleUpload = async () => {
if (!file) return;
const result = await dispatch(
_teacherUploadQuestionFile({
file,
questionType,
gradeLevel: gradeLevel || null,
difficulty: difficulty || null,
})
);
if (result.meta.requestStatus === "rejected") {
enqueueSnackbar(messageFrom(result.payload), { variant: "error" });
}
};
const handlePaste = async () => {
if (!pasted.trim()) return;
const result = await dispatch(_teacherPasteQuestion({ text: pasted, questionType }));
if (result.meta.requestStatus === "rejected") {
enqueueSnackbar(messageFrom(result.payload), { variant: "error" });
}
};
const handleSave = async (questions) => {
const result = await dispatch(
_teacherCommitImport({ jobId, questions, questionSubject: subject, questionTopic: topic })
);
if (result.meta.requestStatus === "rejected") {
enqueueSnackbar(messageFrom(result.payload), { variant: "error" });
return;
}
const created = result.payload?.created ?? questions.length;
const skipped = result.payload?.skipped_duplicates ?? 0;
enqueueSnackbar(
skipped
? `Added ${created} questions, skipped ${skipped} already in your bank`
: `Added ${created} questions`,
{ variant: "success" }
);
};
return (
<Box sx={{ p: 3 }} data-testid="import-wizard">
<Typography variant="h5" mb={1}>
Import questions
</Typography>
<Typography variant="body2" color="text.secondary" mb={3}>
Upload a Word document, PDF, CSV or spreadsheet — or paste a single question. You review everything
before anything is added.
</Typography>
<Stepper activeStep={step} sx={{ mb: 3 }}>
{STEPS.map((label) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
{(error || failed) && (
<Alert severity="error" sx={{ mb: 2 }} data-testid="import-error">
<AlertTitle>That did not work</AlertTitle>
{failed
? rowErrors.length > 0
? rowErrors.slice(0, 5).map((rowError, index) => (
<Typography key={index} variant="body2">
{rowError.message}
</Typography>
))
: "That file could not be read. Try another one."
: messageFrom(error)}
</Alert>
)}
{step === 0 && (
<Paper variant="outlined" sx={{ p: 3 }}>
<Stack spacing={3} maxWidth={520}>
<TextField
select
label="What kind of questions are in the file?"
value={questionType}
onChange={(e) => setQuestionType(e.target.value)}
helperText={
questionType === AUTO_DETECT
? "For a PDF where every item states its own type, such as a STAAR released-item export."
: "One file holds one kind of question."
}
>
{QUESTION_TYPES.map((type) => (
<MenuItem key={type.value} value={type.value}>
{type.label}
</MenuItem>
))}
</TextField>
<TextField
select
label="Subject"
value={subject}
onChange={(e) => setSubject(e.target.value)}
data-testid="question-subject"
helperText="Required. Applied to every question in this import."
>
{subjects.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
{/* A document cannot state either of these. Asked for once, here,
rather than question by question on the review screen. */}
<Stack direction="row" spacing={2}>
<TextField
select
fullWidth
label="Grade"
value={gradeLevel}
onChange={(e) => setGradeLevel(e.target.value)}
data-testid="batch-grade"
helperText="A file never states this."
>
{gradeLevels.map((grade) => (
<MenuItem key={grade.value} value={grade.value}>
{grade.label}
</MenuItem>
))}
</TextField>
<TextField
select
fullWidth
label="Difficulty"
value={difficulty}
onChange={(e) => setDifficulty(e.target.value)}
data-testid="batch-difficulty"
helperText="Applied where the file has none."
>
{difficultyOptions.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
</Stack>
<TextField
label="Topic"
value={topic}
onChange={(e) => setTopic(e.target.value)}
data-testid="question-topic"
helperText="Required. The API rejects an empty topic."
/>
{questionType === "Graph" && (
<Alert severity="info">
A graph answer cannot be written in a document. These questions will import without an
answer, and you draw each one afterwards.
</Alert>
)}
<ToggleButtonGroup
exclusive
size="small"
value={mode}
onChange={(e, next) => next && setMode(next)}
data-testid="import-mode"
>
<ToggleButton value="file" data-testid="mode-file">
Upload a file
</ToggleButton>
<ToggleButton value="paste" data-testid="mode-paste">
Paste one question
</ToggleButton>
</ToggleButtonGroup>
{mode === "file" ? (
<React.Fragment>
<Button variant="contained" component="label" data-testid="choose-file">
{file ? file.name : "Choose a file"}
<input
hidden
type="file"
accept=".csv,.tsv,.txt,.xlsx,.xlsm,.docx,.pdf"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
</Button>
<Button
variant="contained"
color="primary"
disabled={!file || uploading}
onClick={handleUpload}
data-testid="start-import"
>
{uploading ? "Uploading…" : "Start import"}
</Button>
</React.Fragment>
) : (
<React.Fragment>
<TextField
multiline
minRows={7}
label="Paste your question"
value={pasted}
onChange={(e) => setPasted(e.target.value)}
data-testid="paste-box"
placeholder={
"Question 1: [Points: 1]\nWhat is the capital of France?\nA. Paris\nB. London\nAnswer: B"
}
helperText="One question. List the options as A. B. C. and give the answer by its letter. Include [Points: 1] — the question bank requires it."
/>
<Button
variant="contained"
color="primary"
disabled={!pasted.trim() || uploading}
onClick={handlePaste}
data-testid="start-paste"
>
{uploading ? "Adding…" : "Add this question"}
</Button>
</React.Fragment>
)}
</Stack>
</Paper>
)}
{step === 1 && (
<Paper variant="outlined" sx={{ p: 3 }} data-testid="import-progress">
<Typography variant="body1" mb={2}>
{state === "scanning" ? "Checking the file is safe…" : "Reading your questions…"}
</Typography>
<LinearProgress />
<Typography variant="caption" color="text.secondary" mt={2} display="block">
You can leave this page; the import keeps going.
</Typography>
</Paper>
)}
{step === 2 && !subject.trim() && (
<Alert severity="warning" sx={{ mb: 2 }} data-testid="subject-required">
Go back and set a Subject — the question bank will not accept questions without one.
</Alert>
)}
{step === 2 && duplicates > 0 && (
<Alert severity="info" sx={{ mb: 2 }} data-testid="duplicate-summary">
{duplicates === 1
? "1 question is already in your bank and will be skipped."
: `${duplicates} questions are already in your bank and will be skipped.`}
</Alert>
)}
{/* null, not 0: the API says null when the lookup failed. Saying nothing
here would let a failed check read as "no duplicates". */}
{step === 2 && duplicates === null && (
<Alert severity="warning" sx={{ mb: 2 }} data-testid="duplicate-unknown">
We could not check for duplicates just now, so some of these may already be in your bank.
</Alert>
)}
{step === 2 && <ImportReview onSave={handleSave} onCancel={() => dispatch(resetImport())} />}
{step === 3 && (
<ImportResults
committed={committed}
rowErrors={rowErrors}
questionsFound={questionsFound}
onDone={() => {
dispatch(resetImport());
navigate(`/${role}/question-bank`);
}}
/>
)}
</Box>
);
}
/**
* Pull a readable message out of an API error body.
*
* The API returns `detail` as a string, as an object with `message` and `problems`, or
* as pydantic's list of field errors. Rendering an object into JSX throws, so each shape
* is flattened here.
*/
export function messageFrom(payload) {
Iif (!payload) return "Something went wrong.";
const detail = payload.detail ?? payload;
Iif (typeof detail === "string") return detail;
Iif (Array.isArray(detail)) {
return detail.map((d) => d.msg ?? JSON.stringify(d)).join("; ");
}
Eif (typeof detail === "object") {
Eif (detail.message) {
// The API names the offending field per question in `problems`. Rendering
// only `message` left the screen saying "1 of 1 questions failed
// validation" with no clue which field — it took three round-trips through
// the API to find out that an empty Topic was the cause.
const problems = Array.isArray(detail.problems) ? detail.problems : [];
const reasons = problems
.map((p) => (p.question ? `Question ${p.question}: ${p.message}` : p.message))
.filter(Boolean);
return reasons.length ? `${detail.message} — ${reasons.join("; ")}` : detail.message;
}
return JSON.stringify(detail);
}
return String(detail);
}
|