Skip to content

Commit

Permalink
fix typescript and eslint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
vgimonnet-wt committed Feb 19, 2024
1 parent 7d10b58 commit dd56562
Show file tree
Hide file tree
Showing 36 changed files with 159 additions and 128 deletions.
2 changes: 1 addition & 1 deletion server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ async function startApp() {
if (port === false) {
logger.error(`Exiting. Invalid port to use: %s`, port);
} else {
const server = Server(app);
const server = new Server(app);
// --- Start socket server ---
startSocketServer(server);
server.listen(port);
Expand Down
2 changes: 1 addition & 1 deletion server/authentication/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export async function login(req: Request, res: Response): Promise<void> {
await getConnection()
.createQueryBuilder()
.update(Project)
.set({ isCollaborationActive: false, joinCode: false })
.set({ isCollaborationActive: false, joinCode: null })
.where({ userId: user.id, isCollaborationActive: true })
.execute();

Expand Down
2 changes: 2 additions & 0 deletions server/authentication/loginStudent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export async function loginStudent(req: Request, res: Response): Promise<void> {
project === undefined ||
teacher === undefined ||
sequency === undefined ||
sequency.project === undefined ||
sequency.project.user === undefined ||
project.id !== sequency.project.id ||
teacher.id !== sequency.project.user.id ||
project.isCollaborationActive !== true
Expand Down
5 changes: 3 additions & 2 deletions server/controllers/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ type PostProjectData = {
soundUrl?: string | null;
soundVolume?: number | null;
musicBeginTime?: number;
videoJobId?: string | null;
};
const POST_PROJECT_SCHEMA: JSONSchemaType<PostProjectData> = {
type: 'object',
Expand Down Expand Up @@ -265,7 +266,7 @@ projectController.post({ path: '/', userType: UserType.CLASS }, async (req, res,
newProject.soundUrl = data.soundUrl || null;
newProject.soundVolume = data.soundVolume || null;
newProject.musicBeginTime = data.musicBeginTime || 0;
newProject.videoJobId = data.videoJobId || 0;
newProject.videoJobId = data.videoJobId || null;
const languageCode = getQueryString(req.query.languageCode) || req.cookies?.['app-language'] || 'fr';
newProject.languageCode = languageCode;
const newQuestions: Question[] = [];
Expand Down Expand Up @@ -370,7 +371,7 @@ projectController.put({ path: '/:id', userType: UserType.CLASS }, async (req, re
project.joinCode = null;
} else if (data.isCollaborationActive === true) {
project.isCollaborationActive = true;
project.joinCode = data.joinCode;
project.joinCode = data.joinCode || null;
// set collaboration mode to false on each user project
await getConnection()
.createQueryBuilder()
Expand Down
2 changes: 2 additions & 0 deletions server/controllers/questions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Title } from '../../types/models/title.type';
import { Question } from '../entities/question';
import { UserType } from '../entities/user';
import { ajv, sendInvalidDataError } from '../lib/json-schema-validator';
import { logger } from '../lib/logger';
import { getQueryString } from '../utils/get-query-string';
import { Controller } from './controller';

Expand Down Expand Up @@ -253,6 +254,7 @@ questionController.put({ path: '/:id', userType: UserType.CLASS }, async (req, r
question.soundUrl = data.soundUrl !== undefined ? data.soundUrl : question.soundUrl;
question.soundVolume = data.soundVolume !== undefined ? data.soundVolume : question.soundVolume;
const dataStatus = data.status;
logger.info(`dataStatus: ${dataStatus}`);
if (dataStatus !== undefined && dataStatus !== null) {
question.status = dataStatus;
question.feedback = [QuestionStatus.ONGOING, QuestionStatus.PREMOUNTING].includes(dataStatus) && data.feedback ? data.feedback : null;
Expand Down
9 changes: 4 additions & 5 deletions server/controllers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,12 @@ userController.post({ path: '' }, async (req, res) => {

const fromAdmin = req.user !== undefined && req.user.type === UserType.PLMO_ADMIN;
if (!fromAdmin) {
const isValid: boolean = (await getRepository(Invite).count({ where: { token: data.inviteCode } })) > 0;
if (!isValid) {
throw new AppError('forbidden', ['Invite code provided is invalid.']);
} else {
if (data.expired_at < new Date().toISOString()) {
const invite = await getRepository(Invite).findOne({ where: { token: data.inviteCode } });
if (invite === undefined || invite.expired_at < new Date()) {
if (invite !== undefined) {
await getRepository(Invite).delete({ token: data.inviteCode });
}
throw new AppError('forbidden', ['Invite code provided is invalid.']);
}
}

Expand Down
3 changes: 2 additions & 1 deletion server/lib/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const getDBConfig = (): ConnectionOptions | null => {
}

const options = {
logging: process.env.NODE_ENV !== 'production',
logging: false,
// logging: process.env.NODE_ENV !== 'production',
entities: [path.join(__dirname, '../entities/*.js')],
migrations: [path.join(__dirname, '../migration/**/*.js')],
synchronize: true,
Expand Down
2 changes: 1 addition & 1 deletion server/middlewares/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ export function authenticate(userType: UserType | undefined = undefined): Reques
if (data.isStudent) {
const user: User = ANONYMOUS_USER;
const teacher = await getRepository(User).findOne({ where: { id: data.teacherId } });
user.teacherId = teacher.id;
const project = await getRepository(Project).findOne({ where: { id: data.projectId } });
const sequency = await getRepository(Question).findOne({ where: { id: data.sequencyId }, relations: ['project', 'project.user'] });

Expand All @@ -97,6 +96,7 @@ export function authenticate(userType: UserType | undefined = undefined): Reques
) {
throw new AppError('forbidden');
}
user.teacherId = teacher.id;
req.user = user;
next();
} else {
Expand Down
3 changes: 2 additions & 1 deletion server/socket/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { Server as HttpServer } from 'http';
import type { Project } from 'server/entities/project';
import type { Question } from 'server/entities/question';
import type { Socket } from 'socket.io';
import { Server } from 'socket.io';

import type { AlertStudentData, AlertTeacherData } from '../../types/models/socket.type';

export function startSocketServer(server) {
export function startSocketServer(server: HttpServer) {
const io = new Server(server, {
cors: {
origin: '*',
Expand Down
4 changes: 2 additions & 2 deletions src/api/projects/projects.pdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export type GetPDFParams = {
scenarioDescription: string;
questions: Question[];
languageCode: string;
soundUrl: string | null;
soundVolume: number | null;
soundUrl?: string | null;
soundVolume?: number | null;
musicBeginTime?: number;
};

Expand Down
2 changes: 1 addition & 1 deletion src/api/projects/projects.put.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type PUTParams = {
soundVolume?: number | null;
musicBeginTime?: number;
isCollaborationActive?: boolean;
joinCode?: number;
joinCode?: number | null;
};

export const updateProject = async ({ projectId, ...data }: PUTParams): Promise<PUTResponse> => {
Expand Down
2 changes: 2 additions & 0 deletions src/api/questions/questions.put.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { UseMutationOptions } from 'react-query';
import { useMutation, useQueryClient } from 'react-query';

import type { HttpRequestError } from 'src/utils/http-request';
import { httpRequest } from 'src/utils/http-request';
import type { Question, QuestionStatus } from 'types/models/question.type';
import type { Title } from 'types/models/title.type';
Expand All @@ -15,6 +16,7 @@ type PUTParams = {
soundUrl?: string | null;
soundVolume?: number | null;
status?: QuestionStatus | null;
feedback?: string | null;
};

export const updateQuestion = async ({ questionId, ...data }: PUTParams): Promise<PUTResponse> => {
Expand Down
76 changes: 42 additions & 34 deletions src/components/collaboration/AlertModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { useRouter } from 'next/router';
import React from 'react';

import { Modal } from '../layout/Modal';
import useQuery from 'src/hooks/useQuery';
import type { ModalProps } from '../layout/Modal/Modal';
import { useTranslation } from 'src/i18n/useTranslation';
import { COLORS } from 'src/utils/colors';
import { useQueryNumber, useQueryString } from 'src/utils/useQueryId';
import { QuestionStatus } from 'types/models/question.type';

export const AlertModal: React.FunctionComponent = () => {
Expand All @@ -14,44 +15,53 @@ export const AlertModal: React.FunctionComponent = () => {
const [modalTitle, setModalTitle] = React.useState('');
const [modalContent, setModalContent] = React.useState('');
const [hasConfirmButton, setHasConfirmButton] = React.useState(false);
const [route, setRoute] = React.useState(null);
const [route, setRoute] = React.useState('');
const router = useRouter();

const query = useQuery();
// retrieve query params
const alert: string | undefined = useQueryString('alert');
const sequency: number | undefined = useQueryNumber('sequency');
const type: string | undefined = useQueryString('type');
const status: number | undefined = useQueryNumber('status');
const projectId: string | undefined = useQueryString('projectId');

React.useEffect(() => {
if (!query) return;
setModal(query);
}, [query]);
if (alert !== undefined && alert === 'teacher' && sequency !== undefined && projectId !== undefined && status !== undefined) {
setModalForTeacher();
} else if (alert !== undefined && alert == 'student' && type !== undefined) {
setModalForStudent();
}

return;
}, [alert]);

Check warning on line 36 in src/components/collaboration/AlertModal.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook React.useEffect has missing dependencies: 'projectId', 'sequency', 'setModalForStudent', 'setModalForTeacher', 'status', and 'type'. Either include them or remove the dependency array

const setModalForStudent = () => {
const isFeedback = type === 'feedback';
setModalTitle(t(`collaboration_alert_modal_student_title_${isFeedback ? 'feedback' : 'ok'}`));
setModalContent(t(`collaboration_alert_modal_student_content_${isFeedback ? 'feedback' : 'ok'}`));
setShowModal(true);
};

const setModal = ({ alert, sequency, type, status, projectId }) => {
if (alert && alert === 'teacher') {
setModalTitle(t('collaboration_alert_modal_teacher_title'));
if (sequency) {
setModalContent(t('collaboration_alert_modal_teacher_content', { color: COLORS[sequency], sequency: parseInt(sequency) + 1 }));
} else {
setModalContent(t('collaboration_alert_modal_teacher_content_empty'));
}
const setModalForTeacher = () => {
setModalTitle(t('collaboration_alert_modal_teacher_title'));

if (sequency && projectId && status && [QuestionStatus.STORYBOARD, QuestionStatus.SUBMITTED].includes(parseInt(status))) {
setHasConfirmButton(true);
setRoute(
parseInt(status) === QuestionStatus.STORYBOARD
? `/create/3-storyboard?projectId=${projectId}`
: `/create/4-pre-mounting/edit?question=${sequency}&projectId=${projectId}`,
);
}
setShowModal(true);
} else if (alert && alert === 'student') {
const isFeedback = type === 'feedback';
setModalTitle(t(`collaboration_alert_modal_student_title_${isFeedback ? 'feedback' : 'ok'}`));
setModalContent(t(`collaboration_alert_modal_student_content_${isFeedback ? 'feedback' : 'ok'}`));
setShowModal(true);
if (sequency !== undefined) {
setModalContent(t('collaboration_alert_modal_teacher_content', { color: COLORS[sequency], sequency: sequency + 1 }));
} else {
setModalContent(t('collaboration_alert_modal_teacher_content_empty'));
}

setHasConfirmButton(true);
setRoute(
status === QuestionStatus.STORYBOARD
? `/create/3-storyboard?projectId=${projectId}`
: `/create/4-pre-mounting/edit?question=${sequency}&projectId=${projectId}`,
);
setShowModal(true);
};

const closeModal = (goToPage: boolean = false) => {
if (goToPage) {
if (goToPage && route) {
router.push(route);
} else {
delete router.query.alert;
Expand All @@ -64,19 +74,17 @@ export const AlertModal: React.FunctionComponent = () => {
setModalContent('');
setModalTitle('');
setHasConfirmButton(false);
setRoute(null);
setRoute('');
setShowModal(false);
};

const modalProps = {
const modalProps: ModalProps = {
isOpen: showModal,
onClose: () => closeModal(),
onConfirm: hasConfirmButton ? () => closeModal(true) : null,
onConfirm: hasConfirmButton ? () => closeModal(true) : undefined,
title: modalTitle,
cancelLabel: t('close'),
confirmLabel: t('see'),
ariaLabelledBy: '',
ariaDescribedBy: '',
};

return (
Expand Down
2 changes: 1 addition & 1 deletion src/components/collaboration/ButtonShowFeedback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const ButtonShowFeedback: React.FunctionComponent<ButtonShowFeedbackProps

return (
<Button
component="a"
as="a"
variant="contained"
color="secondary"
style={{
Expand Down
9 changes: 1 addition & 8 deletions src/components/collaboration/FeedbackModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,7 @@ export const FeedbackModal: React.FunctionComponent<FeedbackModalProps> = ({ fee
const { t } = useTranslation();

return (
<Modal
isOpen={isOpen}
onClose={onClose}
title={t('collaboration_modal_feedback_title')}
cancelLabel={t('close')}
ariaLabelledBy=""
ariaDescribedBy=""
>
<Modal isOpen={isOpen} onClose={onClose} title={t('collaboration_modal_feedback_title')} cancelLabel={t('close')}>
{feedback}
</Modal>
);
Expand Down
8 changes: 5 additions & 3 deletions src/components/collaboration/FormFeedback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ export const FormFeedback: React.FunctionComponent<FormFeedbackProps> = ({ quest
updateProjectSocket(updatedProject);
}

alertStudentSocket({ room: `project-${project.id}_question-${question.id}`, feedback: feedbackData, projectId: project.id });
if (project) {
alertStudentSocket({ room: `project-${project.id}_question-${question.id}`, feedback: feedbackData, projectId: project.id });
}
} catch (err) {
console.error(err);
sendToast({ message: t('unknown_error'), type: 'error' });
Expand Down Expand Up @@ -97,7 +99,7 @@ export const FormFeedback: React.FunctionComponent<FormFeedbackProps> = ({ quest
}}
>
<Button
component="a"
as="a"
variant="contained"
color="secondary"
style={{
Expand All @@ -109,7 +111,7 @@ export const FormFeedback: React.FunctionComponent<FormFeedbackProps> = ({ quest
label={t('collaboration_form_feedback_btn_feedback')}
></Button>
<Button
component="a"
as="a"
variant="contained"
color="secondary"
style={{
Expand Down
5 changes: 4 additions & 1 deletion src/components/collaboration/NextStepButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ export const NextStepButton: React.FunctionComponent<NextStepButtonProps> = ({ s
if (updatedProject) {
updateProjectSocket(updatedProject);
}
alertTeacher({ projectId: project.id, sequencyId, sequencyOrder, status: newStatus });

if (project) {
alertTeacher({ projectId: project.id, sequencyId, sequencyOrder, status: newStatus });
}
}
} catch (err) {
console.error(err);
Expand Down
4 changes: 1 addition & 3 deletions src/components/collaboration/StatusModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { QuestionStatus, type Question } from 'types/models/question.type';

type onConfirmData = {
question: Question;
status: QuestionStatus;
status?: QuestionStatus;
};

interface StatusModalProps {
Expand Down Expand Up @@ -41,8 +41,6 @@ export const StatusModal: React.FunctionComponent<StatusModalProps> = ({ questio
title={t('sequency_status_modal_title')}
cancelLabel={t('close')}
confirmLabel={t('validate')}
ariaLabelledBy=""
ariaDescribedBy=""
>
<Field
name="sequency-status"
Expand Down
2 changes: 2 additions & 0 deletions src/components/create/DiaporamaPlayer/DiaporamaPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ export const DiaporamaPlayer = ({
if (
isQuestionEditing &&
currentQuestion &&
currentQuestion.soundUrl &&
!audioRef.current?.src.includes(currentQuestion.soundUrl) &&
audioRef.current?.duration &&
audioRef.current?.duration > 0 &&
audioRef.current?.currentTime === 0
) {
Expand Down
3 changes: 1 addition & 2 deletions src/components/layout/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { CircularProgress } from '../CircularProgress';
import { Title } from '../Typography';
import styles from './modal.module.scss';

type ModalProps = {
export type ModalProps = {
// --
isOpen: boolean;
onClose: () => void;
Expand Down Expand Up @@ -54,7 +54,6 @@ export const Modal = ({
onClose();
}
}}
style={{ zIndex: '99999' }}
>
<Dialog.Portal>
<Dialog.Overlay className={styles.overlay} />
Expand Down
Loading

0 comments on commit dd56562

Please sign in to comment.