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..faa93f05 --- /dev/null +++ b/client/src/pivots/AbsenceTrackingList.jsx @@ -0,0 +1,527 @@ +import { useState } from 'react'; +import { + DateInput, + NullableBooleanInput, + RecordContextProvider, + TextInput, + useDataProvider, + useGetOne, + useListContext, + usePermissions, +} from 'react-admin'; +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 { + 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 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); + +// 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, isPending } = useListContext(); + const year = filterValues?.year; + const klasses = useQuery({ + queryKey: ['student_base_klass', 'absence-tracking', year, (data ?? []).map((row) => row.id)], + enabled: !isPending && !!data?.length, + queryFn: () => fetchBaseKlasses(dataProvider, data, year), + }); + return { + rows: data ?? [], + klasses: klasses.data ?? [], + total: total ?? 0, + isPending: isPending || (!!data?.length && klasses.isPending), + }; +}; + +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 ( + `inset 0 0 0 1px ${theme.palette.primary.main}` }), + }} + > + 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} + + + ); + })} + + ); +}; + +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} – {formatPercent(topSubject.rate)}, פי{' '} + {topSubject.times.toFixed(1)} מאחוז החיסור הכללי בכיתה ({formatPercent(topSubject.classRate)}) + + )} + + {group.students.map((student) => ( + onToggle(student.id)} + /> + ))} + + ); +}; + +const AbsenceTrackingView = () => { + const { rows, klasses, total, isPending } = usePivotPage(); + 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 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); + 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 ? ( + + ) : ( + <> + {total > rows.length && ( + + מוצגות {rows.length} מתוך {total} תלמידות, והסיכום מתייחס אליהן בלבד. לדוח של כיתה שלמה בחרי כיתה + במסנן. + + )} + + {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} + > + + + ); +}; + +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..d8b9cd12 --- /dev/null +++ b/client/src/utils/absenceTracking.js @@ -0,0 +1,152 @@ +// 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); + // `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, + tz: row.tz, + hasReports: lessons > 0, + lessons, + abs, + approved, + unapproved, + ratio: lessons ? unapproved / lessons : 0, + subjects, + subjectTotals, + 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 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 totalLessons = 0; + let totalAbs = 0; + students.forEach((student) => + 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 || !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. +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..fcaf297f --- /dev/null +++ b/client/src/utils/absenceTracking.test.js @@ -0,0 +1,125 @@ +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, 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, lessons: 30 }]); + expect(stats.subjectTotals).toHaveLength(2); + 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', () => { + 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 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(); + }); +}); + +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 }); + }); +}); 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;