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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import teacher from "src/entities/teacher";
import transportation from 'src/entities/transportation';
import absenceType from 'src/entities/absenceType';
import studentKlassesReport from "src/entities/student-klasses-report";
import StudentEventReport from "src/components/StudentView/student-event-report";
import reportMonth from "src/entities/report-month";
import teacherReportStatus from "src/entities/teacher-report-status";
import teacherGradeReportStatus from "src/entities/teacher-grade-report-status";
Expand Down Expand Up @@ -68,7 +69,7 @@ import paymentTrack from '@shared/components/common-entities/payment-track';
import yemotCall from '@shared/components/common-entities/yemot-call';

import { isShowUsersData, isEditPagesData, isEditPaymentTracksData, isAdmin } from "@shared/utils/permissionsUtil";
import { isLessonSignature, isOnlyInLessonReport, isTeacherView, isTransportation, isAbsenceType } from 'src/utils/appPermissions';
import { isLessonSignature, isOnlyInLessonReport, isTeacherView, isTransportation, isAbsenceType, isStudentView } from 'src/utils/appPermissions';
import YemotSimulator from "@shared/components/views/YemotSimulator";
import { RegisterPage } from '@shared/components/layout/RegisterPage';
import { LoginPage } from '@shared/components/layout/LoginPage';
Expand Down Expand Up @@ -123,6 +124,7 @@ const App = () => (
{permissions => {
const onlyInLesson = isOnlyInLessonReport(permissions) && !isAdmin(permissions);
const teacherView = isTeacherView(permissions) && !isAdmin(permissions);
const studentView = isStudentView(permissions) && !isAdmin(permissions);
if (onlyInLesson) {
return (
<>
Expand Down Expand Up @@ -151,8 +153,11 @@ const App = () => (
</>
);
}


if (studentView) {
return(
<> </>
);
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont you need to have StudentEventReport here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

לא כי אני לא רוצה שיהיה ניתוב בדף הבית של תלמידה לדף דיווח.

return (
<>
<Resource name="teacher" {...teacher} options={{ menuGroup: 'data' }} icon={BadgeIcon} />
Expand All @@ -168,7 +173,6 @@ const App = () => (
<Resource name="att_report_with_report_month" {...attReportWithReportMonth} options={{ menuGroup: 'data' }} icon={ViewListIcon} />
<Resource name="grade" {...grade} options={{ menuGroup: 'data' }} icon={GradingIcon} />
<Resource name="known_absence" {...knownAbsence} options={{ menuGroup: 'data' }} icon={PlaylistRemoveIcon} />

<Resource name="student_klass_report" {...studentKlassesReport} options={{ menuGroup: 'report' }} icon={GroupWorkIcon} />
<Resource name="teacher_report_status" {...teacherReportStatus} options={{ menuGroup: 'report' }} icon={RuleIcon} />
<Resource name="teacher_grade_report_status" {...teacherGradeReportStatus} options={{ menuGroup: 'report' }} icon={RuleIcon} />
Expand Down
8 changes: 4 additions & 4 deletions client/src/GeneralLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ import ViewListIcon from '@mui/icons-material/ViewList';

import BaseLayout from "@shared/components/layout/Layout";
import BaseDashboard from '@shared/components/views/Dashboard';
import { isInLessonReport, isScannerUpload, isOnlyInLessonReport, isTeacherView } from './utils/appPermissions';
import { isInLessonReport, isScannerUpload, isOnlyInLessonReport, isTeacherView, isStudentView } from './utils/appPermissions';
import { useDashboardItems } from './settings/settingsUtil';

const isStandardView = (permissions) => !isOnlyInLessonReport(permissions) && !isTeacherView(permissions);
const shouldShowLessonReports = (permissions) => isInLessonReport(permissions) || isTeacherView(permissions);
const isStandardView = (permissions) => !isOnlyInLessonReport(permissions) && !isTeacherView(permissions) && !isStudentView(permissions);
const shouldShowLessonReports = (permissions) => (isInLessonReport(permissions) || isTeacherView(permissions));

const customMenuItems = [
// static items: render only when NOT restricted to lesson-report-only
Expand All @@ -47,7 +47,7 @@ const menuGroups = [
<MenuItemLink key="approved-absences-upload" to="/approved-absences-upload" primaryText="העלאת חיסורים מאושרים" leftIcon={<FileUploadIcon />} />
]
}),
({ permissions }) => !isOnlyInLessonReport(permissions) && ({
({ permissions }) => (!isOnlyInLessonReport(permissions) && (!isStudentView(permissions))) && ({
name: 'report', icon: <AnalyticsIcon />, routes: [
({ permissions }) => !isTeacherView(permissions) && <MenuItemLink key="student-attendance" to="/student/student-attendance" primaryText="דוח נוכחות (פיבוט)" leftIcon={<SummarizeIcon />} />,
<MenuItemLink key="percent-report-with-dates" to="/percent-report-with-dates" primaryText="דוח אחוזים לתלמידה" leftIcon={<PercentIcon />} />,
Expand Down
16 changes: 13 additions & 3 deletions client/src/RootDashboard.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import React from 'react';
import { Dashboard } from 'src/GeneralLayout';
import { useIsTeacherView } from 'src/utils/appPermissions';
import { useIsTeacherView, useIsStudentView } from 'src/utils/appPermissions';
import { TeacherGuard } from 'src/components/TeacherView/TeacherAccess';
import { StudentGuard } from './components/StudentView/StudentAccess';
import StudentEventReport from './components/StudentView/student-event-report';

export const RootDashboard = (props) => {
const isTeacherView = useIsTeacherView();
const isStudentView = useIsStudentView();

if (isTeacherView) {
return (
<TeacherGuard>
Expand All @@ -13,7 +17,13 @@ export const RootDashboard = (props) => {

);
}
else {
return <Dashboard {...props} />;
else if (isStudentView) {
return (
<StudentGuard>
<StudentEventReport />
</StudentGuard>
);
}
else return <Dashboard {...props} />;

}
118 changes: 118 additions & 0 deletions client/src/components/StudentView/StudentAccess.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
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 StudentGuard = ({ children }) => {
const dataProvider = useDataProvider();
const notify = useNotify();
const reset = useResetStore();
const { value: student, set: setStudent, clear } = useObjectStore("student");

const handleLogout = () => {
clear();
reset();
};

if (student) {
return (
<Box display="flex" flexDirection="column" width="100%">
<Paper
elevation={1}
sx={{
p: 2,
mb: 2,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Typography variant="h6" component="div">
שלום התלמידה <strong>{student.name}</strong>
</Typography>
<Button
variant="outlined"
color="secondary"
onClick={handleLogout}
startIcon={<LogoutIcon />}
>
התנתק
</Button>
</Paper>
<Box flexGrow={1}>{children}</Box>
</Box>
);
}

const handleSubmit = async (values) => {
const { tz } = values;
const result = await dataProvider.getList("student", {
pagination: { page: 1, perPage: 1 },
filter: { tz },
});
const student = result.data[0] || null;

if (student) {
setStudent(student);
} else {
notify("Student not found", { type: "warning" });
}
};

return (
<Box
display="flex"
flexDirection="column"
alignItems="center"
justifyContent="center"
minHeight="100vh"
bgcolor="grey.100"
>
<Card sx={{ minWidth: 300, maxWidth: 400, p: 2, boxShadow: 3 }}>
<Box display="flex" flexDirection="column" alignItems="center" mb={2}>
<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
כניסת תלמידה
</Typography>
</Box>
<CardContent>
<SimpleForm
key="view-search-form"
onSubmit={handleSubmit}
resource="student"
toolbar={
<Toolbar
sx={{
display: "flex",
justifyContent: "center",
width: "100%",
bgcolor: "transparent",
p: 0,
}}
>
<SaveButton
label="כניסה"
variant="contained"
fullWidth
color="secondary"
/>
</Toolbar>
}
>
<TextInput source="tz" label="ת.ז" fullWidth variant="outlined" />
</SimpleForm>
</CardContent>
</Card>
</Box>
);
};
145 changes: 145 additions & 0 deletions client/src/components/StudentView/student-event-report.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import React from 'react';
import {
TextInput,
NumberInput,
DateInput,
BooleanInput,
required,
useNotify,
useResetStore,
useDataProvider,
useGetOne,
Create,
SimpleForm,
FormDataConsumer,
Loading,
} from 'react-admin';
import { filterByUserIdAndYear } from '@shared/components/fields/CommonReferenceInputFilter';
import CommonReferenceInput from '@shared/components/fields/CommonReferenceInput';
import { defaultYearFilter, yearChoices } from '@shared/utils/yearFilter';
import CommonAutocompleteInput from '@shared/components/fields/CommonAutocompleteInput';
import { handleActionSuccess, handleError } from '@shared/utils/notifyUtil';
import { useObjectStore } from "src/utils/storeUtil";

const DynamicFields = ({ absenceType, isLoading }) => {

if (isLoading) return <Loading loadingPrimary="טוען שדות..." />;
if (!absenceType?.requiredLabels?.length) return null;
return (
<div style={{ padding: '10px 0', width: '100%', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
{absenceType.requiredLabels.map((label, index) => (
<TextInput
key={`${absenceType.id}-${label}`}
source={`dynamic_${label}`}
label={label}
validate={required()}
style={{ flex: 1, minWidth: '200px' }}
/>
))}
</div>
);
};

const formatPayload = (values, userId, studentId, absenceType) => {
const allowedLabels = absenceType?.requiredLabels || [];

const extraInfo = Object.keys(values)
.filter(key => {
if (!key.startsWith('dynamic_')) return false;
const label = key.replace('dynamic_', '');
return allowedLabels.includes(label) && values[key];
})
.map(key => {
const label = key.replace('dynamic_', '');
return `${label}: ${values[key]}`;
})
.join(' | ');

const cleanValues = { ...values };
Object.keys(cleanValues).forEach(key => {
if (key.startsWith('dynamic_')) delete cleanValues[key];
});

return {
...cleanValues,
userId: userId,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userid is added by default so not needed here (unless in isAdmin mode, if relevant)

studentReferenceId: studentId,
year: parseInt(defaultYearFilter.year),
reportDate: cleanValues.reportDate,
absnceCount: parseFloat(cleanValues.absnceCount) || 1,
isApproved: true,
reason: cleanValues.reason ? `${cleanValues.reason} [${extraInfo}]` : extraInfo,
};
};

const StudentEventReport = (props) => {
const dataProvider = useDataProvider();
const notify = useNotify();
const reset = useResetStore();
const { value: student, clear } = useObjectStore("student");
const [selectedAbsenceTypeId, setSelectedAbsenceTypeId] = React.useState(null);
const { data: absenceType, isLoading } = useGetOne(
'absence_type',
{ id: selectedAbsenceTypeId },
{ enabled: !!selectedAbsenceTypeId }
);

const handleSave = async (values) => {
try {
const quota = absenceType?.quota;

if (quota) {
const { data: existingAbsences } = await dataProvider.getList('known_absence', {
pagination: { page: 1, perPage: 1000 },
filter: {
studentReferenceId: student.id,
absenceTypeId: values.absenceTypeId,
year: values.year
},
});

const currentTotal = existingAbsences.reduce((sum, item) => sum + (parseFloat(item.absnceCount) || 0), 0);
const requestedAmount = parseFloat(values.absnceCount || 1);

if (currentTotal + requestedAmount > quota) {
notify(
`חריגה מהמכסה! המכסה היא ${quota}. נוצלו ${currentTotal}, ניסיון להוסיף ${requestedAmount}.`,
{ type: 'error', autoHideDuration: 10000 }
);
return;
}
}

const formattedData = formatPayload(values, student.userId, student.id, absenceType)
const response = await dataProvider.create('known_absence', { data: formattedData });
handleActionSuccess(notify)(response);
clear();
reset();
} catch (error) {
handleError(notify)(error);
}
};

return (
<Create resource="known_absence" {...props} {...props} title="הוספת דיווח אירוע">
<SimpleForm onSubmit={handleSave} sanitizeEmptyValues>
<CommonReferenceInput source="klassReferenceId" reference="klass" validate={required()} dynamicFilter={filterByUserIdAndYear} />
<CommonReferenceInput source="absenceTypeId" reference="absence_type" dynamicFilter={filterByUserIdAndYear} validate={required()}
onChange={(e) => setSelectedAbsenceTypeId(e?.target?.value ?? e)} />
<FormDataConsumer>
{() => (
<DynamicFields absenceType={absenceType} isLoading={isLoading} />
)}
</FormDataConsumer>
<DateInput source="reportDate" validate={required()} defaultValue={new Date()} />
<NumberInput source="absnceCount" defaultValue={1} min={0} step={0.5} />
<TextInput source="senderName" />
<TextInput source="reason" multiline fullWidth />
<CommonAutocompleteInput source="year" choices={yearChoices} defaultValue={defaultYearFilter.year} disabled />
<BooleanInput source="isApproved" defaultValue={true} disabled />
</SimpleForm>
</Create>
);
};

export default StudentEventReport;
3 changes: 2 additions & 1 deletion client/src/domainTranslations.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export default {
reason: 'סיבה',
comment: 'הערה',
isApproved: 'מאושר',
absenceTypeId: 'סוג אירוע',
absenceTypeId: 'סוג אירוע',
}
},
lesson: {
Expand Down Expand Up @@ -213,6 +213,7 @@ export default {
name: 'אירוע |||| אירועים',
fields: {
...generalResourceFieldsTranslation,
absenceTypeId: 'סוג אירוע',
name: 'שם האירוע',
quota: 'מכסה שנתית',
requiredLabels: 'שדות חובה לדיווח',
Expand Down
Loading