Merge branch 'dev' into test/e2e-setup

This commit is contained in:
Tibo De Peuter 2025-04-21 14:36:44 +02:00
commit 2e465e707b
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
178 changed files with 4951 additions and 2114 deletions

2
.gitignore vendored
View file

@ -738,3 +738,5 @@ flycheck_*.el
/network-security.data
docs/.venv
idp_data/h2/keycloakdb.mv.db
idp_data/h2/keycloakdb.trace.db

View file

@ -1,21 +0,0 @@
PORT=3000
DWENGO_DB_HOST=db
DWENGO_DB_PORT=5432
DWENGO_DB_USERNAME=postgres
DWENGO_DB_PASSWORD=postgres
DWENGO_DB_UPDATE=false
DWENGO_AUTH_STUDENT_URL=http://localhost/idp/realms/student
DWENGO_AUTH_STUDENT_CLIENT_ID=dwengo
DWENGO_AUTH_STUDENT_JWKS_ENDPOINT=http://idp:7080/idp/realms/student/protocol/openid-connect/certs
DWENGO_AUTH_TEACHER_URL=http://localhost/idp/realms/teacher
DWENGO_AUTH_TEACHER_CLIENT_ID=dwengo
DWENGO_AUTH_TEACHER_JWKS_ENDPOINT=http://idp:7080/idp/realms/teacher/protocol/openid-connect/certs
# Allow Vite dev-server to access the backend (for testing purposes). Don't forget to remove this in production!
#DWENGO_CORS_ALLOWED_ORIGINS=http://localhost/,127.0.0.1:80,http://127.0.0.1,http://localhost:80,http://127.0.0.1:80,localhost
DWENGO_CORS_ALLOWED_ORIGINS=http://localhost/*,http://idp:7080,https://idp:7080
# Logging and monitoring
LOKI_HOST=http://logging:3102

View file

@ -11,3 +11,10 @@ DWENGO_PORT=3000
DWENGO_DB_NAME=":memory:"
DWENGO_DB_UPDATE=true
DWENGO_AUTH_STUDENT_URL=http://localhost:7080/realms/student
DWENGO_AUTH_STUDENT_JWKS_ENDPOINT=http://localhost:7080/realms/student/protocol/openid-connect/certs
DWENGO_AUTH_TEACHER_URL=http://localhost:7080/realms/teacher
DWENGO_AUTH_TEACHER_JWKS_ENDPOINT=http://localhost:7080/realms/teacher/protocol/openid-connect/certs
DWENGO_CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000

View file

