Skip to content

Commit

Permalink
fix the course training history
Browse files Browse the repository at this point in the history
  • Loading branch information
ngoerlitz committed Aug 14, 2023
1 parent e252b99 commit d6ebf81
Show file tree
Hide file tree
Showing 12 changed files with 97 additions and 62 deletions.
20 changes: 16 additions & 4 deletions src/controllers/course/CourseAdminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
});
Expand All @@ -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;
}

Expand Down
17 changes: 15 additions & 2 deletions src/controllers/course/CourseInformationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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) {
Expand Down
20 changes: 10 additions & 10 deletions src/controllers/login/SessionController.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
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);
}

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
}
deleteUserSession,
};
18 changes: 10 additions & 8 deletions src/controllers/training-request/TrainingRequestAdminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [],
},
},
],
},
],
});

Expand Down
24 changes: 12 additions & 12 deletions src/controllers/training-session/TrainingSessionAdminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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) {
Expand All @@ -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;
}

Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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,
});
}

Expand Down
12 changes: 7 additions & 5 deletions src/controllers/training-session/TrainingSessionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
validateCreateSessionRequest,
};
4 changes: 3 additions & 1 deletion src/controllers/user/UserCourseController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/user/UserInformationAdminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 12 additions & 8 deletions src/controllers/user/UserNotificationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/core/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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...`);
Expand Down
2 changes: 1 addition & 1 deletion src/utility/helper/ValidationHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit d6ebf81

Please sign in to comment.