diff --git a/client/src/App.jsx b/client/src/App.jsx
index a15ba9d8..2d4414a0 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -66,11 +66,13 @@ import {
isStudentView,
isSeminarAttendanceYemot,
isAttendanceCleanupRules,
+ isAttendanceSheetImport,
} from 'src/utils/appPermissions';
import ScannerUpload from '@shared/components/views/ScannerUpload';
import InLessonReport from 'src/reports/InLessonReport';
import MichlolFileHelper from '@shared/components/views/MichlolFileHelper';
import ApprovedAbsencesUpload from 'src/components/ApprovedAbsencesUpload';
+import AttendanceSheetImport from 'src/components/AttendanceSheetImport';
import BadgeIcon from '@mui/icons-material/BadgeOutlined';
import SupervisedUserCircleIcon from '@mui/icons-material/SupervisedUserCircleOutlined';
@@ -345,6 +347,9 @@ const App = () => (
} />
} />
} />
+ {isAttendanceSheetImport(permissions) && (
+ } />
+ )}
{CommonRoutes({ permissions, roadmapFeatures, settingsPage: })}
>
diff --git a/client/src/GeneralLayout.jsx b/client/src/GeneralLayout.jsx
index c36ee0d4..b495b45b 100644
--- a/client/src/GeneralLayout.jsx
+++ b/client/src/GeneralLayout.jsx
@@ -18,6 +18,7 @@ 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 TableViewIcon from '@mui/icons-material/TableViewOutlined';
import BaseLayout from '@shared/components/layout/Layout';
import BaseDashboard from '@shared/components/views/Dashboard';
@@ -29,6 +30,7 @@ import {
isTeacherView,
isStudentView,
isStudentAttendanceByKlass,
+ isAttendanceSheetImport,
} from './utils/appPermissions';
import { useDashboardItems } from './settings/settingsUtil';
@@ -121,6 +123,15 @@ const menuGroups = [
primaryText="העלאת חיסורים מאושרים"
leftIcon={}
/>,
+ ({ permissions }) =>
+ isAttendanceSheetImport(permissions) && (
+ }
+ />
+ ),
],
},
({ permissions }) =>
diff --git a/client/src/components/AttendanceSheetImport.jsx b/client/src/components/AttendanceSheetImport.jsx
new file mode 100644
index 00000000..25b8c533
--- /dev/null
+++ b/client/src/components/AttendanceSheetImport.jsx
@@ -0,0 +1,377 @@
+import { useCallback, useMemo, useRef, useState } from 'react';
+import Container from '@mui/material/Container';
+import Paper from '@mui/material/Paper';
+import Stack from '@mui/material/Stack';
+import Box from '@mui/material/Box';
+import Divider from '@mui/material/Divider';
+import Typography from '@mui/material/Typography';
+import Autocomplete from '@mui/material/Autocomplete';
+import TextField from '@mui/material/TextField';
+import Alert from '@mui/material/Alert';
+import Table from '@mui/material/Table';
+import TableBody from '@mui/material/TableBody';
+import TableCell from '@mui/material/TableCell';
+import TableHead from '@mui/material/TableHead';
+import TableRow from '@mui/material/TableRow';
+import CircularProgress from '@mui/material/CircularProgress';
+import Dialog from '@mui/material/Dialog';
+import DialogTitle from '@mui/material/DialogTitle';
+import DialogContent from '@mui/material/DialogContent';
+import DialogActions from '@mui/material/DialogActions';
+import LinearProgress from '@mui/material/LinearProgress';
+import FileDownloadIcon from '@mui/icons-material/FileDownload';
+import FileUploadIcon from '@mui/icons-material/FileUpload';
+import { Button, useDataProvider, useGetList, useNotify, useTranslate } from 'react-admin';
+import { handleError } from '@shared/utils/notifyUtil';
+import { readAsDataURL } from '@shared/utils/fileUtil';
+import { getCurrentHebrewYear } from '@shared/utils/yearFilter';
+
+const listParams = {
+ pagination: { page: 1, perPage: 1000 },
+ sort: { field: 'key', order: 'ASC' },
+ filter: { year: getCurrentHebrewYear() },
+};
+
+const PREVIEW_ROWS_LIMIT = 200;
+
+const getOptionLabel = (option) => `${option.key} - ${option.name}`;
+
+const isLessonOfKlass = (lesson, klass) =>
+ Boolean(klass) && (lesson.klassReferenceIds ?? []).map(String).includes(String(klass.id));
+
+const IssuesTable = ({ issues }) => {
+ const translate = useTranslate();
+ return (
+
+
+
+ {translate('attendance_sheet.sheet')}
+ {translate('attendance_sheet.cell')}
+ {translate('attendance_sheet.reason')}
+
+
+
+ {issues.map((issue, index) => (
+
+ {issue.sheet}
+ {issue.cell}
+ {issue.message}
+
+ ))}
+
+
+ );
+};
+
+const SummaryTable = ({ details }) => {
+ const translate = useTranslate();
+ return (
+
+
+
+ {translate('attendance_sheet.sheet')}
+ {translate('attendance_sheet.teacher')}
+ {translate('attendance_sheet.lesson')}
+ {translate('attendance_sheet.created')}
+ {translate('attendance_sheet.updated')}
+
+
+
+ {details.map((row, index) => (
+
+ {row.sheet}
+ {row.teacherName}
+ {`${row.lessonKey} - ${row.lessonName}`}
+ {row.created}
+ {row.updated}
+
+ ))}
+
+
+ );
+};
+
+const Warnings = ({ warnings }) => {
+ const translate = useTranslate();
+ if (!warnings.length) return null;
+ return (
+ <>
+ {translate('attendance_sheet.warnings_title', { count: warnings.length })}
+
+ >
+ );
+};
+
+const PreviewRowsTable = ({ rows }) => {
+ const translate = useTranslate();
+ return (
+ <>
+ {rows.length > PREVIEW_ROWS_LIMIT && (
+
+ {translate('attendance_sheet.rows_limited', { shown: PREVIEW_ROWS_LIMIT, total: rows.length })}
+
+ )}
+
+
+
+ {translate('attendance_sheet.sheet')}
+ {translate('attendance_sheet.cell')}
+ {translate('attendance_sheet.student')}
+ {translate('attendance_sheet.teacher')}
+ {translate('attendance_sheet.lesson')}
+ {translate('attendance_sheet.date')}
+ {translate('attendance_sheet.how_many_lessons')}
+ {translate('attendance_sheet.abs_count')}
+ {translate('attendance_sheet.action')}
+
+
+
+ {rows.slice(0, PREVIEW_ROWS_LIMIT).map((row, index) => (
+
+ {row.sheet}
+ {row.cell}
+ {row.studentName}
+ {row.teacherName}
+ {row.lessonName}
+ {row.reportDate.split('-').reverse().join('/')}
+ {row.howManyLessons}
+ {row.absCount}
+
+ {translate(row.isUpdate ? 'attendance_sheet.row_update' : 'attendance_sheet.row_create')}
+
+
+ ))}
+
+
+ >
+ );
+};
+
+const PreviewDialog = ({ preview, saving, onCancel, onSave }) => {
+ const translate = useTranslate();
+ return (
+
+ );
+};
+
+const ImportResult = ({ result }) => {
+ const translate = useTranslate();
+ return (
+
+
+ {translate('attendance_sheet.success', { created: result.created, updated: result.updated })}
+
+ {result.details.length > 0 && }
+
+
+ );
+};
+
+const AttendanceSheetImport = () => {
+ const translate = useTranslate();
+ const dataProvider = useDataProvider();
+ const notify = useNotify();
+ const fileSelector = useRef();
+ const [klass, setKlass] = useState(null);
+ const [lessons, setLessons] = useState([]);
+ const [loading, setLoading] = useState(false);
+ const [preview, setPreview] = useState(null);
+ const [result, setResult] = useState(null);
+
+ const { data: klasses = [] } = useGetList('klass', listParams);
+ const { data: allLessons = [] } = useGetList('lesson', listParams);
+ const lessonOptions = useMemo(
+ () =>
+ allLessons
+ .map((lesson) => ({ ...lesson, isKlassLesson: isLessonOfKlass(lesson, klass) }))
+ .sort((a, b) => Number(b.isKlassLesson) - Number(a.isKlassLesson)),
+ [allLessons, klass]
+ );
+
+ const handleDownload = useCallback(() => {
+ const queryParams = {
+ 'extra.klassId': klass.id,
+ 'extra.lessonIds': lessons.map((lesson) => lesson.id).join(','),
+ };
+ setLoading(true);
+ dataProvider
+ .actionAndDownload('att_report', 'attendanceSheetTemplate', queryParams)
+ .catch(handleError(notify))
+ .finally(() => setLoading(false));
+ }, [dataProvider, notify, klass, lessons]);
+
+ const handleFileSelect = useCallback((e) => {
+ e.preventDefault();
+ fileSelector.current?.click();
+ }, []);
+
+ const importFile = useCallback(
+ (file, dryRun) =>
+ dataProvider
+ .action('att_report', 'attendanceSheetImport', dryRun ? { 'extra.dryRun': true } : {}, file)
+ .then((response) => response.json),
+ [dataProvider]
+ );
+
+ const handleFileUpload = useCallback(
+ async (e) => {
+ const [selectedFile] = e.target.files ?? [];
+ e.target.value = null;
+ if (!selectedFile) return;
+ setLoading(true);
+ setResult(null);
+ try {
+ const dataUrl = await readAsDataURL(selectedFile);
+ const file = { fileName: selectedFile.name, fileData: dataUrl.split(',')[1] };
+ setPreview({ fileName: file.fileName, file, result: await importFile(file, true) });
+ } catch (error) {
+ handleError(notify)(error);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [importFile, notify]
+ );
+
+ const handleSave = useCallback(async () => {
+ setLoading(true);
+ try {
+ const saved = await importFile(preview.file, false);
+ if (saved.success) {
+ setPreview(null);
+ setResult(saved);
+ } else {
+ setPreview({ ...preview, result: saved });
+ }
+ } catch (error) {
+ handleError(notify)(error);
+ } finally {
+ setLoading(false);
+ }
+ }, [importFile, notify, preview]);
+
+ return (
+
+
+
+
+
+ {translate('attendance_sheet.title')}
+
+
+ {translate('attendance_sheet.description')}
+
+
+
+
+
+ {translate('attendance_sheet.download_title')}
+ setKlass(value)}
+ renderInput={(params) => (
+
+ )}
+ />
+
+ translate(
+ option.isKlassLesson
+ ? 'attendance_sheet.klass_lessons'
+ : 'attendance_sheet.other_lessons'
+ )
+ }
+ getOptionLabel={getOptionLabel}
+ isOptionEqualToValue={(option, value) => option.id === value.id}
+ value={lessons}
+ onChange={(e, value) => setLessons(value)}
+ renderInput={(params) => (
+
+ )}
+ />
+
+ }
+ label={translate('attendance_sheet.download')}
+ onClick={handleDownload}
+ disabled={loading || !klass || !lessons.length}
+ />
+
+
+
+
+
+ {translate('attendance_sheet.upload_title')}
+
+ }
+ label={translate('attendance_sheet.upload')}
+ onClick={handleFileSelect}
+ disabled={loading}
+ />
+ {loading && }
+
+
+ {result && }
+ {preview && (
+ setPreview(null)}
+ onSave={handleSave}
+ />
+ )}
+
+
+
+
+ );
+};
+
+export default AttendanceSheetImport;
diff --git a/client/src/components/AttendanceSheetImport.test.jsx b/client/src/components/AttendanceSheetImport.test.jsx
new file mode 100644
index 00000000..874e8dcf
--- /dev/null
+++ b/client/src/components/AttendanceSheetImport.test.jsx
@@ -0,0 +1,111 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { AdminContext } from 'react-admin';
+import { getI18nProvider } from '@shared/providers/i18nProvider';
+import domainTranslations from 'src/domainTranslations';
+import AttendanceSheetImport from './AttendanceSheetImport';
+
+const makeDataProvider = (importResult) => ({
+ getList: jest.fn(() => 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 })),
+ action: jest.fn(() => Promise.resolve({ json: importResult })),
+ actionAndDownload: jest.fn(() => Promise.resolve({ data: {} })),
+});
+
+const renderScreen = (dataProvider) =>
+ render(
+
+
+
+ );
+
+const uploadFile = () =>
+ fireEvent.change(screen.getByTestId('attendance-sheet-file'), {
+ target: { files: [new File(['abc'], 'att.xlsx')] },
+ });
+
+const savedResult = {
+ success: true,
+ errors: [],
+ warnings: [{ sheet: 'א1', cell: 'A10', message: 'התלמידה לא משויכת לכיתה' }],
+ created: 3,
+ updated: 1,
+ details: [{ sheet: 'א1', teacherName: 'מורה א', lessonKey: 101, lessonName: 'מתמטיקה', created: 3, updated: 1 }],
+};
+const previewResult = {
+ ...savedResult,
+ rows: [
+ {
+ sheet: 'א1',
+ cell: 'D9',
+ studentTz: '900',
+ studentName: 'תלמידה א',
+ teacherName: 'מורה א',
+ lessonName: 'מתמטיקה',
+ reportDate: '2026-09-01',
+ howManyLessons: 2,
+ absCount: 1,
+ isUpdate: true,
+ },
+ ],
+};
+
+test('previews the file without saving, then imports it on confirm', async () => {
+ const dataProvider = makeDataProvider();
+ dataProvider.action
+ .mockResolvedValueOnce({ json: previewResult })
+ .mockResolvedValueOnce({ json: savedResult });
+ renderScreen(dataProvider);
+
+ expect(screen.getByText('שלב 1: הורדת קובץ לכיתה')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /הורדת קובץ/ })).toBeDisabled();
+
+ uploadFile();
+
+ expect(await screen.findByText('תצוגה מקדימה: att.xlsx')).toBeInTheDocument();
+ expect(screen.getByText('תלמידה א')).toBeInTheDocument();
+ expect(screen.getByText('01/09/2026')).toBeInTheDocument();
+ expect(screen.getByText('עדכון')).toBeInTheDocument();
+ expect(screen.getByText('התלמידה לא משויכת לכיתה')).toBeInTheDocument();
+ const [resource, action, query, body] = dataProvider.action.mock.calls[0];
+ expect([resource, action, query, body.fileName]).toEqual([
+ 'att_report',
+ 'attendanceSheetImport',
+ { 'extra.dryRun': true },
+ 'att.xlsx',
+ ]);
+ expect(body.fileData).toBe(btoa('abc'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'ייבא' }));
+
+ expect(await screen.findByText('הקובץ נקלט: 3 דיווחים חדשים, 1 דיווחים עודכנו')).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByText('תצוגה מקדימה: att.xlsx')).not.toBeInTheDocument());
+ expect(dataProvider.action.mock.calls[1][2]).toEqual({});
+ expect(dataProvider.action.mock.calls[1][3]).toEqual(body);
+});
+
+test('shows every error with sheet and cell and offers no import when the file is rejected', async () => {
+ renderScreen(
+ makeDataProvider({
+ success: false,
+ errors: [
+ { sheet: 'א1', cell: 'F2', message: 'חסר קוד כיתה' },
+ { sheet: 'א1', cell: 'D9', message: 'הערך "x" אינו מספר' },
+ ],
+ warnings: [],
+ created: 0,
+ updated: 0,
+ details: [],
+ })
+ );
+
+ uploadFile();
+
+ await waitFor(() =>
+ expect(screen.getByText('הקובץ לא נקלט. יש לתקן 2 שגיאות ולהעלות שוב (שום דיווח לא נשמר)')).toBeInTheDocument()
+ );
+ expect(screen.getByText('F2')).toBeInTheDocument();
+ expect(screen.getByText('הערך "x" אינו מספר')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'ייבא' })).not.toBeInTheDocument();
+});
diff --git a/client/src/domainTranslations.js b/client/src/domainTranslations.js
index 1834bd00..b66a2840 100644
--- a/client/src/domainTranslations.js
+++ b/client/src/domainTranslations.js
@@ -8,6 +8,38 @@ export default {
settings: 'הגדרות',
admin: 'ניהול',
},
+ attendance_sheet: {
+ title: 'קליטת קובץ נוכחות מגמה',
+ description: 'הורדת קובץ נוכחות מלא מראש לכיתה, והעלאת הקובץ אחרי שהמורות סימנו בו נוכחות',
+ download_title: 'שלב 1: הורדת קובץ לכיתה',
+ klass: 'כיתה',
+ lessons: 'שיעורים',
+ klass_lessons: 'שיעורים של הכיתה',
+ other_lessons: 'שיעורים אחרים',
+ download: 'הורדת קובץ',
+ upload_title: 'שלב 2: העלאת קובץ שמולא',
+ upload: 'בחירת קובץ להעלאה',
+ success: 'הקובץ נקלט: %{created} דיווחים חדשים, %{updated} דיווחים עודכנו',
+ errors_title: 'הקובץ לא נקלט. יש לתקן %{count} שגיאות ולהעלות שוב (שום דיווח לא נשמר)',
+ warnings_title: '%{count} אזהרות (הדיווחים נשמרו)',
+ sheet: 'גיליון',
+ cell: 'תא',
+ reason: 'סיבה',
+ teacher: 'מורה',
+ lesson: 'שיעור',
+ created: 'נוצרו',
+ updated: 'עודכנו',
+ preview_title: 'תצוגה מקדימה: %{fileName}',
+ preview_summary: 'ייקלטו %{created} דיווחים חדשים ו-%{updated} דיווחים קיימים יעודכנו. הדיווחים יישמרו רק אחרי לחיצה על "ייבא"',
+ rows_limited: 'מוצגים %{shown} דיווחים ראשונים מתוך %{total}',
+ student: 'תלמידה',
+ date: 'תאריך',
+ how_many_lessons: 'מספר שיעורים',
+ abs_count: 'חיסורים',
+ action: 'פעולה',
+ row_create: 'חדש',
+ row_update: 'עדכון',
+ },
resources: {
...sharedEntityTranslations,
settings: {
diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js
index b706e18d..c5f73a6f 100644
--- a/client/src/roadmapFeatures.js
+++ b/client/src/roadmapFeatures.js
@@ -42,4 +42,5 @@ export default [
{ html: 'דפי העזרה במערכת עודכנו ונכתבו מחדש, וכל הדפים מוצגים ברשימת העזרה', status: 'בוצע', statusColor: 'success' },
{ html: 'אישור חיסורים לפי תלמידה וטווח תאריכים: טופס "אישור ימים מלאים" והעלאת קובץ לפי ת.ז. ותאריך', status: 'בוצע', statusColor: 'success' },
{ html: 'רשימות: כפתור "מיון" למיון מתקדם לפי כמה עמודות (למשל סדר כיתה ואז שם מורה), כולל בייצוא לאקסל. בדוח שכר למורה אפשר למיין גם לפי סדר כיתה ושיוך כיתה', status: 'בוצע', statusColor: 'success' },
+ { html: 'מסך "קליטת קובץ נוכחות מגמה": הורדת קובץ אקסל מלא מראש לכיתה עם בלוק עמודות לכל מורה, והעלאתו אחרי הסימון ליצירה ועדכון של דיווחי נוכחות (בהרשאה)', status: 'בוצע', statusColor: 'success' },
].reverse();
diff --git a/client/src/utils/appPermissions.js b/client/src/utils/appPermissions.js
index bfd5fd69..e5dd305f 100644
--- a/client/src/utils/appPermissions.js
+++ b/client/src/utils/appPermissions.js
@@ -18,6 +18,7 @@ export const appPermissions = {
lessonSchedule: 'lessonSchedule',
perDateLessonCount: 'perDateLessonCount',
attendanceCleanupRules: 'attendanceCleanupRules',
+ attendanceSheetImport: 'attendanceSheetImport',
};
export const isScannerUpload = (permissions) => hasPermissionLogic(permissions, appPermissions.scannerUpload);
@@ -81,3 +82,7 @@ export const useIsPerDateLessonCount = () => useHasPermission(appPermissions.per
export const isAttendanceCleanupRules = (permissions) =>
isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.attendanceCleanupRules);
export const useIsAttendanceCleanupRules = () => useHasPermission(appPermissions.attendanceCleanupRules) || useIsAdmin();
+
+export const isAttendanceSheetImport = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.attendanceSheetImport);
+export const useIsAttendanceSheetImport = () => useHasPermission(appPermissions.attendanceSheetImport) || useIsAdmin();
diff --git a/server/src/entity-modules/__tests__/att-report.service.spec.ts b/server/src/entity-modules/__tests__/att-report.service.spec.ts
new file mode 100644
index 00000000..232c184f
--- /dev/null
+++ b/server/src/entity-modules/__tests__/att-report.service.spec.ts
@@ -0,0 +1,103 @@
+import * as ExcelJS from 'exceljs';
+import { DataSource } from 'typeorm';
+import { Test } from '@nestjs/testing';
+import { BadRequestException, ForbiddenException } from '@nestjs/common';
+import { CrudRequest } from '@dataui/crud';
+import { MailSendService } from '@shared/utils/mail/mail-send.service';
+import { ENTITY_EXPORTER, ENTITY_REPOSITORY } from '@shared/base-entity/interface';
+import * as reportUtil from '@shared/utils/report/report.util';
+import * as attendanceSheetUtil from 'src/utils/attendanceSheet.util';
+import attendanceSheetTemplate from 'src/reports/attendanceSheetTemplate';
+import attReportConfig from '../att-report.config';
+
+jest.mock('@shared/utils/report/report.util', () => ({
+ generateCommonFileResponse: jest.fn().mockResolvedValue({ data: 'file' }),
+}));
+jest.mock('src/utils/attendanceSheet.util', () => ({
+ parseAttendanceWorkbook: jest.fn().mockReturnValue({ sheets: [], errors: [] }),
+ importAttendanceWorkbook: jest.fn().mockResolvedValue({ success: true }),
+}));
+
+describe('att-report service attendance sheet actions', () => {
+ let service: any;
+ const dataSource = {} as DataSource;
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ const repository = {
+ metadata: { columns: [{ propertyName: 'id' }], relations: [], connection: { options: { type: 'mysql' } } },
+ manager: { connection: { createQueryRunner: jest.fn() } },
+ };
+ const module = await Test.createTestingModule({
+ providers: [
+ attReportConfig.service,
+ { provide: ENTITY_REPOSITORY, useValue: repository },
+ { provide: ENTITY_EXPORTER, useValue: attReportConfig.exporter },
+ { provide: MailSendService, useValue: { send: jest.fn() } },
+ { provide: DataSource, useValue: dataSource },
+ ],
+ }).compile();
+ service = module.get(attReportConfig.service);
+ });
+
+ const makeReq = (extra: any, permissions: any = { attendanceSheetImport: true }) =>
+ ({ parsed: { extra }, auth: { id: 7, permissions } } as unknown as CrudRequest);
+
+ it('rejects users without the attendanceSheetImport permission', async () => {
+ await expect(service.doAction(makeReq({ action: 'attendanceSheetTemplate' }, {}), {})).rejects.toThrow(
+ ForbiddenException,
+ );
+ await expect(service.doAction(makeReq({ action: 'attendanceSheetImport' }, {}), {})).rejects.toThrow(
+ ForbiddenException,
+ );
+ });
+
+ it('requires an admin to impersonate a user', async () => {
+ await expect(service.doAction(makeReq({ action: 'attendanceSheetImport' }, { admin: true }), {})).rejects.toThrow(
+ BadRequestException,
+ );
+ });
+
+ it('generates the template for the selected klass and lessons', async () => {
+ await service.doAction(makeReq({ action: 'attendanceSheetTemplate', klassId: '3', lessonIds: '4,5' }), {});
+ expect(reportUtil.generateCommonFileResponse).toHaveBeenCalledWith(
+ attendanceSheetTemplate,
+ { userId: 7, klassId: 3, lessonIds: [4, 5] },
+ dataSource,
+ );
+ });
+
+ it('parses the uploaded workbook and imports it for the user', async () => {
+ const workbook = new ExcelJS.Workbook();
+ workbook.addWorksheet('א1').getCell('F2').value = 11;
+ const fileData = Buffer.from(await workbook.xlsx.writeBuffer()).toString('base64');
+
+ const result = await service.doAction(makeReq({ action: 'attendanceSheetImport' }), { fileData });
+
+ expect(result).toEqual({ success: true });
+ const parsedWorkbook = (attendanceSheetUtil.parseAttendanceWorkbook as jest.Mock).mock.calls[0][0];
+ expect(parsedWorkbook.getWorksheet('א1').getCell('F2').value).toBe(11);
+ expect(attendanceSheetUtil.importAttendanceWorkbook).toHaveBeenCalledWith(
+ dataSource,
+ 7,
+ { sheets: [], errors: [] },
+ { dryRun: undefined },
+ );
+ });
+
+ it('passes the dry run flag', async () => {
+ const workbook = new ExcelJS.Workbook();
+ workbook.addWorksheet('א1');
+ const fileData = Buffer.from(await workbook.xlsx.writeBuffer()).toString('base64');
+
+ await service.doAction(makeReq({ action: 'attendanceSheetImport', dryRun: 'true' }), { fileData });
+
+ expect((attendanceSheetUtil.importAttendanceWorkbook as jest.Mock).mock.calls[0][3]).toEqual({ dryRun: true });
+ });
+
+ it('rejects a file that is not xlsx', async () => {
+ await expect(
+ service.doAction(makeReq({ action: 'attendanceSheetImport' }), { fileData: 'bm90IGFuIHhsc3g=' }),
+ ).rejects.toThrow(BadRequestException);
+ });
+});
diff --git a/server/src/entity-modules/att-report.config.ts b/server/src/entity-modules/att-report.config.ts
index fb532741..1417efac 100644
--- a/server/src/entity-modules/att-report.config.ts
+++ b/server/src/entity-modules/att-report.config.ts
@@ -1,11 +1,19 @@
import { CrudRequest } from '@dataui/crud';
-import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { BadRequestException, ForbiddenException } from '@nestjs/common';
+import * as ExcelJS from 'exceljs';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { generateCommonFileResponse } from '@shared/utils/report/report.util';
+import { getAsBoolean, getAsNumber, getAsNumberArray } from '@shared/utils/queryParam.util';
import { User } from '@shared/entities/User.entity';
import { IHeader } from '@shared/utils/exporter/types';
import { getHebrewDateFormatter } from '@shared/utils/formatting/formatter.util';
import { AttReport } from 'src/db/entities/AttReport.entity';
import { hasPermission, isAdmin } from '@shared/utils/permissionsUtil';
import { roundObjectProperty } from '@shared/utils/reportData.util';
+import attendanceSheetTemplate, { AttendanceSheetTemplateParams } from 'src/reports/attendanceSheetTemplate';
+import { importAttendanceWorkbook, parseAttendanceWorkbook } from 'src/utils/attendanceSheet.util';
function getConfig(): BaseEntityModuleOptions {
return {
@@ -71,9 +79,50 @@ function getConfig(): BaseEntityModuleOptions {
};
},
},
+ service: AttReportService,
};
}
+class AttReportService extends BaseEntityService {
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'attendanceSheetTemplate': {
+ const params: AttendanceSheetTemplateParams = {
+ userId: getAttendanceSheetUserId(req),
+ klassId: getAsNumber(req.parsed.extra.klassId),
+ lessonIds: getAsNumberArray(req.parsed.extra.lessonIds) ?? [],
+ };
+ return generateCommonFileResponse(attendanceSheetTemplate, params, this.dataSource);
+ }
+ case 'attendanceSheetImport': {
+ const userId = getAttendanceSheetUserId(req);
+ const workbook = new ExcelJS.Workbook();
+ try {
+ await workbook.xlsx.load(Buffer.from(body?.fileData ?? '', 'base64'));
+ } catch {
+ throw new BadRequestException('הקובץ אינו קובץ xlsx תקין');
+ }
+ return importAttendanceWorkbook(this.dataSource, userId, parseAttendanceWorkbook(workbook), {
+ dryRun: getAsBoolean(req.parsed.extra.dryRun),
+ });
+ }
+ }
+ return super.doAction(req, body);
+ }
+}
+
+// Every lookup and saved report is scoped to this user, so an admin must impersonate one first
+const getAttendanceSheetUserId = (req: CrudRequest) => {
+ if (!isAdmin(req.auth) && !hasPermission(req.auth, 'attendanceSheetImport')) {
+ throw new ForbiddenException('אין הרשאה לקליטת קובץ נוכחות');
+ }
+ const userId = getUserIdFromUser(req.auth);
+ if (!userId) {
+ throw new BadRequestException('יש להתחבר כמשתמש כדי לקלוט קובץ נוכחות');
+ }
+ return userId;
+};
+
export default getConfig();
export const shouldShowTopic = (req: CrudRequest | undefined): boolean => {
diff --git a/server/src/reports/__tests__/attendanceSheetTemplate.spec.ts b/server/src/reports/__tests__/attendanceSheetTemplate.spec.ts
new file mode 100644
index 00000000..5e4ad4d3
--- /dev/null
+++ b/server/src/reports/__tests__/attendanceSheetTemplate.spec.ts
@@ -0,0 +1,164 @@
+import * as ExcelJS from 'exceljs';
+import { DataSource } from 'typeorm';
+import { BadRequestException } from '@nestjs/common';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Teacher } from 'src/db/entities/Teacher.entity';
+import attendanceSheetTemplate, {
+ AttendanceSheetTemplateData,
+ DATE_COLUMNS_PER_TEACHER,
+} from '../attendanceSheetTemplate';
+import { parseAttendanceWorkbook } from 'src/utils/attendanceSheet.util';
+
+const data: AttendanceSheetTemplateData = {
+ klass: { key: 11, name: 'א1' },
+ blocks: [
+ { lessonKey: 101, teacherTz: '111', teacherName: 'מורה א' },
+ { lessonKey: 102, teacherTz: null, teacherName: null },
+ ],
+ students: [
+ { tz: '900', name: 'תלמידה א' },
+ { tz: '901', name: 'תלמידה ב' },
+ ],
+};
+
+const loadTemplate = async (templateData = data) => {
+ const workbook = new ExcelJS.Workbook();
+ await workbook.xlsx.load(await attendanceSheetTemplate.getFileBuffer(templateData));
+ return workbook;
+};
+
+const YELLOW = 'FFFFF2CC';
+
+describe('attendanceSheetTemplate', () => {
+ describe('getFileBuffer', () => {
+ it('builds the sheet layout with a block of date columns per lesson', async () => {
+ const workbook = await loadTemplate();
+ const sheet = workbook.getWorksheet('א1');
+
+ expect(sheet.views[0].rightToLeft).toBe(true);
+ expect(sheet.getCell('E2').value).toBe('קוד כיתה:');
+ expect(sheet.getCell('F2').value).toBe(11);
+ expect(sheet.getCell('D3').value).toBe('מורה א');
+ expect(sheet.getCell('D4').value).toBe('111');
+ expect(sheet.getCell('D5').value).toBe(101);
+ const secondBlock = 4 + DATE_COLUMNS_PER_TEACHER;
+ expect(sheet.getCell(5, secondBlock).value).toBe(102);
+ expect(sheet.getCell('A9').value).toBe('900');
+ expect(sheet.getCell('B10').value).toBe('תלמידה ב');
+
+ const dateCell = sheet.getCell(6, secondBlock + DATE_COLUMNS_PER_TEACHER - 1);
+ expect(dateCell.dataValidation.type).toBe('date');
+ expect((dateCell.fill as ExcelJS.FillPattern).fgColor.argb).toBe(YELLOW);
+ expect(sheet.getCell(10, secondBlock + DATE_COLUMNS_PER_TEACHER - 1).dataValidation.type).toBe('whole');
+ expect(sheet.getCell(6, secondBlock + DATE_COLUMNS_PER_TEACHER).dataValidation).toBeUndefined();
+
+ expect(workbook.getWorksheet('הוראות').getCell('A1').value).toBe('הוראות מילוי');
+ });
+
+ it('leaves teacher cells empty and yellow when the lesson has no teacher', async () => {
+ const sheet = (await loadTemplate()).getWorksheet('א1');
+ const secondBlock = 4 + DATE_COLUMNS_PER_TEACHER;
+ [3, 4].forEach((row) => {
+ const cell = sheet.getCell(row, secondBlock);
+ expect(cell.value).toBeNull();
+ expect((cell.fill as ExcelJS.FillPattern).fgColor.argb).toBe(YELLOW);
+ });
+ });
+
+ it('imports a downloaded file filled without other changes with no errors', async () => {
+ const workbook = await loadTemplate({ ...data, blocks: [data.blocks[0]] });
+ const sheet = workbook.getWorksheet('א1');
+ sheet.getCell('D6').value = new Date(Date.UTC(2026, 8, 1));
+ sheet.getCell('E6').value = '08/09/26';
+ sheet.getCell('D7').value = 2;
+ sheet.getCell('D9').value = 1;
+
+ const reloaded = new ExcelJS.Workbook();
+ await reloaded.xlsx.load(await workbook.xlsx.writeBuffer());
+ const parsed = parseAttendanceWorkbook(reloaded);
+
+ expect(parsed.errors).toEqual([]);
+ expect(parsed.sheets).toHaveLength(1);
+ expect(parsed.sheets[0].reports.map((r) => [r.studentTz, r.reportDate, r.howManyLessons, r.absCount])).toEqual([
+ ['900', '2026-09-01', 2, 1],
+ ['900', '2026-09-08', 1, 0],
+ ['901', '2026-09-01', 2, 0],
+ ['901', '2026-09-08', 1, 0],
+ ]);
+ });
+ });
+
+ describe('getReportData', () => {
+ const repos = {
+ klass: { findOne: jest.fn() },
+ lesson: { find: jest.fn() },
+ teacher: { find: jest.fn() },
+ studentKlass: { find: jest.fn() },
+ };
+ const dataSource = {
+ getRepository: jest.fn((entity) => {
+ switch (entity) {
+ case Klass:
+ return repos.klass;
+ case Lesson:
+ return repos.lesson;
+ case Teacher:
+ return repos.teacher;
+ case StudentKlass:
+ return repos.studentKlass;
+ }
+ }),
+ } as unknown as DataSource;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ repos.klass.findOne.mockResolvedValue({ id: 1, key: 11, name: 'א1' });
+ repos.lesson.find.mockResolvedValue([
+ { id: 4, key: 101, teacherReferenceId: 2 },
+ { id: 5, key: 102, teacherReferenceId: null },
+ ]);
+ repos.teacher.find.mockResolvedValue([{ id: 2, tz: '111', name: 'מורה א' }]);
+ repos.studentKlass.find.mockResolvedValue([
+ { student: { tz: '901', name: 'ת' } },
+ { student: { tz: '900', name: 'א' } },
+ ]);
+ });
+
+ it('fills klass, lesson teachers and klass students for the user', async () => {
+ const result = await attendanceSheetTemplate.getReportData(
+ { userId: 7, klassId: 1, lessonIds: [4, 5] },
+ dataSource,
+ );
+
+ expect(result).toEqual({
+ klass: { id: 1, key: 11, name: 'א1' },
+ blocks: [
+ { lessonKey: 101, teacherTz: '111', teacherName: 'מורה א' },
+ { lessonKey: 102, teacherTz: null, teacherName: null },
+ ],
+ students: [
+ { tz: '900', name: 'א' },
+ { tz: '901', name: 'ת' },
+ ],
+ });
+ expect(repos.klass.findOne.mock.calls[0][0].where).toMatchObject({ id: 1, userId: 7 });
+ expect(repos.lesson.find.mock.calls[0][0].where).toMatchObject({ userId: 7 });
+ expect(repos.studentKlass.find.mock.calls[0][0].where).toMatchObject({ klassReferenceId: 1, userId: 7 });
+ });
+
+ it('rejects a klass of another user or year', async () => {
+ repos.klass.findOne.mockResolvedValue(null);
+ await expect(
+ attendanceSheetTemplate.getReportData({ userId: 7, klassId: 1, lessonIds: [4] }, dataSource),
+ ).rejects.toThrow(BadRequestException);
+ });
+
+ it('requires at least one lesson', async () => {
+ await expect(
+ attendanceSheetTemplate.getReportData({ userId: 7, klassId: 1, lessonIds: [] }, dataSource),
+ ).rejects.toThrow(BadRequestException);
+ });
+ });
+});
diff --git a/server/src/reports/attendanceSheetTemplate.ts b/server/src/reports/attendanceSheetTemplate.ts
new file mode 100644
index 00000000..7673cc5b
--- /dev/null
+++ b/server/src/reports/attendanceSheetTemplate.ts
@@ -0,0 +1,228 @@
+import * as ExcelJS from 'exceljs';
+import { BadRequestException } from '@nestjs/common';
+import { In } from 'typeorm';
+import { BaseReportGenerator, IGetReportDataFunction } from '@shared/utils/report/report.generators';
+import { getIntegerDataValidation } from '@shared/utils/report/data-to-excel.generator';
+import { CommonFileFormat } from '@shared/utils/report/types';
+import { getCurrentHebrewYear } from '@shared/utils/entity/year.util';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Teacher } from 'src/db/entities/Teacher.entity';
+import {
+ DATE_ROW,
+ FIRST_BLOCK_COL,
+ FIRST_STUDENT_ROW,
+ HEADER_ROW,
+ KLASS_LABEL,
+ KLASS_LABEL_CELL,
+ KLASS_VALUE_CELL,
+ LESSON_KEY_ROW,
+ LESSONS_COUNT_ROW,
+ STUDENT_TZ_COL,
+ TEACHER_NAME_ROW,
+ TEACHER_TZ_ROW,
+} from 'src/utils/attendanceSheet.util';
+
+export const DATE_COLUMNS_PER_TEACHER = 10;
+
+export interface AttendanceSheetTemplateParams {
+ userId: number;
+ klassId: number;
+ lessonIds: number[];
+}
+
+export interface AttendanceSheetTemplateData {
+ klass: Pick;
+ blocks: { lessonKey: number; teacherTz: string | null; teacherName: string | null }[];
+ students: { tz: string; name: string }[];
+}
+
+const getReportData: IGetReportDataFunction = async (
+ params,
+ dataSource,
+) => {
+ const year = getCurrentHebrewYear();
+ const klass = await dataSource
+ .getRepository(Klass)
+ .findOne({ where: { id: params.klassId, userId: params.userId, year } });
+ if (!klass) {
+ throw new BadRequestException('יש לבחור כיתה מהשנה הנוכחית');
+ }
+ const lessons = params.lessonIds.length
+ ? await dataSource
+ .getRepository(Lesson)
+ .find({ where: { id: In(params.lessonIds), userId: params.userId }, order: { key: 'ASC' } })
+ : [];
+ if (!lessons.length) {
+ throw new BadRequestException('יש לבחור לפחות שיעור אחד');
+ }
+ const teacherIds = lessons.map((l) => l.teacherReferenceId).filter(Boolean);
+ const [teachers, studentKlasses] = await Promise.all([
+ teacherIds.length
+ ? dataSource.getRepository(Teacher).find({ where: { id: In(teacherIds), userId: params.userId } })
+ : ([] as Teacher[]),
+ dataSource.getRepository(StudentKlass).find({
+ where: { klassReferenceId: klass.id, userId: params.userId, year },
+ relations: { student: true },
+ }),
+ ]);
+ const teacherById = new Map(teachers.map((t) => [t.id, t]));
+
+ return {
+ klass,
+ blocks: lessons.map((lesson) => {
+ const teacher = teacherById.get(lesson.teacherReferenceId);
+ return { lessonKey: lesson.key, teacherTz: teacher?.tz ?? null, teacherName: teacher?.name ?? null };
+ }),
+ students: studentKlasses
+ .map((sk) => sk.student)
+ .filter(Boolean)
+ .map((s) => ({ tz: s.tz, name: s.name }))
+ .sort((a, b) => a.name.localeCompare(b.name, 'he')),
+ };
+};
+
+const fill = (argb: string): ExcelJS.Fill => ({ type: 'pattern', pattern: 'solid', fgColor: { argb } });
+const REQUIRED_FILL = fill('FFFFF2CC');
+const LABEL_FILL = fill('FFD9E1F2');
+const TEACHER_FILL = fill('FFE2EFDA');
+const thin: Partial = { style: 'thin' };
+const BORDER: Partial = { top: thin, bottom: thin, left: thin, right: thin };
+
+const getDateValidation = (): ExcelJS.DataValidation => ({
+ type: 'date',
+ operator: 'greaterThan',
+ formulae: [new Date(2000, 0, 1)],
+ allowBlank: true,
+ showErrorMessage: true,
+ errorStyle: 'stop',
+ errorTitle: 'הערך אינו תאריך תקין',
+ error: 'יש להזין תאריך, לדוגמה 01/09/26',
+});
+
+const instructions = [
+ 'הוראות מילוי',
+ 'כל גיליון = כיתה אחת. כל מורה = בלוק עמודות. אפשר להוסיף גיליונות לכיתות נוספות ובלוקים למורות נוספות.',
+ 'תאים צהובים = חובה למלא.',
+ '',
+ 'ברמת הגיליון:',
+ 'קוד כיתה – הקוד מתוך מסך הכיתות.',
+ 'ת.ז. תלמידה – בעמודה A, לכל תלמידה. שם התלמידה לנוחות בלבד.',
+ '',
+ 'לכל מורה:',
+ 'ת.ז. מורה – כפי שמופיעה במסך המורות.',
+ 'קוד שיעור – הקוד מתוך מסך השיעורים.',
+ 'תאריך – בראש כל עמודה, תאריך השיעור. עמודה ריקה מתאריך לא תיקלט.',
+ "מס' שיעורים – כמה שיעורים התקיימו באותו תאריך (ברירת מחדל 1).",
+ 'אפשר להוסיף עמודות בתוך הבלוק של המורה, לפני העמודה של המורה הבאה.',
+ '',
+ 'סימון בתאי התלמידות:',
+ 'ריק = נוכחת בכל השיעורים.',
+ "מספר = כמה שיעורים התלמידה חיסרה באותו תאריך (לא יותר ממס' השיעורים).",
+];
+
+const sanitizeSheetName = (name: string) => name.replace(/[\\\/\?\*\[\]:]/g, ' ').slice(0, 31) || 'כיתה';
+
+export class AttendanceSheetTemplateGenerator extends BaseReportGenerator<
+ AttendanceSheetTemplateParams,
+ AttendanceSheetTemplateData
+> {
+ fileFormat = CommonFileFormat.Excel;
+
+ async getFileBuffer(data: AttendanceSheetTemplateData): Promise {
+ const workbook = new ExcelJS.Workbook();
+ const sheet = workbook.addWorksheet(sanitizeSheetName(data.klass.name), {
+ views: [{ rightToLeft: true, state: 'frozen', xSplit: 3, ySplit: HEADER_ROW }],
+ });
+ const lastStudentRow = FIRST_STUDENT_ROW + Math.max(data.students.length, 1) - 1;
+ const lastCol = FIRST_BLOCK_COL + data.blocks.length * DATE_COLUMNS_PER_TEACHER - 1;
+
+ sheet.getCell('A1').value = 'ב"ה';
+ sheet.getCell('B2').value = `נוכחות ${data.klass.name}`;
+ sheet.getCell('B2').font = { bold: true };
+ sheet.getCell(KLASS_LABEL_CELL).value = KLASS_LABEL;
+ sheet.getCell(KLASS_LABEL_CELL).font = { bold: true };
+ Object.assign(sheet.getCell(KLASS_VALUE_CELL), { value: data.klass.key, fill: REQUIRED_FILL, border: BORDER });
+
+ const labels: [number, string][] = [
+ [TEACHER_NAME_ROW, 'שם מורה'],
+ [TEACHER_TZ_ROW, 'ת.ז. מורה'],
+ [LESSON_KEY_ROW, 'קוד שיעור'],
+ [DATE_ROW, 'תאריך'],
+ [LESSONS_COUNT_ROW, "מס' שיעורים"],
+ ];
+ labels.forEach(([row, label]) =>
+ Object.assign(sheet.getCell(row, 3), { value: label, fill: LABEL_FILL, font: { bold: true }, border: BORDER }),
+ );
+ ['ת.ז. תלמידה', 'שם התלמידה', ''].forEach((label, index) =>
+ Object.assign(sheet.getCell(HEADER_ROW, index + 1), {
+ value: label,
+ fill: LABEL_FILL,
+ font: { bold: true },
+ border: BORDER,
+ }),
+ );
+
+ data.students.forEach((student, index) => {
+ const row = FIRST_STUDENT_ROW + index;
+ Object.assign(sheet.getCell(row, STUDENT_TZ_COL), { value: student.tz, fill: REQUIRED_FILL, border: BORDER });
+ Object.assign(sheet.getCell(row, 2), { value: student.name, border: BORDER });
+ sheet.getCell(row, 3).border = BORDER;
+ });
+
+ data.blocks.forEach((block, index) => {
+ const startCol = FIRST_BLOCK_COL + index * DATE_COLUMNS_PER_TEACHER;
+ const endCol = startCol + DATE_COLUMNS_PER_TEACHER - 1;
+ const headerCells: [number, any, ExcelJS.Fill][] = [
+ [TEACHER_NAME_ROW, block.teacherName, block.teacherName ? TEACHER_FILL : REQUIRED_FILL],
+ [TEACHER_TZ_ROW, block.teacherTz, REQUIRED_FILL],
+ [LESSON_KEY_ROW, block.lessonKey, REQUIRED_FILL],
+ ];
+ headerCells.forEach(([row, value, cellFill]) => {
+ sheet.mergeCells(row, startCol, row, endCol);
+ Object.assign(sheet.getCell(row, startCol), {
+ value,
+ fill: cellFill,
+ font: { bold: row === TEACHER_NAME_ROW },
+ alignment: { horizontal: 'center' },
+ border: BORDER,
+ });
+ });
+ for (let col = startCol; col <= endCol; col++) {
+ Object.assign(sheet.getCell(DATE_ROW, col), {
+ fill: REQUIRED_FILL,
+ border: BORDER,
+ numFmt: 'dd/mm/yy',
+ dataValidation: getDateValidation(),
+ });
+ Object.assign(sheet.getCell(LESSONS_COUNT_ROW, col), {
+ fill: REQUIRED_FILL,
+ border: BORDER,
+ dataValidation: getIntegerDataValidation(),
+ });
+ for (let row = FIRST_STUDENT_ROW; row <= lastStudentRow; row++) {
+ Object.assign(sheet.getCell(row, col), { border: BORDER, dataValidation: getIntegerDataValidation() });
+ }
+ }
+ });
+
+ sheet.getColumn(1).width = 13;
+ sheet.getColumn(2).width = 20;
+ sheet.getColumn(3).width = 13;
+ for (let col = FIRST_BLOCK_COL; col <= lastCol; col++) {
+ sheet.getColumn(col).width = 9;
+ }
+
+ const instructionsSheet = workbook.addWorksheet('הוראות', { views: [{ rightToLeft: true }] });
+ instructions.forEach((line, index) => (instructionsSheet.getCell(index + 1, 1).value = line));
+ instructionsSheet.getCell('A1').font = { bold: true, size: 14 };
+ instructionsSheet.getColumn(1).width = 100;
+
+ return workbook.xlsx.writeBuffer().then((buffer) => Buffer.from(buffer));
+ }
+}
+
+const getReportName = (data: AttendanceSheetTemplateData) => `נוכחות ${data.klass.name}`;
+
+export default new AttendanceSheetTemplateGenerator(getReportName, getReportData);
diff --git a/server/src/utils/__tests__/attendanceSheet.util.spec.ts b/server/src/utils/__tests__/attendanceSheet.util.spec.ts
new file mode 100644
index 00000000..228cde52
--- /dev/null
+++ b/server/src/utils/__tests__/attendanceSheet.util.spec.ts
@@ -0,0 +1,424 @@
+import * as ExcelJS from 'exceljs';
+import { DataSource } from 'typeorm';
+import { AttReport } from 'src/db/entities/AttReport.entity';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { Student } from 'src/db/entities/Student.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Teacher } from 'src/db/entities/Teacher.entity';
+import {
+ importAttendanceWorkbook,
+ parseAttendanceWorkbook,
+ parseSheetDate,
+ ParsedWorkbook,
+} from '../attendanceSheet.util';
+
+interface TestBlock {
+ name?: string;
+ tz?: string | number;
+ lesson?: string | number;
+ dates: any[];
+ counts?: any[];
+ merge?: boolean;
+}
+interface TestSheet {
+ name?: string;
+ klass?: any;
+ blocks: TestBlock[];
+ students: { tz?: string | number; values: any[] }[];
+}
+
+// Builds a sheet in the client template layout; student values are listed across all blocks' columns in order
+function addSheet(workbook: ExcelJS.Workbook, sheet: TestSheet) {
+ const ws = workbook.addWorksheet(sheet.name ?? 'כיתה א');
+ ws.getCell('E2').value = 'קוד כיתה:';
+ if (sheet.klass !== undefined) ws.getCell('F2').value = sheet.klass;
+ ws.getCell('A8').value = 'ת.ז. תלמידה';
+ let col = 4;
+ const columns: number[] = [];
+ sheet.blocks.forEach((block) => {
+ const width = block.dates.length;
+ if (block.name !== undefined) ws.getCell(3, col).value = block.name;
+ if (block.tz !== undefined) ws.getCell(4, col).value = block.tz;
+ if (block.lesson !== undefined) ws.getCell(5, col).value = block.lesson;
+ if (block.merge && width > 1) {
+ [3, 4, 5].forEach((row) => ws.mergeCells(row, col, row, col + width - 1));
+ }
+ block.dates.forEach((date, index) => {
+ if (date !== null) ws.getCell(6, col + index).value = date;
+ const count = block.counts?.[index];
+ if (count !== undefined) ws.getCell(7, col + index).value = count;
+ columns.push(col + index);
+ });
+ col += width;
+ });
+ sheet.students.forEach((student, index) => {
+ const row = 9 + index;
+ if (student.tz !== undefined) ws.getCell(row, 1).value = student.tz;
+ student.values.forEach((value, i) => {
+ if (value !== null && value !== undefined) ws.getCell(row, columns[i]).value = value;
+ });
+ });
+ return ws;
+}
+
+function buildWorkbook(...sheets: TestSheet[]) {
+ const workbook = new ExcelJS.Workbook();
+ sheets.forEach((sheet) => addSheet(workbook, sheet));
+ return workbook;
+}
+
+const d = (y: number, m: number, day: number) => new Date(Date.UTC(y, m - 1, day));
+const messages = (parsed: { errors: { message: string }[] }) => parsed.errors.map((e) => e.message);
+
+describe('parseSheetDate', () => {
+ it('parses excel dates, serial numbers and text dates', () => {
+ expect(parseSheetDate(d(2026, 9, 1))).toBe('2026-09-01');
+ expect(parseSheetDate(46266)).toBe('2026-09-01');
+ expect(parseSheetDate('01/09/26')).toBe('2026-09-01');
+ expect(parseSheetDate('1/9/2026')).toBe('2026-09-01');
+ });
+
+ it('rejects invalid dates', () => {
+ expect(parseSheetDate('31/02/26')).toBeNull();
+ expect(parseSheetDate('abc')).toBeNull();
+ expect(parseSheetDate(5)).toBeNull();
+ });
+});
+
+describe('parseAttendanceWorkbook', () => {
+ it('parses several teacher blocks of different widths', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [
+ { name: 'מורה א', tz: '111', lesson: 101, dates: [d(2026, 9, 1), d(2026, 9, 8)], counts: [2], merge: true },
+ {
+ name: 'מורה ב',
+ tz: 222,
+ lesson: '102',
+ dates: [d(2026, 9, 2), d(2026, 9, 9), d(2026, 9, 16)],
+ merge: true,
+ },
+ ],
+ students: [{ tz: '900', values: [1, null, null, 1, null] }],
+ }),
+ );
+
+ expect(parsed.errors).toEqual([]);
+ const [sheet] = parsed.sheets;
+ expect(sheet.klassKey).toBe(11);
+ expect(sheet.blocks.map((b) => [b.teacherTz, b.lessonKey, b.columns.length])).toEqual([
+ ['111', 101, 2],
+ ['222', 102, 3],
+ ]);
+ expect(sheet.reports.map((r) => [r.block.teacherTz, r.reportDate, r.howManyLessons, r.absCount])).toEqual([
+ ['111', '2026-09-01', 2, 1],
+ ['111', '2026-09-08', 1, 0],
+ ['222', '2026-09-02', 1, 0],
+ ['222', '2026-09-09', 1, 1],
+ ['222', '2026-09-16', 1, 0],
+ ]);
+ });
+
+ it('parses a file with one teacher', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [{ name: 'מורה א', tz: '111', lesson: 101, dates: ['01/09/26', '08/09/2026'] }],
+ students: [{ tz: '900', values: [null, 1] }],
+ }),
+ );
+ expect(parsed.errors).toEqual([]);
+ expect(parsed.sheets[0].reports.map((r) => r.reportDate)).toEqual(['2026-09-01', '2026-09-08']);
+ });
+
+ it('assigns a column added at the end of a merged block to the same teacher', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [
+ { name: 'מורה א', tz: '111', lesson: 101, dates: [d(2026, 9, 1), d(2026, 9, 8)], merge: true },
+ // column inserted by hand after the merged block: no teacher header of its own
+ { dates: [d(2026, 9, 15)] },
+ { name: 'מורה ב', tz: '222', lesson: 102, dates: [d(2026, 9, 2)] },
+ ],
+ students: [{ tz: '900', values: [null, null, 1, null] }],
+ }),
+ );
+ expect(parsed.errors).toEqual([]);
+ const byDate = (date: string) => parsed.sheets[0].reports.find((r) => r.reportDate === date);
+ expect(byDate('2026-09-15')).toMatchObject({ absCount: 1, block: { teacherTz: '111', lessonKey: 101 } });
+ expect(byDate('2026-09-02').block.teacherTz).toBe('222');
+ });
+
+ it('skips columns without a date, even with values', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [{ name: 'מורה א', tz: '111', lesson: 101, dates: [d(2026, 9, 1), null, null] }],
+ students: [{ tz: '900', values: [null, 'x', 1] }],
+ }),
+ );
+ expect(parsed.errors).toEqual([]);
+ expect(parsed.sheets[0].reports).toHaveLength(1);
+ });
+
+ it('parses several sheets, skips the instructions sheet and rows without student tz', () => {
+ const workbook = buildWorkbook(
+ {
+ name: 'כיתה א',
+ klass: 11,
+ blocks: [{ tz: '111', lesson: 101, dates: [d(2026, 9, 1)] }],
+ students: [{ tz: '900', values: [] }, { values: [1] }],
+ },
+ {
+ name: 'כיתה ב',
+ klass: 12,
+ blocks: [{ tz: '111', lesson: 103, dates: [d(2026, 9, 1)] }],
+ students: [{ tz: '901', values: [] }],
+ },
+ );
+ workbook.addWorksheet('הוראות').getCell('A1').value = 'הוראות מילוי';
+
+ const parsed = parseAttendanceWorkbook(workbook);
+ expect(parsed.errors).toEqual([]);
+ expect(parsed.sheets.map((s) => [s.name, s.klassKey, s.reports.length])).toEqual([
+ ['כיתה א', 11, 1],
+ ['כיתה ב', 12, 1],
+ ]);
+ });
+
+ it('ignores template blocks that have no dates yet', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [
+ { name: 'מורה א', tz: '111', lesson: 101, dates: [d(2026, 9, 1)] },
+ { lesson: 102, dates: [null, null] },
+ ],
+ students: [{ tz: '900', values: [] }],
+ }),
+ );
+ expect(parsed.errors).toEqual([]);
+ expect(parsed.sheets[0].blocks).toHaveLength(1);
+ });
+
+ it('reports structural errors with sheet and cell', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ name: 'גיליון',
+ blocks: [
+ { name: 'מורה א', lesson: 101, dates: [d(2026, 9, 1), 'not a date'], counts: [2] },
+ { name: 'מורה ב', tz: '222', dates: [d(2026, 9, 1)] },
+ ],
+ students: [{ tz: '900', values: [3, null, 'x'] }],
+ }),
+ );
+
+ expect(parsed.errors).toEqual(
+ expect.arrayContaining([
+ { sheet: 'גיליון', cell: 'F2', message: 'חסר קוד כיתה' },
+ { sheet: 'גיליון', cell: 'D4', message: 'חסרה ת.ז. מורה' },
+ { sheet: 'גיליון', cell: 'F5', message: 'חסר קוד שיעור' },
+ { sheet: 'גיליון', cell: 'E6', message: 'תאריך "not a date" לא תקין' },
+ { sheet: 'גיליון', cell: 'D9', message: 'מספר החיסורים (3) גדול ממספר השיעורים (2)' },
+ { sheet: 'גיליון', cell: 'F9', message: 'הערך "x" אינו מספר' },
+ ]),
+ );
+ expect(parsed.errors).toHaveLength(6);
+ });
+
+ it('reports the same student, teacher, lesson and date twice as an error', () => {
+ const parsed = parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [{ tz: '111', lesson: 101, dates: [d(2026, 9, 1), d(2026, 9, 1)] }],
+ students: [{ tz: '900', values: [] }],
+ }),
+ );
+ expect(messages(parsed)).toEqual(['דיווח כפול לאותה תלמידה, מורה, שיעור ותאריך']);
+ });
+});
+
+describe('importAttendanceWorkbook', () => {
+ const userId = 7;
+ const year = 5787;
+ let repos: Record;
+ let save: jest.Mock;
+ let dataSource: DataSource;
+
+ beforeEach(() => {
+ repos = {
+ Klass: { find: jest.fn().mockResolvedValue([{ id: 1, key: 11, name: 'א1' }]) },
+ Teacher: {
+ find: jest.fn().mockResolvedValue([
+ { id: 2, tz: '111', name: 'מורה א' },
+ { id: 3, tz: '222', name: 'מורה ב' },
+ ]),
+ },
+ Lesson: {
+ find: jest.fn().mockResolvedValue([
+ { id: 4, key: 101, name: 'שיעור א' },
+ { id: 5, key: 102, name: 'שיעור ב' },
+ ]),
+ },
+ Student: {
+ find: jest.fn().mockResolvedValue([
+ { id: 8, tz: '900', name: 'תלמידה א' },
+ { id: 9, tz: '901', name: 'תלמידה ב' },
+ ]),
+ },
+ StudentKlass: { find: jest.fn().mockResolvedValue([{ studentReferenceId: 8, klassReferenceId: 1 }]) },
+ AttReport: { find: jest.fn().mockResolvedValue([]) },
+ };
+ const entities = { Klass, Teacher, Lesson, Student, StudentKlass, AttReport };
+ save = jest.fn();
+ dataSource = {
+ getRepository: jest.fn((entity) => repos[Object.keys(entities).find((k) => entities[k] === entity)]),
+ transaction: jest.fn((cb) => cb({ save })),
+ } as any;
+ });
+
+ const parse = (sheet: Partial): ParsedWorkbook =>
+ parseAttendanceWorkbook(
+ buildWorkbook({
+ klass: 11,
+ blocks: [
+ { name: 'מורה א', tz: '111', lesson: 101, dates: [d(2026, 9, 1)] },
+ { name: 'מורה ב', tz: '222', lesson: 102, dates: [d(2026, 9, 2)], counts: [2] },
+ ],
+ students: [
+ { tz: '900', values: [1, null] },
+ { tz: '901', values: [null, 2] },
+ ],
+ ...sheet,
+ }),
+ );
+
+ it('creates a report per student and dated column, filtered by user', async () => {
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({}), { year });
+
+ expect(result).toMatchObject({ success: true, errors: [], created: 4, updated: 0 });
+ expect(result.details).toEqual([
+ {
+ sheet: 'כיתה א',
+ teacherTz: '111',
+ teacherName: 'מורה א',
+ lessonKey: 101,
+ lessonName: 'שיעור א',
+ created: 2,
+ updated: 0,
+ },
+ {
+ sheet: 'כיתה א',
+ teacherTz: '222',
+ teacherName: 'מורה ב',
+ lessonKey: 102,
+ lessonName: 'שיעור ב',
+ created: 2,
+ updated: 0,
+ },
+ ]);
+ Object.values(repos).forEach((repo) =>
+ expect(repo.find).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ userId }) })),
+ );
+ expect(repos.Klass.find.mock.calls[0][0].where.year).toBe(year);
+ expect(repos.Lesson.find.mock.calls[0][0].where.year).toBe(year);
+
+ const [, saved, options] = save.mock.calls[0];
+ expect(options).toMatchObject({ listeners: false });
+ expect(saved[0]).toEqual({
+ userId,
+ year: 5787,
+ studentTz: '900',
+ studentReferenceId: 8,
+ teacherId: '111',
+ teacherReferenceId: 2,
+ klassId: 11,
+ klassReferenceId: 1,
+ lessonId: 101,
+ lessonReferenceId: 4,
+ reportDate: '2026-09-01',
+ howManyLessons: 1,
+ absCount: 1,
+ });
+ expect(saved.map((r) => [r.howManyLessons, r.absCount])).toEqual([
+ [1, 1],
+ [2, 0],
+ [1, 0],
+ [2, 2],
+ ]);
+ });
+
+ it('returns the reports to preview without saving on a dry run', async () => {
+ repos.AttReport.find.mockResolvedValue([
+ { id: 50, studentReferenceId: 8, teacherReferenceId: 2, lessonReferenceId: 4, reportDate: '2026-09-01' },
+ ]);
+
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({}), { dryRun: true, year });
+
+ expect(result).toMatchObject({ success: true, created: 3, updated: 1 });
+ expect(result.rows).toHaveLength(4);
+ expect(result.rows[0]).toEqual({
+ sheet: 'כיתה א',
+ cell: 'D9',
+ studentTz: '900',
+ studentName: 'תלמידה א',
+ teacherName: 'מורה א',
+ lessonName: 'שיעור א',
+ reportDate: '2026-09-01',
+ howManyLessons: 1,
+ absCount: 1,
+ isUpdate: true,
+ });
+ expect(dataSource.transaction).not.toHaveBeenCalled();
+ });
+
+ it('updates existing reports on re-upload instead of duplicating', async () => {
+ repos.AttReport.find.mockResolvedValue([
+ { id: 50, studentReferenceId: 8, teacherReferenceId: 2, lessonReferenceId: 4, reportDate: '2026-09-01' },
+ ]);
+
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({}), { year });
+
+ expect(result).toMatchObject({ success: true, created: 3, updated: 1 });
+ expect(result.details[0]).toMatchObject({ created: 1, updated: 1 });
+ const saved = save.mock.calls[0][1];
+ expect(saved).toHaveLength(4);
+ expect(saved.filter((r) => r.id)).toEqual([expect.objectContaining({ id: 50, absCount: 1 })]);
+ });
+
+ it('saves nothing and lists every unknown klass, teacher, lesson and student', async () => {
+ repos.Klass.find.mockResolvedValue([]);
+ repos.Teacher.find.mockResolvedValue([{ id: 2, tz: '111' }]);
+ repos.Lesson.find.mockResolvedValue([{ id: 4, key: 101 }]);
+ repos.Student.find.mockResolvedValue([{ id: 8, tz: '900' }]);
+
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({}), { year });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toEqual([
+ { sheet: 'כיתה א', cell: 'F2', message: 'קוד כיתה 11 לא קיים בשנה הנוכחית' },
+ { sheet: 'כיתה א', cell: 'E4', message: 'ת.ז. מורה 222 לא קיימת' },
+ { sheet: 'כיתה א', cell: 'E5', message: 'קוד שיעור 102 לא קיים בשנה הנוכחית' },
+ { sheet: 'כיתה א', cell: 'A10', message: 'ת.ז. תלמידה 901 לא קיימת' },
+ ]);
+ expect(dataSource.transaction).not.toHaveBeenCalled();
+ });
+
+ it('saves nothing when the file has structural errors', async () => {
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({ klass: undefined }), { year });
+ expect(result.success).toBe(false);
+ expect(result.errors).toEqual([{ sheet: 'כיתה א', cell: 'F2', message: 'חסר קוד כיתה' }]);
+ expect(dataSource.transaction).not.toHaveBeenCalled();
+ });
+
+ it('warns without blocking when a student is not assigned to the sheet klass', async () => {
+ const result = await importAttendanceWorkbook(dataSource, userId, parse({}), { year });
+ expect(result.success).toBe(true);
+ expect(result.warnings).toEqual([
+ { sheet: 'כיתה א', cell: 'A10', message: 'התלמידה תלמידה ב (901) לא משויכת לכיתה א1' },
+ ]);
+ });
+});
diff --git a/server/src/utils/attendanceSheet.util.ts b/server/src/utils/attendanceSheet.util.ts
new file mode 100644
index 00000000..bb99973c
--- /dev/null
+++ b/server/src/utils/attendanceSheet.util.ts
@@ -0,0 +1,481 @@
+import * as ExcelJS from 'exceljs';
+import { DataSource, In } from 'typeorm';
+import { AttReport } from 'src/db/entities/AttReport.entity';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { Student } from 'src/db/entities/Student.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Teacher } from 'src/db/entities/Teacher.entity';
+import { getCurrentHebrewYear, getHebrewYearByGregorianDate } from '@shared/utils/entity/year.util';
+
+// Attendance sheet layout (1-based rows/columns, as in Excel)
+export const KLASS_LABEL_CELL = 'E2';
+export const KLASS_VALUE_CELL = 'F2';
+export const TEACHER_NAME_ROW = 3;
+export const TEACHER_TZ_ROW = 4;
+export const LESSON_KEY_ROW = 5;
+export const DATE_ROW = 6;
+export const LESSONS_COUNT_ROW = 7;
+export const HEADER_ROW = 8;
+export const FIRST_STUDENT_ROW = 9;
+export const STUDENT_TZ_COL = 1;
+export const FIRST_BLOCK_COL = 4;
+export const KLASS_LABEL = 'קוד כיתה:';
+
+export interface SheetIssue {
+ sheet: string;
+ cell: string;
+ message: string;
+}
+
+export interface ParsedColumn {
+ col: number;
+ dateCell: string;
+ reportDate: string;
+ howManyLessons: number;
+}
+
+export interface ParsedBlock {
+ teacherTz: string | null;
+ teacherName: string | null;
+ teacherCell: string;
+ lessonKey: number | null;
+ lessonValue: any;
+ lessonCell: string;
+ columns: ParsedColumn[];
+}
+
+export interface ParsedReport {
+ cell: string;
+ studentTz: string;
+ studentCell: string;
+ block: ParsedBlock;
+ reportDate: string;
+ howManyLessons: number;
+ absCount: number;
+}
+
+export interface ParsedSheet {
+ name: string;
+ klassKey: number | null;
+ blocks: ParsedBlock[];
+ reports: ParsedReport[];
+}
+
+export interface ParsedWorkbook {
+ sheets: ParsedSheet[];
+ errors: SheetIssue[];
+}
+
+export interface AttendanceSheetSummaryRow {
+ sheet: string;
+ teacherTz: string;
+ teacherName: string;
+ lessonKey: number;
+ lessonName: string;
+ created: number;
+ updated: number;
+}
+
+export interface AttendanceSheetPreviewRow {
+ sheet: string;
+ cell: string;
+ studentTz: string;
+ studentName: string;
+ teacherName: string;
+ lessonName: string;
+ reportDate: string;
+ howManyLessons: number;
+ absCount: number;
+ isUpdate: boolean;
+}
+
+export interface AttendanceSheetImportResult {
+ success: boolean;
+ errors: SheetIssue[];
+ warnings: SheetIssue[];
+ created: number;
+ updated: number;
+ details: AttendanceSheetSummaryRow[];
+ // dry run only: the reports that would be saved
+ rows?: AttendanceSheetPreviewRow[];
+}
+
+const isEmpty = (value: any) => value === null || value === undefined;
+
+// Reads a cell's own value: merged slave cells count as empty, formulas/rich text are unwrapped
+export function getCellValue(cell: ExcelJS.Cell): any {
+ if (cell.isMerged && cell.master.address !== cell.address) {
+ return null;
+ }
+ let value: any = cell.value;
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
+ if ('result' in value) value = value.result;
+ else if ('richText' in value) value = value.richText.map((part) => part.text).join('');
+ else if ('text' in value) value = value.text;
+ else if ('error' in value) value = String(value.error);
+ }
+ if (typeof value === 'string') {
+ value = value.trim();
+ if (value === '') return null;
+ }
+ return value ?? null;
+}
+
+const pad = (n: number) => String(n).padStart(2, '0');
+const toYmd = (year: number, month: number, day: number) => `${year}-${pad(month)}-${pad(day)}`;
+const isSaneYear = (year: number) => year >= 2000 && year <= 2100;
+
+// Accepts Excel dates, Excel serial numbers and dd/mm/yy or dd/mm/yyyy text; returns YYYY-MM-DD or null
+export function parseSheetDate(value: any): string | null {
+ if (value instanceof Date) {
+ if (isNaN(value.getTime()) || !isSaneYear(value.getUTCFullYear())) return null;
+ return toYmd(value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate());
+ }
+ if (typeof value === 'number') {
+ const date = new Date(Date.UTC(1899, 11, 30) + Math.floor(value) * 86400000);
+ return parseSheetDate(date);
+ }
+ if (typeof value === 'string') {
+ const match = value.match(/^(\d{1,2})[\/.\-](\d{1,2})[\/.\-](\d{2}|\d{4})$/);
+ if (!match) return null;
+ const day = Number(match[1]);
+ const month = Number(match[2]);
+ const year = match[3].length === 2 ? 2000 + Number(match[3]) : Number(match[3]);
+ const date = new Date(Date.UTC(year, month - 1, day));
+ if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;
+ return parseSheetDate(date);
+ }
+ return null;
+}
+
+// null = empty cell, NaN = not a number
+export function parseSheetNumber(value: any): number | null {
+ if (isEmpty(value)) return null;
+ if (typeof value === 'number') return value;
+ if (typeof value === 'string' && /^\d+(\.\d+)?$/.test(value)) return Number(value);
+ return NaN;
+}
+
+const parseTz = (value: any): string | null => (isEmpty(value) ? null : String(value).replace(/\s/g, ''));
+
+const isAttendanceSheet = (worksheet: ExcelJS.Worksheet) => {
+ const label = getCellValue(worksheet.getCell(KLASS_LABEL_CELL));
+ return (
+ (typeof label === 'string' && label.includes('קוד כיתה')) ||
+ !isEmpty(getCellValue(worksheet.getCell(KLASS_VALUE_CELL)))
+ );
+};
+
+export function parseAttendanceWorkbook(workbook: ExcelJS.Workbook): ParsedWorkbook {
+ const sheets: ParsedSheet[] = [];
+ const errors: SheetIssue[] = [];
+ const seenReports = new Set();
+
+ workbook.eachSheet((worksheet) => {
+ if (!isAttendanceSheet(worksheet)) return;
+
+ const sheetName = worksheet.name;
+ const addError = (cell: string, message: string) => errors.push({ sheet: sheetName, cell, message });
+ const cellAt = (row: number, col: number) => worksheet.getCell(row, col);
+
+ const blocks: ParsedBlock[] = [];
+ let block: ParsedBlock = null;
+ for (let col = FIRST_BLOCK_COL; col <= worksheet.columnCount; col++) {
+ const teacherName = getCellValue(cellAt(TEACHER_NAME_ROW, col));
+ const teacherTz = getCellValue(cellAt(TEACHER_TZ_ROW, col));
+ const lessonValue = getCellValue(cellAt(LESSON_KEY_ROW, col));
+ // A new block starts where teacher name, teacher tz or lesson key is filled (merged slave cells read as empty)
+ if (!isEmpty(teacherName) || !isEmpty(teacherTz) || !isEmpty(lessonValue) || !block) {
+ const lessonKey = parseSheetNumber(lessonValue);
+ block = {
+ teacherTz: parseTz(teacherTz),
+ teacherName: isEmpty(teacherName) ? null : String(teacherName),
+ teacherCell: cellAt(TEACHER_TZ_ROW, col).address,
+ lessonKey: Number.isInteger(lessonKey) ? lessonKey : null,
+ lessonValue,
+ lessonCell: cellAt(LESSON_KEY_ROW, col).address,
+ columns: [],
+ };
+ blocks.push(block);
+ }
+
+ const dateCell = cellAt(DATE_ROW, col);
+ const dateValue = getCellValue(dateCell);
+ if (isEmpty(dateValue)) continue;
+ const reportDate = parseSheetDate(dateValue);
+ if (!reportDate) {
+ addError(dateCell.address, `תאריך "${dateValue}" לא תקין`);
+ continue;
+ }
+ const howManyCell = cellAt(LESSONS_COUNT_ROW, col);
+ const howManyLessons = parseSheetNumber(getCellValue(howManyCell)) ?? 1;
+ if (isNaN(howManyLessons) || howManyLessons <= 0) {
+ addError(howManyCell.address, 'מספר השיעורים אינו מספר תקין');
+ continue;
+ }
+ block.columns.push({ col, dateCell: dateCell.address, reportDate, howManyLessons });
+ }
+
+ const activeBlocks = blocks.filter((b) => b.columns.length);
+ activeBlocks.forEach((b) => {
+ if (!b.teacherTz) addError(b.teacherCell, 'חסרה ת.ז. מורה');
+ if (b.lessonKey === null) {
+ addError(b.lessonCell, isEmpty(b.lessonValue) ? 'חסר קוד שיעור' : `קוד שיעור "${b.lessonValue}" לא תקין`);
+ }
+ });
+
+ const klassValue = getCellValue(worksheet.getCell(KLASS_VALUE_CELL));
+ const klassKey = parseSheetNumber(klassValue);
+ const sheet: ParsedSheet = {
+ name: sheetName,
+ klassKey: Number.isInteger(klassKey) ? klassKey : null,
+ blocks: activeBlocks,
+ reports: [],
+ };
+ if (activeBlocks.length && sheet.klassKey === null) {
+ addError(KLASS_VALUE_CELL, isEmpty(klassValue) ? 'חסר קוד כיתה' : `קוד כיתה "${klassValue}" לא תקין`);
+ }
+
+ for (let row = FIRST_STUDENT_ROW; row <= worksheet.rowCount; row++) {
+ const studentCell = cellAt(row, STUDENT_TZ_COL);
+ const studentTz = parseTz(getCellValue(studentCell));
+ if (!studentTz) continue;
+
+ activeBlocks.forEach((b) =>
+ b.columns.forEach((column) => {
+ const cell = cellAt(row, column.col);
+ const rawValue = getCellValue(cell);
+ const absCount = parseSheetNumber(rawValue) ?? 0;
+ if (isNaN(absCount)) {
+ addError(cell.address, `הערך "${rawValue}" אינו מספר`);
+ return;
+ }
+ if (absCount > column.howManyLessons) {
+ addError(cell.address, `מספר החיסורים (${absCount}) גדול ממספר השיעורים (${column.howManyLessons})`);
+ return;
+ }
+ const reportKey = [studentTz, b.teacherTz, b.lessonKey, column.reportDate].join('|');
+ if (seenReports.has(reportKey)) {
+ addError(cell.address, 'דיווח כפול לאותה תלמידה, מורה, שיעור ותאריך');
+ return;
+ }
+ seenReports.add(reportKey);
+ sheet.reports.push({
+ cell: cell.address,
+ studentTz,
+ studentCell: studentCell.address,
+ block: b,
+ reportDate: column.reportDate,
+ howManyLessons: column.howManyLessons,
+ absCount,
+ });
+ }),
+ );
+ }
+
+ sheets.push(sheet);
+ });
+
+ return { sheets, errors };
+}
+
+const uniq = (values: T[]) => [...new Set(values.filter((v) => !isEmpty(v)))];
+
+const findByKeys = async (dataSource: DataSource, entity: any, where: any, values: any[], field: string) => {
+ if (!values.length) return [] as T[];
+ return dataSource.getRepository(entity).find({ where: { ...where, [field]: In(values) } }) as Promise;
+};
+
+const toDateKey = (value: string | Date) =>
+ value instanceof Date
+ ? toYmd(value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate())
+ : String(value).slice(0, 10);
+
+const getReportKey = (studentId: number, teacherId: number, lessonId: number, reportDate: string | Date) =>
+ [studentId, teacherId, lessonId, toDateKey(reportDate)].join('|');
+
+const getYearByDate = (reportDate: string) => {
+ const [year, month, day] = reportDate.split('-').map(Number);
+ return getHebrewYearByGregorianDate(new Date(year, month - 1, day));
+};
+
+export async function importAttendanceWorkbook(
+ dataSource: DataSource,
+ userId: number,
+ parsed: ParsedWorkbook,
+ { dryRun = false, year = getCurrentHebrewYear() } = {},
+): Promise {
+ const errors: SheetIssue[] = [...parsed.errors];
+ const warnings: SheetIssue[] = [];
+ const result = (success: boolean, created = 0, updated = 0, details: AttendanceSheetSummaryRow[] = []) => ({
+ success,
+ errors,
+ warnings,
+ created,
+ updated,
+ details,
+ });
+
+ const sheets = parsed.sheets.filter((sheet) => sheet.blocks.length);
+ if (!sheets.length && !errors.length) {
+ errors.push({ sheet: '', cell: '', message: 'לא נמצאו בקובץ עמודות עם תאריך לקליטה' });
+ }
+ const allBlocks = sheets.flatMap((sheet) => sheet.blocks);
+ const allReports = sheets.flatMap((sheet) => sheet.reports);
+
+ const [klasses, teachers, lessons, students] = await Promise.all([
+ findByKeys(dataSource, Klass, { userId, year }, uniq(sheets.map((s) => s.klassKey)), 'key'),
+ findByKeys(dataSource, Teacher, { userId }, uniq(allBlocks.map((b) => b.teacherTz)), 'tz'),
+ findByKeys(dataSource, Lesson, { userId, year }, uniq(allBlocks.map((b) => b.lessonKey)), 'key'),
+ findByKeys(dataSource, Student, { userId }, uniq(allReports.map((r) => r.studentTz)), 'tz'),
+ ]);
+ const klassByKey = new Map(klasses.map((k) => [k.key, k]));
+ const teacherByTz = new Map(teachers.map((t) => [t.tz, t]));
+ const lessonByKey = new Map(lessons.map((l) => [l.key, l]));
+ const studentByTz = new Map(students.map((s) => [s.tz, s]));
+
+ sheets.forEach((sheet) => {
+ const addError = (cell: string, message: string) => errors.push({ sheet: sheet.name, cell, message });
+ if (sheet.klassKey !== null && !klassByKey.has(sheet.klassKey)) {
+ addError(KLASS_VALUE_CELL, `קוד כיתה ${sheet.klassKey} לא קיים בשנה הנוכחית`);
+ }
+ sheet.blocks.forEach((block) => {
+ if (block.teacherTz && !teacherByTz.has(block.teacherTz)) {
+ addError(block.teacherCell, `ת.ז. מורה ${block.teacherTz} לא קיימת`);
+ }
+ if (block.lessonKey !== null && !lessonByKey.has(block.lessonKey)) {
+ addError(block.lessonCell, `קוד שיעור ${block.lessonKey} לא קיים בשנה הנוכחית`);
+ }
+ });
+ uniq(sheet.reports.map((r) => r.studentCell)).forEach((studentCell) => {
+ const report = sheet.reports.find((r) => r.studentCell === studentCell);
+ if (!studentByTz.has(report.studentTz)) {
+ addError(studentCell, `ת.ז. תלמידה ${report.studentTz} לא קיימת`);
+ }
+ });
+ });
+
+ if (errors.length) {
+ return result(false);
+ }
+ if (!allReports.length) {
+ return result(true);
+ }
+
+ const studentKlasses = await findByKeys(
+ dataSource,
+ StudentKlass,
+ { userId, year, studentReferenceId: In(students.map((s) => s.id)) },
+ klasses.map((k) => k.id),
+ 'klassReferenceId',
+ );
+ const studentKlassSet = new Set(studentKlasses.map((sk) => `${sk.studentReferenceId}|${sk.klassReferenceId}`));
+ sheets.forEach((sheet) => {
+ const klass = klassByKey.get(sheet.klassKey);
+ uniq(sheet.reports.map((r) => r.studentTz)).forEach((studentTz) => {
+ const student = studentByTz.get(studentTz);
+ if (!studentKlassSet.has(`${student.id}|${klass.id}`)) {
+ const report = sheet.reports.find((r) => r.studentTz === studentTz);
+ warnings.push({
+ sheet: sheet.name,
+ cell: report.studentCell,
+ message: `התלמידה ${student.name} (${studentTz}) לא משויכת לכיתה ${klass.name}`,
+ });
+ }
+ });
+ });
+
+ const existingReports = await dataSource.getRepository(AttReport).find({
+ where: {
+ userId,
+ studentReferenceId: In(students.map((s) => s.id)),
+ teacherReferenceId: In(teachers.map((t) => t.id)),
+ lessonReferenceId: In(lessons.map((l) => l.id)),
+ reportDate: In(uniq(allReports.map((r) => r.reportDate))) as any,
+ },
+ select: { id: true, studentReferenceId: true, teacherReferenceId: true, lessonReferenceId: true, reportDate: true },
+ });
+ const existingIdByKey = new Map();
+ existingReports.forEach((r) => {
+ const key = getReportKey(r.studentReferenceId, r.teacherReferenceId, r.lessonReferenceId, r.reportDate);
+ if (!existingIdByKey.has(key)) existingIdByKey.set(key, r.id);
+ });
+
+ const summary = new Map();
+ const toSave: Partial[] = [];
+ const rows: AttendanceSheetPreviewRow[] = [];
+ let created = 0;
+ let updated = 0;
+ sheets.forEach((sheet) => {
+ const klass = klassByKey.get(sheet.klassKey);
+ sheet.reports.forEach((report) => {
+ const student = studentByTz.get(report.studentTz);
+ const teacher = teacherByTz.get(report.block.teacherTz);
+ const lesson = lessonByKey.get(report.block.lessonKey);
+ const existingId = existingIdByKey.get(getReportKey(student.id, teacher.id, lesson.id, report.reportDate));
+
+ toSave.push({
+ ...(existingId ? { id: existingId } : {}),
+ userId,
+ year: getYearByDate(report.reportDate),
+ studentTz: student.tz,
+ studentReferenceId: student.id,
+ teacherId: teacher.tz,
+ teacherReferenceId: teacher.id,
+ klassId: klass.key,
+ klassReferenceId: klass.id,
+ lessonId: lesson.key,
+ lessonReferenceId: lesson.id,
+ reportDate: report.reportDate as any,
+ howManyLessons: report.howManyLessons,
+ absCount: report.absCount,
+ });
+
+ rows.push({
+ sheet: sheet.name,
+ cell: report.cell,
+ studentTz: student.tz,
+ studentName: student.name,
+ teacherName: teacher.name,
+ lessonName: lesson.name,
+ reportDate: report.reportDate,
+ howManyLessons: report.howManyLessons,
+ absCount: report.absCount,
+ isUpdate: Boolean(existingId),
+ });
+
+ const summaryKey = [sheet.name, teacher.id, lesson.id].join('|');
+ if (!summary.has(summaryKey)) {
+ summary.set(summaryKey, {
+ sheet: sheet.name,
+ teacherTz: teacher.tz,
+ teacherName: teacher.name,
+ lessonKey: lesson.key,
+ lessonName: lesson.name,
+ created: 0,
+ updated: 0,
+ });
+ }
+ const row = summary.get(summaryKey);
+ if (existingId) {
+ row.updated++;
+ updated++;
+ } else {
+ row.created++;
+ created++;
+ }
+ });
+ });
+
+ if (dryRun) {
+ return { ...result(true, created, updated, [...summary.values()]), rows };
+ }
+
+ // Reference ids are resolved above, so entity listeners (one DB connection per row) are skipped
+ await dataSource.transaction((manager) =>
+ manager.save(AttReport, toSave as AttReport[], { listeners: false, chunk: 500 }),
+ );
+
+ return result(true, created, updated, [...summary.values()]);
+}