@ -7,7 +7,8 @@
"main": "dist/app.js",
"scripts": {
"build": "cross-env NODE_ENV=production tsc --build",
"dev": "cross-env NODE_ENV=development tsx tool/seed.ts; tsx watch --env-file=.env.development.local src/app.ts",
"predev": "tsc --build ../common/tsconfig.json",
"dev": "cross-env NODE_ENV=development tsx tool/seed.ts && tsx watch --env-file=.env.development.local src/app.ts",
"start": "cross-env NODE_ENV=production node --env-file=.env dist/app.js",
"format": "prettier --write src/",
"format-check": "prettier --check src/",
@ -16,11 +17,11 @@
"test:unit": "vitest --run"
},
"dependencies": {
"@mikro-orm/core": "6.4.9",
"@mikro-orm/knex": "6.4.9",
"@mikro-orm/postgresql": "6.4.9",
"@mikro-orm/reflection": "6.4.9",
"@mikro-orm/sqlite": "6.4.9",
"@mikro-orm/core": "6.4.12",
"@mikro-orm/knex": "6.4.12",
"@mikro-orm/postgresql": "6.4.12",
"@mikro-orm/reflection": "6.4.12",
"@mikro-orm/sqlite": "6.4.12",
"axios": "^1.8.2",
"cors": "^2.8.5",
"cross": "^1.0.0",
@ -42,7 +43,7 @@
"winston-loki": "^6.1.3"
},
"devDependencies": {
"@mikro-orm/cli": "6.4.9",
"@mikro-orm/cli": "6.4.12",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/js-yaml": "^4.0.9",

View file

@ -1,4 +1,10 @@
import { UnauthorizedException } from '../exceptions/unauthorized-exception.js';
import { getLogger } from '../logging/initalize.js';
import { AuthenticatedRequest } from '../middleware/auth/authenticated-request.js';
import { createOrUpdateStudent } from '../services/students.js';
import { createOrUpdateTeacher } from '../services/teachers.js';
import { envVars, getEnvVar } from '../util/envVars.js';
import { Response } from 'express';
interface FrontendIdpConfig {
authority: string;
@ -15,6 +21,8 @@ interface FrontendAuthConfig {
const SCOPE = 'openid profile email';
const RESPONSE_TYPE = 'code';
const logger = getLogger();
export function getFrontendAuthConfig(): FrontendAuthConfig {
return {
student: {
@ -31,3 +39,24 @@ export function getFrontendAuthConfig(): FrontendAuthConfig {
},
};
}
export async function postHelloHandler(req: AuthenticatedRequest, res: Response): Promise<void> {
const auth = req.auth;
if (!auth) {
throw new UnauthorizedException('Cannot say hello when not authenticated.');
}
const userData = {
id: auth.username,
username: auth.username,
firstName: auth.firstName ?? '',
lastName: auth.lastName ?? '',
};
if (auth.accountType === 'student') {
await createOrUpdateStudent(userData);
logger.debug(`Synchronized student ${userData.username} with IDP`);
} else {
await createOrUpdateTeacher(userData);
logger.debug(`Synchronized teacher ${userData.username} with IDP`);
}
res.status(200).send({ message: 'Welcome!' });
}

View file

@ -69,8 +69,8 @@ export async function getAllGroupsHandler(req: Request, res: Response): Promise<
export async function createGroupHandler(req: Request, res: Response): Promise<void> {
const classid = req.params.classid;
const assignmentId = Number(req.params.assignmentid);
requireFields({ classid, assignmentId });
const members = req.body.members;
requireFields({ classid, assignmentId, members });
if (isNaN(assignmentId)) {
throw new BadRequestException('Assignment id must be a number');

View file

@ -3,13 +3,10 @@ import { themes } from '../data/themes.js';
import { FALLBACK_LANG } from '../config.js';
import learningPathService from '../services/learning-paths/learning-path-service.js';
import { Language } from '@dwengo-1/common/util/language';
import {
PersonalizationTarget,
personalizedForGroup,
personalizedForStudent,
} from '../services/learning-paths/learning-path-personalization-util.js';
import { BadRequestException } from '../exceptions/bad-request-exception.js';
import { NotFoundException } from '../exceptions/not-found-exception.js';
import { Group } from '../entities/assignments/group.entity.js';
import { getAssignmentRepository, getGroupRepository } from '../data/repositories.js';
/**
* Fetch learning paths based on query parameters.
@ -20,20 +17,20 @@ export async function getLearningPaths(req: Request, res: Response): Promise<voi
const searchQuery = req.query.search as string;
const language = (req.query.language as string) || FALLBACK_LANG;
const forStudent = req.query.forStudent as string;
const forGroupNo = req.query.forGroup as string;
const assignmentNo = req.query.assignmentNo as string;
const classId = req.query.classId as string;
let personalizationTarget: PersonalizationTarget | undefined;
let forGroup: Group | undefined;
if (forStudent) {
personalizationTarget = await personalizedForStudent(forStudent);
} else if (forGroupNo) {
if (forGroupNo) {
if (!assignmentNo || !classId) {
throw new BadRequestException('If forGroupNo is specified, assignmentNo and classId must also be specified.');
}
personalizationTarget = await personalizedForGroup(classId, parseInt(assignmentNo), parseInt(forGroupNo));
const assignment = await getAssignmentRepository().findByClassIdAndAssignmentId(classId, parseInt(assignmentNo));
if (assignment) {
forGroup = (await getGroupRepository().findByAssignmentAndGroupNumber(assignment, parseInt(forGroupNo))) ?? undefined;
}
}
let hruidList;
@ -48,18 +45,13 @@ export async function getLearningPaths(req: Request, res: Response): Promise<voi
throw new NotFoundException(`Theme "${themeKey}" not found.`);
}
} else if (searchQuery) {
const searchResults = await learningPathService.searchLearningPaths(searchQuery, language as Language, personalizationTarget);
const searchResults = await learningPathService.searchLearningPaths(searchQuery, language as Language, forGroup);
res.json(searchResults);
return;
} else {
hruidList = themes.flatMap((theme) => theme.hruids);
}
const learningPaths = await learningPathService.fetchLearningPaths(
hruidList,
language as Language,
`HRUIDs: ${hruidList.join(', ')}`,
personalizationTarget
);
const learningPaths = await learningPathService.fetchLearningPaths(hruidList, language as Language, `HRUIDs: ${hruidList.join(', ')}`, forGroup);
res.json(learningPaths.data);
}

View file

@ -17,15 +17,18 @@ export async function getSubmissionsHandler(req: Request, res: Response): Promis
const lang = languageMap[req.query.language as string] || Language.Dutch;
const version = parseInt(req.query.version as string) ?? 1;
const submissions = await getSubmissionsForLearningObjectAndAssignment(
const forGroup = req.query.forGroup as string | undefined;
const submissions: SubmissionDTO[] = await getSubmissionsForLearningObjectAndAssignment(
loHruid,
lang,
version,
req.query.classId as string,
parseInt(req.query.assignmentId as string)
parseInt(req.query.assignmentId as string),
forGroup ? parseInt(forGroup) : undefined
);
res.json(submissions);
res.json({ submissions });
}
export async function getSubmissionHandler(req: Request, res: Response): Promise<void> {

View file

@ -0,0 +1,66 @@
import { Request, Response } from 'express';
import { requireFields } from './error-helper.js';
import { createInvitation, deleteInvitation, getAllInvitations, getInvitation, updateInvitation } from '../services/teacher-invitations.js';
import { TeacherInvitationData } from '@dwengo-1/common/interfaces/teacher-invitation';
export async function getAllInvitationsHandler(req: Request, res: Response): Promise<void> {
const username = req.params.username;
const by = req.query.sent === 'true';
requireFields({ username });
const invitations = await getAllInvitations(username, by);
res.json({ invitations });
}
export async function getInvitationHandler(req: Request, res: Response): Promise<void> {
const sender = req.params.sender;
const receiver = req.params.receiver;
const classId = req.params.classId;
requireFields({ sender, receiver, classId });
const invitation = await getInvitation(sender, receiver, classId);
res.json({ invitation });
}
export async function createInvitationHandler(req: Request, res: Response): Promise<void> {
const sender = req.body.sender;
const receiver = req.body.receiver;
const classId = req.body.class;
requireFields({ sender, receiver, classId });
const data = req.body as TeacherInvitationData;
const invitation = await createInvitation(data);
res.json({ invitation });
}
export async function updateInvitationHandler(req: Request, res: Response): Promise<void> {
const sender = req.body.sender;
const receiver = req.body.receiver;
const classId = req.body.class;
req.body.accepted = req.body.accepted !== false;
requireFields({ sender, receiver, classId });
const data = req.body as TeacherInvitationData;
const invitation = await updateInvitation(data);
res.json({ invitation });
}
export async function deleteInvitationHandler(req: Request, res: Response): Promise<void> {
const sender = req.params.sender;
const receiver = req.params.receiver;
const classId = req.params.classId;
requireFields({ sender, receiver, classId });
const data: TeacherInvitationData = {
sender,
receiver,
class: classId,
};
const invitation = await deleteInvitation(data);
res.json({ invitation });
}

View file

@ -4,7 +4,7 @@ import { Class } from '../../entities/classes/class.entity.js';
export class AssignmentRepository extends DwengoEntityRepository<Assignment> {
public async findByClassAndId(within: Class, id: number): Promise<Assignment | null> {
return this.findOne({ within: within, id: id });
return this.findOne({ within: within, id: id }, { populate: ['groups', 'groups.members'] });
}
public async findByClassIdAndAssignmentId(withinClass: string, id: number): Promise<Assignment | null> {
return this.findOne({ within: { classId: withinClass }, id: id });
@ -23,7 +23,7 @@ export class AssignmentRepository extends DwengoEntityRepository<Assignment> {
});
}
public async findAllAssignmentsInClass(within: Class): Promise<Assignment[]> {
return this.findAll({ where: { within: within } });
return this.findAll({ where: { within: within }, populate: ['groups', 'groups.members'] });
}
public async deleteByClassAndId(within: Class, id: number): Promise<void> {
return this.deleteWhere({ within: within, id: id });

View file

@ -61,32 +61,30 @@ export class SubmissionRepository extends DwengoEntityRepository<Submission> {
/**
* Looks up all submissions for the given learning object which were submitted as part of the given assignment.
* When forStudentUsername is set, only the submissions of the given user's group are shown.
*/
public async findAllSubmissionsForLearningObjectAndAssignment(
loId: LearningObjectIdentifier,
assignment: Assignment,
forStudentUsername?: string
): Promise<Submission[]> {
const onBehalfOf = forStudentUsername
? {
assignment,
members: {
$some: {
username: forStudentUsername,
},
},
}
: {
assignment,
};
public async findAllSubmissionsForLearningObjectAndAssignment(loId: LearningObjectIdentifier, assignment: Assignment): Promise<Submission[]> {
return this.findAll({
where: {
learningObjectHruid: loId.hruid,
learningObjectLanguage: loId.language,
learningObjectVersion: loId.version,
onBehalfOf,
onBehalfOf: {
assignment,
},
},
});
}
/**
* Looks up all submissions for the given learning object which were submitted by the given group
*/
public async findAllSubmissionsForLearningObjectAndGroup(loId: LearningObjectIdentifier, group: Group): Promise<Submission[]> {
return this.findAll({
where: {
learningObjectHruid: loId.hruid,
learningObjectLanguage: loId.language,
learningObjectVersion: loId.version,
onBehalfOf: group,
},
});
}

View file

@ -2,14 +2,14 @@ import { DwengoEntityRepository } from '../dwengo-entity-repository.js';
import { Class } from '../../entities/classes/class.entity.js';
import { ClassJoinRequest } from '../../entities/classes/class-join-request.entity.js';
import { Student } from '../../entities/users/student.entity.js';
import { ClassJoinRequestStatus } from '@dwengo-1/common/util/class-join-request';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export class ClassJoinRequestRepository extends DwengoEntityRepository<ClassJoinRequest> {
public async findAllRequestsBy(requester: Student): Promise<ClassJoinRequest[]> {
return this.findAll({ where: { requester: requester } });
}
public async findAllOpenRequestsTo(clazz: Class): Promise<ClassJoinRequest[]> {
return this.findAll({ where: { class: clazz, status: ClassJoinRequestStatus.Open } }); // TODO check if works like this
return this.findAll({ where: { class: clazz, status: ClassStatus.Open } }); // TODO check if works like this
}
public async findByStudentAndClass(requester: Student, clazz: Class): Promise<ClassJoinRequest | null> {
return this.findOne({ requester, class: clazz });

View file

@ -2,6 +2,7 @@ import { DwengoEntityRepository } from '../dwengo-entity-repository.js';
import { Class } from '../../entities/classes/class.entity.js';
import { TeacherInvitation } from '../../entities/classes/teacher-invitation.entity.js';
import { Teacher } from '../../entities/users/teacher.entity.js';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export class TeacherInvitationRepository extends DwengoEntityRepository<TeacherInvitation> {
public async findAllInvitationsForClass(clazz: Class): Promise<TeacherInvitation[]> {
@ -11,7 +12,7 @@ export class TeacherInvitationRepository extends DwengoEntityRepository<TeacherI
return this.findAll({ where: { sender: sender } });
}
public async findAllInvitationsFor(receiver: Teacher): Promise<TeacherInvitation[]> {
return this.findAll({ where: { receiver: receiver } });
return this.findAll({ where: { receiver: receiver, status: ClassStatus.Open } });
}
public async deleteBy(clazz: Class, sender: Teacher, receiver: Teacher): Promise<void> {
return this.deleteWhere({
@ -20,4 +21,11 @@ export class TeacherInvitationRepository extends DwengoEntityRepository<TeacherI
class: clazz,
});
}
public async findBy(clazz: Class, sender: Teacher, receiver: Teacher): Promise<TeacherInvitation | null> {
return this.findOne({
sender: sender,
receiver: receiver,
class: clazz,
});
}
}

View file

@ -1,6 +1,10 @@
import { DwengoEntityRepository } from '../dwengo-entity-repository.js';
import { LearningPath } from '../../entities/content/learning-path.entity.js';
import { Language } from '@dwengo-1/common/util/language';
import { LearningPathNode } from '../../entities/content/learning-path-node.entity.js';
import { RequiredEntityData } from '@mikro-orm/core';
import { LearningPathTransition } from '../../entities/content/learning-path-transition.entity.js';
import { EntityAlreadyExistsException } from '../../exceptions/entity-already-exists-exception.js';
export class LearningPathRepository extends DwengoEntityRepository<LearningPath> {
public async findByHruidAndLanguage(hruid: string, language: Language): Promise<LearningPath | null> {
@ -23,4 +27,27 @@ export class LearningPathRepository extends DwengoEntityRepository<LearningPath>
populate: ['nodes', 'nodes.transitions'],
});
}
public createNode(nodeData: RequiredEntityData<LearningPathNode>): LearningPathNode {
return this.em.create(LearningPathNode, nodeData);
}
public createTransition(transitionData: RequiredEntityData<LearningPathTransition>): LearningPathTransition {
return this.em.create(LearningPathTransition, transitionData);
}
public async saveLearningPathNodesAndTransitions(
path: LearningPath,
nodes: LearningPathNode[],
transitions: LearningPathTransition[],
options?: { preventOverwrite?: boolean }
): Promise<void> {
if (options?.preventOverwrite && (await this.findOne(path))) {
throw new EntityAlreadyExistsException('A learning path with this hruid/language combination already exists.');
}
const em = this.getEntityManager();
await em.persistAndFlush(path);
await Promise.all(nodes.map(async (it) => em.persistAndFlush(it)));
await Promise.all(transitions.map(async (it) => em.persistAndFlush(it)));
}
}

View file

@ -14,7 +14,7 @@ export class Assignment {
})
within!: Class;
@PrimaryKey({ type: 'number', autoincrement: true })
@PrimaryKey({ type: 'integer', autoincrement: true })
id?: number;
@Property({ type: 'string' })
@ -35,5 +35,5 @@ export class Assignment {
entity: () => Group,
mappedBy: 'assignment',
})
groups!: Collection<Group>;
groups: Collection<Group> = new Collection<Group>(this);
}

View file

@ -7,17 +7,23 @@ import { GroupRepository } from '../../data/assignments/group-repository.js';
repository: () => GroupRepository,
})
export class Group {
/*
WARNING: Don't move the definition of groupNumber! If it does not come before the definition of assignment,
creating groups fails because of a MikroORM bug!
*/
@PrimaryKey({ type: 'integer', autoincrement: true })
groupNumber?: number;
@ManyToOne({
entity: () => Assignment,
primary: true,
})
assignment!: Assignment;
@PrimaryKey({ type: 'integer', autoincrement: true })
groupNumber?: number;
@ManyToMany({
entity: () => Student,
owner: true,
inversedBy: 'groups',
})
members!: Collection<Student>;
members: Collection<Student> = new Collection<Student>(this);
}

View file

@ -6,6 +6,9 @@ import { Language } from '@dwengo-1/common/util/language';
@Entity({ repository: () => SubmissionRepository })
export class Submission {
@PrimaryKey({ type: 'integer', autoincrement: true })
submissionNumber?: number;
@PrimaryKey({ type: 'string' })
learningObjectHruid!: string;
@ -15,12 +18,9 @@ export class Submission {
})
learningObjectLanguage!: Language;
@PrimaryKey({ type: 'numeric' })
@PrimaryKey({ type: 'numeric', autoincrement: false })
learningObjectVersion = 1;
@PrimaryKey({ type: 'integer', autoincrement: true })
submissionNumber?: number;
@ManyToOne({
entity: () => Group,
})

View file

@ -2,7 +2,7 @@ import { Entity, Enum, ManyToOne } from '@mikro-orm/core';
import { Student } from '../users/student.entity.js';
import { Class } from './class.entity.js';
import { ClassJoinRequestRepository } from '../../data/classes/class-join-request-repository.js';
import { ClassJoinRequestStatus } from '@dwengo-1/common/util/class-join-request';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
@Entity({
repository: () => ClassJoinRequestRepository,
@ -20,6 +20,6 @@ export class ClassJoinRequest {
})
class!: Class;
@Enum(() => ClassJoinRequestStatus)
status!: ClassJoinRequestStatus;
@Enum(() => ClassStatus)
status!: ClassStatus;
}

View file

@ -14,9 +14,9 @@ export class Class {
@Property({ type: 'string' })
displayName!: string;
@ManyToMany(() => Teacher)
@ManyToMany({ entity: () => Teacher, owner: true, inversedBy: 'classes' })
teachers!: Collection<Teacher>;
@ManyToMany(() => Student)
@ManyToMany({ entity: () => Student, owner: true, inversedBy: 'classes' })
students!: Collection<Student>;
}

View file

@ -1,7 +1,8 @@
import { Entity, ManyToOne } from '@mikro-orm/core';
import { Entity, Enum, ManyToOne } from '@mikro-orm/core';
import { Teacher } from '../users/teacher.entity.js';
import { Class } from './class.entity.js';
import { TeacherInvitationRepository } from '../../data/classes/teacher-invitation-repository.js';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
/**
* Invitation of a teacher into a class (in order to teach it).
@ -25,4 +26,7 @@ export class TeacherInvitation {
primary: true,
})
class!: Class;
@Enum(() => ClassStatus)
status!: ClassStatus;
}

View file

@ -1,4 +1,4 @@
import { Embedded, Entity, Enum, ManyToMany, OneToMany, PrimaryKey, Property } from '@mikro-orm/core';
import { ArrayType, Embedded, Entity, Enum, ManyToMany, OneToMany, PrimaryKey, Property } from '@mikro-orm/core';
import { Attachment } from './attachment.entity.js';
import { Teacher } from '../users/teacher.entity.js';
import { DwengoContentType } from '../../services/learning-objects/processing/content-type.js';
@ -42,7 +42,7 @@ export class LearningObject {
@Property({ type: 'array' })
keywords: string[] = [];
@Property({ type: 'array', nullable: true })
@Property({ type: new ArrayType((i) => Number(i)), nullable: true })
targetAges?: number[] = [];
@Property({ type: 'bool' })

View file

@ -1,16 +1,16 @@
import { Entity, Enum, ManyToOne, OneToMany, PrimaryKey, Property, Rel } from '@mikro-orm/core';
import { Collection, Entity, Enum, ManyToOne, OneToMany, PrimaryKey, Property, Rel } from '@mikro-orm/core';
import { LearningPath } from './learning-path.entity.js';
import { LearningPathTransition } from './learning-path-transition.entity.js';
import { Language } from '@dwengo-1/common/util/language';
@Entity()
export class LearningPathNode {
@PrimaryKey({ type: 'integer', autoincrement: true })
nodeNumber?: number;
@ManyToOne({ entity: () => LearningPath, primary: true })
learningPath!: Rel<LearningPath>;
@PrimaryKey({ type: 'integer', autoincrement: true })
nodeNumber!: number;
@Property({ type: 'string' })
learningObjectHruid!: string;
@ -27,7 +27,7 @@ export class LearningPathNode {
startNode!: boolean;
@OneToMany({ entity: () => LearningPathTransition, mappedBy: 'node' })
transitions: LearningPathTransition[] = [];
transitions!: Collection<LearningPathTransition>;
@Property({ length: 3 })
createdAt: Date = new Date();

View file

@ -3,12 +3,12 @@ import { LearningPathNode } from './learning-path-node.entity.js';
@Entity()
export class LearningPathTransition {
@ManyToOne({ entity: () => LearningPathNode, primary: true })
node!: Rel<LearningPathNode>;
@PrimaryKey({ type: 'numeric' })
transitionNumber!: number;
@ManyToOne({ entity: () => LearningPathNode, primary: true })
node!: Rel<LearningPathNode>;
@Property({ type: 'string' })
condition!: string;

View file

@ -1,4 +1,4 @@
import { Entity, Enum, ManyToMany, OneToMany, PrimaryKey, Property } from '@mikro-orm/core';
import { Collection, Entity, Enum, ManyToMany, OneToMany, PrimaryKey, Property } from '@mikro-orm/core';
import { Teacher } from '../users/teacher.entity.js';
import { LearningPathRepository } from '../../data/content/learning-path-repository.js';
import { LearningPathNode } from './learning-path-node.entity.js';
@ -25,5 +25,5 @@ export class LearningPath {
image: Buffer | null = null;
@OneToMany({ entity: () => LearningPathNode, mappedBy: 'learningPath' })
nodes: LearningPathNode[] = [];
nodes: Collection<LearningPathNode> = new Collection<LearningPathNode>(this);
}

View file

@ -8,9 +8,9 @@ import { StudentRepository } from '../../data/users/student-repository.js';
repository: () => StudentRepository,
})
export class Student extends User {
@ManyToMany(() => Class)
@ManyToMany({ entity: () => Class, mappedBy: 'students' })
classes!: Collection<Class>;
@ManyToMany(() => Group)
groups!: Collection<Group>;
@ManyToMany({ entity: () => Group, mappedBy: 'members' })
groups: Collection<Group> = new Collection<Group>(this);
}

View file

@ -5,6 +5,6 @@ import { TeacherRepository } from '../../data/users/teacher-repository.js';
@Entity({ repository: () => TeacherRepository })
export class Teacher extends User {
@ManyToMany(() => Class)
@ManyToMany({ entity: () => Class, mappedBy: 'teachers' })
classes!: Collection<Class>;
}

View file

@ -1,7 +1,9 @@
import { HasStatusCode } from './has-status-code';
/**
* Exceptions which are associated with a HTTP error code.
*/
export abstract class ExceptionWithHttpState extends Error {
export abstract class ExceptionWithHttpState extends Error implements HasStatusCode {
constructor(
public status: number,
public error: string

View file

@ -0,0 +1,6 @@
export interface HasStatusCode {
status: number;
}
export function hasStatusCode(err: unknown): err is HasStatusCode {
return typeof err === 'object' && err !== null && 'status' in err && typeof (err as HasStatusCode)?.status === 'number';
}

View file

@ -0,0 +1,12 @@
import { ExceptionWithHttpState } from './exception-with-http-state.js';
/**
* Exception for HTTP 500 Internal Server Error
*/
export class ServerErrorException extends ExceptionWithHttpState {
status = 500;
constructor(message = 'Internal server error, something went wrong') {
super(500, message);
}
}

View file

@ -1,18 +1,14 @@
import { languageMap } from '@dwengo-1/common/util/language';
import { FALLBACK_LANG } from '../config.js';
import { Assignment } from '../entities/assignments/assignment.entity.js';
import { Class } from '../entities/classes/class.entity.js';
import { getLogger } from '../logging/initalize.js';
import { AssignmentDTO } from '@dwengo-1/common/interfaces/assignment';
import { AssignmentDTO, AssignmentDTOId } from '@dwengo-1/common/interfaces/assignment';
import { mapToGroupDTO } from './group.js';
import { getAssignmentRepository } from '../data/repositories.js';
export function mapToAssignmentDTOId(assignment: Assignment): AssignmentDTO {
export function mapToAssignmentDTOId(assignment: Assignment): AssignmentDTOId {
return {
id: assignment.id!,
within: assignment.within.classId!,
title: assignment.title,
description: assignment.description,
learningPath: assignment.learningPathHruid,
language: assignment.learningPathLanguage,
};
}
@ -24,19 +20,17 @@ export function mapToAssignmentDTO(assignment: Assignment): AssignmentDTO {
description: assignment.description,
learningPath: assignment.learningPathHruid,
language: assignment.learningPathLanguage,
// Groups: assignment.groups.map(mapToGroupDTO),
groups: assignment.groups.map((group) => mapToGroupDTO(group, assignment.within)),
};
}
export function mapToAssignment(assignmentData: AssignmentDTO, cls: Class): Assignment {
const assignment = new Assignment();
assignment.title = assignmentData.title;
assignment.description = assignmentData.description;
assignment.learningPathHruid = assignmentData.learningPath;
assignment.learningPathLanguage = languageMap[assignmentData.language] || FALLBACK_LANG;
assignment.within = cls;
getLogger().debug(assignment);
return assignment;
return getAssignmentRepository().create({
within: cls,
title: assignmentData.title,
description: assignmentData.description,
learningPathHruid: assignmentData.learningPath,
learningPathLanguage: languageMap[assignmentData.language],
groups: [],
});
}

View file

@ -1,14 +1,12 @@
import { Group } from '../entities/assignments/group.entity.js';
import { mapToAssignment } from './assignment.js';
import { mapToStudent } from './student.js';
import { mapToAssignmentDTO } from './assignment.js';
import { mapToStudentDTO } from './student.js';
import { GroupDTO } from '@dwengo-1/common/interfaces/group';
import { GroupDTO, GroupDTOId } from '@dwengo-1/common/interfaces/group';
import { getGroupRepository } from '../data/repositories.js';
import { AssignmentDTO } from '@dwengo-1/common/interfaces/assignment';
import { Class } from '../entities/classes/class.entity.js';
import { StudentDTO } from '@dwengo-1/common/interfaces/student';
import { mapToClassDTO } from './class.js';
export function mapToGroup(groupDto: GroupDTO, clazz: Class): Group {
const assignmentDto = groupDto.assignment as AssignmentDTO;
@ -20,18 +18,18 @@ export function mapToGroup(groupDto: GroupDTO, clazz: Class): Group {
});
}
export function mapToGroupDTO(group: Group): GroupDTO {
export function mapToGroupDTO(group: Group, cls: Class): GroupDTO {
return {
class: mapToClassDTO(group.assignment.within),
assignment: mapToAssignmentDTO(group.assignment),
class: cls.classId!,
assignment: group.assignment.id!,
groupNumber: group.groupNumber!,
members: group.members.map(mapToStudentDTO),
};
}
export function mapToGroupDTOId(group: Group): GroupDTO {
export function mapToGroupDTOId(group: Group, cls: Class): GroupDTOId {
return {
class: group.assignment.within.classId!,
class: cls.classId!,
assignment: group.assignment.id!,
groupNumber: group.groupNumber!,
};

View file

@ -31,7 +31,7 @@ export function mapToQuestionDTO(question: Question): QuestionDTO {
learningObjectIdentifier,
sequenceNumber: question.sequenceNumber!,
author: mapToStudentDTO(question.author),
inGroup: mapToGroupDTOId(question.inGroup),
inGroup: mapToGroupDTOId(question.inGroup, question.inGroup.assignment?.within),
timestamp: question.timestamp.toISOString(),
content: question.content,
};

View file

@ -4,7 +4,7 @@ import { getClassJoinRequestRepository } from '../data/repositories.js';
import { Student } from '../entities/users/student.entity.js';
import { Class } from '../entities/classes/class.entity.js';
import { ClassJoinRequestDTO } from '@dwengo-1/common/interfaces/class-join-request';
import { ClassJoinRequestStatus } from '@dwengo-1/common/util/class-join-request';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export function mapToStudentRequestDTO(request: ClassJoinRequest): ClassJoinRequestDTO {
return {
@ -18,6 +18,6 @@ export function mapToStudentRequest(student: Student, cls: Class): ClassJoinRequ
return getClassJoinRequestRepository().create({
requester: student,
class: cls,
status: ClassJoinRequestStatus.Open,
status: ClassStatus.Open,
});
}

View file

@ -1,5 +1,5 @@
import { Submission } from '../entities/assignments/submission.entity.js';
import { mapToGroupDTO } from './group.js';
import { mapToGroupDTOId } from './group.js';
import { mapToStudentDTO } from './student.js';
import { SubmissionDTO, SubmissionDTOId } from '@dwengo-1/common/interfaces/submission';
import { getSubmissionRepository } from '../data/repositories.js';
@ -13,11 +13,10 @@ export function mapToSubmissionDTO(submission: Submission): SubmissionDTO {
language: submission.learningObjectLanguage,
version: submission.learningObjectVersion,
},
submissionNumber: submission.submissionNumber,
submitter: mapToStudentDTO(submission.submitter),
time: submission.submissionTime,
group: mapToGroupDTO(submission.onBehalfOf),
group: submission.onBehalfOf ? mapToGroupDTOId(submission.onBehalfOf, submission.onBehalfOf.assignment.within) : undefined,
content: submission.content,
};
}

View file

@ -1,13 +1,17 @@
import { TeacherInvitation } from '../entities/classes/teacher-invitation.entity.js';
import { mapToClassDTO } from './class.js';
import { mapToUserDTO } from './user.js';
import { TeacherInvitationDTO } from '@dwengo-1/common/interfaces/teacher-invitation';
import { getTeacherInvitationRepository } from '../data/repositories.js';
import { Teacher } from '../entities/users/teacher.entity.js';
import { Class } from '../entities/classes/class.entity.js';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export function mapToTeacherInvitationDTO(invitation: TeacherInvitation): TeacherInvitationDTO {
return {
sender: mapToUserDTO(invitation.sender),
receiver: mapToUserDTO(invitation.receiver),
class: mapToClassDTO(invitation.class),
classId: invitation.class.classId!,
status: invitation.status,
};
}
@ -15,6 +19,16 @@ export function mapToTeacherInvitationDTOIds(invitation: TeacherInvitation): Tea
return {
sender: invitation.sender.username,
receiver: invitation.receiver.username,
class: invitation.class.classId!,
classId: invitation.class.classId!,
status: invitation.status,
};
}
export function mapToInvitation(sender: Teacher, receiver: Teacher, cls: Class): TeacherInvitation {
return getTeacherInvitationRepository().create({
sender,
receiver,
class: cls,
status: ClassStatus.Open,
});
}

View file

@ -26,13 +26,15 @@ function initializeLogger(): Logger {
const consoleTransport = new transports.Console({
level: getEnvVar(envVars.LogLevel),
format: format.combine(format.cli(), format.colorize()),
format: format.combine(format.cli(), format.simple()),
});
if (getEnvVar(envVars.RunMode) === 'dev') {
return createLogger({
logger = createLogger({
transports: [consoleTransport],
});
logger.debug(`Logger initialized with level ${logLevel} to console`);
return logger;
}
const lokiHost = getEnvVar(envVars.LokiHost);

View file

@ -11,7 +11,7 @@ export class MikroOrmLogger extends DefaultLogger {
};
let message: string;
if (context?.label) {
if (context !== undefined && context.labels !== undefined) {
message = `[${namespace}] (${context.label}) ${messageArg}`;
} else {
message = `[${namespace}] ${messageArg}`;

View file

@ -48,14 +48,14 @@ const idpConfigs = {
const verifyJwtToken = expressjwt({
secret: async (_: express.Request, token: jwt.Jwt | undefined) => {
if (!token?.payload || !(token.payload as JwtPayload).iss) {
throw new Error('Invalid token');
throw new UnauthorizedException('Invalid token.');
}
const issuer = (token.payload as JwtPayload).iss;
const idpConfig = Object.values(idpConfigs).find((config) => config.issuer === issuer);
if (!idpConfig) {
throw new Error('Issuer not accepted.');
throw new UnauthorizedException('Issuer not accepted.');
}
const signingKey = await idpConfig.jwksClient.getSigningKey(token.header.kid);

View file

@ -1,15 +1,15 @@
import { NextFunction, Request, Response } from 'express';
import { getLogger, Logger } from '../../logging/initalize.js';
import { ExceptionWithHttpState } from '../../exceptions/exception-with-http-state.js';
import { hasStatusCode } from '../../exceptions/has-status-code.js';
const logger: Logger = getLogger();
export function errorHandler(err: unknown, _req: Request, res: Response, _: NextFunction): void {
if (err instanceof ExceptionWithHttpState) {
if (hasStatusCode(err)) {
logger.warn(`An error occurred while handling a request: ${err} (-> HTTP ${err.status})`);
res.status(err.status).json(err);
} else {
logger.error(`Unexpected error occurred while handing a request: ${JSON.stringify(err)}`);
logger.error(`Unexpected error occurred while handing a request: ${(err as { stack: string })?.stack ?? JSON.stringify(err)}`);
res.status(500).json(err);
}
}

View file

@ -1,5 +1,5 @@
import express from 'express';
import { getFrontendAuthConfig } from '../controllers/auth.js';
import { getFrontendAuthConfig, postHelloHandler } from '../controllers/auth.js';
import { authenticatedOnly, studentsOnly, teachersOnly } from '../middleware/auth/auth.js';
const router = express.Router();
@ -23,4 +23,6 @@ router.get('/testTeachersOnly', teachersOnly, (_req, res) => {
res.json({ message: 'If you see this, you should be a teacher!' });
});
router.post('/hello', authenticatedOnly, postHelloHandler);
export default router;

View file

@ -5,7 +5,7 @@ const router = express.Router({ mergeParams: true });
// Root endpoint used to search objects
router.get('/', getSubmissionsHandler);
router.post('/:id', createSubmissionHandler);
router.post('/', createSubmissionHandler);
// Information about an submission with id 'id'
router.get('/:id', getSubmissionHandler);

View file

@ -0,0 +1,22 @@
import express from 'express';
import {
createInvitationHandler,
deleteInvitationHandler,
getAllInvitationsHandler,
getInvitationHandler,
updateInvitationHandler,
} from '../controllers/teacher-invitations.js';
const router = express.Router({ mergeParams: true });
router.get('/:username', getAllInvitationsHandler);
router.get('/:sender/:receiver/:classId', getInvitationHandler);
router.post('/', createInvitationHandler);
router.put('/', updateInvitationHandler);
router.delete('/:sender/:receiver/:classId', deleteInvitationHandler);
export default router;

View file

@ -10,6 +10,8 @@ import {
getTeacherStudentHandler,
updateStudentJoinRequestHandler,
} from '../controllers/teachers.js';
import invitationRouter from './teacher-invitations.js';
const router = express.Router();
// Root endpoint used to search objects
@ -32,10 +34,6 @@ router.get('/:username/joinRequests/:classId', getStudentJoinRequestHandler);
router.put('/:username/joinRequests/:classId/:studentUsername', updateStudentJoinRequestHandler);
// Invitations to other classes a teacher received
router.get('/:id/invitations', (_req, res) => {
res.json({
invitations: ['0'],
});
});
router.use('/invitations', invitationRouter);
export default router;

View file

@ -1,4 +1,4 @@
import { AssignmentDTO } from '@dwengo-1/common/interfaces/assignment';
import { AssignmentDTO, AssignmentDTOId } from '@dwengo-1/common/interfaces/assignment';
import {
getAssignmentRepository,
getClassRepository,
@ -16,6 +16,8 @@ import { QuestionDTO, QuestionId } from '@dwengo-1/common/interfaces/question';
import { SubmissionDTO, SubmissionDTOId } from '@dwengo-1/common/interfaces/submission';
import { EntityDTO } from '@mikro-orm/core';
import { putObject } from './service-helper.js';
import { fetchStudents } from './students.js';
import { ServerErrorException } from '../exceptions/server-error-exception.js';
export async function fetchAssignment(classid: string, assignmentNumber: number): Promise<Assignment> {
const classRepository = getClassRepository();
@ -35,7 +37,7 @@ export async function fetchAssignment(classid: string, assignmentNumber: number)
return assignment;
}
export async function getAllAssignments(classid: string, full: boolean): Promise<AssignmentDTO[]> {
export async function getAllAssignments(classid: string, full: boolean): Promise<AssignmentDTO[] | AssignmentDTOId[]> {
const cls = await fetchClass(classid);
const assignmentRepository = getAssignmentRepository();
@ -51,13 +53,39 @@ export async function getAllAssignments(classid: string, full: boolean): Promise
export async function createAssignment(classid: string, assignmentData: AssignmentDTO): Promise<AssignmentDTO> {
const cls = await fetchClass(classid);
const assignment = mapToAssignment(assignmentData, cls);
const assignmentRepository = getAssignmentRepository();
const newAssignment = assignmentRepository.create(assignment);
await assignmentRepository.save(newAssignment, { preventOverwrite: true });
const assignment = mapToAssignment(assignmentData, cls);
await assignmentRepository.save(assignment);
return mapToAssignmentDTO(newAssignment);
if (assignmentData.groups) {
/*
For some reason when trying to add groups, it does not work when using the original assignment variable.
The assignment needs to be refetched in order for it to work.
*/
const assignmentCopy = await assignmentRepository.findByClassAndId(cls, assignment.id!);
if (assignmentCopy === null) {
throw new ServerErrorException('Something has gone horribly wrong. Could not find newly added assignment which is needed to add groups.');
}
const groupRepository = getGroupRepository();
(assignmentData.groups as string[][]).forEach(async (memberUsernames) => {
const members = await fetchStudents(memberUsernames);
const newGroup = groupRepository.create({
assignment: assignmentCopy,
members: members,
});
await groupRepository.save(newGroup);
});
}
/* Need to refetch the assignment here again such that the groups are added. */
const assignmentWithGroups = await fetchAssignment(classid, assignment.id!);
return mapToAssignmentDTO(assignmentWithGroups);
}
export async function getAssignment(classid: string, id: number): Promise<AssignmentDTO> {

View file

@ -1,13 +1,14 @@
import { EntityDTO } from '@mikro-orm/core';
import { getGroupRepository, getStudentRepository, getSubmissionRepository } from '../data/repositories.js';
import { getGroupRepository, getSubmissionRepository } from '../data/repositories.js';
import { Group } from '../entities/assignments/group.entity.js';
import { mapToGroupDTO, mapToShallowGroupDTO } from '../interfaces/group.js';
import { mapToGroupDTO, mapToGroupDTOId } from '../interfaces/group.js';
import { mapToSubmissionDTO, mapToSubmissionDTOId } from '../interfaces/submission.js';
import { GroupDTO } from '@dwengo-1/common/interfaces/group';
import { GroupDTO, GroupDTOId } from '@dwengo-1/common/interfaces/group';
import { SubmissionDTO, SubmissionDTOId } from '@dwengo-1/common/interfaces/submission';
import { fetchAssignment } from './assignments.js';
import { NotFoundException } from '../exceptions/not-found-exception.js';
import { putObject } from './service-helper.js';
import { fetchStudents } from './students.js';
export async function fetchGroup(classId: string, assignmentNumber: number, groupNumber: number): Promise<Group> {
const assignment = await fetchAssignment(classId, assignmentNumber);
@ -24,7 +25,7 @@ export async function fetchGroup(classId: string, assignmentNumber: number, grou
export async function getGroup(classId: string, assignmentNumber: number, groupNumber: number): Promise<GroupDTO> {
const group = await fetchGroup(classId, assignmentNumber, groupNumber);
return mapToGroupDTO(group);
return mapToGroupDTO(group, group.assignment.within);
}
export async function putGroup(
@ -37,7 +38,7 @@ export async function putGroup(
await putObject<Group>(group, groupData, getGroupRepository());
return mapToGroupDTO(group);
return mapToGroupDTO(group, group.assignment.within);
}
export async function deleteGroup(classId: string, assignmentNumber: number, groupNumber: number): Promise<GroupDTO> {
@ -47,7 +48,7 @@ export async function deleteGroup(classId: string, assignmentNumber: number, gro
const groupRepository = getGroupRepository();
await groupRepository.deleteByAssignmentAndGroupNumber(assignment, groupNumber);
return mapToGroupDTO(group);
return mapToGroupDTO(group, assignment.within);
}
export async function getExistingGroupFromGroupDTO(groupData: GroupDTO): Promise<Group> {
@ -59,12 +60,8 @@ export async function getExistingGroupFromGroupDTO(groupData: GroupDTO): Promise
}
export async function createGroup(groupData: GroupDTO, classid: string, assignmentNumber: number): Promise<GroupDTO> {
const studentRepository = getStudentRepository();
const memberUsernames = (groupData.members as string[]) || [];
const members = (await Promise.all([...memberUsernames].map(async (id) => studentRepository.findByUsername(id)))).filter(
(student) => student !== null
);
const members = await fetchStudents(memberUsernames);
const assignment = await fetchAssignment(classid, assignmentNumber);
@ -73,22 +70,23 @@ export async function createGroup(groupData: GroupDTO, classid: string, assignme
assignment: assignment,
members: members,
});
await groupRepository.save(newGroup);
return mapToGroupDTO(newGroup);
return mapToGroupDTO(newGroup, newGroup.assignment.within);
}
export async function getAllGroups(classId: string, assignmentNumber: number, full: boolean): Promise<GroupDTO[]> {
export async function getAllGroups(classId: string, assignmentNumber: number, full: boolean): Promise<GroupDTO[] | GroupDTOId[]> {
const assignment = await fetchAssignment(classId, assignmentNumber);
const groupRepository = getGroupRepository();
const groups = await groupRepository.findAllGroupsForAssignment(assignment);
if (full) {
return groups.map(mapToGroupDTO);
return groups.map((group) => mapToGroupDTO(group, assignment.within));
}
return groups.map(mapToShallowGroupDTO);
return groups.map((group) => mapToGroupDTOId(group, assignment.within));
}
export async function getGroupSubmissions(

View file

@ -8,12 +8,13 @@ import {
LearningPathResponse,
} from '@dwengo-1/common/interfaces/learning-content';
import { getLogger } from '../logging/initalize.js';
import { v4 } from 'uuid';
function filterData(data: LearningObjectMetadata, htmlUrl: string): FilteredLearningObject {
return {
key: data.hruid, // Hruid learningObject (not path)
_id: data._id,
uuid: data.uuid,
uuid: data.uuid || v4(),
version: data.version,
title: data.title,
htmlUrl, // Url to fetch html content

View file

@ -32,7 +32,7 @@ function convertLearningObject(learningObject: LearningObject | null): FilteredL
educationalGoals: learningObject.educationalGoals,
returnValue: {
callback_url: learningObject.returnValue.callbackUrl,
callback_schema: JSON.parse(learningObject.returnValue.callbackSchema),
callback_schema: learningObject.returnValue.callbackSchema === '' ? '' : JSON.parse(learningObject.returnValue.callbackSchema),
},
skosConcepts: learningObject.skosConcepts,
targetAges: learningObject.targetAges || [],

View file

@ -11,6 +11,7 @@ import {
LearningPathIdentifier,
LearningPathResponse,
} from '@dwengo-1/common/interfaces/learning-content';
import { v4 } from 'uuid';
const logger: Logger = getLogger();
@ -23,7 +24,7 @@ function filterData(data: LearningObjectMetadata): FilteredLearningObject {
return {
key: data.hruid, // Hruid learningObject (not path)
_id: data._id,
uuid: data.uuid,
uuid: data.uuid ?? v4(),
version: data.version,
title: data.title,
htmlUrl: `/learningObject/${data.hruid}/html?language=${data.language}&version=${data.version}`, // Url to fetch html content

View file

@ -38,7 +38,7 @@ class GiftProcessor extends StringProcessor {
let html = "<div class='learning-object-gift'>\n";
let i = 1;
for (const question of quizQuestions) {
html += ` <div class='gift-question' id='gift-q${i}'>\n`;
html += ` <div class='gift-question gift-question-type-${question.type}' id='gift-q${i}'>\n`;
html += ' ' + this.renderQuestion(question, i).replaceAll(/\n(.+)/g, '\n $1'); // Replace for indentation.
html += ` </div>\n`;
i++;

View file

@ -14,7 +14,7 @@ export class MultipleChoiceQuestionRenderer extends GIFTQuestionRenderer<Multipl
for (const choice of question.choices) {
renderedHtml += `<div class="gift-choice-div">\n`;
renderedHtml += ` <input type='radio' id='gift-q${questionNumber}-choice-${i}' name='gift-q${questionNumber}-choices' value="${i}"/>\n`;
renderedHtml += ` <label for='gift-q${questionNumber}-choice-${i}'>${choice.text}</label>\n`;
renderedHtml += ` <label for='gift-q${questionNumber}-choice-${i}'>${choice.text.text}</label>\n`;
renderedHtml += `</div>\n`;
i++;
}

View file

@ -4,7 +4,7 @@ import { getLearningPathRepository } from '../../data/repositories.js';
import learningObjectService from '../learning-objects/learning-object-service.js';
import { LearningPathNode } from '../../entities/content/learning-path-node.entity.js';
import { LearningPathTransition } from '../../entities/content/learning-path-transition.entity.js';
import { getLastSubmissionForCustomizationTarget, isTransitionPossible, PersonalizationTarget } from './learning-path-personalization-util.js';
import { getLastSubmissionForGroup, isTransitionPossible } from './learning-path-personalization-util.js';
import {
FilteredLearningObject,
LearningObjectNode,
@ -13,13 +13,16 @@ import {
Transition,
} from '@dwengo-1/common/interfaces/learning-content';
import { Language } from '@dwengo-1/common/util/language';
import { Group } from '../../entities/assignments/group.entity';
import { Collection } from '@mikro-orm/core';
import { v4 } from 'uuid';
/**
* Fetches the corresponding learning object for each of the nodes and creates a map that maps each node to its
* corresponding learning object.
* @param nodes The nodes to find the learning object for.
*/
async function getLearningObjectsForNodes(nodes: LearningPathNode[]): Promise<Map<LearningPathNode, FilteredLearningObject>> {
async function getLearningObjectsForNodes(nodes: Collection<LearningPathNode>): Promise<Map<LearningPathNode, FilteredLearningObject>> {
// Fetching the corresponding learning object for each of the nodes and creating a map that maps each node to
// Its corresponding learning object.
const nullableNodesToLearningObjects = new Map<LearningPathNode, FilteredLearningObject | null>(
@ -44,7 +47,7 @@ async function getLearningObjectsForNodes(nodes: LearningPathNode[]): Promise<Ma
/**
* Convert the given learning path entity to an object which conforms to the learning path content.
*/
async function convertLearningPath(learningPath: LearningPathEntity, order: number, personalizedFor?: PersonalizationTarget): Promise<LearningPath> {
async function convertLearningPath(learningPath: LearningPathEntity, order: number, personalizedFor?: Group): Promise<LearningPath> {
// Fetch the corresponding learning object for each node since some parts of the expected response contains parts
// With information which is not available in the LearningPathNodes themselves.
const nodesToLearningObjects: Map<LearningPathNode, FilteredLearningObject> = await getLearningObjectsForNodes(learningPath.nodes);
@ -89,10 +92,10 @@ async function convertLearningPath(learningPath: LearningPathEntity, order: numb
async function convertNode(
node: LearningPathNode,
learningObject: FilteredLearningObject,
personalizedFor: PersonalizationTarget | undefined,
personalizedFor: Group | undefined,
nodesToLearningObjects: Map<LearningPathNode, FilteredLearningObject>
): Promise<LearningObjectNode> {
const lastSubmission = personalizedFor ? await getLastSubmissionForCustomizationTarget(node, personalizedFor) : null;
const lastSubmission = personalizedFor ? await getLastSubmissionForGroup(node, personalizedFor) : null;
const transitions = node.transitions
.filter(
(trans) =>
@ -108,6 +111,7 @@ async function convertNode(
updatedAt: node.updatedAt.toISOString(),
learningobject_hruid: node.learningObjectHruid,
version: learningObject.version,
done: personalizedFor ? lastSubmission !== null : undefined,
transitions,
};
}
@ -121,7 +125,7 @@ async function convertNode(
*/
async function convertNodes(
nodesToLearningObjects: Map<LearningPathNode, FilteredLearningObject>,
personalizedFor?: PersonalizationTarget
personalizedFor?: Group
): Promise<LearningObjectNode[]> {
const nodesPromise = Array.from(nodesToLearningObjects.entries()).map(async (entry) =>
convertNode(entry[0], entry[1], personalizedFor, nodesToLearningObjects)
@ -161,7 +165,7 @@ function convertTransition(
_id: String(index), // Retained for backwards compatibility. The index uniquely identifies the transition within the learning path.
default: false, // We don't work with default transitions but retain this for backwards compatibility.
next: {
_id: nextNode._id + index, // Construct a unique ID for the transition for backwards compatibility.
_id: nextNode._id ? nextNode._id + index : v4(), // Construct a unique ID for the transition for backwards compatibility.
hruid: transition.next.learningObjectHruid,
language: nextNode.language,
version: nextNode.version,
@ -177,12 +181,7 @@ const databaseLearningPathProvider: LearningPathProvider = {
/**
* Fetch the learning paths with the given hruids from the database.
*/
async fetchLearningPaths(
hruids: string[],
language: Language,
source: string,
personalizedFor?: PersonalizationTarget
): Promise<LearningPathResponse> {
async fetchLearningPaths(hruids: string[], language: Language, source: string, personalizedFor?: Group): Promise<LearningPathResponse> {
const learningPathRepo = getLearningPathRepository();
const learningPaths = (await Promise.all(hruids.map(async (hruid) => learningPathRepo.findByHruidAndLanguage(hruid, language)))).filter(
@ -202,7 +201,7 @@ const databaseLearningPathProvider: LearningPathProvider = {
/**
* Search learning paths in the database using the given search string.
*/
async searchLearningPaths(query: string, language: Language, personalizedFor?: PersonalizationTarget): Promise<LearningPath[]> {
async searchLearningPaths(query: string, language: Language, personalizedFor?: Group): Promise<LearningPath[]> {
const learningPathRepo = getLearningPathRepository();
const searchResults = await learningPathRepo.findByQueryStringAndLanguage(query, language);

View file

@ -1,76 +1,22 @@
import { LearningPathNode } from '../../entities/content/learning-path-node.entity.js';
import { Student } from '../../entities/users/student.entity.js';
import { Group } from '../../entities/assignments/group.entity.js';
import { Submission } from '../../entities/assignments/submission.entity.js';
import { getClassRepository, getGroupRepository, getStudentRepository, getSubmissionRepository } from '../../data/repositories.js';
import { getSubmissionRepository } from '../../data/repositories.js';
import { LearningObjectIdentifier } from '../../entities/content/learning-object-identifier.js';
import { LearningPathTransition } from '../../entities/content/learning-path-transition.entity.js';
import { JSONPath } from 'jsonpath-plus';
export type PersonalizationTarget = { type: 'student'; student: Student } | { type: 'group'; group: Group };
/**
* Shortcut function to easily create a PersonalizationTarget object for a student by his/her username.
* @param username Username of the student we want to generate a personalized learning path for.
* If there is no student with this username, return undefined.
* Returns the last submission for the learning object associated with the given node and for the group
*/
export async function personalizedForStudent(username: string): Promise<PersonalizationTarget | undefined> {
const student = await getStudentRepository().findByUsername(username);
if (student) {
return {
type: 'student',
student: student,
};
}
return undefined;
}
/**
* Shortcut function to easily create a PersonalizationTarget object for a group by class name, assignment number and
* group number.
* @param classId Id of the class in which this group was created
* @param assignmentNumber Number of the assignment for which this group was created
* @param groupNumber Number of the group for which we want to personalize the learning path.
*/
export async function personalizedForGroup(
classId: string,
assignmentNumber: number,
groupNumber: number
): Promise<PersonalizationTarget | undefined> {
const clazz = await getClassRepository().findById(classId);
if (!clazz) {
return undefined;
}
const group = await getGroupRepository().findOne({
assignment: {
within: clazz,
id: assignmentNumber,
},
groupNumber: groupNumber,
});
if (group) {
return {
type: 'group',
group: group,
};
}
return undefined;
}
/**
* Returns the last submission for the learning object associated with the given node and for the student or group
*/
export async function getLastSubmissionForCustomizationTarget(node: LearningPathNode, pathFor: PersonalizationTarget): Promise<Submission | null> {
export async function getLastSubmissionForGroup(node: LearningPathNode, pathFor: Group): Promise<Submission | null> {
const submissionRepo = getSubmissionRepository();
const learningObjectId: LearningObjectIdentifier = {
hruid: node.learningObjectHruid,
language: node.language,
version: node.version,
};
if (pathFor.type === 'group') {
return await submissionRepo.findMostRecentSubmissionForGroup(learningObjectId, pathFor.group);
}
return await submissionRepo.findMostRecentSubmissionForStudent(learningObjectId, pathFor.student);
return await submissionRepo.findMostRecentSubmissionForGroup(learningObjectId, pathFor);
}
/**

View file

@ -1,6 +1,6 @@
import { LearningPath, LearningPathResponse } from '@dwengo-1/common/interfaces/learning-content';
import { PersonalizationTarget } from './learning-path-personalization-util.js';
import { Language } from '@dwengo-1/common/util/language';
import { Group } from '../../entities/assignments/group.entity';
/**
* Generic interface for a service which provides access to learning paths from a data source.
@ -9,10 +9,10 @@ export interface LearningPathProvider {
/**
* Fetch the learning paths with the given hruids from the data source.
*/
fetchLearningPaths(hruids: string[], language: Language, source: string, personalizedFor?: PersonalizationTarget): Promise<LearningPathResponse>;
fetchLearningPaths(hruids: string[], language: Language, source: string, personalizedFor?: Group): Promise<LearningPathResponse>;
/**
* Search learning paths in the data source using the given search string.
*/
searchLearningPaths(query: string, language: Language, personalizedFor?: PersonalizationTarget): Promise<LearningPath[]>;
searchLearningPaths(query: string, language: Language, personalizedFor?: Group): Promise<LearningPath[]>;
}

View file

@ -1,13 +1,78 @@
import dwengoApiLearningPathProvider from './dwengo-api-learning-path-provider.js';
import databaseLearningPathProvider from './database-learning-path-provider.js';
import { envVars, getEnvVar } from '../../util/envVars.js';
import { PersonalizationTarget } from './learning-path-personalization-util.js';
import { LearningPath, LearningPathResponse } from '@dwengo-1/common/interfaces/learning-content';
import { LearningObjectNode, LearningPath, LearningPathResponse } from '@dwengo-1/common/interfaces/learning-content';
import { Language } from '@dwengo-1/common/util/language';
import { Group } from '../../entities/assignments/group.entity.js';
import { LearningPath as LearningPathEntity } from '../../entities/content/learning-path.entity.js';
import { getLearningPathRepository } from '../../data/repositories.js';
import { LearningPathNode } from '../../entities/content/learning-path-node.entity.js';
import { LearningPathTransition } from '../../entities/content/learning-path-transition.entity.js';
import { base64ToArrayBuffer } from '../../util/base64-buffer-conversion.js';
import { TeacherDTO } from '@dwengo-1/common/interfaces/teacher';
import { mapToTeacher } from '../../interfaces/teacher.js';
import { Collection } from '@mikro-orm/core';
const userContentPrefix = getEnvVar(envVars.UserContentPrefix);
const allProviders = [dwengoApiLearningPathProvider, databaseLearningPathProvider];
export function mapToLearningPath(dto: LearningPath, adminsDto: TeacherDTO[]): LearningPathEntity {
const admins = adminsDto.map((admin) => mapToTeacher(admin));
const repo = getLearningPathRepository();
const path = repo.create({
hruid: dto.hruid,
language: dto.language as Language,
description: dto.description,
title: dto.title,
admins,
image: dto.image ? Buffer.from(base64ToArrayBuffer(dto.image)) : null,
});
const nodes = dto.nodes.map((nodeDto: LearningObjectNode, i: number) =>
repo.createNode({
learningPath: path,
learningObjectHruid: nodeDto.learningobject_hruid,
nodeNumber: i,
language: nodeDto.language,
version: nodeDto.version,
startNode: nodeDto.start_node ?? false,
createdAt: new Date(),
updatedAt: new Date(),
})
);
dto.nodes.forEach((nodeDto) => {
const fromNode = nodes.find(
(it) => it.learningObjectHruid === nodeDto.learningobject_hruid && it.language === nodeDto.language && it.version === nodeDto.version
)!;
const transitions = nodeDto.transitions
.map((transDto, i) => {
const toNode = nodes.find(
(it) =>
it.learningObjectHruid === transDto.next.hruid &&
it.language === transDto.next.language &&
it.version === transDto.next.version
);
if (toNode) {
return repo.createTransition({
transitionNumber: i,
node: fromNode,
next: toNode,
condition: transDto.condition ?? 'true',
});
}
return undefined;
})
.filter((it) => it)
.map((it) => it!);
fromNode.transitions = new Collection<LearningPathTransition>(fromNode, transitions);
});
path.nodes = new Collection<LearningPathNode>(path, nodes);
return path;
}
/**
* Service providing access to data about learning paths from the appropriate data source (database or Dwengo-api)
*/
@ -19,12 +84,7 @@ const learningPathService = {
* @param source
* @param personalizedFor If this is set, a learning path personalized for the given group or student will be returned.
*/
async fetchLearningPaths(
hruids: string[],
language: Language,
source: string,
personalizedFor?: PersonalizationTarget
): Promise<LearningPathResponse> {
async fetchLearningPaths(hruids: string[], language: Language, source: string, personalizedFor?: Group): Promise<LearningPathResponse> {
const userContentHruids = hruids.filter((hruid) => hruid.startsWith(userContentPrefix));
const nonUserContentHruids = hruids.filter((hruid) => !hruid.startsWith(userContentPrefix));
@ -48,12 +108,23 @@ const learningPathService = {
/**
* Search learning paths in the data source using the given search string.
*/
async searchLearningPaths(query: string, language: Language, personalizedFor?: PersonalizationTarget): Promise<LearningPath[]> {
async searchLearningPaths(query: string, language: Language, personalizedFor?: Group): Promise<LearningPath[]> {
const providerResponses = await Promise.all(
allProviders.map(async (provider) => provider.searchLearningPaths(query, language, personalizedFor))
);
return providerResponses.flat();
},
/**
* Add a new learning path to the database.
* @param dto Learning path DTO from which the learning path will be created.
* @param admins Teachers who should become an admin of the learning path.
*/
async createNewLearningPath(dto: LearningPath, admins: TeacherDTO[]): Promise<void> {
const repo = getLearningPathRepository();
const path = mapToLearningPath(dto, admins);
await repo.save(path, { preventOverwrite: true });
},
};
export default learningPathService;

View file

@ -7,7 +7,7 @@ import {
getSubmissionRepository,
} from '../data/repositories.js';
import { mapToClassDTO } from '../interfaces/class.js';
import { mapToGroupDTO, mapToShallowGroupDTO } from '../interfaces/group.js';
import { mapToGroupDTO, mapToGroupDTOId } from '../interfaces/group.js';
import { mapToStudent, mapToStudentDTO } from '../interfaces/student.js';
import { mapToSubmissionDTO, mapToSubmissionDTOId } from '../interfaces/submission.js';
import { getAllAssignments } from './assignments.js';
@ -18,8 +18,8 @@ import { NotFoundException } from '../exceptions/not-found-exception.js';
import { fetchClass } from './classes.js';
import { StudentDTO } from '@dwengo-1/common/interfaces/student';
import { ClassDTO } from '@dwengo-1/common/interfaces/class';
import { AssignmentDTO } from '@dwengo-1/common/interfaces/assignment';
import { GroupDTO } from '@dwengo-1/common/interfaces/group';
import { AssignmentDTO, AssignmentDTOId } from '@dwengo-1/common/interfaces/assignment';
import { GroupDTO, GroupDTOId } from '@dwengo-1/common/interfaces/group';
import { SubmissionDTO, SubmissionDTOId } from '@dwengo-1/common/interfaces/submission';
import { QuestionDTO, QuestionId } from '@dwengo-1/common/interfaces/question';
import { ClassJoinRequestDTO } from '@dwengo-1/common/interfaces/class-join-request';
@ -48,6 +48,11 @@ export async function fetchStudent(username: string): Promise<Student> {
return user;
}
export async function fetchStudents(usernames: string[]): Promise<Student[]> {
const members = await Promise.all(usernames.map(async (username) => await fetchStudent(username)));
return members;
}
export async function getStudent(username: string): Promise<StudentDTO> {
const user = await fetchStudent(username);
return mapToStudentDTO(user);
@ -58,6 +63,16 @@ export async function createStudent(userData: StudentDTO): Promise<StudentDTO> {
const newStudent = mapToStudent(userData);
await studentRepository.save(newStudent, { preventOverwrite: true });
return userData;
}
export async function createOrUpdateStudent(userData: StudentDTO): Promise<StudentDTO> {
await getStudentRepository().upsert({
username: userData.username,
firstName: userData.firstName,
lastName: userData.lastName,
});
return userData;
}
@ -83,7 +98,7 @@ export async function getStudentClasses(username: string, full: boolean): Promis
return classes.map((cls) => cls.classId!);
}
export async function getStudentAssignments(username: string, full: boolean): Promise<AssignmentDTO[]> {
export async function getStudentAssignments(username: string, full: boolean): Promise<AssignmentDTO[] | AssignmentDTOId[]> {
const student = await fetchStudent(username);
const classRepository = getClassRepository();
@ -92,17 +107,17 @@ export async function getStudentAssignments(username: string, full: boolean): Pr
return (await Promise.all(classes.map(async (cls) => await getAllAssignments(cls.classId!, full)))).flat();
}
export async function getStudentGroups(username: string, full: boolean): Promise<GroupDTO[]> {
export async function getStudentGroups(username: string, full: boolean): Promise<GroupDTO[] | GroupDTOId[]> {
const student = await fetchStudent(username);
const groupRepository = getGroupRepository();
const groups = await groupRepository.findAllGroupsWithStudent(student);
if (full) {
return groups.map(mapToGroupDTO);
return groups.map((group) => mapToGroupDTO(group, group.assignment.within));
}
return groups.map(mapToShallowGroupDTO);
return groups.map((group) => mapToGroupDTOId(group, group.assignment.within));
}
export async function getStudentSubmissions(username: string, full: boolean): Promise<SubmissionDTO[] | SubmissionDTOId[]> {

View file

@ -1,4 +1,4 @@
import { getAssignmentRepository, getSubmissionRepository } from '../data/repositories.js';
import { getAssignmentRepository, getGroupRepository, getSubmissionRepository } from '../data/repositories.js';
import { LearningObjectIdentifier } from '../entities/content/learning-object-identifier.js';
import { NotFoundException } from '../exceptions/not-found-exception.js';
import { mapToSubmission, mapToSubmissionDTO } from '../interfaces/submission.js';
@ -33,10 +33,11 @@ export async function getAllSubmissions(loId: LearningObjectIdentifier): Promise
export async function createSubmission(submissionDTO: SubmissionDTO): Promise<SubmissionDTO> {
const submitter = await fetchStudent(submissionDTO.submitter.username);
const group = await getExistingGroupFromGroupDTO(submissionDTO.group);
const group = await getExistingGroupFromGroupDTO(submissionDTO.group!);
const submissionRepository = getSubmissionRepository();
const submission = mapToSubmission(submissionDTO, submitter, group);
await submissionRepository.save(submission);
return mapToSubmissionDTO(submission);
@ -60,12 +61,18 @@ export async function getSubmissionsForLearningObjectAndAssignment(
version: number,
classId: string,
assignmentId: number,
studentUsername?: string
groupId?: number
): Promise<SubmissionDTO[]> {
const loId = new LearningObjectIdentifier(learningObjectHruid, language, version);
const assignment = await getAssignmentRepository().findByClassIdAndAssignmentId(classId, assignmentId);
const submissions = await getSubmissionRepository().findAllSubmissionsForLearningObjectAndAssignment(loId, assignment!, studentUsername);
let submissions: Submission[];
if (groupId !== undefined) {
const group = await getGroupRepository().findByAssignmentAndGroupNumber(assignment!, groupId);
submissions = await getSubmissionRepository().findAllSubmissionsForLearningObjectAndGroup(loId, group!);
} else {
submissions = await getSubmissionRepository().findAllSubmissionsForLearningObjectAndAssignment(loId, assignment!);
}
return submissions.map((s) => mapToSubmissionDTO(s));
}

View file

@ -0,0 +1,87 @@
import { fetchTeacher } from './teachers.js';
import { getTeacherInvitationRepository } from '../data/repositories.js';
import { mapToInvitation, mapToTeacherInvitationDTO } from '../interfaces/teacher-invitation.js';
import { addClassTeacher, fetchClass } from './classes.js';
import { TeacherInvitationData, TeacherInvitationDTO } from '@dwengo-1/common/interfaces/teacher-invitation';
import { ConflictException } from '../exceptions/conflict-exception.js';
import { NotFoundException } from '../exceptions/not-found-exception.js';
import { TeacherInvitation } from '../entities/classes/teacher-invitation.entity.js';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export async function getAllInvitations(username: string, sent: boolean): Promise<TeacherInvitationDTO[]> {
const teacher = await fetchTeacher(username);
const teacherInvitationRepository = getTeacherInvitationRepository();
let invitations;
if (sent) {
invitations = await teacherInvitationRepository.findAllInvitationsBy(teacher);
} else {
invitations = await teacherInvitationRepository.findAllInvitationsFor(teacher);
}
return invitations.map(mapToTeacherInvitationDTO);
}
export async function createInvitation(data: TeacherInvitationData): Promise<TeacherInvitationDTO> {
const teacherInvitationRepository = getTeacherInvitationRepository();
const sender = await fetchTeacher(data.sender);
const receiver = await fetchTeacher(data.receiver);
const cls = await fetchClass(data.class);
if (!cls.teachers.contains(sender)) {
throw new ConflictException('The teacher sending the invite is not part of the class');
}
const newInvitation = mapToInvitation(sender, receiver, cls);
await teacherInvitationRepository.save(newInvitation, { preventOverwrite: true });
return mapToTeacherInvitationDTO(newInvitation);
}
async function fetchInvitation(usernameSender: string, usernameReceiver: string, classId: string): Promise<TeacherInvitation> {
const sender = await fetchTeacher(usernameSender);
const receiver = await fetchTeacher(usernameReceiver);
const cls = await fetchClass(classId);
const teacherInvitationRepository = getTeacherInvitationRepository();
const invite = await teacherInvitationRepository.findBy(cls, sender, receiver);
if (!invite) {
throw new NotFoundException('Teacher invite not found');
}
return invite;
}
export async function getInvitation(sender: string, receiver: string, classId: string): Promise<TeacherInvitationDTO> {
const invitation = await fetchInvitation(sender, receiver, classId);
return mapToTeacherInvitationDTO(invitation);
}
export async function updateInvitation(data: TeacherInvitationData): Promise<TeacherInvitationDTO> {
const invitation = await fetchInvitation(data.sender, data.receiver, data.class);
invitation.status = ClassStatus.Declined;
if (data.accepted) {
invitation.status = ClassStatus.Accepted;
await addClassTeacher(data.class, data.receiver);
}
const teacherInvitationRepository = getTeacherInvitationRepository();
await teacherInvitationRepository.save(invitation);
return mapToTeacherInvitationDTO(invitation);
}
export async function deleteInvitation(data: TeacherInvitationData): Promise<TeacherInvitationDTO> {
const invitation = await fetchInvitation(data.sender, data.receiver, data.class);
const sender = await fetchTeacher(data.sender);
const receiver = await fetchTeacher(data.receiver);
const cls = await fetchClass(data.class);
const teacherInvitationRepository = getTeacherInvitationRepository();
await teacherInvitationRepository.deleteBy(cls, sender, receiver);
return mapToTeacherInvitationDTO(invitation);
}

View file

@ -28,7 +28,7 @@ import { ClassDTO } from '@dwengo-1/common/interfaces/class';
import { StudentDTO } from '@dwengo-1/common/interfaces/student';
import { QuestionDTO, QuestionId } from '@dwengo-1/common/interfaces/question';
import { ClassJoinRequestDTO } from '@dwengo-1/common/interfaces/class-join-request';
import { ClassJoinRequestStatus } from '@dwengo-1/common/util/class-join-request';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
import { ConflictException } from '../exceptions/conflict-exception.js';
export async function getAllTeachers(full: boolean): Promise<TeacherDTO[] | string[]> {
@ -62,9 +62,19 @@ export async function createTeacher(userData: TeacherDTO): Promise<TeacherDTO> {
const newTeacher = mapToTeacher(userData);
await teacherRepository.save(newTeacher, { preventOverwrite: true });
return mapToTeacherDTO(newTeacher);
}
export async function createOrUpdateTeacher(userData: TeacherDTO): Promise<TeacherDTO> {
await getTeacherRepository().upsert({
username: userData.username,
firstName: userData.firstName,
lastName: userData.lastName,
});
return userData;
}
export async function deleteTeacher(username: string): Promise<TeacherDTO> {
const teacherRepository: TeacherRepository = getTeacherRepository();
@ -160,10 +170,10 @@ export async function updateClassJoinRequestStatus(studentUsername: string, clas
throw new NotFoundException('Join request not found');
}
request.status = ClassJoinRequestStatus.Declined;
request.status = ClassStatus.Declined;
if (accepted) {
request.status = ClassJoinRequestStatus.Accepted;
request.status = ClassStatus.Accepted;
await addClassStudent(classId, studentUsername);
}

View file

@ -27,7 +27,7 @@ export class SqliteAutoincrementSubscriber implements EventSubscriber {
for (const prop of Object.values(args.meta.properties)) {
const property = prop as EntityProperty<T>;
if (property.primary && property.autoincrement && !(args.entity as Record<string, unknown>)[property.name]) {
if (property.primary && property.autoincrement && (args.entity as Record<string, unknown>)[property.name] === undefined) {
// Obtain and increment sequence number of this entity.
const propertyKey = args.meta.class.name + '.' + property.name;
const nextSeqNumber = this.sequenceNumbersForEntityType.get(propertyKey) || 0;

View file

@ -0,0 +1,12 @@
/**
* Convert a Base64-encoded string into a buffer with the same data.
* @param base64 The Base64 encoded string.
*/
export function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

View file

@ -0,0 +1,123 @@
import { beforeAll, beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import { Request, Response } from 'express';
import { setupTestApp } from '../setup-tests.js';
import {
createInvitationHandler,
deleteInvitationHandler,
getAllInvitationsHandler,
getInvitationHandler,
updateInvitationHandler,
} from '../../src/controllers/teacher-invitations';
import { TeacherInvitationData } from '@dwengo-1/common/interfaces/teacher-invitation';
import { getClassHandler } from '../../src/controllers/classes';
import { BadRequestException } from '../../src/exceptions/bad-request-exception';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
describe('Teacher controllers', () => {
let req: Partial<Request>;
let res: Partial<Response>;
let jsonMock: Mock;
beforeAll(async () => {
await setupTestApp();
});
beforeEach(() => {
jsonMock = vi.fn();
res = {
json: jsonMock,
};
});
it('Get teacher invitations by', async () => {
req = { params: { username: 'LimpBizkit' }, query: { sent: 'true' } };
await getAllInvitationsHandler(req as Request, res as Response);
expect(jsonMock).toHaveBeenCalledWith(expect.objectContaining({ invitations: expect.anything() }));
const result = jsonMock.mock.lastCall?.[0];
// Console.log(result.invitations);
expect(result.invitations).to.have.length.greaterThan(0);
});
it('Get teacher invitations for', async () => {
req = { params: { username: 'FooFighters' }, query: { by: 'false' } };
await getAllInvitationsHandler(req as Request, res as Response);
expect(jsonMock).toHaveBeenCalledWith(expect.objectContaining({ invitations: expect.anything() }));
const result = jsonMock.mock.lastCall?.[0];
expect(result.invitations).to.have.length.greaterThan(0);
});
it('Create and delete invitation', async () => {
const body = {
sender: 'LimpBizkit',
receiver: 'testleerkracht1',
class: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
} as TeacherInvitationData;
req = { body };
await createInvitationHandler(req as Request, res as Response);
req = {
params: {
sender: 'LimpBizkit',
receiver: 'testleerkracht1',
classId: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
},
body: { accepted: 'false' },
};
await deleteInvitationHandler(req as Request, res as Response);
});
it('Get invitation', async () => {
req = {
params: {
sender: 'LimpBizkit',
receiver: 'FooFighters',
classId: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
},
};
await getInvitationHandler(req as Request, res as Response);
expect(jsonMock).toHaveBeenCalledWith(expect.objectContaining({ invitation: expect.anything() }));
});
it('Get invitation error', async () => {
req = {
params: { no: 'no params' },
};
await expect(async () => getInvitationHandler(req as Request, res as Response)).rejects.toThrowError(BadRequestException);
});
it('Accept invitation', async () => {
const body = {
sender: 'LimpBizkit',
receiver: 'FooFighters',
class: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
} as TeacherInvitationData;
req = { body };
await updateInvitationHandler(req as Request, res as Response);
const result1 = jsonMock.mock.lastCall?.[0];
expect(result1.invitation.status).toEqual(ClassStatus.Accepted);
req = {
params: {
id: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
},
};
await getClassHandler(req as Request, res as Response);
const result = jsonMock.mock.lastCall?.[0];
expect(result.class.teachers).toContain('FooFighters');
});
});

View file

@ -16,7 +16,7 @@ describe('AssignmentRepository', () => {
it('should return the requested assignment', async () => {
const class_ = await classRepository.findById('34d484a1-295f-4e9f-bfdc-3e7a23d86a89');
const assignment = await assignmentRepository.findByClassAndId(class_!, 2);
const assignment = await assignmentRepository.findByClassAndId(class_!, 21001);
expect(assignment).toBeTruthy();
expect(assignment!.title).toBe('tool');
@ -35,7 +35,7 @@ describe('AssignmentRepository', () => {
const result = await assignmentRepository.findAllByResponsibleTeacher('testleerkracht1');
const resultIds = result.map((it) => it.id).sort((a, b) => (a ?? 0) - (b ?? 0));
expect(resultIds).toEqual([1, 3, 4]);
expect(resultIds).toEqual([21000, 21002, 21003, 21004]);
});
it('should not find removed assignment', async () => {

View file

@ -19,16 +19,16 @@ describe('GroupRepository', () => {
it('should return the requested group', async () => {
const class_ = await classRepository.findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
const assignment = await assignmentRepository.findByClassAndId(class_!, 1);
const assignment = await assignmentRepository.findByClassAndId(class_!, 21000);
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 1);
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 21001);
expect(group).toBeTruthy();
});
it('should return all groups for assignment', async () => {
const class_ = await classRepository.findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
const assignment = await assignmentRepository.findByClassAndId(class_!, 1);
const assignment = await assignmentRepository.findByClassAndId(class_!, 21000);
const groups = await groupRepository.findAllGroupsForAssignment(assignment!);
@ -38,9 +38,9 @@ describe('GroupRepository', () => {
it('should not find removed group', async () => {
const class_ = await classRepository.findById('34d484a1-295f-4e9f-bfdc-3e7a23d86a89');
const assignment = await assignmentRepository.findByClassAndId(class_!, 2);
const assignment = await assignmentRepository.findByClassAndId(class_!, 21001);
await groupRepository.deleteByAssignmentAndGroupNumber(assignment!, 1);
await groupRepository.deleteByAssignmentAndGroupNumber(assignment!, 21001);
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 1);

View file

@ -54,8 +54,8 @@ describe('SubmissionRepository', () => {
it('should find the most recent submission for a group', async () => {
const id = new LearningObjectIdentifier('id03', Language.English, 1);
const class_ = await classRepository.findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
const assignment = await assignmentRepository.findByClassAndId(class_!, 1);
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 1);
const assignment = await assignmentRepository.findByClassAndId(class_!, 21000);
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 21001);
const submission = await submissionRepository.findMostRecentSubmissionForGroup(id, group!);
expect(submission).toBeTruthy();
@ -67,7 +67,7 @@ describe('SubmissionRepository', () => {
let loId: LearningObjectIdentifier;
it('should find all submissions for a certain learning object and assignment', async () => {
clazz = await classRepository.findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
assignment = await assignmentRepository.findByClassAndId(clazz!, 1);
assignment = await assignmentRepository.findByClassAndId(clazz!, 21000);
loId = {
hruid: 'id02',
language: Language.English,
@ -91,9 +91,9 @@ describe('SubmissionRepository', () => {
expect(result[2].submissionNumber).toBe(3);
});
it("should find only the submissions for a certain learning object and assignment made for the user's group", async () => {
const result = await submissionRepository.findAllSubmissionsForLearningObjectAndAssignment(loId, assignment!, 'Tool');
// (student Tool is in group #2)
it('should find only the submissions for a certain learning object and assignment made for the given group', async () => {
const group = await groupRepository.findByAssignmentAndGroupNumber(assignment!, 21002);
const result = await submissionRepository.findAllSubmissionsForLearningObjectAndGroup(loId, group!);
expect(result).toHaveLength(1);

View file

@ -2,66 +2,57 @@ import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests.js';
import { getAttachmentRepository, getLearningObjectRepository } from '../../../src/data/repositories.js';
import { AttachmentRepository } from '../../../src/data/content/attachment-repository.js';
import { LearningObjectRepository } from '../../../src/data/content/learning-object-repository.js';
import example from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example.js';
import { LearningObject } from '../../../src/entities/content/learning-object.entity.js';
import { Attachment } from '../../../src/entities/content/attachment.entity.js';
import { LearningObjectIdentifier } from '../../../src/entities/content/learning-object-identifier.js';
const NEWER_TEST_SUFFIX = 'nEweR';
async function createTestLearningObjects(learningObjectRepo: LearningObjectRepository): Promise<{
older: LearningObject;
newer: LearningObject;
}> {
const olderExample = example.createLearningObject();
await learningObjectRepo.save(olderExample);
const newerExample = example.createLearningObject();
newerExample.title = 'Newer example';
newerExample.version = 100;
return {
older: olderExample,
newer: newerExample,
};
}
import { testLearningObjectPnNotebooks } from '../../test_assets/content/learning-objects.testdata';
import { v4 as uuidV4 } from 'uuid';
describe('AttachmentRepository', () => {
let attachmentRepo: AttachmentRepository;
let exampleLearningObjects: { older: LearningObject; newer: LearningObject };
let newLearningObject: LearningObject;
let attachmentsOlderLearningObject: Attachment[];
beforeAll(async () => {
await setupTestApp();
attachmentsOlderLearningObject = testLearningObjectPnNotebooks.attachments as Attachment[];
attachmentRepo = getAttachmentRepository();
exampleLearningObjects = await createTestLearningObjects(getLearningObjectRepository());
});
const learningObjectRepo = getLearningObjectRepository();
it('can add attachments to learning objects without throwing an error', async () => {
attachmentsOlderLearningObject = Object.values(example.createAttachment).map((fn) => fn(exampleLearningObjects.older));
const newLearningObjectData = structuredClone(testLearningObjectPnNotebooks);
newLearningObjectData.title = 'Newer example';
newLearningObjectData.version = 101;
newLearningObjectData.attachments = [];
newLearningObjectData.uuid = uuidV4();
newLearningObjectData.content = Buffer.from('Content of the newer example');
await Promise.all(attachmentsOlderLearningObject.map(async (attachment) => attachmentRepo.save(attachment)));
newLearningObject = learningObjectRepo.create(newLearningObjectData);
await learningObjectRepo.save(newLearningObject);
});
let attachmentOnlyNewer: Attachment;
it('allows us to add attachments with the same name to a different learning object without throwing an error', async () => {
attachmentOnlyNewer = Object.values(example.createAttachment)[0](exampleLearningObjects.newer);
attachmentOnlyNewer.content.write(NEWER_TEST_SUFFIX);
attachmentOnlyNewer = structuredClone(attachmentsOlderLearningObject[0]);
attachmentOnlyNewer.learningObject = newLearningObject;
attachmentOnlyNewer.content = Buffer.from('New attachment content');
await attachmentRepo.save(attachmentOnlyNewer);
await attachmentRepo.save(attachmentRepo.create(attachmentOnlyNewer));
});
let olderLearningObjectId: LearningObjectIdentifier;
it('returns the correct attachment when queried by learningObjectId and attachment name', async () => {
olderLearningObjectId = {
hruid: exampleLearningObjects.older.hruid,
language: exampleLearningObjects.older.language,
version: exampleLearningObjects.older.version,
hruid: testLearningObjectPnNotebooks.hruid,
language: testLearningObjectPnNotebooks.language,
version: testLearningObjectPnNotebooks.version,
};
const result = await attachmentRepo.findByLearningObjectIdAndName(olderLearningObjectId, attachmentsOlderLearningObject[0].name);
expect(result).toBe(attachmentsOlderLearningObject[0]);
expect(result).not.toBeNull();
expect(result!.name).toEqual(attachmentsOlderLearningObject[0].name);
expect(result!.content).toEqual(attachmentsOlderLearningObject[0].content);
});
it('returns null when queried by learningObjectId and non-existing attachment name', async () => {
@ -71,10 +62,12 @@ describe('AttachmentRepository', () => {
it('returns the newer version of the attachment when only queried by hruid, language and attachment name (but not version)', async () => {
const result = await attachmentRepo.findByMostRecentVersionOfLearningObjectAndName(
exampleLearningObjects.older.hruid,
exampleLearningObjects.older.language,
testLearningObjectPnNotebooks.hruid,
testLearningObjectPnNotebooks.language,
attachmentOnlyNewer.name
);
expect(result).toBe(attachmentOnlyNewer);
expect(result).not.toBeNull();
expect(result!.name).toEqual(attachmentOnlyNewer.name);
expect(result!.content).toEqual(attachmentOnlyNewer.content);
});
});

View file

@ -1,28 +1,21 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests.js';
import { getAttachmentRepository, getLearningObjectRepository } from '../../../src/data/repositories.js';
import { getAttachmentRepository } from '../../../src/data/repositories.js';
import { AttachmentRepository } from '../../../src/data/content/attachment-repository.js';
import { LearningObjectRepository } from '../../../src/data/content/learning-object-repository.js';
import { LearningObjectIdentifier } from '../../../src/entities/content/learning-object-identifier.js';
import { Language } from '@dwengo-1/common/util/language';
import { testLearningObject02 } from '../../test_assets/content/learning-objects.testdata';
describe('AttachmentRepository', () => {
let attachmentRepository: AttachmentRepository;
let learningObjectRepository: LearningObjectRepository;
beforeAll(async () => {
await setupTestApp();
attachmentRepository = getAttachmentRepository();
learningObjectRepository = getLearningObjectRepository();
});
it('should return the requested attachment', async () => {
const id = new LearningObjectIdentifier('id02', Language.English, 1);
const learningObject = await learningObjectRepository.findByIdentifier(id);
const attachment = await attachmentRepository.findByMostRecentVersionOfLearningObjectAndName(
learningObject!.hruid,
Language.English,
testLearningObject02.hruid,
testLearningObject02.language,
'attachment01'
);

View file

@ -2,48 +2,33 @@ import { beforeAll, describe, it, expect } from 'vitest';
import { LearningObjectRepository } from '../../../src/data/content/learning-object-repository.js';
import { setupTestApp } from '../../setup-tests.js';
import { getLearningObjectRepository } from '../../../src/data/repositories.js';
import example from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example.js';
import { LearningObject } from '../../../src/entities/content/learning-object.entity.js';
import { expectToBeCorrectEntity } from '../../test-utils/expectations.js';
import { testLearningObject01, testLearningObject02, testLearningObject03 } from '../../test_assets/content/learning-objects.testdata';
import { v4 } from 'uuid';
describe('LearningObjectRepository', () => {
let learningObjectRepository: LearningObjectRepository;
let exampleLearningObject: LearningObject;
beforeAll(async () => {
await setupTestApp();
learningObjectRepository = getLearningObjectRepository();
});
it('should be able to add a learning object to it without an error', async () => {
exampleLearningObject = example.createLearningObject();
await learningObjectRepository.insert(exampleLearningObject);
});
it('should return the learning object when queried by id', async () => {
it('should return a learning object when queried by id', async () => {
const result = await learningObjectRepository.findByIdentifier({
hruid: exampleLearningObject.hruid,
language: exampleLearningObject.language,
version: exampleLearningObject.version,
hruid: testLearningObject01.hruid,
language: testLearningObject02.language,
version: testLearningObject03.version,
});
expect(result).toBeInstanceOf(LearningObject);
expectToBeCorrectEntity(
{
name: 'actual',
entity: result!,
},
{
name: 'expected',
entity: exampleLearningObject,
}
);
expectToBeCorrectEntity(result!, testLearningObject01);
});
it('should return null when non-existing version is queried', async () => {
const result = await learningObjectRepository.findByIdentifier({
hruid: exampleLearningObject.hruid,
language: exampleLearningObject.language,
hruid: testLearningObject01.hruid,
language: testLearningObject01.language,
version: 100,
});
expect(result).toBe(null);
@ -52,9 +37,12 @@ describe('LearningObjectRepository', () => {
let newerExample: LearningObject;
it('should allow a learning object with the same id except a different version to be added', async () => {
newerExample = example.createLearningObject();
newerExample.version = 10;
newerExample.title += ' (nieuw)';
const testLearningObject01Newer = structuredClone(testLearningObject01);
testLearningObject01Newer.version = 10;
testLearningObject01Newer.title += ' (nieuw)';
testLearningObject01Newer.uuid = v4();
testLearningObject01Newer.content = Buffer.from('This is the new content.');
newerExample = learningObjectRepository.create(testLearningObject01Newer);
await learningObjectRepository.save(newerExample);
});
@ -66,7 +54,7 @@ describe('LearningObjectRepository', () => {
});
it('should return null when queried by non-existing hruid or language', async () => {
const result = await learningObjectRepository.findLatestByHruidAndLanguage('something_that_does_not_exist', exampleLearningObject.language);
const result = await learningObjectRepository.findLatestByHruidAndLanguage('something_that_does_not_exist', testLearningObject01.language);
expect(result).toBe(null);
});
});

View file

@ -4,6 +4,7 @@ import { getLearningObjectRepository } from '../../../src/data/repositories';
import { setupTestApp } from '../../setup-tests';
import { LearningObjectIdentifier } from '../../../src/entities/content/learning-object-identifier';
import { Language } from '@dwengo-1/common/util/language';
import { testLearningObject01 } from '../../test_assets/content/learning-objects.testdata';
describe('LearningObjectRepository', () => {
let learningObjectRepository: LearningObjectRepository;
@ -13,8 +14,8 @@ describe('LearningObjectRepository', () => {
learningObjectRepository = getLearningObjectRepository();
});
const id01 = new LearningObjectIdentifier('id01', Language.English, 1);
const id02 = new LearningObjectIdentifier('test_id', Language.English, 1);
const id01 = new LearningObjectIdentifier(testLearningObject01.hruid, testLearningObject01.language, testLearningObject01.version);
const id02 = new LearningObjectIdentifier('non_existing_id', Language.English, 1);
it('should return the learning object that matches identifier 1', async () => {
const learningObject = await learningObjectRepository.findByIdentifier(id01);

View file

@ -2,41 +2,27 @@ import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests.js';
import { getLearningPathRepository } from '../../../src/data/repositories.js';
import { LearningPathRepository } from '../../../src/data/content/learning-path-repository.js';
import example from '../../test-assets/learning-paths/pn-werking-example.js';
import { LearningPath } from '../../../src/entities/content/learning-path.entity.js';
import { expectToBeCorrectEntity } from '../../test-utils/expectations.js';
import { expectToBeCorrectEntity, expectToHaveFoundNothing, expectToHaveFoundPrecisely } from '../../test-utils/expectations.js';
import { Language } from '@dwengo-1/common/util/language';
function expectToHaveFoundPrecisely(expected: LearningPath, result: LearningPath[]): void {
expect(result).toHaveProperty('length');
expect(result.length).toBe(1);
expectToBeCorrectEntity({ entity: result[0] }, { entity: expected });
}
function expectToHaveFoundNothing(result: LearningPath[]): void {
expect(result).toHaveProperty('length');
expect(result.length).toBe(0);
}
import { testLearningPath01 } from '../../test_assets/content/learning-paths.testdata';
import { mapToLearningPath } from '../../../src/services/learning-paths/learning-path-service';
describe('LearningPathRepository', () => {
let learningPathRepo: LearningPathRepository;
let examplePath: LearningPath;
beforeAll(async () => {
await setupTestApp();
learningPathRepo = getLearningPathRepository();
examplePath = mapToLearningPath(testLearningPath01, []);
});
let examplePath: LearningPath;
it('should be able to add a learning path without throwing an error', async () => {
examplePath = example.createLearningPath();
await learningPathRepo.insert(examplePath);
});
it('should return the added path when it is queried by hruid and language', async () => {
const result = await learningPathRepo.findByHruidAndLanguage(examplePath.hruid, examplePath.language);
it('should return a learning path when it is queried by hruid and language', async () => {
const result = await learningPathRepo.findByHruidAndLanguage(testLearningPath01.hruid, testLearningPath01.language as Language);
expect(result).toBeInstanceOf(LearningPath);
expectToBeCorrectEntity({ entity: result! }, { entity: examplePath });
expectToBeCorrectEntity(result!, examplePath);
});
it('should return null to a query on a non-existing hruid or language', async () => {
@ -45,7 +31,7 @@ describe('LearningPathRepository', () => {
});
it('should return the learning path when we search for a search term occurring in its title', async () => {
const result = await learningPathRepo.findByQueryStringAndLanguage(examplePath.title.slice(4, 9), examplePath.language);
const result = await learningPathRepo.findByQueryStringAndLanguage(examplePath.title.slice(9, 13), examplePath.language);
expectToHaveFoundPrecisely(examplePath, result);
});

View file

@ -3,6 +3,7 @@ import { getLearningPathRepository } from '../../../src/data/repositories';
import { LearningPathRepository } from '../../../src/data/content/learning-path-repository';
import { setupTestApp } from '../../setup-tests';
import { Language } from '@dwengo-1/common/util/language';
import { testLearningPath01 } from '../../test_assets/content/learning-paths.testdata';
describe('LearningPathRepository', () => {
let learningPathRepository: LearningPathRepository;
@ -19,10 +20,10 @@ describe('LearningPathRepository', () => {
});
it('should return requested learning path', async () => {
const learningPath = await learningPathRepository.findByHruidAndLanguage('id01', Language.English);
const learningPath = await learningPathRepository.findByHruidAndLanguage(testLearningPath01.hruid, testLearningPath01.language as Language);
expect(learningPath).toBeTruthy();
expect(learningPath?.title).toBe('repertoire Tool');
expect(learningPath?.description).toBe('all about Tool');
expect(learningPath?.title).toBe(testLearningPath01.title);
expect(learningPath?.description).toBe(testLearningPath01.description);
});
});

View file

@ -38,8 +38,8 @@ describe('QuestionRepository', () => {
const student = await studentRepository.findByUsername('Noordkaap');
const clazz = await getClassRepository().findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
const assignment = await getAssignmentRepository().findByClassAndId(clazz!, 1);
const group = await getGroupRepository().findByAssignmentAndGroupNumber(assignment!, 1);
const assignment = await getAssignmentRepository().findByClassAndId(clazz!, 21000);
const group = await getGroupRepository().findByAssignmentAndGroupNumber(assignment!, 21001);
await questionRepository.createQuestion({
loId: id,
inGroup: group!,
@ -57,7 +57,7 @@ describe('QuestionRepository', () => {
let loId: LearningObjectIdentifier;
it('should find all questions for a certain learning object and assignment', async () => {
clazz = await getClassRepository().findById('8764b861-90a6-42e5-9732-c0d9eb2f55f9');
assignment = await getAssignmentRepository().findByClassAndId(clazz!, 1);
assignment = await getAssignmentRepository().findByClassAndId(clazz!, 21000);
loId = {
hruid: 'id05',
language: Language.English,

View file

@ -1,37 +1,32 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests';
import { getLearningObjectRepository, getLearningPathRepository } from '../../../src/data/repositories';
import example from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example';
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
import databaseLearningObjectProvider from '../../../src/services/learning-objects/database-learning-object-provider';
import { expectToBeCorrectFilteredLearningObject } from '../../test-utils/expectations';
import { Language } from '@dwengo-1/common/util/language';
import learningObjectExample from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example';
import learningPathExample from '../../test-assets/learning-paths/pn-werking-example';
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
import { FilteredLearningObject } from '@dwengo-1/common/interfaces/learning-content';
async function initExampleData(): Promise<{ learningObject: LearningObject; learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
}
import { FilteredLearningObject, LearningObjectNode, LearningPathIdentifier } from '@dwengo-1/common/interfaces/learning-content';
import { testPartiallyDatabaseAndPartiallyDwengoApiLearningPath } from '../../test_assets/content/learning-paths.testdata';
import { testLearningObjectPnNotebooks } from '../../test_assets/content/learning-objects.testdata';
import { LearningPath } from '@dwengo-1/common/dist/interfaces/learning-content';
import { RequiredEntityData } from '@mikro-orm/core';
import { getHtmlRenderingForTestLearningObject } from '../../test-utils/get-html-rendering';
const EXPECTED_TITLE_FROM_DWENGO_LEARNING_OBJECT = 'Notebook opslaan';
describe('DatabaseLearningObjectProvider', () => {
let exampleLearningObject: LearningObject;
let exampleLearningObject: RequiredEntityData<LearningObject>;
let exampleLearningPath: LearningPath;
let exampleLearningPathId: LearningPathIdentifier;
beforeAll(async () => {
await setupTestApp();
const exampleData = await initExampleData();
exampleLearningObject = exampleData.learningObject;
exampleLearningPath = exampleData.learningPath;
exampleLearningObject = testLearningObjectPnNotebooks;
exampleLearningPath = testPartiallyDatabaseAndPartiallyDwengoApiLearningPath;
exampleLearningPathId = {
hruid: exampleLearningPath.hruid,
language: exampleLearningPath.language as Language,
};
});
describe('getLearningObjectById', () => {
it('should return the learning object when it is queried by its id', async () => {
@ -61,7 +56,7 @@ describe('DatabaseLearningObjectProvider', () => {
it('should return the correct rendering of the learning object', async () => {
const result = await databaseLearningObjectProvider.getLearningObjectHTML(exampleLearningObject);
// Set newlines so your tests are platform-independent.
expect(result).toEqual(example.getHTMLRendering().replace(/\r\n/g, '\n'));
expect(result).toEqual(getHtmlRenderingForTestLearningObject(exampleLearningObject).replace(/\r\n/g, '\n'));
});
it('should return null for a non-existing learning object', async () => {
const result = await databaseLearningObjectProvider.getLearningObjectHTML({
@ -73,8 +68,8 @@ describe('DatabaseLearningObjectProvider', () => {
});
describe('getLearningObjectIdsFromPath', () => {
it('should return all learning object IDs from a path', async () => {
const result = await databaseLearningObjectProvider.getLearningObjectIdsFromPath(exampleLearningPath);
expect(new Set(result)).toEqual(new Set(exampleLearningPath.nodes.map((it) => it.learningObjectHruid)));
const result = await databaseLearningObjectProvider.getLearningObjectIdsFromPath(exampleLearningPathId);
expect(new Set(result)).toEqual(new Set(exampleLearningPath.nodes.map((it: LearningObjectNode) => it.learningobject_hruid)));
});
it('should throw an error if queried with a path identifier for which there is no learning path', async () => {
await expect(
@ -89,9 +84,11 @@ describe('DatabaseLearningObjectProvider', () => {
});
describe('getLearningObjectsFromPath', () => {
it('should correctly return all learning objects which are on the path, even those who are not in the database', async () => {
const result = await databaseLearningObjectProvider.getLearningObjectsFromPath(exampleLearningPath);
const result = await databaseLearningObjectProvider.getLearningObjectsFromPath(exampleLearningPathId);
expect(result.length).toBe(exampleLearningPath.nodes.length);
expect(new Set(result.map((it) => it.key))).toEqual(new Set(exampleLearningPath.nodes.map((it) => it.learningObjectHruid)));
expect(new Set(result.map((it) => it.key))).toEqual(
new Set(exampleLearningPath.nodes.map((it: LearningObjectNode) => it.learningobject_hruid))
);
expect(result.map((it) => it.title)).toContainEqual(EXPECTED_TITLE_FROM_DWENGO_LEARNING_OBJECT);
});

View file

@ -1,14 +1,14 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests';
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
import { getLearningObjectRepository, getLearningPathRepository } from '../../../src/data/repositories';
import learningObjectExample from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example';
import learningObjectService from '../../../src/services/learning-objects/learning-object-service';
import { envVars, getEnvVar } from '../../../src/util/envVars';
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
import learningPathExample from '../../test-assets/learning-paths/pn-werking-example';
import { LearningObjectIdentifierDTO, LearningPathIdentifier } from '@dwengo-1/common/interfaces/learning-content';
import { LearningObjectIdentifierDTO, LearningPath as LearningPathDTO, LearningPathIdentifier } from '@dwengo-1/common/interfaces/learning-content';
import { Language } from '@dwengo-1/common/util/language';
import { testLearningObjectPnNotebooks } from '../../test_assets/content/learning-objects.testdata';
import { testPartiallyDatabaseAndPartiallyDwengoApiLearningPath } from '../../test_assets/content/learning-paths.testdata';
import { RequiredEntityData } from '@mikro-orm/core';
import { getHtmlRenderingForTestLearningObject } from '../../test-utils/get-html-rendering';
const EXPECTED_DWENGO_LEARNING_OBJECT_TITLE = 'Werken met notebooks';
const DWENGO_TEST_LEARNING_OBJECT_ID: LearningObjectIdentifierDTO = {
@ -23,25 +23,20 @@ const DWENGO_TEST_LEARNING_PATH_ID: LearningPathIdentifier = {
};
const DWENGO_TEST_LEARNING_PATH_HRUIDS = new Set(['pn_werkingnotebooks', 'pn_werkingnotebooks2', 'pn_werkingnotebooks3']);
async function initExampleData(): Promise<{ learningObject: LearningObject; learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
}
describe('LearningObjectService', () => {
let exampleLearningObject: LearningObject;
let exampleLearningPath: LearningPath;
let exampleLearningObject: RequiredEntityData<LearningObject>;
let exampleLearningPath: LearningPathDTO;
let exampleLearningPathId: LearningPathIdentifier;
beforeAll(async () => {
await setupTestApp();
const exampleData = await initExampleData();
exampleLearningObject = exampleData.learningObject;
exampleLearningPath = exampleData.learningPath;
exampleLearningObject = testLearningObjectPnNotebooks;
exampleLearningPath = testPartiallyDatabaseAndPartiallyDwengoApiLearningPath;
exampleLearningPathId = {
hruid: exampleLearningPath.hruid,
language: exampleLearningPath.language as Language,
};
});
describe('getLearningObjectById', () => {
@ -69,7 +64,7 @@ describe('LearningObjectService', () => {
const result = await learningObjectService.getLearningObjectHTML(exampleLearningObject);
expect(result).not.toBeNull();
// Set newlines so your tests are platform-independent.
expect(result).toEqual(learningObjectExample.getHTMLRendering().replace(/\r\n/g, '\n'));
expect(result).toEqual(getHtmlRenderingForTestLearningObject(exampleLearningObject).replace(/\r\n/g, '\n'));
});
it(
'returns the same HTML as the Dwengo API when queried with the identifier of a learning object that does ' +
@ -97,8 +92,8 @@ describe('LearningObjectService', () => {
describe('getLearningObjectsFromPath', () => {
it('returns all learning objects when a learning path in the database is queried', async () => {
const result = await learningObjectService.getLearningObjectsFromPath(exampleLearningPath);
expect(result.map((it) => it.key)).toEqual(exampleLearningPath.nodes.map((it) => it.learningObjectHruid));
const result = await learningObjectService.getLearningObjectsFromPath(exampleLearningPathId);
expect(result.map((it) => it.key)).toEqual(exampleLearningPath.nodes.map((it) => it.learningobject_hruid));
});
it('also returns all learning objects when a learning path from the Dwengo API is queried', async () => {
const result = await learningObjectService.getLearningObjectsFromPath(DWENGO_TEST_LEARNING_PATH_ID);
@ -115,8 +110,8 @@ describe('LearningObjectService', () => {
describe('getLearningObjectIdsFromPath', () => {
it('returns all learning objects when a learning path in the database is queried', async () => {
const result = await learningObjectService.getLearningObjectIdsFromPath(exampleLearningPath);
expect(result).toEqual(exampleLearningPath.nodes.map((it) => it.learningObjectHruid));
const result = await learningObjectService.getLearningObjectIdsFromPath(exampleLearningPathId);
expect(result).toEqual(exampleLearningPath.nodes.map((it) => it.learningobject_hruid));
});
it('also returns all learning object hruids when a learning path from the Dwengo API is queried', async () => {
const result = await learningObjectService.getLearningObjectIdsFromPath(DWENGO_TEST_LEARNING_PATH_ID);

View file

@ -1,26 +1,35 @@
import { describe, expect, it } from 'vitest';
import mdExample from '../../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example';
import multipleChoiceExample from '../../../test-assets/learning-objects/test-multiple-choice/test-multiple-choice-example';
import essayExample from '../../../test-assets/learning-objects/test-essay/test-essay-example';
import { beforeAll, describe, expect, it } from 'vitest';
import processingService from '../../../../src/services/learning-objects/processing/processing-service';
import {
testLearningObjectEssayQuestion,
testLearningObjectMultipleChoice,
testLearningObjectPnNotebooks,
} from '../../../test_assets/content/learning-objects.testdata';
import { getHtmlRenderingForTestLearningObject } from '../../../test-utils/get-html-rendering';
import { getLearningObjectRepository } from '../../../../src/data/repositories';
import { setupTestApp } from '../../../setup-tests';
describe('ProcessingService', () => {
beforeAll(async () => {
await setupTestApp();
});
it('renders a markdown learning object correctly', async () => {
const markdownLearningObject = mdExample.createLearningObject();
const markdownLearningObject = getLearningObjectRepository().create(testLearningObjectPnNotebooks);
const result = await processingService.render(markdownLearningObject);
// Set newlines so your tests are platform-independent.
expect(result).toEqual(mdExample.getHTMLRendering().replace(/\r\n/g, '\n'));
expect(result).toEqual(getHtmlRenderingForTestLearningObject(markdownLearningObject).replace(/\r\n/g, '\n'));
});
it('renders a multiple choice question correctly', async () => {
const multipleChoiceLearningObject = multipleChoiceExample.createLearningObject();
const result = await processingService.render(multipleChoiceLearningObject);
expect(result).toEqual(multipleChoiceExample.getHTMLRendering().replace(/\r\n/g, '\n'));
const testLearningObject = getLearningObjectRepository().create(testLearningObjectMultipleChoice);
const result = await processingService.render(testLearningObject);
expect(result).toEqual(getHtmlRenderingForTestLearningObject(testLearningObjectMultipleChoice).replace(/\r\n/g, '\n'));
});
it('renders an essay question correctly', async () => {
const essayLearningObject = essayExample.createLearningObject();
const essayLearningObject = getLearningObjectRepository().create(testLearningObjectEssayQuestion);
const result = await processingService.render(essayLearningObject);
expect(result).toEqual(essayExample.getHTMLRendering().replace(/\r\n/g, '\n'));
expect(result).toEqual(getHtmlRenderingForTestLearningObject(essayLearningObject).replace(/\r\n/g, '\n'));
});
});

View file

@ -2,227 +2,112 @@ import { beforeAll, describe, expect, it } from 'vitest';
import { LearningObject } from '../../../src/entities/content/learning-object.entity.js';
import { setupTestApp } from '../../setup-tests.js';
import { LearningPath } from '../../../src/entities/content/learning-path.entity.js';
import {
getAssignmentRepository,
getClassRepository,
getGroupRepository,
getLearningObjectRepository,
getLearningPathRepository,
getStudentRepository,
getSubmissionRepository,
} from '../../../src/data/repositories.js';
import learningObjectExample from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example.js';
import learningPathExample from '../../test-assets/learning-paths/pn-werking-example.js';
import { getSubmissionRepository } from '../../../src/data/repositories.js';
import databaseLearningPathProvider from '../../../src/services/learning-paths/database-learning-path-provider.js';
import { expectToBeCorrectLearningPath } from '../../test-utils/expectations.js';
import learningObjectService from '../../../src/services/learning-objects/learning-object-service.js';
import { Language } from '@dwengo-1/common/util/language';
import {
ConditionTestLearningPathAndLearningObjects,
createConditionTestLearningPathAndLearningObjects,
} from '../../test-assets/learning-paths/test-conditions-example.js';
import { Student } from '../../../src/entities/users/student.entity.js';
import { LearningObjectNode, LearningPathResponse } from '@dwengo-1/common/interfaces/learning-content';
import {
testLearningObject01,
testLearningObjectEssayQuestion,
testLearningObjectMultipleChoice,
} from '../../test_assets/content/learning-objects.testdata';
import { testLearningPathWithConditions } from '../../test_assets/content/learning-paths.testdata';
import { mapToLearningPath } from '../../../src/services/learning-paths/learning-path-service';
import { getTestGroup01, getTestGroup02 } from '../../test_assets/assignments/groups.testdata';
import { Group } from '../../../src/entities/assignments/group.entity.js';
import { RequiredEntityData } from '@mikro-orm/core';
const STUDENT_A_USERNAME = 'student_a';
const STUDENT_B_USERNAME = 'student_b';
const CLASS_NAME = 'test_class';
async function initExampleData(): Promise<{ learningObject: LearningObject; learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
}
async function initPersonalizationTestData(): Promise<{
learningContent: ConditionTestLearningPathAndLearningObjects;
studentA: Student;
studentB: Student;
}> {
const studentRepo = getStudentRepository();
const classRepo = getClassRepository();
const assignmentRepo = getAssignmentRepository();
const groupRepo = getGroupRepository();
const submissionRepo = getSubmissionRepository();
const learningPathRepo = getLearningPathRepository();
const learningObjectRepo = getLearningObjectRepository();
const learningContent = createConditionTestLearningPathAndLearningObjects();
await learningObjectRepo.save(learningContent.branchingObject);
await learningObjectRepo.save(learningContent.finalObject);
await learningObjectRepo.save(learningContent.extraExerciseObject);
await learningPathRepo.save(learningContent.learningPath);
// Create students
const studentA = studentRepo.create({
username: STUDENT_A_USERNAME,
firstName: 'Aron',
lastName: 'Student',
});
await studentRepo.save(studentA);
const studentB = studentRepo.create({
username: STUDENT_B_USERNAME,
firstName: 'Bill',
lastName: 'Student',
});
await studentRepo.save(studentB);
// Create class for students
const testClass = classRepo.create({
classId: CLASS_NAME,
displayName: 'Test class',
});
await classRepo.save(testClass);
// Create assignment for students and assign them to different groups
const assignment = assignmentRepo.create({
id: 0,
title: 'Test assignment',
description: 'Test description',
learningPathHruid: learningContent.learningPath.hruid,
learningPathLanguage: learningContent.learningPath.language,
within: testClass,
});
const groupA = groupRepo.create({
groupNumber: 0,
members: [studentA],
assignment,
});
await groupRepo.save(groupA);
const groupB = groupRepo.create({
groupNumber: 1,
members: [studentB],
assignment,
});
await groupRepo.save(groupB);
// Let each of the students make a submission in his own group.
const submissionA = submissionRepo.create({
learningObjectHruid: learningContent.branchingObject.hruid,
learningObjectLanguage: learningContent.branchingObject.language,
learningObjectVersion: learningContent.branchingObject.version,
onBehalfOf: groupA,
submitter: studentA,
submissionTime: new Date(),
content: '[0]',
});
await submissionRepo.save(submissionA);
const submissionB = submissionRepo.create({
learningObjectHruid: learningContent.branchingObject.hruid,
learningObjectLanguage: learningContent.branchingObject.language,
learningObjectVersion: learningContent.branchingObject.version,
onBehalfOf: groupA,
submitter: studentB,
submissionTime: new Date(),
content: '[1]',
});
await submissionRepo.save(submissionB);
return {
learningContent: learningContent,
studentA: studentA,
studentB: studentB,
};
}
function expectBranchingObjectNode(
result: LearningPathResponse,
persTestData: {
learningContent: ConditionTestLearningPathAndLearningObjects;
studentA: Student;
studentB: Student;
}
): LearningObjectNode {
const branchingObjectMatches = result.data![0].nodes.filter(
(it) => it.learningobject_hruid === persTestData.learningContent.branchingObject.hruid
);
function expectBranchingObjectNode(result: LearningPathResponse): LearningObjectNode {
const branchingObjectMatches = result.data![0].nodes.filter((it) => it.learningobject_hruid === testLearningObjectMultipleChoice.hruid);
expect(branchingObjectMatches.length).toBe(1);
return branchingObjectMatches[0];
}
describe('DatabaseLearningPathProvider', () => {
let example: { learningObject: LearningObject; learningPath: LearningPath };
let persTestData: { learningContent: ConditionTestLearningPathAndLearningObjects; studentA: Student; studentB: Student };
let testLearningPath: LearningPath;
let branchingLearningObject: RequiredEntityData<LearningObject>;
let extraExerciseLearningObject: RequiredEntityData<LearningObject>;
let finalLearningObject: RequiredEntityData<LearningObject>;
let groupA: Group;
let groupB: Group;
beforeAll(async () => {
await setupTestApp();
example = await initExampleData();
persTestData = await initPersonalizationTestData();
testLearningPath = mapToLearningPath(testLearningPathWithConditions, []);
branchingLearningObject = testLearningObjectMultipleChoice;
extraExerciseLearningObject = testLearningObject01;
finalLearningObject = testLearningObjectEssayQuestion;
groupA = getTestGroup01();
groupB = getTestGroup02();
// Place different submissions for group A and B.
const submissionRepo = getSubmissionRepository();
const submissionA = submissionRepo.create({
learningObjectHruid: branchingLearningObject.hruid,
learningObjectLanguage: branchingLearningObject.language,
learningObjectVersion: branchingLearningObject.version,
content: '[0]',
onBehalfOf: groupA,
submissionTime: new Date(),
submitter: groupA.members[0],
});
await submissionRepo.save(submissionA);
const submissionB = submissionRepo.create({
learningObjectHruid: branchingLearningObject.hruid,
learningObjectLanguage: branchingLearningObject.language,
learningObjectVersion: branchingLearningObject.version,
content: '[1]',
onBehalfOf: groupB,
submissionTime: new Date(),
submitter: groupB.members[0],
});
await submissionRepo.save(submissionB);
});
describe('fetchLearningPaths', () => {
it('returns the learning path correctly', async () => {
const result = await databaseLearningPathProvider.fetchLearningPaths(
[example.learningPath.hruid],
example.learningPath.language,
'the source'
);
const result = await databaseLearningPathProvider.fetchLearningPaths([testLearningPath.hruid], testLearningPath.language, 'the source');
expect(result.success).toBe(true);
expect(result.data?.length).toBe(1);
const learningObjectsOnPath = (
await Promise.all(
example.learningPath.nodes.map(async (node) =>
learningObjectService.getLearningObjectById({
hruid: node.learningObjectHruid,
version: node.version,
language: node.language,
})
)
)
).filter((it) => it !== null);
expectToBeCorrectLearningPath(result.data![0], example.learningPath, learningObjectsOnPath);
expectToBeCorrectLearningPath(result.data![0], testLearningPathWithConditions);
});
it('returns the correct personalized learning path', async () => {
// For student A:
let result = await databaseLearningPathProvider.fetchLearningPaths(
[persTestData.learningContent.learningPath.hruid],
persTestData.learningContent.learningPath.language,
[testLearningPath.hruid],
testLearningPath.language,
'the source',
{ type: 'student', student: persTestData.studentA }
groupA
);
expect(result.success).toBeTruthy();
expect(result.data?.length).toBe(1);
// There should be exactly one branching object
let branchingObject = expectBranchingObjectNode(result, persTestData);
let branchingObject = expectBranchingObjectNode(result);
expect(branchingObject.transitions.filter((it) => it.next.hruid === persTestData.learningContent.finalObject.hruid).length).toBe(0); // StudentA picked the first option, therefore, there should be no direct path to the final object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === persTestData.learningContent.extraExerciseObject.hruid).length).toBe(
1
); // There should however be a path to the extra exercise object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === finalLearningObject.hruid).length).toBe(0); // StudentA picked the first option, therefore, there should be no direct path to the final object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === extraExerciseLearningObject.hruid).length).toBe(1); // There should however be a path to the extra exercise object.
// For student B:
result = await databaseLearningPathProvider.fetchLearningPaths(
[persTestData.learningContent.learningPath.hruid],
persTestData.learningContent.learningPath.language,
'the source',
{ type: 'student', student: persTestData.studentB }
);
result = await databaseLearningPathProvider.fetchLearningPaths([testLearningPath.hruid], testLearningPath.language, 'the source', groupB);
expect(result.success).toBeTruthy();
expect(result.data?.length).toBe(1);
// There should still be exactly one branching object
branchingObject = expectBranchingObjectNode(result, persTestData);
branchingObject = expectBranchingObjectNode(result);
// However, now the student picks the other option.
expect(branchingObject.transitions.filter((it) => it.next.hruid === persTestData.learningContent.finalObject.hruid).length).toBe(1); // StudentB picked the second option, therefore, there should be a direct path to the final object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === persTestData.learningContent.extraExerciseObject.hruid).length).toBe(
0
); // There should not be a path anymore to the extra exercise object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === finalLearningObject.hruid).length).toBe(1); // StudentB picked the second option, therefore, there should be a direct path to the final object.
expect(branchingObject.transitions.filter((it) => it.next.hruid === extraExerciseLearningObject.hruid).length).toBe(0); // There should not be a path anymore to the extra exercise object.
});
it('returns a non-successful response if a non-existing learning path is queried', async () => {
const result = await databaseLearningPathProvider.fetchLearningPaths(
[example.learningPath.hruid],
[testLearningPath.hruid],
Language.Abkhazian, // Wrong language
'the source'
);
@ -233,27 +118,24 @@ describe('DatabaseLearningPathProvider', () => {
describe('searchLearningPaths', () => {
it('returns the correct learning path when queried with a substring of its title', async () => {
const result = await databaseLearningPathProvider.searchLearningPaths(
example.learningPath.title.substring(2, 6),
example.learningPath.language
);
const result = await databaseLearningPathProvider.searchLearningPaths(testLearningPath.title.substring(2, 6), testLearningPath.language);
expect(result.length).toBe(1);
expect(result[0].title).toBe(example.learningPath.title);
expect(result[0].description).toBe(example.learningPath.description);
expect(result[0].title).toBe(testLearningPath.title);
expect(result[0].description).toBe(testLearningPath.description);
});
it('returns the correct learning path when queried with a substring of the description', async () => {
const result = await databaseLearningPathProvider.searchLearningPaths(
example.learningPath.description.substring(5, 12),
example.learningPath.language
testLearningPath.description.substring(5, 12),
testLearningPath.language
);
expect(result.length).toBe(1);
expect(result[0].title).toBe(example.learningPath.title);
expect(result[0].description).toBe(example.learningPath.description);
expect(result[0].title).toBe(testLearningPath.title);
expect(result[0].description).toBe(testLearningPath.description);
});
it('returns an empty result when queried with a text which is not a substring of the title or the description of a learning path', async () => {
const result = await databaseLearningPathProvider.searchLearningPaths(
'substring which does not occur in the title or the description of a learning object',
example.learningPath.language
testLearningPath.language
);
expect(result.length).toBe(0);
});

View file

@ -1,22 +1,9 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { setupTestApp } from '../../setup-tests';
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
import { getLearningObjectRepository, getLearningPathRepository } from '../../../src/data/repositories';
import learningObjectExample from '../../test-assets/learning-objects/pn-werkingnotebooks/pn-werkingnotebooks-example';
import learningPathExample from '../../test-assets/learning-paths/pn-werking-example';
import learningPathService from '../../../src/services/learning-paths/learning-path-service';
import { Language } from '@dwengo-1/common/util/language';
async function initExampleData(): Promise<{ learningObject: LearningObject; learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
}
import { testPartiallyDatabaseAndPartiallyDwengoApiLearningPath } from '../../test_assets/content/learning-paths.testdata';
import { LearningPath as LearningPathDTO } from '@dwengo-1/common/interfaces/learning-content';
const TEST_DWENGO_LEARNING_PATH_HRUID = 'pn_werking';
const TEST_DWENGO_LEARNING_PATH_TITLE = 'Werken met notebooks';
@ -24,42 +11,49 @@ const TEST_DWENGO_EXCLUSIVE_LEARNING_PATH_SEARCH_QUERY = 'Microscopie';
const TEST_SEARCH_QUERY_EXPECTING_NO_MATCHES = 'su$m8f9usf89ud<p9<U8SDP8UP9';
describe('LearningPathService', () => {
let example: { learningObject: LearningObject; learningPath: LearningPath };
let testLearningPath: LearningPathDTO;
beforeAll(async () => {
await setupTestApp();
example = await initExampleData();
testLearningPath = testPartiallyDatabaseAndPartiallyDwengoApiLearningPath;
});
describe('fetchLearningPaths', () => {
it('should return learning paths both from the database and from the Dwengo API', async () => {
const result = await learningPathService.fetchLearningPaths(
[example.learningPath.hruid, TEST_DWENGO_LEARNING_PATH_HRUID],
example.learningPath.language,
[testLearningPath.hruid, TEST_DWENGO_LEARNING_PATH_HRUID],
testLearningPath.language as Language,
'the source'
);
expect(result.success).toBeTruthy();
expect(result.data?.filter((it) => it.hruid === TEST_DWENGO_LEARNING_PATH_HRUID).length).not.toBe(0);
expect(result.data?.filter((it) => it.hruid === example.learningPath.hruid).length).not.toBe(0);
expect(result.data?.filter((it) => it.hruid === testLearningPath.hruid).length).not.toBe(0);
expect(result.data?.find((it) => it.hruid === TEST_DWENGO_LEARNING_PATH_HRUID)?.title).toEqual(TEST_DWENGO_LEARNING_PATH_TITLE);
expect(result.data?.find((it) => it.hruid === example.learningPath.hruid)?.title).toEqual(example.learningPath.title);
expect(result.data?.find((it) => it.hruid === testLearningPath.hruid)?.title).toEqual(testLearningPath.title);
});
it('should include both the learning objects from the Dwengo API and learning objects from the database in its response', async () => {
const result = await learningPathService.fetchLearningPaths([example.learningPath.hruid], example.learningPath.language, 'the source');
const result = await learningPathService.fetchLearningPaths(
[testLearningPath.hruid],
testLearningPath.language as Language,
'the source'
);
expect(result.success).toBeTruthy();
expect(result.data?.length).toBe(1);
// Should include all the nodes, even those pointing to foreign learning objects.
expect([...result.data![0].nodes.map((it) => it.learningobject_hruid)].sort((a, b) => a.localeCompare(b))).toEqual(
example.learningPath.nodes.map((it) => it.learningObjectHruid).sort((a, b) => a.localeCompare(b))
testLearningPath.nodes.map((it) => it.learningobject_hruid).sort((a, b) => a.localeCompare(b))
);
});
});
describe('searchLearningPath', () => {
it('should include both the learning paths from the Dwengo API and those from the database in its response', async () => {
// This matches the learning object in the database, but definitely also some learning objects in the Dwengo API.
const result = await learningPathService.searchLearningPaths(example.learningPath.title.substring(2, 3), example.learningPath.language);
const result = await learningPathService.searchLearningPaths(
testLearningPath.title.substring(2, 3),
testLearningPath.language as Language
);
// Should find the one from the database
expect(result.filter((it) => it.hruid === example.learningPath.hruid && it.title === example.learningPath.title).length).toBe(1);
expect(result.filter((it) => it.hruid === testLearningPath.hruid && it.title === testLearningPath.title).length).toBe(1);
// But should not only find that one.
expect(result.length).not.toBeLessThan(2);
@ -71,7 +65,7 @@ describe('LearningPathService', () => {
expect(result.length).not.toBe(0);
// But not the example learning path.
expect(result.filter((it) => it.hruid === example.learningPath.hruid && it.title === example.learningPath.title).length).toBe(0);
expect(result.filter((it) => it.hruid === testLearningPath.hruid && it.title === testLearningPath.title).length).toBe(0);
});
it('should return an empty list if neither the Dwengo API nor the database contains matches', async () => {
const result = await learningPathService.searchLearningPaths(TEST_SEARCH_QUERY_EXPECTING_NO_MATCHES, Language.Dutch);

View file

@ -13,6 +13,8 @@ import { makeTestAttachments } from './test_assets/content/attachments.testdata.
import { makeTestQuestions } from './test_assets/questions/questions.testdata.js';
import { makeTestAnswers } from './test_assets/questions/answers.testdata.js';
import { makeTestSubmissions } from './test_assets/assignments/submission.testdata.js';
import { Collection } from '@mikro-orm/core';
import { Group } from '../src/entities/assignments/group.entity';
export async function setupTestApp(): Promise<void> {
dotenv.config({ path: '.env.test' });
@ -28,8 +30,8 @@ export async function setupTestApp(): Promise<void> {
const assignments = makeTestAssignemnts(em, classes);
const groups = makeTestGroups(em, students, assignments);
assignments[0].groups = groups.slice(0, 3);
assignments[1].groups = groups.slice(3, 4);
assignments[0].groups = new Collection<Group>(groups.slice(0, 3));
assignments[1].groups = new Collection<Group>(groups.slice(3, 4));
const teacherInvitations = makeTestTeacherInvitations(em, teachers, classes);
const classJoinRequests = makeTestClassJoinRequests(em, students, classes);

View file

@ -1,10 +0,0 @@
import { LearningObjectExample } from './learning-object-example';
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
export function createExampleLearningObjectWithAttachments(example: LearningObjectExample): LearningObject {
const learningObject = example.createLearningObject();
for (const creationFn of Object.values(example.createAttachment)) {
learningObject.attachments.push(creationFn(learningObject));
}
return learningObject;
}

View file

@ -1,32 +0,0 @@
import { LearningObjectExample } from '../learning-object-example';
import { LearningObject } from '../../../../src/entities/content/learning-object.entity';
import { Language } from '@dwengo-1/common/util/language';
import { loadTestAsset } from '../../../test-utils/load-test-asset';
import { DwengoContentType } from '../../../../src/services/learning-objects/processing/content-type';
import { envVars, getEnvVar } from '../../../../src/util/envVars';
/**
* Create a dummy learning object to be used in tests where multiple learning objects are needed (for example for use
* on a path), but where the precise contents of the learning object are not important.
*/
export function dummyLearningObject(hruid: string, language: Language, title: string): LearningObjectExample {
return {
createLearningObject: (): LearningObject => {
const learningObject = new LearningObject();
learningObject.hruid = getEnvVar(envVars.UserContentPrefix) + hruid;
learningObject.language = language;
learningObject.version = 1;
learningObject.title = title;
learningObject.description = 'Just a dummy learning object for testing purposes';
learningObject.contentType = DwengoContentType.TEXT_PLAIN;
learningObject.content = Buffer.from('Dummy content');
learningObject.returnValue = {
callbackUrl: `/learningObject/${hruid}/submissions`,
callbackSchema: '[]',
};
return learningObject;
},
createAttachment: {},
getHTMLRendering: () => loadTestAsset('learning-objects/dummy/rendering.txt').toString(),
};
}

View file

@ -1,8 +0,0 @@
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
import { Attachment } from '../../../src/entities/content/attachment.entity';
interface LearningObjectExample {
createLearningObject: () => LearningObject;
createAttachment: Record<string, (owner: LearningObject) => Attachment>;
getHTMLRendering: () => string;
}

View file

@ -1,74 +0,0 @@
import { LearningObjectExample } from '../learning-object-example';
import { Language } from '@dwengo-1/common/util/language';
import { DwengoContentType } from '../../../../src/services/learning-objects/processing/content-type';
import { loadTestAsset } from '../../../test-utils/load-test-asset';
import { LearningObject } from '../../../../src/entities/content/learning-object.entity';
import { Attachment } from '../../../../src/entities/content/attachment.entity';
import { envVars, getEnvVar } from '../../../../src/util/envVars';
import { EducationalGoal } from '../../../../src/entities/content/educational-goal.entity';
import { ReturnValue } from '../../../../src/entities/content/return-value.entity';
const ASSETS_PREFIX = 'learning-objects/pn-werkingnotebooks/';
const example: LearningObjectExample = {
createLearningObject: () => {
const learningObject = new LearningObject();
learningObject.hruid = `${getEnvVar(envVars.UserContentPrefix)}pn_werkingnotebooks`;
learningObject.version = 3;
learningObject.language = Language.Dutch;
learningObject.title = 'Werken met notebooks';
learningObject.description = 'Leren werken met notebooks';
learningObject.keywords = ['Python', 'KIKS', 'Wiskunde', 'STEM', 'AI'];
const educationalGoal1 = new EducationalGoal();
educationalGoal1.source = 'Source';
educationalGoal1.id = 'id';
const educationalGoal2 = new EducationalGoal();
educationalGoal2.source = 'Source2';
educationalGoal2.id = 'id2';
learningObject.educationalGoals = [educationalGoal1, educationalGoal2];
learningObject.admins = [];
learningObject.contentType = DwengoContentType.TEXT_MARKDOWN;
learningObject.teacherExclusive = false;
learningObject.skosConcepts = [
'http://ilearn.ilabt.imec.be/vocab/curr1/s-vaktaal',
'http://ilearn.ilabt.imec.be/vocab/curr1/s-digitale-media-en-toepassingen',
'http://ilearn.ilabt.imec.be/vocab/curr1/s-computers-en-systemen',
];
learningObject.copyright = 'dwengo';
learningObject.license = 'dwengo';
learningObject.estimatedTime = 10;
const returnValue = new ReturnValue();
returnValue.callbackUrl = 'callback_url_example';
returnValue.callbackSchema = '{"att": "test", "att2": "test2"}';
learningObject.returnValue = returnValue;
learningObject.available = true;
learningObject.content = loadTestAsset(`${ASSETS_PREFIX}/content.md`);
return learningObject;
},
createAttachment: {
dwengoLogo: (learningObject) => {
const att = new Attachment();
att.learningObject = learningObject;
att.name = 'dwengo.png';
att.mimeType = 'image/png';
att.content = loadTestAsset(`${ASSETS_PREFIX}/dwengo.png`);
return att;
},
knop: (learningObject) => {
const att = new Attachment();
att.learningObject = learningObject;
att.name = 'Knop.png';
att.mimeType = 'image/png';
att.content = loadTestAsset(`${ASSETS_PREFIX}/Knop.png`);
return att;
},
},
getHTMLRendering: () => loadTestAsset(`${ASSETS_PREFIX}/rendering.txt`).toString(),
};
export default example;

View file

@ -1,2 +0,0 @@
::MC basic::
How are you? {}

View file

@ -1,7 +0,0 @@
<div class="learning-object-gift">
<div id="gift-q1" class="gift-question">
<h2 id="gift-q1-title" class="gift-title">MC basic</h2>
<p id="gift-q1-stem" class="gift-stem">How are you?</p>
<textarea id="gift-q1-answer" class="gift-essay-answer"></textarea>
</div>
</div>

View file

@ -1,28 +0,0 @@
import { LearningObjectExample } from '../learning-object-example';
import { LearningObject } from '../../../../src/entities/content/learning-object.entity';
import { loadTestAsset } from '../../../test-utils/load-test-asset';
import { envVars, getEnvVar } from '../../../../src/util/envVars';
import { Language } from '@dwengo-1/common/util/language';
import { DwengoContentType } from '../../../../src/services/learning-objects/processing/content-type';
const example: LearningObjectExample = {
createLearningObject: () => {
const learningObject = new LearningObject();
learningObject.hruid = `${getEnvVar(envVars.UserContentPrefix)}test_essay`;
learningObject.language = Language.English;
learningObject.version = 1;
learningObject.title = 'Essay question for testing';
learningObject.description = 'This essay question was only created for testing purposes.';
learningObject.contentType = DwengoContentType.GIFT;
learningObject.returnValue = {
callbackUrl: `/learningObject/${learningObject.hruid}/submissions`,
callbackSchema: '["antwoord vraag 1"]',
};
learningObject.content = loadTestAsset('learning-objects/test-essay/content.txt');
return learningObject;
},
createAttachment: {},
getHTMLRendering: () => loadTestAsset('learning-objects/test-essay/rendering.txt').toString(),
};
export default example;

View file

@ -1,28 +0,0 @@
import { LearningObjectExample } from '../learning-object-example';
import { LearningObject } from '../../../../src/entities/content/learning-object.entity';
import { loadTestAsset } from '../../../test-utils/load-test-asset';
import { envVars, getEnvVar } from '../../../../src/util/envVars';
import { DwengoContentType } from '../../../../src/services/learning-objects/processing/content-type';
import { Language } from '@dwengo-1/common/util/language';
const example: LearningObjectExample = {
createLearningObject: () => {
const learningObject = new LearningObject();
learningObject.hruid = `${getEnvVar(envVars.UserContentPrefix)}test_multiple_choice`;
learningObject.language = Language.English;
learningObject.version = 1;
learningObject.title = 'Multiple choice question for testing';
learningObject.description = 'This multiple choice question was only created for testing purposes.';
learningObject.contentType = DwengoContentType.GIFT;
learningObject.returnValue = {
callbackUrl: `/learningObject/${learningObject.hruid}/submissions`,
callbackSchema: '["antwoord vraag 1"]',
};
learningObject.content = loadTestAsset('learning-objects/test-multiple-choice/content.txt');
return learningObject;
},
createAttachment: {},
getHTMLRendering: () => loadTestAsset('learning-objects/test-multiple-choice/rendering.txt').toString(),
};
export default example;

View file

@ -1,3 +0,0 @@
interface LearningPathExample {
createLearningPath: () => LearningPath;
}

View file

@ -1,36 +0,0 @@
import { Language } from '@dwengo-1/common/util/language';
import { LearningPathTransition } from '../../../src/entities/content/learning-path-transition.entity';
import { LearningPathNode } from '../../../src/entities/content/learning-path-node.entity';
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
export function createLearningPathTransition(
node: LearningPathNode,
transitionNumber: number,
condition: string | null,
to: LearningPathNode
): LearningPathTransition {
const trans = new LearningPathTransition();
trans.node = node;
trans.transitionNumber = transitionNumber;
trans.condition = condition || 'true';
trans.next = to;
return trans;
}
export function createLearningPathNode(
learningPath: LearningPath,
nodeNumber: number,
learningObjectHruid: string,
version: number,
language: Language,
startNode: boolean
): LearningPathNode {
const node = new LearningPathNode();
node.learningPath = learningPath;
node.nodeNumber = nodeNumber;
node.learningObjectHruid = learningObjectHruid;
node.version = version;
node.language = language;
node.startNode = startNode;
return node;
}

View file

@ -1,30 +0,0 @@
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
import { Language } from '@dwengo-1/common/util/language';
import { envVars, getEnvVar } from '../../../src/util/envVars';
import { createLearningPathNode, createLearningPathTransition } from './learning-path-utils';
import { LearningPathNode } from '../../../src/entities/content/learning-path-node.entity';
function createNodes(learningPath: LearningPath): LearningPathNode[] {
const nodes = [
createLearningPathNode(learningPath, 0, 'u_pn_werkingnotebooks', 3, Language.Dutch, true),
createLearningPathNode(learningPath, 1, 'pn_werkingnotebooks2', 3, Language.Dutch, false),
createLearningPathNode(learningPath, 2, 'pn_werkingnotebooks3', 3, Language.Dutch, false),
];
nodes[0].transitions.push(createLearningPathTransition(nodes[0], 0, 'true', nodes[1]));
nodes[1].transitions.push(createLearningPathTransition(nodes[1], 0, 'true', nodes[2]));
return nodes;
}
const example: LearningPathExample = {
createLearningPath: () => {
const path = new LearningPath();
path.language = Language.Dutch;
path.hruid = `${getEnvVar(envVars.UserContentPrefix)}pn_werking`;
path.title = 'Werken met notebooks';
path.description = 'Een korte inleiding tot Python notebooks. Hoe ga je gemakkelijk en efficiënt met de notebooks aan de slag?';
path.nodes = createNodes(path);
return path;
},
};
export default example;

View file

@ -1,80 +0,0 @@
import { LearningPath } from '../../../src/entities/content/learning-path.entity';
import { Language } from '@dwengo-1/common/util/language';
import testMultipleChoiceExample from '../learning-objects/test-multiple-choice/test-multiple-choice-example';
import { dummyLearningObject } from '../learning-objects/dummy/dummy-learning-object-example';
import { createLearningPathNode, createLearningPathTransition } from './learning-path-utils';
import { LearningObject } from '../../../src/entities/content/learning-object.entity';
import { envVars, getEnvVar } from '../../../src/util/envVars';
export interface ConditionTestLearningPathAndLearningObjects {
branchingObject: LearningObject;
extraExerciseObject: LearningObject;
finalObject: LearningObject;
learningPath: LearningPath;
}
export function createConditionTestLearningPathAndLearningObjects(): ConditionTestLearningPathAndLearningObjects {
const learningPath = new LearningPath();
learningPath.hruid = `${getEnvVar(envVars.UserContentPrefix)}test_conditions`;
learningPath.language = Language.English;
learningPath.title = 'Example learning path with conditional transitions';
learningPath.description = 'This learning path was made for the purpose of testing conditional transitions';
const branchingLearningObject = testMultipleChoiceExample.createLearningObject();
const extraExerciseLearningObject = dummyLearningObject(
'test_extra_exercise',
Language.English,
'Extra exercise (for students with difficulties)'
).createLearningObject();
const finalLearningObject = dummyLearningObject(
'test_final_learning_object',
Language.English,
'Final exercise (for everyone)'
).createLearningObject();
const branchingNode = createLearningPathNode(
learningPath,
0,
branchingLearningObject.hruid,
branchingLearningObject.version,
branchingLearningObject.language,
true
);
const extraExerciseNode = createLearningPathNode(
learningPath,
1,
extraExerciseLearningObject.hruid,
extraExerciseLearningObject.version,
extraExerciseLearningObject.language,
false
);
const finalNode = createLearningPathNode(
learningPath,
2,
finalLearningObject.hruid,
finalLearningObject.version,
finalLearningObject.language,
false
);
const transitionToExtraExercise = createLearningPathTransition(
branchingNode,
0,
'$[?(@[0] == 0)]', // The answer to the first question was the first one, which says that it is difficult for the student to follow along.
extraExerciseNode
);
const directTransitionToFinal = createLearningPathTransition(branchingNode, 1, '$[?(@[0] == 1)]', finalNode);
const transitionExtraExerciseToFinal = createLearningPathTransition(extraExerciseNode, 0, 'true', finalNode);
branchingNode.transitions = [transitionToExtraExercise, directTransitionToFinal];
extraExerciseNode.transitions = [transitionExtraExerciseToFinal];
learningPath.nodes = [branchingNode, extraExerciseNode, finalNode];
return {
branchingObject: branchingLearningObject,
finalObject: finalLearningObject,
extraExerciseObject: extraExerciseLearningObject,
learningPath: learningPath,
};
}

View file

@ -1,8 +1,8 @@
import { AssertionError } from 'node:assert';
import { LearningObject } from '../../src/entities/content/learning-object.entity';
import { LearningPath as LearningPathEntity } from '../../src/entities/content/learning-path.entity';
import { expect } from 'vitest';
import { FilteredLearningObject, LearningPath } from '@dwengo-1/common/interfaces/learning-content';
import { RequiredEntityData } from '@mikro-orm/core';
// Ignored properties because they belang for example to the class, not to the entity itself.
const IGNORE_PROPERTIES = ['parent'];
@ -11,53 +11,44 @@ const IGNORE_PROPERTIES = ['parent'];
* Checks if the actual entity from the database conforms to the entity that was added previously.
* @param actual The actual entity retrieved from the database
* @param expected The (previously added) entity we would expect to retrieve
* @param propertyPrefix Prefix to append to property in error messages.
*/
export function expectToBeCorrectEntity<T extends object>(actual: { entity: T; name?: string }, expected: { entity: T; name?: string }): void {
if (!actual.name) {
actual.name = 'actual';
}
if (!expected.name) {
expected.name = 'expected';
}
for (const property in expected.entity) {
if (
property in IGNORE_PROPERTIES &&
expected.entity[property] !== undefined && // If we don't expect a certain value for a property, we assume it can be filled in by the database however it wants.
typeof expected.entity[property] !== 'function' // Functions obviously are not persisted via the database
) {
if (!Object.prototype.hasOwnProperty.call(actual.entity, property)) {
throw new AssertionError({
message: `${expected.name} has defined property ${property}, but ${actual.name} is missing it.`,
});
}
if (typeof expected.entity[property] === 'boolean') {
// Sometimes, booleans get represented by numbers 0 and 1 in the objects actual from the database.
if (Boolean(expected.entity[property]) !== Boolean(actual.entity[property])) {
export function expectToBeCorrectEntity<T extends object>(actual: T, expected: T, propertyPrefix = ''): void {
for (const property in expected) {
if (Object.prototype.hasOwnProperty.call(expected, property)) {
const prefixedProperty = propertyPrefix + property;
if (
property in IGNORE_PROPERTIES &&
expected[property] !== undefined && // If we don't expect a certain value for a property, we assume it can be filled in by the database however it wants.
typeof expected[property] !== 'function' // Functions obviously are not persisted via the database
) {
if (!Object.prototype.hasOwnProperty.call(actual, property)) {
throw new AssertionError({
message: `${property} was ${expected.entity[property]} in ${expected.name},
but ${actual.entity[property]} (${Boolean(expected.entity[property])}) in ${actual.name}`,
message: `Expected property ${prefixedProperty}, but it is missing.`,
});
}
} else if (typeof expected.entity[property] !== typeof actual.entity[property]) {
throw new AssertionError({
message: `${property} has type ${typeof expected.entity[property]} in ${expected.name}, but type ${typeof actual.entity[property]} in ${actual.name}.`,
});
} else if (typeof expected.entity[property] === 'object') {
expectToBeCorrectEntity(
{
name: actual.name + '.' + property,
entity: actual.entity[property] as object,
},
{
name: expected.name + '.' + property,
entity: expected.entity[property] as object,
if (typeof expected[property] === 'boolean') {
// Sometimes, booleans get represented by numbers 0 and 1 in the objects actual from the database.
if (Boolean(expected[property]) !== Boolean(actual[property])) {
throw new AssertionError({
message: `Expected ${prefixedProperty} to be ${expected[property]},
but was ${actual[property]} (${Boolean(expected[property])}).`,
});
}
);
} else {
if (expected.entity[property] !== actual.entity[property]) {
} else if (typeof expected[property] !== typeof actual[property]) {
throw new AssertionError({
message: `${property} was ${expected.entity[property]} in ${expected.name}, but ${actual.entity[property]} in ${actual.name}`,
message:
`${prefixedProperty} was expected to have type ${typeof expected[property]},` +
`but had type ${typeof actual[property]}.`,
});
} else if (typeof expected[property] === 'object') {
expectToBeCorrectEntity(actual[property] as object, expected[property] as object, property);
} else {
if (expected[property] !== actual[property]) {
throw new AssertionError({
message: `${prefixedProperty} was expected to be ${expected[property]}, ` + `but was ${actual[property]}.`,
});
}
}
}
}
@ -67,9 +58,9 @@ export function expectToBeCorrectEntity<T extends object>(actual: { entity: T; n
/**
* Checks that filtered is the correct representation of original as FilteredLearningObject.
* @param filtered the representation as FilteredLearningObject
* @param original the original entity added to the database
* @param original the data of the entity in the database that was filtered.
*/
export function expectToBeCorrectFilteredLearningObject(filtered: FilteredLearningObject, original: LearningObject): void {
export function expectToBeCorrectFilteredLearningObject(filtered: FilteredLearningObject, original: RequiredEntityData<LearningObject>): void {
expect(filtered.uuid).toEqual(original.uuid);
expect(filtered.version).toEqual(original.version);
expect(filtered.language).toEqual(original.language);
@ -97,54 +88,55 @@ export function expectToBeCorrectFilteredLearningObject(filtered: FilteredLearni
* is a correct representation of the given learning path entity.
*
* @param learningPath The learning path returned by the retriever, service or endpoint
* @param expectedEntity The expected entity
* @param learningObjectsOnPath The learning objects on LearningPath. Necessary since some information in
* the learning path returned from the API endpoint
* @param expected The learning path that should have been returned.
*/
export function expectToBeCorrectLearningPath(
learningPath: LearningPath,
expectedEntity: LearningPathEntity,
learningObjectsOnPath: FilteredLearningObject[]
): void {
expect(learningPath.hruid).toEqual(expectedEntity.hruid);
expect(learningPath.language).toEqual(expectedEntity.language);
expect(learningPath.description).toEqual(expectedEntity.description);
expect(learningPath.title).toEqual(expectedEntity.title);
export function expectToBeCorrectLearningPath(learningPath: LearningPath, expected: LearningPath): void {
expect(learningPath.hruid).toEqual(expected.hruid);
expect(learningPath.language).toEqual(expected.language);
expect(learningPath.description).toEqual(expected.description);
expect(learningPath.title).toEqual(expected.title);
const keywords = new Set(learningObjectsOnPath.flatMap((it) => it.keywords || []));
expect(new Set(learningPath.keywords.split(' '))).toEqual(keywords);
expect(new Set(learningPath.keywords.split(' '))).toEqual(new Set(learningPath.keywords.split(' ')));
const targetAges = new Set(learningObjectsOnPath.flatMap((it) => it.targetAges || []));
expect(new Set(learningPath.target_ages)).toEqual(targetAges);
expect(learningPath.min_age).toEqual(Math.min(...targetAges));
expect(learningPath.max_age).toEqual(Math.max(...targetAges));
expect(new Set(learningPath.target_ages)).toEqual(new Set(expected.target_ages));
expect(learningPath.min_age).toEqual(Math.min(...expected.target_ages));
expect(learningPath.max_age).toEqual(Math.max(...expected.target_ages));
expect(learningPath.num_nodes).toEqual(expectedEntity.nodes.length);
expect(learningPath.image || null).toEqual(expectedEntity.image);
expect(learningPath.num_nodes).toEqual(expected.nodes.length);
expect(learningPath.image ?? null).toEqual(expected.image ?? null);
const expectedLearningPathNodes = new Map(
expectedEntity.nodes.map((node) => [
{ learningObjectHruid: node.learningObjectHruid, language: node.language, version: node.version },
{ startNode: node.startNode, transitions: node.transitions },
])
);
for (const node of learningPath.nodes) {
const nodeKey = {
learningObjectHruid: node.learningobject_hruid,
language: node.language,
version: node.version,
};
expect(expectedLearningPathNodes.keys()).toContainEqual(nodeKey);
const expectedNode = [...expectedLearningPathNodes.entries()].find(
([key, _]) => key.learningObjectHruid === nodeKey.learningObjectHruid && key.language === node.language && key.version === node.version
)![1];
expect(node.start_node).toEqual(expectedNode.startNode);
expect(new Set(node.transitions.map((it) => it.next.hruid))).toEqual(
new Set(expectedNode.transitions.map((it) => it.next.learningObjectHruid))
for (const node of expected.nodes) {
const correspondingNode = learningPath.nodes.find(
(it) => node.learningobject_hruid === it.learningobject_hruid && node.language === it.language && node.version === it.version
);
expect(new Set(node.transitions.map((it) => it.next.language))).toEqual(new Set(expectedNode.transitions.map((it) => it.next.language)));
expect(new Set(node.transitions.map((it) => it.next.version))).toEqual(new Set(expectedNode.transitions.map((it) => it.next.version)));
expect(correspondingNode).toBeTruthy();
expect(Boolean(correspondingNode!.start_node)).toEqual(Boolean(node.start_node));
for (const transition of node.transitions) {
const correspondingTransition = correspondingNode!.transitions.find(
(it) =>
it.next.hruid === transition.next.hruid &&
it.next.language === transition.next.language &&
it.next.version === transition.next.version
);
expect(correspondingTransition).toBeTruthy();
}
}
}
/**
* Expect that the given result is a singleton list with exactly the given element.
*/
export function expectToHaveFoundPrecisely<T extends object>(expected: T, result: T[]): void {
expect(result).toHaveProperty('length');
expect(result.length).toBe(1);
expectToBeCorrectEntity(result[0], expected);
}
/**
* Expect that the given result is an empty list.
*/
export function expectToHaveFoundNothing<T>(result: T[]): void {
expect(result).toHaveProperty('length');
expect(result.length).toBe(0);
}

View file

@ -0,0 +1,10 @@
import { RequiredEntityData } from '@mikro-orm/core';
import { loadTestAsset } from './load-test-asset';
import { LearningObject } from '../../src/entities/content/learning-object.entity';
import { envVars, getEnvVar } from '../../src/util/envVars';
export function getHtmlRenderingForTestLearningObject(learningObject: RequiredEntityData<LearningObject>): string {
const userPrefix = getEnvVar(envVars.UserContentPrefix);
const cleanedHruid = learningObject.hruid.startsWith(userPrefix) ? learningObject.hruid.substring(userPrefix.length) : learningObject.hruid;
return loadTestAsset(`/content/learning-object-resources/${cleanedHruid}/rendering.txt`).toString();
}

View file

@ -1,10 +1,14 @@
import fs from 'fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const fileName = fileURLToPath(import.meta.url);
const dirName = path.dirname(fileName);
/**
* Load the asset at the given path.
* @param relPath Path of the asset relative to the test-assets folder.
*/
export function loadTestAsset(relPath: string): Buffer {
return fs.readFileSync(path.resolve(__dirname, `../test-assets/${relPath}`));
return fs.readFileSync(path.resolve(dirName, `../test_assets/${relPath}`));
}

View file

@ -2,11 +2,13 @@ import { EntityManager } from '@mikro-orm/core';
import { Assignment } from '../../../src/entities/assignments/assignment.entity';
import { Class } from '../../../src/entities/classes/class.entity';
import { Language } from '@dwengo-1/common/util/language';
import { testLearningPathWithConditions } from '../content/learning-paths.testdata';
import { getClassWithTestleerlingAndTestleerkracht } from '../classes/classes.testdata';
export function makeTestAssignemnts(em: EntityManager, classes: Class[]): Assignment[] {
const assignment01 = em.create(Assignment, {
assignment01 = em.create(Assignment, {
id: 21000,
within: classes[0],
id: 1,
title: 'dire straits',
description: 'reading',
learningPathHruid: 'id02',
@ -14,9 +16,9 @@ export function makeTestAssignemnts(em: EntityManager, classes: Class[]): Assign
groups: [],
});
const assignment02 = em.create(Assignment, {
assignment02 = em.create(Assignment, {
id: 21001,
within: classes[1],
id: 2,
title: 'tool',
description: 'reading',
learningPathHruid: 'id01',
@ -24,9 +26,9 @@ export function makeTestAssignemnts(em: EntityManager, classes: Class[]): Assign
groups: [],
});
const assignment03 = em.create(Assignment, {
assignment03 = em.create(Assignment, {
id: 21002,
within: classes[0],
id: 3,
title: 'delete',
description: 'will be deleted',
learningPathHruid: 'id02',
@ -34,9 +36,9 @@ export function makeTestAssignemnts(em: EntityManager, classes: Class[]): Assign
groups: [],
});
const assignment04 = em.create(Assignment, {
assignment04 = em.create(Assignment, {
id: 21003,
within: classes[0],
id: 4,
title: 'another assignment',
description: 'with a description',
learningPathHruid: 'id01',
@ -44,5 +46,41 @@ export function makeTestAssignemnts(em: EntityManager, classes: Class[]): Assign
groups: [],
});
return [assignment01, assignment02, assignment03, assignment04];
conditionalPathAssignment = em.create(Assignment, {
within: getClassWithTestleerlingAndTestleerkracht(),
id: 21004,
title: 'Assignment: Conditional Learning Path',
description: 'You have to do the testing learning path with a condition.',
learningPathHruid: testLearningPathWithConditions.hruid,
learningPathLanguage: testLearningPathWithConditions.language as Language,
groups: [],
});
return [assignment01, assignment02, assignment03, assignment04, conditionalPathAssignment];
}
let assignment01: Assignment;
let assignment02: Assignment;
let assignment03: Assignment;
let assignment04: Assignment;
let conditionalPathAssignment: Assignment;
export function getAssignment01(): Assignment {
return assignment01;
}
export function getAssignment02(): Assignment {
return assignment02;
}
export function getAssignment03(): Assignment {
return assignment03;
}
export function getAssignment04(): Assignment {
return assignment04;
}
export function getConditionalPathAssignment(): Assignment {
return conditionalPathAssignment;
}

View file

@ -2,15 +2,17 @@ import { EntityManager } from '@mikro-orm/core';
import { Group } from '../../../src/entities/assignments/group.entity';
import { Assignment } from '../../../src/entities/assignments/assignment.entity';
import { Student } from '../../../src/entities/users/student.entity';
import { getConditionalPathAssignment } from './assignments.testdata';
import { getTestleerling1 } from '../users/students.testdata';
export function makeTestGroups(em: EntityManager, students: Student[], assignments: Assignment[]): Group[] {
/*
* Group #1 for Assignment #1 in class 'id01'
* => Assigned to do learning path 'id02'
*/
const group01 = em.create(Group, {
group01 = em.create(Group, {
assignment: assignments[0],
groupNumber: 1,
groupNumber: 21001,
members: students.slice(0, 2),
});
@ -18,9 +20,9 @@ export function makeTestGroups(em: EntityManager, students: Student[], assignmen
* Group #2 for Assignment #1 in class 'id01'
* => Assigned to do learning path 'id02'
*/
const group02 = em.create(Group, {
group02 = em.create(Group, {
assignment: assignments[0],
groupNumber: 2,
groupNumber: 21002,
members: students.slice(2, 4),
});
@ -28,9 +30,9 @@ export function makeTestGroups(em: EntityManager, students: Student[], assignmen
* Group #3 for Assignment #1 in class 'id01'
* => Assigned to do learning path 'id02'
*/
const group03 = em.create(Group, {
group03 = em.create(Group, {
assignment: assignments[0],
groupNumber: 3,
groupNumber: 21003,
members: students.slice(4, 6),
});
@ -38,9 +40,9 @@ export function makeTestGroups(em: EntityManager, students: Student[], assignmen
* Group #4 for Assignment #2 in class 'id02'
* => Assigned to do learning path 'id01'
*/
const group04 = em.create(Group, {
group04 = em.create(Group, {
assignment: assignments[1],
groupNumber: 4,
groupNumber: 21004,
members: students.slice(3, 4),
});
@ -48,11 +50,51 @@ export function makeTestGroups(em: EntityManager, students: Student[], assignmen
* Group #5 for Assignment #4 in class 'id01'
* => Assigned to do learning path 'id01'
*/
const group05 = em.create(Group, {
group05 = em.create(Group, {
assignment: assignments[3],
groupNumber: 1,
groupNumber: 21001,
members: students.slice(0, 2),
});
return [group01, group02, group03, group04, group05];
/**
* Group 1 for the assignment of the testing learning path with conditions.
*/
group1ConditionalLearningPath = em.create(Group, {
assignment: getConditionalPathAssignment(),
groupNumber: 1,
members: [getTestleerling1()],
});
return [group01, group02, group03, group04, group05, group1ConditionalLearningPath];
}
let group01: Group;
let group02: Group;
let group03: Group;
let group04: Group;
let group05: Group;
let group1ConditionalLearningPath: Group;
export function getTestGroup01(): Group {
return group01;
}
export function getTestGroup02(): Group {
return group02;
}
export function getTestGroup03(): Group {
return group03;
}
export function getTestGroup04(): Group {
return group04;
}
export function getTestGroup05(): Group {
return group05;
}
export function getGroup1ConditionalLearningPath(): Group {
return group1ConditionalLearningPath;
}

View file

@ -2,31 +2,31 @@ import { EntityManager } from '@mikro-orm/core';
import { ClassJoinRequest } from '../../../src/entities/classes/class-join-request.entity';
import { Student } from '../../../src/entities/users/student.entity';
import { Class } from '../../../src/entities/classes/class.entity';
import { ClassJoinRequestStatus } from '@dwengo-1/common/util/class-join-request';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export function makeTestClassJoinRequests(em: EntityManager, students: Student[], classes: Class[]): ClassJoinRequest[] {
const classJoinRequest01 = em.create(ClassJoinRequest, {
requester: students[4],
class: classes[1],
status: ClassJoinRequestStatus.Open,
status: ClassStatus.Open,
});
const classJoinRequest02 = em.create(ClassJoinRequest, {
requester: students[2],
class: classes[1],
status: ClassJoinRequestStatus.Open,
status: ClassStatus.Open,
});
const classJoinRequest03 = em.create(ClassJoinRequest, {
requester: students[4],
class: classes[2],
status: ClassJoinRequestStatus.Open,
status: ClassStatus.Open,
});
const classJoinRequest04 = em.create(ClassJoinRequest, {
requester: students[3],
class: classes[2],
status: ClassJoinRequestStatus.Open,
status: ClassStatus.Open,
});
return [classJoinRequest01, classJoinRequest02, classJoinRequest03, classJoinRequest04];

View file

@ -2,12 +2,14 @@ import { EntityManager } from '@mikro-orm/core';
import { Class } from '../../../src/entities/classes/class.entity';
import { Student } from '../../../src/entities/users/student.entity';
import { Teacher } from '../../../src/entities/users/teacher.entity';
import { getTestleerkracht1 } from '../users/teachers.testdata';
import { getTestleerling1 } from '../users/students.testdata';
export function makeTestClasses(em: EntityManager, students: Student[], teachers: Teacher[]): Class[] {
const studentsClass01 = students.slice(0, 8);
const teacherClass01: Teacher[] = teachers.slice(4, 5);
const class01 = em.create(Class, {
class01 = em.create(Class, {
classId: '8764b861-90a6-42e5-9732-c0d9eb2f55f9',
displayName: 'class01',
teachers: teacherClass01,
@ -17,7 +19,7 @@ export function makeTestClasses(em: EntityManager, students: Student[], teachers
const studentsClass02: Student[] = students.slice(0, 2).concat(students.slice(3, 4));
const teacherClass02: Teacher[] = teachers.slice(1, 2);
const class02 = em.create(Class, {
class02 = em.create(Class, {
classId: '34d484a1-295f-4e9f-bfdc-3e7a23d86a89',
displayName: 'class02',
teachers: teacherClass02,
@ -27,7 +29,7 @@ export function makeTestClasses(em: EntityManager, students: Student[], teachers
const studentsClass03: Student[] = students.slice(1, 4);
const teacherClass03: Teacher[] = teachers.slice(2, 3);
const class03 = em.create(Class, {
class03 = em.create(Class, {
classId: '80dcc3e0-1811-4091-9361-42c0eee91cfa',
displayName: 'class03',
teachers: teacherClass03,
@ -37,12 +39,45 @@ export function makeTestClasses(em: EntityManager, students: Student[], teachers
const studentsClass04: Student[] = students.slice(0, 2);
const teacherClass04: Teacher[] = teachers.slice(2, 3);
const class04 = em.create(Class, {
class04 = em.create(Class, {
classId: '33d03536-83b8-4880-9982-9bbf2f908ddf',
displayName: 'class04',
teachers: teacherClass04,
students: studentsClass04,
});
return [class01, class02, class03, class04];
classWithTestleerlingAndTestleerkracht = em.create(Class, {
classId: 'a75298b5-18aa-471d-8eeb-5d77eb989393',
displayName: 'Testklasse',
teachers: [getTestleerkracht1()],
students: [getTestleerling1()],
});
return [class01, class02, class03, class04, classWithTestleerlingAndTestleerkracht];
}
let class01: Class;
let class02: Class;
let class03: Class;
let class04: Class;
let classWithTestleerlingAndTestleerkracht: Class;
export function getClass01(): Class {
return class01;
}
export function getClass02(): Class {
return class02;
}
export function getClass03(): Class {
return class03;
}
export function getClass04(): Class {
return class04;
}
export function getClassWithTestleerlingAndTestleerkracht(): Class {
return classWithTestleerlingAndTestleerkracht;
}

View file

@ -2,30 +2,35 @@ import { EntityManager } from '@mikro-orm/core';
import { TeacherInvitation } from '../../../src/entities/classes/teacher-invitation.entity';
import { Teacher } from '../../../src/entities/users/teacher.entity';
import { Class } from '../../../src/entities/classes/class.entity';
import { ClassStatus } from '@dwengo-1/common/util/class-join-request';
export function makeTestTeacherInvitations(em: EntityManager, teachers: Teacher[], classes: Class[]): TeacherInvitation[] {
const teacherInvitation01 = em.create(TeacherInvitation, {
sender: teachers[1],
receiver: teachers[0],
class: classes[1],
status: ClassStatus.Open,
});
const teacherInvitation02 = em.create(TeacherInvitation, {
sender: teachers[1],
receiver: teachers[2],
class: classes[1],
status: ClassStatus.Open,
});
const teacherInvitation03 = em.create(TeacherInvitation, {
sender: teachers[2],
receiver: teachers[0],
class: classes[2],
status: ClassStatus.Open,
});
const teacherInvitation04 = em.create(TeacherInvitation, {
sender: teachers[0],
receiver: teachers[1],
class: classes[0],
status: ClassStatus.Open,
});
return [teacherInvitation01, teacherInvitation02, teacherInvitation03, teacherInvitation04];

Some files were not shown because too many files have changed in this diff Show more