Solved a problem with the download of the excel

This commit is contained in:
Tiago Ribeiro
2024-09-09 08:19:32 +01:00
parent 6d1e8a9788
commit 192132559b
2 changed files with 198 additions and 223 deletions

View File

@@ -343,7 +343,7 @@ const MasterStatistical = (props: Props) => {
</div> </div>
{renderSearch()} {renderSearch()}
<div className="flex flex-col gap-3 justify-end"> <div className="flex flex-col gap-3 justify-end">
<Button className="max-w-[200px] h-[70px]" variant="outline" onClick={triggerDownload}> <Button className="max-w-[200px] h-[70px]" variant="outline" isLoading={downloading} onClick={triggerDownload}>
Download Download
</Button> </Button>
</div> </div>

View File

@@ -1,19 +1,19 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type {NextApiRequest, NextApiResponse} from "next";
import { storage } from "@/firebase"; import {storage} from "@/firebase";
import { withIronSessionApiRoute } from "iron-session/next"; import {withIronSessionApiRoute} from "iron-session/next";
import { sessionOptions } from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage"; import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
import { AssignmentWithCorporateId } from "@/interfaces/results"; import {AssignmentWithCorporateId} from "@/interfaces/results";
import moment from "moment-timezone"; import moment from "moment-timezone";
import ExcelJS from "exceljs"; import ExcelJS from "exceljs";
import { getSpecificUsers } from "@/utils/users.be"; import {getSpecificUsers} from "@/utils/users.be";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import { getAssignmentsForCorporates } from "@/utils/assignments.be"; import {getAssignmentsForCorporates} from "@/utils/assignments.be";
import { search } from "@/utils/search"; import {search} from "@/utils/search";
import { getGradingSystem } from "@/utils/grading.be"; import {getGradingSystem} from "@/utils/grading.be";
import { User } from "@/interfaces/user"; import {User} from "@/interfaces/user";
import { calculateBandScore, getGradingLabel } from "@/utils/score"; import {calculateBandScore, getGradingLabel} from "@/utils/score";
import { Module } from "@/interfaces"; import {Module} from "@/interfaces";
export default withIronSessionApiRoute(handler, sessionOptions); export default withIronSessionApiRoute(handler, sessionOptions);
@@ -45,10 +45,8 @@ const searchFilters = [["email"], ["user"], ["userId"]];
async function post(req: NextApiRequest, res: NextApiResponse) { async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to export // verify if it's a logged user that is trying to export
if (req.session.user) { if (req.session.user) {
if ( if (!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])) {
!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"]) return res.status(403).json({error: "Unauthorized"});
) {
return res.status(403).json({ error: "Unauthorized" });
} }
const { const {
ids, ids,
@@ -65,15 +63,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
}; };
const startDateParsed = startDate ? new Date(startDate) : undefined; const startDateParsed = startDate ? new Date(startDate) : undefined;
const endDateParsed = endDate ? new Date(endDate) : undefined; const endDateParsed = endDate ? new Date(endDate) : undefined;
const assignments = await getAssignmentsForCorporates( const assignments = await getAssignmentsForCorporates(ids, startDateParsed, endDateParsed);
ids,
startDateParsed,
endDateParsed
);
const assignmentUsers = [ const assignmentUsers = [...new Set(assignments.flatMap((a) => a.assignees))];
...new Set(assignments.flatMap((a) => a.assignees)),
];
const assigners = [...new Set(assignments.map((a) => a.assigner))]; const assigners = [...new Set(assignments.map((a) => a.assigner))];
const users = await getSpecificUsers(assignmentUsers); const users = await getSpecificUsers(assignmentUsers);
const assignerUsers = await getSpecificUsers(assigners); const assignerUsers = await getSpecificUsers(assigners);
@@ -82,28 +74,21 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
assignerUsers.map(async (user: User) => { assignerUsers.map(async (user: User) => {
const data = await getGradingSystem(user); const data = await getGradingSystem(user);
// in this context I need to override as I'll have to match to the assigner // in this context I need to override as I'll have to match to the assigner
return { ...data, user: user.id }; return {...data, user: user.id};
}) }),
); );
const getGradingSystemHelper = ( const getGradingSystemHelper = (
exams: { id: string; module: Module; assignee: string }[], exams: {id: string; module: Module; assignee: string}[],
assigner: string, assigner: string,
user: User, user: User,
correct: number, correct: number,
total: number total: number,
) => { ) => {
if (exams.some((e) => e.module === "level")) { if (exams.some((e) => e.module === "level")) {
const gradingSystem = assignerUsersGradingSystems.find( const gradingSystem = assignerUsersGradingSystems.find((gs) => gs.user === assigner);
(gs) => gs.user === assigner
);
if (gradingSystem) { if (gradingSystem) {
const bandScore = calculateBandScore( const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
correct,
total,
"level",
user.focus
);
return { return {
label: getGradingLabel(bandScore, gradingSystem?.steps || []), label: getGradingLabel(bandScore, gradingSystem?.steps || []),
score: bandScore, score: bandScore,
@@ -111,25 +96,18 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
} }
} }
return { score: -1, label: "N/A" }; return {score: -1, label: "N/A"};
}; };
const tableResults = assignments const tableResults = assignments
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => { .reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
const userResults = a.assignees.map((assignee) => { const userResults = a.assignees.map((assignee) => {
const userStats = const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
a.results.find((r) => r.user === assignee)?.stats || [];
const userData = users.find((u) => u.id === assignee); const userData = users.find((u) => u.id === assignee);
const corporateUser = users.find((u) => u.id === a.assigner); const corporateUser = users.find((u) => u.id === a.assigner);
const correct = userStats.reduce((n, e) => n + e.score.correct, 0); const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
const total = userStats.reduce((n, e) => n + e.score.total, 0); const total = userStats.reduce((n, e) => n + e.score.total, 0);
const { label: level, score } = getGradingSystemHelper( const {label: level, score} = getGradingSystemHelper(a.exams, a.assigner, userData!, correct, total);
a.exams,
a.assigner,
userData!,
correct,
total
);
console.log("Level", level); console.log("Level", level);
const commonData = { const commonData = {
@@ -223,9 +201,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
})), })),
]; ];
const filteredSearch = searchText const filteredSearch = searchText ? search(searchText, searchFilters, tableResults) : tableResults;
? search(searchText, searchFilters, tableResults)
: tableResults;
worksheet.addRow(headers.map((h) => h.label)); worksheet.addRow(headers.map((h) => h.label));
(filteredSearch as TableData[]).forEach((entry) => { (filteredSearch as TableData[]).forEach((entry) => {
@@ -241,8 +217,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const fileRef = ref(storage, refName); const fileRef = ref(storage, refName);
// upload the pdf to storage // upload the pdf to storage
await uploadBytes(fileRef, buffer, { await uploadBytes(fileRef, buffer, {
contentType: contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}); });
const url = await getDownloadURL(fileRef); const url = await getDownloadURL(fileRef);
@@ -250,5 +225,5 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
return; return;
} }
return res.status(401).json({ error: "Unauthorized" }); return res.status(401).json({error: "Unauthorized"});
} }