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 | 2x 18x 17x 18x 18x 18x 2x 1026x 1026x 8x 8x 513x 513x 513x 513x 8x 26x 26x 26x 8x 513x 513x 513x 513x 513x 8x 18x 18x 25x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 18x 18x 18x 8x 18x 18x 7x 18x 8x 8x 8x 8x 8x 7x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 18x 18x 89x 89x 89x 18x 18x 72x 71x 71x 71x 18x 18x 18x | import { useCallback, useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { useTheme } from "@mui/material/styles";
import { Box, Grid, Stack, useMediaQuery } from "@mui/material";
import SchoolIcon from "@mui/icons-material/School";
import AssignmentIcon from "@mui/icons-material/Assignment";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import GradeIcon from "@mui/icons-material/Grade";
import axios from "axios";
import { API_ENDPOINTS } from "@/api/endpoints";
import useAutoRefresh from "@/utils/hooks/useAutoRefresh";
import { useStudentDashboardWebSocket } from "@/utils/hooks/useStudentDashboardWebSocket";
import StatCard from "./components/StatCard";
import WelcomeBanner from "./components/WelcomeBanner";
import GradesChart from "./components/GradesChart";
import QuickActionsPanel from "./components/QuickActionsPanel";
import SearchTeacherWidget from "./components/SearchTeacherWidget";
import { capChartCategories } from "./components/capChartCategories";
// EI-2966 backfill widgets — re-integrated 2026-06-17 after PR #117 dropped them.
import AssignmentsCalendar from "./components/AssignmentsCalendar";
import GpaCard from "./components/GpaCard";
import ScoreDistributionCard from "./components/ScoreDistributionCard";
import AchievementsCard from "./components/AchievementsCard";
import DashboardPersonalizationMenu from "./components/DashboardPersonalizationMenu";
import {
DEFAULT_WIDGET_ORDER,
loadDashboardPreferences,
resolveWidgetOrder,
saveDashboardPreferences,
toggleWidgetVisibility,
} from "./components/dashboardPreferences";
const _WIDGET_RENDERERS = {
gpa: (key, refreshKey) => <GpaCard key={key} refreshKey={refreshKey} />,
achievements: (key, refreshKey) => <AchievementsCard key={key} refreshKey={refreshKey} />,
distribution: (key, refreshKey) => <ScoreDistributionCard key={key} refreshKey={refreshKey} />,
calendar: (key, refreshKey) => <AssignmentsCalendar key={key} refreshKey={refreshKey} />,
search_teacher: (key) => <SearchTeacherWidget key={key} />,
};
// GPA, Achievements, Score Distribution, and Upcoming Assignments render in
// the dashboard body grid alongside GradesChart; everything else (Quick
// Actions, Search Teacher) stays in the fixed-width sidebar.
const _BODY_WIDGET_IDS = new Set(["gpa", "achievements", "distribution", "calendar"]);
// `grade` on a submission is a string from the API — either a formatted
// numeric value (e.g. "85.50") or a status word ("pending"/"incomplete")
// for a submitted-but-ungraded attempt (see `submissions_statistics_fetch`
// in the services repo). Coercing a status word with `+` silently produces
// a "NaN" string once `.toFixed` runs on it, so ungraded entries must be
// filtered out before averaging rather than treated as 0 or NaN.
function numericGrade(grade) {
const num = Number(grade);
return Number.isFinite(num) ? num : null;
}
function computeStats(submissionsData) {
const classes = submissionsData?.classes ?? [];
const perClass = classes.map((cls) => {
const submitted = (cls.submissions ?? []).filter((s) => s.is_submitted);
const graded = submitted.map((s) => numericGrade(s.grade)).filter((g) => g !== null);
const avg =
graded.length === 0 ? 0 : parseFloat((graded.reduce((sum, g) => sum + g, 0) / graded.length).toFixed(2));
return { label: `${cls.title} (${cls.section})`, grade: avg, count: submitted.length, weight: graded.length };
});
// Allan Ninal 2026-10-04: cap chart categories (defence in depth after the 2,333-class freeze, eruditiontx-services-mvp #440).
const capped = capChartCategories(perClass);
const cats = capped.map((c) => c.label);
const grades = capped.map((c) => c.grade);
const submissionCounts = capped.map((c) => c.count);
const allGraded = classes
.flatMap((cls) => cls.submissions ?? [])
.filter((s) => s.is_submitted)
.map((s) => numericGrade(s.grade))
.filter((g) => g !== null);
const overallAvg =
allGraded.length > 0 ? (allGraded.reduce((sum, g) => sum + g, 0) / allGraded.length).toFixed(2) : null;
return { cats, grades, submissionCounts, overallAvg, classCount: perClass.length };
}
export default function Dashboard() {
const theme = useTheme();
const isMobile = useMediaQuery("(max-width:450px)");
const { studentData } = useSelector((state) => state.StudentData);
const [totalClasses, setTotalClasses] = useState(null);
const [totalAssignments, setTotalAssignments] = useState(null);
const [totalSubmissions, setTotalSubmissions] = useState(null);
const [avgGrade, setAvgGrade] = useState(null);
const [chartCategories, setChartCategories] = useState([]);
// The chart may fold classes into "Other (n)"; the chip shows the real count.
const [chartClassCount, setChartClassCount] = useState(0);
const [gradeData, setGradeData] = useState([]);
const [submissionsChartData, setSubmissionsChartData] = useState([]);
const [statsLoading, setStatsLoading] = useState(true);
// EI-2966 backfill: per-user widget visibility + order (localStorage).
const [prefs, setPrefs] = useState(() => loadDashboardPreferences());
const widgetOrder = useMemo(() => resolveWidgetOrder(prefs, DEFAULT_WIDGET_ORDER), [prefs]);
const hiddenSet = useMemo(() => new Set(prefs.hidden ?? []), [prefs]);
const handleToggleWidget = useCallback((widgetId) => {
setPrefs((curr) => {
const next = toggleWidgetVisibility(widgetId, curr);
saveDashboardPreferences(next);
return next;
});
}, []);
// EI-2966 backfill: WebSocket push triggers a refreshKey bump alongside
// the existing fetch-on-mount; the 30 s `useAutoRefresh` graceful-
// degradation path carries the dashboard today.
//
// No `url` is passed yet, so the socket never opens — the push channel
// also has no producers server-side, so there is nothing to receive. That
// wiring is EI-2966 follow-up work, deliberately NOT done under SEC-3.
// The token plumbing that used to sit here is gone: auth is the HttpOnly
// cookie, so there is nothing for the caller to supply.
const [refreshKey, setRefreshKey] = useState(0);
const { lastEvent } = useStudentDashboardWebSocket({});
useEffect(() => {
if (lastEvent) setRefreshKey((k) => k + 1);
}, [lastEvent]);
// Graceful-degradation polling fallback — 30 s tick re-fetches stats
// even when the WS isn't connected. Replicates the EI-3209 cadence.
const pollTick = useAutoRefresh(30000);
useEffect(() => {
Iif (pollTick > 0) setRefreshKey((k) => k + 1);
}, [pollTick]);
useEffect(() => {
const fetchAll = async () => {
const [classesRes, assignmentsRes, submissionsRes] = await Promise.allSettled([
axios.get(API_ENDPOINTS.student.dashboard.classesStatistics),
axios.get(API_ENDPOINTS.student.dashboard.assignmentsStatistics),
axios.get(API_ENDPOINTS.student.dashboard.submissionsStatistics),
]);
Eif (classesRes.status === "fulfilled" && classesRes.value.status === 200) {
setTotalClasses(classesRes.value.data.totalClasses);
}
if (assignmentsRes.status === "fulfilled" && assignmentsRes.value.status === 200) {
setTotalAssignments(assignmentsRes.value.data.totalAssignments);
}
Eif (submissionsRes.status === "fulfilled" && submissionsRes.value.status === 200) {
setTotalSubmissions(submissionsRes.value.data.totalSubmissions);
const { cats, grades, submissionCounts, overallAvg, classCount } = computeStats(
submissionsRes.value.data
);
setChartCategories(cats);
setChartClassCount(classCount);
setGradeData(grades);
setSubmissionsChartData(submissionCounts);
setAvgGrade(overallAvg);
}
setStatsLoading(false);
};
fetchAll();
}, [refreshKey]);
const firstName = studentData?.first_name ?? "";
const statCards = [
{
id: "student-dashboard-statcard-classes",
icon: <SchoolIcon />,
value: totalClasses ?? "—",
label: "Enrolled Classes",
color: theme.palette.primary.main,
},
{
id: "student-dashboard-statcard-assignments",
icon: <AssignmentIcon />,
value: totalAssignments ?? "—",
label: "Total Assignments",
color: theme.palette.warning.main,
},
{
id: "student-dashboard-statcard-submissions",
icon: <CheckCircleIcon />,
value: totalSubmissions ?? "—",
label: "Submissions",
color: theme.palette.success.main,
},
{
id: "student-dashboard-statcard-avg-grade",
icon: <GradeIcon />,
value: avgGrade ?? "—",
label: "Avg. Grade",
color: theme.palette.info.main,
tooltip:
"Weighted average across every graded submission from all your classes " +
"(not a plain average of your per-class grades). Classes with more graded " +
"work count for more.",
},
];
const visibleWidgets = widgetOrder.filter((id) => !hiddenSet.has(id));
const visibleBodyWidgets = visibleWidgets.filter((id) => _BODY_WIDGET_IDS.has(id));
const visibleSidebarWidgets = visibleWidgets.filter((id) => !_BODY_WIDGET_IDS.has(id));
return (
<Box
id="student-dashboard"
sx={{
minHeight: "100vh",
bgcolor: (t) => (t.palette.mode === "dark" ? "background.default" : "#f8f9fc"),
}}
>
<WelcomeBanner firstName={firstName} isMobile={isMobile} />
<Box sx={{ px: { xs: 2, sm: 3, md: 4 }, mt: -3, pb: 10 }}>
<Stack direction="row" justifyContent="flex-end" sx={{ mb: 1 }}>
<DashboardPersonalizationMenu
allWidgetIds={DEFAULT_WIDGET_ORDER}
hiddenSet={hiddenSet}
onToggle={handleToggleWidget}
/>
</Stack>
<Grid container spacing={{ xs: 1.5, sm: 2 }} sx={{ mb: 4 }}>
{statCards.map((s) => (
<Grid id={s.id} size={{ xs: 6, md: 3 }} key={s.label}>
<StatCard {...s} loading={statsLoading} />
</Grid>
))}
</Grid>
<Box
sx={{
display: "flex",
gap: 3,
alignItems: "flex-start",
flexDirection: { xs: "column", md: "row" },
}}
>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Stack spacing={3}>
<GradesChart
gradeData={gradeData}
submissionsData={submissionsChartData}
chartCategories={chartCategories}
classCount={chartClassCount}
loading={statsLoading}
/>
{visibleBodyWidgets.length > 0 && (
<Grid container spacing={3}>
{visibleBodyWidgets.map((widgetId) => {
const render = _WIDGET_RENDERERS[widgetId];
Iif (!render) return null;
return (
<Grid key={widgetId} size={{ xs: 12, sm: 6 }}>
{render(widgetId, refreshKey)}
</Grid>
);
})}
</Grid>
)}
</Stack>
</Box>
<Box id="student-dashboard-widgets" sx={{ width: { xs: "100%", md: "310px" }, flexShrink: 0 }}>
<Stack spacing={3}>
<QuickActionsPanel
totalClasses={totalClasses ?? "—"}
totalAssignments={totalAssignments ?? "—"}
totalSubmissions={totalSubmissions ?? "—"}
/>
{visibleSidebarWidgets.map((widgetId) => {
const render = _WIDGET_RENDERERS[widgetId];
Iif (!render) return null;
return render(widgetId, refreshKey);
})}
</Stack>
</Box>
</Box>
</Box>
</Box>
);
}
|