All files / src/app/teacher-page/page/tests GlobalAssignments.jsx

98.55% Statements 136/138
89.41% Branches 76/85
100% Functions 33/33
98.42% Lines 125/127

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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539                                                                          1x 100x 100x 100x 100x 100x 100x   100x 100x 100x 100x 100x 100x 100x 100x 100x   100x 141x         141x 141x 141x     141x 141x   141x                                       100x 141x       100x 80x                     326x 326x 326x     326x       100x 99x 90x 86x 84x 82x     481x   100x 1x 1x 1x 1x 1x     100x 4x 4x 2x           100x   13x 13x 1x 1x 1x   12x 6x 6x 6x 2x 2x   4x 4x           100x 11x 11x 11x 2x     9x 9x   9x 9x 5x   11x 4x 4x         4x 4x 1x               3x 3x         9x       789x       100x 789x 789x   789x       10x     10x                 100x 31x         479x                                                                         479x                     479x 479x               479x   479x                                   479x 479x             479x 66x                       413x             100x 481x 481x 481x       1x             100x   100x 31x 31x 31x 30x 29x   1x     1x 1x   31x       31x     100x                                                                                                               66x                                             7x                 2x                 2x                   2x                                                                                                              
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTheme, alpha } from "@mui/material/styles";
import PinnedTable from "@/utils/components/tables/pinned-table/PinnedTable";
import { Alert, AlertTitle, Box, IconButton, MenuItem, Tooltip, Typography } from "@mui/material";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { useDispatch } from "react-redux";
import { utcToLocalTime } from "@/utils/helpers/utcToLocalTime";
import { useLocation, useNavigate } from "react-router-dom";
import { API_ENDPOINTS } from "@/api/endpoints";
import axios from "axios";
import { _setSpecificAssignmentData } from "@/store/slices/teacher/TeacherSpecificAssignment";
import useFeatureFlag from "@/utils/hooks/useFeatureFlag";
import {
    formatExamCatalogTitle,
    formatFeatureKeyLabel,
    formatGlobalAssignmentTypeLabel,
    getAssignmentAccessState,
    getPlanChipColor,
    getPlanLabel,
    isEruditionLibraryAssignment,
    isExamCatalogAssignment,
    isFeatureNotEnabled403,
    parseExamFeatureKey,
    parseFeatureKeyFrom403,
    ERUDITION_LIBRARY_LABEL,
} from "@/utils/features/featureAccess";
import { useUpgradeDialog } from "@/utils/components/feature-access/UpgradeDialogProvider";
import PlanBadge from "@/utils/components/feature-access/PlanBadge";
import SoftChip from "@/utils/components/feature-access/SoftChip";
import SidebarLockedBadge from "@/utils/components/side-drawer/SidebarLockedBadge";
import { getCatalogRowSoftSx } from "@/utils/components/tables/heroTableStyles";
import { getThemeGradientBarSx } from "@/utils/theme/themeSoftTokens";
import { TEACHER_TESTS_IDS, teacherTestsRowActionViewId, teacherTestsRowId } from "@/utils/helpers/testIds";
import TestsTableToolbar from "@/app/teacher-page/page/tests/TestsTableToolbar";
import { applyTestsFilters, DEFAULT_TESTS_FILTERS } from "@/app/teacher-page/page/tests/testsFilters";
 
