Files
encoach_frontend/src/utils/exams.be.ts
Tiago Ribeiro 872cc62fe4 - Added the ability for a student/developer to choose a gender for a speaking instructor;
- Made it so, if chosen, the user will only get speaking exams with their chosen gender;
- Added the ability for speaking exams to select a gender when generating;
2024-02-09 12:14:47 +00:00

59 lines
2.0 KiB
TypeScript

import {collection, getDocs, query, where, setDoc, doc, Firestore} from "firebase/firestore";
import {shuffle} from "lodash";
import {Exam, InstructorGender, Variant} from "@/interfaces/exam";
import {Stat} from "@/interfaces/user";
export const getExams = async (
db: Firestore,
module: string,
avoidRepeated: string,
// added userId as due to assignments being set from the teacher to the student
// we need to make sure we are serving exams not executed by the user and not
// by the teacher that performed the request
userId: string | undefined,
variant?: Variant,
instructorGender?: InstructorGender,
): Promise<Exam[]> => {
const moduleRef = collection(db, module);
const q = query(moduleRef, where("isDiagnostic", "==", false));
const snapshot = await getDocs(q);
const allExams = shuffle(
snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
module,
})),
) as Exam[];
const variantExams: Exam[] = filterByVariant(allExams, variant);
const genderedExams: Exam[] = filterByInstructorGender(variantExams, instructorGender);
if (avoidRepeated === "true") {
const statsQ = query(collection(db, "stats"), where("user", "==", userId));
const statsSnapshot = await getDocs(statsQ);
const stats: Stat[] = statsSnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as unknown as Stat[];
const filteredExams = genderedExams.filter((x) => !stats.map((s) => s.exam).includes(x.id));
return filteredExams.length > 0 ? filteredExams : genderedExams;
}
return genderedExams;
};
const filterByInstructorGender = (exams: Exam[], instructorGender?: InstructorGender) => {
if (!instructorGender || instructorGender === "varied") return exams;
return exams.filter((e) => (e.module === "speaking" ? e.instructorGender === instructorGender : true));
};
const filterByVariant = (exams: Exam[], variant?: Variant) => {
const filtered = variant && variant === "partial" ? exams.filter((x) => x.variant === "partial") : exams.filter((x) => x.variant !== "partial");
return filtered.length > 0 ? filtered : exams;
};