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 | 3x 3x 3x 3x 3x 3x 22x 22x 22x 22x 316x 316x 6x 2x 2x 4x 310x 15x 15x 295x 22x 22x 11x 11x 11x 11x 11x 11x 28x 28x 28x 22x 17x 10x 12x 12x 12x 12x 19x 12x 11x 76x 521x 521x 513x 76x 76x 1x 74x 74x 74x 7x 66x 66x 1x 64x 64x 64x 64x 92x 64x 60x 60x 60x 3x 56x 56x 1x 54x 76x 76x 76x 76x 76x 50x 50x 49x 50x 48x 1x 47x 50x 34x 34x 16x 16x 16x 15x 57x 15x 14x 16x 14x 14x 14x 14x 14x 14x 54x 8x 8x 8x 7x 23x 7x 6x 8x 5x 11x 5x 5x 9x 1x 4x 14x 4x 4x 4x 3x 3x 3x 9x 9x 9x 8x 9x 8x 10x 8x 1x 7x 9x 6x 18x 6x 6x 7x 1x 5x 5x 15x 6x 10x 10x 10x 9x 10x 9x 13x 9x 9x 10x 8x 13x 28x 8x 1x 7x 10x 9x 2x 4x 5x 4x 5x 79x 79x 78x 2x 76x 76x 16x 8x 4x 3x 9x 10x | // Valid enum values mirrored from src/utils/components/question-bank/utils/constants.jsx
const VALID_ASSIGNMENT_TYPES = ["STAAR", "SAT", "ACT", "TSI"];
const VALID_DIFFICULTIES = ["Easy", "Average", "Advance"];
// Texas caps at grade 12. This list previously ended at "13", which disagreed
// with BOTH sources it is meant to match: constants.jsx `gradeLevels` stops at
// 12, and the API's validate_grade_level raises
// 400 "invalid grade level: should only be between 3 to 12". A bulk-import row
// with gradeLevel=13 therefore passed frontend validation and was then rejected
// by the server — the worst place to find out, since the user was told the row
// was fine.
const VALID_GRADE_LEVELS = ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
const VALID_SUBJECTS = ["English", "Math", "Science", "Social Studies"];
const VALID_CATEGORIES = ["1", "2", "3", "4", "5"];
const VALID_QUESTION_TYPES = [
"Multiple-choice",
"Checkbox",
"Free-response",
"Graph",
"Drag-and-drop",
"Drop-down-menu",
];
// ── CSV line parser ────────────────────────────────────────────────────────────
/**
* Parses a single CSV line, handling quoted fields that may contain commas or
* escaped double-quotes ("").
*/
function parseCSVLine(line) {
const fields = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (char === "," && !inQuotes) {
fields.push(current.trim());
current = "";
} else {
current += char;
}
}
fields.push(current.trim());
return fields;
}
/**
* Parses raw CSV text into an array of row objects keyed by normalised header
* names (lowercased, whitespace stripped). Lines starting with "#" and blank
* lines are skipped.
*
* @param {string} csvText
* @returns {{ rows: object[], headers: string[] | null, errors: {line: number, message: string}[] }}
*/
export function parseCSV(csvText) {
const lines = csvText.split(/\r?\n/);
const rows = [];
const errors = [];
let headers = null;
let lineNumber = 0;
for (const rawLine of lines) {
lineNumber++;
const line = rawLine.trim();
if (!line || line.startsWith("#")) continue;
if (!headers) {
headers = parseCSVLine(line).map((h) => h.toLowerCase().replace(/\s+/g, ""));
continue;
}
const values = parseCSVLine(line);
Iif (values.length === 1 && values[0] === "") continue;
const row = { _line: lineNumber };
headers.forEach((header, i) => {
row[header] = values[i] !== undefined ? values[i] : "";
});
rows.push(row);
}
return { rows, headers, errors };
}
// ── Common field validation ────────────────────────────────────────────────────
function extractCommonFields(row) {
const required = (key, label) => {
const val = row[key]?.trim();
if (!val) throw new Error(`Missing required field: ${label}`);
return val;
};
const assignmentType = required("assignmenttype", "assignmentType");
if (!VALID_ASSIGNMENT_TYPES.includes(assignmentType)) {
throw new Error(
`Invalid assignmentType "${assignmentType}". Must be one of: ${VALID_ASSIGNMENT_TYPES.join(", ")}`
);
}
const gradeLevelRaw = required("gradelevel", "gradeLevel");
const gradeLevel = parseInt(gradeLevelRaw, 10);
if (isNaN(gradeLevel) || !VALID_GRADE_LEVELS.includes(String(gradeLevel))) {
throw new Error(`Invalid gradeLevel "${gradeLevelRaw}". Must be a number between 3 and 12`);
}
const questionSubject = required("questionsubject", "questionSubject");
if (!VALID_SUBJECTS.includes(questionSubject)) {
throw new Error(`Invalid questionSubject "${questionSubject}". Must be one of: ${VALID_SUBJECTS.join(", ")}`);
}
const questionTopic = required("questiontopic", "questionTopic");
const question = required("question", "question");
const keywordsRaw = required("keywords", "keywords");
const keywords = keywordsRaw
.split(";")
.map((k) => k.trim())
.filter(Boolean);
if (keywords.length === 0) throw new Error("At least one keyword is required (semicolon-separated)");
const pointsRaw = required("questionpoints", "questionPoints");
const points = parseInt(pointsRaw, 10);
if (isNaN(points) || points < 1)
throw new Error(`Invalid questionPoints "${pointsRaw}". Must be a positive integer`);
const difficulty = required("difficulty", "difficulty");
if (!VALID_DIFFICULTIES.includes(difficulty)) {
throw new Error(`Invalid difficulty "${difficulty}". Must be one of: ${VALID_DIFFICULTIES.join(", ")}`);
}
const studentExpectation = row["studentexpectation"]?.trim() || "";
const answerDetails = row["answerdetails"]?.trim() || "";
const questionDetails = row["questiondetails"]?.trim() || "";
let teksCode = null;
let category = null;
if (assignmentType === "STAAR") {
teksCode = row["tekscode"]?.trim() || "";
if (!teksCode) throw new Error("teksCode is required for STAAR assignment type");
category = row["category"]?.trim() || "";
if (!category) throw new Error("category is required for STAAR assignment type");
if (!VALID_CATEGORIES.includes(category)) {
throw new Error(`Invalid category "${category}". Must be one of: ${VALID_CATEGORIES.join(", ")}`);
}
if (!studentExpectation) throw new Error("studentExpectation is required for STAAR assignment type");
}
return {
assignmentType,
gradeLevel,
questionSubject,
questionTopic,
studentExpectation,
keywords,
questionImages: [],
questionGraphs: [],
question,
points,
difficulty,
questionDetails,
answerDetails,
teksCode,
category,
};
}
function applyRole(payload, role) {
if (role === "staff") payload.solutions = "test";
return payload;
}
// ── Type-specific builders ─────────────────────────────────────────────────────
function buildMultipleChoicePayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
const choicesRaw = row["choices"]?.trim();
if (!choicesRaw) throw new Error("Missing required field: choices (pipe-separated)");
const choiceTexts = choicesRaw
.split("|")
.map((c) => c.trim())
.filter(Boolean);
if (choiceTexts.length < 2) throw new Error("At least 2 choices are required (pipe-separated)");
const correctAnswersRaw = row["correctanswers"]?.trim();
Iif (!correctAnswersRaw) throw new Error("Missing required field: correctAnswers");
const correctAnswers = correctAnswersRaw
.split("|")
.map((a) => a.trim())
.filter(Boolean);
Iif (correctAnswers.length === 0) throw new Error("At least one correct answer is required");
for (const ans of correctAnswers) {
Iif (!choiceTexts.includes(ans)) {
throw new Error(`correctAnswer "${ans}" does not match any value in choices`);
}
}
return applyRole(
{
...commonFields,
questionType: "Multiple-choice",
choices: choiceTexts.map((text, i) => ({ id: Date.now() + i, text })),
correctAnswer: { answers: correctAnswers, answerDetails },
},
role
);
}
function buildCheckboxPayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
const choicesRaw = row["choices"]?.trim();
if (!choicesRaw) throw new Error("Missing required field: choices (pipe-separated)");
const choiceTexts = choicesRaw
.split("|")
.map((c) => c.trim())
.filter(Boolean);
if (choiceTexts.length < 2) throw new Error("At least 2 choices are required (pipe-separated)");
const correctAnswersRaw = row["correctanswers"]?.trim();
if (!correctAnswersRaw) throw new Error("Missing required field: correctAnswers");
const correctAnswers = correctAnswersRaw
.split("|")
.map((a) => a.trim())
.filter(Boolean);
Iif (correctAnswers.length === 0) throw new Error("At least one correct answer is required");
for (const ans of correctAnswers) {
if (!choiceTexts.includes(ans)) {
throw new Error(`correctAnswer "${ans}" does not match any value in choices`);
}
}
return applyRole(
{
...commonFields,
questionType: "Checkbox",
choices: choiceTexts.map((text, i) => ({ id: Date.now() + i, text })),
correctAnswer: { answers: correctAnswers, answerDetails },
},
role
);
}
function buildFreeResponsePayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
// correctAnswer is a single string for free-response (LaTeX or plain text)
const correctAnswer = row["correctanswer"]?.trim() || "";
return applyRole(
{
...commonFields,
questionType: "Free-response",
correctAnswer: { answers: correctAnswer, answerDetails },
},
role
);
}
// Empty canvas state produced by getCanvasAnswerObjectToString(0) when nothing is drawn.
// Used as a placeholder for Graph questions uploaded via CSV — the teacher must open and
// draw the actual answer in the editor after upload.
const EMPTY_GRAPH_ANSWER =
"lines#o#{}&dots#o#{}&labeldots#o#{}&labeldotstypes#o#{}&pointValueDots#o#{}&odots#o#{}&tplines#o#{}&ineqlines#o#{}";
function buildGraphPayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
return applyRole(
{
...commonFields,
questionType: "Graph",
correctAnswer: { answers: EMPTY_GRAPH_ANSWER, answerDetails },
},
role
);
}
function buildDragAndDropPayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
// Validate [[blank]] markers in the original question text
const blankMarkers = (commonFields.question.match(/\[\[blank\]\]/g) || []).length;
if (blankMarkers === 0) throw new Error("question must contain at least one [[blank]] marker for Drag-and-drop");
// blanks: pipe-separated correct answers, one per [[blank]] position
const blanksRaw = row["blanks"]?.trim();
Iif (!blanksRaw) throw new Error("Missing required field: blanks (pipe-separated correct answers per blank)");
const blanks = blanksRaw
.split("|")
.map((b) => b.trim())
.filter(Boolean);
if (blanks.length !== blankMarkers) {
throw new Error(
`blanks count (${blanks.length}) must match [[blank]] marker count in question (${blankMarkers})`
);
}
// dragChoices: pipe-separated all draggable items (correct answers + distractors)
const dragChoicesRaw = row["dragchoices"]?.trim();
if (!dragChoicesRaw) throw new Error("Missing required field: dragChoices (pipe-separated draggable items)");
const dragChoiceTexts = dragChoicesRaw
.split("|")
.map((c) => c.trim())
.filter(Boolean);
Iif (dragChoiceTexts.length === 0) throw new Error("At least one dragChoice is required");
for (const blank of blanks) {
if (!dragChoiceTexts.includes(blank)) {
throw new Error(`blank answer "${blank}" is not found in dragChoices`);
}
}
// Replace [[blank]] tokens with __blank__ (matches dragDropToString() in the editor)
const question = commonFields.question.replace(/\[\[blank\]\]/g, "__blank__");
return applyRole(
{
...commonFields,
questionType: "Drag-and-Drop",
question,
choices: dragChoiceTexts.map((text, i) => ({ id: i, text })),
correctAnswer: {
answers: blanks.map((answer, i) => ({ id: i, answer })),
answerDetails,
},
},
role
);
}
function buildDropDownMenuPayload(row, common, role) {
const { answerDetails, ...commonFields } = common;
// Validate [[blank]] markers in question
const blankMarkers = (commonFields.question.match(/\[\[blank\]\]/g) || []).length;
if (blankMarkers === 0) throw new Error("question must contain at least one [[blank]] marker for Drop-down-menu");
// blanks: pipe-separated correct answers, one per [[blank]] position
const blanksRaw = row["blanks"]?.trim();
Iif (!blanksRaw) throw new Error("Missing required field: blanks (pipe-separated correct answers per blank)");
const blanks = blanksRaw
.split("|")
.map((b) => b.trim())
.filter(Boolean);
Iif (blanks.length !== blankMarkers) {
throw new Error(
`blanks count (${blanks.length}) must match [[blank]] marker count in question (${blankMarkers})`
);
}
// dropdownOptions: pipe separates blank groups, comma separates options within each group
// e.g. "Paris,London,Berlin|Red,Blue,Green"
const dropdownOptionsRaw = row["dropdownoptions"]?.trim();
if (!dropdownOptionsRaw) throw new Error("Missing required field: dropdownOptions");
const optionGroups = dropdownOptionsRaw.split("|").map((group) =>
group
.split(",")
.map((opt) => opt.trim())
.filter(Boolean)
);
if (optionGroups.length !== blankMarkers) {
throw new Error(
`dropdownOptions groups (${optionGroups.length}) must match [[blank]] marker count (${blankMarkers})`
);
}
for (let i = 0; i < optionGroups.length; i++) {
if (optionGroups[i].length === 0) throw new Error(`Blank ${i + 1} has no dropdown options`);
if (!optionGroups[i].includes(blanks[i])) {
throw new Error(`blank answer "${blanks[i]}" for position ${i + 1} is not found in its dropdown options`);
}
}
// Replace [[blank]] with __blank__ (matches dropDownMenuToString() in the editor)
const question = commonFields.question.replace(/\[\[blank\]\]/g, "__blank__");
// Build the unnormalized choices structure: [{ id, items: [string] }]
const choices = optionGroups.map((items, i) => ({ id: i, items }));
return applyRole(
{
...commonFields,
questionType: "Drop-down-Menu",
question,
choices,
correctAnswer: {
answers: blanks.map((answer, i) => ({ id: i, answer })),
answerDetails,
},
},
role
);
}
// ── Public API ─────────────────────────────────────────────────────────────────
/**
* Maps a parsed CSV row to the API payload for createNewQuestion.
* Reads questionType from the row itself.
* Throws a descriptive Error if any field is missing or invalid.
*
* @param {object} row - Row object from parseCSV()
* @param {string} role - "teacher" | "staff"
* @returns {object} API-ready payload
*/
export function mapRowToPayload(row, role = "teacher") {
const questionType = row["questiontype"]?.trim();
if (!questionType) throw new Error("Missing required field: questionType");
if (!VALID_QUESTION_TYPES.includes(questionType)) {
throw new Error(`Invalid questionType "${questionType}". Must be one of: ${VALID_QUESTION_TYPES.join(", ")}`);
}
const common = extractCommonFields(row);
switch (questionType) {
case "Multiple-choice":
return buildMultipleChoicePayload(row, common, role);
case "Checkbox":
return buildCheckboxPayload(row, common, role);
case "Free-response":
return buildFreeResponsePayload(row, common, role);
case "Graph":
return buildGraphPayload(row, common, role);
case "Drag-and-drop":
return buildDragAndDropPayload(row, common, role);
case "Drop-down-menu":
return buildDropDownMenuPayload(row, common, role);
}
}
|