From b3449796d0773bf91f6b600654aaed5c1f7d2d4b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 7 Oct 2026 19:36:33 +0000 Subject: [PATCH 1/3] Add absence tracking page: class cards, typed threshold, absences left per student MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New client-only page (/student/absence-tracking, menu: מעקב חיסורים) built on the existing StudentAttendance pivot, kept separate from the pivot table. Fetches all pivot pages, groups students by base class, shows how many unapproved absences each student has left before a user-typed threshold, summary tiles that filter over/near students, the subject behind most of a class's absences, and a per-student drill-down from att_report. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T5Hdg7cKavdUKRf9T4FPnP --- client/src/App.jsx | 2 + client/src/GeneralLayout.jsx | 10 + client/src/pivots/AbsenceTrackingList.jsx | 550 ++++++++++++++++++ .../src/pivots/AbsenceTrackingList.test.jsx | 66 +++ client/src/roadmapFeatures.js | 1 + client/src/utils/absenceTracking.js | 140 +++++ client/src/utils/absenceTracking.test.js | 119 ++++ 7 files changed, 888 insertions(+) create mode 100644 client/src/pivots/AbsenceTrackingList.jsx create mode 100644 client/src/pivots/AbsenceTrackingList.test.jsx create mode 100644 client/src/utils/absenceTracking.js create mode 100644 client/src/utils/absenceTracking.test.js diff --git a/client/src/App.jsx b/client/src/App.jsx index af065695..a15ba9d8 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -53,6 +53,7 @@ import Settings from 'src/settings/Settings'; import StudentAttendanceList from 'src/pivots/StudentAttendanceList'; import StudentAttendanceByKlassList from 'src/pivots/StudentAttendanceByKlassList'; import PercentReportWithDatesList from 'src/pivots/PercentReportWithDatesList'; +import AbsenceTrackingList from 'src/pivots/AbsenceTrackingList'; import { isUploadedFiles, isAdmin } from '@shared/utils/permissionsUtil'; import { @@ -175,6 +176,7 @@ const App = () => ( } /> } /> + } /> } /> ), + ({ permissions }) => + !isTeacherView(permissions) && ( + } + /> + ), ({ permissions }) => !isTeacherView(permissions) && isStudentAttendanceByKlass(permissions) && ( diff --git a/client/src/pivots/AbsenceTrackingList.jsx b/client/src/pivots/AbsenceTrackingList.jsx new file mode 100644 index 00000000..3e37975d --- /dev/null +++ b/client/src/pivots/AbsenceTrackingList.jsx @@ -0,0 +1,550 @@ +import { useMemo, useState } from 'react'; +import { + DateInput, + NullableBooleanInput, + RecordContextProvider, + TextInput, + useDataProvider, + useGetOne, + useListContext, + usePermissions, +} from 'react-admin'; +import { useQuery } from '@tanstack/react-query'; +import { Box, ButtonBase, Card, CircularProgress, TextField as MuiTextField, Typography } from '@mui/material'; +import { CommonList } from '@shared/components/crudContainers/CommonList'; +import { EmptyPage } from '@shared/components/crudContainers/EmptyPage'; +import { + CommonReferenceInputFilter, + filterByUserId, + filterByUserIdAndYear, +} from '@shared/components/fields/CommonReferenceInputFilter'; +import CommonReferenceArrayInput from '@shared/components/fields/CommonReferenceArrayInput'; +import { CommonYearInputFilter } from '@shared/components/fields/CommonYear'; +import { ShowMatchingRecordsButton } from '@shared/components/fields/ShowMatchingRecordsButton'; +import { adminUserFilter } from '@shared/components/fields/PermissionFilter'; +import { defaultYearFilter } from '@shared/utils/yearFilter'; +import { filterArrayByParams } from '@shared/utils/filtersUtil'; +import { useIsAdmin } from '@shared/utils/permissionsUtil'; +import { MAX_PAGE_SIZE } from '@shared/config/settings'; +import { + DEFAULT_THRESHOLD_PERCENT, + NEAR_THRESHOLD_ABSENCES, + formatPercent, + getDetailDateRange, + getLessonHeaders, + getStudentStats, + getTopSubject, + groupByKlass, + summarizeStudentReports, +} from 'src/utils/absenceTracking'; + +// Reuses the StudentAttendance pivot as is; this page only changes how its numbers are shown. +const RESOURCE = 'student_by_year/pivot?extra.pivot=StudentAttendance'; +const STORE_KEY = 'absence-tracking'; +const THRESHOLD_STORAGE_KEY = 'absenceTracking.thresholdPercent'; +const NO_KLASS_LABEL = 'ללא כיתת אם'; +// The drill-down reads one student's reports page by page; this caps it for very long ranges. +const MAX_DETAIL_PAGES = 10; + +const filters = [ + adminUserFilter, + , + , + , + , + , + , + , + , + , +]; + +const filterDefaultValues = { + year: defaultYearFilter.year, + isActive: true, + extra: {}, +}; + +const STATUS_STYLES = { + over: { pill: { bgcolor: '#fde7e6', color: '#a5221a', fontWeight: 'bold' }, bar: '#d93a2e', text: '#a5221a' }, + near: { pill: { bgcolor: '#fff1dc', color: '#9a4a00', fontWeight: 'bold' }, bar: '#e98a15', text: '#9a4a00' }, + ok: { pill: { color: 'text.secondary' }, bar: '#8fb7a3', text: 'text.secondary' }, +}; + +const readStoredThreshold = () => { + try { + const stored = Number(localStorage.getItem(THRESHOLD_STORAGE_KEY)); + return stored > 0 && stored <= 100 ? stored : DEFAULT_THRESHOLD_PERCENT; + } catch { + return DEFAULT_THRESHOLD_PERCENT; + } +}; + +const chunk = (items, size) => { + const chunks = []; + for (let i = 0; i < items.length; i += size) chunks.push(items.slice(i, i + size)); + return chunks; +}; + +// The list context holds page 1 (the data provider caps a page at MAX_PAGE_SIZE); fetch the rest. +const useAllPivotRows = () => { + const dataProvider = useDataProvider(); + const { data, total, filterValues, sort, isPending } = useListContext(); + const pageCount = Math.ceil((total ?? 0) / MAX_PAGE_SIZE); + const { data: restPages, isPending: restPending } = useQuery({ + queryKey: [RESOURCE, 'absence-tracking-pages', filterValues, sort, pageCount], + enabled: !isPending && pageCount > 1, + queryFn: () => + Promise.all( + Array.from({ length: pageCount - 1 }, (_, i) => + dataProvider + .getList(RESOURCE, { + pagination: { page: i + 2, perPage: MAX_PAGE_SIZE }, + sort, + filter: filterValues, + }) + .then((result) => result.data), + ), + ), + }); + const pages = useMemo(() => [data ?? [], ...(restPages ?? [])], [data, restPages]); + return { pages, isPending: isPending || (pageCount > 1 && restPending) }; +}; + +const useBaseKlasses = (studentIds, year) => { + const dataProvider = useDataProvider(); + const { data } = useQuery({ + queryKey: ['student_base_klass', 'absence-tracking', studentIds, year], + enabled: studentIds.length > 0, + queryFn: () => + Promise.all( + chunk(studentIds, MAX_PAGE_SIZE).map((ids) => + dataProvider + .getList('student_base_klass', { + pagination: { page: 1, perPage: MAX_PAGE_SIZE }, + sort: { field: 'id', order: 'ASC' }, + filter: { id: ids, ...(year && { year }) }, + }) + .then((result) => result.data), + ), + ).then((results) => Object.fromEntries(results.flat().map((row) => [row.id, row.klassName]))), + }); + return data ?? {}; +}; + +const ThresholdInput = ({ value, onChange }) => ( + onChange(event.target.value)} + inputProps={{ min: 1, max: 100, step: 1 }} + helperText="חיסורים לא מאושרים מתוך כל השיעורים" + sx={{ width: 220 }} + /> +); + +const SummaryTiles = ({ students, noReportsCount, thresholdPercent, status, onStatusChange }) => { + const over = students.filter((s) => s.status.key === 'over').length; + const near = students.filter((s) => s.status.key === 'near').length; + const lessons = students.reduce((sum, s) => sum + s.lessons, 0); + const unapproved = students.reduce((sum, s) => sum + s.unapproved, 0); + const approved = students.reduce((sum, s) => sum + s.approved, 0); + const tiles = [ + { + key: '', + label: 'תלמידות בדוח', + value: students.length, + hint: noReportsCount ? `ועוד ${noReportsCount} בלי דיווחים בתקופה` : 'לחיצה מציגה את כולן', + }, + { key: 'over', label: 'עברו את הסף', value: over, hint: `${thresholdPercent}% חיסורים לא מאושרים ומעלה`, color: STATUS_STYLES.over.text }, + { key: 'near', label: 'קרובות לסף', value: near, hint: `עוד 1–${NEAR_THRESHOLD_ABSENCES} חיסורים ויעברו`, color: STATUS_STYLES.near.text }, + { + label: 'אחוז חיסור כללי', + value: lessons ? formatPercent(unapproved / lessons) : '–', + hint: `${unapproved} חיסורים לא מאושרים · ${approved} מאושרים`, + }, + ]; + return ( + + {tiles.map((tile) => { + const clickable = tile.key !== undefined; + const selected = clickable && status === tile.key; + return ( + onStatusChange(status === tile.key ? '' : tile.key) : undefined} + aria-pressed={clickable ? selected : undefined} + sx={{ + px: 2.5, + py: 1.5, + borderRadius: 3, + display: 'flex', + flexDirection: 'column', + alignItems: 'flex-start', + textAlign: 'start', + ...(selected && { borderColor: 'primary.main', boxShadow: (theme) => `inset 0 0 0 1px ${theme.palette.primary.main}` }), + }} + > + {tile.label} + + {tile.value} + + {tile.hint} + + ); + })} + + ); +}; + +const leftText = ({ key, left }) => { + if (key === 'over') return left === 0 ? 'הגיעה לסף' : `${-left} מעל הסף`; + return left === 1 ? 'עוד חיסור אחד לסף' : `עוד ${left} חיסורים לסף`; +}; + +const ThresholdMeter = ({ student, thresholdRatio }) => { + const style = STATUS_STYLES[student.status.key]; + const scaleMax = Math.max(0.4, thresholdRatio * 2); + return ( + + + + {formatPercent(student.ratio)} + + + {leftText(student.status)} + + + + + + + + ); +}; + +const chipSx = { + fontSize: 12.5, + border: 1, + borderColor: 'divider', + borderRadius: 999, + px: 1, + whiteSpace: 'nowrap', + fontVariantNumeric: 'tabular-nums', +}; + +const SubjectChips = ({ subjects }) => { + if (!subjects.length) { + return ללא חיסורים; + } + return ( + + {subjects.slice(0, 4).map((subject, index) => ( + = 3 && { borderColor: 'transparent', ...STATUS_STYLES.over.pill, fontWeight: 600 }) }} + > + {subject.name} {subject.abs} + + ))} + {subjects.length > 4 && ( + +{subjects.length - 4} + )} + + ); +}; + +const formatDate = (value) => (value ? new Date(value).toLocaleDateString('he-IL') : ''); + +const StudentDetail = ({ student, lessonHeaders }) => { + const dataProvider = useDataProvider(); + const { filterValues } = useListContext(); + const reportMonthId = filterValues?.extra?.reportMonthReferenceId; + const { data: reportMonth, isPending: monthPending } = useGetOne('report_month', { id: reportMonthId }, { enabled: !!reportMonthId }); + const range = getDetailDateRange(filterValues?.extra, reportMonth); + const filter = { + studentReferenceId: student.id, + ...(filterValues?.year && { year: filterValues.year }), + ...(filterValues?.['klassReferenceIds:$cont'] && { klassReferenceId: filterValues['klassReferenceIds:$cont'] }), + ...(range.from && { 'reportDate:$gte': range.from }), + ...(range.to && { 'reportDate:$lte': range.to }), + }; + const { data: reports, isPending } = useQuery({ + queryKey: ['att_report', 'absence-tracking-detail', filter], + enabled: !reportMonthId || !monthPending, + queryFn: async () => { + const rows = []; + for (let page = 1; page <= MAX_DETAIL_PAGES; page++) { + const result = await dataProvider.getList('att_report', { + pagination: { page, perPage: MAX_PAGE_SIZE }, + sort: { field: 'reportDate', order: 'DESC' }, + filter, + }); + rows.push(...result.data); + if (rows.length >= result.total || !result.data.length) break; + } + return rows; + }, + }); + + if (isPending) { + return ; + } + const { subjects, absences } = summarizeStudentReports(reports ?? [], lessonHeaders); + const cell = { py: 0.25, px: 0.75, borderBottom: 1, borderColor: 'divider', textAlign: 'start' }; + + return ( + + + פירוט לפי מקצוע + + + + {['מקצוע', 'שיעורים', 'חיסורים', 'אחוז'].map((label) => ( + {label} + ))} + + + + {subjects.map((subject) => ( + + {subject.name} + {subject.lessons} + {subject.abs} + {formatPercent(subject.ratio)} + + ))} + + + כולל חיסורים מאושרים + + + חיסורים אחרונים + {absences.length ? ( + + {absences.slice(0, 10).map((absence) => ( + + {formatDate(absence.date)} · {absence.subject}{absence.count > 1 ? ` (${absence.count})` : ''} + + ))} + + ) : ( + אין חיסורים בתקופה + )} + + + + + + + + ); +}; + +const StudentRow = ({ student, thresholdRatio, lessonHeaders, open, onToggle }) => ( + <> + { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + onToggle(); + } + }} + sx={{ + display: 'grid', + gridTemplateColumns: { xs: 'minmax(0, 1fr) minmax(0, 1.1fr)', sm: 'minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1.6fr)' }, + gap: 1.5, + alignItems: 'center', + px: 2, + py: 1, + borderTop: 1, + borderColor: 'divider', + cursor: 'pointer', + '&:hover': { bgcolor: 'action.hover' }, + '&:focus-visible': { outline: 2, outlineColor: 'primary.main', outlineStyle: 'solid' }, + }} + > + + {student.name} + + {student.unapproved} חיסורים מתוך {student.lessons} שיעורים{student.approved ? ` · ${student.approved} מאושרים` : ''} + + + + + + + + {open && } + +); + +const KlassCard = ({ group, thresholdRatio, lessonHeaders, openIds, onToggle }) => { + const topSubject = getTopSubject(group.all); + return ( + + + + {group.name} + + {group.all.length} תלמידות · ממוצע {formatPercent(group.ratio)} + {group.over > 0 && · {group.over} מעל הסף} + {group.near > 0 && · {group.near} קרובות} + + + {topSubject && ( + + הכי הרבה חיסורים בכיתה: {topSubject.name} – {topSubject.abs} חיסורים, {Math.round(topSubject.share * 100)}% מכל החיסורים בכיתה + + )} + + {group.students.map((student) => ( + onToggle(student.id)} + /> + ))} + + ); +}; + +const AbsenceTrackingView = () => { + const { filterValues } = useListContext(); + const { pages, isPending } = useAllPivotRows(); + const [thresholdInput, setThresholdInput] = useState(readStoredThreshold); + const [status, setStatus] = useState(''); + const [openIds, setOpenIds] = useState(() => new Set()); + + const parsedThreshold = Number(thresholdInput); + const thresholdPercent = parsedThreshold > 0 && parsedThreshold <= 100 ? parsedThreshold : DEFAULT_THRESHOLD_PERCENT; + const thresholdRatio = thresholdPercent / 100; + + const rows = useMemo(() => pages.flat(), [pages]); + const lessonHeaders = useMemo(() => getLessonHeaders(pages), [pages]); + const studentIds = useMemo(() => rows.map((row) => row.id), [rows]); + const baseKlassByStudent = useBaseKlasses(studentIds, filterValues?.year); + + const allStudents = rows.map((row) => getStudentStats(row, lessonHeaders, thresholdRatio)); + const students = allStudents.filter((s) => s.hasReports); + const groups = groupByKlass(students, baseKlassByStudent, NO_KLASS_LABEL) + .map((group) => ({ ...group, all: group.students, students: status ? group.students.filter((s) => s.status.key === status) : group.students })) + .filter((group) => group.students.length); + + const handleThresholdChange = (value) => { + setThresholdInput(value); + try { + if (Number(value) > 0 && Number(value) <= 100) localStorage.setItem(THRESHOLD_STORAGE_KEY, String(Number(value))); + } catch { + // Storage blocked: the threshold still works for this visit. + } + }; + const toggleOpen = (id) => + setOpenIds((current) => { + const next = new Set(current); + next.has(id) ? next.delete(id) : next.add(id); + return next; + }); + + return ( + + + + אחוז החיסור הוא חיסורים לא מאושרים מתוך כל השיעורים בתקופה. תלמידה שעברה את הסף מסומנת באדום, ותלמידה + שחסרים לה עד {NEAR_THRESHOLD_ABSENCES} חיסורים לסף מסומנת בכתום. לחיצה על תלמידה פותחת פירוט. + + + + {isPending ? ( + + ) : ( + <> + + {groups.length ? ( + + {groups.map((group) => ( + + ))} + + ) : ( + אין תלמידות שמתאימות לסינון. + )} + + )} + + ); +}; + +const AbsenceTrackingList = () => { + const isAdmin = useIsAdmin(); + const { permissions } = usePermissions(); + const filtersArr = filterArrayByParams(filters, { isAdmin, permissions }); + + return ( + } + sort={{ field: 'id', order: 'ASC' }} + configurable={false} + perPage={MAX_PAGE_SIZE} + pagination={false} + > + + + ); +}; + +export default AbsenceTrackingList; diff --git a/client/src/pivots/AbsenceTrackingList.test.jsx b/client/src/pivots/AbsenceTrackingList.test.jsx new file mode 100644 index 00000000..b31818cd --- /dev/null +++ b/client/src/pivots/AbsenceTrackingList.test.jsx @@ -0,0 +1,66 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { AdminContext } from 'react-admin'; +import AbsenceTrackingList from './AbsenceTrackingList'; + +const pivotRows = [ + { + id: 1, + name: 'שרה כהן', + tz: '1', + 11: 9, + 12: 1, + total: 10, + totalKnownAbsences: 0, + totalLessons: 40, + headers: [ + { value: '11', label: 'אנגלית' }, + { value: '12', label: 'תנ"ך' }, + { value: 'total', label: 'סה"כ' }, + ], + }, + { id: 2, name: 'רחל לוי', tz: '2', 11: 1, total: 1, totalKnownAbsences: 0, totalLessons: 40 }, + { id: 3, name: 'לאה בלי דיווח', tz: '3' }, +]; + +const dataProvider = { + getList: jest.fn((resource) => { + if (resource.startsWith('student_by_year/pivot')) { + return Promise.resolve({ data: pivotRows, total: pivotRows.length }); + } + if (resource === 'student_base_klass') { + return Promise.resolve({ data: [{ id: 1, klassName: 'א1' }, { id: 2, klassName: 'א1' }], total: 2 }); + } + if (resource === 'att_report') { + return Promise.resolve({ + data: [{ id: 7, lessonReferenceId: 11, howManyLessons: 2, absCount: 1, reportDate: '2026-10-05' }], + total: 1, + }); + } + return Promise.resolve({ data: [], total: 0 }); + }), + getOne: jest.fn(() => Promise.resolve({ data: { id: 1 } })), + getMany: jest.fn(() => Promise.resolve({ data: [] })), + getManyReference: jest.fn(() => Promise.resolve({ data: [], total: 0 })), +}; + +test('shows class cards, threshold status and the student drill-down', async () => { + render( + + + , + ); + + expect(await screen.findByText('שרה כהן')).toBeInTheDocument(); + expect(await screen.findByText('א1')).toBeInTheDocument(); + // 10 of 40 = 25%, over the default 20% threshold by 2 absences. + expect(screen.getByText('2 מעל הסף')).toBeInTheDocument(); + expect(screen.getByText('ועוד 1 בלי דיווחים בתקופה')).toBeInTheDocument(); + expect(screen.queryByText('לאה בלי דיווח')).not.toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('סף חיסורים (%)'), { target: { value: '30' } }); + expect(screen.getByText('עוד 2 חיסורים לסף')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('שרה כהן')); + expect(await screen.findByText('פירוט לפי מקצוע')).toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('50.0%')).toBeInTheDocument()); +}); diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index 3d8390f7..1c6576b4 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -32,6 +32,7 @@ export default [ { html: 'ניקוי אוטומטי של נוכחות שיעור נבחר, לפי כיתה/מסלול לשמירה, בכל מוצאי שבת', status: 'בוצע', statusColor: 'success' }, { html: 'עיצוב חדש לדוח המורות שדיווחו: כרטיס לכל כיתה עם שורה לכל שיעור, צביעת מספר החסרות וריבועי סיכום', status: 'בוצע', statusColor: 'success' }, { html: 'דוח המורות שדיווחו: לחיצה על מספר החסרות מציגה את שמות הבנות שחסרו', status: 'בוצע', statusColor: 'success' }, + { html: 'דוח חדש "מעקב חיסורים": כרטיס לכל כיתה, סף חיסורים לבחירה, כמה חיסורים נשארו לכל תלמידה עד הסף ופירוט בלחיצה', status: 'בוצע', statusColor: 'success' }, // { html: 'הגדרת תקופת זמן לפי תאריכים', status: 'בקרוב', statusColor: 'warning' }, // { html: 'הגדרת תקופת זמן לפי יום בשבוע', status: 'בוצע', statusColor: 'success' }, diff --git a/client/src/utils/absenceTracking.js b/client/src/utils/absenceTracking.js new file mode 100644 index 00000000..16ce4752 --- /dev/null +++ b/client/src/utils/absenceTracking.js @@ -0,0 +1,140 @@ +// Pure helpers for the absence tracking page (src/pivots/AbsenceTrackingList.jsx). +// The page reads the existing StudentAttendance pivot; these turn its rows into per-student stats. + +// A student this many unapproved absences (or fewer) away from the threshold counts as "near". +export const NEAR_THRESHOLD_ABSENCES = 3; + +export const DEFAULT_THRESHOLD_PERCENT = 20; + +const PIVOT_SUMMARY_KEYS = new Set([ + 'total', + 'totalKnownAbsences', + 'unApprovedAbsences', + 'totalLessons', + 'absencePercentage', + 'totalAbsencePercentage', +]); + +// Every page of the pivot carries its own headers on its first row; merge them into one lesson map. +export function getLessonHeaders(pages) { + const lessons = new Map(); + pages.forEach((rows) => { + (rows?.[0]?.headers ?? []).forEach((header) => { + if (!PIVOT_SUMMARY_KEYS.has(header.value) && !lessons.has(header.value)) { + const label = header.label && header.label !== 'undefined' ? header.label : 'ללא שיעור'; + lessons.set(header.value, label); + } + }); + }); + return lessons; +} + +// How many more unapproved absences before reaching the threshold; 0 or less means at/over it. +export function getThresholdStatus(unapproved, lessons, thresholdRatio) { + const allowed = Math.ceil(thresholdRatio * lessons - 1e-9); + const left = allowed - unapproved; + if (left <= 0) return { key: 'over', left }; + if (left <= NEAR_THRESHOLD_ABSENCES) return { key: 'near', left }; + return { key: 'ok', left }; +} + +export function getStudentStats(row, lessonHeaders, thresholdRatio) { + const lessons = Number(row.totalLessons) || 0; + const abs = Number(row.total) || 0; + const approved = Number(row.totalKnownAbsences) || 0; + const unapproved = Math.max(0, abs - approved); + const subjects = [...lessonHeaders.entries()] + .map(([key, name]) => ({ key, name, abs: Number(row[key]) || 0 })) + .filter((subject) => subject.abs > 0) + .sort((a, b) => b.abs - a.abs); + return { + id: row.id, + name: row.name, + tz: row.tz, + hasReports: lessons > 0, + lessons, + abs, + approved, + unapproved, + ratio: lessons ? unapproved / lessons : 0, + subjects, + status: lessons ? getThresholdStatus(unapproved, lessons, thresholdRatio) : { key: 'ok', left: 0 }, + }; +} + +const STATUS_ORDER = { over: 0, near: 1, ok: 2 }; + +// One group per base class, worst class first; students inside sorted by absence ratio, worst first. +export function groupByKlass(students, baseKlassByStudent, noKlassLabel) { + const groups = new Map(); + students.forEach((student) => { + const name = baseKlassByStudent[student.id] || noKlassLabel; + if (!groups.has(name)) groups.set(name, { name, students: [] }); + groups.get(name).students.push(student); + }); + const result = [...groups.values()].map((group) => { + group.students.sort((a, b) => b.ratio - a.ratio || STATUS_ORDER[a.status.key] - STATUS_ORDER[b.status.key]); + group.over = group.students.filter((s) => s.status.key === 'over').length; + group.near = group.students.filter((s) => s.status.key === 'near').length; + group.lessons = group.students.reduce((sum, s) => sum + s.lessons, 0); + group.unapproved = group.students.reduce((sum, s) => sum + s.unapproved, 0); + group.ratio = group.lessons ? group.unapproved / group.lessons : 0; + return group; + }); + return result.sort((a, b) => { + if (a.name === noKlassLabel) return 1; + if (b.name === noKlassLabel) return -1; + return b.over - a.over || b.near - a.near || a.name.localeCompare(b.name, 'he'); + }); +} + +// The subject behind an unusually large share of the class's absences, if there is one. +export function getTopSubject(students, minShare = 0.25, minAbsences = 5) { + const bySubject = new Map(); + let total = 0; + students.forEach((student) => + student.subjects.forEach((subject) => { + bySubject.set(subject.name, (bySubject.get(subject.name) ?? 0) + subject.abs); + total += subject.abs; + }), + ); + if (bySubject.size < 2 || !total) return null; + const [name, abs] = [...bySubject.entries()].sort((a, b) => b[1] - a[1])[0]; + const share = abs / total; + return abs >= minAbsences && share >= minShare ? { name, abs, share } : null; +} + +// Per-subject lessons/absences and the list of absence dates, from one student's att_report rows. +export function summarizeStudentReports(reports, lessonHeaders) { + const bySubject = new Map(); + const absences = []; + reports.forEach((report) => { + const key = String(report.lessonReferenceId); + const name = lessonHeaders.get(key) ?? 'ללא שיעור'; + if (!bySubject.has(key)) bySubject.set(key, { key, name, lessons: 0, abs: 0 }); + const subject = bySubject.get(key); + subject.lessons += Number(report.howManyLessons) || 0; + subject.abs += Number(report.absCount) || 0; + if (Number(report.absCount) > 0) { + absences.push({ id: report.id, date: report.reportDate, subject: name, count: Number(report.absCount) }); + } + }); + const subjects = [...bySubject.values()] + .map((subject) => ({ ...subject, ratio: subject.lessons ? subject.abs / subject.lessons : 0 })) + .sort((a, b) => b.ratio - a.ratio); + absences.sort((a, b) => String(b.date).localeCompare(String(a.date))); + return { subjects, absences }; +} + +// Date range for the drill-down: the report's own dates, narrowed by the chosen report month. +export function getDetailDateRange(extra = {}, reportMonth) { + const pickLater = (a, b) => (!a ? b : !b ? a : a > b ? a : b); + const pickEarlier = (a, b) => (!a ? b : !b ? a : a < b ? a : b); + const toDay = (value) => (value ? String(value).slice(0, 10) : undefined); + return { + from: pickLater(toDay(extra.fromDate), toDay(reportMonth?.startDate)), + to: pickEarlier(toDay(extra.toDate), toDay(reportMonth?.endDate)), + }; +} + +export const formatPercent = (ratio) => `${(ratio * 100).toFixed(1)}%`; diff --git a/client/src/utils/absenceTracking.test.js b/client/src/utils/absenceTracking.test.js new file mode 100644 index 00000000..d995264b --- /dev/null +++ b/client/src/utils/absenceTracking.test.js @@ -0,0 +1,119 @@ +import { + getDetailDateRange, + getLessonHeaders, + getStudentStats, + getThresholdStatus, + getTopSubject, + groupByKlass, + summarizeStudentReports, +} from './absenceTracking'; + +const headers = [ + { value: '11', label: 'אנגלית' }, + { value: 'null', label: 'undefined' }, + { value: 'total', label: 'סה"כ' }, + { value: 'totalLessons', label: 'סה"כ שיעורים' }, +]; + +describe('getLessonHeaders', () => { + it('merges lesson headers from every page and skips summary columns', () => { + const pages = [[{ headers }], [{ headers: [{ value: '12', label: 'מתמטיקה' }] }], []]; + const lessons = getLessonHeaders(pages); + expect([...lessons.entries()]).toEqual([ + ['11', 'אנגלית'], + ['null', 'ללא שיעור'], + ['12', 'מתמטיקה'], + ]); + }); +}); + +describe('getThresholdStatus', () => { + it('counts absences left until the threshold', () => { + expect(getThresholdStatus(2, 50, 0.2)).toEqual({ key: 'ok', left: 8 }); + expect(getThresholdStatus(7, 50, 0.2)).toEqual({ key: 'near', left: 3 }); + expect(getThresholdStatus(10, 50, 0.2)).toEqual({ key: 'over', left: 0 }); + expect(getThresholdStatus(12, 50, 0.2)).toEqual({ key: 'over', left: -2 }); + }); + + it('is not thrown off by floating point', () => { + // 0.2 * 35 = 7.000000000000001 + expect(getThresholdStatus(7, 35, 0.2).key).toBe('over'); + }); +}); + +describe('getStudentStats', () => { + const lessons = getLessonHeaders([[{ headers }]]); + + it('uses unapproved absences for the ratio and lists subjects with absences', () => { + const stats = getStudentStats( + { id: 1, name: 'שרה', 11: 4, null: 0, total: 6, totalKnownAbsences: 2, totalLessons: 40 }, + lessons, + 0.2, + ); + expect(stats).toMatchObject({ unapproved: 4, approved: 2, lessons: 40, ratio: 0.1, hasReports: true }); + expect(stats.subjects).toEqual([{ key: '11', name: 'אנגלית', abs: 4 }]); + expect(stats.status).toEqual({ key: 'ok', left: 4 }); + }); + + it('marks students without reports', () => { + expect(getStudentStats({ id: 2, name: 'רחל' }, lessons, 0.2).hasReports).toBe(false); + }); +}); + +describe('groupByKlass', () => { + const student = (id, ratio, key) => ({ id, ratio, lessons: 10, unapproved: ratio * 10, status: { key } }); + + it('puts the class with most students over the threshold first and the no-class group last', () => { + const groups = groupByKlass( + [student(1, 0.1, 'ok'), student(2, 0.3, 'over'), student(3, 0.05, 'ok'), student(4, 0.5, 'over')], + { 1: 'א1', 2: 'ב1', 4: 'ב1' }, + 'ללא', + ); + expect(groups.map((g) => g.name)).toEqual(['ב1', 'א1', 'ללא']); + expect(groups[0].students.map((s) => s.id)).toEqual([4, 2]); + expect(groups[0].over).toBe(2); + }); +}); + +describe('getTopSubject', () => { + it('returns the subject behind a large share of absences', () => { + const students = [ + { subjects: [{ name: 'אנגלית', abs: 6 }, { name: 'תנ"ך', abs: 1 }] }, + { subjects: [{ name: 'אנגלית', abs: 3 }, { name: 'תנ"ך', abs: 2 }] }, + ]; + expect(getTopSubject(students)).toEqual({ name: 'אנגלית', abs: 9, share: 0.75 }); + }); + + it('returns nothing for a single subject or too few absences', () => { + expect(getTopSubject([{ subjects: [{ name: 'אנגלית', abs: 9 }] }])).toBeNull(); + expect(getTopSubject([{ subjects: [{ name: 'אנגלית', abs: 2 }, { name: 'תנ"ך', abs: 1 }] }])).toBeNull(); + }); +}); + +describe('summarizeStudentReports', () => { + it('sums lessons and absences per subject and lists absence dates newest first', () => { + const lessons = new Map([['11', 'אנגלית']]); + const { subjects, absences } = summarizeStudentReports( + [ + { id: 1, lessonReferenceId: 11, howManyLessons: 2, absCount: 1, reportDate: '2026-10-01' }, + { id: 2, lessonReferenceId: 11, howManyLessons: 2, absCount: 0, reportDate: '2026-10-03' }, + { id: 3, lessonReferenceId: 11, howManyLessons: 1, absCount: 1, reportDate: '2026-10-05' }, + ], + lessons, + ); + expect(subjects).toEqual([{ key: '11', name: 'אנגלית', lessons: 5, abs: 2, ratio: 0.4 }]); + expect(absences.map((a) => a.id)).toEqual([3, 1]); + }); +}); + +describe('getDetailDateRange', () => { + it('narrows the report dates by the report month', () => { + expect( + getDetailDateRange( + { fromDate: '2026-10-10' }, + { startDate: '2026-10-01T00:00:00.000Z', endDate: '2026-10-31T00:00:00.000Z' }, + ), + ).toEqual({ from: '2026-10-10', to: '2026-10-31' }); + expect(getDetailDateRange({}, undefined)).toEqual({ from: undefined, to: undefined }); + }); +}); From 12f561c63e48cb945c11c23f5b44f1a47efbf483 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 7 Oct 2026 20:05:48 +0000 Subject: [PATCH 2/3] Absence tracking: top subject by absence rate, progressive loading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - StudentAttendance pivot also sends lessons per subject (lessons_), with no header, so the existing pivot table and export are unchanged. - The class insight now picks the subject with the highest absence rate against the class's overall rate, instead of the most absences. - Pages load in parallel and show as they arrive with a progress bar; each page shows only with its base classes, so students never flash under "no class". Page 1's classes load before the other pages start. - Clickable tiles use CardActionArea; row text says "לא מאושרים". Verified in a browser against a local server with 600 students / 32k reports: class grouping, threshold counts (match SQL), and drill-down totals matching the row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T5Hdg7cKavdUKRf9T4FPnP --- client/src/pivots/AbsenceTrackingList.jsx | 141 +++++++++--------- client/src/utils/absenceTracking.js | 40 +++-- client/src/utils/absenceTracking.test.js | 28 ++-- .../__tests__/student-by-year.config.spec.ts | 4 + .../entity-modules/student-by-year.config.ts | 3 + 5 files changed, 122 insertions(+), 94 deletions(-) diff --git a/client/src/pivots/AbsenceTrackingList.jsx b/client/src/pivots/AbsenceTrackingList.jsx index 3e37975d..004e3877 100644 --- a/client/src/pivots/AbsenceTrackingList.jsx +++ b/client/src/pivots/AbsenceTrackingList.jsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useState } from 'react'; import { DateInput, NullableBooleanInput, @@ -9,8 +9,8 @@ import { useListContext, usePermissions, } from 'react-admin'; -import { useQuery } from '@tanstack/react-query'; -import { Box, ButtonBase, Card, CircularProgress, TextField as MuiTextField, Typography } from '@mui/material'; +import { useQueries, useQuery } from '@tanstack/react-query'; +import { Box, Card, CardActionArea, CircularProgress, LinearProgress, TextField as MuiTextField, Typography } from '@mui/material'; import { CommonList } from '@shared/components/crudContainers/CommonList'; import { EmptyPage } from '@shared/components/crudContainers/EmptyPage'; import { @@ -102,56 +102,54 @@ const readStoredThreshold = () => { } }; -const chunk = (items, size) => { - const chunks = []; - for (let i = 0; i < items.length; i += size) chunks.push(items.slice(i, i + size)); - return chunks; -}; +const fetchBaseKlasses = (dataProvider, rows, year) => + dataProvider + .getList('student_base_klass', { + pagination: { page: 1, perPage: MAX_PAGE_SIZE }, + sort: { field: 'id', order: 'ASC' }, + filter: { id: rows.map((row) => row.id), ...(year && { year }) }, + }) + .then((result) => result.data); -// The list context holds page 1 (the data provider caps a page at MAX_PAGE_SIZE); fetch the rest. -const useAllPivotRows = () => { +// The list context holds page 1 (the data provider caps a page at MAX_PAGE_SIZE). Its base classes load first, +// then the other pages load in parallel, each with its base classes, and show as soon as they arrive. +// A page is shown only with its base classes, so students never flash under "no class". +const usePivotPages = () => { const dataProvider = useDataProvider(); const { data, total, filterValues, sort, isPending } = useListContext(); const pageCount = Math.ceil((total ?? 0) / MAX_PAGE_SIZE); - const { data: restPages, isPending: restPending } = useQuery({ - queryKey: [RESOURCE, 'absence-tracking-pages', filterValues, sort, pageCount], - enabled: !isPending && pageCount > 1, - queryFn: () => - Promise.all( - Array.from({ length: pageCount - 1 }, (_, i) => - dataProvider - .getList(RESOURCE, { - pagination: { page: i + 2, perPage: MAX_PAGE_SIZE }, - sort, - filter: filterValues, - }) - .then((result) => result.data), - ), - ), + const year = filterValues?.year; + const firstKlasses = useQuery({ + queryKey: ['student_base_klass', 'absence-tracking', year, (data ?? []).map((row) => row.id)], + enabled: !isPending && !!data?.length, + queryFn: () => fetchBaseKlasses(dataProvider, data, year), }); - const pages = useMemo(() => [data ?? [], ...(restPages ?? [])], [data, restPages]); - return { pages, isPending: isPending || (pageCount > 1 && restPending) }; -}; - -const useBaseKlasses = (studentIds, year) => { - const dataProvider = useDataProvider(); - const { data } = useQuery({ - queryKey: ['student_base_klass', 'absence-tracking', studentIds, year], - enabled: studentIds.length > 0, - queryFn: () => - Promise.all( - chunk(studentIds, MAX_PAGE_SIZE).map((ids) => - dataProvider - .getList('student_base_klass', { - pagination: { page: 1, perPage: MAX_PAGE_SIZE }, - sort: { field: 'id', order: 'ASC' }, - filter: { id: ids, ...(year && { year }) }, - }) - .then((result) => result.data), - ), - ).then((results) => Object.fromEntries(results.flat().map((row) => [row.id, row.klassName]))), + const rest = useQueries({ + queries: Array.from({ length: Math.max(0, pageCount - 1) }, (_, i) => ({ + queryKey: [RESOURCE, 'absence-tracking-page', filterValues, sort, i + 2], + enabled: !isPending && !firstKlasses.isPending, + queryFn: async () => { + const { data: rows } = await dataProvider.getList(RESOURCE, { + pagination: { page: i + 2, perPage: MAX_PAGE_SIZE }, + sort, + filter: filterValues, + }); + return { rows, klasses: await fetchBaseKlasses(dataProvider, rows, year) }; + }, + })), + combine: (results) => ({ + pages: results.map((query) => query.data).filter(Boolean), + isLoadingMore: results.some((query) => query.isPending), + }), }); - return data ?? {}; + const firstPage = data?.length && !firstKlasses.isPending ? [{ rows: data, klasses: firstKlasses.data ?? [] }] : []; + const pages = [...firstPage, ...rest.pages]; + return { + pages, + total: total ?? 0, + isPending: isPending || (!!data?.length && firstKlasses.isPending), + isLoadingMore: rest.isLoadingMore, + }; }; const ThresholdInput = ({ value, onChange }) => ( @@ -198,25 +196,23 @@ const SummaryTiles = ({ students, noReportsCount, thresholdPercent, status, onSt onStatusChange(status === tile.key ? '' : tile.key) : undefined} - aria-pressed={clickable ? selected : undefined} sx={{ - px: 2.5, - py: 1.5, borderRadius: 3, - display: 'flex', - flexDirection: 'column', - alignItems: 'flex-start', - textAlign: 'start', ...(selected && { borderColor: 'primary.main', boxShadow: (theme) => `inset 0 0 0 1px ${theme.palette.primary.main}` }), }} > - {tile.label} - - {tile.value} - - {tile.hint} + onStatusChange(status === tile.key ? '' : tile.key) : undefined} + aria-pressed={clickable ? selected : undefined} + sx={{ px: 2.5, py: 1.5, height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'flex-start', textAlign: 'start' }} + > + {tile.label} + + {tile.value} + + {tile.hint} + ); })} @@ -399,7 +395,7 @@ const StudentRow = ({ student, thresholdRatio, lessonHeaders, open, onToggle }) {student.name} - {student.unapproved} חיסורים מתוך {student.lessons} שיעורים{student.approved ? ` · ${student.approved} מאושרים` : ''} + {student.unapproved} לא מאושרים מתוך {student.lessons} שיעורים{student.approved ? ` · ${student.approved} מאושרים` : ''} @@ -426,7 +422,8 @@ const KlassCard = ({ group, thresholdRatio, lessonHeaders, openIds, onToggle }) {topSubject && ( - הכי הרבה חיסורים בכיתה: {topSubject.name} – {topSubject.abs} חיסורים, {Math.round(topSubject.share * 100)}% מכל החיסורים בכיתה + אחוז החיסור הגבוה בכיתה: {topSubject.name} – {formatPercent(topSubject.rate)}, פי{' '} + {topSubject.times.toFixed(1)} מאחוז החיסור הכללי בכיתה ({formatPercent(topSubject.classRate)}) )} @@ -445,8 +442,7 @@ const KlassCard = ({ group, thresholdRatio, lessonHeaders, openIds, onToggle }) }; const AbsenceTrackingView = () => { - const { filterValues } = useListContext(); - const { pages, isPending } = useAllPivotRows(); + const { pages, total, isPending, isLoadingMore } = usePivotPages(); const [thresholdInput, setThresholdInput] = useState(readStoredThreshold); const [status, setStatus] = useState(''); const [openIds, setOpenIds] = useState(() => new Set()); @@ -455,10 +451,9 @@ const AbsenceTrackingView = () => { const thresholdPercent = parsedThreshold > 0 && parsedThreshold <= 100 ? parsedThreshold : DEFAULT_THRESHOLD_PERCENT; const thresholdRatio = thresholdPercent / 100; - const rows = useMemo(() => pages.flat(), [pages]); - const lessonHeaders = useMemo(() => getLessonHeaders(pages), [pages]); - const studentIds = useMemo(() => rows.map((row) => row.id), [rows]); - const baseKlassByStudent = useBaseKlasses(studentIds, filterValues?.year); + const rows = pages.flatMap((page) => page.rows); + const lessonHeaders = getLessonHeaders(pages.map((page) => page.rows)); + const baseKlassByStudent = Object.fromEntries(pages.flatMap((page) => page.klasses).map((row) => [row.id, row.klassName])); const allStudents = rows.map((row) => getStudentStats(row, lessonHeaders, thresholdRatio)); const students = allStudents.filter((s) => s.hasReports); @@ -494,6 +489,14 @@ const AbsenceTrackingView = () => { ) : ( <> + {isLoadingMore && ( + + + נטענו {rows.length} מתוך {total} תלמידות… + + + + )} ({ key, name, abs: Number(row[key]) || 0 })) - .filter((subject) => subject.abs > 0) - .sort((a, b) => b.abs - a.abs); + // `lessons_` is sent by the pivot without a header, next to the lesson's absence count. + const subjectTotals = [...lessonHeaders.entries()] + .map(([key, name]) => ({ key, name, abs: Number(row[key]) || 0, lessons: Number(row[`lessons_${key}`]) || 0 })) + .filter((subject) => subject.lessons > 0 || subject.abs > 0); + const subjects = subjectTotals.filter((subject) => subject.abs > 0).sort((a, b) => b.abs - a.abs); return { id: row.id, name: row.name, @@ -58,6 +59,7 @@ export function getStudentStats(row, lessonHeaders, thresholdRatio) { unapproved, ratio: lessons ? unapproved / lessons : 0, subjects, + subjectTotals, status: lessons ? getThresholdStatus(unapproved, lessons, thresholdRatio) : { key: 'ok', left: 0 }, }; } @@ -88,20 +90,30 @@ export function groupByKlass(students, baseKlassByStudent, noKlassLabel) { }); } -// The subject behind an unusually large share of the class's absences, if there is one. -export function getTopSubject(students, minShare = 0.25, minAbsences = 5) { +// The subject whose absence rate in the class stands out against the class's rate over all subjects. +// Rates include approved absences, like the per-subject counts the pivot sends. +export function getTopSubject(students, { minRatio = 1.5, minLessons = 10, minAbsences = 5 } = {}) { const bySubject = new Map(); - let total = 0; + let totalLessons = 0; + let totalAbs = 0; students.forEach((student) => - student.subjects.forEach((subject) => { - bySubject.set(subject.name, (bySubject.get(subject.name) ?? 0) + subject.abs); - total += subject.abs; + student.subjectTotals.forEach((subject) => { + const current = bySubject.get(subject.name) ?? { name: subject.name, abs: 0, lessons: 0 }; + current.abs += subject.abs; + current.lessons += subject.lessons; + bySubject.set(subject.name, current); + totalLessons += subject.lessons; + totalAbs += subject.abs; }), ); - if (bySubject.size < 2 || !total) return null; - const [name, abs] = [...bySubject.entries()].sort((a, b) => b[1] - a[1])[0]; - const share = abs / total; - return abs >= minAbsences && share >= minShare ? { name, abs, share } : null; + if (bySubject.size < 2 || !totalLessons || !totalAbs) return null; + const classRate = totalAbs / totalLessons; + const top = [...bySubject.values()] + .filter((subject) => subject.lessons >= minLessons) + .map((subject) => ({ ...subject, rate: subject.abs / subject.lessons })) + .sort((a, b) => b.rate - a.rate)[0]; + if (!top || top.abs < minAbsences || top.rate < classRate * minRatio) return null; + return { ...top, classRate, times: top.rate / classRate }; } // Per-subject lessons/absences and the list of absence dates, from one student's att_report rows. diff --git a/client/src/utils/absenceTracking.test.js b/client/src/utils/absenceTracking.test.js index d995264b..fcaf297f 100644 --- a/client/src/utils/absenceTracking.test.js +++ b/client/src/utils/absenceTracking.test.js @@ -46,12 +46,13 @@ describe('getStudentStats', () => { it('uses unapproved absences for the ratio and lists subjects with absences', () => { const stats = getStudentStats( - { id: 1, name: 'שרה', 11: 4, null: 0, total: 6, totalKnownAbsences: 2, totalLessons: 40 }, + { id: 1, name: 'שרה', 11: 4, lessons_11: 30, null: 0, lessons_null: 10, total: 6, totalKnownAbsences: 2, totalLessons: 40 }, lessons, 0.2, ); expect(stats).toMatchObject({ unapproved: 4, approved: 2, lessons: 40, ratio: 0.1, hasReports: true }); - expect(stats.subjects).toEqual([{ key: '11', name: 'אנגלית', abs: 4 }]); + expect(stats.subjects).toEqual([{ key: '11', name: 'אנגלית', abs: 4, lessons: 30 }]); + expect(stats.subjectTotals).toHaveLength(2); expect(stats.status).toEqual({ key: 'ok', left: 4 }); }); @@ -76,17 +77,22 @@ describe('groupByKlass', () => { }); describe('getTopSubject', () => { - it('returns the subject behind a large share of absences', () => { - const students = [ - { subjects: [{ name: 'אנגלית', abs: 6 }, { name: 'תנ"ך', abs: 1 }] }, - { subjects: [{ name: 'אנגלית', abs: 3 }, { name: 'תנ"ך', abs: 2 }] }, - ]; - expect(getTopSubject(students)).toEqual({ name: 'אנגלית', abs: 9, share: 0.75 }); + const st = (...subjects) => ({ subjectTotals: subjects.map(([name, abs, lessons]) => ({ name, abs, lessons })) }); + + it('picks the subject by absence rate, not by count', () => { + // תנ"ך has more absences (8) but over many lessons; אנגלית has the higher rate. + const students = [st(['אנגלית', 3, 10], ['תנ"ך', 4, 60]), st(['אנגלית', 3, 10], ['תנ"ך', 4, 60])]; + const top = getTopSubject(students); + expect(top).toMatchObject({ name: 'אנגלית', abs: 6, lessons: 20, rate: 0.3 }); + expect(top.classRate).toBeCloseTo(14 / 140); + expect(top.times).toBeCloseTo(3); }); - it('returns nothing for a single subject or too few absences', () => { - expect(getTopSubject([{ subjects: [{ name: 'אנגלית', abs: 9 }] }])).toBeNull(); - expect(getTopSubject([{ subjects: [{ name: 'אנגלית', abs: 2 }, { name: 'תנ"ך', abs: 1 }] }])).toBeNull(); + it('returns nothing when no subject stands out, or for too few lessons/absences', () => { + expect(getTopSubject([st(['אנגלית', 5, 50], ['תנ"ך', 5, 50])])).toBeNull(); + expect(getTopSubject([st(['אנגלית', 5, 8], ['תנ"ך', 1, 100])])).toBeNull(); + expect(getTopSubject([st(['אנגלית', 4, 20], ['תנ"ך', 0, 100])])).toBeNull(); + expect(getTopSubject([st(['אנגלית', 9, 20])])).toBeNull(); }); }); diff --git a/server/src/entity-modules/__tests__/student-by-year.config.spec.ts b/server/src/entity-modules/__tests__/student-by-year.config.spec.ts index e5a59781..6c4c3186 100644 --- a/server/src/entity-modules/__tests__/student-by-year.config.spec.ts +++ b/server/src/entity-modules/__tests__/student-by-year.config.spec.ts @@ -189,6 +189,10 @@ describe('StudentByYear Config', () => { value: '101', label: 'Math', }); + + // Lessons per subject are sent without a header, so the pivot table gets no extra column + expect((mockStudents[0] as any).lessons_101).toBe(10); + expect(mockStudents[0].headers.map((h) => h.value)).not.toContain('lessons_101'); }); it('should round StudentAttendanceByKlass numeric results', async () => { diff --git a/server/src/entity-modules/student-by-year.config.ts b/server/src/entity-modules/student-by-year.config.ts index d3f53c0f..193a9c4b 100644 --- a/server/src/entity-modules/student-by-year.config.ts +++ b/server/src/entity-modules/student-by-year.config.ts @@ -101,6 +101,9 @@ class StudentByYearService extends BaseEntityS headers[key] ??= { value: key, label: `${item.lesson?.name}` }; studentMap[item.studentReferenceId][key] ??= 0; studentMap[item.studentReferenceId][key] += item.absCount; + // Lessons per subject, without a header: not a column of this pivot, read by the absence tracking page. + studentMap[item.studentReferenceId][`lessons_${key}`] ??= 0; + studentMap[item.studentReferenceId][`lessons_${key}`] += item.howManyLessons; studentMap[item.studentReferenceId].total ??= 0; studentMap[item.studentReferenceId].total += item.absCount; studentMap[item.studentReferenceId].totalLessons ??= 0; From 35dd7d8d3b426b1f84c1ff7054f88d88c34c3f7a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 7 Oct 2026 21:53:41 +0000 Subject: [PATCH 3/3] Absence tracking: load one page like the pivot, with pagination Loading the whole school (1,050 students, 11 pivot pages) took ~26s, so the page now loads only the current page (100 students by default) with the usual pagination, like the existing pivot table. When there are more students than shown, a note says the summary covers the shown students only and suggests choosing a class. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T5Hdg7cKavdUKRf9T4FPnP --- client/src/pivots/AbsenceTrackingList.jsx | 62 +++++++---------------- 1 file changed, 18 insertions(+), 44 deletions(-) diff --git a/client/src/pivots/AbsenceTrackingList.jsx b/client/src/pivots/AbsenceTrackingList.jsx index 004e3877..faa93f05 100644 --- a/client/src/pivots/AbsenceTrackingList.jsx +++ b/client/src/pivots/AbsenceTrackingList.jsx @@ -9,8 +9,8 @@ import { useListContext, usePermissions, } from 'react-admin'; -import { useQueries, useQuery } from '@tanstack/react-query'; -import { Box, Card, CardActionArea, CircularProgress, LinearProgress, TextField as MuiTextField, Typography } from '@mui/material'; +import { useQuery } from '@tanstack/react-query'; +import { Box, Card, CardActionArea, CircularProgress, TextField as MuiTextField, Typography } from '@mui/material'; import { CommonList } from '@shared/components/crudContainers/CommonList'; import { EmptyPage } from '@shared/components/crudContainers/EmptyPage'; import { @@ -111,44 +111,22 @@ const fetchBaseKlasses = (dataProvider, rows, year) => }) .then((result) => result.data); -// The list context holds page 1 (the data provider caps a page at MAX_PAGE_SIZE). Its base classes load first, -// then the other pages load in parallel, each with its base classes, and show as soon as they arrive. -// A page is shown only with its base classes, so students never flash under "no class". -const usePivotPages = () => { +// Like the pivot table, this shows one page of students (the list context's current page), plus their base classes. +// The page is shown only with its base classes, so students never flash under "no class". +const usePivotPage = () => { const dataProvider = useDataProvider(); - const { data, total, filterValues, sort, isPending } = useListContext(); - const pageCount = Math.ceil((total ?? 0) / MAX_PAGE_SIZE); + const { data, total, filterValues, isPending } = useListContext(); const year = filterValues?.year; - const firstKlasses = useQuery({ + const klasses = useQuery({ queryKey: ['student_base_klass', 'absence-tracking', year, (data ?? []).map((row) => row.id)], enabled: !isPending && !!data?.length, queryFn: () => fetchBaseKlasses(dataProvider, data, year), }); - const rest = useQueries({ - queries: Array.from({ length: Math.max(0, pageCount - 1) }, (_, i) => ({ - queryKey: [RESOURCE, 'absence-tracking-page', filterValues, sort, i + 2], - enabled: !isPending && !firstKlasses.isPending, - queryFn: async () => { - const { data: rows } = await dataProvider.getList(RESOURCE, { - pagination: { page: i + 2, perPage: MAX_PAGE_SIZE }, - sort, - filter: filterValues, - }); - return { rows, klasses: await fetchBaseKlasses(dataProvider, rows, year) }; - }, - })), - combine: (results) => ({ - pages: results.map((query) => query.data).filter(Boolean), - isLoadingMore: results.some((query) => query.isPending), - }), - }); - const firstPage = data?.length && !firstKlasses.isPending ? [{ rows: data, klasses: firstKlasses.data ?? [] }] : []; - const pages = [...firstPage, ...rest.pages]; return { - pages, + rows: data ?? [], + klasses: klasses.data ?? [], total: total ?? 0, - isPending: isPending || (!!data?.length && firstKlasses.isPending), - isLoadingMore: rest.isLoadingMore, + isPending: isPending || (!!data?.length && klasses.isPending), }; }; @@ -442,7 +420,7 @@ const KlassCard = ({ group, thresholdRatio, lessonHeaders, openIds, onToggle }) }; const AbsenceTrackingView = () => { - const { pages, total, isPending, isLoadingMore } = usePivotPages(); + const { rows, klasses, total, isPending } = usePivotPage(); const [thresholdInput, setThresholdInput] = useState(readStoredThreshold); const [status, setStatus] = useState(''); const [openIds, setOpenIds] = useState(() => new Set()); @@ -451,9 +429,8 @@ const AbsenceTrackingView = () => { const thresholdPercent = parsedThreshold > 0 && parsedThreshold <= 100 ? parsedThreshold : DEFAULT_THRESHOLD_PERCENT; const thresholdRatio = thresholdPercent / 100; - const rows = pages.flatMap((page) => page.rows); - const lessonHeaders = getLessonHeaders(pages.map((page) => page.rows)); - const baseKlassByStudent = Object.fromEntries(pages.flatMap((page) => page.klasses).map((row) => [row.id, row.klassName])); + const lessonHeaders = getLessonHeaders([rows]); + const baseKlassByStudent = Object.fromEntries(klasses.map((row) => [row.id, row.klassName])); const allStudents = rows.map((row) => getStudentStats(row, lessonHeaders, thresholdRatio)); const students = allStudents.filter((s) => s.hasReports); @@ -489,13 +466,11 @@ const AbsenceTrackingView = () => { ) : ( <> - {isLoadingMore && ( - - - נטענו {rows.length} מתוך {total} תלמידות… - - - + {total > rows.length && ( + + מוצגות {rows.length} מתוך {total} תלמידות, והסיכום מתייחס אליהן בלבד. לדוח של כיתה שלמה בחרי כיתה + במסנן. + )} { sort={{ field: 'id', order: 'ASC' }} configurable={false} perPage={MAX_PAGE_SIZE} - pagination={false} >