Skip to content

Commit

Permalink
new logic
Browse files Browse the repository at this point in the history
  • Loading branch information
YanLabarthe committed Sep 11, 2023
1 parent ee59648 commit 339a28f
Show file tree
Hide file tree
Showing 12 changed files with 420 additions and 390 deletions.
8 changes: 8 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ module.exports = {
});
return config;
},
webpackDevMiddleware: (config) => {
// Enable hot reloading
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
};
return config;
},
experimental: { esmExternals: false },
eslint: {
// ESLint is already called before building with nextJS. So no need here.
Expand Down
1 change: 1 addition & 0 deletions server/controllers/classroom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ classroomController.post({ path: '', userType: UserType.TEACHER }, async (req: R
if (!createClassroomValidator(data)) {
sendInvalidDataError(createClassroomValidator);
}

if (!req.user) {
throw new AppError('Forbidden', ErrorCode.UNKNOWN);
}
Expand Down
35 changes: 27 additions & 8 deletions server/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -824,17 +824,36 @@ userController.delete({ path: '/:userId/linked-students/:studentId' }, async (re
});

// Get the visibility parameters for Family members
userController.get({ path: '/visibility-params', userType: UserType.FAMILY }, async (req: Request, res: Response) => {
userController.get({ path: '/:id/visibility-params/', userType: UserType.FAMILY }, async (req: Request, res: Response) => {
if (!req.user) {
throw new AppError('Forbidden', ErrorCode.UNKNOWN);
}
const visibilityParams = await AppDataSource.getRepository(UserToStudent)
.createQueryBuilder('userStudent')
.innerJoinAndSelect('userStudent.student', 'student')
.innerJoinAndSelect('student.classroom', 'classroom')
.where('userStudent.user = :familyId', { familyId: req.user.id })
.getRawMany(); //* Here it's getRawMany because for some reason we lost 2 attributes otherwise classroom.userId and classroom.villageId
res.json(visibilityParams);
const id = parseInt(req.params.id, 10) || 0;
const user = await AppDataSource.getRepository(User).findOne({ where: { id }, relations: ['userToStudents', 'userToStudents.student'] });

if (user && user.type === UserType.TEACHER) {
const teacherClassroom = await AppDataSource.getRepository(Classroom).findOne({
where: { user: { id: user.id } },
});
return res.json(teacherClassroom);
}

if (user && user.type === UserType.FAMILY) {
const classrooms = [];

for (const student of user.userToStudents) {
const classroom = await AppDataSource.getRepository(Classroom).findOne({
where: { students: { id: student.student.id } },
});
if (classroom) {
classrooms.push(classroom);
}
}

return res.json(classrooms);
}

return res.json([]);
});

userController.get({ path: '/get-student-vp', userType: UserType.FAMILY }, async (req: Request, res: Response) => {
Expand Down
14 changes: 14 additions & 0 deletions src/api/user/user.get.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { axiosRequest } from 'src/utils/axiosRequest';
import type { Student } from 'types/student.type';
import type { User } from 'types/user.type';
import { UserType } from 'types/user.type';

export const getUsers = async () => {
const response = await axiosRequest({
Expand All @@ -25,3 +27,15 @@ export const getLinkedStudentsToUser = async (userId: number) => {
}
};

export const getUserVisibilityFamilyParams = async (user: User) => {
if (user.type === UserType.FAMILY || user.type === UserType.TEACHER) {
const response = await axiosRequest({
method: 'GET',
url: `/users/${user.id}/visibility-params`,
});
if (response.error) return null;
console.log('User visibility params: ', response.data);
return response.data;
}
return [];
};
26 changes: 11 additions & 15 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// import SearchIcon from '@mui/icons-material/Search';

import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';

import SettingsIcon from '@mui/icons-material/Settings';
import { Button, FormControl, InputLabel, Select } from '@mui/material';
import IconButton from '@mui/material/IconButton';
// import InputBase from '@mui/material/InputBase';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';

import AccessControl from './AccessControl';
import { getClassroomOfStudent } from 'src/api/student/student.get';
import { getLinkedStudentsToUser } from 'src/api/user/user.get';
import { updateUser } from 'src/api/user/user.put';
Expand All @@ -32,7 +32,7 @@ export const Header = () => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

const open = Boolean(anchorEl);

//* NOTE: might be interesting to make a hook for this below
const isPelico =
(user !== null && user.type === UserType.MEDIATOR) ||
Expand Down Expand Up @@ -85,12 +85,12 @@ export const Header = () => {
setUser({ ...user, country: { isoCode: classroomOfStudent?.country?.isoCode, name: '' } });

// updateUser(user?.id, {country: });
} catch (err) { }
} catch (err) {}
}
setIsModalOpen(false);
};

useEffect(()=>{
useEffect(() => {
console.log('user ===', user);
}, [user]);

Expand Down Expand Up @@ -187,9 +187,7 @@ export const Header = () => {
>
<MenuItem onClick={() => goToPage('/mon-compte')}>Mon compte</MenuItem>
{user.type !== UserType.FAMILY && <MenuItem onClick={() => goToPage('/mes-videos')}>Mes vidéos</MenuItem>}
<AccessControl featureName="id-family" key={user?.id || 'default'}>
{user.type === UserType.TEACHER ? <MenuItem onClick={() => goToPage('/familles/1')}>Mes familles</MenuItem> : null}{' '}
</AccessControl>
{user.type === UserType.TEACHER ? <MenuItem onClick={() => goToPage('/familles/1')}>Mes familles</MenuItem> : null}{' '}
<MenuItem onClick={logout}>
<span className="text text--alert">Se déconnecter</span>
</MenuItem>
Expand All @@ -206,8 +204,8 @@ export const Header = () => {
{selectedStudent
? `${selectedStudent.firstname} ${selectedStudent.lastname}`
: linkedStudents.length > 0
? `${linkedStudents[0].firstname} ${linkedStudents[0].lastname}`
: 'Eleve non selectionne'}
? `${linkedStudents[0].firstname} ${linkedStudents[0].lastname}`
: 'Eleve non selectionne'}
</span>
<Button variant="contained" color="secondary" size="small" style={{ margin: '-1px -1px 0 0' }} onClick={showSelectStudentModal}>
{linkedStudents?.length > 0 ? 'Changer' : 'Choisir un élève'}
Expand Down Expand Up @@ -288,9 +286,7 @@ export const Header = () => {
>
<MenuItem onClick={() => goToPage('/mon-compte')}>Mon compte</MenuItem>
{user.type !== UserType.FAMILY && <MenuItem onClick={() => goToPage('/mes-videos')}>Mes vidéos</MenuItem>}
<AccessControl featureName="id-family" key={user?.id || 'default'}>
{user.type === UserType.TEACHER ? <MenuItem onClick={() => goToPage('/familles/1')}>Mes familles</MenuItem> : null}{' '}
</AccessControl>
{user.type === UserType.TEACHER ? <MenuItem onClick={() => goToPage('/familles/1')}>Mes familles</MenuItem> : null}{' '}
<MenuItem onClick={logout}>
<span className="text text--alert">Se déconnecter</span>
</MenuItem>
Expand Down
5 changes: 5 additions & 0 deletions src/components/accueil/Accueil.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Button } from '@mui/material';

import { filterActivitiesByTerm, filterActivitiesWithLastMimicGame } from './Filters/FilterActivities';
import { LinkChild } from './LinkChild';
import { getUserVisibilityFamilyParams } from 'src/api/user/user.get';
import { Base } from 'src/components/Base';
import { KeepRatio } from 'src/components/KeepRatio';
import { WorldMap } from 'src/components/WorldMap';
Expand Down Expand Up @@ -86,6 +87,10 @@ export const Accueil = () => {
);
}

if ((user && user.type === UserType.FAMILY) || (user && user.type === UserType.TEACHER)) {
getUserVisibilityFamilyParams(user);
}

return (
<Base showSubHeader>
{village && selectedPhase <= village.activePhase ? (
Expand Down
6 changes: 5 additions & 1 deletion src/contexts/classroomContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useEffect } from 'react';

import { UserContext } from './userContext';
import { VillageContext } from './villageContext';
Expand Down Expand Up @@ -284,6 +284,10 @@ export const ClassroomContextProvider = ({ children }: ClassroomContextProviderP
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [createClassroom, fetchClassroom, getStudents, user]);

useEffect(() => {
console.log('classroom ===', classroom);
}, [classroom]);

const value = React.useMemo(
() => ({
classroom,
Expand Down
14 changes: 8 additions & 6 deletions src/contexts/userContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useRouter } from 'next/router';
import React from 'react';
import React, { useEffect } from 'react';

import { axiosRequest } from 'src/utils/axiosRequest';
import type { Student } from 'types/student.type';
Expand All @@ -10,7 +10,7 @@ type UserContextFunc = Promise<{ success: boolean; errorCode: number }>;

interface UserContextValue {
user: User | null;
selectedStudent: Student | null;
selectedStudent: number;
isLoggedIn: boolean;
login(username: string, password: string, remember: boolean): UserContextFunc;
loginWithSso(code: string): UserContextFunc;
Expand All @@ -31,7 +31,7 @@ interface UserContextValue {

export const UserContext = React.createContext<UserContextValue>({
user: null,
selectedStudent: null,
selectedStudent: 1,
isLoggedIn: false,
login: async () => ({ success: false, errorCode: 0 }),
loginWithSso: async () => ({ success: false, errorCode: 0 }),
Expand All @@ -57,9 +57,7 @@ interface UserContextProviderProps {

export const UserContextProvider = ({ user, setUser, children }: React.PropsWithChildren<UserContextProviderProps>) => {
const router = useRouter();
const [selectedStudent, setSelectedStudent] = React.useState<Student | null>(null);

// const [linkedStudents, setLinkedStudents] = React.useState<Student[]>([]);
const [selectedStudent, setSelectedStudent] = React.useState<number>(1);

React.useEffect(() => {
if (
Expand Down Expand Up @@ -351,6 +349,10 @@ export const UserContextProvider = ({ user, setUser, children }: React.PropsWith
[user],
);

useEffect(() => {
console.log('user===', user);
}, [user]);

const value = React.useMemo(
() => ({
user,
Expand Down
Loading

0 comments on commit 339a28f

Please sign in to comment.