diff --git a/client/src/components/ApproveFullDays.jsx b/client/src/components/ApproveFullDays.jsx new file mode 100644 index 00000000..19889241 --- /dev/null +++ b/client/src/components/ApproveFullDays.jsx @@ -0,0 +1,73 @@ +import { + useDataProvider, + useNotify, + useRefresh, + SimpleForm, + TextInput, + DateInput, + required, + maxLength, +} from 'react-admin'; +import { ActionOrDialogButton } from '@shared/components/crudContainers/ActionOrDialogButton'; +import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput'; +import { filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter'; +import { handleActionSuccess, handleError } from '@shared/utils/notifyUtil'; +import { defaultYearFilter } from '@shared/utils/yearFilter'; + +export const ApproveFullDays = ({ label }) => { + const dataProvider = useDataProvider(); + const refresh = useRefresh(); + const notify = useNotify(); + + const handleSave = async (values, onClose) => { + const row = { + studentReferenceId: values.studentReferenceId, + klassReferenceId: values.klassReferenceId, + fromDate: values.fromDate, + toDate: values.toDate, + }; + try { + const response = await dataProvider.action( + 'known_absence', + 'approveByStudentDates', + {}, + { rows: [row], reason: values.reason, senderName: values.senderName, comment: values.comment }, + ); + handleActionSuccess(notify)(response); + refresh(); + onClose?.(); + } catch (err) { + handleError(notify)(err); + } + }; + + return ( + ( + handleSave(values, onClose)}> + + + + + + + + + )} + /> + ); +}; diff --git a/client/src/components/ApprovedAbsencesUpload.jsx b/client/src/components/ApprovedAbsencesUpload.jsx index 759d740f..5062267d 100644 --- a/client/src/components/ApprovedAbsencesUpload.jsx +++ b/client/src/components/ApprovedAbsencesUpload.jsx @@ -7,6 +7,8 @@ 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 Tabs from '@mui/material/Tabs'; +import Tab from '@mui/material/Tab'; // React-Admin import { usePermissions } from 'react-admin'; @@ -17,6 +19,7 @@ import PreviewSummary from './ApprovedAbsencesUpload/PreviewSummary'; import PreviewTable from './ApprovedAbsencesUpload/PreviewTable'; import ConfigurationForm from './ApprovedAbsencesUpload/ConfigurationForm'; import ActionButtons from './ApprovedAbsencesUpload/ActionButtons'; +import StudentDatesUpload from './ApprovedAbsencesUpload/StudentDatesUpload'; // Custom Hooks import { useFileProcessor } from './ApprovedAbsencesUpload/useFileProcessor'; @@ -24,6 +27,7 @@ import { useApplyAction } from './ApprovedAbsencesUpload/useApplyAction'; const ApprovedAbsencesUpload = () => { const { permissions } = usePermissions(); + const [mode, setMode] = useState('klass'); const [loading, setLoading] = useState(false); const [previewData, setPreviewData] = useState(null); const [fileName, setFileName] = useState(''); @@ -67,48 +71,58 @@ const ApprovedAbsencesUpload = () => { העלאת חיסורים מאושרים - העלאת קובץ Excel להוספת חיסורים מאושרים עבור כיתות שלמות + העלאת קובץ Excel להוספת חיסורים מאושרים עבור כיתות שלמות או תלמידות - + setMode(value)}> + + + - {/* File Upload Section */} - - - {/* Preview Section */} - {previewData && !loading && ( + {mode === 'student' && } + {mode === 'klass' && ( <> - {/* Summary Statistics */} - - - {/* Preview Table */} - {previewData.details && previewData.details.length > 0 && ( - - - - )} - - - - {/* Configuration Form */} - - - {/* Action Buttons */} - + + {/* Preview Section */} + {previewData && !loading && ( + <> + + + {/* Summary Statistics */} + + + {/* Preview Table */} + {previewData.details && previewData.details.length > 0 && ( + + + + )} + + + + {/* Configuration Form */} + + + {/* Action Buttons */} + + + )} )} diff --git a/client/src/components/ApprovedAbsencesUpload/ConfigurationForm.jsx b/client/src/components/ApprovedAbsencesUpload/ConfigurationForm.jsx index 2e531727..eeabb8c9 100644 --- a/client/src/components/ApprovedAbsencesUpload/ConfigurationForm.jsx +++ b/client/src/components/ApprovedAbsencesUpload/ConfigurationForm.jsx @@ -1,11 +1,11 @@ -import { Form, TextInput } from 'react-admin'; import Box from '@mui/material/Box'; import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; import Typography from '@mui/material/Typography'; const ConfigurationForm = ({ configValues, onChange }) => { - const handleFormChange = (values) => { - onChange(values); + const handleChange = (event) => { + onChange({ ...configValues, [event.target.name]: event.target.value }); }; return ( @@ -13,16 +13,28 @@ const ConfigurationForm = ({ configValues, onChange }) => { שלב 2: הגדרות -
{}} onChange={handleFormChange}> - - - - - - הערה: תאריך ומספר חיסורים יילקחו מהדיווח המקורי - - -
+ + + + + + הערה: תאריך ומספר חיסורים יילקחו מהדיווח המקורי + + ); }; diff --git a/client/src/components/ApprovedAbsencesUpload/StudentDatesUpload.jsx b/client/src/components/ApprovedAbsencesUpload/StudentDatesUpload.jsx new file mode 100644 index 00000000..1da8ae93 --- /dev/null +++ b/client/src/components/ApprovedAbsencesUpload/StudentDatesUpload.jsx @@ -0,0 +1,198 @@ +import { useCallback, useRef, useState } from 'react'; +import { + Button, + Datagrid, + FunctionField, + ListContextProvider, + ResourceContextProvider, + useDataProvider, + useList, + useNotify, + useRecordContext, +} from 'react-admin'; +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Divider from '@mui/material/Divider'; +import Chip from '@mui/material/Chip'; +import Typography from '@mui/material/Typography'; +import CircularProgress from '@mui/material/CircularProgress'; +import FileUploadIcon from '@mui/icons-material/FileUpload'; +import CheckCircleIcon from '@mui/icons-material/CheckCircle'; +import ErrorIcon from '@mui/icons-material/Error'; +import { ExcelImportInput } from '@shared/components/import/ExcelImportInput'; +import { handleActionSuccess, handleError } from '@shared/utils/notifyUtil'; +import PreviewSummary from './PreviewSummary'; +import ConfigurationForm from './ConfigurationForm'; +import ActionButtons from './ActionButtons'; + +const defaultConfigValues = { reason: '', senderName: '', comment: '' }; + +const ExpandedRow = () => { + const record = useRecordContext(); + if (!record?.reports?.length) return null; + return ( + + + {record.reports.map((report) => ( + + ))} + + + ); +}; + +const PreviewTable = ({ data }) => { + const listContext = useList({ data: data.map((item) => ({ id: item.index, ...item })) }); + return ( + + + }> + + record.error ? : + } + /> + record.row.studentTz ?? ''} /> + record.studentName || 'לא נמצאה'} /> + record.klassName || record.row.klassId || ''} /> + [record.row.fromDate, record.row.toDate].filter(Boolean).join(' - ')} + /> + record.reports.length} /> + record.alreadyApprovedCount} /> + record.error || '-'} /> + + + + ); +}; + +const StudentDatesUpload = () => { + const dataProvider = useDataProvider(); + const notify = useNotify(); + const fileInputRef = useRef(); + const [loading, setLoading] = useState(false); + const [fileName, setFileName] = useState(''); + const [rows, setRows] = useState(null); + const [previewData, setPreviewData] = useState(null); + const [configValues, setConfigValues] = useState(defaultConfigValues); + + const resetForm = () => { + setFileName(''); + setRows(null); + setPreviewData(null); + setConfigValues(defaultConfigValues); + }; + + const handleFileUpload = useCallback( + async ({ name, data }) => { + setFileName(name); + const validRows = data.filter((row) => row.studentTz && row.fromDate); + if (validRows.length === 0) { + notify('הקובץ ריק או לא מכיל שורות תקינות', { type: 'error' }); + return; + } + try { + setLoading(true); + const { json: details } = await dataProvider.action( + 'known_absence', + 'previewByStudentDates', + {}, + { rows: validRows }, + ); + const matched = details.filter((item) => item.reports.length > 0).length; + setRows(validRows); + setPreviewData({ + total: validRows.length, + matched, + notMatched: details.length - matched, + details, + }); + } catch (error) { + handleError(notify)(error); + } finally { + setLoading(false); + } + }, + [dataProvider, notify], + ); + + const handleApply = async () => { + try { + setLoading(true); + const response = await dataProvider.action( + 'known_absence', + 'approveByStudentDates', + {}, + { rows, ...configValues }, + ); + handleActionSuccess(notify)(response); + resetForm(); + } catch (error) { + handleError(notify)(error); + } finally { + setLoading(false); + } + }; + + return ( + + + + שלב 1: בחירת קובץ + + + + + {fileName && ( + + קובץ נבחר: {fileName} + + )} + {loading && } + + + הקובץ צריך לכלול עמודות: ת.ז. תלמידה, מספר כיתה (לא חובה), תאריך, עד תאריך (לא חובה). כל החיסורים של + התלמידה בימים אלו יאושרו. + + + + {previewData && !loading && ( + <> + + + + + + + + )} + + ); +}; + +export default StudentDatesUpload; diff --git a/client/src/entities/known-absence.jsx b/client/src/entities/known-absence.jsx index 28ff8899..8fe0ffd0 100644 --- a/client/src/entities/known-absence.jsx +++ b/client/src/entities/known-absence.jsx @@ -25,6 +25,7 @@ import { defaultYearFilter } from '@shared/utils/yearFilter'; import { CommonYearField, CommonYearInput, CommonYearInputFilter } from '@shared/components/fields/CommonYear'; import { CommonHebrewDateField } from '@shared/components/fields/CommonHebrewDateField'; import { BulkApproveAbsences } from 'src/components/BulkApproveAbsences'; +import { ApproveFullDays } from 'src/components/ApproveFullDays'; import { commonAdminFilters } from '@shared/components/fields/PermissionFilter'; import { BulkEditButton } from '@shared/components/crudContainers/BulkEditButton'; import { useIsAbsenceType } from 'src/utils/appPermissions'; @@ -188,6 +189,7 @@ const importer = { const additionalListActions = [ , + , ]; const entity = { diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js index 6d8cad57..55a9e8ea 100644 --- a/client/src/roadmapFeatures.js +++ b/client/src/roadmapFeatures.js @@ -40,5 +40,5 @@ export default [ { html: 'תלמידה שסומנה "לא פעילה" לא מופיעה יותר בדיווח שיעור חדש, בדיווח טלפוני ובקובץ הדיווח למורה (הנתונים הקודמים שלה נשמרים)', status: 'בוצע', statusColor: 'success' }, { html: 'עריכה מרוכזת בדיווחי נוכחות, ציונים, חיסורים מאושרים, תלמידות, שיעורים ומורות: מסמנים שורות ומעדכנים שדות נבחרים בכולן יחד (שדה ריק לא משתנה)', status: 'בוצע', statusColor: 'success' }, { html: 'דפי העזרה במערכת עודכנו ונכתבו מחדש, וכל הדפים מוצגים ברשימת העזרה', status: 'בוצע', statusColor: 'success' }, - { html: 'חיסורים מאושרים לפי תלמידה או ליום שלם', status: 'בתהליך', statusColor: 'warning' }, + { html: 'אישור חיסורים לפי תלמידה וטווח תאריכים: טופס "אישור ימים מלאים" והעלאת קובץ לפי ת.ז. ותאריך', status: 'בוצע', statusColor: 'success' }, ].reverse(); diff --git a/server/src/entity-modules/known-absence.config.ts b/server/src/entity-modules/known-absence.config.ts index aa9ec611..20373b5b 100644 --- a/server/src/entity-modules/known-absence.config.ts +++ b/server/src/entity-modules/known-absence.config.ts @@ -1,7 +1,15 @@ import { CrudRequest } from '@dataui/crud'; -import { BaseEntityModuleOptions } from '@shared/base-entity/interface'; +import { getUserIdFromUser } from '@shared/auth/auth.util'; +import { BaseEntityService } from '@shared/base-entity/base-entity.service'; +import { validateBulk } from '@shared/base-entity/base-entity.util'; +import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface'; import { IHeader } from '@shared/utils/exporter/types'; import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity'; +import { + buildKnownAbsences, + findAbsencesByStudentDates, + StudentDatesRow, +} from 'src/utils/approveAbsencesByStudentDates.util'; function getConfig(): BaseEntityModuleOptions { return { @@ -49,7 +57,31 @@ function getConfig(): BaseEntityModuleOptions { ]; }, }, + service: KnownAbsenceService, }; } +class KnownAbsenceService extends BaseEntityService { + async doAction(req: CrudRequest, body: any): Promise { + switch (req.parsed.extra.action) { + // body.rows: [{ studentTz | studentReferenceId, klassId?, fromDate, toDate? }] + case 'previewByStudentDates': + return findAbsencesByStudentDates(this.dataSource, getUserIdFromUser(req.auth), getRows(body)); + case 'approveByStudentDates': { + const matches = await findAbsencesByStudentDates(this.dataSource, getUserIdFromUser(req.auth), getRows(body)); + const knownAbsences = buildKnownAbsences(matches, body ?? {}); + if (knownAbsences.length === 0) return 'לא נמצאו חיסורים לאישור'; + await validateBulk(knownAbsences, KnownAbsence); + await this.dataSource.getRepository(KnownAbsence).insert(knownAbsences); + return `נוצרו ${knownAbsences.length} חיסורים מאושרים`; + } + } + return super.doAction(req, body); + } +} + +function getRows(body: any): StudentDatesRow[] { + return Array.isArray(body?.rows) ? body.rows : []; +} + export default getConfig(); diff --git a/server/src/utils/__tests__/approveAbsencesByStudentDates.util.spec.ts b/server/src/utils/__tests__/approveAbsencesByStudentDates.util.spec.ts new file mode 100644 index 00000000..08795460 --- /dev/null +++ b/server/src/utils/__tests__/approveAbsencesByStudentDates.util.spec.ts @@ -0,0 +1,128 @@ +import { Student } from 'src/db/entities/Student.entity'; +import { Klass } from 'src/db/entities/Klass.entity'; +import { AttReport } from 'src/db/entities/AttReport.entity'; +import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity'; +import { buildKnownAbsences, findAbsencesByStudentDates, toDateStr } from '../approveAbsencesByStudentDates.util'; + +function makeDataSource({ student = null, klass = null, reports = [], approved = [] }: any) { + const repos = new Map([ + [Student, { findOne: jest.fn().mockResolvedValue(student) }], + [Klass, { findOne: jest.fn().mockResolvedValue(klass) }], + [AttReport, { find: jest.fn().mockResolvedValue(reports) }], + [KnownAbsence, { find: jest.fn().mockResolvedValue(approved) }], + ]); + return { dataSource: { getRepository: (entity: any) => repos.get(entity) } as any, repos }; +} + +const student = { id: 7, userId: 3, name: 'רחל' }; + +describe('toDateStr', () => { + it('keeps YYYY-MM-DD and normalizes dates', () => { + expect(toDateStr('2026-10-18')).toBe('2026-10-18'); + expect(toDateStr(new Date(2026, 9, 18))).toBe('2026-10-18'); + expect(toDateStr('10/03/2026')).toBe('2026-03-10'); + expect(toDateStr('5.3.2026')).toBe('2026-03-05'); + expect(toDateStr('not a date')).toBeNull(); + expect(toDateStr(undefined)).toBeNull(); + }); +}); + +describe('findAbsencesByStudentDates', () => { + it('returns the student absences in range, skipping already approved lesson+date', async () => { + const reports = [ + { id: 1, userId: 3, studentReferenceId: 7, lessonReferenceId: 10, reportDate: '2026-10-18', absCount: 1 }, + { id: 2, userId: 3, studentReferenceId: 7, lessonReferenceId: 11, reportDate: '2026-10-18', absCount: 2 }, + ]; + const approved = [{ lessonReferenceId: 10, reportDate: '2026-10-18' }]; + const { dataSource, repos } = makeDataSource({ student, reports, approved }); + + const [result] = await findAbsencesByStudentDates(dataSource, 3, [{ studentTz: 12345678, fromDate: '2026-10-18' }]); + + expect(result.error).toBeUndefined(); + expect(result.studentName).toBe('רחל'); + expect(result.reports.map((r) => r.id)).toEqual([2]); + expect(result.alreadyApprovedCount).toBe(1); + const studentWhere = repos.get(Student).findOne.mock.calls[0][0].where; + expect(studentWhere.userId).toBe(3); + expect(studentWhere.tz.value).toEqual(['12345678', '012345678']); + expect(repos.get(Klass).findOne).not.toHaveBeenCalled(); + }); + + it('filters by klass when given', async () => { + const { dataSource, repos } = makeDataSource({ student, klass: { id: 20, name: 'י1' } }); + + const [result] = await findAbsencesByStudentDates(dataSource, 3, [ + { studentReferenceId: 7, klassId: '5', fromDate: '2026-10-18', toDate: '2026-10-20' }, + ]); + + expect(result.klassName).toBe('י1'); + expect(repos.get(AttReport).find.mock.calls[0][0].where.klassReferenceId).toBe(20); + expect(result.error).toBe('לא נמצאו חיסורים בתאריכים אלו'); + }); + + it('looks up the klass by id when klassReferenceId is given', async () => { + const { dataSource, repos } = makeDataSource({ student, klass: { id: 21, name: 'י2' } }); + + await findAbsencesByStudentDates(dataSource, 3, [ + { studentReferenceId: 7, klassReferenceId: 21, fromDate: '2026-10-18' }, + ]); + + expect(repos.get(Klass).findOne.mock.calls[0][0].where).toEqual({ userId: 3, id: 21 }); + expect(repos.get(AttReport).find.mock.calls[0][0].where.klassReferenceId).toBe(21); + }); + + it('reports row errors', async () => { + const { dataSource } = makeDataSource({ student: null }); + const results = await findAbsencesByStudentDates(dataSource, 3, [ + { studentTz: '1', fromDate: '' }, + { studentTz: '1', fromDate: '2026-10-20', toDate: '2026-10-18' }, + { studentTz: '1', fromDate: '2026-10-18' }, + ]); + expect(results.map((r) => r.error)).toEqual([ + 'תאריך חסר או לא תקין', + 'תאריך הסיום לפני תאריך ההתחלה', + 'תלמידה לא נמצאה במערכת', + ]); + }); + + it('errors when the klass is not found', async () => { + const { dataSource } = makeDataSource({ student, klass: null }); + const [result] = await findAbsencesByStudentDates(dataSource, 3, [ + { studentReferenceId: 7, klassId: 99, fromDate: '2026-10-18' }, + ]); + expect(result.error).toBe('כיתה לא נמצאה במערכת'); + }); +}); + +describe('buildKnownAbsences', () => { + it('creates one approved known absence per report', () => { + const report = { + userId: 3, + studentReferenceId: 7, + klassReferenceId: 20, + lessonReferenceId: 10, + reportDate: '2026-10-18', + absCount: 2, + year: 5787, + } as any; + const result = buildKnownAbsences( + [{ index: 0, row: { fromDate: '2026-10-18' }, reports: [report], alreadyApprovedCount: 0 }], + { reason: 'חתונת אח' }, + ); + expect(result).toEqual([ + { + userId: 3, + studentReferenceId: 7, + klassReferenceId: 20, + lessonReferenceId: 10, + reportDate: '2026-10-18', + absnceCount: 2, + reason: 'חתונת אח', + senderName: null, + comment: null, + isApproved: true, + year: 5787, + }, + ]); + }); +}); diff --git a/server/src/utils/approveAbsencesByStudentDates.util.ts b/server/src/utils/approveAbsencesByStudentDates.util.ts new file mode 100644 index 00000000..e55cabcb --- /dev/null +++ b/server/src/utils/approveAbsencesByStudentDates.util.ts @@ -0,0 +1,161 @@ +import { Between, DataSource, In, MoreThan } from 'typeorm'; +import { getHebrewYearByGregorianDate } from '@shared/utils/entity/year.util'; +import { Student } from 'src/db/entities/Student.entity'; +import { Klass } from 'src/db/entities/Klass.entity'; +import { AttReport } from 'src/db/entities/AttReport.entity'; +import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity'; + +export interface StudentDatesRow { + studentTz?: string | number; + studentReferenceId?: number; + klassId?: string | number; + klassReferenceId?: number; + fromDate: string; + toDate?: string; +} + +export interface StudentDatesMatch { + index: number; + row: StudentDatesRow; + studentName?: string; + klassName?: string; + reports: AttReport[]; + alreadyApprovedCount: number; + error?: string; +} + +export interface KnownAbsenceExtraFields { + reason?: string; + senderName?: string; + comment?: string; +} + +// Normalizes a date (Date, ISO string, 'YYYY-MM-DD' or Israeli 'DD/MM/YYYY') to 'YYYY-MM-DD', or null when invalid. +export function toDateStr(value: Date | string | undefined | null): string | null { + if (!value) return null; + if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value; + const dayFirst = typeof value === 'string' && value.trim().match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/); + const date = dayFirst ? new Date(Number(dayFirst[3]), Number(dayFirst[2]) - 1, Number(dayFirst[1])) : new Date(value); + if (isNaN(date.getTime())) return null; + const pad = (n: number) => String(n).padStart(2, '0'); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; +} + +/** + * For each row (student + date range, optional klass), finds the student's + * att_reports with absences in that range, leaving out the ones that already + * have an approved known absence for the same lesson and date. + * userId undefined means admin: the student is looked up across all users. + */ +export async function findAbsencesByStudentDates( + dataSource: DataSource, + userId: number | undefined, + rows: StudentDatesRow[], +): Promise { + const results: StudentDatesMatch[] = []; + for (const [index, row] of rows.entries()) { + results.push(await findRowAbsences(dataSource, userId, row, index)); + } + return results; +} + +async function findRowAbsences( + dataSource: DataSource, + userId: number | undefined, + row: StudentDatesRow, + index: number, +): Promise { + const result: StudentDatesMatch = { index, row, reports: [], alreadyApprovedCount: 0 }; + + const fromDate = toDateStr(row.fromDate); + const toDate = toDateStr(row.toDate) ?? fromDate; + if (!fromDate || !toDate) { + return { ...result, error: 'תאריך חסר או לא תקין' }; + } + if (toDate < fromDate) { + return { ...result, error: 'תאריך הסיום לפני תאריך ההתחלה' }; + } + + const student = await findStudent(dataSource, userId, row); + if (!student) { + return { ...result, error: 'תלמידה לא נמצאה במערכת' }; + } + result.studentName = student.name; + + let klassReferenceId: number | undefined; + const hasKlassKey = row.klassId !== undefined && row.klassId !== null && String(row.klassId).trim() !== ''; + if (row.klassReferenceId || hasKlassKey) { + const klass = await dataSource.getRepository(Klass).findOne({ + where: row.klassReferenceId + ? { userId: student.userId, id: Number(row.klassReferenceId) } + : { + userId: student.userId, + key: Number(row.klassId), + year: getHebrewYearByGregorianDate(new Date(fromDate)), + }, + }); + if (!klass) { + return { ...result, error: 'כיתה לא נמצאה במערכת' }; + } + klassReferenceId = klass.id; + result.klassName = klass.name; + } + + const reportDate = Between(fromDate, toDate) as any; + const reports = await dataSource.getRepository(AttReport).find({ + where: { + userId: student.userId, + studentReferenceId: student.id, + reportDate, + absCount: MoreThan(0), + ...(klassReferenceId ? { klassReferenceId } : {}), + }, + relations: { lesson: true }, + order: { reportDate: 'ASC' }, + }); + const approved = await dataSource.getRepository(KnownAbsence).find({ + where: { userId: student.userId, studentReferenceId: student.id, reportDate, isApproved: true }, + }); + const approvedKeys = new Set(approved.map((item) => `${item.lessonReferenceId}_${toDateStr(item.reportDate)}`)); + + result.reports = reports.filter( + (report) => !approvedKeys.has(`${report.lessonReferenceId}_${toDateStr(report.reportDate)}`), + ); + result.alreadyApprovedCount = reports.length - result.reports.length; + if (reports.length === 0) { + result.error = 'לא נמצאו חיסורים בתאריכים אלו'; + } + return result; +} + +function findStudent(dataSource: DataSource, userId: number | undefined, row: StudentDatesRow): Promise { + const userFilter = userId ? { userId } : {}; + if (row.studentReferenceId) { + return dataSource.getRepository(Student).findOne({ where: { id: Number(row.studentReferenceId), ...userFilter } }); + } + const tz = String(row.studentTz ?? '').trim(); + if (!tz) return Promise.resolve(null); + // Excel drops leading zeros from ids, so match both the raw and the 9-digit padded value. + return dataSource.getRepository(Student).findOne({ where: { tz: In([tz, tz.padStart(9, '0')]), ...userFilter } }); +} + +export function buildKnownAbsences( + matches: StudentDatesMatch[], + extra: KnownAbsenceExtraFields, +): Array> { + return matches.flatMap((match) => + match.reports.map((report) => ({ + userId: report.userId, + studentReferenceId: report.studentReferenceId, + klassReferenceId: report.klassReferenceId, + lessonReferenceId: report.lessonReferenceId, + reportDate: report.reportDate, + absnceCount: Math.round(report.absCount), + reason: extra.reason || null, + senderName: extra.senderName || null, + comment: extra.comment || null, + isApproved: true, + year: report.year, + })), + ); +}