import { Exception, SafePromise, SafeResult } from "@rolesvillesoftware/tools/dist"; import { Calculator } from "./"; import { ExamDim, ExamStat, ExamContext, ExamFact } from "../models"; import { Logger } from "../Logger"; export class ExamCalculator extends Calculator { private async getExamStat(exam: ExamDim): Promise { const query = this.processResults( await SafePromise.run(() => this.context.examStat.selectOrCreate((i, b) => i.examDimId === b.examDimId, { examDimId: exam.id } as ExamStat)) ); if ( query.count === 0) { throw new Exception("Unable to create exam stat record"); } return query.toArray()[0]; } private async getExamStudents(exam: ExamDim): Promise { const students = this.processResults( await SafePromise.run(() => this.context.examFact .where((i, b) => i.examDimId === b.id, exam) .execute() .toPromise() ) ).toArray(); if (students.length === 0) { throw new Exception("No exam, student, question data exists"); } if (!students.every((v, i) => i === 0 || v.examDimId === students[i - 1].examDimId)) { throw new Exception("Not all question facts are for the same question."); } return students; } async calculate(input?: ExamDim): Promise { if (input == null) { return null; } Logger.log(`Loading Student Answers`); const students = this.processResults(await SafePromise.run(() => this.getExamStudents(input))); Logger.log(`Loading or creating Exam Stat Record`); const examStat = this.processResults(await SafePromise.run(() => this.getExamStat(input))); Logger.log(`Calculating initial exam statistics`); examStat.populate(input, students); return examStat; } }