const GlobalAssignments = () => {
    const theme = useTheme();
    const navigate = useNavigate();
    const location = useLocation();
    const dispatch = useDispatch();
    const { isFeatureEnabled, features, currentPlan, planName, isLoading: featuresLoading } = useFeatureFlag("teacher");
    const { openUpgradeDialog } = useUpgradeDialog();
 
    const [assignments, setAssignments] = useState([]);
    const [assignmentsLoading, setAssignmentsLoading] = useState(true);
    const [viewingAssignmentId, setViewingAssignmentId] = useState(null);
    const [error, setError] = useState("");
    const [assignmentType, setAssignmentType] = useState(DEFAULT_TESTS_FILTERS.assignmentType);
    const [accessFilter, setAccessFilter] = useState(DEFAULT_TESTS_FILTERS.accessFilter);
    const [catalogFilter, setCatalogFilter] = useState(DEFAULT_TESTS_FILTERS.catalogFilter);
    const [slotFilter, setSlotFilter] = useState(DEFAULT_TESTS_FILTERS.slotFilter);
    const [globalFilter, setGlobalFilter] = useState(DEFAULT_TESTS_FILTERS.globalFilter);
 
    const enrichAssignment = (assignment) => {
        const access = getAssignmentAccessState(assignment, features, isFeatureEnabled, {
            featuresLoading,
            currentPlan,
            planName,
        });
        const examMeta = parseExamFeatureKey(access.featureKey);
        const isCatalogTest = isExamCatalogAssignment(assignment);
        const catalogTitle = isCatalogTest
            ? formatExamCatalogTitle(access.featureKey, assignment?.type, examMeta?.slot)
            : null;
        const sourceTitle = assignment?.title;
        const sourceDescription = assignment?.description;
 
        return {
            ...assignment,
            // Catalog rows: short slot title (`TSI 1`); API title becomes the description.
            title: catalogTitle || sourceTitle,
            description: isCatalogTest
                ? sourceDescription || sourceTitle || ""
                : sourceDescription,
            feature_key: access.featureKey,
            _accessLocked: access.locked,
            _accessFeatureKey: access.featureKey,
            _accessMinPlan: access.minPlan,
            _accessFeatureMeta: access.featureMeta,
            _isCatalogTest: isCatalogTest,
            _isStaffLibraryTest: isEruditionLibraryAssignment(assignment),
            _typeLabel: formatGlobalAssignmentTypeLabel(assignment),
            _examSlot: examMeta?.slot ?? null,
            _sourceTitle: sourceTitle,
        };
    };
 
    const enrichedAssignments = useMemo(
        () => assignments.map((row) => enrichAssignment(row)),
        [assignments, features, isFeatureEnabled, featuresLoading, currentPlan, planName]
    );
 
    const filteredAssignments = useMemo(
        () =>
            applyTestsFilters(enrichedAssignments, {
                assignmentType,
                accessFilter,
                catalogFilter,
                slotFilter,
                globalFilter,
            }),
        [enrichedAssignments, assignmentType, accessFilter, catalogFilter, slotFilter, globalFilter]
    );
 
    const catalogCount = enrichedAssignments.filter((row) => row._isCatalogTest).length;
    const staffLibraryCount = enrichedAssignments.filter((row) => row._isStaffLibraryTest).length;
    const lockedCount = enrichedAssignments.filter((row) => row._accessLocked).length;
    // "Available" = tests the teacher can actually open on their current subscription.
    // A subscription-locked test (catalog OR non-catalog) is excluded here.
    const availableCount = enrichedAssignments.filter((row) => !row._accessLocked).length;
 
    // Stat badges are mutually exclusive quick filters: at most ONE is active, and it
    // maps to a single clean filter state (catalog OR staff library OR available OR locked).
    const activeQuickFilter = (() => {
        if (catalogFilter === "catalog" && accessFilter === "all") return "catalog";
        if (catalogFilter === "staffLibrary" && accessFilter === "all") return "staffLibrary";
        if (catalogFilter === "all" && accessFilter === "available") return "available";
        if (catalogFilter === "all" && accessFilter === "locked") return "locked";
        return null;
    })();
 
    const isRowLocked = (row) => Boolean(row?.original?._accessLocked);
 
    const resetFilters = useCallback(() => {
        setAssignmentType(DEFAULT_TESTS_FILTERS.assignmentType);
        setAccessFilter(DEFAULT_TESTS_FILTERS.accessFilter);
        setCatalogFilter(DEFAULT_TESTS_FILTERS.catalogFilter);
        setSlotFilter(DEFAULT_TESTS_FILTERS.slotFilter);
        setGlobalFilter(DEFAULT_TESTS_FILTERS.globalFilter);
    }, []);
 
    const handleCatalogFilterChange = useCallback((value) => {
        setCatalogFilter(value);
        if (value === "staffLibrary") {
            setSlotFilter("all");
        }
    }, []);
 
    // One badge at a time: clicking a badge applies exactly its filter (and clears the
    // others); clicking the already-active badge clears back to "all".
    const toggleQuickFilter = useCallback(
        (kind) => {
            setSlotFilter("all");
            if (activeQuickFilter === kind) {
                setCatalogFilter("all");
                setAccessFilter("all");
                return;
            }
            if (kind === "catalog") {
                setCatalogFilter("catalog");
                setAccessFilter("all");
            } else if (kind === "staffLibrary") {
                setCatalogFilter("staffLibrary");
                setAccessFilter("all");
            } else {
                setCatalogFilter("all");
                setAccessFilter(kind);
            }
        },
        [activeQuickFilter]
    );
 
    const viewAssignment = async (row) => {
        const assignmentId = row?.original?._id;
        const title = row?.original?.title;
        if (!assignmentId || viewingAssignmentId) {
            return;
        }
 
        setError("");
        setViewingAssignmentId(assignmentId);
 
        try {
            const response = await axios.get(API_ENDPOINTS.teacher.assignment.staffAssignmentsFetch(assignmentId));
            const assignment = response?.data?.assignment;
 
            if (assignment) {
                dispatch(_setSpecificAssignmentData(assignment));
                navigate(`${location.pathname}/${encodeURIComponent(title)}`, {
                    state: { assignmentUUID: assignmentId, accessGranted: true },
                });
            }
        } catch (err) {
            const rowData = row?.original || {};
            if (isFeatureNotEnabled403(err)) {
                openUpgradeDialog({
                    title: "This test is locked",
                    featureKey: parseFeatureKeyFrom403(err),
                    featureLabel: rowData.title,
                    featureMeta: rowData._accessFeatureMeta,
                    minPlan: rowData._accessMinPlan,
                });
            } else {
                console.error("Failed to fetch assignment:", err);
                setError(
                    err?.response?.data?.detail || "Could not open this test. Please try again or contact support."
                );
            }
        } finally {
            setViewingAssignmentId(null);
        }
    };
 
    const getAccessRowSx = (row) => ({
        sx: getCatalogRowSoftSx(row.original._accessLocked, theme),
    });
 
    const getTableRowProps = ({ row }) => {
        const accessRowProps = getAccessRowSx(row);
        const rowMeta = { ...row.original, _rowIndex: row.index };
 
        return {
            id: teacherTestsRowId(rowMeta),
            ...accessRowProps,
            onClick: (event) => {
                Iif (event.target.closest("button, a, [role='menuitem'], input, select, textarea")) {
                    return;
                }
                viewAssignment(row);
            },
            sx: {
                ...(accessRowProps.sx || {}),
                cursor: "pointer",
            },
        };
    };
 
    const columns = useMemo(
        () => [
            {
                accessorKey: "title",
                header: "Title",
                Cell: ({ row }) => (
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
                        <Box sx={{ minWidth: 0, flex: 1 }}>
                            <Typography
                                variant="body2"
                                sx={{
                                    fontWeight: row.original._isCatalogTest ? 600 : 400,
                                    lineHeight: 1.3,
                                }}
                            >
                                {row.original.title}
                            </Typography>
                            {row.original._isCatalogTest && row.original.description ? (
                                <Typography
                                    variant="caption"
                                    color="text.secondary"
                                    sx={{
                                        display: "block",
                                        lineHeight: 1.3,
                                        mt: 0.25,
                                        overflow: "hidden",
                                        textOverflow: "ellipsis",
                                        whiteSpace: "nowrap",
                                    }}
                                    title={row.original.description}
                                >
                                    {row.original.description}
                                </Typography>
                            ) : null}
                        </Box>
                        {row.original._accessLocked ? <SidebarLockedBadge isActive={false} /> : null}
                    </Box>
                ),
            },
            {
                accessorKey: "type",
                header: "Type",
                Cell: ({ row }) => (
                    <SoftChip
                        label={row.original._typeLabel || formatGlobalAssignmentTypeLabel(row.original)}
                        color={row.original._isStaffLibraryTest ? "info" : "accent"}
                        size="sm"
                    />
                ),
            },
            {
                id: "planFeature",
                header: "Plan feature",
                Cell: ({ row }) => {
                    const featureKey = row.original._accessFeatureKey;
                    Iif (!featureKey) {
                        return (
                            <Typography variant="caption" color="text.secondary">
                                —
                            </Typography>
                        );
                    }
 
                    const locked = row.original._accessLocked;
 
                    return (
                        <SoftChip
                            label={formatFeatureKeyLabel(featureKey)}
                            color={locked ? "warning" : "success"}
                            size="sm"
                            sx={{ maxWidth: "100%" }}
                        />
                    );
                },
            },
            {
                accessorKey: "questions",
                header: "Questions",
            },
            {
                accessorKey: "created_at",
                header: "Date Created",
                Cell: ({ cell }) => {
                    const dateOpen = cell.getValue();
                    return utcToLocalTime(dateOpen) == "Invalid date" ? "" : utcToLocalTime(dateOpen);
                },
            },
            {
                id: "access",
                header: "Access",
                Cell: ({ row }) => {
                    if (row.original._accessLocked) {
                        return (
                            <SoftChip
                                icon={<LockOutlinedIcon />}
                                label={
                                    row.original._accessMinPlan ? getPlanLabel(row.original._accessMinPlan) : "Locked"
                                }
                                color={getPlanChipColor(row.original._accessMinPlan)}
                                size="sm"
                            />
                        );
                    }
 
                    return <SoftChip label="On your plan" color="success" size="sm" />;
                },
            },
        ],
        [currentPlan]
    );
 
    const rowActions = ({ row }) => {
        const locked = isRowLocked(row);
        const rowMeta = { ...row.original, _rowIndex: row.index };
        return [
            <MenuItem
                id={teacherTestsRowActionViewId(rowMeta)}
                key="viewAssignment"
                onClick={() => viewAssignment(row)}
            >
                {locked ? "View (locked)" : "View"}
            </MenuItem>,
        ];
    };
 
    const catalogHelp = `Green left edge = on your plan; amber = upgrade required. Plan catalog = tiered STAAR/TSI/SAT/ACT practice tests (per-slot keys). ${ERUDITION_LIBRARY_LABEL} = tests created by Erudition outside the plan catalog (Intermediate+).`;
 
    useEffect(() => {
        const fetchAssignments = async () => {
            try {
                const response = await axios.get(API_ENDPOINTS.teacher.assignment.staffAssignmentsFetchAll);
                if (Array.isArray(response.data?.assignments)) {
                    setAssignments(response.data.assignments);
                } else {
                    setAssignments([]);
                }
            } catch (err) {
                console.error("Failed to fetch assignments:", err);
                setError("Failed to load assignments.");
            } finally {
                setAssignmentsLoading(false);
            }
        };
 
        fetchAssignments();
    }, []);
 
    return (
        <Box
            id={TEACHER_TESTS_IDS.page}
            sx={{
                height: "calc(100vh - var(--app-footer-height, 32px))",
                maxHeight: "calc(100vh - var(--app-footer-height, 32px))",
                minHeight: 480,
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
            }}
        >
            <Box
                id={TEACHER_TESTS_IDS.header}
                sx={{
                    flexShrink: 0,
                    px: 2,
                    py: 1,
                    ...getThemeGradientBarSx(theme),
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    gap: 1,
                }}
            >
                <Box sx={{ display: "flex", alignItems: "center", gap: 0.5, minWidth: 0 }}>
                    <Typography
                        id={TEACHER_TESTS_IDS.title}
                        variant="h6"
                        sx={{ fontSize: "1.1rem", fontWeight: 600, lineHeight: 1.3 }}
                    >
                        Tests
                    </Typography>
                    <Tooltip title={catalogHelp} arrow placement="bottom-start">
                        <IconButton
                            id={TEACHER_TESTS_IDS.helpButton}
                            size="small"
                            sx={{ color: "inherit", opacity: 0.9 }}
                        >
                            <InfoOutlinedIcon fontSize="small" />
                        </IconButton>
                    </Tooltip>
                </Box>
                <PlanBadge id={TEACHER_TESTS_IDS.planBadge} plan={currentPlan} planName={planName} onPrimary />
            </Box>
 
            {error && (
                <Alert id={TEACHER_TESTS_IDS.errorAlert} sx={{ borderRadius: 0, flexShrink: 0 }} severity="error">
                    <AlertTitle>Error</AlertTitle>
                    {error}
                </Alert>
            )}
 
            {enrichedAssignments.length > 0 ? (
                <Box
                    id={TEACHER_TESTS_IDS.statsBar}
                    sx={(t) => ({
                        flexShrink: 0,
                        px: 2,
                        py: 0.75,
                        display: "flex",
                        flexWrap: "wrap",
                        alignItems: "center",
                        gap: 0.75,
                        borderBottom: "1px solid",
                        borderColor: "divider",
                        bgcolor:
                            t.palette.mode === "dark"
                                ? alpha(t.palette.common.white, 0.03)
                                : alpha(t.palette.common.black, 0.02),
                    })}
                >
                    <SoftChip
                        id={TEACHER_TESTS_IDS.statCatalog}
                        label={`${catalogCount} plan catalog`}
                        color="accent"
                        size="sm"
                        clickable
                        active={activeQuickFilter === "catalog"}
                        onClick={() => toggleQuickFilter("catalog")}
                    />
                    <SoftChip
                        id={TEACHER_TESTS_IDS.statEruditionLibrary}
                        label={`${staffLibraryCount} Erudition library`}
                        color="info"
                        size="sm"
                        clickable
                        active={activeQuickFilter === "staffLibrary"}
                        onClick={() => toggleQuickFilter("staffLibrary")}
                    />
                    <SoftChip
                        id={TEACHER_TESTS_IDS.statAvailable}
                        label={`${availableCount} available`}
                        color="success"
                        size="sm"
                        clickable
                        active={activeQuickFilter === "available"}
                        onClick={() => toggleQuickFilter("available")}
                    />
                    {lockedCount > 0 ? (
                        <SoftChip
                            id={TEACHER_TESTS_IDS.statLocked}
                            label={`${lockedCount} locked`}
                            color="warning"
                            size="sm"
                            clickable
                            active={activeQuickFilter === "locked"}
                            onClick={() => toggleQuickFilter("locked")}
                        />
                    ) : null}
                </Box>
            ) : null}
 
            <Box
                sx={{
                    flex: 1,
                    minHeight: 0,
                    px: 2,
                    pt: 1,
                    pb: 0.5,
                    display: "flex",
                    flexDirection: "column",
                    overflow: "hidden",
                    gap: 0,
                }}
            >
                <TestsTableToolbar
                    assignmentType={assignmentType}
                    accessFilter={accessFilter}
                    catalogFilter={catalogFilter}
                    slotFilter={slotFilter}
                    globalFilter={globalFilter}
                    filteredCount={filteredAssignments.length}
                    totalCount={enrichedAssignments.length}
                    onAssignmentTypeChange={setAssignmentType}
                    onAccessFilterChange={setAccessFilter}
                    onCatalogFilterChange={handleCatalogFilterChange}
                    onSlotFilterChange={setSlotFilter}
                    onGlobalFilterChange={setGlobalFilter}
                    onReset={resetFilters}
                />
                <Box sx={{ flex: 1, minHeight: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
                    <PinnedTable
                        tableId={TEACHER_TESTS_IDS.table}
                        variant="soft"
                        columns={columns}
                        data={filteredAssignments}
                        enableTopToolbar={false}
                        pinnedColumn={false}
                        rowActions={rowActions}
                        isLoading={assignmentsLoading}
                        enableStickyHeader
                        enableGlobalFilter={false}
                        muiTableBodyRowProps={getTableRowProps}
                    />
                </Box>
            </Box>
        </Box>
    );
};
 
export default GlobalAssignments;