-
שימי לב: המכסה השנתית לאירוע זה היא {absenceType.quota} ימים. עד כה ניצלת {utilizedDays} ימים. באפשרותך לדווח על {Math.max(0, absenceType.quota - utilizedDays)} ימים במקביל. מלאי את השדות הנדרשים מטה.
+
+ שימי לב: המכסה השנתית לאירוע זה היא {absenceType.quota} ימים. עד כה ניצלת{' '}
+ {utilizedDays} ימים. באפשרותך לדווח על {Math.max(0, absenceType.quota - utilizedDays)} ימים
+ במקביל. מלאי את השדות הנדרשים מטה.
)}
@@ -184,8 +203,11 @@ const StudentEventReport = (props) => {
מספר שיעורי חיסור בכל כיתה:
- {studentKlasses?.map(sk => (
-
+ {studentKlasses?.map((sk) => (
+
{
-
+
-
+
);
};
-export default StudentEventReport;
\ No newline at end of file
+export default StudentEventReport;
diff --git a/client/src/components/TeacherView/TeacherAccess.jsx b/client/src/components/TeacherView/TeacherAccess.jsx
index 56cffb33..5a038de0 100644
--- a/client/src/components/TeacherView/TeacherAccess.jsx
+++ b/client/src/components/TeacherView/TeacherAccess.jsx
@@ -1,118 +1,108 @@
-import React from "react";
-import { useDataProvider, SimpleForm, TextInput, useNotify, Toolbar, SaveButton, useResetStore } from "react-admin";
-import { useObjectStore } from "src/utils/storeUtil";
-import Button from "@mui/material/Button";
-import Card from "@mui/material/Card";
-import CardContent from "@mui/material/CardContent";
-import Box from "@mui/material/Box";
-import Typography from "@mui/material/Typography";
-import Avatar from "@mui/material/Avatar";
-import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
-import LogoutIcon from "@mui/icons-material/Logout";
-import Paper from "@mui/material/Paper";
+import React from 'react';
+import { useDataProvider, SimpleForm, TextInput, useNotify, Toolbar, SaveButton, useResetStore } from 'react-admin';
+import { useObjectStore } from 'src/utils/storeUtil';
+import Button from '@mui/material/Button';
+import Card from '@mui/material/Card';
+import CardContent from '@mui/material/CardContent';
+import Box from '@mui/material/Box';
+import Typography from '@mui/material/Typography';
+import Avatar from '@mui/material/Avatar';
+import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
+import LogoutIcon from '@mui/icons-material/Logout';
+import Paper from '@mui/material/Paper';
export const TeacherGuard = ({ children }) => {
- const dataProvider = useDataProvider();
- const notify = useNotify();
- const reset = useResetStore();
- const { value: teacher, set: setTeacher, clear } = useObjectStore("teacher");
+ const dataProvider = useDataProvider();
+ const notify = useNotify();
+ const reset = useResetStore();
+ const { value: teacher, set: setTeacher, clear } = useObjectStore('teacher');
- const handleLogout = () => {
- clear();
- reset();
- };
-
- if (teacher) {
- return (
-
-
-
- שלום המורה {teacher.name}
-
- }
- >
- התנתק
-
-
- {children}
-
- );
- }
-
- const handleSubmit = async (values) => {
- const { tz } = values;
- const result = await dataProvider.getList("teacher", {
- pagination: { page: 1, perPage: 1 },
- filter: { tz },
- });
- const teacher = result.data[0] || null;
+ const handleLogout = () => {
+ clear();
+ reset();
+ };
if (teacher) {
- setTeacher(teacher);
- } else {
- notify("Teacher not found", { type: "warning" });
+ return (
+
+
+
+ שלום המורה {teacher.name}
+
+ }>
+ התנתק
+
+
+ {children}
+
+ );
}
- };
- return (
-
-
-
-
-
-
-
- כניסת מורה
-
+ const handleSubmit = async (values) => {
+ const { tz } = values;
+ const result = await dataProvider.getList('teacher', {
+ pagination: { page: 1, perPage: 1 },
+ filter: { tz },
+ });
+ const teacher = result.data[0] || null;
+
+ if (teacher) {
+ setTeacher(teacher);
+ } else {
+ notify('Teacher not found', { type: 'warning' });
+ }
+ };
+
+ return (
+
+
+
+
+
+
+
+ כניסת מורה
+
+
+
+
+
+
+ }
+ >
+
+
+
+
-
-
-
-
- }
- >
-
-
-
-
-
- );
+ );
};
diff --git a/client/src/components/TeacherView/lead-teacher-att-report-list.jsx b/client/src/components/TeacherView/lead-teacher-att-report-list.jsx
index 1f3ecc03..d4291725 100644
--- a/client/src/components/TeacherView/lead-teacher-att-report-list.jsx
+++ b/client/src/components/TeacherView/lead-teacher-att-report-list.jsx
@@ -1,21 +1,21 @@
-import attReport from "../../entities/att-report-with-report-month.jsx";
-import { TeacherGuard } from "src/components/TeacherView/TeacherAccess.jsx";
-import { useObjectStore } from "src/utils/storeUtil";
+import attReport from '../../entities/att-report-with-report-month.jsx';
+import { TeacherGuard } from 'src/components/TeacherView/TeacherAccess.jsx';
+import { useObjectStore } from 'src/utils/storeUtil';
const BaseList = attReport.list;
const LeadTeacherAttReportList = (props) => {
- const { value: teacher } = useObjectStore("teacher");
+ const { value: teacher } = useObjectStore('teacher');
- const leadTeacherFilter = {
- 'klass.klassType.teacherReferenceId': teacher?.id,
- };
+ const leadTeacherFilter = {
+ 'klass.klassType.teacherReferenceId': teacher?.id,
+ };
- return (
-
-
-
- );
+ return (
+
+
+
+ );
};
-export default LeadTeacherAttReportList;
\ No newline at end of file
+export default LeadTeacherAttReportList;
diff --git a/client/src/components/TeacherView/percent-report-with-dates-list.jsx b/client/src/components/TeacherView/percent-report-with-dates-list.jsx
index 74a15430..559fa013 100644
--- a/client/src/components/TeacherView/percent-report-with-dates-list.jsx
+++ b/client/src/components/TeacherView/percent-report-with-dates-list.jsx
@@ -1,17 +1,17 @@
-import PercentReportWithDatesList from "src/pivots/PercentReportWithDatesList";
-import { TeacherGuard } from "src/components/TeacherView/TeacherAccess.jsx";
-import { useObjectStore } from "src/utils/storeUtil";
+import PercentReportWithDatesList from 'src/pivots/PercentReportWithDatesList';
+import { TeacherGuard } from 'src/components/TeacherView/TeacherAccess.jsx';
+import { useObjectStore } from 'src/utils/storeUtil';
const TeacherPercentReportWithDatesList = (props) => {
- const { value: teacher } = useObjectStore("teacher");
- const teacherFilter = {
- teacherReferenceId: teacher?.id,
- };
+ const { value: teacher } = useObjectStore('teacher');
+ const teacherFilter = {
+ teacherReferenceId: teacher?.id,
+ };
- return (
-
-
-
- );
+ return (
+
+
+
+ );
};
export default TeacherPercentReportWithDatesList;
diff --git a/client/src/components/TeacherView/student-attendance-list.jsx b/client/src/components/TeacherView/student-attendance-list.jsx
index 91fbe5b6..89bd5a85 100644
--- a/client/src/components/TeacherView/student-attendance-list.jsx
+++ b/client/src/components/TeacherView/student-attendance-list.jsx
@@ -1,17 +1,17 @@
-import StudentAttendanceList from "src/pivots/StudentAttendanceList.jsx";
-import { TeacherGuard } from "src/components/TeacherView/TeacherAccess.jsx";
-import { useObjectStore } from "src/utils/storeUtil";
+import StudentAttendanceList from 'src/pivots/StudentAttendanceList.jsx';
+import { TeacherGuard } from 'src/components/TeacherView/TeacherAccess.jsx';
+import { useObjectStore } from 'src/utils/storeUtil';
const TeacherStudentAttendanceList = (props) => {
- const { value: teacher } = useObjectStore("teacher");
- const teacherFilter = {
- teacherReferenceId: teacher?.id,
- };
+ const { value: teacher } = useObjectStore('teacher');
+ const teacherFilter = {
+ teacherReferenceId: teacher?.id,
+ };
- return (
-
-
-
- );
+ return (
+
+
+
+ );
};
export default TeacherStudentAttendanceList;
diff --git a/client/src/components/TeacherView/taecher-att-report-list.jsx b/client/src/components/TeacherView/taecher-att-report-list.jsx
index 70b32d09..9b36490f 100644
--- a/client/src/components/TeacherView/taecher-att-report-list.jsx
+++ b/client/src/components/TeacherView/taecher-att-report-list.jsx
@@ -1,31 +1,31 @@
-import attReport from "../../entities/att-report-with-report-month.jsx";
-import { TeacherGuard } from "src/components/TeacherView/TeacherAccess.jsx";
-import { useObjectStore } from "src/utils/storeUtil";
+import attReport from '../../entities/att-report-with-report-month.jsx';
+import { TeacherGuard } from 'src/components/TeacherView/TeacherAccess.jsx';
+import { useObjectStore } from 'src/utils/storeUtil';
const BaseList = attReport.list;
const BaseEdit = attReport.edit;
const teacherAttReportList = (props) => {
- const { value: teacher } = useObjectStore("teacher");
- const teacherFilter = {
- teacherReferenceId: teacher?.id,
- };
+ const { value: teacher } = useObjectStore('teacher');
+ const teacherFilter = {
+ teacherReferenceId: teacher?.id,
+ };
- return (
-
-
-
- );
+ return (
+
+
+
+ );
};
const teacherAttReportEdit = (props) => {
- return (
-
-
-
- );
+ return (
+
+
+
+ );
};
export default {
- list: teacherAttReportList,
- edit: teacherAttReportEdit,
+ list: teacherAttReportList,
+ edit: teacherAttReportEdit,
};
diff --git a/client/src/domainTranslations.js b/client/src/domainTranslations.js
index cf3e0b6b..0a22ab9b 100644
--- a/client/src/domainTranslations.js
+++ b/client/src/domainTranslations.js
@@ -1,5 +1,5 @@
-import { generalResourceFieldsTranslation } from "@shared/providers/i18nProvider"
-import { sharedEntityTranslations } from "@shared/entities/shared-entity.translations"
+import { generalResourceFieldsTranslation } from '@shared/providers/i18nProvider';
+import { sharedEntityTranslations } from '@shared/entities/shared-entity.translations';
export default {
menu_groups: {
@@ -39,7 +39,7 @@ export default {
'reportCardSettings.downComment': 'הצג הערה מתחת שם תלמידה',
'reportCardSettings.lastGrade': 'חשב ציון אחרון',
'reportCardSettings.debug': 'הצג פירוט',
- }
+ },
},
att_report: {
name: 'רשומת נוכחות |||| נוכחות',
@@ -61,7 +61,7 @@ export default {
approvedAbsCount: 'חיסורים מאושרים',
comments: 'הערה',
sheetName: 'חודש דיווח',
- }
+ },
},
att_report_with_report_month: {
name: 'רשומת נוכחות |||| נוכחות',
@@ -84,7 +84,7 @@ export default {
approvedAbsCount: 'חיסורים מאושרים',
comments: 'הערה',
sheetName: 'חודש דיווח',
- }
+ },
},
grade: {
name: 'רשומת ציונים |||| ציונים',
@@ -104,7 +104,7 @@ export default {
grade: 'ציון',
estimation: 'הערכה',
comments: 'הערה',
- }
+ },
},
klass: {
name: 'כיתה |||| כיתות',
@@ -115,7 +115,7 @@ export default {
klassTypeReferenceId: 'שיוך כיתה',
teacherId: 'מורה',
teacherReferenceId: 'מורה',
- }
+ },
},
klass_type: {
name: 'שיוך כיתה |||| שיוך כיתות',
@@ -124,7 +124,7 @@ export default {
klassTypeEnum: 'סוג כיתה בדו"ח',
teacherId: 'מורה אחראית',
teacherReferenceId: 'מורה אחראית',
- }
+ },
},
known_absence: {
name: 'חיסור מאושר |||| חיסורים מאושרים',
@@ -144,7 +144,7 @@ export default {
comment: 'הערה',
isApproved: 'מאושר',
absenceTypeId: 'סוג אירוע',
- }
+ },
},
lesson: {
name: 'שיעור |||| שיעורים',
@@ -160,7 +160,7 @@ export default {
howManyLessons: 'מספר שיעורים',
displayName: 'שם לתעודה',
order: 'סדר',
- }
+ },
},
student_klass: {
name: 'רשומת שיוך תלמידות לכיתות |||| שיוך תלמידות לכיתות',
@@ -170,7 +170,7 @@ export default {
studentReferenceId: 'תלמידה',
klassId: 'כיתה',
klassReferenceId: 'כיתה',
- }
+ },
},
student: {
name: 'תלמידה |||| תלמידות',
@@ -181,7 +181,7 @@ export default {
phone: 'טלפון',
address: 'כתובת',
isActive: 'פעיל?',
- }
+ },
},
student_by_year: {
name: 'תלמידה |||| תלמידות',
@@ -189,7 +189,7 @@ export default {
...generalResourceFieldsTranslation,
tz: 'תז',
year: 'שנה',
- }
+ },
},
teacher: {
name: 'מורה |||| מורות',
@@ -199,8 +199,8 @@ export default {
phone: 'טלפון',
phone2: 'טלפון 2',
email: 'כתובת מייל',
- displayName: 'שם לתעודה'
- }
+ displayName: 'שם לתעודה',
+ },
},
transportation: {
name: 'הסעה |||| הסעות',
@@ -209,7 +209,7 @@ export default {
key: 'שילוט',
departureTime: 'שעת יציאה',
description: 'תיאור נסיעה',
- }
+ },
},
absence_type: {
name: 'אירוע |||| אירועים',
@@ -219,7 +219,7 @@ export default {
name: 'שם האירוע',
quota: 'מכסה שנתית',
requiredLabels: 'שדות חובה לדיווח',
- }
+ },
},
student_klass_report: {
name: 'דוח שיוך תלמידה',
@@ -235,7 +235,7 @@ export default {
'klassReferenceId3:$cont': 'התמחות',
klassReferenceIdNull: 'אחר',
'klassReferenceIdNull:$cont': 'אחר',
- }
+ },
},
'student_by_year/pivot?extra.pivot=StudentAttendance': {
name: 'דוח נוכחות (פיבוט)',
@@ -248,7 +248,7 @@ export default {
'year:$cont': 'שנה',
'klassReferenceIds:$cont': 'כיתה',
'klassTypeReferenceIds:$cont': 'שיוך כיתה',
- }
+ },
},
report_month: {
name: 'תקופות דיווח',
@@ -257,7 +257,7 @@ export default {
startDate: 'תאריך התחלה',
endDate: 'תאריך סיום',
semester: 'מחצית',
- }
+ },
},
teacher_report_status: {
name: 'דיווחים למורה',
@@ -268,7 +268,7 @@ export default {
reportMonthReferenceId: 'תקופת דיווח',
reportedLessons: 'שיעורים שדווחו',
notReportedLessons: 'שיעורים שלא דווחו',
- }
+ },
},
teacher_grade_report_status: {
name: 'ציונים למורה',
@@ -279,7 +279,7 @@ export default {
reportMonthReferenceId: 'תקופת דיווח',
reportedLessons: 'שיעורים שדווחו',
notReportedLessons: 'שיעורים שלא דווחו',
- }
+ },
},
student_percent_report: {
name: 'דוח אחוזים כללי',
@@ -295,7 +295,7 @@ export default {
absPercents: 'אחוז חיסור',
attPercents: 'אחוז נוכחות',
gradeAvg: 'ציון ממוצע',
- }
+ },
},
'student_percent_report/pivot?extra.pivot=PercentReportWithDates': {
name: 'דוח אחוזים לתלמידה',
@@ -319,7 +319,7 @@ export default {
estimation: 'הערכה',
comments: 'הערה',
estimatedAbsPercents: 'אחוז חיסור משוער',
- }
+ },
},
teacher_salary_report: {
name: 'דוח שכר למורה',
@@ -331,19 +331,19 @@ export default {
'klass.klassTypeReferenceId': 'שיוך כיתה',
reportMonthReferenceId: 'תקופת דיווח',
howManyLessons: 'מספר שיעורים',
- }
+ },
},
grade_name: {
name: 'שם ציון |||| שמות ציונים',
fields: {
...generalResourceFieldsTranslation,
- }
+ },
},
attendance_name: {
name: 'שם נוכחות |||| שמות נוכחות',
fields: {
...generalResourceFieldsTranslation,
- }
+ },
},
att_grade_effect: {
name: 'קשר נוכחות ציון',
@@ -352,7 +352,7 @@ export default {
percents: 'אחוז נוכחות',
count: 'מספר חיסורים',
effect: 'השפעה',
- }
+ },
},
grade_effect_by_user: {
name: 'קשר נוכחות ציון מורחב',
@@ -360,7 +360,7 @@ export default {
...generalResourceFieldsTranslation,
number: 'אחוז חיסור',
effect: 'השפעה',
- }
+ },
},
abs_count_effect_by_user: {
name: 'קשר נוכחות חיסור מורחב',
@@ -368,7 +368,7 @@ export default {
...generalResourceFieldsTranslation,
number: 'מספר חיסורים',
effect: 'השפעה',
- }
+ },
},
report_group: {
name: 'קבוצת דיווח |||| קבוצות דיווח',
@@ -381,7 +381,7 @@ export default {
klassReferenceId: 'כיתה',
year: 'שנה',
signatureData: 'חתימה',
- }
+ },
},
report_group_session: {
name: 'מפגש דיווח |||| מפגשי דיווח',
@@ -393,7 +393,7 @@ export default {
startTime: 'שעת התחלה',
endTime: 'שעת סיום',
topic: 'נושא',
- }
+ },
},
- }
+ },
};
diff --git a/client/src/entities/absenceType.jsx b/client/src/entities/absenceType.jsx
index 1a27d553..22b94834 100644
--- a/client/src/entities/absenceType.jsx
+++ b/client/src/entities/absenceType.jsx
@@ -10,15 +10,15 @@ import {
SelectField,
ArrayInput,
SimpleFormIterator,
-} from "react-admin";
-import { CommonDatagrid } from "@shared/components/crudContainers/CommonList";
-import { getResourceComponents } from "@shared/components/crudContainers/CommonEntity";
-import CommonReferenceInput from "@shared/components/fields/CommonReferenceInput";
-import { useUnique } from "@shared/utils/useUnique";
-import { commonAdminFilters } from "@shared/components/fields/PermissionFilter";
-import { defaultYearFilter, yearChoices } from "@shared/utils/yearFilter";
-import CommonAutocompleteInput from "@shared/components/fields/CommonAutocompleteInput";
-import { CommonRepresentation } from "@shared/components/CommonRepresentation";
+} from 'react-admin';
+import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
+import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
+import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
+import { useUnique } from '@shared/utils/useUnique';
+import { commonAdminFilters } from '@shared/components/fields/PermissionFilter';
+import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
+import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
+import { CommonRepresentation } from '@shared/components/CommonRepresentation';
const filters = [
...commonAdminFilters,
@@ -41,7 +41,7 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
-
+
{isAdmin && }
{isAdmin && }
@@ -53,10 +53,15 @@ const Inputs = ({ isCreate, isAdmin }) => {
return (
<>
{!isCreate && isAdmin && }
- {isAdmin && ( )}
-
+ {isAdmin && }
+
-
+
@@ -72,7 +77,7 @@ const Inputs = ({ isCreate, isAdmin }) => {
const Representation = CommonRepresentation;
const importer = {
- fields: ["name", "quota", "requiredLabels", "year"],
+ fields: ['name', 'quota', 'requiredLabels', 'year'],
};
const entity = {
@@ -84,4 +89,4 @@ const entity = {
importer,
};
-export default getResourceComponents(entity);
\ No newline at end of file
+export default getResourceComponents(entity);
diff --git a/client/src/entities/att-grade-effect.jsx b/client/src/entities/att-grade-effect.jsx
index 3d5f7ba2..788b813e 100644
--- a/client/src/entities/att-grade-effect.jsx
+++ b/client/src/entities/att-grade-effect.jsx
@@ -1,4 +1,13 @@
-import { NumberInput, TextField, TextInput, ReferenceField, DateField, DateTimeInput, required, maxLength } from 'react-admin';
+import {
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ DateField,
+ DateTimeInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
@@ -24,23 +33,25 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const importer = {
fields: ['percents', 'count', 'effect'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/att-report-with-report-month.jsx b/client/src/entities/att-report-with-report-month.jsx
index 968dafee..1d087f7c 100644
--- a/client/src/entities/att-report-with-report-month.jsx
+++ b/client/src/entities/att-report-with-report-month.jsx
@@ -1,10 +1,27 @@
-import { DateField, DateInput, NumberField, TextField, TextInput, ReferenceField, SelectField, required, NumberInput, BooleanInput, NullableBooleanInput, maxLength } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ NumberField,
+ TextField,
+ TextInput,
+ ReferenceField,
+ SelectField,
+ required,
+ NumberInput,
+ BooleanInput,
+ NullableBooleanInput,
+ maxLength,
+} from 'react-admin';
import PlaylistRemoveIcon from '@mui/icons-material/PlaylistRemove';
import HelpIcon from '@mui/icons-material/Help';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -19,13 +36,36 @@ const filters = [
...commonAdminFilters,
,
,
- ,
+ ,
,
,
- ({ permissions }) => !isTeacherView(permissions) && (),
+ ({ permissions }) =>
+ !isTeacherView(permissions) && (
+
+ ),
,
- ,
- ,
+ ,
+ ,
,
,
];
@@ -36,17 +76,25 @@ const filterDefaultValues = {
export const Datagrid = ({ isAdmin, children, ...props }) => {
const additionalBulkButtons = [
- } name='bulkKnownAbsences' >
+ } name="bulkKnownAbsences">
-
-
-
+
+
+
,
- isAdmin && } reloadOnEnd />,
- ,
+ isAdmin && (
+ }
+ reloadOnEnd
+ />
+ ),
+ ,
];
const hasReportGroupPermission = useIsLessonSignature();
return (
@@ -54,16 +102,52 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
-
-
-
+
+
+
+
-
+
{hasReportGroupPermission && (
-
+
)}
@@ -80,7 +164,7 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const entity = {
resource: 'att_report_with_report_month',
diff --git a/client/src/entities/att-report.jsx b/client/src/entities/att-report.jsx
index 83083c99..cb3c0076 100644
--- a/client/src/entities/att-report.jsx
+++ b/client/src/entities/att-report.jsx
@@ -1,9 +1,26 @@
-import { DateField, DateInput, DateTimeInput, NumberField, NumberInput, TextField, TextInput, ReferenceField, required, minValue, maxLength, SelectField } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ NumberField,
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ required,
+ minValue,
+ maxLength,
+ SelectField,
+} from 'react-admin';
import { useIsLessonSignature, useIsTeacherView } from 'src/utils/appPermissions';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -14,12 +31,28 @@ const filters = [
...commonAdminFilters,
,
,
- ,
+ ,
,
,
,
- ,
- ,
+ ,
+ ,
,
];
@@ -34,16 +67,52 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
-
-
-
+
+
+
+
-
+
{hasReportGroupPermission && (
-
+
)}
@@ -59,33 +128,67 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
export const Inputs = ({ isCreate, isAdmin }) => {
const isTeacher = useIsTeacherView();
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
- {!isTeacher && }
-
-
-
-
-
- {/* */}
-
-
- {/* */}
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+ {!isTeacher && (
+
+ )}
+
+
+
+
+
+ {/* */}
+
+
+ {/* */}
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const importer = {
- fields: ['studentTz', 'teacherId', 'klassId', 'lessonId', 'year', 'reportDate', 'howManyLessons', 'absCount', 'comments']
-}
+ fields: [
+ 'studentTz',
+ 'teacherId',
+ 'klassId',
+ 'lessonId',
+ 'year',
+ 'reportDate',
+ 'howManyLessons',
+ 'absCount',
+ 'comments',
+ ],
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/attendance-name.jsx b/client/src/entities/attendance-name.jsx
index 7bc2782f..bba94de2 100644
--- a/client/src/entities/attendance-name.jsx
+++ b/client/src/entities/attendance-name.jsx
@@ -1,4 +1,13 @@
-import { NumberInput, TextField, TextInput, ReferenceField, DateField, DateTimeInput, required, maxLength } from 'react-admin';
+import {
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ DateField,
+ DateTimeInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
@@ -6,11 +15,7 @@ import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput
import { CommonReferenceInputFilter } from '@shared/components/fields/CommonReferenceInputFilter';
import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
-const filters = [
- adminUserFilter,
- ,
- ,
-];
+const filters = [adminUserFilter, , ];
const Datagrid = ({ isAdmin, children, ...props }) => {
return (
@@ -24,24 +29,26 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['key', 'name'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/grade-name.jsx b/client/src/entities/grade-name.jsx
index bf3212c4..636a286e 100644
--- a/client/src/entities/grade-name.jsx
+++ b/client/src/entities/grade-name.jsx
@@ -1,15 +1,20 @@
-import { NumberInput, TextField, TextInput, ReferenceField, DateField, DateTimeInput, required, maxLength } from 'react-admin';
+import {
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ DateField,
+ DateTimeInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
-const filters = [
- adminUserFilter,
- ,
- ,
-];
+const filters = [adminUserFilter, , ];
const Datagrid = ({ isAdmin, children, ...props }) => {
return (
@@ -23,24 +28,26 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['key', 'name'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/grade.jsx b/client/src/entities/grade.jsx
index d57ae924..57b36efd 100644
--- a/client/src/entities/grade.jsx
+++ b/client/src/entities/grade.jsx
@@ -1,8 +1,25 @@
-import { DateField, DateInput, DateTimeInput, NumberField, NumberInput, TextField, TextInput, ReferenceField, required, maxLength, SelectField, NullableBooleanInput } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ NumberField,
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ required,
+ maxLength,
+ SelectField,
+ NullableBooleanInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -12,12 +29,24 @@ const filters = [
...commonAdminFilters,
,
,
- ,
+ ,
,
,
,
,
- ,
+ ,
,
];
@@ -31,11 +60,35 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
-
-
+
+
+
{/* */}
@@ -46,30 +99,52 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
- {/* */}
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+ {/* */}
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const importer = {
- fields: ['studentTz', 'teacherId', 'klassId', 'lessonId', 'year', 'reportDate', 'grade', 'comments']
-}
+ fields: ['studentTz', 'teacherId', 'klassId', 'lessonId', 'year', 'reportDate', 'grade', 'comments'],
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/klass-type.jsx b/client/src/entities/klass-type.jsx
index 83a0f9d3..3e4f0961 100644
--- a/client/src/entities/klass-type.jsx
+++ b/client/src/entities/klass-type.jsx
@@ -1,4 +1,13 @@
-import { NumberInput, TextField, TextInput, ReferenceField, DateField, DateTimeInput, required, maxLength } from 'react-admin';
+import {
+ NumberInput,
+ TextField,
+ TextInput,
+ ReferenceField,
+ DateField,
+ DateTimeInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
@@ -24,33 +33,44 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
-
+
{isAdmin && }
{isAdmin && }
);
-}
+};
const klassTypeEnum = ['כיתת אם', 'מסלול', 'התמחות', 'אחר'];
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
- ({ id: item, name: item }))} />
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+ ({ id: item, name: item }))}
+ />
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['key', 'name', 'klassTypeEnum', 'teacherId'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/klass.jsx b/client/src/entities/klass.jsx
index 119de114..bd07411a 100644
--- a/client/src/entities/klass.jsx
+++ b/client/src/entities/klass.jsx
@@ -1,9 +1,24 @@
-import { SelectField, TextField, TextInput, ReferenceField, DateField, DateInput, DateTimeInput, NumberInput, required, maxLength } from 'react-admin';
+import {
+ SelectField,
+ TextField,
+ TextInput,
+ ReferenceField,
+ DateField,
+ DateInput,
+ DateTimeInput,
+ NumberInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -20,7 +35,12 @@ const filters = [
,
,
,
- ,
+ ,
,
];
@@ -29,31 +49,23 @@ const filterDefaultValues = {
};
const additionalBulkButtons = [
- }
- name='klassAttendanceReport'
- filename='יומן-נוכחות'
+ }
+ name="klassAttendanceReport"
+ filename="יומן-נוכחות"
>
-
-
-
+
+
,
- ,
+ ,
];
const Datagrid = ({ isAdmin, children, ...props }) => {
@@ -65,36 +77,55 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
-
-
+
+
{isAdmin && }
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
const unique = useUnique({ dynamicFilter: { year: 'year' } });
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
};
const Representation = CommonRepresentation;
const importer = {
fields: ['key', 'name', 'klassTypeId', 'teacherId', 'year', 'displayName'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/known-absence.jsx b/client/src/entities/known-absence.jsx
index 225f5ffa..69017a4b 100644
--- a/client/src/entities/known-absence.jsx
+++ b/client/src/entities/known-absence.jsx
@@ -1,8 +1,27 @@
-import { BooleanField, BooleanInput, DateField, DateInput, DateTimeInput, maxLength, NullableBooleanInput, NumberField, NumberInput, ReferenceField, required, SelectField, TextField, TextInput } from 'react-admin';
+import {
+ BooleanField,
+ BooleanInput,
+ DateField,
+ DateInput,
+ DateTimeInput,
+ maxLength,
+ NullableBooleanInput,
+ NumberField,
+ NumberInput,
+ ReferenceField,
+ required,
+ SelectField,
+ TextField,
+ TextInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -13,10 +32,18 @@ import { useIsAbsenceType } from 'src/utils/appPermissions';
const filters = [
...commonAdminFilters,
- ,
+ ,
,
,
- ,
+ ,
,
,
,
@@ -25,7 +52,11 @@ const filters = [
,
,
,
- ,
+ ,
];
const filterDefaultValues = {
@@ -39,9 +70,27 @@ const Datagrid = ({ isAdmin, children, isPreview, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
-
-
+
+
+
{isAbsenceType && }
@@ -56,41 +105,69 @@ const Datagrid = ({ isAdmin, children, isPreview, ...props }) => {
{isAdmin && }
);
-}
+};
-const lessonKeyAndName = item => `${item.name} (${item.key})`;
+const lessonKeyAndName = (item) => `${item.name} (${item.key})`;
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
-
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const importer = {
- fields: ['studentTz', 'klassId', 'lessonId', 'reportDate', 'absnceCount', 'absnceCode', 'senderName', 'reason', 'comment', 'isApproved'],
-}
+ fields: [
+ 'studentTz',
+ 'klassId',
+ 'lessonId',
+ 'reportDate',
+ 'absnceCount',
+ 'absnceCode',
+ 'senderName',
+ 'reason',
+ 'comment',
+ 'isApproved',
+ ],
+};
const additionalListActions = [
- ,
+ ,
];
const entity = {
diff --git a/client/src/entities/lesson.jsx b/client/src/entities/lesson.jsx
index c6878b1a..cdd43dfb 100644
--- a/client/src/entities/lesson.jsx
+++ b/client/src/entities/lesson.jsx
@@ -1,9 +1,27 @@
-import { DateField, DateInput, DateTimeInput, maxLength, NumberInput, ReferenceArrayField, ReferenceArrayInput, ReferenceField, required, TextField, TextInput, SelectField, minValue } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ maxLength,
+ NumberInput,
+ ReferenceArrayField,
+ ReferenceArrayInput,
+ ReferenceField,
+ required,
+ TextField,
+ TextInput,
+ SelectField,
+ minValue,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField, MultiReferenceArrayField } from '@shared/components/fields/CommonReferenceField';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -15,8 +33,18 @@ const filters = [
...commonAdminFilters,
,
,
- ,
- ,
+ ,
+ ,
,
];
@@ -33,8 +61,19 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
-
-
+
+
@@ -45,34 +84,52 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
const unique = useUnique({ dynamicFilter: { year: 'year' } });
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
- fields: ['key', 'name', 'klasses', 'teacherId', 'startDate', 'endDate', 'year', 'comment', 'howManyLessons', 'displayName', 'order'],
-}
+ fields: [
+ 'key',
+ 'name',
+ 'klasses',
+ 'teacherId',
+ 'startDate',
+ 'endDate',
+ 'year',
+ 'comment',
+ 'howManyLessons',
+ 'displayName',
+ 'order',
+ ],
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/report-group-session.jsx b/client/src/entities/report-group-session.jsx
index ced7411f..5935a468 100644
--- a/client/src/entities/report-group-session.jsx
+++ b/client/src/entities/report-group-session.jsx
@@ -1,7 +1,11 @@
import { DateField, TextField, DateInput, ReferenceField, ReferenceManyCount, NumberInput } from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
import { BulkReportButton } from '@shared/components/crudContainers/BulkReportButton';
@@ -12,9 +16,24 @@ import { commonAdminFilters } from '@shared/components/fields/PermissionFilter';
const filters = [
,
- ,
- ,
- ,
+ ,
+ ,
+ ,
,
,
,
@@ -27,23 +46,23 @@ const filterDefaultValues = {
const additionalBulkButtons = [
}
- name='sessionsSummary'
- filename='סיכום-מפגשים'
+ name="sessionsSummary"
+ filename="סיכום-מפגשים"
/>,
- }
- name='adjustTime'
+ }
+ name="adjustTime"
reloadOnEnd
defaultRequestValues={{ hoursAdjustment: 2 }}
>
-
,
diff --git a/client/src/entities/report-group.jsx b/client/src/entities/report-group.jsx
index b527bf7c..49c35526 100644
--- a/client/src/entities/report-group.jsx
+++ b/client/src/entities/report-group.jsx
@@ -1,7 +1,21 @@
-import { DateField, TextField, TextInput, SelectField, ReferenceField, ReferenceManyCount, DateTimeInput, required, maxLength } from 'react-admin';
+import {
+ DateField,
+ TextField,
+ TextInput,
+ SelectField,
+ ReferenceField,
+ ReferenceManyCount,
+ DateTimeInput,
+ required,
+ maxLength,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
@@ -15,17 +29,17 @@ import SignatureInput from '@shared/components/fields/signature/SignatureInput';
const additionalBulkButtons = [
}
- name='lessonSignaturePdf'
- filename='דוחות-קבוצות'
+ name="lessonSignaturePdf"
+ filename="דוחות-קבוצות"
/>,
}
- name='updateSignatureData'
+ name="updateSignatureData"
reloadOnEnd
>
@@ -65,19 +79,36 @@ export const Datagrid = ({ isAdmin, children, ...props }) => {
};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
-
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
diff --git a/client/src/entities/report-month.jsx b/client/src/entities/report-month.jsx
index 70cef157..5b693a9a 100644
--- a/client/src/entities/report-month.jsx
+++ b/client/src/entities/report-month.jsx
@@ -1,4 +1,15 @@
-import { DateField, DateInput, DateTimeInput, maxLength, NumberInput, ReferenceField, required, SelectField, TextField, TextInput } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ maxLength,
+ NumberInput,
+ ReferenceField,
+ required,
+ SelectField,
+ TextField,
+ TextInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
@@ -34,30 +45,32 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const semesterEnum = ['א', 'ב', 'ג', 'שנתי'];
-export const semesterChoices = semesterEnum.map(item => ({ id: item, name: item }));
+export const semesterChoices = semesterEnum.map((item) => ({ id: item, name: item }));
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['name', 'startDate', 'endDate', 'semester', 'year'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/student-klass.jsx b/client/src/entities/student-klass.jsx
index 709ec66d..6a93c6a5 100644
--- a/client/src/entities/student-klass.jsx
+++ b/client/src/entities/student-klass.jsx
@@ -1,8 +1,22 @@
-import { DateField, DateInput, DateTimeInput, NullableBooleanInput, ReferenceField, required, TextField, TextInput, SelectField } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ NullableBooleanInput,
+ ReferenceField,
+ required,
+ TextField,
+ TextInput,
+ SelectField,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ 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';
@@ -23,8 +37,8 @@ const filterDefaultValues = {
};
const additionalBulkButtons = [
- ,
- ,
+ ,
+ ,
];
const Datagrid = ({ isAdmin, children, ...props }) => {
@@ -33,33 +47,64 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
-
+
+
-
+
{isAdmin && }
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const importer = {
fields: ['studentTz', 'klassId', 'year'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/student-klasses-report.jsx b/client/src/entities/student-klasses-report.jsx
index 61805466..0b953a2c 100644
--- a/client/src/entities/student-klasses-report.jsx
+++ b/client/src/entities/student-klasses-report.jsx
@@ -5,16 +5,36 @@ import { getResourceComponents } from '@shared/components/crudContainers/CommonE
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
import StudentReportCardReactButton from 'src/reports/studentReportCardReactButton';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
const filters = [
adminUserFilter,
,
- ,
- ,
- ,
- ,
+ ,
+ ,
+ ,
+ ,
,
];
@@ -23,7 +43,7 @@ const filterDefaultValues = {
};
const additionalBulkButtons = [
- ,
+ ,
];
const Datagrid = ({ isAdmin, children, ...props }) => {
@@ -32,8 +52,21 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
-
+
+
@@ -41,13 +74,33 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
*/}
-
-
-
-
+
+
+
+
);
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/student-percent-report.jsx b/client/src/entities/student-percent-report.jsx
index 3631bef5..af4d795f 100644
--- a/client/src/entities/student-percent-report.jsx
+++ b/client/src/entities/student-percent-report.jsx
@@ -1,8 +1,20 @@
-import { DateInput, NumberField, TextField, ReferenceField, useRecordContext, SelectField, TextInput } from 'react-admin';
+import {
+ DateInput,
+ NumberField,
+ TextField,
+ ReferenceField,
+ useRecordContext,
+ SelectField,
+ TextInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import { ShowMatchingRecordsButton } from '@shared/components/fields/ShowMatchingRecordsButton';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
@@ -12,11 +24,23 @@ const filters = [
adminUserFilter,
// ,
// ,
- ,
+ ,
,
,
,
- ,
+ ,
,
];
@@ -30,11 +54,35 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
-
-
+
+
+
@@ -44,16 +92,14 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
);
-}
+};
const ShowMatchingAttReportsButton = ({ ...props }) => {
const { studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId } = useRecordContext();
const filter = { studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId };
- return (
-
- );
-}
+ return ;
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/student.jsx b/client/src/entities/student.jsx
index 5a46f11e..1b1fe3f4 100644
--- a/client/src/entities/student.jsx
+++ b/client/src/entities/student.jsx
@@ -1,4 +1,20 @@
-import { BooleanField, BooleanInput, DateField, DateInput, DateTimeInput, Labeled, maxLength, NullableBooleanInput, ReferenceField, ReferenceManyField, required, SelectField, SelectInput, TextField, TextInput } from 'react-admin';
+import {
+ BooleanField,
+ BooleanInput,
+ DateField,
+ DateInput,
+ DateTimeInput,
+ Labeled,
+ maxLength,
+ NullableBooleanInput,
+ ReferenceField,
+ ReferenceManyField,
+ required,
+ SelectField,
+ SelectInput,
+ TextField,
+ TextInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
@@ -17,7 +33,7 @@ const filters = [
,
,
,
- ,,
+ ,
];
const filterDefaultValues = {
@@ -27,9 +43,14 @@ const filterDefaultValues = {
const additionalBulkButtons = [
// }
// key='studentReportCard' name='studentReportCard' filename='תעודה' />,
- ,
- }
- name='bulkUpdateActive' key='bulkUpdateActive' reloadOnEnd >
+ ,
+ }
+ name="bulkUpdateActive"
+ key="bulkUpdateActive"
+ reloadOnEnd
+ >
,
];
@@ -50,37 +71,47 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
const unique = useUnique();
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- {!isCreate &&
-
-
-
-
-
-
- }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ {!isCreate && (
+
+
+
+
+
+
+
+
+ )}
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['tz', 'name', 'comment', 'phone', 'address', 'isActive'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/teacher-grade-report-status.jsx b/client/src/entities/teacher-grade-report-status.jsx
index 2f92b35d..ffdbae35 100644
--- a/client/src/entities/teacher-grade-report-status.jsx
+++ b/client/src/entities/teacher-grade-report-status.jsx
@@ -1,4 +1,13 @@
-import { ReferenceField, ReferenceArrayField, TextField, required, SelectField, BooleanInput, TextInput, useGetList } from 'react-admin';
+import {
+ ReferenceField,
+ ReferenceArrayField,
+ TextField,
+ required,
+ SelectField,
+ BooleanInput,
+ TextInput,
+ useGetList,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
import { CommonReferenceInputFilter, filterByUserId } from '@shared/components/fields/CommonReferenceInputFilter';
@@ -14,7 +23,11 @@ import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
const filters = [
adminUserFilter,
,
- ,
+ ,
,
];
@@ -23,18 +36,44 @@ const filterDefaultValues = {
};
const Datagrid = ({ isAdmin, children, ...props }) => {
- const { data: subjectText } = useGetList('text_by_user', { page: 1, perPage: 1, filter: { name: 'teacherReportStatusEmailSubject' } });
- const { data: bodyText } = useGetList('text_by_user', { page: 1, perPage: 1, filter: { name: 'teacherReportStatusEmailBody1' } });
+ const { data: subjectText } = useGetList('text_by_user', {
+ page: 1,
+ perPage: 1,
+ filter: { name: 'teacherReportStatusEmailSubject' },
+ });
+ const { data: bodyText } = useGetList('text_by_user', {
+ page: 1,
+ perPage: 1,
+ filter: { name: 'teacherReportStatusEmailBody1' },
+ });
const defaultMailSubject = subjectText?.[0]?.value ?? 'תזכורת לשליחת דווח ציונים';
- const defaultMailBody = bodyText?.[0]?.value ?? 'שלום המורה {0} היקרה, תזכורת לשלוח נתוני ציונים עבור השיעורים {2} בתודה ההנהלה';
+ const defaultMailBody =
+ bodyText?.[0]?.value ?? 'שלום המורה {0} היקרה, תזכורת לשלוח נתוני ציונים עבור השיעורים {2} בתודה ההנהלה';
const additionalBulkButtons = [
- } name='teacherReportFile' >
+ } name="teacherReportFile">
{/* */}
,
- } name='teacherReportFile' >
-
-
-
+ } name="teacherReportFile">
+
+
+
{/* */}
,
];
@@ -44,15 +83,15 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
+
);
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/teacher-report-status.jsx b/client/src/entities/teacher-report-status.jsx
index bc4f1b17..7aeb11f8 100644
--- a/client/src/entities/teacher-report-status.jsx
+++ b/client/src/entities/teacher-report-status.jsx
@@ -1,4 +1,13 @@
-import { ReferenceField, ReferenceArrayField, TextField, required, SelectField, BooleanInput, TextInput, useGetList } from 'react-admin';
+import {
+ ReferenceField,
+ ReferenceArrayField,
+ TextField,
+ required,
+ SelectField,
+ BooleanInput,
+ TextInput,
+ useGetList,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
import { CommonReferenceInputFilter, filterByUserId } from '@shared/components/fields/CommonReferenceInputFilter';
@@ -14,7 +23,11 @@ import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
const filters = [
adminUserFilter,
,
- ,
+ ,
,
];
@@ -23,18 +36,44 @@ const filterDefaultValues = {
};
const Datagrid = ({ isAdmin, children, ...props }) => {
- const { data: subjectText } = useGetList('text_by_user', { page: 1, perPage: 1, filter: { name: 'teacherReportStatusEmailSubject' } });
- const { data: bodyText } = useGetList('text_by_user', { page: 1, perPage: 1, filter: { name: 'teacherReportStatusEmailBody1' } });
+ const { data: subjectText } = useGetList('text_by_user', {
+ page: 1,
+ perPage: 1,
+ filter: { name: 'teacherReportStatusEmailSubject' },
+ });
+ const { data: bodyText } = useGetList('text_by_user', {
+ page: 1,
+ perPage: 1,
+ filter: { name: 'teacherReportStatusEmailBody1' },
+ });
const defaultMailSubject = subjectText?.[0]?.value ?? 'תזכורת לשליחת דווח נוכחות';
- const defaultMailBody = bodyText?.[0]?.value ?? 'שלום המורה {0} היקרה, תזכורת לשלוח נתוני נוכחות עבור השיעורים {2} בתודה ההנהלה';
+ const defaultMailBody =
+ bodyText?.[0]?.value ?? 'שלום המורה {0} היקרה, תזכורת לשלוח נתוני נוכחות עבור השיעורים {2} בתודה ההנהלה';
const additionalBulkButtons = [
- } name='teacherReportFile' >
+ } name="teacherReportFile">
{/* */}
,
- } name='teacherReportFile' >
-
-
-
+ } name="teacherReportFile">
+
+
+
{/* */}
,
];
@@ -44,15 +83,15 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
+
);
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/teacher-salary-report.jsx b/client/src/entities/teacher-salary-report.jsx
index bbeeb63f..969bc29e 100644
--- a/client/src/entities/teacher-salary-report.jsx
+++ b/client/src/entities/teacher-salary-report.jsx
@@ -10,8 +10,16 @@ import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
const filters = [
adminUserFilter,
,
- ,
- ,
+ ,
+ ,
,
];
@@ -25,18 +33,25 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
-
-
-
-
+
+
+
+
+
-
+
);
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/teacher.jsx b/client/src/entities/teacher.jsx
index 58b14039..375caca8 100644
--- a/client/src/entities/teacher.jsx
+++ b/client/src/entities/teacher.jsx
@@ -1,4 +1,14 @@
-import { DateField, DateInput, DateTimeInput, EmailField, maxLength, ReferenceField, required, TextField, TextInput } from 'react-admin';
+import {
+ DateField,
+ DateInput,
+ DateTimeInput,
+ EmailField,
+ maxLength,
+ ReferenceField,
+ required,
+ TextField,
+ TextInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { CommonRepresentation } from '@shared/components/CommonRepresentation';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
@@ -29,30 +39,32 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{isAdmin && }
);
-}
+};
const Inputs = ({ isCreate, isAdmin }) => {
const unique = useUnique();
- return <>
- {!isCreate && isAdmin && }
- {isAdmin && }
-
-
-
-
-
-
-
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
-}
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
+
+
+
+
+
+
+
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
+};
const Representation = CommonRepresentation;
const importer = {
fields: ['tz', 'name', 'phone', 'phone2', 'email', 'comment', 'displayName'],
-}
+};
const entity = {
Datagrid,
diff --git a/client/src/entities/transportation.jsx b/client/src/entities/transportation.jsx
index aede2528..9c275a05 100644
--- a/client/src/entities/transportation.jsx
+++ b/client/src/entities/transportation.jsx
@@ -1,93 +1,87 @@
import {
- DateField,
- DateTimeInput,
- ReferenceField,
- required,
- TextField,
- TextInput,
- NumberInput,
- maxLength,
- SelectField,
-} from "react-admin";
-import { CommonDatagrid } from "@shared/components/crudContainers/CommonList";
-import { getResourceComponents } from "@shared/components/crudContainers/CommonEntity";
-import CommonReferenceInput from "@shared/components/fields/CommonReferenceInput";
-import { useUnique } from "@shared/utils/useUnique";
-import { commonAdminFilters } from "@shared/components/fields/PermissionFilter";
-import { defaultYearFilter, yearChoices } from "@shared/utils/yearFilter";
-import CommonAutocompleteInput from "@shared/components/fields/CommonAutocompleteInput";
-import CommonTimeInput from "@shared/components/fields/CommonTimeInput";
+ DateField,
+ DateTimeInput,
+ ReferenceField,
+ required,
+ TextField,
+ TextInput,
+ NumberInput,
+ maxLength,
+ SelectField,
+} from 'react-admin';
+import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
+import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
+import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
+import { useUnique } from '@shared/utils/useUnique';
+import { commonAdminFilters } from '@shared/components/fields/PermissionFilter';
+import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
+import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
+import CommonTimeInput from '@shared/components/fields/CommonTimeInput';
const filters = [
- ...commonAdminFilters,
- ,
- ,
- ,
+ ...commonAdminFilters,
+ ,
+ ,
+ ,
];
const filterDefaultValues = {
- year: defaultYearFilter.year,
+ year: defaultYearFilter.year,
};
const Datagrid = ({ isAdmin, children, ...props }) => {
- return (
-
- {children}
- {isAdmin && }
- {isAdmin && }
-
-
-
-
- {isAdmin && }
- {isAdmin && }
-
- );
+ return (
+
+ {children}
+ {isAdmin && }
+ {isAdmin && }
+
+
+
+
+ {isAdmin && }
+ {isAdmin && }
+
+ );
};
const Inputs = ({ isCreate, isAdmin }) => {
- const unique = useUnique();
- return (
- <>
- {!isCreate && isAdmin && }
- {isAdmin && (
-
- )}
+ const unique = useUnique();
+ return (
+ <>
+ {!isCreate && isAdmin && }
+ {isAdmin && }
-
-
-
+
+
+
-
+
- {!isCreate && isAdmin && }
- {!isCreate && isAdmin && }
- >
- );
+ {!isCreate && isAdmin && }
+ {!isCreate && isAdmin && }
+ >
+ );
};
const Representation = 'key';
const importer = {
- fields: ["key", "departureTime", "description"],
+ fields: ['key', 'departureTime', 'description'],
};
const entity = {
- Datagrid,
- Inputs,
- Representation,
- filters,
- filterDefaultValues,
- importer,
+ Datagrid,
+ Inputs,
+ Representation,
+ filters,
+ filterDefaultValues,
+ importer,
};
export default getResourceComponents(entity);
diff --git a/client/src/index.jsx b/client/src/index.jsx
index c446061d..05b2fcaa 100644
--- a/client/src/index.jsx
+++ b/client/src/index.jsx
@@ -7,9 +7,9 @@ import 'src/openopserve.config';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
-
-
-
+
+
+ ,
);
// If you want to start measuring performance in your app, pass a function
diff --git a/client/src/openopserve.config.ts b/client/src/openopserve.config.ts
index 1b86a95a..20ead49c 100644
--- a/client/src/openopserve.config.ts
+++ b/client/src/openopserve.config.ts
@@ -1,7 +1,8 @@
import { connectToOpenobserve } from '@shared/utils/openobserveRumUtil';
import packageJson from '../package.json';
-const isDevMode = location.href.includes('dev') || location.href.includes('localhost') || location.href.includes('127.0.0.1');
+const isDevMode =
+ location.href.includes('dev') || location.href.includes('localhost') || location.href.includes('127.0.0.1');
const options = {
clientToken: '32363366626236332d333131632d343665642d616433372d316332366563386566313330',
applicationId: 'demo-yoman-online',
diff --git a/client/src/pivots/PercentReportWithDatesList.jsx b/client/src/pivots/PercentReportWithDatesList.jsx
index 62cbb9e7..70c96dc0 100644
--- a/client/src/pivots/PercentReportWithDatesList.jsx
+++ b/client/src/pivots/PercentReportWithDatesList.jsx
@@ -1,8 +1,25 @@
-import { DateInput, NumberField, TextField, ReferenceField, useRecordContext, SelectField, useListFilterContext, TextInput, useAuthState, usePermissions, BooleanInput, NullableBooleanInput } from 'react-admin';
+import {
+ DateInput,
+ NumberField,
+ TextField,
+ ReferenceField,
+ useRecordContext,
+ SelectField,
+ useListFilterContext,
+ TextInput,
+ useAuthState,
+ usePermissions,
+ BooleanInput,
+ NullableBooleanInput,
+} from 'react-admin';
import { CommonDatagrid } from '@shared/components/crudContainers/CommonList';
import { MultiReferenceField } from '@shared/components/fields/CommonReferenceField';
import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import { ShowMatchingRecordsButton } from '@shared/components/fields/ShowMatchingRecordsButton';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
@@ -20,14 +37,34 @@ const filters = [
,
,
,
- ,
+ ,
,
,
- ({ permissions }) => !isTeacherView(permissions) && (),
+ ({ permissions }) =>
+ !isTeacherView(permissions) && (
+
+ ),
,
- ,
+ ,
,
- ,
+ ,
,
];
@@ -41,11 +78,35 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{children}
{isAdmin && }
{isAdmin && }
-
+
-
-
-
+
+
+
@@ -62,7 +123,7 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
);
-}
+};
const ShowMatchingAttReportsButton = ({ ...props }) => {
const { filterValues } = useListFilterContext();
@@ -76,10 +137,8 @@ const ShowMatchingAttReportsButton = ({ ...props }) => {
'reportDate:$lte': filterValues.extra?.toDate,
};
- return (
-
- );
-}
+ return ;
+};
const entity = {
resource: 'student_percent_report/pivot?extra.pivot=PercentReportWithDates',
diff --git a/client/src/pivots/StudentAttendanceList.jsx b/client/src/pivots/StudentAttendanceList.jsx
index f654d086..52dafcfa 100644
--- a/client/src/pivots/StudentAttendanceList.jsx
+++ b/client/src/pivots/StudentAttendanceList.jsx
@@ -1,30 +1,81 @@
-import { getResourceComponents } from "@shared/components/crudContainers/CommonEntity";
-import { CommonDatagrid, getPivotColumns } from "@shared/components/crudContainers/CommonList"
-import { CommonReferenceInputFilter, filterByUserId, filterByUserIdAndYear } from "@shared/components/fields/CommonReferenceInputFilter";
-import { BooleanField, ReferenceField, TextField, useListContext, TextInput, DateInput, BooleanInput, NullableBooleanInput, SelectField } from "react-admin"
+import { getResourceComponents } from '@shared/components/crudContainers/CommonEntity';
+import { CommonDatagrid, getPivotColumns } from '@shared/components/crudContainers/CommonList';
+import {
+ CommonReferenceInputFilter,
+ filterByUserId,
+ filterByUserIdAndYear,
+} from '@shared/components/fields/CommonReferenceInputFilter';
+import {
+ BooleanField,
+ ReferenceField,
+ TextField,
+ useListContext,
+ TextInput,
+ DateInput,
+ BooleanInput,
+ NullableBooleanInput,
+ SelectField,
+} from 'react-admin';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
-import { CommonSelectArrayField } from "@shared/components/fields/CommonSelectArrayField";
-import { semesterChoices } from "src/entities/report-month";
-import CommonReferenceArrayInput from "@shared/components/fields/CommonReferenceArrayInput";
-import { adminUserFilter } from "@shared/components/fields/PermissionFilter";
+import { CommonSelectArrayField } from '@shared/components/fields/CommonSelectArrayField';
+import { semesterChoices } from 'src/entities/report-month';
+import CommonReferenceArrayInput from '@shared/components/fields/CommonReferenceArrayInput';
+import { adminUserFilter } from '@shared/components/fields/PermissionFilter';
const filters = [
adminUserFilter,
,
,
,
- ,
- ,
- ,
- ,
- ,
+ ,
+ ,
+ ,
+ ,
+ ,
,
,
,
- ,
+ ,
,
- ,
+ ,
];
const filterDefaultValues = {
@@ -47,7 +98,7 @@ const Datagrid = ({ isAdmin, children, ...props }) => {
{getPivotColumns(data)}
);
-}
+};
const entity = {
resource: 'student_by_year/pivot?extra.pivot=StudentAttendance',
@@ -55,6 +106,6 @@ const entity = {
filters,
filterDefaultValues,
configurable: false,
-}
+};
-export default getResourceComponents(entity).list;
\ No newline at end of file
+export default getResourceComponents(entity).list;
diff --git a/client/src/reportWebVitals.js b/client/src/reportWebVitals.js
index 5253d3ad..17f8ad17 100644
--- a/client/src/reportWebVitals.js
+++ b/client/src/reportWebVitals.js
@@ -1,13 +1,13 @@
-const reportWebVitals = onPerfEntry => {
- if (onPerfEntry && onPerfEntry instanceof Function) {
- import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
- getCLS(onPerfEntry);
- getFID(onPerfEntry);
- getFCP(onPerfEntry);
- getLCP(onPerfEntry);
- getTTFB(onPerfEntry);
- });
- }
+const reportWebVitals = (onPerfEntry) => {
+ if (onPerfEntry && onPerfEntry instanceof Function) {
+ import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+ getCLS(onPerfEntry);
+ getFID(onPerfEntry);
+ getFCP(onPerfEntry);
+ getLCP(onPerfEntry);
+ getTTFB(onPerfEntry);
+ });
+ }
};
export default reportWebVitals;
diff --git a/client/src/reports/InLessonReport.jsx b/client/src/reports/InLessonReport.jsx
index 0cd53201..ab680d23 100644
--- a/client/src/reports/InLessonReport.jsx
+++ b/client/src/reports/InLessonReport.jsx
@@ -3,7 +3,11 @@ import { useRedirect, useDataProvider, useNotify } from 'react-admin';
import { useSavableData } from '../../shared/components/import/util';
import { Datagrid as AttDatagrid } from 'src/entities/att-report';
import { Datagrid as GradeDatagrid } from 'src/entities/grade';
-import { useIsInLessonReportWithLate, useIsInLessonReportStartWithTeacher, useIsLessonSignature } from '../utils/appPermissions';
+import {
+ useIsInLessonReportWithLate,
+ useIsInLessonReportStartWithTeacher,
+ useIsLessonSignature,
+} from '../utils/appPermissions';
import { InLessonReport } from './in-lesson-report';
import { getCurrentHebrewYear } from '@shared/utils/yearFilter';
import { useObjectStore } from 'src/utils/storeUtil';
@@ -34,87 +38,96 @@ export default ({ gradeMode = false }) => {
const isShowLate = useIsInLessonReportWithLate();
const isStartWithTeacher = useIsInLessonReportStartWithTeacher();
const hasReportGroupPermission = useIsLessonSignature();
- const { entityLabel, resource, Datagrid, redirectUrl } = useMemo(() => entityConfig[gradeMode ? 1 : 0], [gradeMode]);
- const fileName = useMemo(() => 'דיווח ' + entityLabel + ' ' + new Date().toISOString().split('T')[0], [entityLabel]);
+ const { entityLabel, resource, Datagrid, redirectUrl } = useMemo(
+ () => entityConfig[gradeMode ? 1 : 0],
+ [gradeMode],
+ );
+ const fileName = useMemo(
+ () => 'דיווח ' + entityLabel + ' ' + new Date().toISOString().split('T')[0],
+ [entityLabel],
+ );
const [dataToSave, setDataToSave] = useState(null);
const [signatureMetadata, setSignatureMetadata] = useState(null);
const { value: teacher } = useObjectStore('teacher');
// Pre-save hook: creates ReportGroup & Sessions only when actually saving
- const preSaveHook = useCallback(async (data) => {
- if (!data || !data._formData) {
- return null;
- }
- if (!hasReportGroupPermission) {
- delete data._formData;
- return null;
- }
-
- try {
- const { reportDates, lessonDetails, signatureData, lesson } = data._formData;
-
- // Step 1: Create ReportGroup
- const firstDate = reportDates[0];
- const reportGroupData = {
- name: `${lesson.name} - ${firstDate}`,
- topic: lesson.name,
- signatureData: signatureData || null,
- teacherReferenceId: lesson.teacherReferenceId,
- lessonReferenceId: lesson.id,
- klassReferenceId: lesson.klassReferenceIds[0],
- year: getCurrentHebrewYear(),
- };
-
- const reportGroupResponse = await dataProvider.create('report_group', {
- data: reportGroupData
- });
- const reportGroup = reportGroupResponse.data;
-
- // Step 2: Create ReportGroupSession for each date
- const reportGroupSessions = [];
- for (let index = 0; index < reportDates.length; index++) {
- const reportDate = reportDates[index];
- const details = lessonDetails?.[index];
-
- const sessionData = {
- reportGroupId: reportGroup.id,
- sessionDate: reportDate,
- startTime: details?.lessonStartTime || null,
- endTime: details?.lessonEndTime || null,
- topic: details?.lessonTopic || null,
+ const preSaveHook = useCallback(
+ async (data) => {
+ if (!data || !data._formData) {
+ return null;
+ }
+ if (!hasReportGroupPermission) {
+ delete data._formData;
+ return null;
+ }
+
+ try {
+ const { reportDates, lessonDetails, signatureData, lesson } = data._formData;
+
+ // Step 1: Create ReportGroup
+ const firstDate = reportDates[0];
+ const reportGroupData = {
+ name: `${lesson.name} - ${firstDate}`,
+ topic: lesson.name,
+ signatureData: signatureData || null,
+ teacherReferenceId: lesson.teacherReferenceId,
+ lessonReferenceId: lesson.id,
+ klassReferenceId: lesson.klassReferenceIds[0],
+ year: getCurrentHebrewYear(),
};
- const sessionResponse = await dataProvider.create('report_group_session', {
- data: sessionData
+ const reportGroupResponse = await dataProvider.create('report_group', {
+ data: reportGroupData,
});
- reportGroupSessions.push(sessionResponse.data);
- }
+ const reportGroup = reportGroupResponse.data;
+
+ // Step 2: Create ReportGroupSession for each date
+ const reportGroupSessions = [];
+ for (let index = 0; index < reportDates.length; index++) {
+ const reportDate = reportDates[index];
+ const details = lessonDetails?.[index];
+
+ const sessionData = {
+ reportGroupId: reportGroup.id,
+ sessionDate: reportDate,
+ startTime: details?.lessonStartTime || null,
+ endTime: details?.lessonEndTime || null,
+ topic: details?.lessonTopic || null,
+ };
+
+ const sessionResponse = await dataProvider.create('report_group_session', {
+ data: sessionData,
+ });
+ reportGroupSessions.push(sessionResponse.data);
+ }
+
+ // Step 3: Update data items with reportGroupSessionId
+ const updatedData = data.map((item) => {
+ const dateIndex = item._dateIndex;
+ const sessionId = reportGroupSessions[dateIndex]?.id;
+ const { _dateIndex, ...cleanItem } = item; // Remove temporary field
+ return {
+ ...cleanItem,
+ reportGroupSessionId: sessionId,
+ };
+ });
+
+ // Remove temporary _formData
+ delete updatedData._formData;
- // Step 3: Update data items with reportGroupSessionId
- const updatedData = data.map(item => {
- const dateIndex = item._dateIndex;
- const sessionId = reportGroupSessions[dateIndex]?.id;
- const { _dateIndex, ...cleanItem } = item; // Remove temporary field
+ // Step 4: Return updated data and metadata
return {
- ...cleanItem,
- reportGroupSessionId: sessionId,
+ updatedData,
+ metadata: { reportGroupId: reportGroup.id },
};
- });
-
- // Remove temporary _formData
- delete updatedData._formData;
-
- // Step 4: Return updated data and metadata
- return {
- updatedData,
- metadata: { reportGroupId: reportGroup.id },
- };
- } catch (error) {
- notify('שגיאה ביצירת קבוצת דיווח: ' + (error.message || 'שגיאה לא ידועה'), { type: 'error' });
- console.error('Error creating report group:', error);
- throw error; // Re-throw to prevent save
- }
- }, [hasReportGroupPermission, dataProvider, notify]);
+ } catch (error) {
+ notify('שגיאה ביצירת קבוצת דיווח: ' + (error.message || 'שגיאה לא ידועה'), { type: 'error' });
+ console.error('Error creating report group:', error);
+ throw error; // Re-throw to prevent save
+ }
+ },
+ [hasReportGroupPermission, dataProvider, notify],
+ );
const { data, saveData } = useSavableData(
resource,
@@ -122,7 +135,7 @@ export default ({ gradeMode = false }) => {
dataToSave,
signatureMetadata,
IN_LESSON_FILE_SOURCE,
- preSaveHook
+ preSaveHook,
);
const handleSuccess = useCallback(() => {
@@ -148,4 +161,4 @@ export default ({ gradeMode = false }) => {
teacher={teacher}
/>
);
-};
\ No newline at end of file
+};
diff --git a/client/src/reports/in-lesson-report/FormActions.jsx b/client/src/reports/in-lesson-report/FormActions.jsx
index b83e9fa9..a1a5588e 100644
--- a/client/src/reports/in-lesson-report/FormActions.jsx
+++ b/client/src/reports/in-lesson-report/FormActions.jsx
@@ -11,7 +11,9 @@ export const FormActions = () => {
<>
-
+
{
/>
>
);
-};
\ No newline at end of file
+};
diff --git a/client/src/reports/in-lesson-report/LessonSelector.jsx b/client/src/reports/in-lesson-report/LessonSelector.jsx
index ee5cc1df..984d7259 100644
--- a/client/src/reports/in-lesson-report/LessonSelector.jsx
+++ b/client/src/reports/in-lesson-report/LessonSelector.jsx
@@ -5,8 +5,8 @@ import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
import { defaultYearFilter } from '@shared/utils/yearFilter';
-const lessonKeyAndName = item => `${item.name} (${item.key})`;
-const filterToQuery = searchText => {
+const lessonKeyAndName = (item) => `${item.name} (${item.key})`;
+const filterToQuery = (searchText) => {
const keyMatch = /\((\d+)\)/.exec(searchText);
if (keyMatch) {
return { key: keyMatch[1] };
@@ -29,7 +29,9 @@ export const LessonSelector = ({ onLessonFound, selectedTeacher }) => {
const handleGetLesson = useCallback(async () => {
try {
- const { data: [lesson] } = await dataProvider.getManyReference('lesson', {
+ const {
+ data: [lesson],
+ } = await dataProvider.getManyReference('lesson', {
target: 'key',
id: lessonKey,
pagination: { page: 1, perPage: 1 },
@@ -39,21 +41,25 @@ export const LessonSelector = ({ onLessonFound, selectedTeacher }) => {
throw new Error('Lesson not found');
}
- const allStudents = await Promise.all(lesson.klassReferenceIds.map(async (klassId) => {
- const { data: students } = await dataProvider.getManyReference('student_klass', {
- target: 'klassReferenceId',
- id: klassId,
- pagination: { page: 1, perPage: 1000 },
- sort: { field: 'student.name', order: 'ASC' },
- filter: { year: defaultYearFilter.year },
- });
- return students;
- }));
+ const allStudents = await Promise.all(
+ lesson.klassReferenceIds.map(async (klassId) => {
+ const { data: students } = await dataProvider.getManyReference('student_klass', {
+ target: 'klassReferenceId',
+ id: klassId,
+ pagination: { page: 1, perPage: 1000 },
+ sort: { field: 'student.name', order: 'ASC' },
+ filter: { year: defaultYearFilter.year },
+ });
+ return students;
+ }),
+ );
- const students = [], studentIds = new Set();
- allStudents.flat()
- .filter(student => student.student)
- .forEach(student => {
+ const students = [],
+ studentIds = new Set();
+ allStudents
+ .flat()
+ .filter((student) => student.student)
+ .forEach((student) => {
if (!studentIds.has(student.student.id)) {
students.push(student);
studentIds.add(student.student.id);
@@ -85,14 +91,19 @@ export const LessonSelector = ({ onLessonFound, selectedTeacher }) => {
} label='הצג שיעור' />}
- onSubmit={handleGetLesson}>
+ toolbar={
+
+ } label="הצג שיעור" />
+
+ }
+ onSubmit={handleGetLesson}
+ >
setLessonKey(e)}
@@ -100,7 +111,11 @@ export const LessonSelector = ({ onLessonFound, selectedTeacher }) => {
/>
- setLessonKey(e.target.value)} />
+ setLessonKey(e.target.value)}
+ />
diff --git a/client/src/reports/in-lesson-report/MainReport.jsx b/client/src/reports/in-lesson-report/MainReport.jsx
index a47fcce9..8416d0ce 100644
--- a/client/src/reports/in-lesson-report/MainReport.jsx
+++ b/client/src/reports/in-lesson-report/MainReport.jsx
@@ -19,18 +19,10 @@ export const MainReport = ({ gradeMode, handleSave, storePrefix }) => {
{({ formData }) => (
{!gradeMode && (
-
+
)}
-
+
@@ -39,4 +31,4 @@ export const MainReport = ({ gradeMode, handleSave, storePrefix }) => {
>
);
-};
\ No newline at end of file
+};
diff --git a/client/src/reports/in-lesson-report/ReportHeader.jsx b/client/src/reports/in-lesson-report/ReportHeader.jsx
index c91883eb..c0394416 100644
--- a/client/src/reports/in-lesson-report/ReportHeader.jsx
+++ b/client/src/reports/in-lesson-report/ReportHeader.jsx
@@ -4,7 +4,7 @@ import { ReportContext } from './context';
export const ReportHeader = () => {
const { lesson, gradeMode } = useContext(ReportContext);
-
+
return (
diff --git a/client/src/reports/in-lesson-report/StudentList.jsx b/client/src/reports/in-lesson-report/StudentList.jsx
index d8417d53..fa73cd49 100644
--- a/client/src/reports/in-lesson-report/StudentList.jsx
+++ b/client/src/reports/in-lesson-report/StudentList.jsx
@@ -1,5 +1,14 @@
import React, { useCallback, useContext, useMemo } from 'react';
-import { NumberInput, DateInput, minValue, maxValue, useRecordContext, TextInput, maxLength, required } from 'react-admin';
+import {
+ NumberInput,
+ DateInput,
+ minValue,
+ maxValue,
+ useRecordContext,
+ TextInput,
+ maxLength,
+ required,
+} from 'react-admin';
import Table from '@mui/material/Table';
import { CommonTimeInput } from '@shared/components/fields/CommonTimeInput';
import TableBody from '@mui/material/TableBody';
@@ -39,39 +48,42 @@ export const StudentList = ({ reportDates, setReportDates }) => {
return cols;
}, [gradeMode, isShowLate]);
- const handleDateChange = useCallback((index) => (event) => {
- setReportDates(reportDates => {
- const newDates = [...reportDates];
- newDates[index] = event.target.value;
- return newDates;
- });
- }, [setReportDates]);
+ const handleDateChange = useCallback(
+ (index) => (event) => {
+ setReportDates((reportDates) => {
+ const newDates = [...reportDates];
+ newDates[index] = event.target.value;
+ return newDates;
+ });
+ },
+ [setReportDates],
+ );
const addReportDate = useCallback(() => {
- setReportDates(reportDates => [...reportDates, getDefaultReportDate()]);
+ setReportDates((reportDates) => [...reportDates, getDefaultReportDate()]);
}, [setReportDates]);
- const removeReportDate = useCallback((index) => {
- setReportDates(reportDates => {
- const newDates = [...reportDates];
- newDates.splice(index, 1);
- return newDates;
- });
- }, [setReportDates]);
+ const removeReportDate = useCallback(
+ (index) => {
+ setReportDates((reportDates) => {
+ const newDates = [...reportDates];
+ newDates.splice(index, 1);
+ return newDates;
+ });
+ },
+ [setReportDates],
+ );
return (
-
+
{reportDates.map((date, index) => (
-
+
{
)}
-
+
{hasLessonSignaturePermission && (
<>
{
שם התלמידה
- {reportDates.map((date, index) => (
- columns.map(column => (
+ {reportDates.map((date, index) =>
+ columns.map((column) => (
{column.label}
- ))
- ))}
+ )),
+ )}
- {students && students
- .filter(student => student.student)
- .map(student => (
-
-
- {student.student.name}
-
- {reportDates.map((date, index) => (
-
- ))}
-
- ))}
+ {students &&
+ students
+ .filter((student) => student.student)
+ .map((student) => (
+
+
+ {student.student.name}
+
+ {reportDates.map((date, index) => (
+
+ ))}
+
+ ))}
@@ -166,7 +179,7 @@ const Text = ({ children }) => (
);
-const ReportItemInputs = ({ index, columns, studentId, lessonCount, ...rest }) => (
+const ReportItemInputs = ({ index, columns, studentId, lessonCount, ...rest }) =>
columns.map((column) => (
{column.type === 'number' ? (
@@ -188,12 +201,7 @@ const ReportItemInputs = ({ index, columns, studentId, lessonCount, ...rest }) =
{...rest}
/>
) : (
-
+
)}
- ))
-);
+ ));
diff --git a/client/src/reports/in-lesson-report/TeacherSelector.jsx b/client/src/reports/in-lesson-report/TeacherSelector.jsx
index 5c3fc835..7bb13686 100644
--- a/client/src/reports/in-lesson-report/TeacherSelector.jsx
+++ b/client/src/reports/in-lesson-report/TeacherSelector.jsx
@@ -4,69 +4,81 @@ import { TabbedForm, Toolbar, SaveButton, TextInput, useDataProvider, useNotify
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
-const teacherTzAndName = item => `${item.name} (${item.tz})`;
-const filterToQuery = searchText => {
- const tzMatch = /\((\d+)\)/.exec(searchText);
- if (tzMatch) {
- return { tz: tzMatch[1] };
- }
- return { 'name:$contL': searchText };
-}
+const teacherTzAndName = (item) => `${item.name} (${item.tz})`;
+const filterToQuery = (searchText) => {
+ const tzMatch = /\((\d+)\)/.exec(searchText);
+ if (tzMatch) {
+ return { tz: tzMatch[1] };
+ }
+ return { 'name:$contL': searchText };
+};
export const TeacherSelector = ({ onTeacherSelected }) => {
- const [teacherKey, setTeacherKey] = useState('');
- const dataProvider = useDataProvider();
- const notify = useNotify();
+ const [teacherKey, setTeacherKey] = useState('');
+ const dataProvider = useDataProvider();
+ const notify = useNotify();
- const handleGetTeacher = useCallback(async ({ teacherKey }) => {
- try {
- const { data: teachers } = await dataProvider.getList('teacher', {
- pagination: { page: 1, perPage: 1 },
- filter: { tz: teacherKey },
- });
+ const handleGetTeacher = useCallback(
+ async ({ teacherKey }) => {
+ try {
+ const { data: teachers } = await dataProvider.getList('teacher', {
+ pagination: { page: 1, perPage: 1 },
+ filter: { tz: teacherKey },
+ });
- const teacher = teachers[0];
- if (!teacher) {
- throw new Error('Teacher not found');
- }
- onTeacherSelected(teacher);
- } catch (e) {
- console.error(e);
- notify('לא נמצאה מורה עם הפרטים שהוזנו', { type: 'error' });
- }
- }, [dataProvider, notify, onTeacherSelected]);
+ const teacher = teachers[0];
+ if (!teacher) {
+ throw new Error('Teacher not found');
+ }
+ onTeacherSelected(teacher);
+ } catch (e) {
+ console.error(e);
+ notify('לא נמצאה מורה עם הפרטים שהוזנו', { type: 'error' });
+ }
+ },
+ [dataProvider, notify, onTeacherSelected],
+ );
- return (
- <>
-
-
- בחרי מורה
-
-
- בחרי את המורה שברצונך להעלות דוח נוכחות עבורה
-
-
-
-
- } label='בחר מורה' />}
- onSubmit={handleGetTeacher}>
-
- setTeacherKey(e)}
- />
-
-
- setTeacherKey(e.target.value)} />
-
-
-
- >
- );
+ return (
+ <>
+
+
+ בחרי מורה
+
+
+ בחרי את המורה שברצונך להעלות דוח נוכחות עבורה
+
+
+
+
+
+ } label="בחר מורה" />
+
+ }
+ onSubmit={handleGetTeacher}
+ >
+
+ setTeacherKey(e)}
+ />
+
+
+ setTeacherKey(e.target.value)}
+ />
+
+
+
+ >
+ );
};
diff --git a/client/src/reports/in-lesson-report/index.jsx b/client/src/reports/in-lesson-report/index.jsx
index 9b09867d..36edd360 100644
--- a/client/src/reports/in-lesson-report/index.jsx
+++ b/client/src/reports/in-lesson-report/index.jsx
@@ -40,15 +40,21 @@ export const InLessonReport = ({
}
}, [teacher]);
- const handleTeacherSelect = useCallback((teacher) => {
- setSelectedTeacher(teacher);
- }, [setSelectedTeacher]);
+ const handleTeacherSelect = useCallback(
+ (teacher) => {
+ setSelectedTeacher(teacher);
+ },
+ [setSelectedTeacher],
+ );
- const handleLessonFound = useCallback(({ lesson, students }) => {
- setTimeout(() => {
- setLessonContext({ lesson, students });
- }, 0);
- }, [setLessonContext]);
+ const handleLessonFound = useCallback(
+ ({ lesson, students }) => {
+ setTimeout(() => {
+ setLessonContext({ lesson, students });
+ }, 0);
+ },
+ [setLessonContext],
+ );
const clearData = useCallback(() => {
setLessonContext(null);
@@ -67,52 +73,55 @@ export const InLessonReport = ({
handleSuccess();
}, [clearData, handleSuccess]);
- const handleSave = useCallback(async (formData) => {
- const { reportDates, howManyLessons, lessonDetails, signatureData, ...rest } = formData;
-
- // Build dataToSave array WITHOUT reportGroupSessionId
- // The preSaveHook will add it when actually saving
- const dataToSave = [];
- const entry = {
- teacherReferenceId: lesson.teacherReferenceId,
- klassReferenceId: lesson.klassReferenceIds[0],
- lessonReferenceId: lesson.id,
- };
+ const handleSave = useCallback(
+ async (formData) => {
+ const { reportDates, howManyLessons, lessonDetails, signatureData, ...rest } = formData;
- reportDates.forEach((reportDate, index) => {
- const reportDateEntry = {
- ...entry,
- reportDate,
- // Store index for preSaveHook to match with sessions
- _dateIndex: index,
+ // Build dataToSave array WITHOUT reportGroupSessionId
+ // The preSaveHook will add it when actually saving
+ const dataToSave = [];
+ const entry = {
+ teacherReferenceId: lesson.teacherReferenceId,
+ klassReferenceId: lesson.klassReferenceIds[0],
+ lessonReferenceId: lesson.id,
};
- Object.keys(rest).forEach((studentId) => {
- const newEntry = { ...reportDateEntry, studentReferenceId: studentId };
- if (gradeMode) {
- newEntry.grade = rest[studentId]?.[`grade_${index}`] ?? 0;
- newEntry.comments = rest[studentId]?.[`comments_${index}`] ?? '';
- } else {
- newEntry.howManyLessons = howManyLessons;
- newEntry.absCount = round(
- (rest[studentId]?.[`absence_${index}`] ?? 0) +
- (rest[studentId]?.[`late_${index}`] ?? 0) * lateValue
- );
- }
- dataToSave.push(newEntry);
+ reportDates.forEach((reportDate, index) => {
+ const reportDateEntry = {
+ ...entry,
+ reportDate,
+ // Store index for preSaveHook to match with sessions
+ _dateIndex: index,
+ };
+
+ Object.keys(rest).forEach((studentId) => {
+ const newEntry = { ...reportDateEntry, studentReferenceId: studentId };
+ if (gradeMode) {
+ newEntry.grade = rest[studentId]?.[`grade_${index}`] ?? 0;
+ newEntry.comments = rest[studentId]?.[`comments_${index}`] ?? '';
+ } else {
+ newEntry.howManyLessons = howManyLessons;
+ newEntry.absCount = round(
+ (rest[studentId]?.[`absence_${index}`] ?? 0) +
+ (rest[studentId]?.[`late_${index}`] ?? 0) * lateValue,
+ );
+ }
+ dataToSave.push(newEntry);
+ });
});
- });
- // Store form data for preSaveHook to use
- dataToSave._formData = {
- reportDates,
- lessonDetails,
- signatureData,
- lesson,
- };
+ // Store form data for preSaveHook to use
+ dataToSave._formData = {
+ reportDates,
+ lessonDetails,
+ signatureData,
+ lesson,
+ };
- setDataToSave(dataToSave);
- }, [lesson, gradeMode, lateValue, setDataToSave]);
+ setDataToSave(dataToSave);
+ },
+ [lesson, gradeMode, lateValue, setDataToSave],
+ );
const contextValue = {
...defaultContextValue,
@@ -151,4 +160,4 @@ export const InLessonReport = ({
);
-};
\ No newline at end of file
+};
diff --git a/client/src/reports/studentReportCardReactButton.jsx b/client/src/reports/studentReportCardReactButton.jsx
index c4f47375..c0dac8ee 100644
--- a/client/src/reports/studentReportCardReactButton.jsx
+++ b/client/src/reports/studentReportCardReactButton.jsx
@@ -16,18 +16,30 @@ export default ({ defaultRequestValues }) => {
const reportCardSettings = useReportCardSettings();
return (
- }
- name='studentReportCardReact' filename='תעודה'
+ }
+ name="studentReportCardReact"
+ filename="תעודה"
defaultRequestValues={{ ...defaultValues, ...defaultRequestValues }}
- requestValues={reportCardSettings}>
+ requestValues={reportCardSettings}
+ >
-
-
+
+
-
+
);
-};
\ No newline at end of file
+};
diff --git a/client/src/roadmapFeatures.js b/client/src/roadmapFeatures.js
index fc1cde6c..e2229699 100644
--- a/client/src/roadmapFeatures.js
+++ b/client/src/roadmapFeatures.js
@@ -23,4 +23,4 @@ export default [
// { html: 'הגדרת תקופת זמן לפי יום בשבוע', status: 'בוצע', statusColor: 'success' },
// { html: 'הגדרת תקופת זמן לפי יום בשנה', status: 'נדרשת חשיבה נוספת', statusColor: 'primary' },
// { html: 'יצירת דוחות נוכחות לפי תקופת זמן', status: 'לא יבוצע', statusColor: 'error' },
-].reverse();
\ No newline at end of file
+].reverse();
diff --git a/client/src/settings/DashboardItemsInput.jsx b/client/src/settings/DashboardItemsInput.jsx
index 780fe7dd..72a5848e 100644
--- a/client/src/settings/DashboardItemsInput.jsx
+++ b/client/src/settings/DashboardItemsInput.jsx
@@ -7,56 +7,53 @@ import { CommonEntityNameInput } from '@shared/components/fields/CommonEntityNam
import { CommonJsonInput } from '@shared/components/fields/CommonJsonItem';
export function DashboardItemsInput() {
- return (
-
- }
- aria-controls="dashboard-items-content"
- id="dashboard-items-header"
- >
- הגדרות לוח מחוונים
-
-
-
-
-
-
-
-
-
-
-
-
- )
+ return (
+
+ }
+ aria-controls="dashboard-items-content"
+ id="dashboard-items-header"
+ >
+ הגדרות לוח מחוונים
+
+
+
+
+
+
+
+
+
+
+
+
+ );
}
diff --git a/client/src/settings/GeneralSettingsInput.jsx b/client/src/settings/GeneralSettingsInput.jsx
index d24f9e4c..9f6cd58e 100644
--- a/client/src/settings/GeneralSettingsInput.jsx
+++ b/client/src/settings/GeneralSettingsInput.jsx
@@ -5,32 +5,28 @@ import { NumberInput, required } from 'react-admin';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
import { PAGE_SIZE_OPTIONS } from '@shared/config/settings';
-const pageSizeOptions = PAGE_SIZE_OPTIONS.map(option => ({ id: option, name: option }));
+const pageSizeOptions = PAGE_SIZE_OPTIONS.map((option) => ({ id: option, name: option }));
export function GeneralSettingsInput() {
- return (
-
- }
- aria-controls="general-settings-content"
- id="general-settings-header"
- >
- הגדרות כלליות
-
-
-
-
-
-
- );
+ return (
+
+ }
+ aria-controls="general-settings-content"
+ id="general-settings-header"
+ >
+ הגדרות כלליות
+
+
+
+
+
+
+ );
}
diff --git a/client/src/settings/ReportCardSettingsInput.jsx b/client/src/settings/ReportCardSettingsInput.jsx
index 5b5ba85a..283b2045 100644
--- a/client/src/settings/ReportCardSettingsInput.jsx
+++ b/client/src/settings/ReportCardSettingsInput.jsx
@@ -4,31 +4,33 @@ import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { BooleanInput, Link } from 'react-admin';
export function ReportCardSettingsInput() {
- return (
-
- }
- aria-controls="report-card-settings-content"
- id="report-card-settings-header"
- >
- הגדרות ברירת מחדל לתעודה
-
-
-
- להגדרת תמונות
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- );
-}
\ No newline at end of file
+ return (
+
+ }
+ aria-controls="report-card-settings-content"
+ id="report-card-settings-header"
+ >
+ הגדרות ברירת מחדל לתעודה
+
+
+
+
+ להגדרת תמונות
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/client/src/settings/ReportStylesInput.jsx b/client/src/settings/ReportStylesInput.jsx
index 9da431e2..fb550e18 100644
--- a/client/src/settings/ReportStylesInput.jsx
+++ b/client/src/settings/ReportStylesInput.jsx
@@ -6,57 +6,56 @@ import CommonAutocompleteInput from '@shared/components/fields/CommonAutocomplet
// Common Google Fonts list
const fontOptions = [
- { id: 'Arial', name: 'Arial' },
- { id: 'Open Sans', name: 'Open Sans' },
- { id: 'Roboto', name: 'Roboto' },
- { id: 'Lato', name: 'Lato' },
- { id: 'Montserrat', name: 'Montserrat' },
- { id: 'Raleway', name: 'Raleway' },
- { id: 'Poppins', name: 'Poppins' },
- { id: 'Noto Sans Hebrew', name: 'Noto Sans Hebrew' },
- { id: 'Assistant', name: 'Assistant' },
- { id: 'Heebo', name: 'Heebo' },
- { id: 'Rubik', name: 'Rubik' },
- { id: 'David Libre', name: 'David Libre' },
- { id: 'Varela Round', name: 'Varela Round' },
- { id: 'Times New Roman', name: 'Times New Roman' },
- { id: 'Georgia', name: 'Georgia' }
+ { id: 'Arial', name: 'Arial' },
+ { id: 'Open Sans', name: 'Open Sans' },
+ { id: 'Roboto', name: 'Roboto' },
+ { id: 'Lato', name: 'Lato' },
+ { id: 'Montserrat', name: 'Montserrat' },
+ { id: 'Raleway', name: 'Raleway' },
+ { id: 'Poppins', name: 'Poppins' },
+ { id: 'Noto Sans Hebrew', name: 'Noto Sans Hebrew' },
+ { id: 'Assistant', name: 'Assistant' },
+ { id: 'Heebo', name: 'Heebo' },
+ { id: 'Rubik', name: 'Rubik' },
+ { id: 'David Libre', name: 'David Libre' },
+ { id: 'Varela Round', name: 'Varela Round' },
+ { id: 'Times New Roman', name: 'Times New Roman' },
+ { id: 'Georgia', name: 'Georgia' },
].sort((a, b) => a.name.localeCompare(b.name));
-
export function ReportStylesInput() {
- return (
-
- }
- aria-controls="report-styles-content"
- id="report-styles-header"
- >
- הגדרות עיצוב תעודה
-
-
-
-
-
-
-
-
-
-
-
-
-
- )
-}
\ No newline at end of file
+ return (
+
+ }
+ aria-controls="report-styles-content"
+ id="report-styles-header"
+ >
+ הגדרות עיצוב תעודה
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/client/src/settings/Settings.jsx b/client/src/settings/Settings.jsx
index 68ce6b8e..7da6afc2 100644
--- a/client/src/settings/Settings.jsx
+++ b/client/src/settings/Settings.jsx
@@ -1,6 +1,16 @@
import React from 'react';
import { Card, CardContent } from '@mui/material';
-import { SimpleForm, Title, useNotify, useGetIdentity, useDataProvider, SaveButton, Toolbar, useAuthProvider, ResourceContextProvider } from 'react-admin';
+import {
+ SimpleForm,
+ Title,
+ useNotify,
+ useGetIdentity,
+ useDataProvider,
+ SaveButton,
+ Toolbar,
+ useAuthProvider,
+ ResourceContextProvider,
+} from 'react-admin';
import { useNavigate } from 'react-router-dom';
import { getDefaultPageSize } from '@shared/utils/settingsUtil';
import { getLateValue, getDashboardItems, getReportStyles, getReportCardSettings } from './settingsUtil';
@@ -47,11 +57,7 @@ export default function Settings() {
- }
- >
+ }>
@@ -61,4 +67,4 @@ export default function Settings() {
);
-}
\ No newline at end of file
+}
diff --git a/client/src/settings/settingsUtil.js b/client/src/settings/settingsUtil.js
index df3fcb55..31651390 100644
--- a/client/src/settings/settingsUtil.js
+++ b/client/src/settings/settingsUtil.js
@@ -1,8 +1,8 @@
-import { useGetIdentity } from "react-admin";
+import { useGetIdentity } from 'react-admin';
export function useLateValue() {
- const { identity } = useGetIdentity();
- return getLateValue(identity);
+ const { identity } = useGetIdentity();
+ return getLateValue(identity);
}
export function getLateValue(identity) {
@@ -12,7 +12,7 @@ export function getLateValue(identity) {
export const useDashboardItems = () => {
const { identity } = useGetIdentity();
return getDashboardItems(identity);
-}
+};
export function getDashboardItems(identity) {
return identity?.additionalData?.dashboardItems || getDefaultDashboardItems();
@@ -24,21 +24,21 @@ export function getDefaultDashboardItems() {
resource: 'att_report_with_report_month',
icon: 'List',
yearFilterType: 'year',
- filter: {}
+ filter: {},
},
{
resource: 'student_by_year',
icon: 'List',
yearFilterType: 'year',
- filter: {}
- }
+ filter: {},
+ },
];
}
export const useReportStyles = () => {
const { identity } = useGetIdentity();
return getReportStyles(identity);
-}
+};
export function getReportStyles(identity) {
return identity?.additionalData?.reportStyles || [];
@@ -47,7 +47,7 @@ export function getReportStyles(identity) {
export const useReportCardSettings = () => {
const { identity } = useGetIdentity();
return getReportCardSettings(identity);
-}
+};
export function getReportCardSettings(identity) {
return identity?.additionalData?.reportCardSettings || getDefaultReportCardSettings();
@@ -65,6 +65,6 @@ export function getDefaultReportCardSettings() {
forceGrades: false,
downComment: false,
lastGrade: true,
- debug: true
+ debug: true,
};
-}
\ No newline at end of file
+}
diff --git a/client/src/utils/appPermissions.js b/client/src/utils/appPermissions.js
index b7c25e46..3388a8ce 100644
--- a/client/src/utils/appPermissions.js
+++ b/client/src/utils/appPermissions.js
@@ -1,31 +1,35 @@
import { useHasPermission, hasPermissionLogic, isAdmin } from '@shared/utils/permissionsUtil';
export const appPermissions = {
- scannerUpload: 'scannerUpload',
- inLessonReport: 'inLessonReport',
- inLessonReportWithLate: 'inLessonReport.withLate',
- inLessonReportOnly: 'inLessonReport.only',
- inLessonReportStartWithTeacher: 'inLessonReport.startWithTeacher',
- absCountEffect: 'absCountEffect',
- lessonSignature: 'lessonSignature',
- approvedAbsencesBulk: 'approvedAbsencesBulk',
- teacherView: 'teacherView',
- transportation: 'transportation',
- absenceType: 'absenceType',
- studentView: 'studentView',
+ scannerUpload: 'scannerUpload',
+ inLessonReport: 'inLessonReport',
+ inLessonReportWithLate: 'inLessonReport.withLate',
+ inLessonReportOnly: 'inLessonReport.only',
+ inLessonReportStartWithTeacher: 'inLessonReport.startWithTeacher',
+ absCountEffect: 'absCountEffect',
+ lessonSignature: 'lessonSignature',
+ approvedAbsencesBulk: 'approvedAbsencesBulk',
+ teacherView: 'teacherView',
+ transportation: 'transportation',
+ absenceType: 'absenceType',
+ studentView: 'studentView',
};
export const isScannerUpload = (permissions) => hasPermissionLogic(permissions, appPermissions.scannerUpload);
export const useIsScannerUpload = () => useHasPermission(appPermissions.scannerUpload);
-export const isInLessonReport = (permissions) => isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReport);
+export const isInLessonReport = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReport);
export const useIsInLessonReport = () => useHasPermission(appPermissions.inLessonReport);
-export const isInLessonReportWithLate = (permissions) => isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReportWithLate);
+export const isInLessonReportWithLate = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReportWithLate);
export const useIsInLessonReportWithLate = () => useHasPermission(appPermissions.inLessonReportWithLate);
-export const isInLessonReportStartWithTeacher = (permissions) => isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReportStartWithTeacher);
-export const useIsInLessonReportStartWithTeacher = () => useHasPermission(appPermissions.inLessonReportStartWithTeacher);
+export const isInLessonReportStartWithTeacher = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.inLessonReportStartWithTeacher);
+export const useIsInLessonReportStartWithTeacher = () =>
+ useHasPermission(appPermissions.inLessonReportStartWithTeacher);
export const isOnlyInLessonReport = (permissions) => hasPermissionLogic(permissions, appPermissions.inLessonReportOnly);
export const useIsOnlyInLessonReport = () => useHasPermission(appPermissions.inLessonReportOnly);
@@ -33,10 +37,12 @@ export const useIsOnlyInLessonReport = () => useHasPermission(appPermissions.inL
export const isAbsCountEffect = (permissions) => hasPermissionLogic(permissions, appPermissions.absCountEffect);
export const useIsAbsCountEffect = () => useHasPermission(appPermissions.absCountEffect);
-export const isLessonSignature = (permissions) => isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.lessonSignature);
+export const isLessonSignature = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.lessonSignature);
export const useIsLessonSignature = () => useHasPermission(appPermissions.lessonSignature);
-export const isApprovedAbsencesBulk = (permissions) => isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.approvedAbsencesBulk);
+export const isApprovedAbsencesBulk = (permissions) =>
+ isAdmin(permissions) || hasPermissionLogic(permissions, appPermissions.approvedAbsencesBulk);
export const useIsApprovedAbsencesBulk = () => useHasPermission(appPermissions.approvedAbsencesBulk);
export const isTeacherView = (permissions) => hasPermissionLogic(permissions, appPermissions.teacherView);
@@ -50,4 +56,3 @@ export const useIsAbsenceType = () => useHasPermission(appPermissions.absenceTyp
export const isStudentView = (permissions) => hasPermissionLogic(permissions, appPermissions.studentView);
export const useIsStudentView = () => useHasPermission(appPermissions.studentView);
-
diff --git a/client/src/utils/storeUtil.ts b/client/src/utils/storeUtil.ts
index f6084c0c..3da62de5 100644
--- a/client/src/utils/storeUtil.ts
+++ b/client/src/utils/storeUtil.ts
@@ -23,4 +23,3 @@ export const useObjectStore = (storeKey: string): ObjectStore => {
clear,
};
};
-
diff --git a/server/.prettierignore b/server/.prettierignore
new file mode 100644
index 00000000..5c417cc8
--- /dev/null
+++ b/server/.prettierignore
@@ -0,0 +1 @@
+src/migrations/
diff --git a/server/.prettierrc b/server/.prettierrc
index dcb72794..9db28a2b 100644
--- a/server/.prettierrc
+++ b/server/.prettierrc
@@ -1,4 +1,5 @@
{
"singleQuote": true,
- "trailingComma": "all"
-}
\ No newline at end of file
+ "trailingComma": "all",
+ "printWidth": 120
+}
diff --git a/server/src/__tests__/entities.module.spec.ts b/server/src/__tests__/entities.module.spec.ts
index 447043cd..7c381058 100644
--- a/server/src/__tests__/entities.module.spec.ts
+++ b/server/src/__tests__/entities.module.spec.ts
@@ -9,18 +9,20 @@ jest.mock('@shared/base-entity/base-entity.module', () => {
const MockBaseEntityModule = {
register: jest.fn().mockReturnValue({
module: class MockBaseEntityModule {},
- providers: [{
- provide: 'CONFIG',
- useValue: { entity: class MockEntity {} }
- }]
- })
+ providers: [
+ {
+ provide: 'CONFIG',
+ useValue: { entity: class MockEntity {} },
+ },
+ ],
+ }),
};
-
+
// Export the mock for tests to use
global.MockBaseEntityModule = MockBaseEntityModule;
-
+
return {
- BaseEntityModule: MockBaseEntityModule
+ BaseEntityModule: MockBaseEntityModule,
};
});
@@ -42,16 +44,16 @@ import textConfig from '../../shared/entities/configs/text.config';
import { StudentBaseKlass } from '../db/view-entities/StudentBaseKlass.entity';
import { YemotCall } from '@shared/entities/YemotCall.entity';
import { RecievedMail } from '@shared/entities/RecievedMail.entity';
-import { Image } from "@shared/entities/Image.entity";
+import { Image } from '@shared/entities/Image.entity';
import { ReportMonth } from '../db/entities/ReportMonth.entity';
-import { AttReportAndGrade } from "../db/view-entities/AttReportAndGrade.entity";
-import { StudentGlobalReport } from "../db/view-entities/StudentGlobalReport.entity";
-import { KnownAbsenceWithReportMonth } from "../db/view-entities/KnownAbsenceWithReportMonth.entity";
-import { GradeName } from "../db/entities/GradeName.entity";
-import { AttGradeEffect } from "../db/entities/AttGradeEffect";
-import { GradeEffectByUser } from "src/db/view-entities/GradeEffectByUser.entity";
-import { AbsCountEffectByUser } from "src/db/view-entities/AbsCountEffectByUser.entity";
-import { LessonKlassName } from "../db/view-entities/LessonKlassName.entity";
+import { AttReportAndGrade } from '../db/view-entities/AttReportAndGrade.entity';
+import { StudentGlobalReport } from '../db/view-entities/StudentGlobalReport.entity';
+import { KnownAbsenceWithReportMonth } from '../db/view-entities/KnownAbsenceWithReportMonth.entity';
+import { GradeName } from '../db/entities/GradeName.entity';
+import { AttGradeEffect } from '../db/entities/AttGradeEffect';
+import { GradeEffectByUser } from 'src/db/view-entities/GradeEffectByUser.entity';
+import { AbsCountEffectByUser } from 'src/db/view-entities/AbsCountEffectByUser.entity';
+import { LessonKlassName } from '../db/view-entities/LessonKlassName.entity';
describe('EntitiesModule', () => {
let module: TestingModule;
@@ -63,13 +65,13 @@ describe('EntitiesModule', () => {
getRepository: jest.fn().mockReturnValue({
metadata: {
columns: [],
- relations: []
- }
+ relations: [],
+ },
}),
getMetadata: jest.fn().mockReturnValue({
columns: [],
- relations: []
- })
+ relations: [],
+ }),
};
// Create test module
@@ -107,13 +109,13 @@ describe('EntitiesModule', () => {
AttGradeEffect,
GradeEffectByUser,
AbsCountEffectByUser,
- LessonKlassName
+ LessonKlassName,
],
- synchronize: true
- }
- })
- }
- ]
+ synchronize: true,
+ },
+ }),
+ },
+ ],
}).compile();
});
@@ -126,8 +128,8 @@ describe('EntitiesModule', () => {
const imports = Reflect.getMetadata('imports', EntitiesModule);
expect(imports).toBeDefined();
expect(Array.isArray(imports)).toBe(true);
-
- imports.forEach(imp => {
+
+ imports.forEach((imp) => {
expect(typeof imp).toBe('object');
expect(imp).toHaveProperty('module');
});
@@ -146,7 +148,7 @@ describe('EntitiesModule', () => {
{ name: 'studentKlassConfig', config: studentKlassConfig },
{ name: 'studentConfig', config: studentConfig },
{ name: 'teacherConfig', config: teacherConfig },
- { name: 'textConfig', config: textConfig }
+ { name: 'textConfig', config: textConfig },
];
configsToTest.forEach(({ name, config }) => {
@@ -169,7 +171,7 @@ describe('EntitiesModule', () => {
{ name: 'AttGradeEffect', entity: AttGradeEffect },
{ name: 'GradeEffectByUser', entity: GradeEffectByUser },
{ name: 'AbsCountEffectByUser', entity: AbsCountEffectByUser },
- { name: 'LessonKlassName', entity: LessonKlassName }
+ { name: 'LessonKlassName', entity: LessonKlassName },
];
entitiesToTest.forEach(({ name, entity }) => {
@@ -177,7 +179,7 @@ describe('EntitiesModule', () => {
expect(entity).toBeDefined();
// Verify the entity is registered with TypeORM
const metadata = getMetadataArgsStorage();
- const entityMetadata = metadata.tables.find(table => {
+ const entityMetadata = metadata.tables.find((table) => {
const target = table.target;
if (typeof target === 'function') {
return target === entity;
@@ -195,7 +197,7 @@ describe('EntitiesModule', () => {
expect(imports).toBeDefined();
expect(Array.isArray(imports)).toBe(true);
- imports.forEach(imp => {
+ imports.forEach((imp) => {
expect(typeof imp).toBe('object');
expect(imp).toHaveProperty('module');
expect(imp).toHaveProperty('providers');
@@ -205,11 +207,11 @@ describe('EntitiesModule', () => {
it('should have valid configurations for all registered entities', () => {
const imports = Reflect.getMetadata('imports', EntitiesModule);
- imports.forEach(imp => {
- const config = imp.providers.find(p => p.provide === 'CONFIG').useValue;
+ imports.forEach((imp) => {
+ const config = imp.providers.find((p) => p.provide === 'CONFIG').useValue;
expect(config).toBeDefined();
expect(config.entity).toBeDefined();
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/db/entities/AbsenceType.entity.ts b/server/src/db/entities/AbsenceType.entity.ts
index 40d67e60..89fdb6ea 100644
--- a/server/src/db/entities/AbsenceType.entity.ts
+++ b/server/src/db/entities/AbsenceType.entity.ts
@@ -1,24 +1,16 @@
-import {
- Column,
- Entity,
- Index,
- JoinColumn,
- PrimaryGeneratedColumn,
- BeforeInsert,
- BeforeUpdate,
-} from 'typeorm';
+import { Column, Entity, Index, JoinColumn, PrimaryGeneratedColumn, BeforeInsert, BeforeUpdate } from 'typeorm';
import { IHasUserId } from '@shared/base-entity/interface';
import { User } from 'src/db/entities/User.entity';
import { IsOptional, Min } from 'class-validator';
import { CrudValidationGroups } from '@dataui/crud';
import { IsNotEmpty, IsUniqueCombination, MaxLength, IsNumber } from '@shared/utils/validation/class-validator-he';
import { StringType, NumberType } from '@shared/utils/entity/class-transformer';
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
@Index('absenceTypes_users_idx', ['userId'], {})
@Index(['userId', 'name', 'year'], { unique: true })
-@Entity('absenceTypes')
+@Entity('absenceTypes')
export class AbsenceType implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -43,15 +35,15 @@ export class AbsenceType implements IHasUserId {
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Min(0, { always: true })
+ @Min(0, { always: true })
@NumberType
@Column('decimal', { name: 'quota', precision: 5, scale: 1 })
quota: number;
@IsOptional({ always: true })
@Column({
- type: 'simple-array',
- name: 'required_labels',
+ type: 'simple-array',
+ name: 'required_labels',
nullable: true,
})
requiredLabels: string[] | null;
@@ -64,4 +56,4 @@ export class AbsenceType implements IHasUserId {
@JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
-}
\ No newline at end of file
+}
diff --git a/server/src/db/entities/AttGradeEffect.ts b/server/src/db/entities/AttGradeEffect.ts
index 1ed83aa9..3d42d52a 100644
--- a/server/src/db/entities/AttGradeEffect.ts
+++ b/server/src/db/entities/AttGradeEffect.ts
@@ -1,23 +1,18 @@
-import {
- Column,
- Entity,
- Index,
- PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { IsOptional } from "class-validator";
-import { IsNotEmpty, IsNumber } from "@shared/utils/validation/class-validator-he";
-import { CrudValidationGroups } from "@dataui/crud";
-import { NumberType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { IsOptional } from 'class-validator';
+import { IsNotEmpty, IsNumber } from '@shared/utils/validation/class-validator-he';
+import { CrudValidationGroups } from '@dataui/crud';
+import { NumberType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Entity("att_grade_effect")
+@Entity('att_grade_effect')
export class AttGradeEffect implements IHasUserId {
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
- @Index("att_grade_effect_user_id_idx")
+ @Column('int', { name: 'user_id' })
+ @Index('att_grade_effect_user_id_idx')
userId: number;
@IsOptional({ always: true })
diff --git a/server/src/db/entities/AttReport.entity.ts b/server/src/db/entities/AttReport.entity.ts
index d59a3d78..b175d996 100644
--- a/server/src/db/entities/AttReport.entity.ts
+++ b/server/src/db/entities/AttReport.entity.ts
@@ -8,35 +8,43 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Klass } from "./Klass.entity";
-import { Lesson } from "./Lesson.entity";
-import { Student } from "./Student.entity";
-import { Teacher } from "./Teacher.entity";
-import { StudentBaseKlass } from "../view-entities/StudentBaseKlass.entity";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { User } from "./User.entity";
-import { KlassType } from "./KlassType.entity";
-import { IsOptional, ValidateIf } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsNumber, MaxLength, IsDate, IsPositive } from "@shared/utils/validation/class-validator-he";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { fillDefaultReportDateValue } from "@shared/utils/entity/deafultValues.util";
-import { DateType, NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { LessonKlassName } from "../view-entities/LessonKlassName.entity";
-import { ReportGroupSession } from "./ReportGroupSession.entity";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("att_users_idx", ["userId"], {})
-@Index("att_user_sheet_name_lession_klass_year_idx", ["userId", "sheetName", "lessonReferenceId", "klassReferenceId", "year"], {})
-@Index("att_user_year_idx", ["userId", "year"], {})
-@Index("att_user_year_student_reference_id_idx", ["userId", "studentReferenceId", "year"], {})
-@Index("att_user_year_teacher_reference_id_idx", ["userId", "teacherReferenceId", "year"], {})
-@Index("att_user_year_lesson_reference_id_idx", ["userId", "lessonReferenceId", "year"], {})
-@Index("att_user_year_student_teacher_klass_lesson_idx", ["userId", "year", "studentReferenceId", "teacherReferenceId", "klassReferenceId", "lessonReferenceId"], {})
-@Index("att_teacher_lesson_date_idx", ["teacherReferenceId", "lessonReferenceId", "reportDate"], {})
-@Entity("att_reports")
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Klass } from './Klass.entity';
+import { Lesson } from './Lesson.entity';
+import { Student } from './Student.entity';
+import { Teacher } from './Teacher.entity';
+import { StudentBaseKlass } from '../view-entities/StudentBaseKlass.entity';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { User } from './User.entity';
+import { KlassType } from './KlassType.entity';
+import { IsOptional, ValidateIf } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsNumber, MaxLength, IsDate, IsPositive } from '@shared/utils/validation/class-validator-he';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { fillDefaultReportDateValue } from '@shared/utils/entity/deafultValues.util';
+import { DateType, NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { LessonKlassName } from '../view-entities/LessonKlassName.entity';
+import { ReportGroupSession } from './ReportGroupSession.entity';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('att_users_idx', ['userId'], {})
+@Index(
+ 'att_user_sheet_name_lession_klass_year_idx',
+ ['userId', 'sheetName', 'lessonReferenceId', 'klassReferenceId', 'year'],
+ {},
+)
+@Index('att_user_year_idx', ['userId', 'year'], {})
+@Index('att_user_year_student_reference_id_idx', ['userId', 'studentReferenceId', 'year'], {})
+@Index('att_user_year_teacher_reference_id_idx', ['userId', 'teacherReferenceId', 'year'], {})
+@Index('att_user_year_lesson_reference_id_idx', ['userId', 'lessonReferenceId', 'year'], {})
+@Index(
+ 'att_user_year_student_teacher_klass_lesson_idx',
+ ['userId', 'year', 'studentReferenceId', 'teacherReferenceId', 'klassReferenceId', 'lessonReferenceId'],
+ {},
+)
+@Index('att_teacher_lesson_date_idx', ['teacherReferenceId', 'lessonReferenceId', 'reportDate'], {})
+@Entity('att_reports')
export class AttReport implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -49,26 +57,46 @@ export class AttReport implements IHasUserId {
dataSource = await getDataSource([Student, Teacher, Klass, Lesson, User, KlassType, LessonKlassName]);
this.studentReferenceId = await findOneAndAssignReferenceId(
- dataSource, Student, { tz: this.studentTz }, this.userId, this.studentReferenceId, this.studentTz
+ dataSource,
+ Student,
+ { tz: this.studentTz },
+ this.userId,
+ this.studentReferenceId,
+ this.studentTz,
);
this.teacherReferenceId = await findOneAndAssignReferenceId(
- dataSource, Teacher, { tz: this.teacherId }, this.userId, this.teacherReferenceId, this.teacherId
+ dataSource,
+ Teacher,
+ { tz: this.teacherId },
+ this.userId,
+ this.teacherReferenceId,
+ this.teacherId,
);
this.klassReferenceId = await findOneAndAssignReferenceId(
- dataSource, Klass, { year: this.year, key: this.klassId }, this.userId, this.klassReferenceId, this.klassId
+ dataSource,
+ Klass,
+ { year: this.year, key: this.klassId },
+ this.userId,
+ this.klassReferenceId,
+ this.klassId,
);
this.lessonReferenceId = await findOneAndAssignReferenceId(
- dataSource, Lesson, { year: this.year, key: this.lessonId }, this.userId, this.lessonReferenceId, this.lessonId
+ dataSource,
+ Lesson,
+ { year: this.year, key: this.lessonId },
+ this.userId,
+ this.lessonReferenceId,
+ this.lessonId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -76,24 +104,28 @@ export class AttReport implements IHasUserId {
@ValidateIf((attReport: AttReport) => !Boolean(attReport.studentReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "student_tz", length: 10, nullable: true })
+ @Column('varchar', { name: 'student_tz', length: 10, nullable: true })
studentTz: string;
- @ValidateIf((attReport: AttReport) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), { always: true })
+ @ValidateIf((attReport: AttReport) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("att_reports_student_reference_id_idx")
+ @Index('att_reports_student_reference_id_idx')
studentReferenceId: number;
@ValidateIf((attReport: AttReport) => !Boolean(attReport.teacherReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "teacher_id", length: 10, nullable: true })
+ @Column('varchar', { name: 'teacher_id', length: 10, nullable: true })
teacherId: string;
- @ValidateIf((attReport: AttReport) => !Boolean(attReport.teacherId) && Boolean(attReport.teacherReferenceId), { always: true })
+ @ValidateIf((attReport: AttReport) => !Boolean(attReport.teacherId) && Boolean(attReport.teacherReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("att_reports_teacher_reference_id_idx")
+ @Index('att_reports_teacher_reference_id_idx')
teacherReferenceId: number;
@ValidateIf((attReport: AttReport) => !Boolean(attReport.klassReferenceId), { always: true })
@@ -101,64 +133,68 @@ export class AttReport implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "klass_id", nullable: true })
+ @Column('int', { name: 'klass_id', nullable: true })
klassId: number | null;
- @ValidateIf((attReport: AttReport) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), { always: true })
+ @ValidateIf((attReport: AttReport) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("att_reports_klass_reference_id_idx")
+ @Index('att_reports_klass_reference_id_idx')
klassReferenceId: number;
@ValidateIf((attReport: AttReport) => !Boolean(attReport.lessonReferenceId), { always: true })
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "lesson_id", nullable: true })
+ @Column('int', { name: 'lesson_id', nullable: true })
lessonId: number;
- @ValidateIf((attReport: AttReport) => !Boolean(attReport.lessonId) && Boolean(attReport.lessonReferenceId), { always: true })
+ @ValidateIf((attReport: AttReport) => !Boolean(attReport.lessonId) && Boolean(attReport.lessonReferenceId), {
+ always: true,
+ })
@Column({ nullable: true })
- @Index("att_reports_lesson_reference_id_idx")
+ @Index('att_reports_lesson_reference_id_idx')
lessonReferenceId: number;
- @Column("date", { name: "report_date" })
+ @Column('date', { name: 'report_date' })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@DateType
@IsDate({ always: true })
- @Index("att_reports_report_date_idx")
+ @Index('att_reports_report_date_idx')
reportDate: Date;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
@IsPositive({ always: true })
- @Column("float", { name: "how_many_lessons", nullable: true })
+ @Column('float', { name: 'how_many_lessons', nullable: true })
howManyLessons: number | null;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
- @Column("float", { name: "abs_count", default: () => "'0'" })
+ @Column('float', { name: 'abs_count', default: () => "'0'" })
absCount: number;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
- @Column("float", { name: "approved_abs_count", default: () => "'0'" })
+ @Column('float', { name: 'approved_abs_count', default: () => "'0'" })
approvedAbsCount: number;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "comments", nullable: true, length: 500 })
+ @Column('varchar', { name: 'comments', nullable: true, length: 500 })
comments: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(100, { always: true })
- @Column("varchar", { name: "sheet_name", nullable: true, length: 100 })
+ @Column('varchar', { name: 'sheet_name', nullable: true, length: 100 })
sheetName: string | null;
@CreatedAtColumn()
@@ -175,7 +211,7 @@ export class AttReport implements IHasUserId {
@JoinColumn([
{ name: 'user_id', referencedColumnName: 'userId' },
{ name: 'studentReferenceId', referencedColumnName: 'id' },
- { name: 'year', referencedColumnName: 'year' }
+ { name: 'year', referencedColumnName: 'year' },
])
studentBaseKlass: StudentBaseKlass;
@@ -192,10 +228,10 @@ export class AttReport implements IHasUserId {
klass: Klass;
@Column({ nullable: true })
- @Index("att_reports_report_group_session_id_idx")
+ @Index('att_reports_report_group_session_id_idx')
reportGroupSessionId: number;
- @ManyToOne(() => ReportGroupSession, session => session.attReports, { nullable: true })
+ @ManyToOne(() => ReportGroupSession, (session) => session.attReports, { nullable: true })
@JoinColumn({ name: 'reportGroupSessionId' })
reportGroupSession: ReportGroupSession;
}
diff --git a/server/src/db/entities/AttendanceName.entity.ts b/server/src/db/entities/AttendanceName.entity.ts
index c4676e57..3984c03b 100644
--- a/server/src/db/entities/AttendanceName.entity.ts
+++ b/server/src/db/entities/AttendanceName.entity.ts
@@ -1,36 +1,31 @@
-import {
- Column,
- Entity,
- Index,
- PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { IsOptional } from "class-validator";
-import { IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { CrudValidationGroups } from "@dataui/crud";
-import { NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { IsOptional } from 'class-validator';
+import { IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { CrudValidationGroups } from '@dataui/crud';
+import { NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Entity("attendance_names")
+@Entity('attendance_names')
export class AttendanceName implements IHasUserId {
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
- @Index("attendance_names_user_id_idx")
+ @Column('int', { name: 'user_id' })
+ @Index('attendance_names_user_id_idx')
userId: number;
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "key" })
+ @Column('int', { name: 'key' })
key: number;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "name", length: 500, nullable: true })
+ @Column('varchar', { name: 'name', length: 500, nullable: true })
name: string;
@CreatedAtColumn()
diff --git a/server/src/db/entities/Grade.entity.ts b/server/src/db/entities/Grade.entity.ts
index 48c12903..62fc924d 100644
--- a/server/src/db/entities/Grade.entity.ts
+++ b/server/src/db/entities/Grade.entity.ts
@@ -8,31 +8,35 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "src/db/entities/User.entity";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { Student } from "./Student.entity";
-import { Klass } from "./Klass.entity";
-import { Lesson } from "./Lesson.entity";
-import { Teacher } from "./Teacher.entity";
-import { KlassType } from "./KlassType.entity";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { fillDefaultReportDateValue } from "@shared/utils/entity/deafultValues.util";
-import { IsOptional, ValidateIf } from "class-validator";
-import { IsDate, IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { CrudValidationGroups } from "@dataui/crud";
-import { StudentBaseKlass } from "../view-entities/StudentBaseKlass.entity";
-import { DateType, NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { LessonKlassName } from "../view-entities/LessonKlassName.entity";
-import { ReportGroupSession } from "./ReportGroupSession.entity";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("grades_users_idx", ["userId"], {})
-@Index("grades_user_year_idx", ["userId", "year"], {})
-@Index("grades_user_lesson_klass_year_idx", ["userId", "lessonReferenceId", "klassReferenceId", "year"], {})
-@Index("grades_user_year_student_teacher_klass_lesson_idx", ["userId", "year", "studentReferenceId", "teacherReferenceId", "klassReferenceId", "lessonReferenceId"], {})
-@Entity("grades")
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from 'src/db/entities/User.entity';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { Student } from './Student.entity';
+import { Klass } from './Klass.entity';
+import { Lesson } from './Lesson.entity';
+import { Teacher } from './Teacher.entity';
+import { KlassType } from './KlassType.entity';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { fillDefaultReportDateValue } from '@shared/utils/entity/deafultValues.util';
+import { IsOptional, ValidateIf } from 'class-validator';
+import { IsDate, IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { CrudValidationGroups } from '@dataui/crud';
+import { StudentBaseKlass } from '../view-entities/StudentBaseKlass.entity';
+import { DateType, NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { LessonKlassName } from '../view-entities/LessonKlassName.entity';
+import { ReportGroupSession } from './ReportGroupSession.entity';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('grades_users_idx', ['userId'], {})
+@Index('grades_user_year_idx', ['userId', 'year'], {})
+@Index('grades_user_lesson_klass_year_idx', ['userId', 'lessonReferenceId', 'klassReferenceId', 'year'], {})
+@Index(
+ 'grades_user_year_student_teacher_klass_lesson_idx',
+ ['userId', 'year', 'studentReferenceId', 'teacherReferenceId', 'klassReferenceId', 'lessonReferenceId'],
+ {},
+)
+@Entity('grades')
export class Grade implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -45,26 +49,46 @@ export class Grade implements IHasUserId {
dataSource = await getDataSource([Student, Teacher, Klass, Lesson, User, KlassType, LessonKlassName]);
this.studentReferenceId = await findOneAndAssignReferenceId(
- dataSource, Student, { tz: this.studentTz }, this.userId, this.studentReferenceId, this.studentTz
+ dataSource,
+ Student,
+ { tz: this.studentTz },
+ this.userId,
+ this.studentReferenceId,
+ this.studentTz,
);
this.teacherReferenceId = await findOneAndAssignReferenceId(
- dataSource, Teacher, { tz: this.teacherId }, this.userId, this.teacherReferenceId, this.teacherId
+ dataSource,
+ Teacher,
+ { tz: this.teacherId },
+ this.userId,
+ this.teacherReferenceId,
+ this.teacherId,
);
this.klassReferenceId = await findOneAndAssignReferenceId(
- dataSource, Klass, { year: this.year, key: this.klassId }, this.userId, this.klassReferenceId, this.klassId
+ dataSource,
+ Klass,
+ { year: this.year, key: this.klassId },
+ this.userId,
+ this.klassReferenceId,
+ this.klassId,
);
this.lessonReferenceId = await findOneAndAssignReferenceId(
- dataSource, Lesson, { year: this.year, key: this.lessonId }, this.userId, this.lessonReferenceId, this.lessonId
+ dataSource,
+ Lesson,
+ { year: this.year, key: this.lessonId },
+ this.userId,
+ this.lessonReferenceId,
+ this.lessonId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -72,24 +96,24 @@ export class Grade implements IHasUserId {
@ValidateIf((grade: Grade) => !Boolean(grade.studentReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "student_tz", length: 10, nullable: true })
+ @Column('varchar', { name: 'student_tz', length: 10, nullable: true })
studentTz: string;
@ValidateIf((grade: Grade) => !Boolean(grade.studentTz) && Boolean(grade.studentReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("grades_student_reference_id_idx")
+ @Index('grades_student_reference_id_idx')
studentReferenceId: number;
@ValidateIf((grade: Grade) => !Boolean(grade.teacherReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "teacher_id", length: 10, nullable: true })
+ @Column('varchar', { name: 'teacher_id', length: 10, nullable: true })
teacherId: string;
@ValidateIf((grade: Grade) => !Boolean(grade.teacherId) && Boolean(grade.teacherReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("grades_teacher_reference_id_idx")
+ @Index('grades_teacher_reference_id_idx')
teacherReferenceId: number;
@ValidateIf((grade: Grade) => !Boolean(grade.klassReferenceId), { always: true })
@@ -97,57 +121,57 @@ export class Grade implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "klass_id", nullable: true })
+ @Column('int', { name: 'klass_id', nullable: true })
klassId: number | null;
@ValidateIf((grade: Grade) => !Boolean(grade.klassId) && Boolean(grade.klassReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("grades_klass_reference_id_idx")
+ @Index('grades_klass_reference_id_idx')
klassReferenceId: number;
@ValidateIf((grade: Grade) => !Boolean(grade.lessonReferenceId), { always: true })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "lesson_id", nullable: true })
+ @Column('int', { name: 'lesson_id', nullable: true })
lessonId: number;
@ValidateIf((grade: Grade) => !Boolean(grade.lessonId) && Boolean(grade.lessonReferenceId), { always: true })
@Column({ nullable: true })
- @Index("grades_lesson_reference_id_idx")
+ @Index('grades_lesson_reference_id_idx')
lessonReferenceId: number;
- @Column("date", { name: "report_date" })
+ @Column('date', { name: 'report_date' })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@DateType
@IsDate({ always: true })
- @Index("grades_report_date_idx")
+ @Index('grades_report_date_idx')
reportDate: Date;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
- @Column("float", { name: "how_many_lessons", nullable: true })
+ @Column('float', { name: 'how_many_lessons', nullable: true })
howManyLessons: number | null;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
- @Column("float", { name: "grade", default: () => "'0'" })
+ @Column('float', { name: 'grade', default: () => "'0'" })
grade: number;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "estimation", nullable: true, length: 500 })
+ @Column('varchar', { name: 'estimation', nullable: true, length: 500 })
estimation: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "comments", nullable: true, length: 500 })
+ @Column('varchar', { name: 'comments', nullable: true, length: 500 })
comments: string | null;
@CreatedAtColumn()
@@ -157,10 +181,10 @@ export class Grade implements IHasUserId {
updatedAt: Date;
@ManyToOne(() => User, (user) => user.grades, {
- onDelete: "NO ACTION",
- onUpdate: "NO ACTION",
+ onDelete: 'NO ACTION',
+ onUpdate: 'NO ACTION',
})
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
@ManyToOne(() => Student, { createForeignKeyConstraints: false })
@@ -168,7 +192,10 @@ export class Grade implements IHasUserId {
student: Student;
@ManyToOne(() => StudentBaseKlass, { createForeignKeyConstraints: false })
- @JoinColumn([{ name: 'studentReferenceId', referencedColumnName: 'id' }, { name: 'year', referencedColumnName: 'year' }])
+ @JoinColumn([
+ { name: 'studentReferenceId', referencedColumnName: 'id' },
+ { name: 'year', referencedColumnName: 'year' },
+ ])
studentBaseKlass: StudentBaseKlass;
@ManyToOne(() => Teacher, { createForeignKeyConstraints: false })
@@ -184,10 +211,10 @@ export class Grade implements IHasUserId {
klass: Klass;
@Column({ nullable: true })
- @Index("grades_report_group_session_id_idx")
+ @Index('grades_report_group_session_id_idx')
reportGroupSessionId: number;
- @ManyToOne(() => ReportGroupSession, session => session.grades, { nullable: true })
+ @ManyToOne(() => ReportGroupSession, (session) => session.grades, { nullable: true })
@JoinColumn({ name: 'reportGroupSessionId' })
reportGroupSession: ReportGroupSession;
}
diff --git a/server/src/db/entities/GradeName.entity.ts b/server/src/db/entities/GradeName.entity.ts
index d4c4e209..30354697 100644
--- a/server/src/db/entities/GradeName.entity.ts
+++ b/server/src/db/entities/GradeName.entity.ts
@@ -1,36 +1,31 @@
-import {
- Column,
- Entity,
- Index,
- PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { IsOptional } from "class-validator";
-import { IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { CrudValidationGroups } from "@dataui/crud";
-import { NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { IsOptional } from 'class-validator';
+import { IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { CrudValidationGroups } from '@dataui/crud';
+import { NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Entity("grade_names")
+@Entity('grade_names')
export class GradeName implements IHasUserId {
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
- @Index("grade_names_user_id_idx")
+ @Column('int', { name: 'user_id' })
+ @Index('grade_names_user_id_idx')
userId: number;
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "key" })
+ @Column('int', { name: 'key' })
key: number;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "name", length: 500, nullable: true })
+ @Column('varchar', { name: 'name', length: 500, nullable: true })
name: string;
@CreatedAtColumn()
diff --git a/server/src/db/entities/Klass.entity.ts b/server/src/db/entities/Klass.entity.ts
index 7249698c..b718c3ca 100644
--- a/server/src/db/entities/Klass.entity.ts
+++ b/server/src/db/entities/Klass.entity.ts
@@ -8,23 +8,23 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { KlassType } from "./KlassType.entity";
-import { Teacher } from "./Teacher.entity";
-import { User } from "./User.entity";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { IsOptional, ValidateIf } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsNumber, IsUniqueCombination, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("klasses_users_idx", ["userId"], {})
-@Index(["userId", "key", "year"], { unique: true })
-@Index("klasses_user_id_key_idx", ["userId", "key"])
-@Entity("klasses")
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { KlassType } from './KlassType.entity';
+import { Teacher } from './Teacher.entity';
+import { User } from './User.entity';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { IsOptional, ValidateIf } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsNumber, IsUniqueCombination, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('klasses_users_idx', ['userId'], {})
+@Index(['userId', 'key', 'year'], { unique: true })
+@Index('klasses_user_id_key_idx', ['userId', 'key'])
+@Entity('klasses')
export class Klass implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -35,20 +35,30 @@ export class Klass implements IHasUserId {
dataSource = await getDataSource([KlassType, Teacher, User]);
this.klassTypeReferenceId = await findOneAndAssignReferenceId(
- dataSource, KlassType, { key: this.klassTypeId }, this.userId, this.klassTypeReferenceId, this.klassTypeId
+ dataSource,
+ KlassType,
+ { key: this.klassTypeId },
+ this.userId,
+ this.klassTypeReferenceId,
+ this.klassTypeId,
);
this.teacherReferenceId = await findOneAndAssignReferenceId(
- dataSource, Teacher, { tz: this.teacherId }, this.userId, this.teacherReferenceId, this.teacherId
+ dataSource,
+ Teacher,
+ { tz: this.teacherId },
+ this.userId,
+ this.teacherReferenceId,
+ this.teacherId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -59,20 +69,20 @@ export class Klass implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "key" })
+ @Column('int', { name: 'key' })
key: number;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@StringType
@MaxLength(500, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "name", length: 500 })
+ @Column('varchar', { name: 'name', length: 500 })
name: string;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "display_name", length: 500, nullable: true })
+ @Column('varchar', { name: 'display_name', length: 500, nullable: true })
displayName: string;
@ValidateIf((attReport: Klass) => !Boolean(attReport.klassTypeReferenceId), { always: true })
@@ -80,20 +90,22 @@ export class Klass implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "klass_type_id", nullable: true })
+ @Column('int', { name: 'klass_type_id', nullable: true })
klassTypeId: number | null;
- @ValidateIf((attReport: Klass) => !Boolean(attReport.klassTypeId) && Boolean(attReport.klassTypeReferenceId), { always: true })
+ @ValidateIf((attReport: Klass) => !Boolean(attReport.klassTypeId) && Boolean(attReport.klassTypeReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("klasses_klass_type_reference_id_idx")
+ @Index('klasses_klass_type_reference_id_idx')
klassTypeReferenceId: number;
- @Column("varchar", { name: "teacher_id", nullable: true, length: 10 })
+ @Column('varchar', { name: 'teacher_id', nullable: true, length: 10 })
teacherId: string | null;
@Column({ nullable: true })
- @Index("klasses_teacher_reference_id_idx")
+ @Index('klasses_teacher_reference_id_idx')
teacherReferenceId: number;
@CreatedAtColumn()
diff --git a/server/src/db/entities/KlassType.entity.ts b/server/src/db/entities/KlassType.entity.ts
index efb71cf6..94d239eb 100644
--- a/server/src/db/entities/KlassType.entity.ts
+++ b/server/src/db/entities/KlassType.entity.ts
@@ -8,16 +8,16 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "src/db/entities/User.entity";
-import { IsOptional } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { Teacher } from "./Teacher.entity";
-import { NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from 'src/db/entities/User.entity';
+import { IsOptional } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { Teacher } from './Teacher.entity';
+import { NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
export enum KlassTypeEnum {
baseKlass = 'כיתת אם',
@@ -26,50 +26,54 @@ export enum KlassTypeEnum {
other = 'אחר',
}
-@Index("klass_types_users_idx", ["userId"], {})
-@Entity("klass_types")
+@Index('klass_types_users_idx', ['userId'], {})
+@Entity('klass_types')
export class KlassType implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
async fillFields() {
-
let dataSource: DataSource;
try {
dataSource = await getDataSource([Teacher, User]);
this.teacherReferenceId = await findOneAndAssignReferenceId(
- dataSource, Teacher, { tz: this.teacherId }, this.userId, this.teacherReferenceId, this.teacherId
+ dataSource,
+ Teacher,
+ { tz: this.teacherId },
+ this.userId,
+ this.teacherReferenceId,
+ this.teacherId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "key" })
+ @Column('int', { name: 'key' })
key: number;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@StringType
@MaxLength(500, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "name", length: 500 })
+ @Column('varchar', { name: 'name', length: 500 })
name: string;
@Column('varchar', { default: KlassTypeEnum.other })
- @Index("klass_types_klassTypeEnum_idx")
+ @Index('klass_types_klassTypeEnum_idx')
klassTypeEnum: KlassTypeEnum;
- @Column("varchar", { name: "teacher_id", length: 10, nullable: true })
+ @Column('varchar', { name: 'teacher_id', length: 10, nullable: true })
teacherId: string;
@Column({ nullable: true })
@@ -86,9 +90,9 @@ export class KlassType implements IHasUserId {
teacher: Teacher;
@ManyToOne(() => User, (user) => user.klassTypes, {
- onDelete: "NO ACTION",
- onUpdate: "NO ACTION",
+ onDelete: 'NO ACTION',
+ onUpdate: 'NO ACTION',
})
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
}
diff --git a/server/src/db/entities/KnownAbsence.entity.ts b/server/src/db/entities/KnownAbsence.entity.ts
index 8036b663..5f3b00fe 100644
--- a/server/src/db/entities/KnownAbsence.entity.ts
+++ b/server/src/db/entities/KnownAbsence.entity.ts
@@ -8,29 +8,29 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "src/db/entities/User.entity";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { Student } from "./Student.entity";
-import { IsOptional, ValidateIf } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsBoolean, IsDate, IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { fillDefaultReportDateValue } from "@shared/utils/entity/deafultValues.util";
-import { Klass } from "./Klass.entity";
-import { Lesson } from "./Lesson.entity";
-import { KlassType } from "./KlassType.entity";
-import { Teacher } from "./Teacher.entity";
-import { AbsenceType } from "./AbsenceType.entity";
-import { BooleanType, DateType, NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { LessonKlassName } from "../view-entities/LessonKlassName.entity";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("known_users_idx", ["userId"], {})
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from 'src/db/entities/User.entity';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { Student } from './Student.entity';
+import { IsOptional, ValidateIf } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsBoolean, IsDate, IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { fillDefaultReportDateValue } from '@shared/utils/entity/deafultValues.util';
+import { Klass } from './Klass.entity';
+import { Lesson } from './Lesson.entity';
+import { KlassType } from './KlassType.entity';
+import { Teacher } from './Teacher.entity';
+import { AbsenceType } from './AbsenceType.entity';
+import { BooleanType, DateType, NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { LessonKlassName } from '../view-entities/LessonKlassName.entity';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('known_users_idx', ['userId'], {})
@Index(['studentReferenceId', 'year'])
-@Index("known_absences_lookup_idx", ["userId", "year", "isApproved", "studentReferenceId"])
-@Entity("known_absences")
+@Index('known_absences_lookup_idx', ['userId', 'year', 'isApproved', 'studentReferenceId'])
+@Entity('known_absences')
export class KnownAbsence implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -40,26 +40,50 @@ export class KnownAbsence implements IHasUserId {
let dataSource: DataSource;
try {
- dataSource = await getDataSource([Student, User, Klass, KlassType, Lesson, Teacher, LessonKlassName, AbsenceType]);
+ dataSource = await getDataSource([
+ Student,
+ User,
+ Klass,
+ KlassType,
+ Lesson,
+ Teacher,
+ LessonKlassName,
+ AbsenceType,
+ ]);
this.studentReferenceId = await findOneAndAssignReferenceId(
- dataSource, Student, { tz: this.studentTz }, this.userId, this.studentReferenceId, this.studentTz
+ dataSource,
+ Student,
+ { tz: this.studentTz },
+ this.userId,
+ this.studentReferenceId,
+ this.studentTz,
);
this.klassReferenceId = await findOneAndAssignReferenceId(
- dataSource, Klass, { year: this.year, key: this.klassId }, this.userId, this.klassReferenceId, this.klassId
+ dataSource,
+ Klass,
+ { year: this.year, key: this.klassId },
+ this.userId,
+ this.klassReferenceId,
+ this.klassId,
);
this.lessonReferenceId = await findOneAndAssignReferenceId(
- dataSource, Lesson, { year: this.year, key: this.lessonId }, this.userId, this.lessonReferenceId, this.lessonId
+ dataSource,
+ Lesson,
+ { year: this.year, key: this.lessonId },
+ this.userId,
+ this.lessonReferenceId,
+ this.lessonId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -67,13 +91,15 @@ export class KnownAbsence implements IHasUserId {
@ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.studentReferenceId), { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "student_tz", length: 10, nullable: true })
+ @Column('varchar', { name: 'student_tz', length: 10, nullable: true })
studentTz: string;
- @ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), { always: true })
+ @ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
- @Index("known_absences_student_reference_id_idx")
+ @Index('known_absences_student_reference_id_idx')
studentReferenceId: number;
@ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.klassReferenceId), { always: true })
@@ -81,10 +107,12 @@ export class KnownAbsence implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "klass_id", nullable: true })
+ @Column('int', { name: 'klass_id', nullable: true })
klassId: number | null;
- @ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), { always: true })
+ @ValidateIf((attReport: KnownAbsence) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
klassReferenceId: number;
@@ -92,7 +120,7 @@ export class KnownAbsence implements IHasUserId {
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "lesson_id", nullable: true })
+ @Column('int', { name: 'lesson_id', nullable: true })
lessonId: number;
@IsOptional({ always: true })
@@ -101,7 +129,7 @@ export class KnownAbsence implements IHasUserId {
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
- @Column("date", { name: "report_date" })
+ @Column('date', { name: 'report_date' })
@DateType
@IsDate({ always: true })
reportDate: Date;
@@ -109,31 +137,31 @@ export class KnownAbsence implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "absnce_count", nullable: true })
+ @Column('int', { name: 'absnce_count', nullable: true })
absnceCount: number | null;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "absnce_code", nullable: true })
+ @Column('int', { name: 'absnce_code', nullable: true })
absnceCode: number | null;
@IsOptional({ always: true })
@StringType
@MaxLength(100, { always: true })
- @Column("varchar", { name: "sender_name", nullable: true, length: 100 })
+ @Column('varchar', { name: 'sender_name', nullable: true, length: 100 })
senderName: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "reason", nullable: true, length: 500 })
+ @Column('varchar', { name: 'reason', nullable: true, length: 500 })
reason: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "comment", nullable: true, length: 500 })
+ @Column('varchar', { name: 'comment', nullable: true, length: 500 })
comment: string | null;
@IsOptional({ always: true })
@@ -144,11 +172,10 @@ export class KnownAbsence implements IHasUserId {
@IsOptional({ always: true })
@NumberType
- @IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "absence_type_id", nullable: true })
+ @IsNumber({ maxDecimalPlaces: 0 }, { always: true })
+ @Column('int', { name: 'absence_type_id', nullable: true })
absenceTypeId: number | null;
-
@CreatedAtColumn()
createdAt: Date;
@@ -156,10 +183,10 @@ export class KnownAbsence implements IHasUserId {
updatedAt: Date;
@ManyToOne(() => User, (user) => user.knownAbsences, {
- onDelete: "NO ACTION",
- onUpdate: "NO ACTION",
+ onDelete: 'NO ACTION',
+ onUpdate: 'NO ACTION',
})
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
@ManyToOne(() => Student, { createForeignKeyConstraints: false })
@@ -173,9 +200,8 @@ export class KnownAbsence implements IHasUserId {
@ManyToOne(() => Klass, { createForeignKeyConstraints: false })
@JoinColumn({ name: 'klassReferenceId' })
klass: Klass;
-
+
@ManyToOne(() => AbsenceType, { createForeignKeyConstraints: false })
@JoinColumn({ name: 'absence_type_id' })
absenceType: AbsenceType;
-
}
diff --git a/server/src/db/entities/Lesson.entity.ts b/server/src/db/entities/Lesson.entity.ts
index 47282725..1370c31d 100644
--- a/server/src/db/entities/Lesson.entity.ts
+++ b/server/src/db/entities/Lesson.entity.ts
@@ -9,28 +9,39 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "./Teacher.entity";
-import { Klass } from "./Klass.entity";
-import { KlassType } from "./KlassType.entity";
-import { User } from "./User.entity";
-import { findManyAndAssignReferenceIds, findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { IsOptional } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsDate, IsNotEmpty, IsNumber, IsUniqueCombination, MaxLength, Min } from "@shared/utils/validation/class-validator-he";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { cleanDateFields } from "@shared/utils/entity/deafultValues.util";
-import { DateType, NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { LessonKlassName } from "../view-entities/LessonKlassName.entity";
-import { CreatedAtColumn, JsonColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("lessons_users_idx", ["userId"], {})
-@Index(["userId", "key", "year"], { unique: true })
-@Index("lessons_user_id_key_idx", ["userId", "key"])
-@Index("lessons_teacher_year_idx", ["teacherReferenceId", "year"], {})
-@Index("lessons_user_year_teacher_idx", ["userId", "year", "teacherReferenceId"], {})
-@Entity("lessons")
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from './Teacher.entity';
+import { Klass } from './Klass.entity';
+import { KlassType } from './KlassType.entity';
+import { User } from './User.entity';
+import {
+ findManyAndAssignReferenceIds,
+ findOneAndAssignReferenceId,
+ getDataSource,
+} from '@shared/utils/entity/foreignKey.util';
+import { IsOptional } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import {
+ IsDate,
+ IsNotEmpty,
+ IsNumber,
+ IsUniqueCombination,
+ MaxLength,
+ Min,
+} from '@shared/utils/validation/class-validator-he';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { cleanDateFields } from '@shared/utils/entity/deafultValues.util';
+import { DateType, NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { LessonKlassName } from '../view-entities/LessonKlassName.entity';
+import { CreatedAtColumn, JsonColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('lessons_users_idx', ['userId'], {})
+@Index(['userId', 'key', 'year'], { unique: true })
+@Index('lessons_user_id_key_idx', ['userId', 'key'])
+@Index('lessons_teacher_year_idx', ['teacherReferenceId', 'year'], {})
+@Index('lessons_user_year_teacher_idx', ['userId', 'year', 'teacherReferenceId'], {})
+@Entity('lessons')
export class Lesson implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -42,23 +53,34 @@ export class Lesson implements IHasUserId {
try {
dataSource = await getDataSource([Teacher, Klass, KlassType, User, LessonKlassName]);
- const klassesArray = (typeof this.klasses === 'string' && this.klasses.includes(',')) ? this.klasses.split(',') : [this.klasses];
+ const klassesArray =
+ typeof this.klasses === 'string' && this.klasses.includes(',') ? this.klasses.split(',') : [this.klasses];
this.klassReferenceIds = await findManyAndAssignReferenceIds(
- dataSource, Klass, { year: this.year, key: In(klassesArray) }, this.userId, this.klassReferenceIds, this.klasses
+ dataSource,
+ Klass,
+ { year: this.year, key: In(klassesArray) },
+ this.userId,
+ this.klassReferenceIds,
+ this.klasses,
);
this.teacherReferenceId = await findOneAndAssignReferenceId(
- dataSource, Teacher, { tz: this.teacherId }, this.userId, this.teacherReferenceId, this.teacherId
+ dataSource,
+ Teacher,
+ { tz: this.teacherId },
+ this.userId,
+ this.teacherReferenceId,
+ this.teacherId,
);
} finally {
dataSource?.destroy();
}
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -69,55 +91,55 @@ export class Lesson implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "key" })
+ @Column('int', { name: 'key' })
key: number;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@StringType
@MaxLength(500, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "name", length: 500 })
+ @Column('varchar', { name: 'name', length: 500 })
name: string;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "display_name", length: 500, nullable: true })
+ @Column('varchar', { name: 'display_name', length: 500, nullable: true })
displayName: string;
@IsOptional({ always: true })
@StringType
@MaxLength(450, { always: true })
- @Column("varchar", { name: "klasses", nullable: true, length: 450 })
+ @Column('varchar', { name: 'klasses', nullable: true, length: 450 })
klasses: string | null;
- @Column("simple-array", { nullable: true })
+ @Column('simple-array', { nullable: true })
klassReferenceIds: number[];
@JsonColumn({
- type: "json",
- name: "klass_reference_ids_json",
+ type: 'json',
+ name: 'klass_reference_ids_json',
nullable: true,
asExpression: "CAST(CONCAT('[', COALESCE(klassReferenceIds, ''), ']') AS JSON)",
- generatedType: "STORED"
+ generatedType: 'STORED',
})
klassReferenceIdsJson: string;
- @Column("varchar", { name: "teacher_id", length: 10, nullable: true })
+ @Column('varchar', { name: 'teacher_id', length: 10, nullable: true })
teacherId: string;
@Column({ nullable: true })
- @Index("lessons_teacher_reference_id_idx")
+ @Index('lessons_teacher_reference_id_idx')
teacherReferenceId: number;
- @Column("date", { name: "start_date", nullable: true })
+ @Column('date', { name: 'start_date', nullable: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@DateType
@IsDate({ always: true })
startDate: string | null;
- @Column("date", { name: "end_date", nullable: true })
+ @Column('date', { name: 'end_date', nullable: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@DateType
@@ -127,20 +149,20 @@ export class Lesson implements IHasUserId {
@IsOptional({ always: true })
@StringType
@MaxLength(1000, { always: true })
- @Column("varchar", { name: "comment", nullable: true, length: 1000 })
+ @Column('varchar', { name: 'comment', nullable: true, length: 1000 })
comment: string;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 1 }, { always: true })
@Min(0, { always: true })
- @Column("float", { name: "how_many_lessons", nullable: true })
+ @Column('float', { name: 'how_many_lessons', nullable: true })
howManyLessons: number;
@IsOptional({ always: true })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "order", nullable: true })
+ @Column('int', { name: 'order', nullable: true })
order: number;
@CreatedAtColumn()
diff --git a/server/src/db/entities/ReportGroup.entity.ts b/server/src/db/entities/ReportGroup.entity.ts
index 8b103161..1100f040 100644
--- a/server/src/db/entities/ReportGroup.entity.ts
+++ b/server/src/db/entities/ReportGroup.entity.ts
@@ -10,21 +10,21 @@ import {
PrimaryGeneratedColumn,
BeforeInsert,
BeforeUpdate,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "./Teacher.entity";
-import { Lesson } from "./Lesson.entity";
-import { Klass } from "./Klass.entity";
-import { ReportGroupSession } from "./ReportGroupSession.entity";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { StringType, NumberType } from "@shared/utils/entity/class-transformer";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { LongTextColumn } from "@shared/utils/entity/column-types.util";
-
-@Index("report_groups_user_id_idx", ["userId"], {})
-@Index("report_groups_user_id_year_idx", ["userId", "year"], {})
-@Entity("report_groups")
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from './Teacher.entity';
+import { Lesson } from './Lesson.entity';
+import { Klass } from './Klass.entity';
+import { ReportGroupSession } from './ReportGroupSession.entity';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { StringType, NumberType } from '@shared/utils/entity/class-transformer';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { LongTextColumn } from '@shared/utils/entity/column-types.util';
+
+@Index('report_groups_user_id_idx', ['userId'], {})
+@Index('report_groups_user_id_year_idx', ['userId', 'year'], {})
+@Entity('report_groups')
export class ReportGroup implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -32,10 +32,10 @@ export class ReportGroup implements IHasUserId {
fillDefaultYearValue(this);
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@StringType
@@ -51,21 +51,21 @@ export class ReportGroup implements IHasUserId {
@StringType
@LongTextColumn({ nullable: true })
- signatureData: string; // ONE signature for entire group
+ signatureData: string; // ONE signature for entire group
@NumberType
@Column({ nullable: true })
- @Index("report_groups_teacher_reference_id_idx")
+ @Index('report_groups_teacher_reference_id_idx')
teacherReferenceId: number;
@NumberType
@Column({ nullable: true })
- @Index("report_groups_lesson_reference_id_idx")
+ @Index('report_groups_lesson_reference_id_idx')
lessonReferenceId: number;
@NumberType
@Column({ nullable: true })
- @Index("report_groups_klass_reference_id_idx")
+ @Index('report_groups_klass_reference_id_idx')
klassReferenceId: number;
@NumberType
@@ -91,6 +91,6 @@ export class ReportGroup implements IHasUserId {
@JoinColumn({ name: 'klassReferenceId' })
klass: Klass;
- @OneToMany(() => ReportGroupSession, session => session.reportGroup)
+ @OneToMany(() => ReportGroupSession, (session) => session.reportGroup)
sessions: ReportGroupSession[];
}
diff --git a/server/src/db/entities/ReportGroupSession.entity.ts b/server/src/db/entities/ReportGroupSession.entity.ts
index b4257aa2..ca5e29d5 100644
--- a/server/src/db/entities/ReportGroupSession.entity.ts
+++ b/server/src/db/entities/ReportGroupSession.entity.ts
@@ -9,20 +9,20 @@ import {
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { ReportGroup } from "./ReportGroup.entity";
-import { AttReport } from "./AttReport.entity";
-import { Grade } from "./Grade.entity";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsDate } from "@shared/utils/validation/class-validator-he";
-import { StringType, NumberType, DateType } from "@shared/utils/entity/class-transformer";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { cleanDateFields, cleanTimeFields } from "@shared/utils/entity/deafultValues.util";
+} from 'typeorm';
+import { ReportGroup } from './ReportGroup.entity';
+import { AttReport } from './AttReport.entity';
+import { Grade } from './Grade.entity';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsDate } from '@shared/utils/validation/class-validator-he';
+import { StringType, NumberType, DateType } from '@shared/utils/entity/class-transformer';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { cleanDateFields, cleanTimeFields } from '@shared/utils/entity/deafultValues.util';
-@Index("report_group_sessions_user_id_idx", ["userId"], {})
-@Index("report_group_sessions_report_group_id_idx", ["reportGroupId"], {})
-@Index("report_group_sessions_session_date_idx", ["sessionDate"], {})
-@Entity("report_group_sessions")
+@Index('report_group_sessions_user_id_idx', ['userId'], {})
+@Index('report_group_sessions_report_group_id_idx', ['reportGroupId'], {})
+@Index('report_group_sessions_session_date_idx', ['sessionDate'], {})
+@Entity('report_group_sessions')
export class ReportGroupSession {
@BeforeInsert()
@BeforeUpdate()
@@ -31,7 +31,7 @@ export class ReportGroupSession {
cleanTimeFields(this, ['startTime', 'endTime']);
}
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
@Column()
@@ -58,19 +58,19 @@ export class ReportGroupSession {
@StringType
@Column({ length: 255, nullable: true })
- topic: string; // Can override group topic
+ topic: string; // Can override group topic
@CreateDateColumn()
createdAt: Date;
// Relations
- @ManyToOne(() => ReportGroup, group => group.sessions, { onDelete: 'CASCADE' })
+ @ManyToOne(() => ReportGroup, (group) => group.sessions, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'reportGroupId' })
reportGroup: ReportGroup;
- @OneToMany(() => AttReport, report => report.reportGroupSession)
+ @OneToMany(() => AttReport, (report) => report.reportGroupSession)
attReports: AttReport[];
- @OneToMany(() => Grade, grade => grade.reportGroupSession)
+ @OneToMany(() => Grade, (grade) => grade.reportGroupSession)
grades: Grade[];
}
diff --git a/server/src/db/entities/ReportMonth.entity.ts b/server/src/db/entities/ReportMonth.entity.ts
index 138d55b5..e99f55b3 100644
--- a/server/src/db/entities/ReportMonth.entity.ts
+++ b/server/src/db/entities/ReportMonth.entity.ts
@@ -1,5 +1,5 @@
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsOptional } from "class-validator";
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsOptional } from 'class-validator';
import {
BeforeInsert,
BeforeUpdate,
@@ -9,11 +9,10 @@ import {
Index,
PrimaryGeneratedColumn,
UpdateDateColumn,
-} from "typeorm";
-import { IsDate, IsNotEmpty, IsUniqueDateRange, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { DateType, StringType } from "@shared/utils/entity/class-transformer";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-
+} from 'typeorm';
+import { IsDate, IsNotEmpty, IsUniqueDateRange, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { DateType, StringType } from '@shared/utils/entity/class-transformer';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
export enum ReportMonthSemester {
first = 'א',
@@ -21,9 +20,9 @@ export enum ReportMonthSemester {
fullYear = 'שנתי',
}
-@Index("report_month_user_id_start_date_end_date_idx", ["userId", "startDate", "endDate"], {})
-@Index("report_month_user_id_year_idx", ["userId", "year"], {})
-@Index("report_month_user_id_start_date_end_date_year_idx", ["userId", "startDate", "endDate", "year"], {})
+@Index('report_month_user_id_start_date_end_date_idx', ['userId', 'startDate', 'endDate'], {})
+@Index('report_month_user_id_year_idx', ['userId', 'year'], {})
+@Index('report_month_user_id_start_date_end_date_year_idx', ['userId', 'startDate', 'endDate', 'year'], {})
@Entity()
export class ReportMonth {
@BeforeInsert()
@@ -36,7 +35,7 @@ export class ReportMonth {
id: number;
@Column()
- @Index("report_month_user_id_idx")
+ @Index('report_month_user_id_idx')
userId: number;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@@ -51,8 +50,8 @@ export class ReportMonth {
@Column()
@DateType
@IsDate({ always: true })
- @IsUniqueDateRange("startDate", "endDate", [ReportMonth], { always: true })
- @Index("report_month_start_date_idx")
+ @IsUniqueDateRange('startDate', 'endDate', [ReportMonth], { always: true })
+ @Index('report_month_start_date_idx')
startDate: Date;
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@@ -60,8 +59,8 @@ export class ReportMonth {
@Column()
@DateType
@IsDate({ always: true })
- @IsUniqueDateRange("startDate", "endDate", [ReportMonth], { always: true })
- @Index("report_month_end_date_idx")
+ @IsUniqueDateRange('startDate', 'endDate', [ReportMonth], { always: true })
+ @Index('report_month_end_date_idx')
endDate: Date;
@IsOptional({ always: true })
diff --git a/server/src/db/entities/Student.entity.ts b/server/src/db/entities/Student.entity.ts
index a44dacb0..23901670 100644
--- a/server/src/db/entities/Student.entity.ts
+++ b/server/src/db/entities/Student.entity.ts
@@ -1,27 +1,20 @@
-import {
- Column,
- Entity,
- Index,
- JoinColumn,
- ManyToOne,
- PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "src/db/entities/User.entity";
-import { IsOptional } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsUniqueCombination, MaxLength, IsBoolean } from "@shared/utils/validation/class-validator-he";
-import { StringType, BooleanType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from 'src/db/entities/User.entity';
+import { IsOptional } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsUniqueCombination, MaxLength, IsBoolean } from '@shared/utils/validation/class-validator-he';
+import { StringType, BooleanType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Index("students_users_idx", ["userId"], {})
-@Index(["userId", "tz", "year"], { unique: true })
-@Entity("students")
+@Index('students_users_idx', ['userId'], {})
+@Index(['userId', 'tz', 'year'], { unique: true })
+@Entity('students')
export class Student implements IHasUserId {
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -32,38 +25,38 @@ export class Student implements IHasUserId {
@StringType
@IsUniqueCombination(['userId'], [Student, User], { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "tz", length: 10 })
+ @Column('varchar', { name: 'tz', length: 10 })
tz: string;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@StringType
@MaxLength(500, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "name", length: 500 })
+ @Column('varchar', { name: 'name', length: 500 })
name: string;
@IsOptional({ always: true })
@StringType
@MaxLength(1000, { always: true })
- @Column("varchar", { name: "comment", nullable: true, length: 1000 })
+ @Column('varchar', { name: 'comment', nullable: true, length: 1000 })
comment: string;
@IsOptional({ always: true })
@StringType
@MaxLength(1000, { always: true })
- @Column("varchar", { name: "phone", nullable: true, length: 1000 })
+ @Column('varchar', { name: 'phone', nullable: true, length: 1000 })
phone: string;
@IsOptional({ always: true })
@StringType
@MaxLength(1000, { always: true })
- @Column("varchar", { name: "address", nullable: true, length: 1000 })
+ @Column('varchar', { name: 'address', nullable: true, length: 1000 })
address: string;
@IsOptional({ always: true })
@IsBoolean({ groups: [CrudValidationGroups.CREATE, CrudValidationGroups.UPDATE] })
@BooleanType
- @Column("boolean", { name: "is_active", default: true })
+ @Column('boolean', { name: 'is_active', default: true })
isActive: boolean;
@CreatedAtColumn()
@@ -73,9 +66,9 @@ export class Student implements IHasUserId {
updatedAt: Date;
@ManyToOne(() => User, (user) => user.students, {
- onDelete: "NO ACTION",
- onUpdate: "NO ACTION",
+ onDelete: 'NO ACTION',
+ onUpdate: 'NO ACTION',
})
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
}
diff --git a/server/src/db/entities/StudentKlass.entity.ts b/server/src/db/entities/StudentKlass.entity.ts
index 62d0bd98..f23a9fe9 100644
--- a/server/src/db/entities/StudentKlass.entity.ts
+++ b/server/src/db/entities/StudentKlass.entity.ts
@@ -8,33 +8,37 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Student } from "./Student.entity";
-import { Klass } from "./Klass.entity";
-import { User } from "./User.entity";
-import { findOneAndAssignReferenceId, getDataSource } from "@shared/utils/entity/foreignKey.util";
-import { KlassType } from "./KlassType.entity";
-import { Teacher } from "./Teacher.entity";
-import { IsOptional, ValidateIf } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsNumber, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
-import { MaxCountByUserLimit } from "@shared/utils/validation/max-count-by-user-limit";
-import { StudentByYear } from "../view-entities/StudentByYear.entity";
-import { PaymentTrack } from "@shared/entities/PaymentTrack.entity";
-import { NumberType, StringType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+} from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Student } from './Student.entity';
+import { Klass } from './Klass.entity';
+import { User } from './User.entity';
+import { findOneAndAssignReferenceId, getDataSource } from '@shared/utils/entity/foreignKey.util';
+import { KlassType } from './KlassType.entity';
+import { Teacher } from './Teacher.entity';
+import { IsOptional, ValidateIf } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsNumber, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
+import { MaxCountByUserLimit } from '@shared/utils/validation/max-count-by-user-limit';
+import { StudentByYear } from '../view-entities/StudentByYear.entity';
+import { PaymentTrack } from '@shared/entities/PaymentTrack.entity';
+import { NumberType, StringType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Index("student_klasses_users_idx", ["userId"], {})
-@Index("student_klasses_user_year_idx", ["userId", "year"], {})
-@Index("student_klasses_user_year_student_idx", ["userId", "year", "studentReferenceId"], {})
-@Index("student_klasses_student_reference_id_year_idx", ["studentReferenceId", "year"], {})
-@Index("student_klasses_user_klass_year_idx", ["userId", "klassReferenceId", "year"], {})
-@Index("student_klasses_user_student_klass_year_idx", ["userId", "studentReferenceId", "klassReferenceId", "year"], {})
-@Index("student_klasses_user_year_student_klass_covering_idx", ["userId", "year", "studentReferenceId", "klassReferenceId"], {})
+@Index('student_klasses_users_idx', ['userId'], {})
+@Index('student_klasses_user_year_idx', ['userId', 'year'], {})
+@Index('student_klasses_user_year_student_idx', ['userId', 'year', 'studentReferenceId'], {})
+@Index('student_klasses_student_reference_id_year_idx', ['studentReferenceId', 'year'], {})
+@Index('student_klasses_user_klass_year_idx', ['userId', 'klassReferenceId', 'year'], {})
+@Index('student_klasses_user_student_klass_year_idx', ['userId', 'studentReferenceId', 'klassReferenceId', 'year'], {})
+@Index(
+ 'student_klasses_user_year_student_klass_covering_idx',
+ ['userId', 'year', 'studentReferenceId', 'klassReferenceId'],
+ {},
+)
@Index(['studentReferenceId', 'year'])
-@Entity("student_klasses")
+@Entity('student_klasses')
export class StudentKlass implements IHasUserId {
@BeforeInsert()
@BeforeUpdate()
@@ -46,29 +50,52 @@ export class StudentKlass implements IHasUserId {
dataSource = await getDataSource([Student, Klass, User, KlassType, Teacher]);
this.studentReferenceId = await findOneAndAssignReferenceId(
- dataSource, Student, { tz: this.studentTz }, this.userId, this.studentReferenceId, this.studentTz
+ dataSource,
+ Student,
+ { tz: this.studentTz },
+ this.userId,
+ this.studentReferenceId,
+ this.studentTz,
);
this.klassReferenceId = await findOneAndAssignReferenceId(
- dataSource, Klass, { year: this.year, key: this.klassId }, this.userId, this.klassReferenceId, this.klassId
+ dataSource,
+ Klass,
+ { year: this.year, key: this.klassId },
+ this.userId,
+ this.klassReferenceId,
+ this.klassId,
);
} finally {
dataSource?.destroy();
}
}
- @MaxCountByUserLimit(StudentByYear, (userId, dataSource: DataSource) =>
- dataSource.getRepository(User).findOne({ where: { id: userId }, select: { paymentTrackId: true } })
- .then(user => user?.paymentTrackId)
- .then(ptid => ptid
- ? dataSource.getRepository(PaymentTrack).findOne({ where: { id: ptid }, select: { studentNumberLimit: true } })
- : dataSource.getRepository(PaymentTrack).find({ order: { studentNumberLimit: 'asc' }, take: 1, select: { studentNumberLimit: true } }).then(res => res[0])
- )
- .then(pt => pt?.studentNumberLimit ?? 0)
- , [User, PaymentTrack], 'studentReferenceId', { always: true, message: 'הגעת להגבלת הכמות לטבלת שיוך תלמידות, אנא פני לאחראית כדי להגדיל את החבילה' })
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @MaxCountByUserLimit(
+ StudentByYear,
+ (userId, dataSource: DataSource) =>
+ dataSource
+ .getRepository(User)
+ .findOne({ where: { id: userId }, select: { paymentTrackId: true } })
+ .then((user) => user?.paymentTrackId)
+ .then((ptid) =>
+ ptid
+ ? dataSource
+ .getRepository(PaymentTrack)
+ .findOne({ where: { id: ptid }, select: { studentNumberLimit: true } })
+ : dataSource
+ .getRepository(PaymentTrack)
+ .find({ order: { studentNumberLimit: 'asc' }, take: 1, select: { studentNumberLimit: true } })
+ .then((res) => res[0]),
+ )
+ .then((pt) => pt?.studentNumberLimit ?? 0),
+ [User, PaymentTrack],
+ 'studentReferenceId',
+ { always: true, message: 'הגעת להגבלת הכמות לטבלת שיוך תלמידות, אנא פני לאחראית כדי להגדיל את החבילה' },
+ )
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@IsOptional({ always: true })
@@ -81,10 +108,12 @@ export class StudentKlass implements IHasUserId {
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@MaxLength(10, { always: true })
@StringType
- @Column("varchar", { name: "student_tz", length: 10, nullable: true })
+ @Column('varchar', { name: 'student_tz', length: 10, nullable: true })
studentTz: string;
- @ValidateIf((attReport: StudentKlass) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), { always: true })
+ @ValidateIf((attReport: StudentKlass) => !Boolean(attReport.studentTz) && Boolean(attReport.studentReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
studentReferenceId: number;
@@ -94,10 +123,12 @@ export class StudentKlass implements IHasUserId {
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@NumberType
@IsNumber({ maxDecimalPlaces: 0 }, { always: true })
- @Column("int", { name: "klass_id", nullable: true })
+ @Column('int', { name: 'klass_id', nullable: true })
klassId: number;
- @ValidateIf((attReport: StudentKlass) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), { always: true })
+ @ValidateIf((attReport: StudentKlass) => !Boolean(attReport.klassId) && Boolean(attReport.klassReferenceId), {
+ always: true,
+ })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
@Column({ nullable: true })
klassReferenceId: number;
diff --git a/server/src/db/entities/Teacher.entity.ts b/server/src/db/entities/Teacher.entity.ts
index b5257756..9898e6d1 100644
--- a/server/src/db/entities/Teacher.entity.ts
+++ b/server/src/db/entities/Teacher.entity.ts
@@ -1,30 +1,23 @@
-import {
- Column,
- Entity,
- Index,
- JoinColumn,
- ManyToOne,
- PrimaryGeneratedColumn,
-} from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "src/db/entities/User.entity";
-import { IsOptional } from "class-validator";
-import { CrudValidationGroups } from "@dataui/crud";
-import { IsNotEmpty, IsUniqueCombination, MaxLength } from "@shared/utils/validation/class-validator-he";
-import { StringType } from "@shared/utils/entity/class-transformer";
-import { CreatedAtColumn, UpdatedAtColumn } from "@shared/utils/entity/column-types.util";
+import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from 'src/db/entities/User.entity';
+import { IsOptional } from 'class-validator';
+import { CrudValidationGroups } from '@dataui/crud';
+import { IsNotEmpty, IsUniqueCombination, MaxLength } from '@shared/utils/validation/class-validator-he';
+import { StringType } from '@shared/utils/entity/class-transformer';
+import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
-@Index("teachers_users_idx", ["userId"], {})
-@Index(["userId", "tz", "year"], { unique: true })
-@Index("teachers_user_id_tz_idx", ["userId", "tz"])
-@Index("teachers_user_id_phone_idx", ["userId", "phone"])
-@Index("teachers_user_id_phone2_idx", ["userId", "phone2"])
-@Entity("teachers")
+@Index('teachers_users_idx', ['userId'], {})
+@Index(['userId', 'tz', 'year'], { unique: true })
+@Index('teachers_user_id_tz_idx', ['userId', 'tz'])
+@Index('teachers_user_id_phone_idx', ['userId', 'phone'])
+@Index('teachers_user_id_phone2_idx', ['userId', 'phone2'])
+@Entity('teachers')
export class Teacher implements IHasUserId {
- @PrimaryGeneratedColumn({ type: "int", name: "id" })
+ @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -35,44 +28,44 @@ export class Teacher implements IHasUserId {
@MaxLength(10, { always: true })
@IsUniqueCombination(['userId'], [Teacher, User], { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "tz", length: 10 })
+ @Column('varchar', { name: 'tz', length: 10 })
tz: string;
@IsOptional({ groups: [CrudValidationGroups.UPDATE] })
@StringType
@MaxLength(500, { always: true })
@IsNotEmpty({ groups: [CrudValidationGroups.CREATE] })
- @Column("varchar", { name: "name", length: 500 })
+ @Column('varchar', { name: 'name', length: 500 })
name: string;
@IsOptional({ always: true })
@StringType
@MaxLength(10, { always: true })
- @Column("varchar", { name: "phone", nullable: true, length: 10 })
+ @Column('varchar', { name: 'phone', nullable: true, length: 10 })
phone: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(10, { always: true })
- @Column("varchar", { name: "phone2", nullable: true, length: 10 })
+ @Column('varchar', { name: 'phone2', nullable: true, length: 10 })
phone2: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "email", nullable: true, length: 500 })
+ @Column('varchar', { name: 'email', nullable: true, length: 500 })
email: string | null;
@IsOptional({ always: true })
@StringType
@MaxLength(1000, { always: true })
- @Column("varchar", { name: "comment", nullable: true, length: 1000 })
+ @Column('varchar', { name: 'comment', nullable: true, length: 1000 })
comment: string;
@IsOptional({ always: true })
@StringType
@MaxLength(500, { always: true })
- @Column("varchar", { name: "displayName", nullable: true, length: 500 })
+ @Column('varchar', { name: 'displayName', nullable: true, length: 500 })
displayName: string;
@CreatedAtColumn()
@@ -82,9 +75,9 @@ export class Teacher implements IHasUserId {
updatedAt: Date;
@ManyToOne(() => User, (user) => user.teachers, {
- onDelete: "NO ACTION",
- onUpdate: "NO ACTION",
+ onDelete: 'NO ACTION',
+ onUpdate: 'NO ACTION',
})
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
}
diff --git a/server/src/db/entities/Transportation.entity.ts b/server/src/db/entities/Transportation.entity.ts
index b8ec82bd..892ea30a 100644
--- a/server/src/db/entities/Transportation.entity.ts
+++ b/server/src/db/entities/Transportation.entity.ts
@@ -1,19 +1,11 @@
-import {
- Column,
- Entity,
- Index,
- JoinColumn,
- PrimaryGeneratedColumn,
- BeforeInsert,
- BeforeUpdate,
-} from 'typeorm';
+import { Column, Entity, Index, JoinColumn, PrimaryGeneratedColumn, BeforeInsert, BeforeUpdate } from 'typeorm';
import { IHasUserId } from '@shared/base-entity/interface';
import { User } from 'src/db/entities/User.entity';
import { IsOptional } from 'class-validator';
import { CrudValidationGroups } from '@dataui/crud';
import { IsNotEmpty, IsUniqueCombination, MaxLength, IsNumber } from '@shared/utils/validation/class-validator-he';
import { StringType, NumberType } from '@shared/utils/entity/class-transformer';
-import { fillDefaultYearValue } from "@shared/utils/entity/year.util";
+import { fillDefaultYearValue } from '@shared/utils/entity/year.util';
import { CreatedAtColumn, UpdatedAtColumn } from '@shared/utils/entity/column-types.util';
@Index('transportations_users_idx', ['userId'], {})
diff --git a/server/src/db/entities/User.entity.ts b/server/src/db/entities/User.entity.ts
index 19652790..4d1ba1c4 100644
--- a/server/src/db/entities/User.entity.ts
+++ b/server/src/db/entities/User.entity.ts
@@ -1,29 +1,28 @@
-import { Entity, OneToMany } from "typeorm";
-import { User as BaseUser } from "@shared/entities/User.entity";
-import { Grade } from "src/db/entities/Grade.entity";
-import { KlassType } from "src/db/entities/KlassType.entity";
-import { Klass } from "src/db/entities/Klass.entity";
-import { KnownAbsence } from "src/db/entities/KnownAbsence.entity";
-import { Lesson } from "src/db/entities/Lesson.entity";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { Student } from "src/db/entities/Student.entity";
-import { Teacher } from "src/db/entities/Teacher.entity";
+import { Entity, OneToMany } from 'typeorm';
+import { User as BaseUser } from '@shared/entities/User.entity';
+import { Grade } from 'src/db/entities/Grade.entity';
+import { KlassType } from 'src/db/entities/KlassType.entity';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Student } from 'src/db/entities/Student.entity';
+import { Teacher } from 'src/db/entities/Teacher.entity';
-@Entity("users")
+@Entity('users')
export class User extends BaseUser {
- // @OneToMany(() => Grade, (grades) => grades.user)
- grades: Grade[];
-
- // @OneToMany(() => KlassType, (klassTypes) => klassTypes.user)
- klassTypes: KlassType[];
+ // @OneToMany(() => Grade, (grades) => grades.user)
+ grades: Grade[];
- // @OneToMany(() => KnownAbsence, (knownAbsences) => knownAbsences.user)
- knownAbsences: KnownAbsence[];
+ // @OneToMany(() => KlassType, (klassTypes) => klassTypes.user)
+ klassTypes: KlassType[];
- // @OneToMany(() => Student, (students) => students.user)
- students: Student[];
+ // @OneToMany(() => KnownAbsence, (knownAbsences) => knownAbsences.user)
+ knownAbsences: KnownAbsence[];
- // @OneToMany(() => Teacher, (teachers) => teachers.user)
- teachers: Teacher[];
+ // @OneToMany(() => Student, (students) => students.user)
+ students: Student[];
-}
\ No newline at end of file
+ // @OneToMany(() => Teacher, (teachers) => teachers.user)
+ teachers: Teacher[];
+}
diff --git a/server/src/db/view-entities/AbsCountEffectByUser.entity.ts b/server/src/db/view-entities/AbsCountEffectByUser.entity.ts
index a65bc4a9..6f35ced9 100644
--- a/server/src/db/view-entities/AbsCountEffectByUser.entity.ts
+++ b/server/src/db/view-entities/AbsCountEffectByUser.entity.ts
@@ -1,22 +1,25 @@
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "@shared/entities/User.entity";
-import { AttGradeEffect } from "src/db/entities/AttGradeEffect";
-import { DataSource, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { createAbsCountEffectByUserExpression, IAbsCountEffectByUser } from "@shared/view-entities/attendance-effect-view.util";
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from '@shared/entities/User.entity';
+import { AttGradeEffect } from 'src/db/entities/AttGradeEffect';
+import { DataSource, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import {
+ createAbsCountEffectByUserExpression,
+ IAbsCountEffectByUser,
+} from '@shared/view-entities/attendance-effect-view.util';
@ViewEntity('abs_count_effect_by_user', {
- expression: (dataSource: DataSource) => createAbsCountEffectByUserExpression(dataSource, User, AttGradeEffect)
+ expression: (dataSource: DataSource) => createAbsCountEffectByUserExpression(dataSource, User, AttGradeEffect),
})
export class AbsCountEffectByUser implements IHasUserId, IAbsCountEffectByUser {
- @PrimaryColumn()
- id: string;
+ @PrimaryColumn()
+ id: string;
- @ViewColumn()
- userId: number;
+ @ViewColumn()
+ userId: number;
- @ViewColumn()
- number: number;
+ @ViewColumn()
+ number: number;
- @ViewColumn()
- effect: number;
-}
\ No newline at end of file
+ @ViewColumn()
+ effect: number;
+}
diff --git a/server/src/db/view-entities/AttReportAndGrade.entity.ts b/server/src/db/view-entities/AttReportAndGrade.entity.ts
index 5b6eb72b..3fe7ed8f 100644
--- a/server/src/db/view-entities/AttReportAndGrade.entity.ts
+++ b/server/src/db/view-entities/AttReportAndGrade.entity.ts
@@ -1,12 +1,12 @@
-import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { Student } from "../entities/Student.entity";
-import { AttReport } from "../entities/AttReport.entity";
-import { Grade } from "../entities/Grade.entity";
-
-@ViewEntity("att_report_and_grade", {
- expression: `
+import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Student } from '../entities/Student.entity';
+import { AttReport } from '../entities/AttReport.entity';
+import { Grade } from '../entities/Grade.entity';
+
+@ViewEntity('att_report_and_grade', {
+ expression: `
SELECT
CONCAT('a-', id) AS id,
'att' as 'type',
@@ -46,54 +46,54 @@ import { Grade } from "../entities/Grade.entity";
NULL AS 'sheet_name'
FROM
grades
-`
+`,
})
export class AttReportAndGrade implements IHasUserId {
- @Column()
- id: string;
+ @Column()
+ id: string;
- @Column()
- type: 'att' | 'grade';
+ @Column()
+ type: 'att' | 'grade';
- @Column({ name: "user_id" })
- userId: number;
+ @Column({ name: 'user_id' })
+ userId: number;
- @Column({ nullable: true })
- year: number;
+ @Column({ nullable: true })
+ year: number;
- @Column()
- studentReferenceId: number;
+ @Column()
+ studentReferenceId: number;
- @Column()
- klassReferenceId: number;
+ @Column()
+ klassReferenceId: number;
- @Column()
- lessonReferenceId: number;
+ @Column()
+ lessonReferenceId: number;
- @Column()
- teacherReferenceId: number;
+ @Column()
+ teacherReferenceId: number;
- @Column("date", { name: "report_date" })
- reportDate: string;
+ @Column('date', { name: 'report_date' })
+ reportDate: string;
- @Column({ name: "how_many_lessons", nullable: true })
- howManyLessons: number | null;
+ @Column({ name: 'how_many_lessons', nullable: true })
+ howManyLessons: number | null;
- @Column({ name: "abs_count" })
- absCount: number;
+ @Column({ name: 'abs_count' })
+ absCount: number;
- @Column({ name: "approved_abs_count" })
- approvedAbsCount: number;
+ @Column({ name: 'approved_abs_count' })
+ approvedAbsCount: number;
- @Column({ name: "grade" })
- grade: number;
+ @Column({ name: 'grade' })
+ grade: number;
- @Column({ name: "estimation", nullable: true, length: 500 })
- estimation: string | null;
+ @Column({ name: 'estimation', nullable: true, length: 500 })
+ estimation: string | null;
- @Column("varchar", { name: "comments", nullable: true, length: 500 })
- comments: string | null;
+ @Column('varchar', { name: 'comments', nullable: true, length: 500 })
+ comments: string | null;
- @Column("varchar", { name: "sheet_name", nullable: true, length: 100 })
- sheetName: string | null;
+ @Column('varchar', { name: 'sheet_name', nullable: true, length: 100 })
+ sheetName: string | null;
}
diff --git a/server/src/db/view-entities/AttReportWithReportMonth.entity.ts b/server/src/db/view-entities/AttReportWithReportMonth.entity.ts
index 868224ae..c9ffd86d 100644
--- a/server/src/db/view-entities/AttReportWithReportMonth.entity.ts
+++ b/server/src/db/view-entities/AttReportWithReportMonth.entity.ts
@@ -1,17 +1,21 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { AttReport } from "../entities/AttReport.entity";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { ReportGroupSession } from "../entities/ReportGroupSession.entity";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { AttReport } from '../entities/AttReport.entity';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { ReportGroupSession } from '../entities/ReportGroupSession.entity';
-@ViewEntity("att_report_with_report_month", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('ar.*')
- .addSelect('report_months.id', 'reportMonthReferenceId')
- .from(AttReport, 'ar')
- .leftJoin(ReportMonth, 'report_months',
- 'ar.user_id = report_months.userId AND ar.year = report_months.year AND ar.report_date BETWEEN report_months.startDate AND report_months.endDate')
+@ViewEntity('att_report_with_report_month', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('ar.*')
+ .addSelect('report_months.id', 'reportMonthReferenceId')
+ .from(AttReport, 'ar')
+ .leftJoin(
+ ReportMonth,
+ 'report_months',
+ 'ar.user_id = report_months.userId AND ar.year = report_months.year AND ar.report_date BETWEEN report_months.startDate AND report_months.endDate',
+ ),
})
export class AttReportWithReportMonth extends AttReport implements IHasUserId {
@ViewColumn()
@@ -28,7 +32,7 @@ export class AttReportWithReportMonth extends AttReport implements IHasUserId {
@JoinColumn({ name: 'reportMonthReferenceId' })
reportMonth: ReportMonth;
- @ManyToOne(() => ReportGroupSession, session => session.attReports, { nullable: true })
+ @ManyToOne(() => ReportGroupSession, (session) => session.attReports, { nullable: true })
@JoinColumn({ name: 'reportGroupSessionId' })
reportGroupSession: ReportGroupSession;
}
diff --git a/server/src/db/view-entities/GradeEffectByUser.entity.ts b/server/src/db/view-entities/GradeEffectByUser.entity.ts
index f5df7f9b..0e030255 100644
--- a/server/src/db/view-entities/GradeEffectByUser.entity.ts
+++ b/server/src/db/view-entities/GradeEffectByUser.entity.ts
@@ -1,22 +1,25 @@
-import { IHasUserId } from "@shared/base-entity/interface";
-import { User } from "@shared/entities/User.entity";
-import { AttGradeEffect } from "src/db/entities/AttGradeEffect";
-import { DataSource, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { createGradeEffectByUserExpression, IGradeEffectByUser } from "@shared/view-entities/attendance-effect-view.util";
+import { IHasUserId } from '@shared/base-entity/interface';
+import { User } from '@shared/entities/User.entity';
+import { AttGradeEffect } from 'src/db/entities/AttGradeEffect';
+import { DataSource, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import {
+ createGradeEffectByUserExpression,
+ IGradeEffectByUser,
+} from '@shared/view-entities/attendance-effect-view.util';
@ViewEntity('grade_effect_by_user', {
- expression: (dataSource: DataSource) => createGradeEffectByUserExpression(dataSource, User, AttGradeEffect)
+ expression: (dataSource: DataSource) => createGradeEffectByUserExpression(dataSource, User, AttGradeEffect),
})
export class GradeEffectByUser implements IHasUserId, IGradeEffectByUser {
- @PrimaryColumn()
- id: string;
+ @PrimaryColumn()
+ id: string;
- @ViewColumn()
- userId: number;
+ @ViewColumn()
+ userId: number;
- @ViewColumn()
- number: number;
+ @ViewColumn()
+ number: number;
- @ViewColumn()
- effect: number;
-}
\ No newline at end of file
+ @ViewColumn()
+ effect: number;
+}
diff --git a/server/src/db/view-entities/GradeWithReportMonth.entity.ts b/server/src/db/view-entities/GradeWithReportMonth.entity.ts
index 99449e9e..164b3eff 100644
--- a/server/src/db/view-entities/GradeWithReportMonth.entity.ts
+++ b/server/src/db/view-entities/GradeWithReportMonth.entity.ts
@@ -1,15 +1,20 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { Grade } from "../entities/Grade.entity";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { Grade } from '../entities/Grade.entity';
-@ViewEntity("grade_with_report_month", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('grades.*')
- .addSelect('report_months.id', 'reportMonthReferenceId')
- .from(Grade, 'grades')
- .leftJoin(ReportMonth, 'report_months', 'grades.user_id = report_months.userId AND grades.report_date <= report_months.endDate AND grades.report_date >= report_months.startDate')
+@ViewEntity('grade_with_report_month', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('grades.*')
+ .addSelect('report_months.id', 'reportMonthReferenceId')
+ .from(Grade, 'grades')
+ .leftJoin(
+ ReportMonth,
+ 'report_months',
+ 'grades.user_id = report_months.userId AND grades.report_date <= report_months.endDate AND grades.report_date >= report_months.startDate',
+ ),
})
export class GradeWithReportMonth extends Grade implements IHasUserId {
@ViewColumn()
diff --git a/server/src/db/view-entities/KnownAbsenceWithReportMonth.entity.ts b/server/src/db/view-entities/KnownAbsenceWithReportMonth.entity.ts
index f071ae0f..b2364436 100644
--- a/server/src/db/view-entities/KnownAbsenceWithReportMonth.entity.ts
+++ b/server/src/db/view-entities/KnownAbsenceWithReportMonth.entity.ts
@@ -1,14 +1,19 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { KnownAbsence } from "../entities/KnownAbsence.entity";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { KnownAbsence } from '../entities/KnownAbsence.entity';
-@ViewEntity("known_absence_with_report_month", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('known_absences.*')
- .addSelect('report_months.id', 'reportMonthReferenceId')
- .from(KnownAbsence, 'known_absences')
- .leftJoin(ReportMonth, 'report_months', 'known_absences.user_id = report_months.userId AND known_absences.report_date <= report_months.endDate AND known_absences.report_date >= report_months.startDate')
+@ViewEntity('known_absence_with_report_month', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('known_absences.*')
+ .addSelect('report_months.id', 'reportMonthReferenceId')
+ .from(KnownAbsence, 'known_absences')
+ .leftJoin(
+ ReportMonth,
+ 'report_months',
+ 'known_absences.user_id = report_months.userId AND known_absences.report_date <= report_months.endDate AND known_absences.report_date >= report_months.startDate',
+ ),
})
export class KnownAbsenceWithReportMonth extends KnownAbsence {
@ViewColumn()
diff --git a/server/src/db/view-entities/LessonKlassName.entity.ts b/server/src/db/view-entities/LessonKlassName.entity.ts
index 06b10796..bed5aa21 100644
--- a/server/src/db/view-entities/LessonKlassName.entity.ts
+++ b/server/src/db/view-entities/LessonKlassName.entity.ts
@@ -1,10 +1,14 @@
-import { Column, DataSource, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Klass } from "../entities/Klass.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { getGroupConcatExpression, getJsonTableColumn, getJsonTableExpression } from "@shared/utils/entity/column-types.util";
+import { Column, DataSource, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Klass } from '../entities/Klass.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import {
+ getGroupConcatExpression,
+ getJsonTableColumn,
+ getJsonTableExpression,
+} from '@shared/utils/entity/column-types.util';
-@ViewEntity("lesson_klass_name", {
+@ViewEntity('lesson_klass_name', {
expression: `
SELECT lessons.id AS id,
lessons.user_id AS user_id,
@@ -13,13 +17,13 @@ import { getGroupConcatExpression, getJsonTableColumn, getJsonTableExpression }
LEFT JOIN ${getJsonTableExpression('lessons.klass_reference_ids_json', 'klass_id')} AS jt ON 1=1
LEFT JOIN klasses ON klasses.id = jt.${getJsonTableColumn('klass_id')}
GROUP BY lessons.id, lessons.user_id
- `
+ `,
})
export class LessonKlassName implements IHasUserId {
@Column()
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ name: 'name' })
diff --git a/server/src/db/view-entities/StudentBaseKlass.entity.ts b/server/src/db/view-entities/StudentBaseKlass.entity.ts
index 97117d51..382ea3c3 100644
--- a/server/src/db/view-entities/StudentBaseKlass.entity.ts
+++ b/server/src/db/view-entities/StudentBaseKlass.entity.ts
@@ -1,37 +1,38 @@
-import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Klass } from "src/db/entities/Klass.entity";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { Student } from "../entities/Student.entity";
-import { KlassType, KlassTypeEnum } from "../entities/KlassType.entity";
-import { getGroupConcatExpression } from "@shared/utils/entity/column-types.util";
+import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Student } from '../entities/Student.entity';
+import { KlassType, KlassTypeEnum } from '../entities/KlassType.entity';
+import { getGroupConcatExpression } from '@shared/utils/entity/column-types.util';
-@ViewEntity("student_base_klass", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('student_klasses.studentReferenceId', 'id')
- .addSelect('student_klasses.user_id', 'user_id')
- .addSelect('student_klasses.year', 'year')
- .addSelect(getGroupConcatExpression('klasses.name', ', ', true), 'base_klass')
- .from(StudentKlass, 'student_klasses')
- .innerJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
- .innerJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
- .where(`klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}'`)
- .groupBy('student_klasses.user_id')
- .addGroupBy('student_klasses.year')
- .addGroupBy('student_klasses.studentReferenceId')
+@ViewEntity('student_base_klass', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('student_klasses.studentReferenceId', 'id')
+ .addSelect('student_klasses.user_id', 'user_id')
+ .addSelect('student_klasses.year', 'year')
+ .addSelect(getGroupConcatExpression('klasses.name', ', ', true), 'base_klass')
+ .from(StudentKlass, 'student_klasses')
+ .innerJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
+ .innerJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
+ .where(`klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}'`)
+ .groupBy('student_klasses.user_id')
+ .addGroupBy('student_klasses.year')
+ .addGroupBy('student_klasses.studentReferenceId'),
})
export class StudentBaseKlass implements IHasUserId {
@Column()
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
year: number;
- @Column({ name: "base_klass" })
+ @Column({ name: 'base_klass' })
klassName: string;
@ManyToOne(() => Student, { createForeignKeyConstraints: false })
diff --git a/server/src/db/view-entities/StudentByYear.entity.ts b/server/src/db/view-entities/StudentByYear.entity.ts
index 51b036cd..486c9a79 100644
--- a/server/src/db/view-entities/StudentByYear.entity.ts
+++ b/server/src/db/view-entities/StudentByYear.entity.ts
@@ -1,35 +1,36 @@
-import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { Student } from "../entities/Student.entity";
-import { Klass } from "../entities/Klass.entity";
-
-@ViewEntity("student_by_year", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('students.id', 'id')
- .addSelect('student_klasses.user_id', 'user_id')
- .addSelect('students.tz', 'tz')
- .addSelect('students.name', 'name')
- .addSelect('students.isActive', 'isActive')
- .addSelect('student_klasses.year', 'year')
- .addSelect('GROUP_CONCAT(DISTINCT student_klasses.klassReferenceId)', 'klassReferenceIds')
- .addSelect('GROUP_CONCAT(DISTINCT klasses.klassTypeReferenceId)', 'klassTypeReferenceIds')
- .from(StudentKlass, 'student_klasses')
- .leftJoin(Student, 'students', 'students.id = student_klasses.studentReferenceId')
- .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
- .groupBy('students.id')
- .addGroupBy('student_klasses.user_id')
- .addGroupBy('student_klasses.year')
+import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Student } from '../entities/Student.entity';
+import { Klass } from '../entities/Klass.entity';
+
+@ViewEntity('student_by_year', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('students.id', 'id')
+ .addSelect('student_klasses.user_id', 'user_id')
+ .addSelect('students.tz', 'tz')
+ .addSelect('students.name', 'name')
+ .addSelect('students.isActive', 'isActive')
+ .addSelect('student_klasses.year', 'year')
+ .addSelect('GROUP_CONCAT(DISTINCT student_klasses.klassReferenceId)', 'klassReferenceIds')
+ .addSelect('GROUP_CONCAT(DISTINCT klasses.klassTypeReferenceId)', 'klassTypeReferenceIds')
+ .from(StudentKlass, 'student_klasses')
+ .leftJoin(Student, 'students', 'students.id = student_klasses.studentReferenceId')
+ .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
+ .groupBy('students.id')
+ .addGroupBy('student_klasses.user_id')
+ .addGroupBy('student_klasses.year'),
})
export class StudentByYear implements IHasUserId {
@Column()
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
- @Column("varchar", { name: "tz", length: 10 })
+ @Column('varchar', { name: 'tz', length: 10 })
tz: string;
@Column({ name: 'name' })
@@ -38,7 +39,7 @@ export class StudentByYear implements IHasUserId {
@Column({ name: 'isActive', default: true })
isActive: boolean;
- @Column("int", { name: 'year' })
+ @Column('int', { name: 'year' })
year: number;
@Column('simple-array', { nullable: true })
diff --git a/server/src/db/view-entities/StudentGlobalReport.entity.ts b/server/src/db/view-entities/StudentGlobalReport.entity.ts
index 073a9176..f71dabb2 100644
--- a/server/src/db/view-entities/StudentGlobalReport.entity.ts
+++ b/server/src/db/view-entities/StudentGlobalReport.entity.ts
@@ -1,54 +1,62 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Student } from "../entities/Student.entity";
-import { AttReportAndGrade } from "./AttReportAndGrade.entity";
-import { Teacher } from "../entities/Teacher.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { Klass } from "../entities/Klass.entity";
-import { KlassType, KlassTypeEnum } from "../entities/KlassType.entity";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Student } from '../entities/Student.entity';
+import { AttReportAndGrade } from './AttReportAndGrade.entity';
+import { Teacher } from '../entities/Teacher.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import { Klass } from '../entities/Klass.entity';
+import { KlassType, KlassTypeEnum } from '../entities/KlassType.entity';
-@ViewEntity("student_global_report", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('CONCAT(COALESCE(sgr_inner.studentReferenceId, "null"), "_", COALESCE(sgr_inner.teacherReferenceId, "null"), "_", ' +
- 'COALESCE(sgr_inner.klassReferenceId, "null"), "_", COALESCE(sgr_inner.lessonReferenceId, "null"), "_", ' +
- 'COALESCE(sgr_inner.user_id, "null"), "_", COALESCE(sgr_inner.year, "null"))', 'id')
- .addSelect('sgr_inner.user_id', 'user_id')
- .addSelect('sgr_inner.year', 'year')
- .addSelect('sgr_inner.studentReferenceId', 'studentReferenceId')
- .addSelect('sgr_inner.teacherReferenceId', 'teacherReferenceId')
- .addSelect('sgr_inner.klassReferenceId', 'klassReferenceId')
- .addSelect('sgr_inner.lessonReferenceId', 'lessonReferenceId')
- .addSelect(`CASE WHEN klass_types.klassTypeEnum = "${KlassTypeEnum.baseKlass}" THEN 1 ELSE 0 END`, 'isBaseKlass')
- .addSelect('sgr_inner.lessons_count', 'lessons_count')
- .addSelect('sgr_inner.abs_count', 'abs_count')
- .addSelect('sgr_inner.grade_avg', 'grade_avg')
- .from(subQuery => subQuery
- .select('atag.user_id', 'user_id')
- .addSelect('atag.year', 'year')
- .addSelect('atag.studentReferenceId', 'studentReferenceId')
- .addSelect('atag.teacherReferenceId', 'teacherReferenceId')
- .addSelect('atag.klassReferenceId', 'klassReferenceId')
- .addSelect('atag.lessonReferenceId', 'lessonReferenceId')
- .addSelect('SUM(atag.how_many_lessons)', 'lessons_count')
- .addSelect('SUM(atag.abs_count)', 'abs_count')
- .addSelect('AVG(atag.grade)', 'grade_avg')
- .from(AttReportAndGrade, 'atag')
- .groupBy('atag.user_id')
- .addGroupBy('atag.year')
- .addGroupBy('atag.studentReferenceId')
- .addGroupBy('atag.teacherReferenceId')
- .addGroupBy('atag.klassReferenceId')
- .addGroupBy('atag.lessonReferenceId'), 'sgr_inner')
- .leftJoin(Klass, 'klasses', 'klasses.id = sgr_inner.klassReferenceId')
- .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
+@ViewEntity('student_global_report', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select(
+ 'CONCAT(COALESCE(sgr_inner.studentReferenceId, "null"), "_", COALESCE(sgr_inner.teacherReferenceId, "null"), "_", ' +
+ 'COALESCE(sgr_inner.klassReferenceId, "null"), "_", COALESCE(sgr_inner.lessonReferenceId, "null"), "_", ' +
+ 'COALESCE(sgr_inner.user_id, "null"), "_", COALESCE(sgr_inner.year, "null"))',
+ 'id',
+ )
+ .addSelect('sgr_inner.user_id', 'user_id')
+ .addSelect('sgr_inner.year', 'year')
+ .addSelect('sgr_inner.studentReferenceId', 'studentReferenceId')
+ .addSelect('sgr_inner.teacherReferenceId', 'teacherReferenceId')
+ .addSelect('sgr_inner.klassReferenceId', 'klassReferenceId')
+ .addSelect('sgr_inner.lessonReferenceId', 'lessonReferenceId')
+ .addSelect(`CASE WHEN klass_types.klassTypeEnum = "${KlassTypeEnum.baseKlass}" THEN 1 ELSE 0 END`, 'isBaseKlass')
+ .addSelect('sgr_inner.lessons_count', 'lessons_count')
+ .addSelect('sgr_inner.abs_count', 'abs_count')
+ .addSelect('sgr_inner.grade_avg', 'grade_avg')
+ .from(
+ (subQuery) =>
+ subQuery
+ .select('atag.user_id', 'user_id')
+ .addSelect('atag.year', 'year')
+ .addSelect('atag.studentReferenceId', 'studentReferenceId')
+ .addSelect('atag.teacherReferenceId', 'teacherReferenceId')
+ .addSelect('atag.klassReferenceId', 'klassReferenceId')
+ .addSelect('atag.lessonReferenceId', 'lessonReferenceId')
+ .addSelect('SUM(atag.how_many_lessons)', 'lessons_count')
+ .addSelect('SUM(atag.abs_count)', 'abs_count')
+ .addSelect('AVG(atag.grade)', 'grade_avg')
+ .from(AttReportAndGrade, 'atag')
+ .groupBy('atag.user_id')
+ .addGroupBy('atag.year')
+ .addGroupBy('atag.studentReferenceId')
+ .addGroupBy('atag.teacherReferenceId')
+ .addGroupBy('atag.klassReferenceId')
+ .addGroupBy('atag.lessonReferenceId'),
+ 'sgr_inner',
+ )
+ .leftJoin(Klass, 'klasses', 'klasses.id = sgr_inner.klassReferenceId')
+ .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId'),
})
export class StudentGlobalReport implements IHasUserId {
@ViewColumn()
@PrimaryColumn()
id: string;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
diff --git a/server/src/db/view-entities/StudentKlassReport.entity.ts b/server/src/db/view-entities/StudentKlassReport.entity.ts
index 18abe13f..c0b411b4 100644
--- a/server/src/db/view-entities/StudentKlassReport.entity.ts
+++ b/server/src/db/view-entities/StudentKlassReport.entity.ts
@@ -1,57 +1,114 @@
-import { Column, DataSource, JoinColumn, OneToOne, PrimaryColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Klass } from "src/db/entities/Klass.entity";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { User } from "@shared/entities/User.entity";
-import { KlassType, KlassTypeEnum } from "../entities/KlassType.entity";
-import { Student } from "../entities/Student.entity";
-import { getGroupConcatExpression } from "@shared/utils/entity/column-types.util";
-
-@ViewEntity("student_klasses_report", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('students.id', 'id')
- .addSelect('students.id', 'student_reference_id')
- .addSelect('students.tz', 'student_tz')
- .addSelect('students.name', 'student_name')
- .addSelect('student_klasses.user_id', 'user_id')
- .addSelect('student_klasses.year', 'year')
-
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}', student_klasses.klassReferenceId, null)`, ',', false), 'klassReferenceId_1')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.track}', student_klasses.klassReferenceId, null)`, ',', false), 'klassReferenceId_2')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', student_klasses.klassReferenceId, null)`, ',', false), 'klassReferenceId_3')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.other}' || klass_types.klassTypeEnum is null, student_klasses.klassReferenceId, null)`, ',', false), 'klassReferenceId_null')
-
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}', klasses.name, null)`, ', ', false), 'klass_name_1')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.track}', klasses.name, null)`, ', ', false), 'klass_name_2')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', klasses.name, null)`, ', ', false), 'klass_name_3')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.other}' || klass_types.klassTypeEnum is null, klasses.name, null)`, ', ', false), 'klass_name_null')
-
- .from(StudentKlass, 'student_klasses')
- .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
- .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
- .leftJoin(Student, 'students', 'students.id = student_klasses.studentReferenceId')
- .groupBy('students.id')
- .addGroupBy('student_klasses.user_id')
- .addGroupBy('student_klasses.year')
+import { Column, DataSource, JoinColumn, OneToOne, PrimaryColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { User } from '@shared/entities/User.entity';
+import { KlassType, KlassTypeEnum } from '../entities/KlassType.entity';
+import { Student } from '../entities/Student.entity';
+import { getGroupConcatExpression } from '@shared/utils/entity/column-types.util';
+
+@ViewEntity('student_klasses_report', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('students.id', 'id')
+ .addSelect('students.id', 'student_reference_id')
+ .addSelect('students.tz', 'student_tz')
+ .addSelect('students.name', 'student_name')
+ .addSelect('student_klasses.user_id', 'user_id')
+ .addSelect('student_klasses.year', 'year')
+
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}', student_klasses.klassReferenceId, null)`,
+ ',',
+ false,
+ ),
+ 'klassReferenceId_1',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.track}', student_klasses.klassReferenceId, null)`,
+ ',',
+ false,
+ ),
+ 'klassReferenceId_2',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', student_klasses.klassReferenceId, null)`,
+ ',',
+ false,
+ ),
+ 'klassReferenceId_3',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.other}' || klass_types.klassTypeEnum is null, student_klasses.klassReferenceId, null)`,
+ ',',
+ false,
+ ),
+ 'klassReferenceId_null',
+ )
+
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.baseKlass}', klasses.name, null)`,
+ ', ',
+ false,
+ ),
+ 'klass_name_1',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.track}', klasses.name, null)`,
+ ', ',
+ false,
+ ),
+ 'klass_name_2',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', klasses.name, null)`,
+ ', ',
+ false,
+ ),
+ 'klass_name_3',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.other}' || klass_types.klassTypeEnum is null, klasses.name, null)`,
+ ', ',
+ false,
+ ),
+ 'klass_name_null',
+ )
+
+ .from(StudentKlass, 'student_klasses')
+ .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
+ .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
+ .leftJoin(Student, 'students', 'students.id = student_klasses.studentReferenceId')
+ .groupBy('students.id')
+ .addGroupBy('student_klasses.user_id')
+ .addGroupBy('student_klasses.year'),
})
export class StudentKlassReport implements IHasUserId {
@PrimaryColumn()
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
year: number;
- @Column("varchar", { name: "student_tz", length: 10, nullable: true })
+ @Column('varchar', { name: 'student_tz', length: 10, nullable: true })
studentTz: string;
- @Column({ name: "student_reference_id" })
+ @Column({ name: 'student_reference_id' })
studentReferenceId: number;
- @Column({ name: "student_name" })
+ @Column({ name: 'student_name' })
studentName: string;
@Column('simple-array', { name: 'klassReferenceId_1' })
@@ -78,10 +135,10 @@ export class StudentKlassReport implements IHasUserId {
@Column({ name: 'klass_name_null' })
klassNameNull: string;
- @JoinColumn([{ name: "user_id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'user_id', referencedColumnName: 'id' }])
user: User;
@OneToOne(() => Student)
- @JoinColumn([{ name: "id", referencedColumnName: "id" }])
+ @JoinColumn([{ name: 'id', referencedColumnName: 'id' }])
student: Student;
}
diff --git a/server/src/db/view-entities/StudentPercentReport.entity.ts b/server/src/db/view-entities/StudentPercentReport.entity.ts
index 87bea834..5bc8ec94 100644
--- a/server/src/db/view-entities/StudentPercentReport.entity.ts
+++ b/server/src/db/view-entities/StudentPercentReport.entity.ts
@@ -1,35 +1,36 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Student } from "../entities/Student.entity";
-import { Teacher } from "../entities/Teacher.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { Klass } from "../entities/Klass.entity";
-import { StudentGlobalReport } from "./StudentGlobalReport.entity";
-import { StudentBaseKlass } from "./StudentBaseKlass.entity";
-
-@ViewEntity("student_percent_report", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('id')
- .addSelect('user_id')
- .addSelect('year')
- .addSelect('studentReferenceId')
- .addSelect('teacherReferenceId')
- .addSelect('klassReferenceId')
- .addSelect('lessonReferenceId')
- .addSelect('lessons_count')
- .addSelect('abs_count')
- .addSelect('COALESCE(abs_count, 0) / GREATEST(COALESCE(lessons_count, 1), 1)', 'abs_percents')
- .addSelect('(1 - COALESCE(abs_count, 0) / GREATEST(COALESCE(lessons_count, 1), 1))', 'att_percents')
- .addSelect('grade_avg / 100', 'grade_avg')
- .from(StudentGlobalReport, 'sgr')
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Student } from '../entities/Student.entity';
+import { Teacher } from '../entities/Teacher.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import { Klass } from '../entities/Klass.entity';
+import { StudentGlobalReport } from './StudentGlobalReport.entity';
+import { StudentBaseKlass } from './StudentBaseKlass.entity';
+
+@ViewEntity('student_percent_report', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('id')
+ .addSelect('user_id')
+ .addSelect('year')
+ .addSelect('studentReferenceId')
+ .addSelect('teacherReferenceId')
+ .addSelect('klassReferenceId')
+ .addSelect('lessonReferenceId')
+ .addSelect('lessons_count')
+ .addSelect('abs_count')
+ .addSelect('COALESCE(abs_count, 0) / GREATEST(COALESCE(lessons_count, 1), 1)', 'abs_percents')
+ .addSelect('(1 - COALESCE(abs_count, 0) / GREATEST(COALESCE(lessons_count, 1), 1))', 'att_percents')
+ .addSelect('grade_avg / 100', 'grade_avg')
+ .from(StudentGlobalReport, 'sgr'),
})
export class StudentPercentReport implements IHasUserId {
@ViewColumn()
@PrimaryColumn()
id: string;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
@@ -82,7 +83,7 @@ export class StudentPercentReport implements IHasUserId {
@JoinColumn([
{ name: 'studentReferenceId', referencedColumnName: 'id' },
{ name: 'year', referencedColumnName: 'year' },
- { name: 'user_id', referencedColumnName: 'userId' }
+ { name: 'user_id', referencedColumnName: 'userId' },
])
studentBaseKlass: StudentBaseKlass;
}
diff --git a/server/src/db/view-entities/StudentSpeciality.entity.ts b/server/src/db/view-entities/StudentSpeciality.entity.ts
index 297a2690..1a9abbb4 100644
--- a/server/src/db/view-entities/StudentSpeciality.entity.ts
+++ b/server/src/db/view-entities/StudentSpeciality.entity.ts
@@ -1,36 +1,44 @@
-import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Klass } from "src/db/entities/Klass.entity";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { Student } from "../entities/Student.entity";
-import { KlassType, KlassTypeEnum } from "../entities/KlassType.entity";
-import { getGroupConcatExpression } from "@shared/utils/entity/column-types.util";
+import { Column, DataSource, JoinColumn, ManyToOne, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { Student } from '../entities/Student.entity';
+import { KlassType, KlassTypeEnum } from '../entities/KlassType.entity';
+import { getGroupConcatExpression } from '@shared/utils/entity/column-types.util';
-@ViewEntity("student_speciality", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('studentReferenceId', 'id')
- .addSelect('student_klasses.user_id', 'user_id')
- .addSelect('student_klasses.year', 'year')
- .addSelect(getGroupConcatExpression(`if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', klasses.name, null)`, ', ', true), 'base_klass')
- .from(StudentKlass, 'student_klasses')
- .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
- .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
- .groupBy('studentReferenceId')
- .addGroupBy('user_id')
- .addGroupBy('year')
+@ViewEntity('student_speciality', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('studentReferenceId', 'id')
+ .addSelect('student_klasses.user_id', 'user_id')
+ .addSelect('student_klasses.year', 'year')
+ .addSelect(
+ getGroupConcatExpression(
+ `if(klass_types.klassTypeEnum = '${KlassTypeEnum.speciality}', klasses.name, null)`,
+ ', ',
+ true,
+ ),
+ 'base_klass',
+ )
+ .from(StudentKlass, 'student_klasses')
+ .leftJoin(Klass, 'klasses', 'klasses.id = student_klasses.klassReferenceId')
+ .leftJoin(KlassType, 'klass_types', 'klass_types.id = klasses.klassTypeReferenceId')
+ .groupBy('studentReferenceId')
+ .addGroupBy('user_id')
+ .addGroupBy('year'),
})
export class StudentSpeciality implements IHasUserId {
@Column()
id: number;
- @Column("int", { name: "user_id" })
+ @Column('int', { name: 'user_id' })
userId: number;
@Column({ nullable: true })
year: number;
- @Column({ name: "base_klass" })
+ @Column({ name: 'base_klass' })
klassName: string;
@ManyToOne(() => Student, { createForeignKeyConstraints: false })
diff --git a/server/src/db/view-entities/TeacherGradeReportStatus.entity.ts b/server/src/db/view-entities/TeacherGradeReportStatus.entity.ts
index 91652914..98975d2f 100644
--- a/server/src/db/view-entities/TeacherGradeReportStatus.entity.ts
+++ b/server/src/db/view-entities/TeacherGradeReportStatus.entity.ts
@@ -1,35 +1,61 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "../entities/Teacher.entity";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { TeacherLessonGradeReportStatus } from "./TeacherLessonGradeReportStatus.entity";
-import { getGroupConcatExpression } from "@shared/utils/entity/column-types.util";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from '../entities/Teacher.entity';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { TeacherLessonGradeReportStatus } from './TeacherLessonGradeReportStatus.entity';
+import { getGroupConcatExpression } from '@shared/utils/entity/column-types.util';
-@ViewEntity("teacher_grade_report_status", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('CONCAT(COALESCE(tlrs.userId, "null"), "_", COALESCE(tlrs.teacherId, "null"), "_", ' +
- 'COALESCE(tlrs.reportMonthId, "null"), "_", COALESCE(tlrs.year, "null"))', 'id')
- .addSelect('tlrs.userId', 'userId')
- .addSelect('tlrs.teacherId', 'teacherId')
- .addSelect('teacher.name', 'teacherName')
- .addSelect('teacher.comment', 'teacherComment')
- .addSelect('tlrs.reportMonthId', 'reportMonthId')
- .addSelect('tlrs.year', 'year')
- .addSelect('rm.name', 'reportMonthName')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'), 'reportedLessons')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'), 'notReportedLessons')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonName END', ', ', true, 'tlrs.lessonName'), 'reportedLessonNames')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonName END', ', ', true, 'tlrs.lessonName'), 'notReportedLessonNames')
- .from(TeacherLessonGradeReportStatus, 'tlrs')
- .leftJoin(Teacher, 'teacher', 'tlrs.teacherId = teacher.id')
- .leftJoin(ReportMonth, 'rm', 'tlrs.reportMonthId = rm.id')
- .groupBy('tlrs.userId')
- .addGroupBy('tlrs.teacherId')
- .addGroupBy('tlrs.reportMonthId')
- .addGroupBy('tlrs.year')
- .orderBy('tlrs.reportMonthId')
- .addOrderBy('tlrs.teacherId')
+@ViewEntity('teacher_grade_report_status', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select(
+ 'CONCAT(COALESCE(tlrs.userId, "null"), "_", COALESCE(tlrs.teacherId, "null"), "_", ' +
+ 'COALESCE(tlrs.reportMonthId, "null"), "_", COALESCE(tlrs.year, "null"))',
+ 'id',
+ )
+ .addSelect('tlrs.userId', 'userId')
+ .addSelect('tlrs.teacherId', 'teacherId')
+ .addSelect('teacher.name', 'teacherName')
+ .addSelect('teacher.comment', 'teacherComment')
+ .addSelect('tlrs.reportMonthId', 'reportMonthId')
+ .addSelect('tlrs.year', 'year')
+ .addSelect('rm.name', 'reportMonthName')
+ .addSelect(
+ getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'),
+ 'reportedLessons',
+ )
+ .addSelect(
+ getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'),
+ 'notReportedLessons',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ 'CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonName END',
+ ', ',
+ true,
+ 'tlrs.lessonName',
+ ),
+ 'reportedLessonNames',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ 'CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonName END',
+ ', ',
+ true,
+ 'tlrs.lessonName',
+ ),
+ 'notReportedLessonNames',
+ )
+ .from(TeacherLessonGradeReportStatus, 'tlrs')
+ .leftJoin(Teacher, 'teacher', 'tlrs.teacherId = teacher.id')
+ .leftJoin(ReportMonth, 'rm', 'tlrs.reportMonthId = rm.id')
+ .groupBy('tlrs.userId')
+ .addGroupBy('tlrs.teacherId')
+ .addGroupBy('tlrs.reportMonthId')
+ .addGroupBy('tlrs.year')
+ .orderBy('tlrs.reportMonthId')
+ .addOrderBy('tlrs.teacherId'),
})
export class TeacherGradeReportStatus implements IHasUserId {
@PrimaryColumn()
diff --git a/server/src/db/view-entities/TeacherLessonGradeReportStatus.entity.ts b/server/src/db/view-entities/TeacherLessonGradeReportStatus.entity.ts
index 6e06f48b..b1d7e4c8 100644
--- a/server/src/db/view-entities/TeacherLessonGradeReportStatus.entity.ts
+++ b/server/src/db/view-entities/TeacherLessonGradeReportStatus.entity.ts
@@ -1,30 +1,37 @@
-import { Column, DataSource, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "../entities/Teacher.entity";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { GradeWithReportMonth } from "./GradeWithReportMonth.entity";
+import { Column, DataSource, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from '../entities/Teacher.entity';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import { GradeWithReportMonth } from './GradeWithReportMonth.entity';
-@ViewEntity("teacher_lesson_grade_report_status", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('teachers.user_id', 'userId')
- .addSelect('teachers.id', 'teacherId')
- .addSelect('lessons.id', 'lessonId')
- .addSelect('lessons.name', 'lessonName')
- .addSelect('lessons.year', 'year')
- .addSelect('report_months.id', 'reportMonthId')
- .addSelect('CASE WHEN COUNT(grades.id) > 0 THEN 1 ELSE 0 END', 'isReported')
- .from(Teacher, 'teachers')
- .innerJoin(Lesson, 'lessons', 'lessons.teacherReferenceId = teachers.id')
- .leftJoin(ReportMonth, 'report_months', 'report_months.userId = teachers.user_id')
- .leftJoin(GradeWithReportMonth, 'grades', 'grades.teacherReferenceId = teachers.id AND grades.lessonReferenceId = lessons.id AND grades.reportMonthReferenceId = report_months.id')
- .where('COALESCE(lessons.start_date, report_months.endDate) <= report_months.endDate'
- + ' AND COALESCE(lessons.end_date, report_months.startDate) >= report_months.startDate')
- .groupBy('teachers.id')
- .addGroupBy('lessons.id')
- .addGroupBy('report_months.id')
- .orderBy('report_months.id')
+@ViewEntity('teacher_lesson_grade_report_status', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('teachers.user_id', 'userId')
+ .addSelect('teachers.id', 'teacherId')
+ .addSelect('lessons.id', 'lessonId')
+ .addSelect('lessons.name', 'lessonName')
+ .addSelect('lessons.year', 'year')
+ .addSelect('report_months.id', 'reportMonthId')
+ .addSelect('CASE WHEN COUNT(grades.id) > 0 THEN 1 ELSE 0 END', 'isReported')
+ .from(Teacher, 'teachers')
+ .innerJoin(Lesson, 'lessons', 'lessons.teacherReferenceId = teachers.id')
+ .leftJoin(ReportMonth, 'report_months', 'report_months.userId = teachers.user_id')
+ .leftJoin(
+ GradeWithReportMonth,
+ 'grades',
+ 'grades.teacherReferenceId = teachers.id AND grades.lessonReferenceId = lessons.id AND grades.reportMonthReferenceId = report_months.id',
+ )
+ .where(
+ 'COALESCE(lessons.start_date, report_months.endDate) <= report_months.endDate' +
+ ' AND COALESCE(lessons.end_date, report_months.startDate) >= report_months.startDate',
+ )
+ .groupBy('teachers.id')
+ .addGroupBy('lessons.id')
+ .addGroupBy('report_months.id')
+ .orderBy('report_months.id'),
})
export class TeacherLessonGradeReportStatus implements IHasUserId {
@Column()
diff --git a/server/src/db/view-entities/TeacherLessonReportStatus.entity.ts b/server/src/db/view-entities/TeacherLessonReportStatus.entity.ts
index 51ab68b6..f322b2af 100644
--- a/server/src/db/view-entities/TeacherLessonReportStatus.entity.ts
+++ b/server/src/db/view-entities/TeacherLessonReportStatus.entity.ts
@@ -1,32 +1,41 @@
-import { Column, DataSource, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "../entities/Teacher.entity";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { AttReport } from "../entities/AttReport.entity";
+import { Column, DataSource, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from '../entities/Teacher.entity';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import { AttReport } from '../entities/AttReport.entity';
-@ViewEntity("teacher_lesson_report_status", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('lessons.teacherReferenceId', 'teacherId')
- .addSelect('lessons.userId', 'userId')
- .addSelect('lessons.id', 'lessonId')
- .addSelect('lessons.name', 'lessonName')
- .addSelect('lessons.year', 'year')
- .addSelect('report_months.id', 'reportMonthId')
- .addSelect('CASE WHEN COUNT(att_reports.id) > 0 THEN 1 ELSE 0 END', 'isReported')
- .from(Lesson, 'lessons')
- .innerJoin(Teacher, 'teachers', 'teachers.id = lessons.teacherReferenceId AND teachers.user_id = lessons.userId')
- .leftJoin(ReportMonth, 'report_months', 'report_months.userId = lessons.userId AND report_months.year = lessons.year')
- .leftJoin(AttReport, 'att_reports', 'att_reports.teacherReferenceId = lessons.teacherReferenceId AND att_reports.lessonReferenceId = lessons.id AND att_reports.report_date BETWEEN report_months.startDate AND report_months.endDate')
- .where('report_months.id IS NOT NULL')
- .andWhere('(lessons.start_date IS NULL OR lessons.start_date <= report_months.endDate)')
- .andWhere('(lessons.end_date IS NULL OR lessons.end_date >= report_months.startDate)')
- .groupBy('lessons.teacherReferenceId')
- .addGroupBy('lessons.userId')
- .addGroupBy('lessons.id')
- .addGroupBy('report_months.id')
- .orderBy('report_months.id')
+@ViewEntity('teacher_lesson_report_status', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select('lessons.teacherReferenceId', 'teacherId')
+ .addSelect('lessons.userId', 'userId')
+ .addSelect('lessons.id', 'lessonId')
+ .addSelect('lessons.name', 'lessonName')
+ .addSelect('lessons.year', 'year')
+ .addSelect('report_months.id', 'reportMonthId')
+ .addSelect('CASE WHEN COUNT(att_reports.id) > 0 THEN 1 ELSE 0 END', 'isReported')
+ .from(Lesson, 'lessons')
+ .innerJoin(Teacher, 'teachers', 'teachers.id = lessons.teacherReferenceId AND teachers.user_id = lessons.userId')
+ .leftJoin(
+ ReportMonth,
+ 'report_months',
+ 'report_months.userId = lessons.userId AND report_months.year = lessons.year',
+ )
+ .leftJoin(
+ AttReport,
+ 'att_reports',
+ 'att_reports.teacherReferenceId = lessons.teacherReferenceId AND att_reports.lessonReferenceId = lessons.id AND att_reports.report_date BETWEEN report_months.startDate AND report_months.endDate',
+ )
+ .where('report_months.id IS NOT NULL')
+ .andWhere('(lessons.start_date IS NULL OR lessons.start_date <= report_months.endDate)')
+ .andWhere('(lessons.end_date IS NULL OR lessons.end_date >= report_months.startDate)')
+ .groupBy('lessons.teacherReferenceId')
+ .addGroupBy('lessons.userId')
+ .addGroupBy('lessons.id')
+ .addGroupBy('report_months.id')
+ .orderBy('report_months.id'),
})
export class TeacherLessonReportStatus implements IHasUserId {
@Column()
diff --git a/server/src/db/view-entities/TeacherReportStatus.entity.ts b/server/src/db/view-entities/TeacherReportStatus.entity.ts
index 82c17b7c..f33eb9fa 100644
--- a/server/src/db/view-entities/TeacherReportStatus.entity.ts
+++ b/server/src/db/view-entities/TeacherReportStatus.entity.ts
@@ -1,35 +1,61 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { Teacher } from "../entities/Teacher.entity";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { TeacherLessonReportStatus } from "./TeacherLessonReportStatus.entity";
-import { getGroupConcatExpression } from "@shared/utils/entity/column-types.util";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { Teacher } from '../entities/Teacher.entity';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { TeacherLessonReportStatus } from './TeacherLessonReportStatus.entity';
+import { getGroupConcatExpression } from '@shared/utils/entity/column-types.util';
-@ViewEntity("teacher_report_status", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('CONCAT(COALESCE(tlrs.userId, "null"), "_", COALESCE(tlrs.teacherId, "null"), "_", ' +
- 'COALESCE(tlrs.reportMonthId, "null"), "_", COALESCE(tlrs.year, "null"))', 'id')
- .addSelect('tlrs.userId', 'userId')
- .addSelect('tlrs.teacherId', 'teacherId')
- .addSelect('teacher.name', 'teacherName')
- .addSelect('teacher.comment', 'teacherComment')
- .addSelect('tlrs.reportMonthId', 'reportMonthId')
- .addSelect('tlrs.year', 'year')
- .addSelect('rm.name', 'reportMonthName')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'), 'reportedLessons')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'), 'notReportedLessons')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonName END', ', ', true, 'tlrs.lessonName'), 'reportedLessonNames')
- .addSelect(getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonName END', ', ', true, 'tlrs.lessonName'), 'notReportedLessonNames')
- .from(TeacherLessonReportStatus, 'tlrs')
- .leftJoin(Teacher, 'teacher', 'tlrs.teacherId = teacher.id')
- .leftJoin(ReportMonth, 'rm', 'tlrs.reportMonthId = rm.id')
- .groupBy('tlrs.userId')
- .addGroupBy('tlrs.year')
- .addGroupBy('tlrs.teacherId')
- .addGroupBy('tlrs.reportMonthId')
- .orderBy('tlrs.reportMonthId')
- .addOrderBy('tlrs.teacherId')
+@ViewEntity('teacher_report_status', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select(
+ 'CONCAT(COALESCE(tlrs.userId, "null"), "_", COALESCE(tlrs.teacherId, "null"), "_", ' +
+ 'COALESCE(tlrs.reportMonthId, "null"), "_", COALESCE(tlrs.year, "null"))',
+ 'id',
+ )
+ .addSelect('tlrs.userId', 'userId')
+ .addSelect('tlrs.teacherId', 'teacherId')
+ .addSelect('teacher.name', 'teacherName')
+ .addSelect('teacher.comment', 'teacherComment')
+ .addSelect('tlrs.reportMonthId', 'reportMonthId')
+ .addSelect('tlrs.year', 'year')
+ .addSelect('rm.name', 'reportMonthName')
+ .addSelect(
+ getGroupConcatExpression('CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'),
+ 'reportedLessons',
+ )
+ .addSelect(
+ getGroupConcatExpression('CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonId END', ',', true, 'tlrs.lessonName'),
+ 'notReportedLessons',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ 'CASE WHEN tlrs.isReported = 1 THEN tlrs.lessonName END',
+ ', ',
+ true,
+ 'tlrs.lessonName',
+ ),
+ 'reportedLessonNames',
+ )
+ .addSelect(
+ getGroupConcatExpression(
+ 'CASE WHEN tlrs.isReported = 0 THEN tlrs.lessonName END',
+ ', ',
+ true,
+ 'tlrs.lessonName',
+ ),
+ 'notReportedLessonNames',
+ )
+ .from(TeacherLessonReportStatus, 'tlrs')
+ .leftJoin(Teacher, 'teacher', 'tlrs.teacherId = teacher.id')
+ .leftJoin(ReportMonth, 'rm', 'tlrs.reportMonthId = rm.id')
+ .groupBy('tlrs.userId')
+ .addGroupBy('tlrs.year')
+ .addGroupBy('tlrs.teacherId')
+ .addGroupBy('tlrs.reportMonthId')
+ .orderBy('tlrs.reportMonthId')
+ .addOrderBy('tlrs.teacherId'),
})
export class TeacherReportStatus implements IHasUserId {
@PrimaryColumn()
diff --git a/server/src/db/view-entities/TeacherSalaryReport.entity.ts b/server/src/db/view-entities/TeacherSalaryReport.entity.ts
index bb025135..aec16c42 100644
--- a/server/src/db/view-entities/TeacherSalaryReport.entity.ts
+++ b/server/src/db/view-entities/TeacherSalaryReport.entity.ts
@@ -1,27 +1,31 @@
-import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from "typeorm";
-import { IHasUserId } from "@shared/base-entity/interface";
-import { ReportMonth } from "../entities/ReportMonth.entity";
-import { Teacher } from "../entities/Teacher.entity";
-import { Lesson } from "../entities/Lesson.entity";
-import { Klass } from "../entities/Klass.entity";
-import { AttReportWithReportMonth } from "./AttReportWithReportMonth.entity";
+import { Column, DataSource, JoinColumn, ManyToOne, PrimaryColumn, ViewColumn, ViewEntity } from 'typeorm';
+import { IHasUserId } from '@shared/base-entity/interface';
+import { ReportMonth } from '../entities/ReportMonth.entity';
+import { Teacher } from '../entities/Teacher.entity';
+import { Lesson } from '../entities/Lesson.entity';
+import { Klass } from '../entities/Klass.entity';
+import { AttReportWithReportMonth } from './AttReportWithReportMonth.entity';
-@ViewEntity("teacher_salary_report", {
- expression: (dataSource: DataSource) => dataSource
- .createQueryBuilder()
- .select('CONCAT(COALESCE(att_reports.user_id, "null"), "_", COALESCE(att_reports.teacherReferenceId, "null"), "_", ' +
- 'COALESCE(att_reports.lessonReferenceId, "null"), "_", COALESCE(att_reports.klassReferenceId, "null"), "_", ' +
- 'COALESCE(att_reports.how_many_lessons, "null"), "_", COALESCE(att_reports.year, "null"), "_", ' +
- 'COALESCE(att_reports.reportMonthReferenceId, "null"))', 'id')
- .addSelect('att_reports.user_id', 'userId')
- .addSelect('att_reports.teacherReferenceId', 'teacherReferenceId')
- .addSelect('att_reports.lessonReferenceId', 'lessonReferenceId')
- .addSelect('att_reports.klassReferenceId', 'klassReferenceId')
- .addSelect('att_reports.how_many_lessons', 'how_many_lessons')
- .addSelect('att_reports.year', 'year')
- .addSelect('att_reports.reportMonthReferenceId', 'reportMonthReferenceId')
- .distinct(true)
- .from(AttReportWithReportMonth, 'att_reports')
+@ViewEntity('teacher_salary_report', {
+ expression: (dataSource: DataSource) =>
+ dataSource
+ .createQueryBuilder()
+ .select(
+ 'CONCAT(COALESCE(att_reports.user_id, "null"), "_", COALESCE(att_reports.teacherReferenceId, "null"), "_", ' +
+ 'COALESCE(att_reports.lessonReferenceId, "null"), "_", COALESCE(att_reports.klassReferenceId, "null"), "_", ' +
+ 'COALESCE(att_reports.how_many_lessons, "null"), "_", COALESCE(att_reports.year, "null"), "_", ' +
+ 'COALESCE(att_reports.reportMonthReferenceId, "null"))',
+ 'id',
+ )
+ .addSelect('att_reports.user_id', 'userId')
+ .addSelect('att_reports.teacherReferenceId', 'teacherReferenceId')
+ .addSelect('att_reports.lessonReferenceId', 'lessonReferenceId')
+ .addSelect('att_reports.klassReferenceId', 'klassReferenceId')
+ .addSelect('att_reports.how_many_lessons', 'how_many_lessons')
+ .addSelect('att_reports.year', 'year')
+ .addSelect('att_reports.reportMonthReferenceId', 'reportMonthReferenceId')
+ .distinct(true)
+ .from(AttReportWithReportMonth, 'att_reports'),
})
export class TeacherSalaryReport implements IHasUserId {
@ViewColumn()
diff --git a/server/src/entities.module.ts b/server/src/entities.module.ts
index ce419e5c..a7c8703c 100644
--- a/server/src/entities.module.ts
+++ b/server/src/entities.module.ts
@@ -1,4 +1,4 @@
-import { Module } from "@nestjs/common";
+import { Module } from '@nestjs/common';
import { BaseEntityModule } from '@shared/base-entity/base-entity.module';
import { createSharedEntitiesImports } from '@shared/entities/createSharedEntitiesImports';
import attReportConfig from './entity-modules/att-report.config';
@@ -17,79 +17,79 @@ import { registerEntityNameMap } from '@shared/entities/configs/import-file.conf
import { ReportMonth } from './db/entities/ReportMonth.entity';
import teacherReportStatusConfig from './entity-modules/teacher-report-status.config';
import studentPercentReportConfig from './entity-modules/student-percent-report.config';
-import { AttReportAndGrade } from "./db/view-entities/AttReportAndGrade.entity";
-import { StudentGlobalReport } from "./db/view-entities/StudentGlobalReport.entity";
-import studentByYearConfig from "./entity-modules/student-by-year.config";
-import teacherSalaryReportConfig from "./entity-modules/teacher-salary-report.config";
-import attReportWithReportMonthConfig from "./entity-modules/att-report-with-report-month.config";
-import { KnownAbsenceWithReportMonth } from "./db/view-entities/KnownAbsenceWithReportMonth.entity";
-import { GradeName } from "./db/entities/GradeName.entity";
-import { AttGradeEffect } from "./db/entities/AttGradeEffect";
-import teacherGradeReportStatusConfig from "./entity-modules/teacher-grade-report-status.config";
-import { GradeEffectByUser } from "src/db/view-entities/GradeEffectByUser.entity";
-import { AbsCountEffectByUser } from "src/db/view-entities/AbsCountEffectByUser.entity";
-import { LessonKlassName } from "./db/view-entities/LessonKlassName.entity";
-import { StudentSpeciality } from "./db/view-entities/StudentSpeciality.entity";
-import { AttendanceName } from "./db/entities/AttendanceName.entity";
-import reportGroupConfig from "./entity-modules/report-group.config";
-import reportGroupSessionConfig from "./entity-modules/report-group-session.config";
+import { AttReportAndGrade } from './db/view-entities/AttReportAndGrade.entity';
+import { StudentGlobalReport } from './db/view-entities/StudentGlobalReport.entity';
+import studentByYearConfig from './entity-modules/student-by-year.config';
+import teacherSalaryReportConfig from './entity-modules/teacher-salary-report.config';
+import attReportWithReportMonthConfig from './entity-modules/att-report-with-report-month.config';
+import { KnownAbsenceWithReportMonth } from './db/view-entities/KnownAbsenceWithReportMonth.entity';
+import { GradeName } from './db/entities/GradeName.entity';
+import { AttGradeEffect } from './db/entities/AttGradeEffect';
+import teacherGradeReportStatusConfig from './entity-modules/teacher-grade-report-status.config';
+import { GradeEffectByUser } from 'src/db/view-entities/GradeEffectByUser.entity';
+import { AbsCountEffectByUser } from 'src/db/view-entities/AbsCountEffectByUser.entity';
+import { LessonKlassName } from './db/view-entities/LessonKlassName.entity';
+import { StudentSpeciality } from './db/view-entities/StudentSpeciality.entity';
+import { AttendanceName } from './db/entities/AttendanceName.entity';
+import reportGroupConfig from './entity-modules/report-group.config';
+import reportGroupSessionConfig from './entity-modules/report-group-session.config';
import transportationConfig from './entity-modules/transportation.config';
-import absenceTypeConfig from "./entity-modules/absenceType.config";
-import uploadedFileConfig from "@shared/entities/configs/uploaded-file.config";
-import { Student } from "./db/entities/Student.entity";
-import { Teacher } from "./db/entities/Teacher.entity";
-import userConfig from "@shared/entities/configs/user.config";
+import absenceTypeConfig from './entity-modules/absenceType.config';
+import uploadedFileConfig from '@shared/entities/configs/uploaded-file.config';
+import { Student } from './db/entities/Student.entity';
+import { Teacher } from './db/entities/Teacher.entity';
+import userConfig from '@shared/entities/configs/user.config';
registerEntityNameMap({
- att_report: 'נוכחות',
- grade: 'ציונים',
- klass: 'כיתות',
- klass_type: 'שיוך כיתות',
- known_absence: 'חיסורים מאושרים',
- lesson: 'שיעורים',
- student_klass: 'שיוך תלמידות לכיתות',
- student: 'תלמידות',
- teacher: 'מורות',
- uploaded_file: 'קבצים שהועלו',
+ att_report: 'נוכחות',
+ grade: 'ציונים',
+ klass: 'כיתות',
+ klass_type: 'שיוך כיתות',
+ known_absence: 'חיסורים מאושרים',
+ lesson: 'שיעורים',
+ student_klass: 'שיוך תלמידות לכיתות',
+ student: 'תלמידות',
+ teacher: 'מורות',
+ uploaded_file: 'קבצים שהועלו',
});
@Module({
- imports: [
- ...createSharedEntitiesImports(userConfig),
- BaseEntityModule.register(attReportConfig),
- BaseEntityModule.register(attReportWithReportMonthConfig),
- BaseEntityModule.register(gradeConfig),
- BaseEntityModule.register(klassConfig),
- BaseEntityModule.register(klassTypeConfig),
- BaseEntityModule.register(knownAbsenceConfig),
- BaseEntityModule.register(lessonConfig),
- BaseEntityModule.register(studentKlassConfig),
- BaseEntityModule.register(studentConfig),
- BaseEntityModule.register(teacherConfig),
- BaseEntityModule.register(studentKlassReportConfig),
- BaseEntityModule.register({ entity: StudentBaseKlass }),
- BaseEntityModule.register({ entity: StudentSpeciality }),
- BaseEntityModule.register(createAuditLogConfig({ student: Student, teacher: Teacher })),
- BaseEntityModule.register(reportGroupConfig),
- BaseEntityModule.register(reportGroupSessionConfig),
- BaseEntityModule.register({ entity: ReportMonth }),
- BaseEntityModule.register(teacherReportStatusConfig),
- BaseEntityModule.register(teacherGradeReportStatusConfig),
- BaseEntityModule.register(studentPercentReportConfig),
- BaseEntityModule.register({ entity: AttReportAndGrade }),
- BaseEntityModule.register({ entity: StudentGlobalReport }),
- BaseEntityModule.register(studentByYearConfig),
- BaseEntityModule.register(teacherSalaryReportConfig),
- BaseEntityModule.register({ entity: KnownAbsenceWithReportMonth }),
- BaseEntityModule.register({ entity: GradeName }),
- BaseEntityModule.register({ entity: AttendanceName }),
- BaseEntityModule.register({ entity: AttGradeEffect }),
- BaseEntityModule.register({ entity: GradeEffectByUser }),
- BaseEntityModule.register({ entity: AbsCountEffectByUser }),
- BaseEntityModule.register({ entity: LessonKlassName }),
- BaseEntityModule.register(transportationConfig),
- BaseEntityModule.register(absenceTypeConfig),
- BaseEntityModule.register(uploadedFileConfig)
- ]
+ imports: [
+ ...createSharedEntitiesImports(userConfig),
+ BaseEntityModule.register(attReportConfig),
+ BaseEntityModule.register(attReportWithReportMonthConfig),
+ BaseEntityModule.register(gradeConfig),
+ BaseEntityModule.register(klassConfig),
+ BaseEntityModule.register(klassTypeConfig),
+ BaseEntityModule.register(knownAbsenceConfig),
+ BaseEntityModule.register(lessonConfig),
+ BaseEntityModule.register(studentKlassConfig),
+ BaseEntityModule.register(studentConfig),
+ BaseEntityModule.register(teacherConfig),
+ BaseEntityModule.register(studentKlassReportConfig),
+ BaseEntityModule.register({ entity: StudentBaseKlass }),
+ BaseEntityModule.register({ entity: StudentSpeciality }),
+ BaseEntityModule.register(createAuditLogConfig({ student: Student, teacher: Teacher })),
+ BaseEntityModule.register(reportGroupConfig),
+ BaseEntityModule.register(reportGroupSessionConfig),
+ BaseEntityModule.register({ entity: ReportMonth }),
+ BaseEntityModule.register(teacherReportStatusConfig),
+ BaseEntityModule.register(teacherGradeReportStatusConfig),
+ BaseEntityModule.register(studentPercentReportConfig),
+ BaseEntityModule.register({ entity: AttReportAndGrade }),
+ BaseEntityModule.register({ entity: StudentGlobalReport }),
+ BaseEntityModule.register(studentByYearConfig),
+ BaseEntityModule.register(teacherSalaryReportConfig),
+ BaseEntityModule.register({ entity: KnownAbsenceWithReportMonth }),
+ BaseEntityModule.register({ entity: GradeName }),
+ BaseEntityModule.register({ entity: AttendanceName }),
+ BaseEntityModule.register({ entity: AttGradeEffect }),
+ BaseEntityModule.register({ entity: GradeEffectByUser }),
+ BaseEntityModule.register({ entity: AbsCountEffectByUser }),
+ BaseEntityModule.register({ entity: LessonKlassName }),
+ BaseEntityModule.register(transportationConfig),
+ BaseEntityModule.register(absenceTypeConfig),
+ BaseEntityModule.register(uploadedFileConfig),
+ ],
})
-export class EntitiesModule { }
+export class EntitiesModule {}
diff --git a/server/src/entity-modules/__tests__/att-report-with-report-month.config.spec.ts b/server/src/entity-modules/__tests__/att-report-with-report-month.config.spec.ts
index 1b2df9f8..f8a9b947 100644
--- a/server/src/entity-modules/__tests__/att-report-with-report-month.config.spec.ts
+++ b/server/src/entity-modules/__tests__/att-report-with-report-month.config.spec.ts
@@ -9,102 +9,117 @@ const mockBaseCreateMany = jest.fn().mockResolvedValue([{ id: 1 }]);
const mockBaseConstructor = jest.fn();
jest.mock('@shared/base-entity/base-entity.service', () => {
- class MockBaseEntityService {
- dataSource: any;
- constructor(public repo: any, public mailSendService: any) {
- mockBaseConstructor(repo, mailSendService);
- }
- async createOne(req: any, dto: any) { return mockBaseCreateOne(req, dto); }
- async createMany(req: any, dto: any) { return mockBaseCreateMany(req, dto); }
- async updateOne(req: any, dto: any) { return { id: 1 }; }
- async deleteOne(req: any) { return { id: 1 }; }
- async getOne(req: any) { return { id: 1 }; }
- async doAction(req: any, body: any) { return 'success'; }
+ class MockBaseEntityService {
+ dataSource: any;
+ constructor(
+ public repo: any,
+ public mailSendService: any,
+ ) {
+ mockBaseConstructor(repo, mailSendService);
}
- return {
- BaseEntityService: MockBaseEntityService
- };
+ async createOne(req: any, dto: any) {
+ return mockBaseCreateOne(req, dto);
+ }
+ async createMany(req: any, dto: any) {
+ return mockBaseCreateMany(req, dto);
+ }
+ async updateOne(req: any, dto: any) {
+ return { id: 1 };
+ }
+ async deleteOne(req: any) {
+ return { id: 1 };
+ }
+ async getOne(req: any) {
+ return { id: 1 };
+ }
+ async doAction(req: any, body: any) {
+ return 'success';
+ }
+ }
+ return {
+ BaseEntityService: MockBaseEntityService,
+ };
});
describe('att-report-with-report-month.config', () => {
- describe('getConfig', () => {
- it('should return config with proper entity and query settings', () => {
- expect(config.entity).toBe(AttReportWithReportMonth);
- expect(config.query).toBeDefined();
- expect(config.query.join).toEqual({
- studentBaseKlass: { eager: true },
- student: { eager: false },
- teacher: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- 'klass.klassType': { eager: false },
- reportMonth: { eager: false },
- reportGroupSession: { eager: false }
- });
- });
+ describe('getConfig', () => {
+ it('should return config with proper entity and query settings', () => {
+ expect(config.entity).toBe(AttReportWithReportMonth);
+ expect(config.query).toBeDefined();
+ expect(config.query.join).toEqual({
+ studentBaseKlass: { eager: true },
+ student: { eager: false },
+ teacher: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ 'klass.klassType': { eager: false },
+ reportMonth: { eager: false },
+ reportGroupSession: { eager: false },
+ });
});
+ });
+
+ describe('Service', () => {
+ let service: any;
+ let mockDataSource: any;
+ let mockRepo: any;
+
+ beforeEach(() => {
+ mockRepo = {
+ findBy: jest.fn(),
+ insert: jest.fn(),
+ save: jest.fn(),
+ };
+ mockDataSource = {
+ getRepository: jest.fn().mockReturnValue(mockRepo),
+ };
+
+ const ServiceClass = config.service as any;
+ // First arg is repo, second is mailService
+ service = new ServiceClass(mockRepo, {});
+ // Manually inject dataSource as if NestJS did it
+ service.dataSource = mockDataSource;
+
+ // Mock getOne on the service instance itself since it calls this.getOne()
+ service.getOne = jest.fn().mockResolvedValue({ id: 1, reportDate: '2022-01-01' });
+
+ mockBaseCreateOne.mockClear();
+ mockBaseCreateMany.mockClear();
+ mockBaseConstructor.mockClear();
+ (BaseEntityService as unknown as jest.Mock).mockClear?.();
+ });
+
+ it('createOne should delegate to AttReport service', async () => {
+ const req = { options: {}, parsed: {} } as any;
+ const dto = { reportDate: '2022-01-01' };
+
+ await service.createOne(req, dto);
+
+ // Verify BaseEntityService was instantiated with AttReport repository
+ // Note: The first call is in constructor of 'service'.
+ // The second call is inside 'createOne'.
+ // service = new ServiceClass calls super(), which calls BaseEntityService constructor.
+ // THEN service.createOne() calls new BaseEntityService().
+
+ // Expect BaseEntityService to be called with mockRepo (via this.dataSource.getRepository(AttReport))
+ expect(mockBaseConstructor).toHaveBeenLastCalledWith(mockRepo, expect.anything());
+ expect(mockDataSource.getRepository).toHaveBeenCalledWith(AttReport);
+
+ // Verify createOne was called on the delegate
+ expect(mockBaseCreateOne).toHaveBeenCalledWith(req, dto);
+
+ // Verify getOne was called to return the view entity
+ expect(service.getOne).toHaveBeenCalledWith(req);
+ });
+
+ it('createMany should delegate to AttReport service', async () => {
+ const req = { options: {}, parsed: {} } as any;
+ const dto = { bulk: [] };
+
+ await service.createMany(req, dto);
- describe('Service', () => {
- let service: any;
- let mockDataSource: any;
- let mockRepo: any;
-
- beforeEach(() => {
- mockRepo = {
- findBy: jest.fn(),
- insert: jest.fn(),
- save: jest.fn(),
- };
- mockDataSource = {
- getRepository: jest.fn().mockReturnValue(mockRepo),
- };
-
- const ServiceClass = config.service as any;
- // First arg is repo, second is mailService
- service = new ServiceClass(mockRepo, {});
- // Manually inject dataSource as if NestJS did it
- service.dataSource = mockDataSource;
-
- // Mock getOne on the service instance itself since it calls this.getOne()
- service.getOne = jest.fn().mockResolvedValue({ id: 1, reportDate: '2022-01-01' });
-
- mockBaseCreateOne.mockClear();
- mockBaseCreateMany.mockClear();
- mockBaseConstructor.mockClear();
- (BaseEntityService as unknown as jest.Mock).mockClear?.();
- });
-
- it('createOne should delegate to AttReport service', async () => {
- const req = { options: {}, parsed: {} } as any;
- const dto = { reportDate: '2022-01-01' };
-
- await service.createOne(req, dto);
-
- // Verify BaseEntityService was instantiated with AttReport repository
- // Note: The first call is in constructor of 'service'.
- // The second call is inside 'createOne'.
- // service = new ServiceClass calls super(), which calls BaseEntityService constructor.
- // THEN service.createOne() calls new BaseEntityService().
-
- // Expect BaseEntityService to be called with mockRepo (via this.dataSource.getRepository(AttReport))
- expect(mockBaseConstructor).toHaveBeenLastCalledWith(mockRepo, expect.anything());
- expect(mockDataSource.getRepository).toHaveBeenCalledWith(AttReport);
-
- // Verify createOne was called on the delegate
- expect(mockBaseCreateOne).toHaveBeenCalledWith(req, dto);
-
- // Verify getOne was called to return the view entity
- expect(service.getOne).toHaveBeenCalledWith(req);
- });
-
- it('createMany should delegate to AttReport service', async () => {
- const req = { options: {}, parsed: {} } as any;
- const dto = { bulk: [] };
-
- await service.createMany(req, dto);
-
- expect(mockDataSource.getRepository).toHaveBeenCalledWith(AttReport);
- expect(mockBaseCreateMany).toHaveBeenCalledWith(req, dto);
- });
+ expect(mockDataSource.getRepository).toHaveBeenCalledWith(AttReport);
+ expect(mockBaseCreateMany).toHaveBeenCalledWith(req, dto);
});
+ });
});
diff --git a/server/src/entity-modules/__tests__/att-report.config.spec.ts b/server/src/entity-modules/__tests__/att-report.config.spec.ts
index a5746ae2..ecadd8aa 100644
--- a/server/src/entity-modules/__tests__/att-report.config.spec.ts
+++ b/server/src/entity-modules/__tests__/att-report.config.spec.ts
@@ -23,10 +23,10 @@ describe('att-report.config', () => {
// Test processReqForExport
const mockReq = {
options: {
- query: { join: {} }
- }
+ query: { join: {} },
+ },
};
- const mockInnerFunc = jest.fn(req => req);
+ const mockInnerFunc = jest.fn((req) => req);
config.exporter.processReqForExport(mockReq as any, mockInnerFunc);
@@ -50,17 +50,22 @@ describe('att-report.config', () => {
options: { query: { join: {} } },
auth: {
permissions: {
- lessonSignature: true
- }
- }
+ lessonSignature: true,
+ },
+ },
};
config.exporter.processReqForExport(mockReqWithPermissions as any, mockInnerFunc);
expect((mockReqWithPermissions.options.query.join as any).reportGroupSession).toEqual({ eager: true });
- const headersWithPermission = config.exporter.getExportHeaders(['id', 'name', 'absCount'], mockReqWithPermissions as any);
+ const headersWithPermission = config.exporter.getExportHeaders(
+ ['id', 'name', 'absCount'],
+ mockReqWithPermissions as any,
+ );
// Verify that the topic header exists when permission present
- expect(headersWithPermission.find(h => typeof h === 'object' && h.value === 'reportGroupSession.topic')).toBeDefined();
+ expect(
+ headersWithPermission.find((h) => typeof h === 'object' && h.value === 'reportGroupSession.topic'),
+ ).toBeDefined();
});
it('should have proper import configuration', () => {
@@ -77,11 +82,11 @@ describe('att-report.config', () => {
it('should calculate absCount with lateCount and default lateValue', () => {
const report = {
absCount: 2,
- lateCount: 3
+ lateCount: 3,
} as AttReport & { lateCount: number };
const user = {
- additionalData: {}
+ additionalData: {},
} as User;
calcAttLateCount(report, user);
@@ -94,11 +99,11 @@ describe('att-report.config', () => {
it('should use custom lateValue from user data', () => {
const report = {
absCount: 2,
- lateCount: 2
+ lateCount: 2,
} as AttReport & { lateCount: number };
const user = {
- additionalData: { lateValue: 0.5 }
+ additionalData: { lateValue: 0.5 },
} as User;
calcAttLateCount(report, user);
@@ -110,11 +115,11 @@ describe('att-report.config', () => {
it('should handle NaN values', () => {
const report = {
absCount: NaN,
- lateCount: NaN
+ lateCount: NaN,
} as AttReport & { lateCount: number };
const user = {
- additionalData: { lateValue: 0.5 }
+ additionalData: { lateValue: 0.5 },
} as User;
calcAttLateCount(report, user);
@@ -122,4 +127,4 @@ describe('att-report.config', () => {
expect(report.absCount).toBe(0);
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/grade.config.spec.ts b/server/src/entity-modules/__tests__/grade.config.spec.ts
index 93e6059f..29c29a38 100644
--- a/server/src/entity-modules/__tests__/grade.config.spec.ts
+++ b/server/src/entity-modules/__tests__/grade.config.spec.ts
@@ -10,11 +10,11 @@ import * as reportUtil from '@shared/utils/report/report.util';
import * as authUtil from '@shared/auth/auth.util';
jest.mock('@shared/utils/report/report.util', () => ({
- generateCommonFileResponse: jest.fn()
+ generateCommonFileResponse: jest.fn(),
}));
jest.mock('@shared/auth/auth.util', () => ({
- getUserIdFromUser: jest.fn()
+ getUserIdFromUser: jest.fn(),
}));
describe('grade.config', () => {
@@ -34,7 +34,7 @@ describe('grade.config', () => {
expect(gradeConfig.entity).toBe(Grade);
expect(gradeConfig.service).toBeDefined();
expect(gradeConfig.query).toBeDefined();
-
+
// Validate complete query configuration
const queryConfig = gradeConfig.query;
expect(queryConfig).toBeDefined();
@@ -49,7 +49,7 @@ describe('grade.config', () => {
// Validate all required relationships are present
const requiredRelations = ['studentBaseKlass', 'student', 'teacher', 'lesson', 'klass'];
- requiredRelations.forEach(relation => {
+ requiredRelations.forEach((relation) => {
expect(queryConfig.join[relation]).toBeDefined();
});
});
@@ -110,15 +110,15 @@ describe('grade.config', () => {
columns: [{ propertyName: 'id' }],
relations: [],
connection: { options: { type: 'postgres' } },
- targetName: 'Grade'
+ targetName: 'Grade',
},
manager: {
connection: {
createQueryRunner: jest.fn().mockReturnValue({
- manager: {}
- })
- }
- }
+ manager: {},
+ }),
+ },
+ },
};
dataSource = {
@@ -128,8 +128,8 @@ describe('grade.config', () => {
startTransaction: jest.fn(),
commitTransaction: jest.fn(),
rollbackTransaction: jest.fn(),
- release: jest.fn()
- })
+ release: jest.fn(),
+ }),
} as any;
module = await Test.createTestingModule({
@@ -137,21 +137,21 @@ describe('grade.config', () => {
gradeConfig.service,
{
provide: ENTITY_REPOSITORY,
- useValue: repository
+ useValue: repository,
},
{
provide: ENTITY_EXPORTER,
- useValue: gradeConfig.exporter
+ useValue: gradeConfig.exporter,
},
{
provide: MailSendService,
- useValue: { send: jest.fn() }
+ useValue: { send: jest.fn() },
},
{
provide: DataSource,
- useValue: dataSource
- }
- ]
+ useValue: dataSource,
+ },
+ ],
}).compile();
service = module.get>(gradeConfig.service);
@@ -173,11 +173,11 @@ describe('grade.config', () => {
cache: 0,
extra: {
action: 'michlolPopulatedFile',
- fileName: 'test.xlsx'
- }
+ fileName: 'test.xlsx',
+ },
},
options: {},
- auth: { id: 123 }
+ auth: { id: 123 },
} as CrudRequest;
// Cast service to any to access implementation details in tests
@@ -205,9 +205,9 @@ describe('grade.config', () => {
{
userId: 123,
michlolFileName: 'test.xlsx',
- michlolFileData: body.data
+ michlolFileData: body.data,
},
- dataSource
+ dataSource,
);
expect(result).toEqual({ success: true });
@@ -219,7 +219,7 @@ describe('grade.config', () => {
jest.spyOn(BaseEntityService.prototype, 'doAction').mockResolvedValue(mockResponse);
const result = await service.doAction(mockReq, {});
-
+
expect(result).toBe(mockResponse);
});
@@ -227,9 +227,7 @@ describe('grade.config', () => {
const gradeService = service as any;
expect(gradeService.reportsDict).toBeDefined();
expect(gradeService.reportsDict.michlolPopulatedFile).toBeDefined();
- expect(gradeService.reportsDict.michlolPopulatedFile).toEqual(
- expect.any(Object)
- );
+ expect(gradeService.reportsDict.michlolPopulatedFile).toEqual(expect.any(Object));
});
it('should initialize with correct default values', () => {
@@ -239,8 +237,8 @@ describe('grade.config', () => {
expect(gradeService.reportsDict.michlolPopulatedFile).toEqual(
expect.objectContaining({
getReportData: expect.any(Function),
- getReportName: expect.any(Function)
- })
+ getReportName: expect.any(Function),
+ }),
);
});
@@ -248,13 +246,14 @@ describe('grade.config', () => {
const unknownReportReq = createMockRequest({
parsed: {
...createBaseParsedParams(),
- extra: { action: 'nonexistentReport' }
- }
+ extra: { action: 'nonexistentReport' },
+ },
});
-
- const mockSuperDoAction = jest.spyOn(BaseEntityService.prototype, 'doAction')
+
+ const mockSuperDoAction = jest
+ .spyOn(BaseEntityService.prototype, 'doAction')
.mockResolvedValue({ fallback: true });
-
+
const result = await service.doAction(unknownReportReq, {});
expect(result).toEqual({ fallback: true });
expect(mockSuperDoAction).toHaveBeenCalledWith(unknownReportReq, {});
@@ -267,9 +266,9 @@ describe('grade.config', () => {
...createBaseParsedParams(),
extra: {
action: 'michlolPopulatedFile',
- fileName: 'test.xlsx'
- }
- }
+ fileName: 'test.xlsx',
+ },
+ },
});
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(123);
@@ -279,15 +278,15 @@ describe('grade.config', () => {
const expectedGenerator = gradeService.reportsDict.michlolPopulatedFile;
const result = await service.doAction(validReq, testData);
-
+
expect(reportUtil.generateCommonFileResponse).toHaveBeenCalledWith(
expectedGenerator,
{
userId: 123,
michlolFileName: 'test.xlsx',
- michlolFileData: testData.data
+ michlolFileData: testData.data,
},
- dataSource
+ dataSource,
);
expect(result).toEqual({ success: true });
@@ -310,19 +309,20 @@ describe('grade.config', () => {
includeDeleted: 0,
extra: {
action: 'michlolPopulatedFile',
- fileName: 'test.xlsx'
- }
+ fileName: 'test.xlsx',
+ },
});
- const createMockRequest = (overrides: Partial = {}): CrudRequest => ({
- parsed: {
- ...createBaseParsedParams(),
- ...(overrides.parsed || {})
- },
- options: {},
- auth: { id: 123 },
- ...overrides
- } as CrudRequest);
+ const createMockRequest = (overrides: Partial = {}): CrudRequest =>
+ ({
+ parsed: {
+ ...createBaseParsedParams(),
+ ...(overrides.parsed || {}),
+ },
+ options: {},
+ auth: { id: 123 },
+ ...overrides,
+ }) as CrudRequest;
describe('error handling', () => {
beforeEach(() => {
@@ -334,32 +334,24 @@ describe('grade.config', () => {
parsed: {
...createBaseParsedParams(),
extra: {
- action: 'michlolPopulatedFile'
+ action: 'michlolPopulatedFile',
// fileName missing
- }
- }
+ },
+ },
});
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(123);
- (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(
- new Error('fileName is required')
- );
+ (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(new Error('fileName is required'));
- await expect(service.doAction(reqWithoutFileName, { data: {} }))
- .rejects
- .toThrow('fileName is required');
+ await expect(service.doAction(reqWithoutFileName, { data: {} })).rejects.toThrow('fileName is required');
});
it('should handle missing data in body', async () => {
const emptyBody = {};
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(123);
- (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(
- new Error('data is required')
- );
+ (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(new Error('data is required'));
- await expect(service.doAction(mockReq, emptyBody))
- .rejects
- .toThrow('data is required');
+ await expect(service.doAction(mockReq, emptyBody)).rejects.toThrow('data is required');
});
it('should handle file generation failure', async () => {
@@ -367,9 +359,7 @@ describe('grade.config', () => {
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(123);
(reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(error);
- await expect(service.doAction(mockReq, { data: {} }))
- .rejects
- .toThrow('File generation failed');
+ await expect(service.doAction(mockReq, { data: {} })).rejects.toThrow('File generation failed');
});
it('should handle invalid user auth', async () => {
@@ -378,34 +368,28 @@ describe('grade.config', () => {
throw authError;
});
- await expect(service.doAction(mockReq, { data: {} }))
- .rejects
- .toThrow('Invalid auth');
+ await expect(service.doAction(mockReq, { data: {} })).rejects.toThrow('Invalid auth');
});
it('should handle invalid file data format', async () => {
const invalidData = {
data: {
invalidFormat: true,
- missingRequiredFields: true
- }
+ missingRequiredFields: true,
+ },
};
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(123);
- (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(
- new Error('Invalid file data format')
- );
+ (reportUtil.generateCommonFileResponse as jest.Mock).mockRejectedValue(new Error('Invalid file data format'));
- await expect(service.doAction(mockReq, invalidData))
- .rejects
- .toThrow('Invalid file data format');
+ await expect(service.doAction(mockReq, invalidData)).rejects.toThrow('Invalid file data format');
expect(reportUtil.generateCommonFileResponse).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
- michlolFileData: invalidData.data
+ michlolFileData: invalidData.data,
}),
- expect.any(Object)
+ expect.any(Object),
);
});
});
@@ -423,11 +407,11 @@ describe('grade.config', () => {
startTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
rollbackTransaction: jest.fn().mockResolvedValue(undefined),
- release: jest.fn().mockResolvedValue(undefined)
+ release: jest.fn().mockResolvedValue(undefined),
};
dataSource.createQueryRunner.mockReturnValue(queryRunner);
-
+
// Mock generateCommonFileResponse to trigger actual transaction flow in the service
(reportUtil.generateCommonFileResponse as jest.Mock).mockImplementation(async (generator, params, ds) => {
const runner = ds.createQueryRunner();
@@ -458,9 +442,9 @@ describe('grade.config', () => {
expect.objectContaining({
userId: 123,
michlolFileName: 'test.xlsx',
- michlolFileData: testData.data
+ michlolFileData: testData.data,
}),
- dataSource
+ dataSource,
);
expect(dataSource.createQueryRunner).toHaveBeenCalled();
@@ -485,9 +469,7 @@ describe('grade.config', () => {
}
});
- await expect(service.doAction(mockReq, { data: {} }))
- .rejects
- .toThrow('Transaction failed');
+ await expect(service.doAction(mockReq, { data: {} })).rejects.toThrow('Transaction failed');
expect(queryRunner.connect).toHaveBeenCalled();
expect(queryRunner.startTransaction).toHaveBeenCalled();
@@ -501,4 +483,4 @@ describe('grade.config', () => {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/klass-type.config.spec.ts b/server/src/entity-modules/__tests__/klass-type.config.spec.ts
index 9440d3fe..6cd9dd68 100644
--- a/server/src/entity-modules/__tests__/klass-type.config.spec.ts
+++ b/server/src/entity-modules/__tests__/klass-type.config.spec.ts
@@ -9,11 +9,13 @@ describe('KlassTypeConfig', () => {
it('should return correct export headers', () => {
const fields = ['key', 'name'];
const headers = klassTypeConfig.exporter.getExportHeaders(fields);
-
- expect(headers).toEqual(expect.arrayContaining([
- { value: 'key', label: 'מזהה' },
- { value: 'name', label: 'שם' },
- ]));
+
+ expect(headers).toEqual(
+ expect.arrayContaining([
+ { value: 'key', label: 'מזהה' },
+ { value: 'name', label: 'שם' },
+ ]),
+ );
});
it('should return correct import definition', () => {
@@ -26,9 +28,7 @@ describe('KlassTypeConfig', () => {
// Check the returned definition
expect(result).toEqual({
importFields: mockImportFields,
- specialFields: expect.arrayContaining([
- { cell: { c: 0, r: 1 }, value: 'test' }
- ])
+ specialFields: expect.arrayContaining([{ cell: { c: 0, r: 1 }, value: 'test' }]),
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/klass.config.spec.ts b/server/src/entity-modules/__tests__/klass.config.spec.ts
index 13405a85..798e6f93 100644
--- a/server/src/entity-modules/__tests__/klass.config.spec.ts
+++ b/server/src/entity-modules/__tests__/klass.config.spec.ts
@@ -6,10 +6,12 @@ describe('KlassConfig', () => {
it('should have correct base configuration', () => {
expect(klassConfig.entity).toBe(Klass);
expect(klassConfig.query).toBeDefined();
- expect(klassConfig.query.join).toEqual(expect.objectContaining({
- teacher: { eager: false },
- klassType: { eager: false },
- }));
+ expect(klassConfig.query.join).toEqual(
+ expect.objectContaining({
+ teacher: { eager: false },
+ klassType: { eager: false },
+ }),
+ );
});
it('should have correct exporter configuration', () => {
@@ -27,15 +29,17 @@ describe('KlassConfig', () => {
},
} as CrudRequest;
- const mockInnerFunc = jest.fn(req => req);
+ const mockInnerFunc = jest.fn((req) => req);
const result = klassConfig.exporter.processReqForExport(mockRequest, mockInnerFunc);
expect(mockInnerFunc).toHaveBeenCalledWith(mockRequest);
- expect(mockRequest.options.query.join).toEqual(expect.objectContaining({
- klassType: { eager: true },
- teacher: { eager: true },
- }));
+ expect(mockRequest.options.query.join).toEqual(
+ expect.objectContaining({
+ klassType: { eager: true },
+ teacher: { eager: true },
+ }),
+ );
expect(result).toBe(mockRequest);
});
@@ -43,10 +47,12 @@ describe('KlassConfig', () => {
const fields = ['key', 'name', 'klassType.name', 'teacher.name'];
const headers = klassConfig.exporter.getExportHeaders(fields);
- expect(headers).toEqual(expect.arrayContaining([
- { value: 'key', label: 'מזהה' },
- { value: 'name', label: 'שם' },
- { value: 'teacher.name', label: 'מורה' },
- ]));
+ expect(headers).toEqual(
+ expect.arrayContaining([
+ { value: 'key', label: 'מזהה' },
+ { value: 'name', label: 'שם' },
+ { value: 'teacher.name', label: 'מורה' },
+ ]),
+ );
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/student-by-year.config.spec.ts b/server/src/entity-modules/__tests__/student-by-year.config.spec.ts
index 5c51c2c4..2bc24a22 100644
--- a/server/src/entity-modules/__tests__/student-by-year.config.spec.ts
+++ b/server/src/entity-modules/__tests__/student-by-year.config.spec.ts
@@ -1,5 +1,5 @@
import config, { Utils } from '../student-by-year.config';
-import { StudentByYear } from "src/db/view-entities/StudentByYear.entity";
+import { StudentByYear } from 'src/db/view-entities/StudentByYear.entity';
import { DataSource, EntityMetadata, Repository } from 'typeorm';
import { Test, TestingModule } from '@nestjs/testing';
import { BaseEntityService } from '@shared/base-entity/base-entity.service';
@@ -8,7 +8,7 @@ import { ParsedRequestParams } from '@dataui/crud-request';
import { MailSendService } from '@shared/utils/mail/mail-send.service';
jest.mock('@shared/utils/validation/max-count-by-user-limit.ts', () => ({
- MaxCountByUserLimit: jest.fn().mockImplementation(() => jest.fn())
+ MaxCountByUserLimit: jest.fn().mockImplementation(() => jest.fn()),
}));
interface MockStudent extends StudentByYear {
@@ -35,44 +35,40 @@ describe('StudentByYear Config', () => {
transaction: jest.fn((cb) => cb()),
},
metadata: {
- columns: [
- { propertyName: 'id' },
- { propertyName: 'name' },
- { propertyName: 'userId' }
- ],
+ columns: [{ propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'userId' }],
connection: { options: { type: 'mysql' } },
- targetName: 'TestEntity'
+ targetName: 'TestEntity',
},
createQueryBuilder: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getCount: jest.fn(),
- save: jest.fn().mockImplementation(entity => Promise.resolve(entity))
+ save: jest.fn().mockImplementation((entity) => Promise.resolve(entity)),
} as any;
mockDataSource = {
getRepository: jest.fn().mockReturnValue({
- find: jest.fn().mockResolvedValue([])
- })
+ find: jest.fn().mockResolvedValue([]),
+ }),
};
mockMailService = {
- sendMail: jest.fn().mockResolvedValue(undefined)
+ sendMail: jest.fn().mockResolvedValue(undefined),
};
module = await Test.createTestingModule({
providers: [
{
provide: DataSource,
- useValue: mockDataSource
+ useValue: mockDataSource,
},
{
provide: 'CONFIG',
- useValue: config
+ useValue: config,
},
{
provide: MailSendService,
- useValue: mockMailService
+ useValue: mockMailService,
},
{
provide: config.service,
@@ -80,9 +76,9 @@ describe('StudentByYear Config', () => {
const service = new config.service(mockRepository, mockMailService as MailSendService);
service.dataSource = mockDataSource as DataSource;
return service;
- }
- }
- ]
+ },
+ },
+ ],
}).compile();
service = module.get>(config.service);
@@ -111,7 +107,7 @@ describe('StudentByYear Config', () => {
tz: '123',
klassReferenceIds: ['1'],
klassTypeReferenceIds: ['1'],
- isActive: true
+ isActive: true,
},
{
id: 2,
@@ -121,8 +117,8 @@ describe('StudentByYear Config', () => {
tz: '456',
klassReferenceIds: ['1'],
klassTypeReferenceIds: ['1'],
- isActive: true
- }
+ isActive: true,
+ },
];
const mockAttReports = [
@@ -131,45 +127,41 @@ describe('StudentByYear Config', () => {
lessonReferenceId: 101,
lesson: { name: 'Math' },
absCount: 2,
- howManyLessons: 10
+ howManyLessons: 10,
},
{
studentReferenceId: 2,
lessonReferenceId: 101,
lesson: { name: 'Math' },
absCount: 3,
- howManyLessons: 10
- }
+ howManyLessons: 10,
+ },
];
const mockKnownAbsences = [
{
studentReferenceId: 1,
absnceCount: 1,
- isApproved: true
+ isApproved: true,
},
{
studentReferenceId: 2,
absnceCount: 2,
- isApproved: true
- }
+ isApproved: true,
+ },
];
- (mockDataSource.getRepository as jest.Mock)
- .mockImplementation((entity) => ({
- find: jest.fn()
- .mockImplementation(() => {
- if (entity.name === 'AttReportWithReportMonth') {
- return Promise.resolve(mockAttReports);
- } else if (entity.name === 'KnownAbsenceWithReportMonth') {
- return Promise.resolve(mockKnownAbsences);
- }
- })
- }));
-
- const filter = [
- { field: 'year', value: '2023' }
- ] as ParsedRequestParams['filter'];
+ (mockDataSource.getRepository as jest.Mock).mockImplementation((entity) => ({
+ find: jest.fn().mockImplementation(() => {
+ if (entity.name === 'AttReportWithReportMonth') {
+ return Promise.resolve(mockAttReports);
+ } else if (entity.name === 'KnownAbsenceWithReportMonth') {
+ return Promise.resolve(mockKnownAbsences);
+ }
+ }),
+ }));
+
+ const filter = [{ field: 'year', value: '2023' }] as ParsedRequestParams['filter'];
// Access the protected method through type casting
await (service as any).populatePivotData(
@@ -177,7 +169,7 @@ describe('StudentByYear Config', () => {
mockStudents,
{ isCheckKlassType: false },
filter,
- {}
+ {},
);
// Verify the first student's data
@@ -192,7 +184,7 @@ describe('StudentByYear Config', () => {
expect(mockStudents[0].headers).toBeDefined();
expect(mockStudents[0].headers).toContainEqual({
value: '101',
- label: 'Math'
+ label: 'Math',
});
});
});
@@ -237,4 +229,4 @@ describe('StudentByYear Config', () => {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/student-klass.config.spec.ts b/server/src/entity-modules/__tests__/student-klass.config.spec.ts
index f8f42aa8..6470b76b 100644
--- a/server/src/entity-modules/__tests__/student-klass.config.spec.ts
+++ b/server/src/entity-modules/__tests__/student-klass.config.spec.ts
@@ -13,40 +13,41 @@ jest.mock('@shared/utils/report/bulk-to-pdf.generator');
jest.mock('src/reports/reportGenerator');
jest.mock('@shared/base-entity/base-entity.service');
-const createMockCrudRequest = (extra: any): CrudRequest => ({
- parsed: {
- fields: [],
- paramsFilter: [],
- authPersist: undefined,
- classTransformOptions: undefined,
- search: undefined,
- filter: [],
- or: [],
- join: [],
- sort: [],
- limit: undefined,
- offset: undefined,
- page: undefined,
- cache: undefined,
- includeDeleted: undefined,
- extra,
- },
- options: {
- query: {
- join: {},
+const createMockCrudRequest = (extra: any): CrudRequest =>
+ ({
+ parsed: {
+ fields: [],
+ paramsFilter: [],
+ authPersist: undefined,
+ classTransformOptions: undefined,
+ search: undefined,
+ filter: [],
+ or: [],
+ join: [],
+ sort: [],
+ limit: undefined,
+ offset: undefined,
+ page: undefined,
+ cache: undefined,
+ includeDeleted: undefined,
+ extra,
},
- routes: {
- getManyBase: { interceptors: [], decorators: [] },
- getOneBase: { interceptors: [], decorators: [] },
- createOneBase: { interceptors: [], decorators: [] },
- createManyBase: { interceptors: [], decorators: [] },
- updateOneBase: { interceptors: [], decorators: [] },
- replaceOneBase: { interceptors: [], decorators: [] },
- deleteOneBase: { interceptors: [], decorators: [] },
+ options: {
+ query: {
+ join: {},
+ },
+ routes: {
+ getManyBase: { interceptors: [], decorators: [] },
+ getOneBase: { interceptors: [], decorators: [] },
+ createOneBase: { interceptors: [], decorators: [] },
+ createManyBase: { interceptors: [], decorators: [] },
+ updateOneBase: { interceptors: [], decorators: [] },
+ replaceOneBase: { interceptors: [], decorators: [] },
+ deleteOneBase: { interceptors: [], decorators: [] },
+ },
+ params: {},
},
- params: {},
- },
-}) as CrudRequest;
+ }) as CrudRequest;
const createMockStudentKlass = (data: Partial = {}): StudentKlass => ({
id: 1,
@@ -137,7 +138,7 @@ describe('StudentKlassConfig', () => {
// Mock save method to handle both single entities and arrays
mockRepository.save = jest.fn().mockImplementation((entity: any) => {
if (Array.isArray(entity)) {
- return Promise.resolve(entity.map(e => ({ ...e })));
+ return Promise.resolve(entity.map((e) => ({ ...e })));
}
return Promise.resolve({ ...entity });
});
@@ -157,9 +158,11 @@ describe('StudentKlassConfig', () => {
params: {},
};
- mockBaseEntityGetReportData = jest.spyOn(BaseEntityService.prototype, 'getReportData')
+ mockBaseEntityGetReportData = jest
+ .spyOn(BaseEntityService.prototype, 'getReportData')
.mockImplementation(() => Promise.resolve(mockReportData));
- mockBaseEntityDoAction = jest.spyOn(BaseEntityService.prototype, 'doAction')
+ mockBaseEntityDoAction = jest
+ .spyOn(BaseEntityService.prototype, 'doAction')
.mockImplementation(() => Promise.resolve({}));
const Service = config.service;
@@ -254,4 +257,4 @@ describe('StudentKlassConfig', () => {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/student-percent-report.config.spec.ts b/server/src/entity-modules/__tests__/student-percent-report.config.spec.ts
index 2e788200..0f6708ad 100644
--- a/server/src/entity-modules/__tests__/student-percent-report.config.spec.ts
+++ b/server/src/entity-modules/__tests__/student-percent-report.config.spec.ts
@@ -19,19 +19,15 @@ describe('StudentPercentReportConfig', () => {
transaction: jest.fn((cb) => cb()),
},
metadata: {
- columns: [
- { propertyName: 'id' },
- { propertyName: 'name' },
- { propertyName: 'userId' }
- ],
+ columns: [{ propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'userId' }],
connection: { options: { type: 'mysql' } },
- targetName: 'TestEntity'
+ targetName: 'TestEntity',
},
createQueryBuilder: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getCount: jest.fn(),
- save: jest.fn().mockImplementation(entity => Promise.resolve(entity))
+ save: jest.fn().mockImplementation((entity) => Promise.resolve(entity)),
} as any;
mockRepos = {
@@ -154,63 +150,75 @@ describe('StudentPercentReportConfig', () => {
headers?: any[];
}
- const mockData: ExtendedStudentPercentReport[] = [{
- id: '1_1_1_1_1_2023',
- studentReferenceId: 1,
- teacherReferenceId: 1,
- klassReferenceId: 1,
- lessonReferenceId: 1,
- userId: 1,
- year: 2023,
- absCount: 5,
- lessonsCount: 10,
- absPercents: 0.2,
- attPercents: 0.8,
- gradeAvg: 85,
- student: null,
- teacher: null,
- lesson: null,
- klass: null,
- studentBaseKlass: null,
- }];
+ const mockData: ExtendedStudentPercentReport[] = [
+ {
+ id: '1_1_1_1_1_2023',
+ studentReferenceId: 1,
+ teacherReferenceId: 1,
+ klassReferenceId: 1,
+ lessonReferenceId: 1,
+ userId: 1,
+ year: 2023,
+ absCount: 5,
+ lessonsCount: 10,
+ absPercents: 0.2,
+ attPercents: 0.8,
+ gradeAvg: 85,
+ student: null,
+ teacher: null,
+ lesson: null,
+ klass: null,
+ studentBaseKlass: null,
+ },
+ ];
- const mockReportData = [{
- studentReferenceId: 1,
- teacherReferenceId: 1,
- klassReferenceId: 1,
- lessonReferenceId: 1,
- userId: 1,
- year: 2023,
- type: 'grade',
- grade: 3,
- estimation: 'Good',
- comments: 'Nice work',
- reportDate: new Date(),
- }];
+ const mockReportData = [
+ {
+ studentReferenceId: 1,
+ teacherReferenceId: 1,
+ klassReferenceId: 1,
+ lessonReferenceId: 1,
+ userId: 1,
+ year: 2023,
+ type: 'grade',
+ grade: 3,
+ estimation: 'Good',
+ comments: 'Nice work',
+ reportDate: new Date(),
+ },
+ ];
- const mockAbsences = [{
- studentReferenceId: 1,
- klassReferenceId: 1,
- lessonReferenceId: 1,
- userId: 1,
- year: 2023,
- }];
+ const mockAbsences = [
+ {
+ studentReferenceId: 1,
+ klassReferenceId: 1,
+ lessonReferenceId: 1,
+ userId: 1,
+ year: 2023,
+ },
+ ];
- const mockLessons = [{
- id: '1',
- howManyLessons: 10,
- }];
+ const mockLessons = [
+ {
+ id: '1',
+ howManyLessons: 10,
+ },
+ ];
- const mockGradeNames = [{
- userId: 1,
- key: 'A',
- value: '90-100',
- }];
+ const mockGradeNames = [
+ {
+ userId: 1,
+ key: 'A',
+ value: '90-100',
+ },
+ ];
- const mockEffects = [{
- id: '1_0',
- effect: -5,
- }];
+ const mockEffects = [
+ {
+ id: '1_0',
+ effect: -5,
+ },
+ ];
beforeEach(() => {
mockRepos.AttReportAndGrade.find.mockResolvedValue(mockReportData);
@@ -260,4 +268,4 @@ describe('StudentPercentReportConfig', () => {
expect(mockData[0].gradeAvg).toBeDefined();
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/student.config.spec.ts b/server/src/entity-modules/__tests__/student.config.spec.ts
index 511daa3c..5d16c4c9 100644
--- a/server/src/entity-modules/__tests__/student.config.spec.ts
+++ b/server/src/entity-modules/__tests__/student.config.spec.ts
@@ -22,7 +22,7 @@ class MockReportGenerator extends BaseReportGenerator {
constructor() {
super(
(data) => 'test-report',
- async (params) => params
+ async (params) => params,
);
}
@@ -48,7 +48,7 @@ describe('StudentConfig', () => {
{ value: 'comment', label: 'הערה' },
{ value: 'phone', label: 'טלפון' },
{ value: 'year', label: 'כתובת' },
- { value: expect.any(Function), label: 'פעיל' }
+ { value: expect.any(Function), label: 'פעיל' },
]);
});
@@ -71,24 +71,24 @@ describe('StudentConfig', () => {
connection: {
options: {
type: 'mysql',
- name: 'default'
- }
- }
+ name: 'default',
+ },
+ },
},
metadata: {
columns: [],
relations: [],
connection: {
options: {
- type: 'mysql'
- }
- }
- }
+ type: 'mysql',
+ },
+ },
+ },
} as any;
// Create mock mail service
mockMailService = {
- sendMail: jest.fn()
+ sendMail: jest.fn(),
} as any;
// Mock DataSource
@@ -99,7 +99,7 @@ describe('StudentConfig', () => {
commitTransaction: jest.fn(),
rollbackTransaction: jest.fn(),
release: jest.fn(),
- })
+ }),
};
// Create service instance with mocks
@@ -110,12 +110,12 @@ describe('StudentConfig', () => {
// Mock the injected properties
Object.defineProperty(service, 'dataSource', {
value: mockDataSource,
- writable: true
+ writable: true,
});
Object.defineProperty(service, 'exportDefinition', {
value: studentConfig.exporter,
- writable: true
+ writable: true,
});
});
@@ -142,8 +142,8 @@ describe('StudentConfig', () => {
limit: 10,
offset: 0,
page: 1,
- cache: 0
- }
+ cache: 0,
+ },
};
beforeEach(() => {
@@ -154,7 +154,7 @@ describe('StudentConfig', () => {
const mockGenerator = new MockReportGenerator();
const mockReportData: CommonReportData = {
generator: mockGenerator,
- params: { someParams: 'value' }
+ params: { someParams: 'value' },
};
(generateStudentReportCard as jest.Mock).mockResolvedValue(mockReportData);
@@ -164,7 +164,7 @@ describe('StudentConfig', () => {
expect(generateStudentReportCard).toHaveBeenCalledWith(
mockUserId,
mockExtra,
- expect.any(BulkToPdfReportGenerator)
+ expect.any(BulkToPdfReportGenerator),
);
expect(result).toBe(mockReportData);
});
@@ -174,17 +174,16 @@ describe('StudentConfig', () => {
...mockReq,
parsed: {
...mockReq.parsed,
- extra: { report: 'unsupported' }
- }
+ extra: { report: 'unsupported' },
+ },
};
const mockGenerator = new MockReportGenerator();
const mockParentResult: CommonReportData = {
generator: mockGenerator,
- params: { parentParams: 'value' }
+ params: { parentParams: 'value' },
};
- jest.spyOn(BaseEntityService.prototype, 'getReportData')
- .mockResolvedValue(mockParentResult);
+ jest.spyOn(BaseEntityService.prototype, 'getReportData').mockResolvedValue(mockParentResult);
const result = await service.getReportData(unsupportedReq as any);
@@ -193,4 +192,4 @@ describe('StudentConfig', () => {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/teacher-report-status.config.spec.ts b/server/src/entity-modules/__tests__/teacher-report-status.config.spec.ts
index 8e8072c2..b40f15a2 100644
--- a/server/src/entity-modules/__tests__/teacher-report-status.config.spec.ts
+++ b/server/src/entity-modules/__tests__/teacher-report-status.config.spec.ts
@@ -51,21 +51,21 @@ interface ActionResult {
jest.mock('src/reports/reportGenerator', () => ({
getTeacherStatusFileReportParams: jest.fn(),
- sendTeacherReportFileMail: jest.fn()
+ sendTeacherReportFileMail: jest.fn(),
}));
describe('teacher-report-status.config', () => {
describe('getConfig', () => {
it('should return TeacherReportStatus entity and export headers configuration', () => {
expect(config.entity).toBe(TeacherReportStatus);
-
+
const headers = config.exporter.getExportHeaders([]);
expect(headers).toHaveLength(4);
expect(headers).toEqual([
{ value: 'teacherName', label: 'מורה' },
{ value: 'reportMonthName', label: 'תקופת דיווח' },
{ value: 'reportedLessonNames', label: 'שיעורים שדווחו' },
- { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' }
+ { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' },
]);
});
});
@@ -79,33 +79,29 @@ describe('teacher-report-status.config', () => {
const mockRepository = {
target: TeacherReportStatus,
manager: {
- transaction: jest.fn()
+ transaction: jest.fn(),
},
metadata: {
- columns: [
- { propertyName: 'id' },
- { propertyName: 'name' },
- { propertyName: 'userId' }
- ],
+ columns: [{ propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'userId' }],
connection: { options: { type: 'mysql' } },
- targetName: 'TestEntity'
+ targetName: 'TestEntity',
},
createQueryBuilder: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getCount: jest.fn(),
- save: jest.fn().mockImplementation(entity => Promise.resolve(entity))
+ save: jest.fn().mockImplementation((entity) => Promise.resolve(entity)),
} as any;
-
+
mockDataSource = {
createQueryRunner: jest.fn(),
- getRepository: jest.fn().mockReturnValue(mockRepository)
+ getRepository: jest.fn().mockReturnValue(mockRepository),
} as any as DataSource;
mockMailSendService = {
mailerService: {
- sendMail: jest.fn()
- }
+ sendMail: jest.fn(),
+ },
} as unknown as jest.Mocked;
service = new config.service(mockRepository, mockMailSendService);
@@ -121,7 +117,7 @@ describe('teacher-report-status.config', () => {
const req: MockRequest = {
parsed: {
extra: {
- report: 'teacherReportFile'
+ report: 'teacherReportFile',
},
fields: [],
paramsFilter: [],
@@ -129,9 +125,9 @@ describe('teacher-report-status.config', () => {
or: [],
join: [],
sort: [],
- classTransformOptions: {}
+ classTransformOptions: {},
},
- options: {}
+ options: {},
};
const result = await service.getReportData(req as unknown as CrudRequest);
@@ -139,7 +135,7 @@ describe('teacher-report-status.config', () => {
expect(req.parsed.extra.isGrades).toBe(false);
expect(result).toEqual({
generator: service['reportsDict'].teacherReportFile,
- params: mockParams
+ params: mockParams,
});
expect(getTeacherStatusFileReportParams).toHaveBeenCalledWith(req);
});
@@ -148,7 +144,7 @@ describe('teacher-report-status.config', () => {
const req: MockRequest = {
parsed: {
extra: {
- report: 'unknownReport'
+ report: 'unknownReport',
},
fields: [],
paramsFilter: [],
@@ -156,17 +152,18 @@ describe('teacher-report-status.config', () => {
or: [],
join: [],
sort: [],
- classTransformOptions: {}
+ classTransformOptions: {},
},
- options: {}
+ options: {},
};
- const mockParentResult: ReportData = {
+ const mockParentResult: ReportData = {
generator: null,
- params: { someData: 'value' }
+ params: { someData: 'value' },
};
-
- const parentGetReportData =jest.spyOn(BaseEntityService.prototype, 'getReportData')
+
+ const parentGetReportData = jest
+ .spyOn(BaseEntityService.prototype, 'getReportData')
.mockResolvedValue(mockParentResult);
const result = await service.getReportData(req as unknown as CrudRequest);
@@ -185,7 +182,7 @@ describe('teacher-report-status.config', () => {
const req: MockRequest = {
parsed: {
extra: {
- action: 'teacherReportFile'
+ action: 'teacherReportFile',
},
fields: [],
paramsFilter: [],
@@ -193,9 +190,9 @@ describe('teacher-report-status.config', () => {
or: [],
join: [],
sort: [],
- classTransformOptions: {}
+ classTransformOptions: {},
},
- options: {}
+ options: {},
};
const body: Record = { someData: 'value' };
@@ -203,18 +200,14 @@ describe('teacher-report-status.config', () => {
expect(req.parsed.extra.isGrades).toBe(false);
expect(result).toEqual(mockResult);
- expect(sendTeacherReportFileMail).toHaveBeenCalledWith(
- req,
- mockDataSource,
- mockMailSendService
- );
+ expect(sendTeacherReportFileMail).toHaveBeenCalledWith(req, mockDataSource, mockMailSendService);
});
it('should fall back to parent doAction for unknown action', async () => {
const req: MockRequest = {
parsed: {
extra: {
- action: 'unknownAction'
+ action: 'unknownAction',
},
fields: [],
paramsFilter: [],
@@ -222,21 +215,22 @@ describe('teacher-report-status.config', () => {
or: [],
join: [],
sort: [],
- classTransformOptions: {}
+ classTransformOptions: {},
},
- options: {}
+ options: {},
};
const body: Record = { someData: 'value' };
const mockParentResult: ActionResult = { someOtherData: 'value' };
-
- const parentDoAction = jest.spyOn(BaseEntityService.prototype, 'doAction')
+
+ const parentDoAction = jest
+ .spyOn(BaseEntityService.prototype, 'doAction')
.mockImplementation(() => Promise.resolve(mockParentResult));
- const result = await service.doAction(req as unknown as CrudRequest, body);
+ const result = await service.doAction(req as unknown as CrudRequest, body);
expect(result).toEqual(mockParentResult);
expect(parentDoAction).toHaveBeenCalledWith(req, body);
});
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/__tests__/teacher.config.spec.ts b/server/src/entity-modules/__tests__/teacher.config.spec.ts
index 29cb1618..8f649f6a 100644
--- a/server/src/entity-modules/__tests__/teacher.config.spec.ts
+++ b/server/src/entity-modules/__tests__/teacher.config.spec.ts
@@ -9,14 +9,16 @@ describe('TeacherConfig', () => {
it('should return correct export headers', () => {
const fields = ['tz', 'name', 'phone', 'phone2', 'email', 'displayName'];
const headers = teacherConfig.exporter.getExportHeaders(fields);
-
- expect(headers).toEqual(expect.arrayContaining([
- { value: 'tz', label: 'תז' },
- { value: 'name', label: 'שם' },
- { value: 'phone', label: 'טלפון' },
- { value: 'phone2', label: 'טלפון 2' },
- { value: 'email', label: 'כתובת מייל' },
- { value: 'displayName', label: 'שם לתצוגה' },
- ]));
+
+ expect(headers).toEqual(
+ expect.arrayContaining([
+ { value: 'tz', label: 'תז' },
+ { value: 'name', label: 'שם' },
+ { value: 'phone', label: 'טלפון' },
+ { value: 'phone2', label: 'טלפון 2' },
+ { value: 'email', label: 'כתובת מייל' },
+ { value: 'displayName', label: 'שם לתצוגה' },
+ ]),
+ );
});
-});
\ No newline at end of file
+});
diff --git a/server/src/entity-modules/absenceType.config.ts b/server/src/entity-modules/absenceType.config.ts
index 0f46cc72..0ab78896 100644
--- a/server/src/entity-modules/absenceType.config.ts
+++ b/server/src/entity-modules/absenceType.config.ts
@@ -18,4 +18,4 @@ function getConfig(): BaseEntityModuleOptions {
};
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/att-report-with-report-month.config.ts b/server/src/entity-modules/att-report-with-report-month.config.ts
index 0d4532c6..745a3012 100644
--- a/server/src/entity-modules/att-report-with-report-month.config.ts
+++ b/server/src/entity-modules/att-report-with-report-month.config.ts
@@ -1,166 +1,175 @@
-import { CrudRequest, Override, CreateManyDto } from "@dataui/crud";
-import { In, DeepPartial } from "typeorm";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { AttReportWithReportMonth } from "src/db/view-entities/AttReportWithReportMonth.entity";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { AttReport } from "src/db/entities/AttReport.entity";
-import { KnownAbsence } from "src/db/entities/KnownAbsence.entity";
-import { validateBulk } from "@shared/base-entity/base-entity.util";
-import { fixReferences } from "@shared/utils/entity/fixReference.util";
-import { getHebrewDateFormatter } from "@shared/utils/formatting/formatter.util";
-import { shouldShowTopic } from "./att-report.config";
-import { getAsArray, getAsDate, getAsNumber, getAsBoolean, getAsString, getAsNumberArray } from "@shared/utils/queryParam.util";
+import { CrudRequest, Override, CreateManyDto } from '@dataui/crud';
+import { In, DeepPartial } from 'typeorm';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { AttReportWithReportMonth } from 'src/db/view-entities/AttReportWithReportMonth.entity';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { AttReport } from 'src/db/entities/AttReport.entity';
+import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity';
+import { validateBulk } from '@shared/base-entity/base-entity.util';
+import { fixReferences } from '@shared/utils/entity/fixReference.util';
+import { getHebrewDateFormatter } from '@shared/utils/formatting/formatter.util';
+import { shouldShowTopic } from './att-report.config';
+import {
+ getAsArray,
+ getAsDate,
+ getAsNumber,
+ getAsBoolean,
+ getAsString,
+ getAsNumberArray,
+} from '@shared/utils/queryParam.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: AttReportWithReportMonth,
- query: {
- join: {
- studentBaseKlass: { eager: true },
- student: { eager: false },
- teacher: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- 'klass.klassType': { eager: false },
- reportMonth: { eager: false },
- reportGroupSession: { eager: false }
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- studentBaseKlass: { eager: true },
- student: { eager: true },
- teacher: { eager: true },
- klass: { eager: true },
- lesson: { eager: true },
- reportMonth: { eager: true },
- reportGroupSession: { eager: shouldShowTopic(req) }
- };
- return innerFunc(req);
- },
- getExportHeaders(entityColumns?: string[], req?: CrudRequest): IHeader[] {
- const headers: IHeader[] = [
- { value: 'teacher.name', label: 'שם המורה' },
- { value: 'student.name', label: 'שם התלמידה' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'reportGroupSession.topic', label: 'נושא השיעור' },
- { value: 'reportMonth.name', label: 'חודש דיווח' },
- { value: 'reportDate', label: 'תאריך דיווח' },
- { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
- { value: 'howManyLessons', label: 'מספר שיעורים' },
- { value: 'absCount', label: 'מספר חיסורים' },
- // { value: 'approvedAbsCount', label: 'מספר חיסורים מאושרים' },
- // { value: 'sheetName', label: 'חודש דיווח' },
- { value: 'comments', label: 'הערות' },
- ];
- if (!shouldShowTopic(req)) {
- const topicIndex = headers.findIndex(h => typeof h === 'object' && h.value === 'reportGroupSession.topic');
- if (topicIndex !== -1) {
- headers.splice(topicIndex, 1);
- }
- }
- return headers;
- }
- },
- service: AttReportWithReportMonthService,
- }
+ return {
+ entity: AttReportWithReportMonth,
+ query: {
+ join: {
+ studentBaseKlass: { eager: true },
+ student: { eager: false },
+ teacher: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ 'klass.klassType': { eager: false },
+ reportMonth: { eager: false },
+ reportGroupSession: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ studentBaseKlass: { eager: true },
+ student: { eager: true },
+ teacher: { eager: true },
+ klass: { eager: true },
+ lesson: { eager: true },
+ reportMonth: { eager: true },
+ reportGroupSession: { eager: shouldShowTopic(req) },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(entityColumns?: string[], req?: CrudRequest): IHeader[] {
+ const headers: IHeader[] = [
+ { value: 'teacher.name', label: 'שם המורה' },
+ { value: 'student.name', label: 'שם התלמידה' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'reportGroupSession.topic', label: 'נושא השיעור' },
+ { value: 'reportMonth.name', label: 'חודש דיווח' },
+ { value: 'reportDate', label: 'תאריך דיווח' },
+ { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
+ { value: 'howManyLessons', label: 'מספר שיעורים' },
+ { value: 'absCount', label: 'מספר חיסורים' },
+ // { value: 'approvedAbsCount', label: 'מספר חיסורים מאושרים' },
+ // { value: 'sheetName', label: 'חודש דיווח' },
+ { value: 'comments', label: 'הערות' },
+ ];
+ if (!shouldShowTopic(req)) {
+ const topicIndex = headers.findIndex((h) => typeof h === 'object' && h.value === 'reportGroupSession.topic');
+ if (topicIndex !== -1) {
+ headers.splice(topicIndex, 1);
+ }
+ }
+ return headers;
+ },
+ },
+ service: AttReportWithReportMonthService,
+ };
}
-
class AttReportWithReportMonthService extends BaseEntityService {
- private getAttReportService(): BaseEntityService {
- const attReportService = new BaseEntityService(this.dataSource.getRepository(AttReport), this.mailSendService);
- attReportService.dataSource = this.dataSource;
- return attReportService;
- }
+ private getAttReportService(): BaseEntityService {
+ const attReportService = new BaseEntityService(this.dataSource.getRepository(AttReport), this.mailSendService);
+ attReportService.dataSource = this.dataSource;
+ return attReportService;
+ }
- @Override()
- async createOne(req: CrudRequest, dto: DeepPartial): Promise {
- const attReportService = this.getAttReportService();
- await attReportService.createOne(req, dto);
- return this.getOne(req);
- }
+ @Override()
+ async createOne(req: CrudRequest, dto: DeepPartial): Promise {
+ const attReportService = this.getAttReportService();
+ await attReportService.createOne(req, dto);
+ return this.getOne(req);
+ }
- @Override()
- async createMany(req: CrudRequest, dto: CreateManyDto>): Promise {
- const attReportService = this.getAttReportService();
- return attReportService.createMany(req, dto as unknown as CreateManyDto>) as unknown as Promise;
- }
+ @Override()
+ async createMany(req: CrudRequest, dto: CreateManyDto>): Promise {
+ const attReportService = this.getAttReportService();
+ return attReportService.createMany(
+ req,
+ dto as unknown as CreateManyDto>,
+ ) as unknown as Promise;
+ }
- @Override()
- async updateOne(req: CrudRequest, dto: DeepPartial): Promise {
- const attReportService = this.getAttReportService();
- await attReportService.updateOne(req, dto);
- return this.getOne(req);
- }
+ @Override()
+ async updateOne(req: CrudRequest, dto: DeepPartial): Promise {
+ const attReportService = this.getAttReportService();
+ await attReportService.updateOne(req, dto);
+ return this.getOne(req);
+ }
- @Override()
- async deleteOne(req: CrudRequest): Promise {
- const attReportService = new BaseEntityService(this.dataSource.getRepository(AttReport), this.mailSendService);
- return attReportService.deleteOne(req) as Promise;
- }
+ @Override()
+ async deleteOne(req: CrudRequest): Promise {
+ const attReportService = new BaseEntityService(this.dataSource.getRepository(AttReport), this.mailSendService);
+ return attReportService.deleteOne(req) as Promise;
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'bulkKnownAbsences': {
- const ids = getAsArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'bulkKnownAbsences': {
+ const ids = getAsArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });
- const knownAbsences: Array> = reports.map(report => ({
- userId: report.userId,
- studentReferenceId: report.studentReferenceId,
- klassReferenceId: report.klassReferenceId,
- lessonReferenceId: report.lessonReferenceId,
- reportDate: getAsDate(req.parsed.extra.reportDate) ?? report.reportDate,
- absnceCount: getAsNumber(req.parsed.extra.absnceCount) ?? Math.round(report.absCount),
- absnceCode: getAsNumber(req.parsed.extra.absnceCode),
- senderName: getAsString(req.parsed.extra.senderName),
- reason: getAsString(req.parsed.extra.reason),
- comment: getAsString(req.parsed.extra.comment),
- isApproved: getAsBoolean(req.parsed.extra.isApproved),
- year: report.year,
- }))
- await validateBulk(knownAbsences, KnownAbsence);
- await this.dataSource.getRepository(KnownAbsence).insert(knownAbsences);
+ const knownAbsences: Array> = reports.map((report) => ({
+ userId: report.userId,
+ studentReferenceId: report.studentReferenceId,
+ klassReferenceId: report.klassReferenceId,
+ lessonReferenceId: report.lessonReferenceId,
+ reportDate: getAsDate(req.parsed.extra.reportDate) ?? report.reportDate,
+ absnceCount: getAsNumber(req.parsed.extra.absnceCount) ?? Math.round(report.absCount),
+ absnceCode: getAsNumber(req.parsed.extra.absnceCode),
+ senderName: getAsString(req.parsed.extra.senderName),
+ reason: getAsString(req.parsed.extra.reason),
+ comment: getAsString(req.parsed.extra.comment),
+ isApproved: getAsBoolean(req.parsed.extra.isApproved),
+ year: report.year,
+ }));
+ await validateBulk(knownAbsences, KnownAbsence);
+ await this.dataSource.getRepository(KnownAbsence).insert(knownAbsences);
- return `נוצרו ${reports.length} חיסורים מאושרים`;
- }
- case 'fixStudentReferenceV2': {
- const ids = getAsArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });
+ return `נוצרו ${reports.length} חיסורים מאושרים`;
+ }
+ case 'fixStudentReferenceV2': {
+ const ids = getAsArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const reports = await this.dataSource.getRepository(AttReport).findBy({ id: In(ids) });
- const reportsToSave = [];
- for (const report of reports) {
- if (report.studentReferenceId && !report.studentTz) {
- report.studentTz = String(report.studentReferenceId)?.padStart(9, '0');
- report.studentReferenceId = null;
- await report.fillFields();
- reportsToSave.push(report);
- }
- }
- if (reportsToSave.length > 0) {
- await this.dataSource.getRepository(AttReport).save(reportsToSave);
- }
- return `עודכנו ${reportsToSave.length} רשומות`;
- }
- case 'fixReferences': {
- const ids = getAsNumberArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const referenceFields = {
- studentTz: 'studentReferenceId',
- klassId: 'klassReferenceId',
- lessonId: 'lessonReferenceId',
- };
- return fixReferences(this.dataSource.getRepository(AttReport), ids, referenceFields);
- }
+ const reportsToSave = [];
+ for (const report of reports) {
+ if (report.studentReferenceId && !report.studentTz) {
+ report.studentTz = String(report.studentReferenceId)?.padStart(9, '0');
+ report.studentReferenceId = null;
+ await report.fillFields();
+ reportsToSave.push(report);
+ }
+ }
+ if (reportsToSave.length > 0) {
+ await this.dataSource.getRepository(AttReport).save(reportsToSave);
}
- return super.doAction(req, body);
+ return `עודכנו ${reportsToSave.length} רשומות`;
+ }
+ case 'fixReferences': {
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const referenceFields = {
+ studentTz: 'studentReferenceId',
+ klassId: 'klassReferenceId',
+ lessonId: 'lessonReferenceId',
+ };
+ return fixReferences(this.dataSource.getRepository(AttReport), ids, referenceFields);
+ }
}
+ return super.doAction(req, body);
+ }
}
export default getConfig();
diff --git a/server/src/entity-modules/att-report.config.ts b/server/src/entity-modules/att-report.config.ts
index 4f9f53a9..fb532741 100644
--- a/server/src/entity-modules/att-report.config.ts
+++ b/server/src/entity-modules/att-report.config.ts
@@ -1,100 +1,91 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-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 { CrudRequest } from '@dataui/crud';
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+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 { roundObjectProperty } from '@shared/utils/reportData.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: AttReport,
- query: {
- join: {
- studentBaseKlass: { eager: true },
- student: { eager: false },
- teacher: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- reportGroupSession: { eager: false },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- studentBaseKlass: { eager: true },
- student: { eager: true },
- teacher: { eager: true },
- klass: { eager: true },
- lesson: { eager: true },
- reportGroupSession: { eager: shouldShowTopic(req) }
- };
- return innerFunc(req);
- },
- getExportHeaders(entityColumns?: string[], req?: CrudRequest): IHeader[] {
- const headers: IHeader[] = [
- { value: 'teacher.name', label: 'שם המורה' },
- { value: 'student.name', label: 'שם התלמידה' },
- { value: 'student.tz', label: 'תז התלמידה' },
- { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'reportGroupSession.topic', label: 'נושא השיעור' },
- { value: 'reportDate', label: 'תאריך דיווח' },
- { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
- { value: 'howManyLessons', label: 'מספר שיעורים' },
- { value: 'absCount', label: 'מספר חיסורים' },
- // { value: 'approvedAbsCount', label: 'מספר חיסורים מאושרים' },
- // { value: 'sheetName', label: 'חודש דיווח' },
- { value: 'comments', label: 'הערות' },
- ];
- if (!shouldShowTopic(req)) {
- const topicIndex = headers.findIndex(h => typeof h === 'object' && h.value === 'reportGroupSession.topic');
- if (topicIndex !== -1) {
- headers.splice(topicIndex, 1);
- }
- }
- return headers;
- },
- getImportDefinition(importFields) {
- return {
- importFields: [
- 'klassId',
- 'studentReferenceId',
- '',
- 'lateCount',
- 'absCount',
- 'comments',
- ],
- specialFields: [
- { cell: { c: 2, r: 0 }, value: 'teacherId' },
- { cell: { c: 2, r: 1 }, value: 'lessonId' },
- { cell: { c: 4, r: 0 }, value: 'reportDate' },
- { cell: { c: 4, r: 1 }, value: 'howManyLessons' },
- ],
- hardCodedFields: [
- { field: 'reportDate', value: new Date() },
- ],
- beforeSave: calcAttLateCount,
- };
- }
+ return {
+ entity: AttReport,
+ query: {
+ join: {
+ studentBaseKlass: { eager: true },
+ student: { eager: false },
+ teacher: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ reportGroupSession: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ studentBaseKlass: { eager: true },
+ student: { eager: true },
+ teacher: { eager: true },
+ klass: { eager: true },
+ lesson: { eager: true },
+ reportGroupSession: { eager: shouldShowTopic(req) },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(entityColumns?: string[], req?: CrudRequest): IHeader[] {
+ const headers: IHeader[] = [
+ { value: 'teacher.name', label: 'שם המורה' },
+ { value: 'student.name', label: 'שם התלמידה' },
+ { value: 'student.tz', label: 'תז התלמידה' },
+ { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'reportGroupSession.topic', label: 'נושא השיעור' },
+ { value: 'reportDate', label: 'תאריך דיווח' },
+ { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
+ { value: 'howManyLessons', label: 'מספר שיעורים' },
+ { value: 'absCount', label: 'מספר חיסורים' },
+ // { value: 'approvedAbsCount', label: 'מספר חיסורים מאושרים' },
+ // { value: 'sheetName', label: 'חודש דיווח' },
+ { value: 'comments', label: 'הערות' },
+ ];
+ if (!shouldShowTopic(req)) {
+ const topicIndex = headers.findIndex((h) => typeof h === 'object' && h.value === 'reportGroupSession.topic');
+ if (topicIndex !== -1) {
+ headers.splice(topicIndex, 1);
+ }
}
- }
+ return headers;
+ },
+ getImportDefinition(importFields) {
+ return {
+ importFields: ['klassId', 'studentReferenceId', '', 'lateCount', 'absCount', 'comments'],
+ specialFields: [
+ { cell: { c: 2, r: 0 }, value: 'teacherId' },
+ { cell: { c: 2, r: 1 }, value: 'lessonId' },
+ { cell: { c: 4, r: 0 }, value: 'reportDate' },
+ { cell: { c: 4, r: 1 }, value: 'howManyLessons' },
+ ],
+ hardCodedFields: [{ field: 'reportDate', value: new Date() }],
+ beforeSave: calcAttLateCount,
+ };
+ },
+ },
+ };
}
export default getConfig();
export const shouldShowTopic = (req: CrudRequest | undefined): boolean => {
- if (!req) return false;
- return isAdmin(req.auth) || hasPermission(req.auth, 'lessonSignature');
+ if (!req) return false;
+ return isAdmin(req.auth) || hasPermission(req.auth, 'lessonSignature');
};
export const calcAttLateCount = (report: AttReport & { lateCount: number }, user: User) => {
- report.absCount = isNaN(report.absCount) ? 0 : Number(report.absCount);
- report.lateCount = isNaN(report.lateCount) ? 0 : Number(report.lateCount);
- const lateValue = user.additionalData?.lateValue ?? 0.3;
- report.absCount += report.lateCount * lateValue;
- roundObjectProperty(report, 'absCount');
- delete report.lateCount;
-}
+ report.absCount = isNaN(report.absCount) ? 0 : Number(report.absCount);
+ report.lateCount = isNaN(report.lateCount) ? 0 : Number(report.lateCount);
+ const lateValue = user.additionalData?.lateValue ?? 0.3;
+ report.absCount += report.lateCount * lateValue;
+ roundObjectProperty(report, 'absCount');
+ delete report.lateCount;
+};
diff --git a/server/src/entity-modules/grade.config.ts b/server/src/entity-modules/grade.config.ts
index 4896b3e6..882e138d 100644
--- a/server/src/entity-modules/grade.config.ts
+++ b/server/src/entity-modules/grade.config.ts
@@ -1,95 +1,85 @@
-import { CrudRequest } from "@dataui/crud";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { getHebrewDateFormatter } from "@shared/utils/formatting/formatter.util";
-import { generateCommonFileResponse } from "@shared/utils/report/report.util";
-import { Grade } from "src/db/entities/Grade.entity";
-import michlolPopulatedFile, { MichlolPopulatedFileParams } from "src/reports/michlolPopulatedFile";
-import { getAsString } from "@shared/utils/queryParam.util";
+import { CrudRequest } from '@dataui/crud';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { getHebrewDateFormatter } from '@shared/utils/formatting/formatter.util';
+import { generateCommonFileResponse } from '@shared/utils/report/report.util';
+import { Grade } from 'src/db/entities/Grade.entity';
+import michlolPopulatedFile, { MichlolPopulatedFileParams } from 'src/reports/michlolPopulatedFile';
+import { getAsString } from '@shared/utils/queryParam.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: Grade,
- query: {
- join: {
- studentBaseKlass: { eager: false },
- student: { eager: false },
- teacher: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- studentBaseKlass: { eager: true },
- student: { eager: true },
- teacher: { eager: true },
- klass: { eager: true },
- lesson: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'teacher.name', label: 'שם המורה' },
- { value: 'student.name', label: 'שם התלמידה' },
- { value: 'student.tz', label: 'תז התלמידה' },
- { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'reportDate', label: 'תאריך דיווח' },
- { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
- { value: 'grade', label: 'ציון' },
- { value: 'estimation', label: 'הערכה' },
- { value: 'comments', label: 'הערות' },
- ];
- },
- getImportDefinition(importFields) {
- return {
- importFields: [
- 'klassId',
- 'studentReferenceId',
- '',
- 'grade',
- 'estimation',
- 'comments',
- ],
- specialFields: [
- { cell: { c: 2, r: 0 }, value: 'teacherId' },
- { cell: { c: 2, r: 1 }, value: 'lessonId' },
- ],
- hardCodedFields: [
- { field: 'reportDate', value: new Date() },
- ]
- };
- }
- },
- service: GradeService,
- }
+ return {
+ entity: Grade,
+ query: {
+ join: {
+ studentBaseKlass: { eager: false },
+ student: { eager: false },
+ teacher: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ studentBaseKlass: { eager: true },
+ student: { eager: true },
+ teacher: { eager: true },
+ klass: { eager: true },
+ lesson: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'teacher.name', label: 'שם המורה' },
+ { value: 'student.name', label: 'שם התלמידה' },
+ { value: 'student.tz', label: 'תז התלמידה' },
+ { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'reportDate', label: 'תאריך דיווח' },
+ { value: getHebrewDateFormatter('reportDate'), label: 'תאריך עברי' },
+ { value: 'grade', label: 'ציון' },
+ { value: 'estimation', label: 'הערכה' },
+ { value: 'comments', label: 'הערות' },
+ ];
+ },
+ getImportDefinition(importFields) {
+ return {
+ importFields: ['klassId', 'studentReferenceId', '', 'grade', 'estimation', 'comments'],
+ specialFields: [
+ { cell: { c: 2, r: 0 }, value: 'teacherId' },
+ { cell: { c: 2, r: 1 }, value: 'lessonId' },
+ ],
+ hardCodedFields: [{ field: 'reportDate', value: new Date() }],
+ };
+ },
+ },
+ service: GradeService,
+ };
}
-
class GradeService extends BaseEntityService {
- reportsDict = {
- michlolPopulatedFile: michlolPopulatedFile,
- }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'michlolPopulatedFile': {
- const generator = this.reportsDict[req.parsed.extra.action];
- const params: MichlolPopulatedFileParams = {
- userId: getUserIdFromUser(req.auth),
- michlolFileName: getAsString(req.parsed.extra.fileName),
- michlolFileData: body.data,
- }
- return generateCommonFileResponse(generator, params, this.dataSource);
- }
- }
- return super.doAction(req, body);
+ reportsDict = {
+ michlolPopulatedFile: michlolPopulatedFile,
+ };
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'michlolPopulatedFile': {
+ const generator = this.reportsDict[req.parsed.extra.action];
+ const params: MichlolPopulatedFileParams = {
+ userId: getUserIdFromUser(req.auth),
+ michlolFileName: getAsString(req.parsed.extra.fileName),
+ michlolFileData: body.data,
+ };
+ return generateCommonFileResponse(generator, params, this.dataSource);
+ }
}
+ return super.doAction(req, body);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/klass-type.config.ts b/server/src/entity-modules/klass-type.config.ts
index 6a49b3d7..e8675b59 100644
--- a/server/src/entity-modules/klass-type.config.ts
+++ b/server/src/entity-modules/klass-type.config.ts
@@ -1,33 +1,31 @@
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { KlassType } from "src/db/entities/KlassType.entity";
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { KlassType } from 'src/db/entities/KlassType.entity';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: KlassType,
- query: {
- join: {
- teacher: { eager: false },
- }
- },
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'key', label: 'מזהה' },
- { value: 'name', label: 'שם' },
- ];
- },
- getImportDefinition(importFields) {
- importFields.splice(1, 0, '');
- return {
- importFields,
- specialFields: [
- { cell: { c: 0, r: 1 }, value: 'test' },
- ]
- };
- }
- }
- }
+ return {
+ entity: KlassType,
+ query: {
+ join: {
+ teacher: { eager: false },
+ },
+ },
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'key', label: 'מזהה' },
+ { value: 'name', label: 'שם' },
+ ];
+ },
+ getImportDefinition(importFields) {
+ importFields.splice(1, 0, '');
+ return {
+ importFields,
+ specialFields: [{ cell: { c: 0, r: 1 }, value: 'test' }],
+ };
+ },
+ },
+ };
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/klass.config.ts b/server/src/entity-modules/klass.config.ts
index 03999e07..42caaa9b 100644
--- a/server/src/entity-modules/klass.config.ts
+++ b/server/src/entity-modules/klass.config.ts
@@ -1,90 +1,88 @@
-import { CrudRequest } from "@dataui/crud";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { CommonReportData } from "@shared/utils/report/types";
-import { IHeader } from "@shared/utils/exporter/types";
-import { Klass } from "src/db/entities/Klass.entity";
-import klassAttendanceReportGenerator from "src/reports/klassAttendanceReport";
-import { getAsDate, getAsNumberArray } from "@shared/utils/queryParam.util";
-import { fixReferences } from "@shared/utils/entity/fixReference.util";
+import { CrudRequest } from '@dataui/crud';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { CommonReportData } from '@shared/utils/report/types';
+import { IHeader } from '@shared/utils/exporter/types';
+import { Klass } from 'src/db/entities/Klass.entity';
+import klassAttendanceReportGenerator from 'src/reports/klassAttendanceReport';
+import { getAsDate, getAsNumberArray } from '@shared/utils/queryParam.util';
+import { fixReferences } from '@shared/utils/entity/fixReference.util';
class KlassService extends BaseEntityService {
- reportsDict = {
- klassAttendanceReport: klassAttendanceReportGenerator,
- };
+ reportsDict = {
+ klassAttendanceReport: klassAttendanceReportGenerator,
+ };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const generator = this.reportsDict[req.parsed.extra.report];
- const params = this.getKlassAttendanceReportParams(req);
- return { generator, params };
- }
- return super.getReportData(req);
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const params = this.getKlassAttendanceReportParams(req);
+ return { generator, params };
}
+ return super.getReportData(req);
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'fixReferences': {
- const ids = getAsNumberArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const referenceFields = {
- klassTypeId: 'klassTypeReferenceId',
- teacherId: 'teacherReferenceId',
- };
- return fixReferences(this.dataSource.getRepository(Klass), ids, referenceFields);
- }
- }
- return super.doAction(req, body);
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'fixReferences': {
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const referenceFields = {
+ klassTypeId: 'klassTypeReferenceId',
+ teacherId: 'teacherReferenceId',
+ };
+ return fixReferences(this.dataSource.getRepository(Klass), ids, referenceFields);
+ }
}
+ return super.doAction(req, body);
+ }
- private getKlassAttendanceReportParams(req: CrudRequest) {
- const userId = getUserIdFromUser(req.auth);
- const startDate = getAsDate(req.parsed.extra.startDate);
- const endDate = getAsDate(req.parsed.extra.endDate);
- const lessonReferenceIds = getAsNumberArray(req.parsed.extra.lessonReferenceIds);
+ private getKlassAttendanceReportParams(req: CrudRequest) {
+ const userId = getUserIdFromUser(req.auth);
+ const startDate = getAsDate(req.parsed.extra.startDate);
+ const endDate = getAsDate(req.parsed.extra.endDate);
+ const lessonReferenceIds = getAsNumberArray(req.parsed.extra.lessonReferenceIds);
- return getAsNumberArray(req.parsed.extra.ids)
- ?.map(id => ({
- userId,
- klassId: id,
- startDate,
- endDate,
- lessonReferenceIds
- }));
- }
+ return getAsNumberArray(req.parsed.extra.ids)?.map((id) => ({
+ userId,
+ klassId: id,
+ startDate,
+ endDate,
+ lessonReferenceIds,
+ }));
+ }
}
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: Klass,
- service: KlassService,
- query: {
- join: {
- teacher: { eager: false },
- klassType: { eager: false },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- klassType: { eager: true },
- teacher: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'key', label: 'מזהה' },
- { value: 'name', label: 'שם' },
- { value: 'klassType.name', label: 'סוג כיתה' },
- { value: 'teacher.name', label: 'מורה' },
- { value: 'displayName', label: 'שם לתעודה' },
- ];
- }
- }
- }
+ return {
+ entity: Klass,
+ service: KlassService,
+ query: {
+ join: {
+ teacher: { eager: false },
+ klassType: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ klassType: { eager: true },
+ teacher: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'key', label: 'מזהה' },
+ { value: 'name', label: 'שם' },
+ { value: 'klassType.name', label: 'סוג כיתה' },
+ { value: 'teacher.name', label: 'מורה' },
+ { value: 'displayName', label: 'שם לתעודה' },
+ ];
+ },
+ },
+ };
}
export default getConfig();
-
diff --git a/server/src/entity-modules/known-absence.config.ts b/server/src/entity-modules/known-absence.config.ts
index 83bce94a..2de7a1c3 100644
--- a/server/src/entity-modules/known-absence.config.ts
+++ b/server/src/entity-modules/known-absence.config.ts
@@ -1,44 +1,44 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { KnownAbsence } from "src/db/entities/KnownAbsence.entity";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: KnownAbsence,
- query: {
- join: {
- student: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- absenceType: { eager: false },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- student: { eager: true },
- absenceType: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'student.name', label: 'תלמידה' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'absenceType.name', label: 'סוג אירוע' },
- { value: 'reportDate', label: 'תאריך דיווח' },
- { value: 'absnceCount', label: 'מספר היעדרויות' },
- { value: 'absnceCode', label: 'קוד היעדרות' },
- { value: 'senderName', label: 'שם השולח' },
- { value: 'reason', label: 'סיבה' },
- { value: 'comment', label: 'הערה' },
- { value: 'isApproved', label: 'מאושר' },
- ];
- }
- }
- }
+ return {
+ entity: KnownAbsence,
+ query: {
+ join: {
+ student: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ absenceType: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ student: { eager: true },
+ absenceType: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'student.name', label: 'תלמידה' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'absenceType.name', label: 'סוג אירוע' },
+ { value: 'reportDate', label: 'תאריך דיווח' },
+ { value: 'absnceCount', label: 'מספר היעדרויות' },
+ { value: 'absnceCode', label: 'קוד היעדרות' },
+ { value: 'senderName', label: 'שם השולח' },
+ { value: 'reason', label: 'סיבה' },
+ { value: 'comment', label: 'הערה' },
+ { value: 'isApproved', label: 'מאושר' },
+ ];
+ },
+ },
+ };
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/lesson.config.ts b/server/src/entity-modules/lesson.config.ts
index 69ef2d49..5ed4ece8 100644
--- a/server/src/entity-modules/lesson.config.ts
+++ b/server/src/entity-modules/lesson.config.ts
@@ -1,38 +1,38 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { Lesson } from "src/db/entities/Lesson.entity";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { Lesson } from 'src/db/entities/Lesson.entity';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: Lesson,
- query: {
- join: {
- teacher: { eager: false },
- lessonKlassName: { eager: false },
- },
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- teacher: { eager: true },
- lessonKlassName: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'key', label: 'מזהה' },
- { value: 'name', label: 'שם' },
- { value: 'lessonKlassName.name', label: 'כיתות' },
- { value: 'teacher.name', label: 'מורה' },
- { value: 'startDate', label: 'תאריך התחלה' },
- { value: 'endDate', label: 'תאריך סיום' },
- { value: 'displayName', label: 'שם לתעודה' },
- ];
- }
- },
- }
+ return {
+ entity: Lesson,
+ query: {
+ join: {
+ teacher: { eager: false },
+ lessonKlassName: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ teacher: { eager: true },
+ lessonKlassName: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'key', label: 'מזהה' },
+ { value: 'name', label: 'שם' },
+ { value: 'lessonKlassName.name', label: 'כיתות' },
+ { value: 'teacher.name', label: 'מורה' },
+ { value: 'startDate', label: 'תאריך התחלה' },
+ { value: 'endDate', label: 'תאריך סיום' },
+ { value: 'displayName', label: 'שם לתעודה' },
+ ];
+ },
+ },
+ };
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/report-group-session.config.ts b/server/src/entity-modules/report-group-session.config.ts
index a14bda0a..2df445da 100644
--- a/server/src/entity-modules/report-group-session.config.ts
+++ b/server/src/entity-modules/report-group-session.config.ts
@@ -1,111 +1,108 @@
-import { CrudRequest } from "@dataui/crud";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { CommonReportData } from "@shared/utils/report/types";
-import { ReportGroupSession } from "../db/entities/ReportGroupSession.entity";
-import reportGroupSessionsSummary from "src/reports/reportGroupSessionsSummary";
-import { In } from "typeorm";
-import { getAsNumberArray, getAsNumber } from "@shared/utils/queryParam.util";
+import { CrudRequest } from '@dataui/crud';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { CommonReportData } from '@shared/utils/report/types';
+import { ReportGroupSession } from '../db/entities/ReportGroupSession.entity';
+import reportGroupSessionsSummary from 'src/reports/reportGroupSessionsSummary';
+import { In } from 'typeorm';
+import { getAsNumberArray, getAsNumber } from '@shared/utils/queryParam.util';
class ReportGroupSessionService extends BaseEntityService {
- reportsDict = {
- sessionsSummary: reportGroupSessionsSummary,
+ reportsDict = {
+ sessionsSummary: reportGroupSessionsSummary,
+ };
+
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const params = this.getSessionsSummaryParams(req);
+ return {
+ generator,
+ params,
+ };
+ }
+ return super.getReportData(req);
+ }
+
+ private getSessionsSummaryParams(req: CrudRequest) {
+ const userId = getUserIdFromUser(req.auth);
+ const sessionIds = getAsNumberArray(req.parsed.extra.ids);
+
+ return {
+ userId,
+ sessionIds,
};
+ }
+
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'adjustTime': {
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ const hoursAdjustment = getAsNumber(req.parsed.extra.hoursAdjustment) || 0;
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const generator = this.reportsDict[req.parsed.extra.report];
- const params = this.getSessionsSummaryParams(req);
- return {
- generator,
- params,
- };
+ if (hoursAdjustment === 0) {
+ return 'לא בוצע שינוי - יש להזין מספר שעות';
}
- return super.getReportData(req);
- }
- private getSessionsSummaryParams(req: CrudRequest) {
- const userId = getUserIdFromUser(req.auth);
- const sessionIds = getAsNumberArray(req.parsed.extra.ids);
-
- return {
- userId,
- sessionIds,
- };
- }
+ if (!ids) return 'לא נבחרו מפגשים';
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'adjustTime': {
- const ids = getAsNumberArray(req.parsed.extra.ids);
- const hoursAdjustment = getAsNumber(req.parsed.extra.hoursAdjustment) || 0;
-
- if (hoursAdjustment === 0) {
- return 'לא בוצע שינוי - יש להזין מספר שעות';
- }
-
- if (!ids) return 'לא נבחרו מפגשים';
-
- const sessions = await this.dataSource.getRepository(ReportGroupSession).find({
- where: { id: In(ids) }
- });
-
- let updatedCount = 0;
- for (const session of sessions) {
- const updates: Partial = {};
-
- if (session.startTime) {
- updates.startTime = this.adjustTimeString(session.startTime, hoursAdjustment);
- }
- if (session.endTime) {
- updates.endTime = this.adjustTimeString(session.endTime, hoursAdjustment);
- }
-
- if (Object.keys(updates).length > 0) {
- await this.dataSource.getRepository(ReportGroupSession).update(
- { id: session.id },
- updates
- );
- updatedCount++;
- }
- }
-
- return `עודכנו ${updatedCount} מפגשים`;
- }
+ const sessions = await this.dataSource.getRepository(ReportGroupSession).find({
+ where: { id: In(ids) },
+ });
+
+ let updatedCount = 0;
+ for (const session of sessions) {
+ const updates: Partial = {};
+
+ if (session.startTime) {
+ updates.startTime = this.adjustTimeString(session.startTime, hoursAdjustment);
+ }
+ if (session.endTime) {
+ updates.endTime = this.adjustTimeString(session.endTime, hoursAdjustment);
+ }
+
+ if (Object.keys(updates).length > 0) {
+ await this.dataSource.getRepository(ReportGroupSession).update({ id: session.id }, updates);
+ updatedCount++;
+ }
}
- return super.doAction(req, body);
+
+ return `עודכנו ${updatedCount} מפגשים`;
+ }
}
+ return super.doAction(req, body);
+ }
- /**
- * Adjusts a time string (HH:mm:ss or HH:mm) by a number of hours
- * Handles wrapping around midnight (00:00 - 23:59)
- */
- private adjustTimeString(timeStr: string, hoursAdjustment: number): string {
- const parts = timeStr.split(':');
- let hours = parseInt(parts[0]) || 0;
- const minutes = parts[1] || '00';
- const seconds = parts[2] || '00';
+ /**
+ * Adjusts a time string (HH:mm:ss or HH:mm) by a number of hours
+ * Handles wrapping around midnight (00:00 - 23:59)
+ */
+ private adjustTimeString(timeStr: string, hoursAdjustment: number): string {
+ const parts = timeStr.split(':');
+ let hours = parseInt(parts[0]) || 0;
+ const minutes = parts[1] || '00';
+ const seconds = parts[2] || '00';
- hours = (hours + hoursAdjustment) % 24;
- if (hours < 0) hours += 24;
+ hours = (hours + hoursAdjustment) % 24;
+ if (hours < 0) hours += 24;
- return `${hours.toString().padStart(2, '0')}:${minutes}:${seconds}`;
- }
+ return `${hours.toString().padStart(2, '0')}:${minutes}:${seconds}`;
+ }
}
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: ReportGroupSession,
- service: ReportGroupSessionService,
- query: {
- join: {
- reportGroup: { eager: false },
- attReports: { eager: false },
- grades: { eager: false },
- }
- }
- }
+ return {
+ entity: ReportGroupSession,
+ service: ReportGroupSessionService,
+ query: {
+ join: {
+ reportGroup: { eager: false },
+ attReports: { eager: false },
+ grades: { eager: false },
+ },
+ },
+ };
}
export default getConfig();
diff --git a/server/src/entity-modules/report-group.config.ts b/server/src/entity-modules/report-group.config.ts
index b35c7b77..945cf7b4 100644
--- a/server/src/entity-modules/report-group.config.ts
+++ b/server/src/entity-modules/report-group.config.ts
@@ -1,103 +1,102 @@
-import { CrudRequest } from "@dataui/crud";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { BulkToPdfReportGenerator } from "@shared/utils/report/bulk-to-pdf.generator";
-import { CommonReportData } from "@shared/utils/report/types";
-import { ReportGroup } from "../db/entities/ReportGroup.entity";
-import lessonSignaturePdfReport from "src/reports/lessonSignaturePdfReport";
-import { IHeader } from "@shared/utils/exporter/types";
-import { getHebrewDateFormatter } from "@shared/utils/formatting/formatter.util";
-import { Repository } from "typeorm";
-import { BadRequestException } from "@nestjs/common";
-import { getAsNumberArray, getAsString } from "@shared/utils/queryParam.util";
+import { CrudRequest } from '@dataui/crud';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { BulkToPdfReportGenerator } from '@shared/utils/report/bulk-to-pdf.generator';
+import { CommonReportData } from '@shared/utils/report/types';
+import { ReportGroup } from '../db/entities/ReportGroup.entity';
+import lessonSignaturePdfReport from 'src/reports/lessonSignaturePdfReport';
+import { IHeader } from '@shared/utils/exporter/types';
+import { getHebrewDateFormatter } from '@shared/utils/formatting/formatter.util';
+import { Repository } from 'typeorm';
+import { BadRequestException } from '@nestjs/common';
+import { getAsNumberArray, getAsString } from '@shared/utils/queryParam.util';
class ReportGroupService extends BaseEntityService {
- reportsDict = {
- lessonSignaturePdf: new BulkToPdfReportGenerator(lessonSignaturePdfReport),
- };
+ reportsDict = {
+ lessonSignaturePdf: new BulkToPdfReportGenerator(lessonSignaturePdfReport),
+ };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const generator = this.reportsDict[req.parsed.extra.report];
- const params = this.getLessonSignaturePdfParams(req);
- return {
- generator,
- params,
- };
- }
- return super.getReportData(req);
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const params = this.getLessonSignaturePdfParams(req);
+ return {
+ generator,
+ params,
+ };
}
+ return super.getReportData(req);
+ }
- private getLessonSignaturePdfParams(req: CrudRequest) {
- const userId = getUserIdFromUser(req.auth);
- return getAsNumberArray(req.parsed.extra.ids)
- ?.map(id => ({
- userId,
- reportGroupId: id,
- }));
- }
+ private getLessonSignaturePdfParams(req: CrudRequest) {
+ const userId = getUserIdFromUser(req.auth);
+ return getAsNumberArray(req.parsed.extra.ids)?.map((id) => ({
+ userId,
+ reportGroupId: id,
+ }));
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'updateSignatureData': {
- const ids = getAsNumberArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const signatureData = getAsString(req.parsed.extra.signatureData);
- await this.updateSignatureData(ids, signatureData);
- return `עודכנו חתימות ל-${ids.length} קבוצות דוחות`;
- }
- }
- return super.doAction(req, body);
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'updateSignatureData': {
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const signatureData = getAsString(req.parsed.extra.signatureData);
+ await this.updateSignatureData(ids, signatureData);
+ return `עודכנו חתימות ל-${ids.length} קבוצות דוחות`;
+ }
}
+ return super.doAction(req, body);
+ }
- private async updateSignatureData(ids: number[], signatureData: string | undefined) {
- if (!signatureData) {
- throw new BadRequestException('לא סופקה חתימה לעדכון');
- }
- const repo = this.repo as Repository;
- for (const id of ids) {
- await repo.update({ id }, { signatureData });
- }
+ private async updateSignatureData(ids: number[], signatureData: string | undefined) {
+ if (!signatureData) {
+ throw new BadRequestException('לא סופקה חתימה לעדכון');
+ }
+ const repo = this.repo as Repository;
+ for (const id of ids) {
+ await repo.update({ id }, { signatureData });
}
+ }
}
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: ReportGroup,
- service: ReportGroupService,
- query: {
- join: {
- teacher: { eager: false },
- lesson: { eager: false },
- klass: { eager: false },
- sessions: { eager: false },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- teacher: { eager: true },
- lesson: { eager: true },
- klass: { eager: true },
- sessions: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { label: 'שם', value: 'name' },
- { label: 'נושא', value: 'topic' },
- { label: 'מורה', value: 'teacher.name' },
- { label: 'שיעור', value: 'lesson.name' },
- { label: 'כיתה', value: 'klass.name' },
- { label: 'שנה', value: 'year' },
- { label: 'מספר שיעורים', value: 'sessions.length' },
- { label: 'נוצר בתאריך', value: getHebrewDateFormatter('createdAt') },
- ];
- }
- },
- }
+ return {
+ entity: ReportGroup,
+ service: ReportGroupService,
+ query: {
+ join: {
+ teacher: { eager: false },
+ lesson: { eager: false },
+ klass: { eager: false },
+ sessions: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ teacher: { eager: true },
+ lesson: { eager: true },
+ klass: { eager: true },
+ sessions: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { label: 'שם', value: 'name' },
+ { label: 'נושא', value: 'topic' },
+ { label: 'מורה', value: 'teacher.name' },
+ { label: 'שיעור', value: 'lesson.name' },
+ { label: 'כיתה', value: 'klass.name' },
+ { label: 'שנה', value: 'year' },
+ { label: 'מספר שיעורים', value: 'sessions.length' },
+ { label: 'נוצר בתאריך', value: getHebrewDateFormatter('createdAt') },
+ ];
+ },
+ },
+ };
}
export default getConfig();
diff --git a/server/src/entity-modules/student-by-year.config.ts b/server/src/entity-modules/student-by-year.config.ts
index bf254820..779e1303 100644
--- a/server/src/entity-modules/student-by-year.config.ts
+++ b/server/src/entity-modules/student-by-year.config.ts
@@ -1,190 +1,195 @@
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
import { ParsedRequestParams } from '@dataui/crud-request';
-import { StudentByYear } from "src/db/view-entities/StudentByYear.entity";
-import { FindOptionsWhere, In, Not, IsNull } from "typeorm";
-import { IHeader } from "@shared/utils/exporter/types";
-import { AttReportWithReportMonth } from "src/db/view-entities/AttReportWithReportMonth.entity";
-import { getReportDateFilter } from "@shared/utils/entity/filters.util";
-import { ReportMonth, ReportMonthSemester } from "src/db/entities/ReportMonth.entity";
-import { KnownAbsenceWithReportMonth } from "src/db/view-entities/KnownAbsenceWithReportMonth.entity";
-import { Klass } from "src/db/entities/Klass.entity";
-import { formatPercent } from "@shared/utils/formatting/formatter.util";
-import { roundAllNumericProperties } from "@shared/utils/reportData.util";
-import { getAsNumberArray } from "@shared/utils/queryParam.util";
+import { StudentByYear } from 'src/db/view-entities/StudentByYear.entity';
+import { FindOptionsWhere, In, Not, IsNull } from 'typeorm';
+import { IHeader } from '@shared/utils/exporter/types';
+import { AttReportWithReportMonth } from 'src/db/view-entities/AttReportWithReportMonth.entity';
+import { getReportDateFilter } from '@shared/utils/entity/filters.util';
+import { ReportMonth, ReportMonthSemester } from 'src/db/entities/ReportMonth.entity';
+import { KnownAbsenceWithReportMonth } from 'src/db/view-entities/KnownAbsenceWithReportMonth.entity';
+import { Klass } from 'src/db/entities/Klass.entity';
+import { formatPercent } from '@shared/utils/formatting/formatter.util';
+import { roundAllNumericProperties } from '@shared/utils/reportData.util';
+import { getAsNumberArray } from '@shared/utils/queryParam.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: StudentByYear,
- service: StudentByYearService,
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'name', label: 'שם התלמידה' },
- { value: 'tz', label: 'תז התלמידה' },
- { value: 'year', label: 'שנה' },
- ];
- },
- }
- }
+ return {
+ entity: StudentByYear,
+ service: StudentByYearService,
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'name', label: 'שם התלמידה' },
+ { value: 'tz', label: 'תז התלמידה' },
+ { value: 'year', label: 'שנה' },
+ ];
+ },
+ },
+ };
}
interface IStudentAttendancePivot extends StudentByYear {
- total?: number;
- totalLessons?: number;
- totalKnownAbsences?: number;
- unApprovedAbsences?: number;
- absencePercentage?: string;
- totalAbsencePercentage?: string;
+ total?: number;
+ totalLessons?: number;
+ totalKnownAbsences?: number;
+ unApprovedAbsences?: number;
+ absencePercentage?: string;
+ totalAbsencePercentage?: string;
}
class StudentByYearService extends BaseEntityService {
- protected async populatePivotData(pivotName: string, list: T[], extra: any, filter: ParsedRequestParams['filter']) {
- const data = list as StudentByYear[];
- const studentIds = data.map(item => item.id);
- const studentMap: Record = data.reduce((a, b) => ({ ...a, [b.id]: b }), {});
- const yearFilter = filter.find(item => item.field === 'year');
- const klassReferenceIdFilter = filter.find(item => item.field === 'klassReferenceIds');
- const klassTypeReferenceIdFilter = filter.find(item => item.field === 'klassTypeReferenceIds');
- const klassReferenceIds = getAsNumberArray(extra.klassReferenceIds) || klassReferenceIdFilter?.value;
- const klassTypeReferenceIds = getAsNumberArray(extra.klassTypeReferenceIds) || klassTypeReferenceIdFilter?.value;
- const lessonIds = getAsNumberArray(extra?.lessonIds);
- const excludedLessonIds = getAsNumberArray(extra?.excludedLessonIds)
+ protected async populatePivotData(
+ pivotName: string,
+ list: T[],
+ extra: any,
+ filter: ParsedRequestParams['filter'],
+ ) {
+ const data = list as StudentByYear[];
+ const studentIds = data.map((item) => item.id);
+ const studentMap: Record = data.reduce((a, b) => ({ ...a, [b.id]: b }), {});
+ const yearFilter = filter.find((item) => item.field === 'year');
+ const klassReferenceIdFilter = filter.find((item) => item.field === 'klassReferenceIds');
+ const klassTypeReferenceIdFilter = filter.find((item) => item.field === 'klassTypeReferenceIds');
+ const klassReferenceIds = getAsNumberArray(extra.klassReferenceIds) || klassReferenceIdFilter?.value;
+ const klassTypeReferenceIds = getAsNumberArray(extra.klassTypeReferenceIds) || klassTypeReferenceIdFilter?.value;
+ const lessonIds = getAsNumberArray(extra?.lessonIds);
+ const excludedLessonIds = getAsNumberArray(extra?.excludedLessonIds);
- switch (pivotName) {
- case 'StudentAttendance': {
- const headers = {
- // add student tz and name to the headers
- };
+ switch (pivotName) {
+ case 'StudentAttendance': {
+ const headers = {
+ // add student tz and name to the headers
+ };
- // Note: year is now a single number, not an array
+ // Note: year is now a single number, not an array
- const baseWhere = {
- userId: data[0].userId,
- studentReferenceId: In(studentIds),
- klassReferenceId: Utils.getInFilter(klassReferenceIds),
- klass: Utils.getKlassFilter(klassTypeReferenceIds),
- lessonReferenceId: Utils.getInFilter(lessonIds),
- year: yearFilter?.value,
- reportDate: getReportDateFilter(extra?.fromDate, extra?.toDate),
- reportMonth: Utils.getReportMonthFilter(extra?.reportMonthReferenceId, extra?.semester),
- };
+ const baseWhere = {
+ userId: data[0].userId,
+ studentReferenceId: In(studentIds),
+ klassReferenceId: Utils.getInFilter(klassReferenceIds),
+ klass: Utils.getKlassFilter(klassTypeReferenceIds),
+ lessonReferenceId: Utils.getInFilter(lessonIds),
+ year: yearFilter?.value,
+ reportDate: getReportDateFilter(extra?.fromDate, extra?.toDate),
+ reportMonth: Utils.getReportMonthFilter(extra?.reportMonthReferenceId, extra?.semester),
+ };
- const pivotData = await this.dataSource
- .getRepository(AttReportWithReportMonth)
- .find({
- where: Utils.applyExcludedLessons(baseWhere, excludedLessonIds),
- relations: {
- klass: true,
- lesson: true,
- reportMonth: true,
- }
- });
+ const pivotData = await this.dataSource.getRepository(AttReportWithReportMonth).find({
+ where: Utils.applyExcludedLessons(baseWhere, excludedLessonIds),
+ relations: {
+ klass: true,
+ lesson: true,
+ reportMonth: true,
+ },
+ });
- pivotData.forEach(item => {
- // if (item.absCount === 0) {
- // return;
- // }
- const key = `${item.lessonReferenceId}`;
- headers[key] ??= { value: key, label: `${item.lesson?.name}` };
- studentMap[item.studentReferenceId][key] ??= 0;
- studentMap[item.studentReferenceId][key] += item.absCount;
- studentMap[item.studentReferenceId].total ??= 0;
- studentMap[item.studentReferenceId].total += item.absCount;
- studentMap[item.studentReferenceId].totalLessons ??= 0;
- studentMap[item.studentReferenceId].totalLessons += item.howManyLessons;
- });
+ pivotData.forEach((item) => {
+ // if (item.absCount === 0) {
+ // return;
+ // }
+ const key = `${item.lessonReferenceId}`;
+ headers[key] ??= { value: key, label: `${item.lesson?.name}` };
+ studentMap[item.studentReferenceId][key] ??= 0;
+ studentMap[item.studentReferenceId][key] += item.absCount;
+ studentMap[item.studentReferenceId].total ??= 0;
+ studentMap[item.studentReferenceId].total += item.absCount;
+ studentMap[item.studentReferenceId].totalLessons ??= 0;
+ studentMap[item.studentReferenceId].totalLessons += item.howManyLessons;
+ });
- const totalAbsencesData = await this.dataSource
- .getRepository(KnownAbsenceWithReportMonth)
- .find({
- where: Utils.applyExcludedLessons(
- { ...baseWhere, isApproved: true },
- excludedLessonIds,
- true
- ),
- relations: {
- klass: true,
- reportMonth: true,
- }
- });
+ const totalAbsencesData = await this.dataSource.getRepository(KnownAbsenceWithReportMonth).find({
+ where: Utils.applyExcludedLessons(
+ { ...baseWhere, isApproved: true },
+ excludedLessonIds,
+ true,
+ ),
+ relations: {
+ klass: true,
+ reportMonth: true,
+ },
+ });
- totalAbsencesData.forEach(item => {
- studentMap[item.studentReferenceId].totalKnownAbsences ??= 0;
- studentMap[item.studentReferenceId].totalKnownAbsences += item.absnceCount;
- });
+ totalAbsencesData.forEach((item) => {
+ studentMap[item.studentReferenceId].totalKnownAbsences ??= 0;
+ studentMap[item.studentReferenceId].totalKnownAbsences += item.absnceCount;
+ });
- Object.values(studentMap).forEach((student) => {
- const unApprovedAbsences = (student.total ?? 0) - (student.totalKnownAbsences ?? 0);
- const totalLessons = student.totalLessons ?? 1;
- student.unApprovedAbsences = unApprovedAbsences;
- student.absencePercentage = formatPercent(unApprovedAbsences / totalLessons, 2);
- student.totalAbsencePercentage = formatPercent((student.total ?? 0) / totalLessons, 2);
+ Object.values(studentMap).forEach((student) => {
+ const unApprovedAbsences = (student.total ?? 0) - (student.totalKnownAbsences ?? 0);
+ const totalLessons = student.totalLessons ?? 1;
+ student.unApprovedAbsences = unApprovedAbsences;
+ student.absencePercentage = formatPercent(unApprovedAbsences / totalLessons, 2);
+ student.totalAbsencePercentage = formatPercent((student.total ?? 0) / totalLessons, 2);
- roundAllNumericProperties(student);
- });
+ roundAllNumericProperties(student);
+ });
- headers['total'] = {
- value: 'total',
- label: 'סה"כ'
- };
- headers['totalKnownAbsences'] = {
- value: 'totalKnownAbsences',
- label: 'חיסורים מאושרים'
- };
- headers['unApprovedAbsences'] = {
- value: 'unApprovedAbsences',
- label: 'חיסורים לא מאושרים'
- };
- headers['totalLessons'] = {
- value: 'totalLessons',
- label: 'סה"כ שיעורים'
- };
- headers['absencePercentage'] = {
- value: 'absencePercentage',
- label: 'אחוז חיסורים'
- };
- headers['totalAbsencePercentage'] = {
- value: 'totalAbsencePercentage',
- label: 'אחוז חיסורים כולל'
- };
+ headers['total'] = {
+ value: 'total',
+ label: 'סה"כ',
+ };
+ headers['totalKnownAbsences'] = {
+ value: 'totalKnownAbsences',
+ label: 'חיסורים מאושרים',
+ };
+ headers['unApprovedAbsences'] = {
+ value: 'unApprovedAbsences',
+ label: 'חיסורים לא מאושרים',
+ };
+ headers['totalLessons'] = {
+ value: 'totalLessons',
+ label: 'סה"כ שיעורים',
+ };
+ headers['absencePercentage'] = {
+ value: 'absencePercentage',
+ label: 'אחוז חיסורים',
+ };
+ headers['totalAbsencePercentage'] = {
+ value: 'totalAbsencePercentage',
+ label: 'אחוז חיסורים כולל',
+ };
- (data[0] as any).headers = Object.values(headers);
- }
- }
+ (data[0] as any).headers = Object.values(headers);
+ }
}
+ }
}
export const Utils = {
- getReportMonthFilter(id: number, semester: ReportMonthSemester): FindOptionsWhere {
- const filter = { id, semester };
- for (const key in filter) {
- if (!filter[key]) {
- delete filter[key];
- }
- }
- if (Object.keys(filter).length > 0) {
- return filter;
- }
- },
- getInFilter(value: any) {
- if (value) {
- return Array.isArray(value) ? In(value) : value;
- }
- },
- getKlassFilter(klassTypeReferenceId: any): FindOptionsWhere {
- const filter = Utils.getInFilter(klassTypeReferenceId);
- if (filter) {
- return { klassTypeReferenceId: filter };
- }
- },
- applyExcludedLessons(where: FindOptionsWhere, excludedLessonIds: number[], includeNull = false): FindOptionsWhere | FindOptionsWhere[] {
- if (!excludedLessonIds?.length) return where;
- const withExclusion: FindOptionsWhere = { ...where, lessonReferenceId: Not(In(excludedLessonIds)) };
- if (includeNull) {
- return [withExclusion, { ...where, lessonReferenceId: IsNull() }];
- }
- return withExclusion;
+ getReportMonthFilter(id: number, semester: ReportMonthSemester): FindOptionsWhere {
+ const filter = { id, semester };
+ for (const key in filter) {
+ if (!filter[key]) {
+ delete filter[key];
+ }
+ }
+ if (Object.keys(filter).length > 0) {
+ return filter;
+ }
+ },
+ getInFilter(value: any) {
+ if (value) {
+ return Array.isArray(value) ? In(value) : value;
+ }
+ },
+ getKlassFilter(klassTypeReferenceId: any): FindOptionsWhere {
+ const filter = Utils.getInFilter(klassTypeReferenceId);
+ if (filter) {
+ return { klassTypeReferenceId: filter };
+ }
+ },
+ applyExcludedLessons(
+ where: FindOptionsWhere,
+ excludedLessonIds: number[],
+ includeNull = false,
+ ): FindOptionsWhere | FindOptionsWhere[] {
+ if (!excludedLessonIds?.length) return where;
+ const withExclusion: FindOptionsWhere = { ...where, lessonReferenceId: Not(In(excludedLessonIds)) };
+ if (includeNull) {
+ return [withExclusion, { ...where, lessonReferenceId: IsNull() }];
}
+ return withExclusion;
+ },
};
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/student-klass-report.config.ts b/server/src/entity-modules/student-klass-report.config.ts
index b588de7e..bc235cb9 100644
--- a/server/src/entity-modules/student-klass-report.config.ts
+++ b/server/src/entity-modules/student-klass-report.config.ts
@@ -1,61 +1,61 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { StudentKlassReport } from "src/db/view-entities/StudentKlassReport.entity";
-import { CommonReportData } from "@shared/utils/report/types";
-import studentReportCard from "../reports/studentReportCard";
-import { BulkToPdfReportGenerator } from "@shared/utils/report/bulk-to-pdf.generator";
-import studentReportCardReact from "src/reports/studentReportCardReact";
-import { generateStudentReportCard } from "src/reports/reportGenerator";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { StudentKlassReport } from 'src/db/view-entities/StudentKlassReport.entity';
+import { CommonReportData } from '@shared/utils/report/types';
+import studentReportCard from '../reports/studentReportCard';
+import { BulkToPdfReportGenerator } from '@shared/utils/report/bulk-to-pdf.generator';
+import studentReportCardReact from 'src/reports/studentReportCardReact';
+import { generateStudentReportCard } from 'src/reports/reportGenerator';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: StudentKlassReport,
- query: {
- join: {
- student: { eager: false },
- },
- },
- service: StudentKlassReportService,
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- student: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders() {
- return [
- { value: 'student.tz', label: 'תז' },
- { value: 'student.name', label: 'שם' },
- { value: 'student.comment', label: 'הערה' },
- { value: 'student.phone', label: 'טלפון' },
- { value: 'student.address', label: 'כתובת' },
- { value: 'year', label: 'שנה' },
- { value: 'klassName1', label: 'כיתת אם' },
- { value: 'klassName2', label: 'מסלול' },
- { value: 'klassName3', label: 'התמחות' },
- { value: 'klassNameNull', label: 'אחר' },
- ]
- },
- }
- }
+ return {
+ entity: StudentKlassReport,
+ query: {
+ join: {
+ student: { eager: false },
+ },
+ },
+ service: StudentKlassReportService,
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ student: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders() {
+ return [
+ { value: 'student.tz', label: 'תז' },
+ { value: 'student.name', label: 'שם' },
+ { value: 'student.comment', label: 'הערה' },
+ { value: 'student.phone', label: 'טלפון' },
+ { value: 'student.address', label: 'כתובת' },
+ { value: 'year', label: 'שנה' },
+ { value: 'klassName1', label: 'כיתת אם' },
+ { value: 'klassName2', label: 'מסלול' },
+ { value: 'klassName3', label: 'התמחות' },
+ { value: 'klassNameNull', label: 'אחר' },
+ ];
+ },
+ },
+ };
}
class StudentKlassReportService extends BaseEntityService {
- reportsDict = {
- studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
- studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
- };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const userId = getUserIdFromUser(req.auth);
- const generator = this.reportsDict[req.parsed.extra.report];
- return generateStudentReportCard(userId, req.parsed.extra, generator);
- }
- return super.getReportData(req);
+ reportsDict = {
+ studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
+ studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
+ };
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const userId = getUserIdFromUser(req.auth);
+ const generator = this.reportsDict[req.parsed.extra.report];
+ return generateStudentReportCard(userId, req.parsed.extra, generator);
}
+ return super.getReportData(req);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/student-klass.config.ts b/server/src/entity-modules/student-klass.config.ts
index 2a863aca..f6e24f74 100644
--- a/server/src/entity-modules/student-klass.config.ts
+++ b/server/src/entity-modules/student-klass.config.ts
@@ -1,82 +1,83 @@
-import { CrudRequest } from "@dataui/crud";
-import { In } from "typeorm";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { BulkToPdfReportGenerator } from "@shared/utils/report/bulk-to-pdf.generator";
-import { CommonReportData } from "@shared/utils/report/types";
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
-import { generateStudentReportCard } from "src/reports/reportGenerator";
-import studentReportCard from "src/reports/studentReportCard";
-import studentReportCardReact from "src/reports/studentReportCardReact";
-import { fixReferences } from "@shared/utils/entity/fixReference.util";
-import { getAsNumberArray } from "@shared/utils/queryParam.util";
+import { CrudRequest } from '@dataui/crud';
+import { In } from 'typeorm';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { BulkToPdfReportGenerator } from '@shared/utils/report/bulk-to-pdf.generator';
+import { CommonReportData } from '@shared/utils/report/types';
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
+import { generateStudentReportCard } from 'src/reports/reportGenerator';
+import studentReportCard from 'src/reports/studentReportCard';
+import studentReportCardReact from 'src/reports/studentReportCardReact';
+import { fixReferences } from '@shared/utils/entity/fixReference.util';
+import { getAsNumberArray } from '@shared/utils/queryParam.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: StudentKlass,
- query: {
- join: {
- student: { eager: false },
- klass: { eager: false },
- },
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- student: { eager: true },
- klass: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'student.tz', label: 'תז' },
- { value: 'student.name', label: 'שם התלמידה' },
- { value: 'klass.key', label: 'קוד כיתה' },
- { value: 'klass.name', label: 'כיתה' },
- ];
- }
- },
- service: StudentKlassService
- }
+ return {
+ entity: StudentKlass,
+ query: {
+ join: {
+ student: { eager: false },
+ klass: { eager: false },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ student: { eager: true },
+ klass: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'student.tz', label: 'תז' },
+ { value: 'student.name', label: 'שם התלמידה' },
+ { value: 'klass.key', label: 'קוד כיתה' },
+ { value: 'klass.name', label: 'כיתה' },
+ ];
+ },
+ },
+ service: StudentKlassService,
+ };
}
class StudentKlassService extends BaseEntityService {
- reportsDict = {
- studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
- studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
- };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const userId = getUserIdFromUser(req.auth);
- const generator = this.reportsDict[req.parsed.extra.report];
- const ids = getAsNumberArray(req.parsed.extra.ids);
- if (!ids) return { generator, params: [] };
- const studentIds = await this.dataSource.getRepository(StudentKlass)
- .find({ where: { id: In(ids) }, select: { studentReferenceId: true } })
- .then(res => res.map(item => item.studentReferenceId));
- const extraParams = { ...req.parsed.extra, ids: studentIds };
- return generateStudentReportCard(userId, extraParams, generator);
- }
- return super.getReportData(req);
+ reportsDict = {
+ studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
+ studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
+ };
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const userId = getUserIdFromUser(req.auth);
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ if (!ids) return { generator, params: [] };
+ const studentIds = await this.dataSource
+ .getRepository(StudentKlass)
+ .find({ where: { id: In(ids) }, select: { studentReferenceId: true } })
+ .then((res) => res.map((item) => item.studentReferenceId));
+ const extraParams = { ...req.parsed.extra, ids: studentIds };
+ return generateStudentReportCard(userId, extraParams, generator);
}
+ return super.getReportData(req);
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'fixReferences': {
- const ids = getAsNumberArray(req.parsed.extra.ids);
- if (!ids) return 'לא נבחרו רשומות';
- const referenceFields = {
- studentTz: 'studentReferenceId',
- klassId: 'klassReferenceId',
- };
- return fixReferences(this.dataSource.getRepository(StudentKlass), ids, referenceFields);
- }
- }
- return super.doAction(req, body);
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'fixReferences': {
+ const ids = getAsNumberArray(req.parsed.extra.ids);
+ if (!ids) return 'לא נבחרו רשומות';
+ const referenceFields = {
+ studentTz: 'studentReferenceId',
+ klassId: 'klassReferenceId',
+ };
+ return fixReferences(this.dataSource.getRepository(StudentKlass), ids, referenceFields);
+ }
}
+ return super.doAction(req, body);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/student-percent-report.config.ts b/server/src/entity-modules/student-percent-report.config.ts
index ccc33319..7effbdc3 100644
--- a/server/src/entity-modules/student-percent-report.config.ts
+++ b/server/src/entity-modules/student-percent-report.config.ts
@@ -1,180 +1,219 @@
-import { CrudRequest } from "@dataui/crud";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { getPercentsFormatter } from "@shared/utils/formatting/formatter.util";
-import { AbsCountEffectByUser } from "src/db/view-entities/AbsCountEffectByUser.entity";
-import { GradeEffectByUser } from "src/db/view-entities/GradeEffectByUser.entity";
-import { AttGradeEffect } from "src/db/entities/AttGradeEffect";
-import { GradeName } from "src/db/entities/GradeName.entity";
-import { AttendanceName } from "src/db/entities/AttendanceName.entity";
-import { KnownAbsence } from "src/db/entities/KnownAbsence.entity";
-import { Lesson } from "src/db/entities/Lesson.entity";
-import { AttReportAndGrade } from "src/db/view-entities/AttReportAndGrade.entity";
-import { StudentPercentReport } from "src/db/view-entities/StudentPercentReport.entity";
-import { calcSum, getUniqueValues, groupDataByKeys, groupDataByKeysAndCalc } from "@shared/utils/reportData.util";
-import { calcReportsData, getDisplayGrade, getDisplayAttendance, getUnknownAbsCount, getRelevantGrade } from "src/utils/studentReportData.util";
-import { getKnownAbsenceFilterBySprAndDates, getReportDataFilterBySprAndDates } from "src/utils/studentReportData.util";
-import { DataSource, In } from "typeorm";
+import { CrudRequest } from '@dataui/crud';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { getPercentsFormatter } from '@shared/utils/formatting/formatter.util';
+import { AbsCountEffectByUser } from 'src/db/view-entities/AbsCountEffectByUser.entity';
+import { GradeEffectByUser } from 'src/db/view-entities/GradeEffectByUser.entity';
+import { AttGradeEffect } from 'src/db/entities/AttGradeEffect';
+import { GradeName } from 'src/db/entities/GradeName.entity';
+import { AttendanceName } from 'src/db/entities/AttendanceName.entity';
+import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity';
+import { Lesson } from 'src/db/entities/Lesson.entity';
+import { AttReportAndGrade } from 'src/db/view-entities/AttReportAndGrade.entity';
+import { StudentPercentReport } from 'src/db/view-entities/StudentPercentReport.entity';
+import { calcSum, getUniqueValues, groupDataByKeys, groupDataByKeysAndCalc } from '@shared/utils/reportData.util';
+import {
+ calcReportsData,
+ getDisplayGrade,
+ getDisplayAttendance,
+ getUnknownAbsCount,
+ getRelevantGrade,
+} from 'src/utils/studentReportData.util';
+import { getKnownAbsenceFilterBySprAndDates, getReportDataFilterBySprAndDates } from 'src/utils/studentReportData.util';
+import { DataSource, In } from 'typeorm';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: StudentPercentReport,
- query: {
- join: {
- student: {},
- teacher: {},
- lesson: {},
- klass: { eager: true },
- studentBaseKlass: { eager: true },
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- student: { eager: true },
- teacher: { eager: true },
- klass: { eager: true },
- lesson: { eager: true },
- studentBaseKlass: { eager: true },
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'teacher.name', label: 'שם המורה' },
- { value: 'student.name', label: 'שם התלמידה' },
- { value: 'student.tz', label: 'תז התלמידה' },
- { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'lessonsCount', label: 'מספר שיעורים' },
- { value: 'absCount', label: 'מספר חיסורים' },
- { value: getPercentsFormatter('absPercents'), label: 'אחוז חיסור' },
- { value: getPercentsFormatter('attPercents'), label: 'אחוז נוכחות' },
- { value: getPercentsFormatter('gradeAvg'), label: 'ציון ממוצע' },
- ];
- }
- },
- service: StudentPercentReportService,
- }
+ return {
+ entity: StudentPercentReport,
+ query: {
+ join: {
+ student: {},
+ teacher: {},
+ lesson: {},
+ klass: { eager: true },
+ studentBaseKlass: { eager: true },
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ student: { eager: true },
+ teacher: { eager: true },
+ klass: { eager: true },
+ lesson: { eager: true },
+ studentBaseKlass: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'teacher.name', label: 'שם המורה' },
+ { value: 'student.name', label: 'שם התלמידה' },
+ { value: 'student.tz', label: 'תז התלמידה' },
+ { value: 'studentBaseKlass.klassName', label: 'כיתת בסיס' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'lessonsCount', label: 'מספר שיעורים' },
+ { value: 'absCount', label: 'מספר חיסורים' },
+ { value: getPercentsFormatter('absPercents'), label: 'אחוז חיסור' },
+ { value: getPercentsFormatter('attPercents'), label: 'אחוז נוכחות' },
+ { value: getPercentsFormatter('gradeAvg'), label: 'ציון ממוצע' },
+ ];
+ },
+ },
+ service: StudentPercentReportService,
+ };
}
interface StudentPercentReportWithDates extends StudentPercentReport {
- approvedAbsCount?: number;
- attGradeEffect?: number;
- finalGrade?: string;
- finalAttendance?: string;
- estimation?: string;
- comments?: string;
- debug?: any;
+ approvedAbsCount?: number;
+ attGradeEffect?: number;
+ finalGrade?: string;
+ finalAttendance?: string;
+ estimation?: string;
+ comments?: string;
+ debug?: any;
}
class StudentPercentReportService extends BaseEntityService {
- protected async populatePivotData(pivotName: string, list: T[], extra: any, filter: any, auth: any) {
- const data = list as StudentPercentReport[];
- const sprIds = data.map(item => item.id);
- const sprMap: Record = data.reduce((a, b) => ({ ...a, [b.id]: b }), {});
-
-
- switch (pivotName) {
- case 'PercentReportWithDates': {
- const pivotData = await this.dataSource
- .getRepository(AttReportAndGrade)
- .find({ where: getReportDataFilterBySprAndDates(sprIds, extra?.fromDate, extra?.toDate), order: { reportDate: 'ASC' } });
- const pivotDataMap = groupDataByKeys(pivotData, ['studentReferenceId', 'teacherReferenceId', 'klassReferenceId', 'lessonReferenceId', 'userId', 'year']);
-
- const totalAbsencesData = await this.dataSource
- .getRepository(KnownAbsence)
- .find({ where: getKnownAbsenceFilterBySprAndDates(sprIds, extra?.fromDate, extra?.toDate) });
- const totalAbsencesDataMap = groupDataByKeys(totalAbsencesData, ['studentReferenceId', 'klassReferenceId', 'lessonReferenceId', 'userId', 'year']);
-
- const estimatedLessonCount = await this.dataSource
- .getRepository(Lesson)
- .find({ where: { id: In(getUniqueValues(pivotData, item => item.lessonReferenceId)) } });
- const estimatedLessonCountMap = groupDataByKeysAndCalc(estimatedLessonCount, ['id'], items => ({ howManyLessons: calcSum(items, item => item.howManyLessons) }));
-
- Object.entries(sprMap).forEach(([key, val]) => {
- const reports = pivotDataMap[key] ?? [];
- const knownAbsKey = [val.studentReferenceId, val.klassReferenceId, val.lessonReferenceId, val.userId, val.year].map(String).join('_');
- const knownAbs = totalAbsencesDataMap[knownAbsKey] ?? [];
- const estimatedLessonCount = estimatedLessonCountMap[val.lessonReferenceId]?.howManyLessons ?? 0;
-
- const reportData = calcReportsData(reports, knownAbs, estimatedLessonCount);
- val.lessonsCount = reportData.lessonsCount;
- val.absCount = reportData.absCount;
- val.approvedAbsCount = reportData.approvedAbsCount;
- val.absPercents = reportData.absPercents;
- val.attPercents = reportData.attPercents;
- val.gradeAvg = getRelevantGrade(extra?.lastGrade, reportData.gradeAvg, reportData.lastGrade, reportData.maxGrade);
-
- const gradeReports = reports.filter(item => item.type === 'grade');
- val.estimation = getUniqueValues(gradeReports, item => item.estimation).join(', ');
- val.comments = getUniqueValues(gradeReports, item => item.comments).join(', ');
- });
-
- const [absCountEffectsMap, gradeEffectsMap] = await getAbsGradeEffect(Object.values(sprMap), this.dataSource);
- const gradeNames = await this.dataSource.getRepository(GradeName)
- .find({ where: { userId: getUserIdFromUser(auth) }, order: { key: 'DESC' } });
- const attendanceNames = await this.dataSource.getRepository(AttendanceName)
- .find({ where: { userId: getUserIdFromUser(auth) }, order: { key: 'DESC' } });
-
- Object.values(sprMap).forEach(item => {
- item.debug = {
- absCountEffectId: getAbsCountEffectId(item),
- gradeEffectId: getGradeEffectId(item),
- absCountEffect: absCountEffectsMap[getAbsCountEffectId(item)],
- gradeEffect: gradeEffectsMap[getGradeEffectId(item)],
- };
- item.attGradeEffect = gradeEffectsMap[getGradeEffectId(item)] || absCountEffectsMap[getAbsCountEffectId(item)];
- item.finalGrade = getDisplayGrade(item.gradeAvg, item.attGradeEffect, gradeNames);
- item.finalAttendance = getDisplayAttendance(item.attPercents, attendanceNames);
- });
-
- const headers = {};
- headers['attGradeEffect'] = { value: 'attGradeEffect', label: 'קשר נוכחות ציון' };
- headers['finalGrade'] = { value: 'finalGrade', label: 'ציון סופי' };
- headers['finalAttendance'] = { value: 'finalAttendance', label: 'נוכחות סופית' };
- headers['estimation'] = { value: 'estimation', label: 'הערכה' };
- headers['comments'] = { value: 'comments', label: 'הערה' };
- headers['estimatedAbsPercents'] = { value: 'estimatedAbsPercents', label: 'אחוז חיסור משוער' };
- (data[0] as any).headers = Object.values(headers);
- }
- }
+ protected async populatePivotData(pivotName: string, list: T[], extra: any, filter: any, auth: any) {
+ const data = list as StudentPercentReport[];
+ const sprIds = data.map((item) => item.id);
+ const sprMap: Record = data.reduce((a, b) => ({ ...a, [b.id]: b }), {});
+
+ switch (pivotName) {
+ case 'PercentReportWithDates': {
+ const pivotData = await this.dataSource
+ .getRepository(AttReportAndGrade)
+ .find({
+ where: getReportDataFilterBySprAndDates(sprIds, extra?.fromDate, extra?.toDate),
+ order: { reportDate: 'ASC' },
+ });
+ const pivotDataMap = groupDataByKeys(pivotData, [
+ 'studentReferenceId',
+ 'teacherReferenceId',
+ 'klassReferenceId',
+ 'lessonReferenceId',
+ 'userId',
+ 'year',
+ ]);
+
+ const totalAbsencesData = await this.dataSource
+ .getRepository(KnownAbsence)
+ .find({ where: getKnownAbsenceFilterBySprAndDates(sprIds, extra?.fromDate, extra?.toDate) });
+ const totalAbsencesDataMap = groupDataByKeys(totalAbsencesData, [
+ 'studentReferenceId',
+ 'klassReferenceId',
+ 'lessonReferenceId',
+ 'userId',
+ 'year',
+ ]);
+
+ const estimatedLessonCount = await this.dataSource
+ .getRepository(Lesson)
+ .find({ where: { id: In(getUniqueValues(pivotData, (item) => item.lessonReferenceId)) } });
+ const estimatedLessonCountMap = groupDataByKeysAndCalc(estimatedLessonCount, ['id'], (items) => ({
+ howManyLessons: calcSum(items, (item) => item.howManyLessons),
+ }));
+
+ Object.entries(sprMap).forEach(([key, val]) => {
+ const reports = pivotDataMap[key] ?? [];
+ const knownAbsKey = [
+ val.studentReferenceId,
+ val.klassReferenceId,
+ val.lessonReferenceId,
+ val.userId,
+ val.year,
+ ]
+ .map(String)
+ .join('_');
+ const knownAbs = totalAbsencesDataMap[knownAbsKey] ?? [];
+ const estimatedLessonCount = estimatedLessonCountMap[val.lessonReferenceId]?.howManyLessons ?? 0;
+
+ const reportData = calcReportsData(reports, knownAbs, estimatedLessonCount);
+ val.lessonsCount = reportData.lessonsCount;
+ val.absCount = reportData.absCount;
+ val.approvedAbsCount = reportData.approvedAbsCount;
+ val.absPercents = reportData.absPercents;
+ val.attPercents = reportData.attPercents;
+ val.gradeAvg = getRelevantGrade(
+ extra?.lastGrade,
+ reportData.gradeAvg,
+ reportData.lastGrade,
+ reportData.maxGrade,
+ );
+
+ const gradeReports = reports.filter((item) => item.type === 'grade');
+ val.estimation = getUniqueValues(gradeReports, (item) => item.estimation).join(', ');
+ val.comments = getUniqueValues(gradeReports, (item) => item.comments).join(', ');
+ });
+
+ const [absCountEffectsMap, gradeEffectsMap] = await getAbsGradeEffect(Object.values(sprMap), this.dataSource);
+ const gradeNames = await this.dataSource
+ .getRepository(GradeName)
+ .find({ where: { userId: getUserIdFromUser(auth) }, order: { key: 'DESC' } });
+ const attendanceNames = await this.dataSource
+ .getRepository(AttendanceName)
+ .find({ where: { userId: getUserIdFromUser(auth) }, order: { key: 'DESC' } });
+
+ Object.values(sprMap).forEach((item) => {
+ item.debug = {
+ absCountEffectId: getAbsCountEffectId(item),
+ gradeEffectId: getGradeEffectId(item),
+ absCountEffect: absCountEffectsMap[getAbsCountEffectId(item)],
+ gradeEffect: gradeEffectsMap[getGradeEffectId(item)],
+ };
+ item.attGradeEffect =
+ gradeEffectsMap[getGradeEffectId(item)] || absCountEffectsMap[getAbsCountEffectId(item)];
+ item.finalGrade = getDisplayGrade(item.gradeAvg, item.attGradeEffect, gradeNames);
+ item.finalAttendance = getDisplayAttendance(item.attPercents, attendanceNames);
+ });
+
+ const headers = {};
+ headers['attGradeEffect'] = { value: 'attGradeEffect', label: 'קשר נוכחות ציון' };
+ headers['finalGrade'] = { value: 'finalGrade', label: 'ציון סופי' };
+ headers['finalAttendance'] = { value: 'finalAttendance', label: 'נוכחות סופית' };
+ headers['estimation'] = { value: 'estimation', label: 'הערכה' };
+ headers['comments'] = { value: 'comments', label: 'הערה' };
+ headers['estimatedAbsPercents'] = { value: 'estimatedAbsPercents', label: 'אחוז חיסור משוער' };
+ (data[0] as any).headers = Object.values(headers);
+ }
}
+ }
}
async function getAbsGradeEffect(values: StudentPercentReportWithDates[], dataSource: DataSource) {
- const uniqueAbsCountEffectIds = getUniqueValues(values, getAbsCountEffectId);
- const uniqueGradeEffectIds = getUniqueValues(values, getGradeEffectId);
+ const uniqueAbsCountEffectIds = getUniqueValues(values, getAbsCountEffectId);
+ const uniqueGradeEffectIds = getUniqueValues(values, getGradeEffectId);
- const [absCountEffectsMap, gradeEffectsMap] = await Promise.all([
- fetchAttGradeEffect(dataSource, AbsCountEffectByUser, uniqueAbsCountEffectIds),
- fetchAttGradeEffect(dataSource, GradeEffectByUser, uniqueGradeEffectIds),
- ]);
+ const [absCountEffectsMap, gradeEffectsMap] = await Promise.all([
+ fetchAttGradeEffect(dataSource, AbsCountEffectByUser, uniqueAbsCountEffectIds),
+ fetchAttGradeEffect(dataSource, GradeEffectByUser, uniqueGradeEffectIds),
+ ]);
- return [absCountEffectsMap, gradeEffectsMap];
+ return [absCountEffectsMap, gradeEffectsMap];
}
function getAbsCountEffectId(item: StudentPercentReportWithDates): string {
- const unKnownAbsCount = getUnknownAbsCount(item.absCount, item.approvedAbsCount);
- return `${item.userId}_${Math.floor(unKnownAbsCount)}`;
+ const unKnownAbsCount = getUnknownAbsCount(item.absCount, item.approvedAbsCount);
+ return `${item.userId}_${Math.floor(unKnownAbsCount)}`;
}
function getGradeEffectId(item: StudentPercentReportWithDates): string {
- return `${item.userId}_${Math.floor(item.attPercents * 100)}`;
+ return `${item.userId}_${Math.floor(item.attPercents * 100)}`;
}
function fetchAttGradeEffect(dataSource: DataSource, viewEntity: any, ids: string[]): Promise> {
- return dataSource
- .getRepository(viewEntity)
- .find({
- where: {
- id: In(ids),
- },
- select: ['id', 'effect'],
- })
- .then(arr => Object.fromEntries(arr.map(item => [item.id, Number(item.effect)])));
+ return dataSource
+ .getRepository(viewEntity)
+ .find({
+ where: {
+ id: In(ids),
+ },
+ select: ['id', 'effect'],
+ })
+ .then((arr) => Object.fromEntries(arr.map((item) => [item.id, Number(item.effect)])));
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/student.config.ts b/server/src/entity-modules/student.config.ts
index 9fe4d983..b1f22bc5 100644
--- a/server/src/entity-modules/student.config.ts
+++ b/server/src/entity-modules/student.config.ts
@@ -1,68 +1,65 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { getHebrewBooleanFormatter } from "@shared/utils/formatting/formatter.util";
-import { Student } from "src/db/entities/Student.entity";
-import { CommonReportData } from "@shared/utils/report/types";
-import studentReportCard from "../reports/studentReportCard";
-import { BulkToPdfReportGenerator } from "@shared/utils/report/bulk-to-pdf.generator";
-import studentReportCardReact from "src/reports/studentReportCardReact";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { generateStudentReportCard } from "src/reports/reportGenerator";
-import { In } from "typeorm";
-import { getAsArray, getAsBoolean } from "@shared/utils/queryParam.util";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { getHebrewBooleanFormatter } from '@shared/utils/formatting/formatter.util';
+import { Student } from 'src/db/entities/Student.entity';
+import { CommonReportData } from '@shared/utils/report/types';
+import studentReportCard from '../reports/studentReportCard';
+import { BulkToPdfReportGenerator } from '@shared/utils/report/bulk-to-pdf.generator';
+import studentReportCardReact from 'src/reports/studentReportCardReact';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { generateStudentReportCard } from 'src/reports/reportGenerator';
+import { In } from 'typeorm';
+import { getAsArray, getAsBoolean } from '@shared/utils/queryParam.util';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: Student,
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'tz', label: 'תז' },
- { value: 'name', label: 'שם' },
- { value: 'comment', label: 'הערה' },
- { value: 'phone', label: 'טלפון' },
- { value: 'year', label: 'כתובת' },
- { value: getHebrewBooleanFormatter('isActive'), label: 'פעיל' },
- ];
- }
- },
- service: StudentService,
- }
+ return {
+ entity: Student,
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'tz', label: 'תז' },
+ { value: 'name', label: 'שם' },
+ { value: 'comment', label: 'הערה' },
+ { value: 'phone', label: 'טלפון' },
+ { value: 'year', label: 'כתובת' },
+ { value: getHebrewBooleanFormatter('isActive'), label: 'פעיל' },
+ ];
+ },
+ },
+ service: StudentService,
+ };
}
class StudentService extends BaseEntityService {
- reportsDict = {
- studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
- studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
- };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- const userId = getUserIdFromUser(req.auth);
- const generator = this.reportsDict[req.parsed.extra.report];
- return generateStudentReportCard(userId, req.parsed.extra, generator);
- }
- return super.getReportData(req);
+ reportsDict = {
+ studentReportCard: new BulkToPdfReportGenerator(studentReportCard),
+ studentReportCardReact: new BulkToPdfReportGenerator(studentReportCardReact),
+ };
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ const userId = getUserIdFromUser(req.auth);
+ const generator = this.reportsDict[req.parsed.extra.report];
+ return generateStudentReportCard(userId, req.parsed.extra, generator);
}
+ return super.getReportData(req);
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'bulkUpdateActive': {
- const ids = getAsArray(req.parsed.extra.ids);
- const isActive = getAsBoolean(req.parsed.extra.isActive) ?? false;
- if (!ids) return 'לא נבחרו רשומות';
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'bulkUpdateActive': {
+ const ids = getAsArray(req.parsed.extra.ids);
+ const isActive = getAsBoolean(req.parsed.extra.isActive) ?? false;
+ if (!ids) return 'לא נבחרו רשומות';
- const result = await this.dataSource.getRepository(Student).update(
- { id: In(ids) },
- { isActive }
- );
+ const result = await this.dataSource.getRepository(Student).update({ id: In(ids) }, { isActive });
- return `עודכנו ${result.affected} תלמידים`;
- }
- }
- return super.doAction(req, body);
+ return `עודכנו ${result.affected} תלמידים`;
+ }
}
+ return super.doAction(req, body);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/teacher-grade-report-status.config.ts b/server/src/entity-modules/teacher-grade-report-status.config.ts
index 0b34e42c..a200d7f2 100644
--- a/server/src/entity-modules/teacher-grade-report-status.config.ts
+++ b/server/src/entity-modules/teacher-grade-report-status.config.ts
@@ -1,56 +1,56 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { BulkToZipReportGenerator } from "@shared/utils/report/bulk-to-zip.generator";
-import { CommonReportData } from "@shared/utils/report/types";
-import { TeacherGradeReportStatus } from "src/db/view-entities/TeacherGradeReportStatus.entity";
-import teacherReportFile from "src/reports/teacherReportFile";
-import { getTeacherStatusFileReportParams, sendTeacherReportFileMail } from "src/reports/reportGenerator";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { BulkToZipReportGenerator } from '@shared/utils/report/bulk-to-zip.generator';
+import { CommonReportData } from '@shared/utils/report/types';
+import { TeacherGradeReportStatus } from 'src/db/view-entities/TeacherGradeReportStatus.entity';
+import teacherReportFile from 'src/reports/teacherReportFile';
+import { getTeacherStatusFileReportParams, sendTeacherReportFileMail } from 'src/reports/reportGenerator';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: TeacherGradeReportStatus,
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'teacherName', label: 'מורה' },
- { value: 'reportMonthName', label: 'תקופת דיווח' },
- { value: 'reportedLessonNames', label: 'שיעורים שדווחו' },
- { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' },
- ];
- }
- },
- service: TeacherGradeReportStatusService,
- }
+ return {
+ entity: TeacherGradeReportStatus,
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'teacherName', label: 'מורה' },
+ { value: 'reportMonthName', label: 'תקופת דיווח' },
+ { value: 'reportedLessonNames', label: 'שיעורים שדווחו' },
+ { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' },
+ ];
+ },
+ },
+ service: TeacherGradeReportStatusService,
+ };
}
class TeacherGradeReportStatusService extends BaseEntityService {
- reportsDict = {
- teacherReportFile: new BulkToZipReportGenerator(() => 'קבצי ציונים למורות', teacherReportFile),
- };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- req.parsed.extra.isGrades = true;
- const generator = this.reportsDict[req.parsed.extra.report];
- const params = getTeacherStatusFileReportParams(req);
- return {
- generator,
- params,
- };
- }
- return super.getReportData(req);
+ reportsDict = {
+ teacherReportFile: new BulkToZipReportGenerator(() => 'קבצי ציונים למורות', teacherReportFile),
+ };
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ req.parsed.extra.isGrades = true;
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const params = getTeacherStatusFileReportParams(req);
+ return {
+ generator,
+ params,
+ };
}
+ return super.getReportData(req);
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'teacherReportFile': {
- req.parsed.extra.isGrades = true;
- return sendTeacherReportFileMail(req, this.dataSource, this.mailSendService);
- }
- }
- return super.doAction(req, body);
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'teacherReportFile': {
+ req.parsed.extra.isGrades = true;
+ return sendTeacherReportFileMail(req, this.dataSource, this.mailSendService);
+ }
}
+ return super.doAction(req, body);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/teacher-report-status.config.ts b/server/src/entity-modules/teacher-report-status.config.ts
index cdae7dec..1ae5eb3d 100644
--- a/server/src/entity-modules/teacher-report-status.config.ts
+++ b/server/src/entity-modules/teacher-report-status.config.ts
@@ -1,56 +1,56 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityService } from "@shared/base-entity/base-entity.service";
-import { BaseEntityModuleOptions, Entity } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { BulkToZipReportGenerator } from "@shared/utils/report/bulk-to-zip.generator";
-import { CommonReportData } from "@shared/utils/report/types";
-import { TeacherReportStatus } from "src/db/view-entities/TeacherReportStatus.entity";
-import teacherReportFile from "src/reports/teacherReportFile";
-import { getTeacherStatusFileReportParams, sendTeacherReportFileMail } from "src/reports/reportGenerator";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityService } from '@shared/base-entity/base-entity.service';
+import { BaseEntityModuleOptions, Entity } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { BulkToZipReportGenerator } from '@shared/utils/report/bulk-to-zip.generator';
+import { CommonReportData } from '@shared/utils/report/types';
+import { TeacherReportStatus } from 'src/db/view-entities/TeacherReportStatus.entity';
+import teacherReportFile from 'src/reports/teacherReportFile';
+import { getTeacherStatusFileReportParams, sendTeacherReportFileMail } from 'src/reports/reportGenerator';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: TeacherReportStatus,
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'teacherName', label: 'מורה' },
- { value: 'reportMonthName', label: 'תקופת דיווח' },
- { value: 'reportedLessonNames', label: 'שיעורים שדווחו' },
- { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' },
- ];
- }
- },
- service: TeacherReportStatusService,
- }
+ return {
+ entity: TeacherReportStatus,
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'teacherName', label: 'מורה' },
+ { value: 'reportMonthName', label: 'תקופת דיווח' },
+ { value: 'reportedLessonNames', label: 'שיעורים שדווחו' },
+ { value: 'notReportedLessonNames', label: 'שיעורים שלא דווחו' },
+ ];
+ },
+ },
+ service: TeacherReportStatusService,
+ };
}
class TeacherReportStatusService extends BaseEntityService {
- reportsDict = {
- teacherReportFile: new BulkToZipReportGenerator(() => 'קבצי נוכחות למורות', teacherReportFile),
- };
- async getReportData(req: CrudRequest): Promise {
- if (req.parsed.extra.report in this.reportsDict) {
- req.parsed.extra.isGrades = false;
- const generator = this.reportsDict[req.parsed.extra.report];
- const params = getTeacherStatusFileReportParams(req);
- return {
- generator,
- params,
- };
- }
- return super.getReportData(req);
+ reportsDict = {
+ teacherReportFile: new BulkToZipReportGenerator(() => 'קבצי נוכחות למורות', teacherReportFile),
+ };
+ async getReportData(req: CrudRequest): Promise {
+ if (req.parsed.extra.report in this.reportsDict) {
+ req.parsed.extra.isGrades = false;
+ const generator = this.reportsDict[req.parsed.extra.report];
+ const params = getTeacherStatusFileReportParams(req);
+ return {
+ generator,
+ params,
+ };
}
+ return super.getReportData(req);
+ }
- async doAction(req: CrudRequest, body: any): Promise {
- switch (req.parsed.extra.action) {
- case 'teacherReportFile': {
- req.parsed.extra.isGrades = false;
- return sendTeacherReportFileMail(req, this.dataSource, this.mailSendService);
- }
- }
- return super.doAction(req, body);
+ async doAction(req: CrudRequest, body: any): Promise {
+ switch (req.parsed.extra.action) {
+ case 'teacherReportFile': {
+ req.parsed.extra.isGrades = false;
+ return sendTeacherReportFileMail(req, this.dataSource, this.mailSendService);
+ }
}
+ return super.doAction(req, body);
+ }
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/teacher-salary-report.config.ts b/server/src/entity-modules/teacher-salary-report.config.ts
index 7f5fe184..c46a6143 100644
--- a/server/src/entity-modules/teacher-salary-report.config.ts
+++ b/server/src/entity-modules/teacher-salary-report.config.ts
@@ -1,41 +1,41 @@
-import { CrudRequest } from "@dataui/crud";
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { TeacherSalaryReport } from "src/db/view-entities/TeacherSalaryReport.entity";
+import { CrudRequest } from '@dataui/crud';
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { TeacherSalaryReport } from 'src/db/view-entities/TeacherSalaryReport.entity';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: TeacherSalaryReport,
- query: {
- join: {
- teacher: {},
- lesson: {},
- klass: {},
- reportMonth: {},
- }
- },
- exporter: {
- processReqForExport(req: CrudRequest, innerFunc) {
- req.options.query.join = {
- teacher: { eager: true },
- klass: { eager: true },
- lesson: { eager: true },
- reportMonth: { eager: true }
- };
- return innerFunc(req);
- },
- getExportHeaders(): IHeader[] {
- return [
- { value: 'teacher.name', label: 'שם המורה' },
- { value: 'klass.name', label: 'כיתה' },
- { value: 'lesson.name', label: 'שיעור' },
- { value: 'reportMonth.name', label: 'חודש דיווח' },
- { value: 'howManyLessons', label: 'מספר שיעורים' },
- { value: 'year', label: 'שנה' },
- ];
- }
- },
- }
+ return {
+ entity: TeacherSalaryReport,
+ query: {
+ join: {
+ teacher: {},
+ lesson: {},
+ klass: {},
+ reportMonth: {},
+ },
+ },
+ exporter: {
+ processReqForExport(req: CrudRequest, innerFunc) {
+ req.options.query.join = {
+ teacher: { eager: true },
+ klass: { eager: true },
+ lesson: { eager: true },
+ reportMonth: { eager: true },
+ };
+ return innerFunc(req);
+ },
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'teacher.name', label: 'שם המורה' },
+ { value: 'klass.name', label: 'כיתה' },
+ { value: 'lesson.name', label: 'שיעור' },
+ { value: 'reportMonth.name', label: 'חודש דיווח' },
+ { value: 'howManyLessons', label: 'מספר שיעורים' },
+ { value: 'year', label: 'שנה' },
+ ];
+ },
+ },
+ };
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/entity-modules/teacher.config.ts b/server/src/entity-modules/teacher.config.ts
index 029099ab..fc244dcf 100644
--- a/server/src/entity-modules/teacher.config.ts
+++ b/server/src/entity-modules/teacher.config.ts
@@ -1,23 +1,23 @@
-import { BaseEntityModuleOptions } from "@shared/base-entity/interface";
-import { IHeader } from "@shared/utils/exporter/types";
-import { Teacher } from "src/db/entities/Teacher.entity";
+import { BaseEntityModuleOptions } from '@shared/base-entity/interface';
+import { IHeader } from '@shared/utils/exporter/types';
+import { Teacher } from 'src/db/entities/Teacher.entity';
function getConfig(): BaseEntityModuleOptions {
- return {
- entity: Teacher,
- exporter: {
- getExportHeaders(): IHeader[] {
- return [
- { value: 'tz', label: 'תז' },
- { value: 'name', label: 'שם' },
- { value: 'phone', label: 'טלפון' },
- { value: 'phone2', label: 'טלפון 2' },
- { value: 'email', label: 'כתובת מייל' },
- { value: 'displayName', label: 'שם לתצוגה' },
- ];
- }
- },
- }
+ return {
+ entity: Teacher,
+ exporter: {
+ getExportHeaders(): IHeader[] {
+ return [
+ { value: 'tz', label: 'תז' },
+ { value: 'name', label: 'שם' },
+ { value: 'phone', label: 'טלפון' },
+ { value: 'phone2', label: 'טלפון 2' },
+ { value: 'email', label: 'כתובת מייל' },
+ { value: 'displayName', label: 'שם לתצוגה' },
+ ];
+ },
+ },
+ };
}
-export default getConfig();
\ No newline at end of file
+export default getConfig();
diff --git a/server/src/reports/__tests__/michlolPopulatedFile.spec.ts b/server/src/reports/__tests__/michlolPopulatedFile.spec.ts
index 0d700839..7e559261 100644
--- a/server/src/reports/__tests__/michlolPopulatedFile.spec.ts
+++ b/server/src/reports/__tests__/michlolPopulatedFile.spec.ts
@@ -81,9 +81,9 @@ describe('michlolPopulatedFile', () => {
michlolFileData: [{ A: '', B: '', C: 'Test Lesson', D: 'invalid' }],
});
- await expect(michlolPopulatedFile.getReportData(params, mockDataSource as DataSource))
- .rejects
- .toThrow(BadRequestException);
+ await expect(michlolPopulatedFile.getReportData(params, mockDataSource as DataSource)).rejects.toThrow(
+ BadRequestException,
+ );
});
it('should process file with no matching students', async () => {
@@ -130,12 +130,8 @@ describe('michlolPopulatedFile', () => {
{ studentReferenceId: 1, reportDate: '2025-01-01' },
{ studentReferenceId: 2, reportDate: '2025-01-01' },
];
- const mockKnownAbsences = [
- { studentReferenceId: 1, isApproved: true },
- ];
- const mockAttGradeEffects = [
- { percents: 90, count: 1 },
- ];
+ const mockKnownAbsences = [{ studentReferenceId: 1, isApproved: true }];
+ const mockAttGradeEffects = [{ percents: 90, count: 1 }];
(mockLessonRepo.findOne as jest.Mock).mockResolvedValue(mockLesson);
(mockStudentRepo.find as jest.Mock).mockResolvedValue(mockStudents);
@@ -145,7 +141,7 @@ describe('michlolPopulatedFile', () => {
(reportDataUtil.groupDataByKeys as jest.Mock).mockImplementation((data, keys) => {
const result = {};
- data.forEach(item => {
+ data.forEach((item) => {
const key = item[keys[0]];
result[key] = [item];
});
@@ -183,8 +179,8 @@ describe('michlolPopulatedFile', () => {
});
// Verify the updated grades in specialFields
- const gradeFields = result.specialFields.filter(field => field.cell.c === 4);
- expect(gradeFields.some(field => field.value === '90')).toBeTruthy();
+ const gradeFields = result.specialFields.filter((field) => field.cell.c === 4);
+ expect(gradeFields.some((field) => field.value === '90')).toBeTruthy();
});
});
@@ -204,4 +200,4 @@ describe('michlolPopulatedFile', () => {
expect(reportName).toBe('123 - Test Lesson');
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/reports/__tests__/reportGenerator.spec.ts b/server/src/reports/__tests__/reportGenerator.spec.ts
index 315f9fbf..25391f91 100644
--- a/server/src/reports/__tests__/reportGenerator.spec.ts
+++ b/server/src/reports/__tests__/reportGenerator.spec.ts
@@ -2,7 +2,11 @@ import { BaseReportGenerator } from '@shared/utils/report/report.generators';
import { CrudRequest } from '@dataui/crud';
import { DataSource } from 'typeorm';
import { MailSendService } from '@shared/utils/mail/mail-send.service';
-import { generateStudentReportCard, getTeacherStatusFileReportParams, sendTeacherReportFileMail } from '../reportGenerator';
+import {
+ generateStudentReportCard,
+ getTeacherStatusFileReportParams,
+ sendTeacherReportFileMail,
+} from '../reportGenerator';
import * as yearUtil from '@shared/utils/entity/year.util';
import * as authUtil from '@shared/auth/auth.util';
import * as mailAddressUtil from '@shared/utils/mail/mail-address.util';
@@ -29,7 +33,7 @@ const createMockCrudRequest = (extra: any, auth: any = { id: 'default' }): CrudR
cache: 0,
includeDeleted: 0,
extra,
- classTransformOptions: {}
+ classTransformOptions: {},
},
options: {
routes: {
@@ -40,10 +44,10 @@ const createMockCrudRequest = (extra: any, auth: any = { id: 'default' }): CrudR
updateOneBase: { interceptors: [], decorators: [] },
replaceOneBase: { interceptors: [], decorators: [] },
deleteOneBase: { interceptors: [], decorators: [] },
- recoverOneBase: { interceptors: [], decorators: [] }
- }
+ recoverOneBase: { interceptors: [], decorators: [] },
+ },
},
- auth
+ auth,
});
describe('reportGenerator', () => {
@@ -60,7 +64,7 @@ describe('reportGenerator', () => {
const reqExtra = {
ids: '1,2,3',
attendance: 'true',
- grades: 'true'
+ grades: 'true',
};
const generator: BaseReportGenerator = {} as any;
@@ -73,7 +77,7 @@ describe('reportGenerator', () => {
studentId: '1',
year: mockYear,
attendance: true,
- grades: true
+ grades: true,
});
});
@@ -81,7 +85,7 @@ describe('reportGenerator', () => {
const userId = '123';
const reqExtra = {
ids: '1',
- year: 2024
+ year: 2024,
};
const generator: BaseReportGenerator = {} as any;
@@ -96,11 +100,14 @@ describe('reportGenerator', () => {
const mockUserId = '456';
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(mockUserId);
- const mockRequest = createMockCrudRequest({
- ids: '10,20',
- isGrades: 'true',
- lessonReferenceId: '100'
- }, { id: mockUserId });
+ const mockRequest = createMockCrudRequest(
+ {
+ ids: '10,20',
+ isGrades: 'true',
+ lessonReferenceId: '100',
+ },
+ { id: mockUserId },
+ );
const result = getTeacherStatusFileReportParams(mockRequest);
@@ -109,7 +116,7 @@ describe('reportGenerator', () => {
userId: mockUserId,
id: '10',
isGrades: true,
- lessonReferenceId: 100
+ lessonReferenceId: 100,
});
});
@@ -117,10 +124,13 @@ describe('reportGenerator', () => {
const mockUserId = '456';
(authUtil.getUserIdFromUser as jest.Mock).mockReturnValue(mockUserId);
- const mockRequest = createMockCrudRequest({
- ids: '10',
- isGrades: 'true'
- }, { id: mockUserId });
+ const mockRequest = createMockCrudRequest(
+ {
+ ids: '10',
+ isGrades: 'true',
+ },
+ { id: mockUserId },
+ );
const result = getTeacherStatusFileReportParams(mockRequest);
@@ -132,12 +142,15 @@ describe('reportGenerator', () => {
it('should send teacher report file email', async () => {
const mockUserId = '789';
const mockReplyToAddress = 'teacher@test.com';
- const mockRequest = createMockCrudRequest({
- ids: '30',
- isGrades: 'true',
- mailSubject: 'Report for {0}',
- mailBody: 'Report content for {0}'
- }, { id: mockUserId });
+ const mockRequest = createMockCrudRequest(
+ {
+ ids: '30',
+ isGrades: 'true',
+ mailSubject: 'Report for {0}',
+ mailBody: 'Report content for {0}',
+ },
+ { id: mockUserId },
+ );
const mockDataSource = {} as DataSource;
const mockMailService = {} as MailSendService;
@@ -152,4 +165,4 @@ describe('reportGenerator', () => {
expect(bulkMailFileUtil.sendBulkTeacherMailWithFile).toHaveBeenCalled();
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/reports/__tests__/teacherReportFile.spec.ts b/server/src/reports/__tests__/teacherReportFile.spec.ts
index 31a83842..341af7e6 100644
--- a/server/src/reports/__tests__/teacherReportFile.spec.ts
+++ b/server/src/reports/__tests__/teacherReportFile.spec.ts
@@ -108,7 +108,7 @@ describe('teacherReportFile', () => {
id: 1,
name: 'Math',
key: 123,
- klassReferenceIds: ['1']
+ klassReferenceIds: ['1'],
};
const mockStudents = [
{
@@ -140,7 +140,7 @@ describe('teacherReportFile', () => {
id: 1,
name: 'Math',
key: 123,
- klassReferenceIds: null
+ klassReferenceIds: null,
};
(mockUserRepo.findOneBy as jest.Mock).mockResolvedValue({ id: 1, name: 'User 1' });
@@ -166,7 +166,7 @@ describe('teacherReportFile', () => {
id: 1,
name: 'Math',
key: 123,
- klassReferenceIds: ['1', '2']
+ klassReferenceIds: ['1', '2'],
};
const mockStudents = [
{
@@ -211,7 +211,7 @@ describe('teacherReportFile', () => {
id: 1,
name: 'Math',
key: 123,
- klassReferenceIds: ['1']
+ klassReferenceIds: ['1'],
};
const mockStudents = [
{
@@ -237,9 +237,7 @@ describe('teacherReportFile', () => {
expect(result[0]).toMatchObject({
fileTitle: 'קובץ נוכחות',
headerRow: ['קוד כיתה', 'ת.ז.', 'שם תלמידה', 'איחורים', 'חיסורים', 'הערות'],
- formattedData: [
- ['A1', '123', 'Student 1'],
- ],
+ formattedData: [['A1', '123', 'Student 1']],
sheetName: 'January',
});
});
@@ -250,7 +248,7 @@ describe('teacherReportFile', () => {
id: 1,
name: 'Math',
key: 123,
- klassReferenceIds: ['1']
+ klassReferenceIds: ['1'],
};
(mockUserRepo.findOneBy as jest.Mock).mockResolvedValue({ id: 1, name: 'User 1' });
@@ -281,7 +279,7 @@ describe('teacherReportFile', () => {
teacherReportStatus: { reportMonthName: 'January' } as TeacherReportStatus,
headerRow: [],
formattedData: [],
- specialFields: []
+ specialFields: [],
};
const result = teacherReportFileModule.getReportName(mockData);
@@ -289,4 +287,4 @@ describe('teacherReportFile', () => {
expect(result).toBe('קבצי נוכחות למורה');
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/reports/klassAttendanceReport.ts b/server/src/reports/klassAttendanceReport.ts
index bf6c1190..1a56a02e 100644
--- a/server/src/reports/klassAttendanceReport.ts
+++ b/server/src/reports/klassAttendanceReport.ts
@@ -1,5 +1,8 @@
import { IGetReportDataFunction } from '@shared/utils/report/report.generators';
-import { GenericDataToExcelReportGenerator, IDataToExcelReportGenerator } from '@shared/utils/report/data-to-excel.generator';
+import {
+ GenericDataToExcelReportGenerator,
+ IDataToExcelReportGenerator,
+} from '@shared/utils/report/data-to-excel.generator';
import { BulkToZipReportGenerator } from '@shared/utils/report/bulk-to-zip.generator';
import { ReportGroupSession } from 'src/db/entities/ReportGroupSession.entity';
import { AttReport } from 'src/db/entities/AttReport.entity';
@@ -15,9 +18,9 @@ import { formatTime, formatDate, formatDisplayName } from '@shared/utils/formatt
export interface KlassAttendanceReportParams {
userId: number;
- klassId: number; // Single klass ID
- startDate: Date; // ISO date string (required)
- endDate: Date; // ISO date string (required)
+ klassId: number; // Single klass ID
+ startDate: Date; // ISO date string (required)
+ endDate: Date; // ISO date string (required)
lessonReferenceIds?: number[];
}
@@ -32,7 +35,7 @@ export interface KlassAttendanceReportData extends IDataToExcelReportGenerator {
}
interface SessionData {
- sessionId: number | null; // null for placeholder (no session that day)
+ sessionId: number | null; // null for placeholder (no session that day)
date: Date;
dayOfWeek: string;
startTime: string;
@@ -46,159 +49,152 @@ interface SessionData {
interface StudentAttendanceData {
studentName: string;
tz: string;
- attendanceMarks: string[]; // 'V', '±', 'X', '--' for each session
+ attendanceMarks: string[]; // 'V', '±', 'X', '--' for each session
}
-const getReportData: IGetReportDataFunction =
- async (params, dataSource): Promise => {
+const getReportData: IGetReportDataFunction = async (
+ params,
+ dataSource,
+): Promise => {
+ console.log('klass attendance report params:', params);
- console.log('klass attendance report params:', params);
+ const { userId, klassId, startDate, endDate, lessonReferenceIds } = params;
- const { userId, klassId, startDate, endDate, lessonReferenceIds } = params;
-
- // Build where conditions for sessions
- const sessionWhere: FindOptionsWhere = {
- reportGroup: {
- userId,
- klassReferenceId: klassId,
- }
- };
-
- // Add lesson filtering if provided
- if (lessonReferenceIds?.length > 0) {
- (sessionWhere.reportGroup as FindOptionsWhere).lessonReferenceId = In(lessonReferenceIds);
- }
-
- // Add date filtering (both dates are required)
- sessionWhere.sessionDate = getReportDateFilter(startDate, endDate);
-
- // Fetch all data in parallel
- const [user, klass, allSessions] = await Promise.all([
- dataSource.getRepository(User).findOne({
- where: { id: userId }
- }),
- dataSource.getRepository(Klass).findOne({
- where: { id: klassId }
- }),
- dataSource.getRepository(ReportGroupSession).find({
- where: sessionWhere,
- relations: ['reportGroup', 'reportGroup.teacher', 'reportGroup.lesson'],
- order: { sessionDate: 'ASC' }
- })
- ]);
-
- if (!klass) {
- console.log('klass attendance report: klass not found', klassId);
- return null;
- }
-
- if (allSessions.length === 0) {
- console.log('klass attendance report: no sessions found for klass', klassId);
- return null;
- }
-
- // Get attendance reports for these sessions
- const sessionIds = getUniqueValues(allSessions, s => s.id);
- const attReports = await dataSource.getRepository(AttReport).find({
- where: { reportGroupSessionId: In(sessionIds) },
- relations: ['student'],
- order: { student: { name: 'ASC' } }
- });
-
- // Group attendance reports by session to calculate lesson counts
- const lessonCountsBySession = groupDataByKeysAndCalc(
- attReports,
- ['reportGroupSessionId'],
- (reports) => Math.max(...reports.map(r => r.howManyLessons || 0), 0)
- );
-
- // Group attendance reports by student and session for easy lookup
- const reportsByStudentAndSession = groupDataByKeysAndCalc(
- attReports,
- ['studentReferenceId', 'reportGroupSessionId'],
- (reports) => reports[0]
- );
-
- // Group sessions by date string for fast lookup
- const sessionsByDate = groupDataByKeyFn(
- allSessions.filter(s => lessonCountsBySession[s.id]),
- s => formatDate(s.sessionDate)
- );
-
- // Build sessions list: one entry per real session, placeholder for days with no data
- const sessions: SessionData[] = getDateRange(startDate, endDate)
- .flatMap(date => {
- const dateSessions: (ReportGroupSession | null)[] = sessionsByDate[formatDate(date)] || [null];
- return dateSessions.map(session => ({
- sessionId: session?.id ?? null,
- date,
- dayOfWeek: FORMATTING.getHebrewDayOfWeek(date),
- startTime: session?.startTime || '',
- endTime: session?.endTime || '',
- topic: session?.reportGroup?.lesson?.name || '',
- lessonCount: session ? lessonCountsBySession[session.id] : 0,
- teacherName: session?.reportGroup?.teacher?.name || '',
- signatureData: session?.reportGroup?.signatureData,
- }));
- });
-
- // Get unique students from attendance reports
- const uniqueStudentIds = getUniqueValues(attReports, r => r.studentReferenceId);
- const studentByIdMap = groupDataByKeysAndCalc(
- attReports,
- ['studentReferenceId'],
- (reports) => reports[0].student
- );
- const uniqueStudents = uniqueStudentIds
- .map(studentId => studentByIdMap[studentId])
- .filter(s => s)
- .sort((a, b) => a.name.localeCompare(b.name, 'he'));
-
- // Build student data with attendance marks (one mark per session column)
- const students: StudentAttendanceData[] = uniqueStudents.map(student => {
- const attendanceMarks = sessions.map(session => {
- if (!session.sessionId) return '';
- const key = `${student.id}_${session.sessionId}`;
- const report = reportsByStudentAndSession[key];
- return FORMATTING.getAttendanceMark(report);
- });
+ // Build where conditions for sessions
+ const sessionWhere: FindOptionsWhere = {
+ reportGroup: {
+ userId,
+ klassReferenceId: klassId,
+ },
+ };
- return {
- studentName: student.name,
- tz: student.tz,
- attendanceMarks
- };
- });
- console.log(`klass attendance report: built attendance data for ${students.length} students`);
+ // Add lesson filtering if provided
+ if (lessonReferenceIds?.length > 0) {
+ (sessionWhere.reportGroup as FindOptionsWhere).lessonReferenceId = In(lessonReferenceIds);
+ }
- const klassName = formatDisplayName(klass) || 'לא ידוע';
+ // Add date filtering (both dates are required)
+ sessionWhere.sessionDate = getReportDateFilter(startDate, endDate);
+
+ // Fetch all data in parallel
+ const [user, klass, allSessions] = await Promise.all([
+ dataSource.getRepository(User).findOne({
+ where: { id: userId },
+ }),
+ dataSource.getRepository(Klass).findOne({
+ where: { id: klassId },
+ }),
+ dataSource.getRepository(ReportGroupSession).find({
+ where: sessionWhere,
+ relations: ['reportGroup', 'reportGroup.teacher', 'reportGroup.lesson'],
+ order: { sessionDate: 'ASC' },
+ }),
+ ]);
+
+ if (!klass) {
+ console.log('klass attendance report: klass not found', klassId);
+ return null;
+ }
- // Build and return Excel data
- const excelData = BUILDING.buildExcelData({
- klassName: `${klassName} - ${klass.key}`,
- institutionName: user?.userInfo?.organizationName || 'לא ידוע',
- institutionCode: user?.userInfo?.organizationCode || 'לא ידוע',
- sessions,
- students,
- startDate: new Date(startDate),
- endDate: new Date(endDate),
- headerRow: [],
- formattedData: [],
- sheetName: '',
- specialFields: []
- });
+ if (allSessions.length === 0) {
+ console.log('klass attendance report: no sessions found for klass', klassId);
+ return null;
+ }
- console.log('Excel data summary:', {
- klassName: excelData.klassName,
- sessionCount: excelData.sessions.length,
- studentCount: excelData.students.length,
- formattedDataRows: excelData.formattedData.length,
- formattedDataPreview: excelData.formattedData.slice(0, 3)
+ // Get attendance reports for these sessions
+ const sessionIds = getUniqueValues(allSessions, (s) => s.id);
+ const attReports = await dataSource.getRepository(AttReport).find({
+ where: { reportGroupSessionId: In(sessionIds) },
+ relations: ['student'],
+ order: { student: { name: 'ASC' } },
+ });
+
+ // Group attendance reports by session to calculate lesson counts
+ const lessonCountsBySession = groupDataByKeysAndCalc(attReports, ['reportGroupSessionId'], (reports) =>
+ Math.max(...reports.map((r) => r.howManyLessons || 0), 0),
+ );
+
+ // Group attendance reports by student and session for easy lookup
+ const reportsByStudentAndSession = groupDataByKeysAndCalc(
+ attReports,
+ ['studentReferenceId', 'reportGroupSessionId'],
+ (reports) => reports[0],
+ );
+
+ // Group sessions by date string for fast lookup
+ const sessionsByDate = groupDataByKeyFn(
+ allSessions.filter((s) => lessonCountsBySession[s.id]),
+ (s) => formatDate(s.sessionDate),
+ );
+
+ // Build sessions list: one entry per real session, placeholder for days with no data
+ const sessions: SessionData[] = getDateRange(startDate, endDate).flatMap((date) => {
+ const dateSessions: (ReportGroupSession | null)[] = sessionsByDate[formatDate(date)] || [null];
+ return dateSessions.map((session) => ({
+ sessionId: session?.id ?? null,
+ date,
+ dayOfWeek: FORMATTING.getHebrewDayOfWeek(date),
+ startTime: session?.startTime || '',
+ endTime: session?.endTime || '',
+ topic: session?.reportGroup?.lesson?.name || '',
+ lessonCount: session ? lessonCountsBySession[session.id] : 0,
+ teacherName: session?.reportGroup?.teacher?.name || '',
+ signatureData: session?.reportGroup?.signatureData,
+ }));
+ });
+
+ // Get unique students from attendance reports
+ const uniqueStudentIds = getUniqueValues(attReports, (r) => r.studentReferenceId);
+ const studentByIdMap = groupDataByKeysAndCalc(attReports, ['studentReferenceId'], (reports) => reports[0].student);
+ const uniqueStudents = uniqueStudentIds
+ .map((studentId) => studentByIdMap[studentId])
+ .filter((s) => s)
+ .sort((a, b) => a.name.localeCompare(b.name, 'he'));
+
+ // Build student data with attendance marks (one mark per session column)
+ const students: StudentAttendanceData[] = uniqueStudents.map((student) => {
+ const attendanceMarks = sessions.map((session) => {
+ if (!session.sessionId) return '';
+ const key = `${student.id}_${session.sessionId}`;
+ const report = reportsByStudentAndSession[key];
+ return FORMATTING.getAttendanceMark(report);
});
- return excelData;
- };
-
+ return {
+ studentName: student.name,
+ tz: student.tz,
+ attendanceMarks,
+ };
+ });
+ console.log(`klass attendance report: built attendance data for ${students.length} students`);
+
+ const klassName = formatDisplayName(klass) || 'לא ידוע';
+
+ // Build and return Excel data
+ const excelData = BUILDING.buildExcelData({
+ klassName: `${klassName} - ${klass.key}`,
+ institutionName: user?.userInfo?.organizationName || 'לא ידוע',
+ institutionCode: user?.userInfo?.organizationCode || 'לא ידוע',
+ sessions,
+ students,
+ startDate: new Date(startDate),
+ endDate: new Date(endDate),
+ headerRow: [],
+ formattedData: [],
+ sheetName: '',
+ specialFields: [],
+ });
+
+ console.log('Excel data summary:', {
+ klassName: excelData.klassName,
+ sessionCount: excelData.sessions.length,
+ studentCount: excelData.students.length,
+ formattedDataRows: excelData.formattedData.length,
+ formattedDataPreview: excelData.formattedData.slice(0, 3),
+ });
+
+ return excelData;
+};
// Row index constants
const ROW_INDEX = {
@@ -211,7 +207,7 @@ const ROW_INDEX = {
const ROW_COUNT = {
TITLE_ROWS: 2,
SPACING_ROWS: 1,
- HEADER_OFFSET: 3, // Title rows + spacing
+ HEADER_OFFSET: 3, // Title rows + spacing
} as const;
const STYLING: Record> = {
@@ -225,44 +221,44 @@ const STYLING: Record> = {
fill: {
type: 'pattern',
pattern: 'solid',
- fgColor: { argb: 'FFE6F3FF' }
- }
+ fgColor: { argb: 'FFE6F3FF' },
+ },
},
subHeaderStyle: {
font: { bold: true, size: 14, name: 'Arial' },
alignment: {
horizontal: 'center',
- readingOrder: 'rtl'
- }
+ readingOrder: 'rtl',
+ },
},
tableHeaderStyle: {
alignment: {
horizontal: 'center',
readingOrder: 'rtl',
- wrapText: true
+ wrapText: true,
},
font: { name: 'Arial', size: 11, bold: true },
fill: {
type: 'pattern',
pattern: 'solid',
- fgColor: { argb: 'FFF0F0F0' } // Light gray background
- }
+ fgColor: { argb: 'FFF0F0F0' }, // Light gray background
+ },
},
tableStyle: {
alignment: {
horizontal: 'center',
readingOrder: 'rtl',
- wrapText: true
+ wrapText: true,
},
- font: { name: 'Arial', size: 11 }
- }
-}
+ font: { name: 'Arial', size: 11 },
+ },
+};
const BUILDING = {
// Build table header section: rows + special fields + borders
buildTableHeaderSection(sessions: SessionData[]) {
- const dayRow = ['יום בשבוע', ...sessions.map(s => s.dayOfWeek)];
- const dateRow = ['תאריך', ...sessions.map(s => s.date.getDate().toString())];
+ const dayRow = ['יום בשבוע', ...sessions.map((s) => s.dayOfWeek)];
+ const dateRow = ['תאריך', ...sessions.map((s) => s.date.getDate().toString())];
// const hoursRow = ['שעות לימוד', ...sessions.map(s => `${formatTime(s.startTime)}-${formatTime(s.endTime)}`)];
// const topicRow = ['שיעור', ...sessions.map(s => s.topic)];
// const lessonCountRow = ['מס\' שעות לימוד', ...sessions.map(s => s.lessonCount.toString())];
@@ -288,7 +284,7 @@ const BUILDING = {
specialFields.push({
cell: { r: actualRowIndex, c: colIndex },
value: cell,
- style: STYLING.tableHeaderStyle
+ style: STYLING.tableHeaderStyle,
});
}
});
@@ -303,8 +299,8 @@ const BUILDING = {
{
from: { r: startRow, c: 0 },
to: { r: endRow, c: lastCol },
- innerBorder: { style: 'thin' } as ExcelJS.Border
- }
+ innerBorder: { style: 'thin' } as ExcelJS.Border,
+ },
];
return { rowCount: rows.length, specialFields, borderRanges };
@@ -327,7 +323,7 @@ const BUILDING = {
specialFields.push({
cell: { r: actualRowIndex, c: colIndex },
value: cell,
- style: STYLING.tableStyle
+ style: STYLING.tableStyle,
});
}
});
@@ -338,8 +334,8 @@ const BUILDING = {
{
from: { r: startRow, c: 0 },
to: { r: lastRow, c: 0 },
- innerBorder: { style: 'thin' } as ExcelJS.Border
- }
+ innerBorder: { style: 'thin' } as ExcelJS.Border,
+ },
];
return { specialFields, borderRanges };
@@ -355,10 +351,7 @@ const BUILDING = {
const lastCol = sessions.length;
// Combine special fields from both sections
- const specialFields = [
- ...headerSection.specialFields,
- ...dataSection.specialFields
- ];
+ const specialFields = [...headerSection.specialFields, ...dataSection.specialFields];
// Combine border ranges + add outer border for entire table
const borderRanges = [
@@ -366,10 +359,10 @@ const BUILDING = {
{
from: { r: ROW_INDEX.TABLE_START, c: 0 },
to: { r: lastRow, c: lastCol },
- outerBorder: { style: 'medium' } as ExcelJS.Border
+ outerBorder: { style: 'medium' } as ExcelJS.Border,
},
...headerSection.borderRanges,
- ...dataSection.borderRanges
+ ...dataSection.borderRanges,
];
return { totalRowCount, specialFields, borderRanges };
@@ -382,7 +375,7 @@ const BUILDING = {
klassName: string,
sessionCount: number,
startDate?: Date,
- endDate?: Date
+ endDate?: Date,
) {
const titleRow1 = `יומן נוכחות ${institutionName} סמל מוסד ${institutionCode}`;
const titleRow2 = klassName;
@@ -395,37 +388,37 @@ const BUILDING = {
cell: { r: ROW_INDEX.TITLE_1, c: 0 },
value: titleRow1,
style: STYLING.headerStyle,
- merge: { s: { r: ROW_INDEX.TITLE_1, c: 0 }, e: { r: ROW_INDEX.TITLE_1, c: sessionCount } }
+ merge: { s: { r: ROW_INDEX.TITLE_1, c: 0 }, e: { r: ROW_INDEX.TITLE_1, c: sessionCount } },
},
{
cell: { r: ROW_INDEX.TITLE_2, c: 0 },
value: titleRow2,
style: STYLING.subHeaderStyle,
- merge: { s: { r: ROW_INDEX.TITLE_2, c: 0 }, e: { r: ROW_INDEX.TITLE_2, c: sessionCount } }
+ merge: { s: { r: ROW_INDEX.TITLE_2, c: 0 }, e: { r: ROW_INDEX.TITLE_2, c: sessionCount } },
},
{
cell: { r: ROW_INDEX.SPACING, c: 0 },
value: dateRangeText,
style: STYLING.subHeaderStyle,
- merge: { s: { r: ROW_INDEX.SPACING, c: 0 }, e: { r: ROW_INDEX.SPACING, c: sessionCount } }
- }
+ merge: { s: { r: ROW_INDEX.SPACING, c: 0 }, e: { r: ROW_INDEX.SPACING, c: sessionCount } },
+ },
],
borderRanges: [
// Heavy border around title rows
{
from: { r: ROW_INDEX.TITLE_1, c: 0 },
to: { r: ROW_INDEX.SPACING, c: lastCol },
- outerBorder: { style: 'medium' } as ExcelJS.Border
- }
- ]
+ outerBorder: { style: 'medium' } as ExcelJS.Border,
+ },
+ ],
};
},
// Build signature section: one signature (first available) below the entire table
buildSignatureSection(sessions: SessionData[], tableEndRow: number) {
- const signatureRow = tableEndRow + 2; // Leave 2 rows spacing after table
+ const signatureRow = tableEndRow + 2; // Leave 2 rows spacing after table
- const firstSignature = sessions.find(s => s.signatureData)?.signatureData;
+ const firstSignature = sessions.find((s) => s.signatureData)?.signatureData;
const specialFields: ISpecialField[] = [];
const images: IImageField[] = [];
@@ -439,24 +432,24 @@ const BUILDING = {
alignment: {
horizontal: 'center' as const,
vertical: 'middle' as const,
- readingOrder: 'rtl' as const
- }
- }
+ readingOrder: 'rtl' as const,
+ },
+ },
});
images.push({
imageBase64Data: firstSignature,
position: {
tl: { row: signatureRow, col: 1 },
- ext: { width: 120, height: 80 }
- }
+ ext: { width: 120, height: 80 },
+ },
});
}
return {
specialFields,
images,
- additionalRows: firstSignature ? 8 : 0
+ additionalRows: firstSignature ? 8 : 0,
};
},
@@ -467,16 +460,22 @@ const BUILDING = {
console.log('buildExcelData input:', {
klassName,
sessionCount: sessions.length,
- studentCount: students.length
+ studentCount: students.length,
});
// 1. Build title section (merged headers + borders)
- const titleSection = BUILDING.buildTitleSection(institutionName, institutionCode, klassName, sessions.length, startDate, endDate);
+ const titleSection = BUILDING.buildTitleSection(
+ institutionName,
+ institutionCode,
+ klassName,
+ sessions.length,
+ startDate,
+ endDate,
+ );
// 2. Build complete table section (header rows + student rows + borders)
const tableSection = BUILDING.buildTableSection(sessions, students);
-
// 3. Build signature section - one signature below the table
const signatureSection = BUILDING.buildSignatureSection(sessions, tableSection.totalRowCount);
@@ -511,8 +510,8 @@ const BUILDING = {
borderRanges,
images,
};
- }
-}
+ },
+};
const FORMATTING = {
getHebrewDayOfWeek(date: Date): string {
@@ -521,18 +520,21 @@ const FORMATTING = {
},
getAttendanceMark(report: AttReport | null | undefined): string {
- if (!report) return '--'; // No report for this session
+ if (!report) return '--'; // No report for this session
const absPercent = report.howManyLessons > 0 ? report.absCount / report.howManyLessons : 0;
- if (absPercent === 0) return '3'; // נוכחות מלאה - Full attendance
- if (absPercent < 1.0) return '1'; // איחור - Partial absence (late)
- return '0'; // העדרות מלאה - Full absence
+ if (absPercent === 0) return '3'; // נוכחות מלאה - Full attendance
+ if (absPercent < 1.0) return '1'; // איחור - Partial absence (late)
+ return '0'; // העדרות מלאה - Full absence
},
-}
+};
const getReportName = (data: KlassAttendanceReportData) => `יומן נוכחות - ${data.klassName}`;
-const singleGenerator = new GenericDataToExcelReportGenerator(getReportName, getReportData);
+const singleGenerator = new GenericDataToExcelReportGenerator(
+ getReportName,
+ getReportData,
+);
const generator = new BulkToZipReportGenerator(() => 'יומני נוכחות', singleGenerator);
export default generator;
diff --git a/server/src/reports/michlolPopulatedFile.ts b/server/src/reports/michlolPopulatedFile.ts
index c6406391..cb8c795d 100644
--- a/server/src/reports/michlolPopulatedFile.ts
+++ b/server/src/reports/michlolPopulatedFile.ts
@@ -13,98 +13,118 @@ import { AttGradeEffect } from 'src/db/entities/AttGradeEffect';
import { BadRequestException } from '@nestjs/common';
export interface MichlolPopulatedFileParams {
- userId: number;
- michlolFileName: string;
- michlolFileData: { [key: string]: string }[];
+ userId: number;
+ michlolFileName: string;
+ michlolFileData: { [key: string]: string }[];
}
export interface MichlolPopulatedFileData extends IDataToExcelReportGenerator {
- lesson: Partial;
- filename: string;
- extension: string;
+ lesson: Partial;
+ filename: string;
+ extension: string;
}
-const getReportData: IGetReportDataFunction = async (params: MichlolPopulatedFileParams, dataSource): Promise => {
- const extension = path.extname(params.michlolFileName);
- const filename = path.basename(params.michlolFileName, extension);
+const getReportData: IGetReportDataFunction = async (
+ params: MichlolPopulatedFileParams,
+ dataSource,
+): Promise => {
+ const extension = path.extname(params.michlolFileName);
+ const filename = path.basename(params.michlolFileName, extension);
- const lessonKey = Number(params.michlolFileData[0]['D'].replace(/\s/g, ''));
- const studentTzs = params.michlolFileData.slice(3).map(row => row['B']).filter(Boolean);
+ const lessonKey = Number(params.michlolFileData[0]['D'].replace(/\s/g, ''));
+ const studentTzs = params.michlolFileData
+ .slice(3)
+ .map((row) => row['B'])
+ .filter(Boolean);
- if (isNaN(lessonKey)) {
- throw new BadRequestException("קוד שיעור לא תקין");
- }
+ if (isNaN(lessonKey)) {
+ throw new BadRequestException('קוד שיעור לא תקין');
+ }
- const [lesson, students] = await Promise.all([
- dataSource.getRepository(Lesson).findOne({ where: { userId: params.userId, key: lessonKey, year: getCurrentHebrewYear() }, select: { id: true, key: true, name: true, userId: true } }),
- dataSource.getRepository(Student).find({ where: { userId: params.userId, tz: In(studentTzs) }, select: { id: true, tz: true } }),
- ]);
+ const [lesson, students] = await Promise.all([
+ dataSource
+ .getRepository(Lesson)
+ .findOne({
+ where: { userId: params.userId, key: lessonKey, year: getCurrentHebrewYear() },
+ select: { id: true, key: true, name: true, userId: true },
+ }),
+ dataSource
+ .getRepository(Student)
+ .find({ where: { userId: params.userId, tz: In(studentTzs) }, select: { id: true, tz: true } }),
+ ]);
- let updatedData = params.michlolFileData;
+ let updatedData = params.michlolFileData;
- if (lesson && students.length > 0) {
- const dataFilter = {
- studentReferenceId: In(students.map(s => s.id)),
- lessonReferenceId: lesson.id,
- year: getCurrentHebrewYear(),
- };
- const [reports, knownAbsences, attGradeEffect] = await Promise.all([
- dataSource.getRepository(AttReportAndGrade).find({ where: dataFilter, order: { reportDate: 'ASC' } }),
- dataSource.getRepository(KnownAbsence).find({ where: { ...dataFilter, isApproved: true } }),
- dataSource.getRepository(AttGradeEffect).find({ where: { userId: lesson.userId }, order: { percents: 'DESC', count: 'ASC' } }),
- ]);
+ if (lesson && students.length > 0) {
+ const dataFilter = {
+ studentReferenceId: In(students.map((s) => s.id)),
+ lessonReferenceId: lesson.id,
+ year: getCurrentHebrewYear(),
+ };
+ const [reports, knownAbsences, attGradeEffect] = await Promise.all([
+ dataSource.getRepository(AttReportAndGrade).find({ where: dataFilter, order: { reportDate: 'ASC' } }),
+ dataSource.getRepository(KnownAbsence).find({ where: { ...dataFilter, isApproved: true } }),
+ dataSource
+ .getRepository(AttGradeEffect)
+ .find({ where: { userId: lesson.userId }, order: { percents: 'DESC', count: 'ASC' } }),
+ ]);
- const studentReportsMap = groupDataByKeys(reports, ['studentReferenceId']);
- const knownAbsencesMap = groupDataByKeys(knownAbsences, ['studentReferenceId']);
- const studentIdMap = groupDataByKeysAndCalc(students, ['tz'], (arr) => arr[0].id);
+ const studentReportsMap = groupDataByKeys(reports, ['studentReferenceId']);
+ const knownAbsencesMap = groupDataByKeys(knownAbsences, ['studentReferenceId']);
+ const studentIdMap = groupDataByKeysAndCalc(students, ['tz'], (arr) => arr[0].id);
- updatedData = params.michlolFileData.map(row => {
- const studentId = studentIdMap[row['B']];
+ updatedData = params.michlolFileData.map((row) => {
+ const studentId = studentIdMap[row['B']];
- const studentReports = studentReportsMap[studentId] || [];
- const studentKnownAbsences = knownAbsencesMap[studentId] || [];
- const { attPercents, absCount, approvedAbsCount, gradeAvg, lessonsCount, lastGrade } = calcReportsData(studentReports, studentKnownAbsences);
- // TODO add param here to use lastGrade or gradeAvg
- const unapprovedAbsCount = getUnknownAbsCount(absCount, approvedAbsCount);
- const gradeEffect = getGradeEffect(attGradeEffect, attPercents, unapprovedAbsCount);
- const displayGrade = getDisplayGrade(lastGrade, gradeEffect);
- const finalGrade = parseInt(displayGrade.replace('%', ''));
+ const studentReports = studentReportsMap[studentId] || [];
+ const studentKnownAbsences = knownAbsencesMap[studentId] || [];
+ const { attPercents, absCount, approvedAbsCount, gradeAvg, lessonsCount, lastGrade } = calcReportsData(
+ studentReports,
+ studentKnownAbsences,
+ );
+ // TODO add param here to use lastGrade or gradeAvg
+ const unapprovedAbsCount = getUnknownAbsCount(absCount, approvedAbsCount);
+ const gradeEffect = getGradeEffect(attGradeEffect, attPercents, unapprovedAbsCount);
+ const displayGrade = getDisplayGrade(lastGrade, gradeEffect);
+ const finalGrade = parseInt(displayGrade.replace('%', ''));
- return {
- ...row,
- E: String(finalGrade || row['E']),
- };
- });
- }
+ return {
+ ...row,
+ E: String(finalGrade || row['E']),
+ };
+ });
+ }
- const specialFields = updatedData.map((row, index) => ([
- { cell: { c: 0, r: index }, value: row['A'] },
- { cell: { c: 1, r: index }, value: row['B'] },
- { cell: { c: 2, r: index }, value: row['C'] },
- { cell: { c: 3, r: index }, value: row['D'] },
- { cell: { c: 4, r: index }, value: row['E'] },
- { cell: { c: 5, r: index }, value: row['F'] },
- { cell: { c: 6, r: index }, value: row['G'] },
- { cell: { c: 7, r: index }, value: row['H'] },
- { cell: { c: 8, r: index }, value: row['I'] },
- { cell: { c: 9, r: index }, value: row['J'] },
- { cell: { c: 10, r: index }, value: row['K'] },
- { cell: { c: 11, r: index }, value: row['L'] },
- { cell: { c: 12, r: index }, value: row['M'] },
- { cell: { c: 13, r: index }, value: row['N'] },
- ])).flat();
+ const specialFields = updatedData
+ .map((row, index) => [
+ { cell: { c: 0, r: index }, value: row['A'] },
+ { cell: { c: 1, r: index }, value: row['B'] },
+ { cell: { c: 2, r: index }, value: row['C'] },
+ { cell: { c: 3, r: index }, value: row['D'] },
+ { cell: { c: 4, r: index }, value: row['E'] },
+ { cell: { c: 5, r: index }, value: row['F'] },
+ { cell: { c: 6, r: index }, value: row['G'] },
+ { cell: { c: 7, r: index }, value: row['H'] },
+ { cell: { c: 8, r: index }, value: row['I'] },
+ { cell: { c: 9, r: index }, value: row['J'] },
+ { cell: { c: 10, r: index }, value: row['K'] },
+ { cell: { c: 11, r: index }, value: row['L'] },
+ { cell: { c: 12, r: index }, value: row['M'] },
+ { cell: { c: 13, r: index }, value: row['N'] },
+ ])
+ .flat();
- return {
- lesson: lesson ?? {
- key: lessonKey,
- name: params.michlolFileData[0]['C'],
- },
- filename,
- extension,
- headerRow: [],
- formattedData: [],
- sheetName: 'נתונים מעודכנים',
- specialFields,
- };
-}
+ return {
+ lesson: lesson ?? {
+ key: lessonKey,
+ name: params.michlolFileData[0]['C'],
+ },
+ filename,
+ extension,
+ headerRow: [],
+ formattedData: [],
+ sheetName: 'נתונים מעודכנים',
+ specialFields,
+ };
+};
const getReportName = (data: MichlolPopulatedFileData) => `${data.lesson?.key} - ${data.lesson?.name}`;
diff --git a/server/src/reports/reportGenerator.ts b/server/src/reports/reportGenerator.ts
index efb3bd97..29f7958d 100644
--- a/server/src/reports/reportGenerator.ts
+++ b/server/src/reports/reportGenerator.ts
@@ -1,89 +1,95 @@
-import { getCurrentHebrewYear } from "@shared/utils/entity/year.util";
-import { BaseReportGenerator } from "@shared/utils/report/report.generators";
-import { IReportParams } from "./studentReportCardReact";
-import { CrudRequest } from "@dataui/crud";
-import teacherReportFile, { TeacherReportFileData, TeacherReportFileParams } from "src/reports/teacherReportFile";
-import { getUserIdFromUser } from "@shared/auth/auth.util";
-import { getMailAddressForEntity } from "@shared/utils/mail/mail-address.util";
-import { FormatString } from "@shared/utils/yemot/yemot.interface";
-import { DataSource } from "typeorm";
-import { MailSendService } from "@shared/utils/mail/mail-send.service";
-import { sendBulkTeacherMailWithFile } from "@shared/utils/report/bulk-mail-file.util";
-import { getAsArray, getAsBoolean, getAsNumber, getAsString } from "@shared/utils/queryParam.util";
+import { getCurrentHebrewYear } from '@shared/utils/entity/year.util';
+import { BaseReportGenerator } from '@shared/utils/report/report.generators';
+import { IReportParams } from './studentReportCardReact';
+import { CrudRequest } from '@dataui/crud';
+import teacherReportFile, { TeacherReportFileData, TeacherReportFileParams } from 'src/reports/teacherReportFile';
+import { getUserIdFromUser } from '@shared/auth/auth.util';
+import { getMailAddressForEntity } from '@shared/utils/mail/mail-address.util';
+import { FormatString } from '@shared/utils/yemot/yemot.interface';
+import { DataSource } from 'typeorm';
+import { MailSendService } from '@shared/utils/mail/mail-send.service';
+import { sendBulkTeacherMailWithFile } from '@shared/utils/report/bulk-mail-file.util';
+import { getAsArray, getAsBoolean, getAsNumber, getAsString } from '@shared/utils/queryParam.util';
export function generateStudentReportCard(userId: any, reqExtra: any, generator: BaseReportGenerator) {
- const extraParams: Partial = {
- year: reqExtra.year ?? getCurrentHebrewYear(),
- startDate: getAsString(reqExtra.startDate),
- endDate: getAsString(reqExtra.endDate),
- globalLessonReferenceIds: getAsString(reqExtra.globalLessonReferenceIds),
- denyLessonReferenceIds: getAsString(reqExtra.denyLessonReferenceIds),
- klassTypeReferenceId: getAsString(reqExtra.klassTypeReferenceId),
- attendance: getAsBoolean(reqExtra.attendance),
- grades: getAsBoolean(reqExtra.grades),
- personalNote: getAsString(reqExtra.personalNote),
- groupByKlass: getAsBoolean(reqExtra.groupByKlass),
- hideAbsTotal: getAsBoolean(reqExtra.hideAbsTotal),
- minimalReport: getAsBoolean(reqExtra.minimalReport),
- forceGrades: getAsBoolean(reqExtra.forceGrades),
- forceAtt: getAsBoolean(reqExtra.forceAtt),
- showStudentTz: getAsBoolean(reqExtra.showStudentTz),
- downComment: getAsBoolean(reqExtra.downComment),
- lastGrade: getAsBoolean(reqExtra.lastGrade),
- debug: getAsBoolean(reqExtra.debug),
- attendanceLessThan: getAttPercentLessThanParam(reqExtra.attendanceLessThan),
- };
- console.log('student report card extra params: ', extraParams);
- const params = getAsArray(reqExtra.ids)
- ?.map(id => ({
- userId,
- studentId: id,
- ...extraParams
- }));
- return {
- generator,
- params,
- };
+ const extraParams: Partial = {
+ year: reqExtra.year ?? getCurrentHebrewYear(),
+ startDate: getAsString(reqExtra.startDate),
+ endDate: getAsString(reqExtra.endDate),
+ globalLessonReferenceIds: getAsString(reqExtra.globalLessonReferenceIds),
+ denyLessonReferenceIds: getAsString(reqExtra.denyLessonReferenceIds),
+ klassTypeReferenceId: getAsString(reqExtra.klassTypeReferenceId),
+ attendance: getAsBoolean(reqExtra.attendance),
+ grades: getAsBoolean(reqExtra.grades),
+ personalNote: getAsString(reqExtra.personalNote),
+ groupByKlass: getAsBoolean(reqExtra.groupByKlass),
+ hideAbsTotal: getAsBoolean(reqExtra.hideAbsTotal),
+ minimalReport: getAsBoolean(reqExtra.minimalReport),
+ forceGrades: getAsBoolean(reqExtra.forceGrades),
+ forceAtt: getAsBoolean(reqExtra.forceAtt),
+ showStudentTz: getAsBoolean(reqExtra.showStudentTz),
+ downComment: getAsBoolean(reqExtra.downComment),
+ lastGrade: getAsBoolean(reqExtra.lastGrade),
+ debug: getAsBoolean(reqExtra.debug),
+ attendanceLessThan: getAttPercentLessThanParam(reqExtra.attendanceLessThan),
+ };
+ console.log('student report card extra params: ', extraParams);
+ const params = getAsArray(reqExtra.ids)?.map((id) => ({
+ userId,
+ studentId: id,
+ ...extraParams,
+ }));
+ return {
+ generator,
+ params,
+ };
}
function getAttPercentLessThanParam(attendanceLessThanStr: string): number {
- if (attendanceLessThanStr) {
- const attLessThanNum = parseInt(attendanceLessThanStr);
- if (!isNaN(attLessThanNum)) {
- return attLessThanNum / 100;
- }
+ if (attendanceLessThanStr) {
+ const attLessThanNum = parseInt(attendanceLessThanStr);
+ if (!isNaN(attLessThanNum)) {
+ return attLessThanNum / 100;
}
- return undefined;
+ }
+ return undefined;
}
export function getTeacherStatusFileReportParams(req: CrudRequest): TeacherReportFileParams[] {
- console.log('teacher report file params: ', req.parsed.extra);
- const isGrades = getAsBoolean(req.parsed.extra?.isGrades);
- const lessonReferenceId = getAsNumber(req.parsed.extra?.lessonReferenceId);
- const params = getAsArray(req.parsed.extra.ids)
- ?.map(id => ({
- userId: getUserIdFromUser(req.auth),
- id,
- isGrades,
- lessonReferenceId,
- }));
- return params;
+ console.log('teacher report file params: ', req.parsed.extra);
+ const isGrades = getAsBoolean(req.parsed.extra?.isGrades);
+ const lessonReferenceId = getAsNumber(req.parsed.extra?.lessonReferenceId);
+ const params = getAsArray(req.parsed.extra.ids)?.map((id) => ({
+ userId: getUserIdFromUser(req.auth),
+ id,
+ isGrades,
+ lessonReferenceId,
+ }));
+ return params;
}
-export async function sendTeacherReportFileMail(req: CrudRequest, dataSource: DataSource, mailSendService: MailSendService): Promise {
- const params = getTeacherStatusFileReportParams(req);
- const generator = teacherReportFile;
- const targetEntity = getAsBoolean(req.parsed.extra?.isGrades) ? 'grade' : 'att_report';
- const getEmailParamsFromData = async (params: TeacherReportFileParams, data: TeacherReportFileData[]) => {
- const replyToAddress = await getMailAddressForEntity(params.userId, targetEntity, dataSource);
- const textParams = [data[0].teacher.name, data[0].teacherReportStatus.reportMonthName, data.map(item => item.lesson.name).join(', ')];
- const mailSubject = FormatString(req.parsed.extra.mailSubject, textParams);
- const mailBody = FormatString(req.parsed.extra.mailBody, textParams);
- return {
- replyToAddress,
- mailSubject,
- mailBody,
- };
- }
- return sendBulkTeacherMailWithFile(generator, params, req.auth, dataSource, mailSendService, getEmailParamsFromData);
+export async function sendTeacherReportFileMail(
+ req: CrudRequest,
+ dataSource: DataSource,
+ mailSendService: MailSendService,
+): Promise {
+ const params = getTeacherStatusFileReportParams(req);
+ const generator = teacherReportFile;
+ const targetEntity = getAsBoolean(req.parsed.extra?.isGrades) ? 'grade' : 'att_report';
+ const getEmailParamsFromData = async (params: TeacherReportFileParams, data: TeacherReportFileData[]) => {
+ const replyToAddress = await getMailAddressForEntity(params.userId, targetEntity, dataSource);
+ const textParams = [
+ data[0].teacher.name,
+ data[0].teacherReportStatus.reportMonthName,
+ data.map((item) => item.lesson.name).join(', '),
+ ];
+ const mailSubject = FormatString(req.parsed.extra.mailSubject, textParams);
+ const mailBody = FormatString(req.parsed.extra.mailBody, textParams);
+ return {
+ replyToAddress,
+ mailSubject,
+ mailBody,
+ };
+ };
+ return sendBulkTeacherMailWithFile(generator, params, req.auth, dataSource, mailSendService, getEmailParamsFromData);
}
diff --git a/server/src/reports/studentReportCard.ts b/server/src/reports/studentReportCard.ts
index d09fbac0..fb634b5d 100644
--- a/server/src/reports/studentReportCard.ts
+++ b/server/src/reports/studentReportCard.ts
@@ -247,7 +247,7 @@ const reportTemplate = `
`;
const reportOptions: ejs.Options = {
- compileDebug: true,
+ compileDebug: true,
};
export default new EjsToPdfReportGenerator(getReportName, getReportData, reportTemplate, reportOptions);
diff --git a/server/src/reports/teacherReportFile.ts b/server/src/reports/teacherReportFile.ts
index 104fb292..c2d2f6ef 100644
--- a/server/src/reports/teacherReportFile.ts
+++ b/server/src/reports/teacherReportFile.ts
@@ -1,8 +1,13 @@
import { User } from 'src/db/entities/User.entity';
import { IGetReportDataFunction } from '@shared/utils/report/report.generators';
-import { DataToExcelReportGenerator, getDateDataValidation, getIntegerDataValidation, IDataToExcelReportGenerator } from '@shared/utils/report/data-to-excel.generator';
+import {
+ DataToExcelReportGenerator,
+ getDateDataValidation,
+ getIntegerDataValidation,
+ IDataToExcelReportGenerator,
+} from '@shared/utils/report/data-to-excel.generator';
import { BulkToZipReportGenerator } from '@shared/utils/report/bulk-to-zip.generator';
-import { StudentKlass } from "src/db/entities/StudentKlass.entity";
+import { StudentKlass } from 'src/db/entities/StudentKlass.entity';
import { TeacherReportStatus } from 'src/db/view-entities/TeacherReportStatus.entity';
import { TeacherGradeReportStatus } from 'src/db/view-entities/TeacherGradeReportStatus.entity';
import { Teacher } from 'src/db/entities/Teacher.entity';
@@ -12,129 +17,134 @@ import { FindOptionsWhere, In, IsNull, Not } from 'typeorm';
import * as ExcelJS from 'exceljs';
import { ISpecialField } from '@shared/utils/importer/types';
-
export interface TeacherReportFileParams {
- id: string;
- userId: number;
- lessonReferenceId?: number;
- isGrades?: boolean;
+ id: string;
+ userId: number;
+ lessonReferenceId?: number;
+ isGrades?: boolean;
}
export interface TeacherReportFileData extends IDataToExcelReportGenerator {
- fileTitle: string;
- user: User,
- teacher: Teacher,
- lesson: Lesson,
- teacherReportStatus: TeacherReportStatus,
- reportMonth: ReportMonth,
+ fileTitle: string;
+ user: User;
+ teacher: Teacher;
+ lesson: Lesson;
+ teacherReportStatus: TeacherReportStatus;
+ reportMonth: ReportMonth;
}
-const getReportData: IGetReportDataFunction = async (params: TeacherReportFileParams, dataSource): Promise => {
- const [userId, teacherId, reportMonthId, year] = params.id.split('_');
- const teacherReportTable = params.isGrades ? TeacherGradeReportStatus : TeacherReportStatus;
- const [user, teacher, teacherReportStatus, reportMonth] = await Promise.all([
- dataSource.getRepository(User).findOneBy({ id: params.userId }),
- dataSource.getRepository(Teacher).findOneBy({ id: Number(teacherId) }),
- dataSource.getRepository(teacherReportTable).findOneBy({ id: params.id, userId: params.userId, teacherReferenceId: Number(teacherId), year: Number(year) }),
- dataSource.getRepository(ReportMonth).findOneBy({ id: Number(reportMonthId) }),
- ])
- if ((teacherReportStatus.notReportedLessons?.length ?? 0) === 0) {
- console.log('teacher report file: no lessons to report')
- return [];
- }
+const getReportData: IGetReportDataFunction = async (
+ params: TeacherReportFileParams,
+ dataSource,
+): Promise => {
+ const [userId, teacherId, reportMonthId, year] = params.id.split('_');
+ const teacherReportTable = params.isGrades ? TeacherGradeReportStatus : TeacherReportStatus;
+ const [user, teacher, teacherReportStatus, reportMonth] = await Promise.all([
+ dataSource.getRepository(User).findOneBy({ id: params.userId }),
+ dataSource.getRepository(Teacher).findOneBy({ id: Number(teacherId) }),
+ dataSource
+ .getRepository(teacherReportTable)
+ .findOneBy({ id: params.id, userId: params.userId, teacherReferenceId: Number(teacherId), year: Number(year) }),
+ dataSource.getRepository(ReportMonth).findOneBy({ id: Number(reportMonthId) }),
+ ]);
+ if ((teacherReportStatus.notReportedLessons?.length ?? 0) === 0) {
+ console.log('teacher report file: no lessons to report');
+ return [];
+ }
- const lessonFilter: FindOptionsWhere = { id: In(teacherReportStatus.notReportedLessons), userId: params.userId };
- if (params.lessonReferenceId) {
- if (teacherReportStatus.notReportedLessons?.includes(String(params.lessonReferenceId))) {
- lessonFilter.id = params.lessonReferenceId;
- } else {
- console.log('teacher report file: lesson not in notReportedLessons')
- return [];
- }
+ const lessonFilter: FindOptionsWhere = {
+ id: In(teacherReportStatus.notReportedLessons),
+ userId: params.userId,
+ };
+ if (params.lessonReferenceId) {
+ if (teacherReportStatus.notReportedLessons?.includes(String(params.lessonReferenceId))) {
+ lessonFilter.id = params.lessonReferenceId;
+ } else {
+ console.log('teacher report file: lesson not in notReportedLessons');
+ return [];
}
- const [lessons] = await Promise.all([
- dataSource.getRepository(Lesson).findBy(lessonFilter),
- ]);
+ }
+ const [lessons] = await Promise.all([dataSource.getRepository(Lesson).findBy(lessonFilter)]);
- console.log('teacher report file: lessons', lessons.length)
+ console.log('teacher report file: lessons', lessons.length);
- const lessonStudents: { [key: number]: StudentKlass[] } = {};
- for (const lesson of lessons) {
- if (lesson.klassReferenceIds?.length) {
- const students = await dataSource.getRepository(StudentKlass).find({
- where: {
- userId: params.userId,
- klassReferenceId: In(lesson.klassReferenceIds),
- year: teacherReportStatus.year,
- studentReferenceId: Not(IsNull()),
- student: {
- id: Not(IsNull())
- }
- },
- relations: {
- student: true,
- klass: true,
- },
- order: {
- student: {
- name: 'ASC'
- }
- }
- });
- lessonStudents[lesson.id] = students;
- } else {
- lessonStudents[lesson.id] = [];
- }
+ const lessonStudents: { [key: number]: StudentKlass[] } = {};
+ for (const lesson of lessons) {
+ if (lesson.klassReferenceIds?.length) {
+ const students = await dataSource.getRepository(StudentKlass).find({
+ where: {
+ userId: params.userId,
+ klassReferenceId: In(lesson.klassReferenceIds),
+ year: teacherReportStatus.year,
+ studentReferenceId: Not(IsNull()),
+ student: {
+ id: Not(IsNull()),
+ },
+ },
+ relations: {
+ student: true,
+ klass: true,
+ },
+ order: {
+ student: {
+ name: 'ASC',
+ },
+ },
+ });
+ lessonStudents[lesson.id] = students;
+ } else {
+ lessonStudents[lesson.id] = [];
}
+ }
- const dataCols = params.isGrades ? ['ציונים'] : ['איחורים', 'חיסורים'];
- const commentCols = params.isGrades ? ['התנהגות א/ב/ג', 'צניעות א/ב/ג'] : ['הערות'];
- const headerRow = ['קוד כיתה', 'ת.ז.', 'שם תלמידה', ...dataCols, ...commentCols];
+ const dataCols = params.isGrades ? ['ציונים'] : ['איחורים', 'חיסורים'];
+ const commentCols = params.isGrades ? ['התנהגות א/ב/ג', 'צניעות א/ב/ג'] : ['הערות'];
+ const headerRow = ['קוד כיתה', 'ת.ז.', 'שם תלמידה', ...dataCols, ...commentCols];
- const formulaStyle: Partial = { fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: '98fb98' } } };
+ const formulaStyle: Partial = {
+ fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: '98fb98' } },
+ };
- return lessons.map(lesson => ({
- fileTitle: params.isGrades ? 'קובץ ציונים' : 'קובץ נוכחות',
- headerRow,
- formattedData: lessonStudents[lesson.id].map(sk => (
- [sk.klass.key, sk.student.id, sk.student.name]
- )),
- sheetName: teacherReportStatus.reportMonthName ?? 'דיווח נוכחות',
- specialFields: [
- { cell: { c: 0, r: 0 }, value: 'מורה: ' },
- { cell: { c: 1, r: 0 }, value: teacher.name },
- { cell: { c: 2, r: 0 }, value: teacher.tz },
- { cell: { c: 3, r: 0 }, value: 'תאריך: (ניתן להשאיר ריק)' },
- { cell: { c: 4, r: 0 }, value: '', style: formulaStyle, dataValidation: getDateDataValidation() },
- { cell: { c: 0, r: 1 }, value: 'שיעור:' },
- { cell: { c: 1, r: 1 }, value: lesson.name },
- { cell: { c: 2, r: 1 }, value: lesson.key.toString() },
- { cell: { c: 3, r: 1 }, value: 'מספר שיעורים:' },
- { cell: { c: 4, r: 1 }, value: '', style: formulaStyle, dataValidation: getIntegerDataValidation() },
- ...getNumbricCells(lessonStudents[lesson.id].length, dataCols.length),
- ],
- user,
- teacher,
- lesson,
- teacherReportStatus,
- reportMonth,
- }));
-}
+ return lessons.map((lesson) => ({
+ fileTitle: params.isGrades ? 'קובץ ציונים' : 'קובץ נוכחות',
+ headerRow,
+ formattedData: lessonStudents[lesson.id].map((sk) => [sk.klass.key, sk.student.id, sk.student.name]),
+ sheetName: teacherReportStatus.reportMonthName ?? 'דיווח נוכחות',
+ specialFields: [
+ { cell: { c: 0, r: 0 }, value: 'מורה: ' },
+ { cell: { c: 1, r: 0 }, value: teacher.name },
+ { cell: { c: 2, r: 0 }, value: teacher.tz },
+ { cell: { c: 3, r: 0 }, value: 'תאריך: (ניתן להשאיר ריק)' },
+ { cell: { c: 4, r: 0 }, value: '', style: formulaStyle, dataValidation: getDateDataValidation() },
+ { cell: { c: 0, r: 1 }, value: 'שיעור:' },
+ { cell: { c: 1, r: 1 }, value: lesson.name },
+ { cell: { c: 2, r: 1 }, value: lesson.key.toString() },
+ { cell: { c: 3, r: 1 }, value: 'מספר שיעורים:' },
+ { cell: { c: 4, r: 1 }, value: '', style: formulaStyle, dataValidation: getIntegerDataValidation() },
+ ...getNumbricCells(lessonStudents[lesson.id].length, dataCols.length),
+ ],
+ user,
+ teacher,
+ lesson,
+ teacherReportStatus,
+ reportMonth,
+ }));
+};
const getNumbricCells = (rowCount: number, colCount: number): ISpecialField[] => {
- const cells = [];
- for (let r = 3; r < rowCount; r++) {
- for (let c = 3; c < colCount; c++) {
- cells.push({ r, c });
- }
+ const cells = [];
+ for (let r = 3; r < rowCount; r++) {
+ for (let c = 3; c < colCount; c++) {
+ cells.push({ r, c });
}
- return cells
- .map(cell => ({
- cell,
- value: '',
- dataValidation: getIntegerDataValidation(),
- }));
-}
+ }
+ return cells.map((cell) => ({
+ cell,
+ value: '',
+ dataValidation: getIntegerDataValidation(),
+ }));
+};
-const getReportName = (data: TeacherReportFileData) => `${data.fileTitle} למורה ${data.teacher?.name} לשיעור ${data.lesson?.name} - ${data.reportMonth?.name}`;
+const getReportName = (data: TeacherReportFileData) =>
+ `${data.fileTitle} למורה ${data.teacher?.name} לשיעור ${data.lesson?.name} - ${data.reportMonth?.name}`;
const generator = new DataToExcelReportGenerator(getReportName);
diff --git a/server/src/user-init.module.ts b/server/src/user-init.module.ts
index 426be10e..dbaa113e 100644
--- a/server/src/user-init.module.ts
+++ b/server/src/user-init.module.ts
@@ -5,13 +5,11 @@ import { UserInitializationService } from './user-initialization.service';
import { ReportMonth } from './db/entities/ReportMonth.entity';
@Module({
- imports: [
- TypeOrmModule.forFeature([ReportMonth]),
- ],
+ imports: [TypeOrmModule.forFeature([ReportMonth])],
providers: [
UserInitializationService,
{ provide: USER_INITIALIZATION_SERVICE, useExisting: UserInitializationService },
],
exports: [UserInitializationService, USER_INITIALIZATION_SERVICE],
})
-export class UserInitModule { }
\ No newline at end of file
+export class UserInitModule {}
diff --git a/server/src/user-initialization.service.ts b/server/src/user-initialization.service.ts
index 4b78e01a..b95fd323 100644
--- a/server/src/user-initialization.service.ts
+++ b/server/src/user-initialization.service.ts
@@ -8,9 +8,7 @@ import { getCurrentHebrewYear, getCurrentYearMonths } from '@shared/utils/entity
@Injectable()
export class UserInitializationService implements IUserInitializationService {
- constructor(
- @InjectRepository(ReportMonth) private reportMonthRepository: Repository,
- ) { }
+ constructor(@InjectRepository(ReportMonth) private reportMonthRepository: Repository) {}
async initializeUserData(user: User): Promise {
await this.generateReportMonthsForUser(user);
@@ -18,14 +16,13 @@ export class UserInitializationService implements IUserInitializationService {
private async generateReportMonthsForUser(user: User): Promise {
const formatter = new Intl.DateTimeFormat('he', { month: 'long' });
- const reportMonths: Partial[] = getCurrentYearMonths()
- .map(monthStartDate => ({
- userId: user.id,
- name: formatter.format(monthStartDate),
- startDate: monthStartDate,
- endDate: new Date(monthStartDate.getFullYear(), monthStartDate.getMonth() + 1, 0),
- year: getCurrentHebrewYear()
- }))
+ const reportMonths: Partial[] = getCurrentYearMonths().map((monthStartDate) => ({
+ userId: user.id,
+ name: formatter.format(monthStartDate),
+ startDate: monthStartDate,
+ endDate: new Date(monthStartDate.getFullYear(), monthStartDate.getMonth() + 1, 0),
+ year: getCurrentHebrewYear(),
+ }));
await this.reportMonthRepository.save(reportMonths);
}
-}
\ No newline at end of file
+}
diff --git a/server/src/utils/__tests__/studentReportData.util.spec.ts b/server/src/utils/__tests__/studentReportData.util.spec.ts
index 63facf25..35fcc245 100644
--- a/server/src/utils/__tests__/studentReportData.util.spec.ts
+++ b/server/src/utils/__tests__/studentReportData.util.spec.ts
@@ -10,7 +10,7 @@ import {
getUnknownAbsCount,
getDisplayGrade,
getGradeEffect,
- getRelevantGrade
+ getRelevantGrade,
} from '../studentReportData.util';
import { AttReportAndGrade } from 'src/db/view-entities/AttReportAndGrade.entity';
import { GradeName } from 'src/db/entities/GradeName.entity';
@@ -28,7 +28,7 @@ describe('studentReportData.util', () => {
klassReferenceId: '789',
lessonReferenceId: '101112',
userId: '131415',
- year: '2024'
+ year: '2024',
});
});
@@ -53,15 +53,17 @@ describe('studentReportData.util', () => {
const result = getReportDataFilterBySprAndDates(ids, startDate, endDate);
- expect(result).toEqual([{
- studentReferenceId: 123,
- teacherReferenceId: 456,
- klassReferenceId: 789,
- lessonReferenceId: 101112,
- userId: 131415,
- year: 2024,
- reportDate: Between(startDate, endDate)
- }]);
+ expect(result).toEqual([
+ {
+ studentReferenceId: 123,
+ teacherReferenceId: 456,
+ klassReferenceId: 789,
+ lessonReferenceId: 101112,
+ userId: 131415,
+ year: 2024,
+ reportDate: Between(startDate, endDate),
+ },
+ ]);
});
it('should handle multiple SPR IDs', () => {
@@ -91,12 +93,16 @@ describe('studentReportData.util', () => {
userId: 131415,
studentReferenceId: In([123]),
year: 2024,
- reportDate: Between(startDate, endDate)
+ reportDate: Between(startDate, endDate),
});
});
it('should create optimized filter for multiple students with same userId and year', () => {
- const ids = ['123_456_789_101112_131415_2024', '456_456_789_101112_131415_2024', '789_456_789_101112_131415_2024'];
+ const ids = [
+ '123_456_789_101112_131415_2024',
+ '456_456_789_101112_131415_2024',
+ '789_456_789_101112_131415_2024',
+ ];
const startDate = new Date('2024-01-01');
const endDate = new Date('2024-12-31');
@@ -108,7 +114,7 @@ describe('studentReportData.util', () => {
userId: 131415,
studentReferenceId: In([123, 456, 789]),
year: 2024,
- reportDate: Between(startDate, endDate)
+ reportDate: Between(startDate, endDate),
});
});
@@ -126,15 +132,15 @@ describe('studentReportData.util', () => {
userId: 100,
studentReferenceId: 123,
year: 2024,
- reportDate: Between(startDate, endDate)
+ reportDate: Between(startDate, endDate),
},
{
isApproved: true,
userId: 200,
studentReferenceId: 456,
year: 2024,
- reportDate: Between(startDate, endDate)
- }
+ reportDate: Between(startDate, endDate),
+ },
]);
});
@@ -152,15 +158,15 @@ describe('studentReportData.util', () => {
userId: 131415,
studentReferenceId: 123,
year: 2024,
- reportDate: Between(startDate, endDate)
+ reportDate: Between(startDate, endDate),
},
{
isApproved: true,
userId: 131415,
studentReferenceId: 456,
year: 2025,
- reportDate: Between(startDate, endDate)
- }
+ reportDate: Between(startDate, endDate),
+ },
]);
});
});
@@ -168,42 +174,30 @@ describe('studentReportData.util', () => {
describe('getReportsFilterForReportCard', () => {
it('should create filter with both reportDate and global lessons', () => {
const reportDateFilter = Between(new Date('2024-01-01'), new Date('2024-12-31'));
- const result = getReportsFilterForReportCard(
- 123,
- 2024,
- reportDateFilter,
- '1,2,3',
- '4,5'
- );
+ const result = getReportsFilterForReportCard(123, 2024, reportDateFilter, '1,2,3', '4,5');
expect(result).toHaveLength(2);
expect(result[0]).toEqual({
studentReferenceId: 123,
year: 2024,
lessonReferenceId: Not(In(['4', '5'])),
- reportDate: reportDateFilter
+ reportDate: reportDateFilter,
});
expect(result[1]).toEqual({
studentReferenceId: 123,
year: 2024,
- lessonReferenceId: In(['1', '2', '3'])
+ lessonReferenceId: In(['1', '2', '3']),
});
});
it('should handle empty deny lesson ids', () => {
// Test when both global and deny lesson IDs are undefined strings
- const filterResult = getReportsFilterForReportCard(
- 123,
- 2024,
- null,
- 'undefined',
- 'undefined'
- );
+ const filterResult = getReportsFilterForReportCard(123, 2024, null, 'undefined', 'undefined');
expect(filterResult[0]).toMatchObject({
studentReferenceId: 123,
year: 2024,
- lessonReferenceId: undefined
+ lessonReferenceId: undefined,
});
});
});
@@ -214,20 +208,17 @@ describe('studentReportData.util', () => {
howManyLessons: 10,
absCount: 2,
type: 'grade',
- grade: 8500
+ grade: 8500,
} as AttReportAndGrade,
{
howManyLessons: 5,
absCount: 1,
type: 'grade',
- grade: 9000
- } as AttReportAndGrade
+ grade: 9000,
+ } as AttReportAndGrade,
];
- const mockAbsencesData = [
- { absnceCount: 1 },
- { absnceCount: 1 }
- ];
+ const mockAbsencesData = [{ absnceCount: 1 }, { absnceCount: 1 }];
it('should calculate correct report statistics', () => {
const result = calcReportsData(mockReportData, mockAbsencesData);
@@ -297,7 +288,7 @@ describe('studentReportData.util', () => {
const mockGradeNames: GradeName[] = [
{ key: 90, name: 'A' } as GradeName,
{ key: 80, name: 'B' } as GradeName,
- { key: 70, name: 'C' } as GradeName
+ { key: 70, name: 'C' } as GradeName,
];
it('should return correct grade display with grade names', () => {
@@ -323,23 +314,23 @@ describe('studentReportData.util', () => {
const mockEffects: AttGradeEffect[] = [
{ percents: 90, count: 2, effect: 5 } as AttGradeEffect,
{ percents: 80, count: 3, effect: 0 } as AttGradeEffect,
- { percents: 70, count: 4, effect: -5 } as AttGradeEffect
+ { percents: 70, count: 4, effect: -5 } as AttGradeEffect,
];
it('should return correct effect based on attendance percentage', () => {
// Effects are returned for the first matching rule where percents <= actualPercents
- expect(getGradeEffect(mockEffects, 0.95, 1)).toBe(5); // 95% matches first rule (90%)
- expect(getGradeEffect(mockEffects, 0.85, 1)).toBe(5); // 85% matches first rule (90%)
- expect(getGradeEffect(mockEffects, 0.75, 1)).toBe(5); // 75% still matches first rule (90%)
- expect(getGradeEffect(mockEffects, 0.65, 1)).toBe(5); // 65% still matches first rule (90%)
+ expect(getGradeEffect(mockEffects, 0.95, 1)).toBe(5); // 95% matches first rule (90%)
+ expect(getGradeEffect(mockEffects, 0.85, 1)).toBe(5); // 85% matches first rule (90%)
+ expect(getGradeEffect(mockEffects, 0.75, 1)).toBe(5); // 75% still matches first rule (90%)
+ expect(getGradeEffect(mockEffects, 0.65, 1)).toBe(5); // 65% still matches first rule (90%)
});
it('should return correct effect based on absence count', () => {
// Effects are returned for the first matching rule where count >= absCount
- expect(getGradeEffect(mockEffects, 0.60, 1)).toBe(5); // matches first rule (count 2)
- expect(getGradeEffect(mockEffects, 0.60, 2)).toBe(5); // exactly matches first rule count
- expect(getGradeEffect(mockEffects, 0.60, 3)).toBe(0); // matches second rule (count 3)
- expect(getGradeEffect(mockEffects, 0.60, 4)).toBe(-5); // matches third rule (count 4)
+ expect(getGradeEffect(mockEffects, 0.6, 1)).toBe(5); // matches first rule (count 2)
+ expect(getGradeEffect(mockEffects, 0.6, 2)).toBe(5); // exactly matches first rule count
+ expect(getGradeEffect(mockEffects, 0.6, 3)).toBe(0); // matches second rule (count 3)
+ expect(getGradeEffect(mockEffects, 0.6, 4)).toBe(-5); // matches third rule (count 4)
});
it('should handle null or empty effects array', () => {
@@ -347,4 +338,4 @@ describe('studentReportData.util', () => {
expect(getGradeEffect([], 0.95, 1)).toBe(0);
});
});
-});
\ No newline at end of file
+});
diff --git a/server/src/utils/studentReportData.util.ts b/server/src/utils/studentReportData.util.ts
index beae1d3a..7176fc07 100644
--- a/server/src/utils/studentReportData.util.ts
+++ b/server/src/utils/studentReportData.util.ts
@@ -1,213 +1,247 @@
-import { calcAvg, calcPercents, calcSum, getNumericValueOrNull, getUniqueValues, keepBetween, roundFractional } from "@shared/utils/reportData.util";
-import { getReportDateFilter } from "@shared/utils/entity/filters.util";
-import { FindOptionsWhere, FindOperator, In, Not, Any } from "typeorm";
-import { KnownAbsence } from "src/db/entities/KnownAbsence.entity";
-import { AttReportAndGrade } from "src/db/view-entities/AttReportAndGrade.entity";
-import { AttGradeEffect } from "src/db/entities/AttGradeEffect";
-import { GradeName } from "src/db/entities/GradeName.entity";
-import { AttendanceName } from "src/db/entities/AttendanceName.entity";
-import { getAsArray } from "@shared/utils/queryParam.util";
+import {
+ calcAvg,
+ calcPercents,
+ calcSum,
+ getNumericValueOrNull,
+ getUniqueValues,
+ keepBetween,
+ roundFractional,
+} from '@shared/utils/reportData.util';
+import { getReportDateFilter } from '@shared/utils/entity/filters.util';
+import { FindOptionsWhere, FindOperator, In, Not, Any } from 'typeorm';
+import { KnownAbsence } from 'src/db/entities/KnownAbsence.entity';
+import { AttReportAndGrade } from 'src/db/view-entities/AttReportAndGrade.entity';
+import { AttGradeEffect } from 'src/db/entities/AttGradeEffect';
+import { GradeName } from 'src/db/entities/GradeName.entity';
+import { AttendanceName } from 'src/db/entities/AttendanceName.entity';
+import { getAsArray } from '@shared/utils/queryParam.util';
interface ISprIdData {
- studentReferenceId: string;
- teacherReferenceId: string;
- klassReferenceId: string;
- lessonReferenceId: string;
- userId: string;
- year: string;
+ studentReferenceId: string;
+ teacherReferenceId: string;
+ klassReferenceId: string;
+ lessonReferenceId: string;
+ userId: string;
+ year: string;
}
export function breakSprId(id: string): ISprIdData {
- const [studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId, userId, year] = id.split('_');
+ const [studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId, userId, year] = id.split('_');
+ return {
+ studentReferenceId,
+ teacherReferenceId,
+ klassReferenceId,
+ lessonReferenceId,
+ userId,
+ year,
+ };
+}
+
+export function getReportDataFilterBySprAndDates(
+ ids: string[],
+ startDate: Date,
+ endDate: Date,
+): FindOptionsWhere[] {
+ return ids.map((id) => {
+ const { studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId, userId, year } =
+ breakSprId(id);
return {
- studentReferenceId,
- teacherReferenceId,
- klassReferenceId,
- lessonReferenceId,
- userId,
- year,
+ studentReferenceId: getNumericValueOrNull(studentReferenceId),
+ teacherReferenceId: getNumericValueOrNull(teacherReferenceId),
+ klassReferenceId: getNumericValueOrNull(klassReferenceId),
+ lessonReferenceId: getNumericValueOrNull(lessonReferenceId),
+ userId: getNumericValueOrNull(userId),
+ year: getNumericValueOrNull(year),
+ reportDate: getReportDateFilter(startDate, endDate),
};
+ });
}
-export function getReportDataFilterBySprAndDates(ids: string[], startDate: Date, endDate: Date): FindOptionsWhere[] {
- return ids.map(id => {
- const { studentReferenceId, teacherReferenceId, klassReferenceId, lessonReferenceId, userId, year } = breakSprId(id);
- return ({
- studentReferenceId: getNumericValueOrNull(studentReferenceId),
- teacherReferenceId: getNumericValueOrNull(teacherReferenceId),
- klassReferenceId: getNumericValueOrNull(klassReferenceId),
- lessonReferenceId: getNumericValueOrNull(lessonReferenceId),
- userId: getNumericValueOrNull(userId),
- year: getNumericValueOrNull(year),
- reportDate: getReportDateFilter(startDate, endDate),
- });
- });
-}
-
-export function getKnownAbsenceFilterBySprAndDates(ids: string[], startDate: Date, endDate: Date): FindOptionsWhere | FindOptionsWhere[] {
- const filters = ids.map(id => {
- const { studentReferenceId, userId, year } = breakSprId(id);
- return {
- userId: getNumericValueOrNull(userId),
- studentReferenceId: getNumericValueOrNull(studentReferenceId),
- year: getNumericValueOrNull(year),
- };
- });
-
- const userIds = getUniqueValues(filters, item => item.userId);
- const studentIds = getUniqueValues(filters, item => item.studentReferenceId);
- const years = getUniqueValues(filters, item => item.year);
-
- if (userIds.length === 1 && years.length === 1) {
- return {
- isApproved: true,
- userId: userIds[0],
- studentReferenceId: In(studentIds),
- year: years[0],
- reportDate: getReportDateFilter(startDate, endDate),
- };
- }
-
- return filters.map(filter => ({
- isApproved: true,
- reportDate: getReportDateFilter(startDate, endDate),
- ...filter,
- }));
-}
-
-export function getReportsFilterForReportCard(studentId: number, year: number, reportDateFilter: FindOperator, globalLessonIdsStr: string, denyLessonIdStr: string, klassIds?: number[]): FindOptionsWhere[] {
- const denyLessonIds = getAsArray(denyLessonIdStr);
- const lessonFilter: FindOperator = denyLessonIds?.length ? Not(In(denyLessonIds)) : undefined;
- const commonFilter: FindOptionsWhere