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 => { 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; };