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>
{renderSearch()}
<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
</Button>
</div>

View File

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