Allowed admins and others to download reports related to other users

This commit is contained in:
Tiago Ribeiro
2024-01-21 12:48:29 +00:00
parent f6bb69f994
commit 83b8ab7774

View File

@@ -1,33 +1,20 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app, storage } from "@/firebase";
import {
getFirestore,
doc,
getDoc,
updateDoc,
getDocs,
query,
collection,
where,
} from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import type {NextApiRequest, NextApiResponse} from "next";
import {app, storage} from "@/firebase";
import {getFirestore, doc, getDoc, updateDoc, getDocs, query, collection, where} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import ReactPDF from "@react-pdf/renderer";
import TestReport from "@/exams/pdf/test.report";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { DemographicInformation, User } from "@/interfaces/user";
import { Module } from "@/interfaces";
import { ModuleScore } from "@/interfaces/module.scores";
import { SkillExamDetails } from "@/exams/pdf/details/skill.exam";
import { LevelExamDetails } from "@/exams/pdf/details/level.exam";
import { calculateBandScore } from "@/utils/score";
import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
import {DemographicInformation, User} from "@/interfaces/user";
import {Module} from "@/interfaces";
import {ModuleScore} from "@/interfaces/module.scores";
import {SkillExamDetails} from "@/exams/pdf/details/skill.exam";
import {LevelExamDetails} from "@/exams/pdf/details/level.exam";
import {calculateBandScore} from "@/utils/score";
import axios from "axios";
import { moduleLabels } from "@/utils/moduleUtils";
import {
generateQRCode,
getRadialProgressPNG,
streamToBuffer,
} from "@/utils/pdf";
import {moduleLabels} from "@/utils/moduleUtils";
import {generateQRCode, getRadialProgressPNG, streamToBuffer} from "@/utils/pdf";
import moment from "moment-timezone";
const db = getFirestore(app);
@@ -97,21 +84,19 @@ interface SkillsFeedbackResponse extends SkillsFeedbackRequest {
const getSkillsFeedback = async (sections: SkillsFeedbackRequest[]) => {
const backendRequest = await axios.post(
`${process.env.BACKEND_URL}/grading_summary`,
{ sections },
{sections},
{
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
}
},
);
return backendRequest.data?.sections;
};
// perform the request with several retries if needed
const handleSkillsFeedbackRequest = async (
sections: SkillsFeedbackRequest[]
): Promise<SkillsFeedbackResponse[] | null> => {
const handleSkillsFeedbackRequest = async (sections: SkillsFeedbackRequest[]): Promise<SkillsFeedbackResponse[] | null> => {
let i = 0;
try {
const data = await getSkillsFeedback(sections);
@@ -129,15 +114,9 @@ const handleSkillsFeedbackRequest = async (
async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to export
if (req.session.user) {
const { id } = req.query as { id: string };
const {id} = req.query as {id: string};
// fetch stats entries for this particular user with the requested exam session
const docsSnap = await getDocs(
query(
collection(db, "stats"),
where("session", "==", id),
where("user", "==", req.session.user.id)
)
);
const docsSnap = await getDocs(query(collection(db, "stats"), where("session", "==", id)));
if (docsSnap.empty) {
res.status(400).end();
@@ -166,20 +145,17 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const user = docUser.data() as User;
// generate the QR code for the report
const qrcode = await generateQRCode(
(req.headers.origin || "") + req.url
);
const qrcode = await generateQRCode((req.headers.origin || "") + req.url);
if (!qrcode) {
res.status(500).json({ ok: false });
res.status(500).json({ok: false});
return;
}
// stats may contain multiple exams of the same type so we need to aggregate them
const results = (
stats.reduce((accm: ModuleScore[], { module, score }) => {
const fixedModuleStr =
module[0].toUpperCase() + module.substring(1);
stats.reduce((accm: ModuleScore[], {module, score}) => {
const fixedModuleStr = module[0].toUpperCase() + module.substring(1);
if (accm.find((e: ModuleScore) => e.module === fixedModuleStr)) {
return accm.map((e: ModuleScore) => {
if (e.module === fixedModuleStr) {
@@ -205,14 +181,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
];
}, []) as ModuleScore[]
).map((moduleScore) => {
const { score, total } = moduleScore;
const {score, total} = moduleScore;
// with all the scores aggreated we can calculate the band score for each module
const bandScore = calculateBandScore(
score,
total,
moduleScore.code as Module,
user.focus
);
const bandScore = calculateBandScore(score, total, moduleScore.code as Module, user.focus);
return {
...moduleScore,
@@ -224,23 +195,21 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// get the skills feedback from the backend based on the module grade
const skillsFeedback = (await handleSkillsFeedbackRequest(
results.map(({ code, bandScore }) => ({
results.map(({code, bandScore}) => ({
code,
name: moduleLabels[code],
grade: bandScore,
}))
})),
)) as SkillsFeedbackResponse[];
if (!skillsFeedback) {
res.status(500).json({ ok: false });
res.status(500).json({ok: false});
return;
}
// assign the feedback to the results
const finalResults = results.map((result) => {
const feedback = skillsFeedback.find(
(f: SkillsFeedbackResponse) => f.code === result.code
);
const feedback = skillsFeedback.find((f: SkillsFeedbackResponse) => f.code === result.code);
if (feedback) {
return {
@@ -254,14 +223,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
});
// calculate the overall score out of all the aggregated results
const overallScore = results.reduce(
(accm, { score }) => accm + score,
0
);
const overallTotal = results.reduce(
(accm, { total }) => accm + total,
0
);
const overallScore = results.reduce((accm, {score}) => accm + score, 0);
const overallTotal = results.reduce((accm, {total}) => accm + total, 0);
const overallResult = overallScore / overallTotal;
const overallPNG = getRadialProgressPNG("laranja", overallScore, overallTotal);
@@ -278,22 +241,14 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const [stat] = stats;
// generate the performance summary based on the overall result
const performanceSummary = getPerformanceSummary(
stat.module,
overallResult
);
const performanceSummary = getPerformanceSummary(stat.module, overallResult);
// level exams have a different report structure than the skill exams
const getCustomData = () => {
if (stat.module === "level") {
return {
title: "ENGLISH LEVEL TEST RESULT REPORT ",
details: (
<LevelExamDetails
detail={overallDetail}
title="Level as per CEFR Levels"
/>
),
details: <LevelExamDetails detail={overallDetail} title="Level as per CEFR Levels" />,
};
}
@@ -303,13 +258,15 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
};
};
const { title, details } = getCustomData();
const {title, details} = getCustomData();
const demographicInformation = user.demographicInformation as DemographicInformation;
const pdfStream = await ReactPDF.renderToStream(
<TestReport
title={title}
date={moment(stat.date).tz(user.demographicInformation?.timezone || 'UTC').format('ll HH:mm:ss')}
date={moment(stat.date)
.tz(user.demographicInformation?.timezone || "UTC")
.format("ll HH:mm:ss")}
name={user.name}
email={user.email}
id={user.id}
@@ -322,7 +279,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
summaryPNG={overallPNG}
summaryScore={`${(overallResult * 100).toFixed(0)}%`}
passportId={demographicInformation?.passport_id || ""}
/>
/>,
);
// generate the file ref for storage
@@ -347,23 +304,21 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
return;
}
res.status(401).json({ ok: false });
res.status(401).json({ok: false});
return;
} catch (err) {
res.status(500).json({ ok: false });
res.status(500).json({ok: false});
return;
}
}
res.status(401).json({ ok: false });
res.status(401).json({ok: false});
return;
}
async function get(req: NextApiRequest, res: NextApiResponse) {
const { id } = req.query as { id: string };
const docsSnap = await getDocs(
query(collection(db, "stats"), where("session", "==", id))
);
const {id} = req.query as {id: string};
const docsSnap = await getDocs(query(collection(db, "stats"), where("session", "==", id)));
if (docsSnap.empty) {
res.status(404).end();