Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -175,6 +176,7 @@ const App = () => (
<Resource name="student" {...student} options={{ menuGroup: 'data' }} icon={PortraitIcon}>
<Route path="student-attendance" element={<StudentAttendanceList />} />
<Route path="student-attendance-by-klass" element={<StudentAttendanceByKlassList />} />
<Route path="absence-tracking" element={<AbsenceTrackingList />} />
</Resource>
<Resource
name="student_klass"
Expand Down
10 changes: 10 additions & 0 deletions client/src/GeneralLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import FileUploadIcon from '@mui/icons-material/FileUploadOutlined';
import ViewListIcon from '@mui/icons-material/ViewListOutlined';
import GridOnIcon from '@mui/icons-material/GridOnOutlined';
import ContactMailIcon from '@mui/icons-material/ContactMailOutlined';
import TrackChangesIcon from '@mui/icons-material/TrackChangesOutlined';

import BaseLayout from '@shared/components/layout/Layout';
import BaseDashboard from '@shared/components/views/Dashboard';
Expand Down Expand Up @@ -137,6 +138,15 @@ const menuGroups = [
leftIcon={<SummarizeIcon />}
/>
),
({ permissions }) =>
!isTeacherView(permissions) && (
<MenuItemLink
key="absence-tracking"
to="/student/absence-tracking"
primaryText="מעקב חיסורים"
leftIcon={<TrackChangesIcon />}
/>
),
({ permissions }) =>
!isTeacherView(permissions) &&
isStudentAttendanceByKlass(permissions) && (
Expand Down
527 changes: 527 additions & 0 deletions client/src/pivots/AbsenceTrackingList.jsx

Large diffs are not rendered by default.

66 changes: 66 additions & 0 deletions client/src/pivots/AbsenceTrackingList.test.jsx
Original file line number Diff line number Diff line change
@@ -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(
<AdminContext dataProvider={dataProvider}>
<AbsenceTrackingList />
</AdminContext>,
);

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());
});
1 change: 1 addition & 0 deletions client/src/roadmapFeatures.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
152 changes: 152 additions & 0 deletions client/src/utils/absenceTracking.js
Original file line number Diff line number Diff line change
@@ -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_<lesson id>` 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)}%`;
125 changes: 125 additions & 0 deletions client/src/utils/absenceTracking.test.js
Original file line number Diff line number Diff line change
@@ -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 });
});
});
Loading
Loading