diff --git a/client/src/components/StudentView/student-event-report.jsx b/client/src/components/StudentView/student-event-report.jsx index 79f1dfb0..465a0c6e 100644 --- a/client/src/components/StudentView/student-event-report.jsx +++ b/client/src/components/StudentView/student-event-report.jsx @@ -9,25 +9,28 @@ import { useResetStore, useDataProvider, useGetOne, + useGetList, Create, SimpleForm, FormDataConsumer, Loading, + ArrayInput, + SimpleFormIterator } from 'react-admin'; import { filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter'; import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput'; import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter'; import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput'; import { handleActionSuccess, handleError } from '@shared/utils/notifyUtil'; +import SignatureInput from '@shared/components/fields/signature/SignatureInput'; import { useObjectStore } from "src/utils/storeUtil"; const DynamicFields = ({ absenceType, isLoading }) => { - if (isLoading) return ; if (!absenceType?.requiredLabels?.length) return null; return (
- {absenceType.requiredLabels.map((label, index) => ( + {absenceType.requiredLabels.map((label) => ( { ); }; -const formatPayload = (values, userId, studentId, absenceType) => { +const extractBasePayload = (rootValues, reportValues, userId, studentId, absenceType) => { const allowedLabels = absenceType?.requiredLabels || []; - - const extraInfo = Object.keys(values) - .filter(key => { - if (!key.startsWith('dynamic_')) return false; - const label = key.replace('dynamic_', ''); - return allowedLabels.includes(label) && values[key]; - }) - .map(key => { - const label = key.replace('dynamic_', ''); - return `${label}: ${values[key]}`; - }) + const extraInfo = Object.keys(rootValues) + .filter(key => key.startsWith('dynamic_') && allowedLabels.includes(key.replace('dynamic_', '')) && rootValues[key]) + .map(key => `${key.replace('dynamic_', '')}: ${rootValues[key]}`) .join(' | '); - const cleanValues = { ...values }; - Object.keys(cleanValues).forEach(key => { - if (key.startsWith('dynamic_')) delete cleanValues[key]; - }); - return { - ...cleanValues, userId: userId, studentReferenceId: studentId, - year: parseInt(defaultYearFilter.year), - reportDate: cleanValues.reportDate, - absnceCount: parseFloat(cleanValues.absnceCount) || 1, + year: defaultYearFilter.year, + reportDate: reportValues.reportDate, isApproved: true, - reason: cleanValues.reason ? `${cleanValues.reason} [${extraInfo}]` : extraInfo, + reason: extraInfo || "", + absenceTypeId: rootValues.absenceTypeId }; }; @@ -78,40 +67,87 @@ const StudentEventReport = (props) => { const reset = useResetStore(); const { value: student, clear } = useObjectStore("student"); const [selectedAbsenceTypeId, setSelectedAbsenceTypeId] = React.useState(null); + const { data: absenceType, isLoading } = useGetOne( 'absence_type', { id: selectedAbsenceTypeId }, { enabled: !!selectedAbsenceTypeId } ); + const { data: existingAbsences } = useGetList( + 'known_absence', + { + pagination: { page: 1, perPage: 1000 }, + filter: { + studentReferenceId: student?.id, + absenceTypeId: selectedAbsenceTypeId, + year: defaultYearFilter.year + } + }, + { enabled: !!selectedAbsenceTypeId && !!student?.id } + ); + + const uniqueDates = React.useMemo(() => { + const datesSet = new Set(); + existingAbsences?.forEach(item => { + datesSet.add(new Date(item.reportDate).toISOString().split('T')[0]); + }); + + return datesSet; + }, [existingAbsences]); + const utilizedDays = uniqueDates.size; + const handleSave = async (values) => { try { - const quota = absenceType?.quota; + const reports = values.reports || []; + if (reports.length === 0) { + notify("יש להזין לפחות דיווח אחד", { type: 'warning' }); + return; + } + const quota = absenceType?.quota; if (quota) { - const { data: existingAbsences } = await dataProvider.getList('known_absence', { - pagination: { page: 1, perPage: 1000 }, - filter: { - studentReferenceId: student.id, - absenceTypeId: values.absenceTypeId, - year: values.year - }, + const newDates = new Set(uniqueDates); + reports.forEach(report => { + newDates.add(new Date(report.reportDate).toISOString().split('T')[0]); }); - const currentTotal = existingAbsences.reduce((sum, item) => sum + (parseFloat(item.absnceCount) || 0), 0); - const requestedAmount = parseFloat(values.absnceCount || 1); - - if (currentTotal + requestedAmount > quota) { + if (newDates.size > quota) { notify( - `חריגה מהמכסה! המכסה היא ${quota}. נוצלו ${currentTotal}, ניסיון להוסיף ${requestedAmount}.`, + `חריגה מהמכסה! המכסה היא ${quota} ימים. עם הדיווחים החדשים את מנסה לנצל ${newDates.size} ימים שונים.`, { type: 'error', autoHideDuration: 10000 } ); return; } } - const formattedData = formatPayload(values, student.userId, student.id, absenceType) - const response = await dataProvider.create('known_absence', { data: formattedData }); + let payloadsToCreate = []; + + const addPayloadIfValid = (base, klassId, count) => { + const parsedCount = parseFloat(count); + if (klassId && parsedCount > 0) { + payloadsToCreate.push({ + ...base, + klassReferenceId: klassId, + absnceCount: parsedCount + }); + } + }; + + reports.forEach(report => { + const basePayload = extractBasePayload(values, report, student.userId, student.id, absenceType); + + addPayloadIfValid(basePayload, report.homeroomKlassId, report.homeroomAbsnceCount); + addPayloadIfValid(basePayload, report.specializationKlassId, report.specializationAbsnceCount); + addPayloadIfValid(basePayload, report.extraKlassId, report.extraAbsnceCount); + }); + + if (payloadsToCreate.length === 0) { + notify("יש להזין שעות היעדרות לפחות עבור כיתה אחת באחד הדיווחים", { type: 'warning' }); + return; + } + + const response = await dataProvider.createMany('known_absence', payloadsToCreate); handleActionSuccess(notify)(response); clear(); reset(); @@ -121,22 +157,52 @@ const StudentEventReport = (props) => { }; return ( - - - - setSelectedAbsenceTypeId(e?.target?.value ?? e)} /> - - {() => ( - - )} - - - - - + + + setSelectedAbsenceTypeId(e?.target?.value ?? e)} /> + {absenceType?.quota !== undefined && ( +
+ שימי לב: המכסה השנתית לאירוע זה היא {absenceType.quota} ימים. עד כה ניצלת {utilizedDays} ימים. באפשרותך לדווח על {Math.max(0, absenceType.quota - utilizedDays)} ימים במקביל. מלאי את השדות הנדרשים מטה. +
+ )} + + + + + + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ +
); diff --git a/server/src/yemot-handler.service.ts b/server/src/yemot-handler.service.ts index 023f7372..ddc3e267 100644 --- a/server/src/yemot-handler.service.ts +++ b/server/src/yemot-handler.service.ts @@ -16,7 +16,7 @@ export class YemotHandlerService extends BaseYemotHandlerService { override async processCall(): Promise { await this.getUserByDidPhone(); this.logger.log(`Processing call with ID: ${this.call.callId} from phone: ${this.call.phone}`); - const student = await this.getStudentByPhone() + const student = await this.getStudentByInput() if (!student) return; const alreadyReported = await this.hasReportedToday(student.id); if (alreadyReported) { @@ -35,15 +35,23 @@ export class YemotHandlerService extends BaseYemotHandlerService { } } - private async getStudentByPhone(): Promise { + private async getStudentByInput(): Promise { + let student = null; + while (!student) { + student = await this.getStudentByTz(); + + if (!student) { + await this.sendMessage('מספר תז לא תקין נסי שוב'); + } + } + return student; + } + private async getStudentByTz(): Promise { + const tz = await this.askForInput('הקישי מספר תז'); const student = await this.dataSource.getRepository(Student).findOneBy({ userId: this.user.id, - phone: this.call.phone, + tz: tz, }); - if (!student) { - await this.hangupWithMessage('הטלפון לא קיים במערכת'); - return null - } return student; }