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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 119 additions & 53 deletions client/src/components/StudentView/student-event-report.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Loading loadingPrimary="טוען שדות..." />;
if (!absenceType?.requiredLabels?.length) return null;
return (
<div style={{ padding: '10px 0', width: '100%', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{absenceType.requiredLabels.map((label, index) => (
{absenceType.requiredLabels.map((label) => (
<TextInput
key={`${absenceType.id}-${label}`}
source={`dynamic_${label}`}
Expand All @@ -40,35 +43,21 @@ const DynamicFields = ({ absenceType, isLoading }) => {
);
};

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
};
};

Expand All @@ -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();
Expand All @@ -121,22 +157,52 @@ const StudentEventReport = (props) => {
};

return (
<Create resource="known_absence" {...props} {...props} title="הוספת דיווח אירוע">
<SimpleForm onSubmit={handleSave} sanitizeEmptyValues>
<CommonReferenceInput source="klassReferenceId" reference="klass" validate={required()} dynamicFilter={filterByUserIdAndYear} />
<CommonReferenceInput source="absenceTypeId" reference="absence_type" dynamicFilter={filterByUserIdAndYear} validate={required()}
onChange={(e) => setSelectedAbsenceTypeId(e?.target?.value ?? e)} />
<FormDataConsumer>
{() => (
<DynamicFields absenceType={absenceType} isLoading={isLoading} />
)}
</FormDataConsumer>
<DateInput source="reportDate" validate={required()} defaultValue={new Date()} />
<NumberInput source="absnceCount" defaultValue={1} min={0} step={0.5} />
<TextInput source="senderName" />
<TextInput source="reason" multiline fullWidth />
<Create resource="known_absence" {...props} title="הוספת דיווח אירוע">
<SimpleForm onSubmit={handleSave} sanitizeEmptyValues defaultValues={{ reports: [{}] }}>
<CommonReferenceInput source="absenceTypeId" reference="absence_type" dynamicFilter={filterByUserIdAndYear} validate={required()} onChange={(e) => setSelectedAbsenceTypeId(e?.target?.value ?? e)} />
{absenceType?.quota !== undefined && (
<div style={{ backgroundColor: '#f0f8ff', padding: '12px', borderRadius: '8px', marginBottom: '16px', color: '#005b9f' }}>
<strong>שימי לב:</strong> המכסה השנתית לאירוע זה היא {absenceType.quota} ימים. עד כה ניצלת {utilizedDays} ימים. באפשרותך לדווח על {Math.max(0, absenceType.quota - utilizedDays)} ימים במקביל. מלאי את השדות הנדרשים מטה.
</div>
)}
<DynamicFields absenceType={absenceType} isLoading={isLoading} />

<ArrayInput source="reports" label="פירוט היעדרויות">
<SimpleFormIterator disableReordering>
<DateInput source="reportDate" label="תאריך החיסור" validate={required()} />

<div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start', width: '100%' }}>
<div style={{ flex: 1 }}>
<CommonReferenceInput source="homeroomKlassId" label="כיתת אם" reference="klass" validate={required()} dynamicFilter={filterByUserIdAndYear} />
</div>
<div style={{ flex: 1 }}>
<NumberInput source="homeroomAbsnceCount" label="שעות היעדרות" validate={required()} defaultValue={0} min={0} step={1} />
</div>
</div>

<div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start', width: '100%' }}>
<div style={{ flex: 1 }}>
<CommonReferenceInput source="specializationKlassId" label="כיתת התמחות (אופציונלי)" reference="klass" dynamicFilter={filterByUserIdAndYear} />
</div>
<div style={{ flex: 1 }}>
<NumberInput source="specializationAbsnceCount" label="שעות היעדרות" defaultValue={0} min={0} step={1} />
</div>
</div>

<div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start', width: '100%' }}>
<div style={{ flex: 1 }}>
<CommonReferenceInput source="extraKlassId" label="כיתת התמחות 2 (אופציונלי)" reference="klass" dynamicFilter={filterByUserIdAndYear} />
</div>
<div style={{ flex: 1 }}>
<NumberInput source="extraAbsnceCount" label="שעות היעדרות" defaultValue={0} min={0} step={1} />
</div>
</div>
</SimpleFormIterator>
</ArrayInput>

<CommonAutocompleteInput source="year" choices={yearChoices} defaultValue={defaultYearFilter.year} disabled />
<BooleanInput source="isApproved" defaultValue={true} disabled />
<SignatureInput source="signatureData" validate={[required()]} label='אני מאשרת כי המידע המוצג בדו"ח זה אמין ומדויק, וכי סיבת ההיעדרות המצוינת היא הסיבה בפועל.' />
</SimpleForm>
</Create>
);
Expand Down
22 changes: 15 additions & 7 deletions server/src/yemot-handler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class YemotHandlerService extends BaseYemotHandlerService {
override async processCall(): Promise<void> {
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) {
Expand All @@ -35,15 +35,23 @@ export class YemotHandlerService extends BaseYemotHandlerService {
}
}

private async getStudentByPhone(): Promise<Student> {
private async getStudentByInput(): Promise<Student> {
let student = null;
while (!student) {
student = await this.getStudentByTz();

if (!student) {
await this.sendMessage('מספר תז לא תקין נסי שוב');
}
}
return student;
}
private async getStudentByTz(): Promise<Student> {
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('הטלפון לא קיים במערכת');
Comment thread
buzz-code marked this conversation as resolved.
Resolved
return null
}
return student;
}

Expand Down
Loading