From d6ebf81cb5dd5184381c862158c715a73ec16a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikolas=20G=C3=B6rlitz?= Date: Mon, 14 Aug 2023 14:39:34 +0200 Subject: [PATCH] fix the course training history --- .../course/CourseAdminController.ts | 20 ++++++++++++---- .../course/CourseInformationController.ts | 17 +++++++++++-- src/controllers/login/SessionController.ts | 20 ++++++++-------- .../TrainingRequestAdminController.ts | 18 +++++++------- .../TrainingSessionAdminController.ts | 24 +++++++++---------- .../TrainingSessionController.ts | 12 ++++++---- .../_TrainingSessionAdminValidator.ts | 16 ++++++------- src/controllers/user/UserCourseController.ts | 4 +++- .../user/UserInformationAdminController.ts | 4 ++-- .../user/UserNotificationController.ts | 20 +++++++++------- src/core/Config.ts | 2 +- src/utility/helper/ValidationHelper.ts | 2 +- 12 files changed, 97 insertions(+), 62 deletions(-) diff --git a/src/controllers/course/CourseAdminController.ts b/src/controllers/course/CourseAdminController.ts index baef6ba..5825c99 100644 --- a/src/controllers/course/CourseAdminController.ts +++ b/src/controllers/course/CourseAdminController.ts @@ -5,6 +5,7 @@ import { MentorGroup } from "../../models/MentorGroup"; import { MentorGroupsBelongsToCourses } from "../../models/through/MentorGroupsBelongsToCourses"; import CourseAdminValidator from "../_validators/CourseAdminValidator"; import { ValidatorType } from "../_validators/ValidatorType"; +import { HttpStatusCode } from "axios"; /** * Gets all courses @@ -67,12 +68,23 @@ async function getEditable(request: Request, response: Response) { * Creates a new course */ async function create(request: Request, response: Response) { - const data = request.body.data; + const data = request.body.data as { + course_uuid: string; + name_de: string; + name_en: string; + description_de: string; + description_en: string; + active: string; + self_enrol: string; + training_id: string; + skill_template_id: string; + mentor_group_id: string; + }; const validation: ValidatorType = CourseAdminValidator.validateCreateRequest(data); if (validation.invalid) { - response.status(400).send({ + response.status(HttpStatusCode.BadRequest).send({ validation: validation.message, validation_failed: true, }); @@ -88,10 +100,10 @@ async function create(request: Request, response: Response) { is_active: Number(data.active) == 1, self_enrollment_enabled: Number(data.self_enrol) == 1, initial_training_type: Number(data.training_id), - skill_template_id: Number(data.skill_template_id) == 0 || isNaN(Number(data.skill_template_id)) ? null : data.skill_template_id, + skill_template_id: Number(data.skill_template_id) == 0 || isNaN(Number(data.skill_template_id)) ? null : Number(data.skill_template_id), }); if (course == null) { - response.status(500).send({ error: "An error occurred creating the course" }); + response.sendStatus(HttpStatusCode.InternalServerError); return; } diff --git a/src/controllers/course/CourseInformationController.ts b/src/controllers/course/CourseInformationController.ts index 54bd42d..d8d4b87 100644 --- a/src/controllers/course/CourseInformationController.ts +++ b/src/controllers/course/CourseInformationController.ts @@ -4,6 +4,7 @@ import { User } from "../../models/User"; import { TrainingSession } from "../../models/TrainingSession"; import { ActionRequirement } from "../../models/ActionRequirement"; import RequirementHelper from "../../utility/helper/RequirementHelper"; +import { HttpStatusCode } from "axios"; /** * Returns course information based on the provided uuid (request.query.uuid) @@ -102,7 +103,6 @@ async function getCourseTrainingInformationByUUID(request: Request, response: Re include: [ { association: User.associations.training_sessions, - as: "training_sessions", through: { attributes: ["passed", "log_id"], where: { @@ -132,7 +132,20 @@ async function getCourseTrainingInformationByUUID(request: Request, response: Re ], }); - response.send(data?.training_sessions ?? []); + if (data == null) { + response.sendStatus(HttpStatusCode.InternalServerError); + return; + } + + data.training_sessions?.sort((a, b) => { + if (a.date == null || b.date == null) { + return 0; + } + + return a.date > b.date ? 1 : -1; + }); + + response.send(data.training_sessions); } async function validateCourseRequirements(request: Request, response: Response) { diff --git a/src/controllers/login/SessionController.ts b/src/controllers/login/SessionController.ts index a2548e4..b0d10b9 100644 --- a/src/controllers/login/SessionController.ts +++ b/src/controllers/login/SessionController.ts @@ -1,18 +1,18 @@ import { User } from "../../models/User"; import { Request, Response } from "express"; import { UserSession } from "../../models/UserSession"; -import { constants } from "http2"; +import { HttpStatusCode } from "axios"; async function getUserSessions(request: Request, response: Response) { const user: User = request.body.user; const sessions = await UserSession.findAll({ where: { - user_id: user.id + user_id: user.id, }, attributes: { - exclude: ['uuid', 'expires_at', 'expires_latest'] - } + exclude: ["uuid", "expires_at", "expires_latest"], + }, }); response.send(sessions); @@ -20,19 +20,19 @@ async function getUserSessions(request: Request, response: Response) { async function deleteUserSession(request: Request, response: Response) { const user: User = request.body.user; - const query = request.body as {session_id: number}; + const query = request.body as { session_id: number }; await UserSession.destroy({ where: { user_id: user.id, - id: query.session_id - } + id: query.session_id, + }, }); - response.sendStatus(204); + response.sendStatus(HttpStatusCode.NoContent); } export default { getUserSessions, - deleteUserSession -} \ No newline at end of file + deleteUserSession, +}; diff --git a/src/controllers/training-request/TrainingRequestAdminController.ts b/src/controllers/training-request/TrainingRequestAdminController.ts index a70dc40..5c1b528 100644 --- a/src/controllers/training-request/TrainingRequestAdminController.ts +++ b/src/controllers/training-request/TrainingRequestAdminController.ts @@ -129,14 +129,16 @@ async function getByUUID(request: Request, response: Response) { TrainingRequest.associations.course, { association: TrainingRequest.associations.training_type, - include: [{ - association: TrainingType.associations.training_stations, - attributes: ['id', 'callsign', 'deactivated'], - through: { - attributes: [] - } - }] - } + include: [ + { + association: TrainingType.associations.training_stations, + attributes: ["id", "callsign", "deactivated"], + through: { + attributes: [], + }, + }, + ], + }, ], }); diff --git a/src/controllers/training-session/TrainingSessionAdminController.ts b/src/controllers/training-session/TrainingSessionAdminController.ts index 6cc36ac..043ebe3 100644 --- a/src/controllers/training-session/TrainingSessionAdminController.ts +++ b/src/controllers/training-session/TrainingSessionAdminController.ts @@ -15,7 +15,7 @@ async function createTrainingSession(request: Request, response: Response) { // TODO: Check if the mentor of the course is even allowed to create such a session! const requestUser: User = request.body.user as User; - const data = request.body.data as { course_uuid?: string, date?: string, training_type_id?: number, training_station_id?: number, user_ids?: number[] }; + const data = request.body.data as { course_uuid?: string; date?: string; training_type_id?: number; training_station_id?: number; user_ids?: number[] }; const validation = _TrainingSessionAdminValidator.validateCreateSessionRequest(data); @@ -32,9 +32,9 @@ async function createTrainingSession(request: Request, response: Response) { let courseParticipants: number[] = []; const course = await Course.findOne({ where: { - uuid: data.course_uuid + uuid: data.course_uuid, }, - include: [Course.associations.users] + include: [Course.associations.users], }); if (course == null) { @@ -43,14 +43,14 @@ async function createTrainingSession(request: Request, response: Response) { } // Filter the requested users that are also enrolled in this course. - data.user_ids?.filter((userID) => { + data.user_ids?.filter(userID => { if (course.users?.find(courseUser => courseUser.id == userID)) { courseParticipants.push(userID); } }); if (courseParticipants.length == 0) { - response.status(400).send({error: "No specified user was a member of this course."}); + response.status(400).send({ error: "No specified user was a member of this course." }); return; } @@ -61,7 +61,7 @@ async function createTrainingSession(request: Request, response: Response) { training_station_id: data.training_station_id, date: dayjs.utc(data.date).toDate(), training_type_id: data.training_type_id, - course_id: course.id + course_id: course.id, }); if (trainingSession == null) { @@ -75,8 +75,8 @@ async function createTrainingSession(request: Request, response: Response) { where: { user_id: userID, course_id: course.id, - training_type_id: data.training_type_id - } + training_type_id: data.training_type_id, + }, }); if (request == null) { @@ -87,19 +87,19 @@ async function createTrainingSession(request: Request, response: Response) { course_id: course.id, training_station_id: data.training_station_id, status: "planned", - expires: dayjs().add(1, 'month').toDate(), - training_session_id: trainingSession.id + expires: dayjs().add(1, "month").toDate(), + training_session_id: trainingSession.id, }); } else { await request.update({ status: "planned", - training_session_id: trainingSession.id + training_session_id: trainingSession.id, }); } await TrainingSessionBelongsToUsers.create({ training_session_id: trainingSession.id, - user_id: userID + user_id: userID, }); } diff --git a/src/controllers/training-session/TrainingSessionController.ts b/src/controllers/training-session/TrainingSessionController.ts index 75586c8..90d9e7a 100644 --- a/src/controllers/training-session/TrainingSessionController.ts +++ b/src/controllers/training-session/TrainingSessionController.ts @@ -5,6 +5,7 @@ import { TrainingSessionBelongsToUsers } from "../../models/through/TrainingSess import { TrainingRequest } from "../../models/TrainingRequest"; import dayjs from "dayjs"; import NotificationLibrary from "../../libraries/notification/NotificationLibrary"; +import { HttpStatusCode } from "axios"; /** * [User] @@ -34,14 +35,15 @@ async function getByUUID(request: Request, response: Response) { ], }); - // Check if the user even exists in this session, else deny the request - if (session?.users?.find((u: User) => u.id == user.id) == null) { - response.status(403).send(); + // Check if the session exists + if (session == null) { + response.sendStatus(HttpStatusCode.InternalServerError); return; } - if (session == null) { - response.status(404).send(); + // Check if the user even exists in this session, else deny the request + if (session?.users?.find((u: User) => u.id == user.id) == null) { + response.sendStatus(HttpStatusCode.Forbidden); return; } diff --git a/src/controllers/training-session/_TrainingSessionAdminValidator.ts b/src/controllers/training-session/_TrainingSessionAdminValidator.ts index f82757a..f9692f4 100644 --- a/src/controllers/training-session/_TrainingSessionAdminValidator.ts +++ b/src/controllers/training-session/_TrainingSessionAdminValidator.ts @@ -6,26 +6,26 @@ function validateCreateSessionRequest(data: any): ValidatorType { { name: "user_ids", validationObject: data.user_ids, - toValidate: [{ val: ValidationOptions.NON_NULL }] + toValidate: [{ val: ValidationOptions.NON_NULL }], }, { name: "course_uuid", validationObject: data.course_uuid, - toValidate: [{ val: ValidationOptions.NON_NULL }] + toValidate: [{ val: ValidationOptions.NON_NULL }], }, { name: "date", validationObject: data.date, - toValidate: [{ val: ValidationOptions.VALID_DATE }] + toValidate: [{ val: ValidationOptions.VALID_DATE }], }, { name: "training_type_id", validationObject: data.training_type_id, - toValidate: [{ val: ValidationOptions.NUMBER }] - } - ]) + toValidate: [{ val: ValidationOptions.NUMBER }], + }, + ]); } export default { - validateCreateSessionRequest -} \ No newline at end of file + validateCreateSessionRequest, +}; diff --git a/src/controllers/user/UserCourseController.ts b/src/controllers/user/UserCourseController.ts index 7288b25..9f6b5cb 100644 --- a/src/controllers/user/UserCourseController.ts +++ b/src/controllers/user/UserCourseController.ts @@ -101,7 +101,9 @@ async function enrolInCourse(request: Request, response: Response) { }); // If Course-Instance couldn't be found, throw an error (caught locally) - if (course == null) throw Error("Course with id " + query.course_uuid + " could not be found!"); + if (course == null) { + throw Error("Course with id " + query.course_uuid + " could not be found!"); + } // Enrol user in course const userBelongsToCourses = await UsersBelongsToCourses.findOrCreate({ diff --git a/src/controllers/user/UserInformationAdminController.ts b/src/controllers/user/UserInformationAdminController.ts index 1e93046..87bb6f2 100644 --- a/src/controllers/user/UserInformationAdminController.ts +++ b/src/controllers/user/UserInformationAdminController.ts @@ -45,8 +45,8 @@ async function getBasicUserDataByID(request: Request, response: Response) { id: query.user_id, }, attributes: { - exclude: ['createdAt', 'updatedAt'] - } + exclude: ["createdAt", "updatedAt"], + }, }); if (user == null) { diff --git a/src/controllers/user/UserNotificationController.ts b/src/controllers/user/UserNotificationController.ts index 18f7da2..dc08548 100644 --- a/src/controllers/user/UserNotificationController.ts +++ b/src/controllers/user/UserNotificationController.ts @@ -11,10 +11,12 @@ async function getNotifications(request: Request, response: Response) { user_id: user.id, }, order: [["createdAt", "desc"]], - include: [{ - association: Notification.associations.author, - attributes: ['id', 'first_name', 'last_name'] - }], + include: [ + { + association: Notification.associations.author, + attributes: ["id", "first_name", "last_name"], + }, + ], }); response.send(notifications); @@ -34,10 +36,12 @@ async function getUnreadNotifications(request: Request, response: Response) { read: false, }, order: [["createdAt", "desc"]], - include: [{ - association: Notification.associations.author, - attributes: ['id', 'first_name', 'last_name'] - }], + include: [ + { + association: Notification.associations.author, + attributes: ["id", "first_name", "last_name"], + }, + ], }); response.send(notifications); diff --git a/src/core/Config.ts b/src/core/Config.ts index 6ff699a..ef49de9 100644 --- a/src/core/Config.ts +++ b/src/core/Config.ts @@ -4,7 +4,7 @@ import Logger, { LogLevels } from "../utility/Logger"; import dayjs from "dayjs"; import utc from "dayjs/plugin/utc"; -dayjs.extend(utc) +dayjs.extend(utc); dotenv.config(); console.log(`Loading .env...`); diff --git a/src/utility/helper/ValidationHelper.ts b/src/utility/helper/ValidationHelper.ts index 24ba87d..7c11477 100644 --- a/src/utility/helper/ValidationHelper.ts +++ b/src/utility/helper/ValidationHelper.ts @@ -100,7 +100,7 @@ function validate(options: ValidationType[]): { invalid: boolean; message: any[] case ValidationOptions.VALID_DATE: if (!dayjs(toCheck).isValid()) { invalid = true; - message.push({key: opt.name, code: "VAL_NOT_VALID_DATE", message: "Parameter is not a valid date."}) + message.push({ key: opt.name, code: "VAL_NOT_VALID_DATE", message: "Parameter is not a valid date." }); } break; }