Initial draft of level test report
This commit is contained in:
184
src/exams/pdf/level.test.report.tsx
Normal file
184
src/exams/pdf/level.test.report.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
/* eslint-disable jsx-a11y/alt-text */
|
||||
import React from "react";
|
||||
import { Document, Page, View, Text, Image } from "@react-pdf/renderer";
|
||||
import { ModuleScore } from "@/interfaces/module.scores";
|
||||
import { styles } from "./styles";
|
||||
|
||||
import { StyleSheet } from "@react-pdf/renderer";
|
||||
|
||||
const customStyles = StyleSheet.create({
|
||||
testDetails: {
|
||||
display: "flex",
|
||||
gap: 4,
|
||||
},
|
||||
testDetailsContainer: {
|
||||
display: "flex",
|
||||
gap: 16,
|
||||
},
|
||||
table: {
|
||||
width: "100%",
|
||||
margin: "10px",
|
||||
},
|
||||
tableRow: {
|
||||
flexDirection: "row",
|
||||
},
|
||||
tableCol50: {
|
||||
width: "50%", // First column width (50%)
|
||||
borderStyle: "solid",
|
||||
borderWidth: 1,
|
||||
borderColor: "#000",
|
||||
padding: 5,
|
||||
},
|
||||
tableCol25: {
|
||||
width: "16.67%", // Remaining four columns each get 1/6 of the total width (50% / 3 = 16.67%)
|
||||
borderStyle: "solid",
|
||||
borderWidth: 1,
|
||||
borderColor: "#000",
|
||||
padding: 5,
|
||||
},
|
||||
tableCol20: {
|
||||
width: "20%", // Width for each of the 5 sub-columns (50% / 5 = 20%)
|
||||
borderStyle: "solid",
|
||||
borderWidth: 1,
|
||||
borderColor: "#000",
|
||||
padding: 5,
|
||||
},
|
||||
tableCellHeader: {
|
||||
backgroundColor: "#d3d3d3",
|
||||
fontWeight: "bold",
|
||||
textAlign: "center",
|
||||
},
|
||||
tableCell: {
|
||||
fontSize: 10,
|
||||
textAlign: "center",
|
||||
},
|
||||
});
|
||||
|
||||
interface Props {
|
||||
date: string;
|
||||
name: string;
|
||||
email: string;
|
||||
id: string;
|
||||
gender?: string;
|
||||
passportId: string;
|
||||
corporateName: string;
|
||||
downloadDate: string;
|
||||
userId: string;
|
||||
uniqueExercises: { name: string; result: string }[];
|
||||
timeSpent: string;
|
||||
score: string;
|
||||
}
|
||||
|
||||
const LevelTestReport = ({
|
||||
date,
|
||||
name,
|
||||
email,
|
||||
id,
|
||||
gender,
|
||||
passportId,
|
||||
corporateName,
|
||||
downloadDate,
|
||||
userId,
|
||||
uniqueExercises,
|
||||
timeSpent,
|
||||
score,
|
||||
}: Props) => {
|
||||
const defaultTextStyle = [styles.textFont, { fontSize: 8 }];
|
||||
return (
|
||||
<Document>
|
||||
<Page style={styles.body}>
|
||||
<Text style={[styles.textFont, styles.textBold, { fontSize: 11 }]}>
|
||||
Corporate Name: {corporateName}
|
||||
</Text>
|
||||
<View style={styles.textMargin}>
|
||||
<Text style={defaultTextStyle}>
|
||||
Report Download date: {downloadDate}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.textFont, styles.textBold, { fontSize: 11 }]}>
|
||||
Test Information: {id}
|
||||
</Text>
|
||||
<View style={styles.textMargin}>
|
||||
<Text style={defaultTextStyle}>Date of Test: {date}</Text>
|
||||
<Text style={defaultTextStyle}>Candidates name: {name}</Text>
|
||||
<Text style={defaultTextStyle}>Email: {email}</Text>
|
||||
<Text style={defaultTextStyle}>National ID: {passportId}</Text>
|
||||
|
||||
<Text style={defaultTextStyle}>Gender: {gender}</Text>
|
||||
<Text style={defaultTextStyle}>Candidate ID: {userId}</Text>
|
||||
</View>
|
||||
|
||||
<View style={customStyles.table}>
|
||||
{/* Header Row */}
|
||||
<View style={customStyles.tableRow}>
|
||||
<View style={customStyles.tableCol50}>
|
||||
<Text style={customStyles.tableCellHeader}>Test sections</Text>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCellHeader}>Time spent</Text>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCellHeader}>Score</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={customStyles.tableRow}>
|
||||
<View style={customStyles.tableCol50}>
|
||||
<View style={customStyles.tableRow}>
|
||||
{uniqueExercises.map((exercise, index) => (
|
||||
<View style={customStyles.tableCol20} key={index}>
|
||||
<Text style={customStyles.tableCell}>Part {index + 1}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}></Text>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}></Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={customStyles.tableRow}>
|
||||
<View style={customStyles.tableCol50}>
|
||||
<View style={customStyles.tableRow}>
|
||||
{uniqueExercises.map((exercise, index) => (
|
||||
<View style={customStyles.tableCol20} key={index}>
|
||||
<Text style={customStyles.tableCell}>{exercise.name}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}></Text>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}></Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={customStyles.tableRow}>
|
||||
<View style={customStyles.tableCol50}>
|
||||
<View style={customStyles.tableRow}>
|
||||
{uniqueExercises.map((exercise, index) => (
|
||||
<View style={customStyles.tableCol20} key={index}>
|
||||
<Text style={customStyles.tableCell}>
|
||||
{exercise.result}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}>{timeSpent}</Text>
|
||||
</View>
|
||||
<View style={customStyles.tableCol25}>
|
||||
<Text style={customStyles.tableCell}>{score}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Page>
|
||||
</Document>
|
||||
);
|
||||
};
|
||||
|
||||
export default LevelTestReport;
|
||||
@@ -1,162 +1,195 @@
|
||||
import {Module} from ".";
|
||||
import {InstructorGender, ShuffleMap} from "./exam";
|
||||
import {PermissionType} from "./permissions";
|
||||
import { Module } from ".";
|
||||
import { InstructorGender, ShuffleMap } from "./exam";
|
||||
import { PermissionType } from "./permissions";
|
||||
|
||||
export type User = StudentUser | TeacherUser | CorporateUser | AgentUser | AdminUser | DeveloperUser | MasterCorporateUser;
|
||||
export type User =
|
||||
| StudentUser
|
||||
| TeacherUser
|
||||
| CorporateUser
|
||||
| AgentUser
|
||||
| AdminUser
|
||||
| DeveloperUser
|
||||
| MasterCorporateUser;
|
||||
export type UserStatus = "active" | "disabled" | "paymentDue";
|
||||
|
||||
export interface BasicUser {
|
||||
email: string;
|
||||
name: string;
|
||||
profilePicture: string;
|
||||
id: string;
|
||||
isFirstLogin: boolean;
|
||||
focus: "academic" | "general";
|
||||
levels: {[key in Module]: number};
|
||||
desiredLevels: {[key in Module]: number};
|
||||
type: Type;
|
||||
bio: string;
|
||||
isVerified: boolean;
|
||||
subscriptionExpirationDate?: null | Date;
|
||||
registrationDate?: Date;
|
||||
status: UserStatus;
|
||||
permissions: PermissionType[];
|
||||
lastLogin?: Date;
|
||||
email: string;
|
||||
name: string;
|
||||
profilePicture: string;
|
||||
id: string;
|
||||
isFirstLogin: boolean;
|
||||
focus: "academic" | "general";
|
||||
levels: { [key in Module]: number };
|
||||
desiredLevels: { [key in Module]: number };
|
||||
type: Type;
|
||||
bio: string;
|
||||
isVerified: boolean;
|
||||
subscriptionExpirationDate?: null | Date;
|
||||
registrationDate?: Date;
|
||||
status: UserStatus;
|
||||
permissions: PermissionType[];
|
||||
lastLogin?: Date;
|
||||
}
|
||||
|
||||
export interface StudentUser extends BasicUser {
|
||||
type: "student";
|
||||
preferredGender?: InstructorGender;
|
||||
demographicInformation?: DemographicInformation;
|
||||
preferredTopics?: string[];
|
||||
type: "student";
|
||||
preferredGender?: InstructorGender;
|
||||
demographicInformation?: DemographicInformation;
|
||||
preferredTopics?: string[];
|
||||
}
|
||||
|
||||
export interface TeacherUser extends BasicUser {
|
||||
type: "teacher";
|
||||
demographicInformation?: DemographicInformation;
|
||||
type: "teacher";
|
||||
demographicInformation?: DemographicInformation;
|
||||
}
|
||||
|
||||
export interface CorporateUser extends BasicUser {
|
||||
type: "corporate";
|
||||
corporateInformation: CorporateInformation;
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
type: "corporate";
|
||||
corporateInformation: CorporateInformation;
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
}
|
||||
|
||||
export interface MasterCorporateUser extends BasicUser {
|
||||
type: "mastercorporate";
|
||||
corporateInformation: CorporateInformation;
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
type: "mastercorporate";
|
||||
corporateInformation: CorporateInformation;
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
}
|
||||
|
||||
export interface AgentUser extends BasicUser {
|
||||
type: "agent";
|
||||
agentInformation: AgentInformation;
|
||||
demographicInformation?: DemographicInformation;
|
||||
type: "agent";
|
||||
agentInformation: AgentInformation;
|
||||
demographicInformation?: DemographicInformation;
|
||||
}
|
||||
|
||||
export interface AdminUser extends BasicUser {
|
||||
type: "admin";
|
||||
demographicInformation?: DemographicInformation;
|
||||
type: "admin";
|
||||
demographicInformation?: DemographicInformation;
|
||||
}
|
||||
|
||||
export interface DeveloperUser extends BasicUser {
|
||||
type: "developer";
|
||||
preferredGender?: InstructorGender;
|
||||
demographicInformation?: DemographicInformation;
|
||||
preferredTopics?: string[];
|
||||
type: "developer";
|
||||
preferredGender?: InstructorGender;
|
||||
demographicInformation?: DemographicInformation;
|
||||
preferredTopics?: string[];
|
||||
}
|
||||
|
||||
export interface CorporateInformation {
|
||||
companyInformation: CompanyInformation;
|
||||
monthlyDuration: number;
|
||||
payment?: {
|
||||
value: number;
|
||||
currency: string;
|
||||
commission: number;
|
||||
};
|
||||
referralAgent?: string;
|
||||
companyInformation: CompanyInformation;
|
||||
monthlyDuration: number;
|
||||
payment?: {
|
||||
value: number;
|
||||
currency: string;
|
||||
commission: number;
|
||||
};
|
||||
referralAgent?: string;
|
||||
}
|
||||
|
||||
export interface AgentInformation {
|
||||
companyName: string;
|
||||
commercialRegistration: string;
|
||||
companyArabName?: string;
|
||||
companyName: string;
|
||||
commercialRegistration: string;
|
||||
companyArabName?: string;
|
||||
}
|
||||
|
||||
export interface CompanyInformation {
|
||||
name: string;
|
||||
userAmount: number;
|
||||
name: string;
|
||||
userAmount: number;
|
||||
}
|
||||
|
||||
export interface DemographicInformation {
|
||||
country: string;
|
||||
phone: string;
|
||||
gender: Gender;
|
||||
employment: EmploymentStatus;
|
||||
passport_id?: string;
|
||||
timezone?: string;
|
||||
country: string;
|
||||
phone: string;
|
||||
gender: Gender;
|
||||
employment: EmploymentStatus;
|
||||
passport_id?: string;
|
||||
timezone?: string;
|
||||
}
|
||||
|
||||
export interface DemographicCorporateInformation {
|
||||
country: string;
|
||||
phone: string;
|
||||
gender: Gender;
|
||||
position: string;
|
||||
timezone?: string;
|
||||
country: string;
|
||||
phone: string;
|
||||
gender: Gender;
|
||||
position: string;
|
||||
timezone?: string;
|
||||
}
|
||||
|
||||
export type Gender = "male" | "female" | "other";
|
||||
export type EmploymentStatus = "employed" | "student" | "self-employed" | "unemployed" | "retired" | "other";
|
||||
export const EMPLOYMENT_STATUS: {status: EmploymentStatus; label: string}[] = [
|
||||
{status: "student", label: "Student"},
|
||||
{status: "employed", label: "Employed"},
|
||||
{status: "unemployed", label: "Unemployed"},
|
||||
{status: "self-employed", label: "Self-employed"},
|
||||
{status: "retired", label: "Retired"},
|
||||
{status: "other", label: "Other"},
|
||||
];
|
||||
export type EmploymentStatus =
|
||||
| "employed"
|
||||
| "student"
|
||||
| "self-employed"
|
||||
| "unemployed"
|
||||
| "retired"
|
||||
| "other";
|
||||
export const EMPLOYMENT_STATUS: { status: EmploymentStatus; label: string }[] =
|
||||
[
|
||||
{ status: "student", label: "Student" },
|
||||
{ status: "employed", label: "Employed" },
|
||||
{ status: "unemployed", label: "Unemployed" },
|
||||
{ status: "self-employed", label: "Self-employed" },
|
||||
{ status: "retired", label: "Retired" },
|
||||
{ status: "other", label: "Other" },
|
||||
];
|
||||
|
||||
export interface Stat {
|
||||
id: string;
|
||||
user: string;
|
||||
exam: string;
|
||||
exercise: string;
|
||||
session: string;
|
||||
date: number;
|
||||
module: Module;
|
||||
solutions: any[];
|
||||
type: string;
|
||||
timeSpent?: number;
|
||||
inactivity?: number;
|
||||
assignment?: string;
|
||||
score: {
|
||||
correct: number;
|
||||
total: number;
|
||||
missing: number;
|
||||
};
|
||||
isDisabled?: boolean;
|
||||
id: string;
|
||||
user: string;
|
||||
exam: string;
|
||||
exercise: string;
|
||||
session: string;
|
||||
date: number;
|
||||
module: Module;
|
||||
solutions: any[];
|
||||
type: string;
|
||||
timeSpent?: number;
|
||||
inactivity?: number;
|
||||
assignment?: string;
|
||||
score: {
|
||||
correct: number;
|
||||
total: number;
|
||||
missing: number;
|
||||
};
|
||||
isDisabled?: boolean;
|
||||
shuffleMaps?: ShuffleMap[];
|
||||
pdf?: {
|
||||
path: string;
|
||||
version: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Group {
|
||||
admin: string;
|
||||
name: string;
|
||||
participants: string[];
|
||||
id: string;
|
||||
disableEditing?: boolean;
|
||||
admin: string;
|
||||
name: string;
|
||||
participants: string[];
|
||||
id: string;
|
||||
disableEditing?: boolean;
|
||||
}
|
||||
|
||||
export interface Code {
|
||||
code: string;
|
||||
creator: string;
|
||||
expiryDate: Date;
|
||||
type: Type;
|
||||
creationDate?: string;
|
||||
userId?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
passport_id?: string;
|
||||
code: string;
|
||||
creator: string;
|
||||
expiryDate: Date;
|
||||
type: Type;
|
||||
creationDate?: string;
|
||||
userId?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
passport_id?: string;
|
||||
}
|
||||
|
||||
export type Type = "student" | "teacher" | "corporate" | "admin" | "developer" | "agent" | "mastercorporate";
|
||||
export const userTypes: Type[] = ["student", "teacher", "corporate", "admin", "developer", "agent", "mastercorporate"];
|
||||
export type Type =
|
||||
| "student"
|
||||
| "teacher"
|
||||
| "corporate"
|
||||
| "admin"
|
||||
| "developer"
|
||||
| "agent"
|
||||
| "mastercorporate";
|
||||
export const userTypes: Type[] = [
|
||||
"student",
|
||||
"teacher",
|
||||
"corporate",
|
||||
"admin",
|
||||
"developer",
|
||||
"agent",
|
||||
"mastercorporate",
|
||||
];
|
||||
|
||||
@@ -1,20 +1,38 @@
|
||||
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 LevelTestReport from "@/exams/pdf/level.test.report";
|
||||
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
|
||||
import {
|
||||
DemographicInformation,
|
||||
Stat,
|
||||
StudentUser,
|
||||
User,
|
||||
} from "@/interfaces/user";
|
||||
import { Module } from "@/interfaces";
|
||||
import { ModuleScore } from "@/interfaces/module.scores";
|
||||
import { SkillExamDetails } from "@/exams/pdf/details/skill.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);
|
||||
@@ -22,332 +40,397 @@ const db = getFirestore(app);
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return get(req, res);
|
||||
if (req.method === "POST") return post(req, res);
|
||||
if (req.method === "GET") return get(req, res);
|
||||
if (req.method === "POST") return post(req, res);
|
||||
}
|
||||
|
||||
const getExamSummary = (score: number) => {
|
||||
if (score > 0.8) {
|
||||
return "Scoring between 81% and 100% on the English exam demonstrates an outstanding level of proficiency in writing, speaking, listening, and reading. Mastery of key concepts is evident across all language domains, showcasing not only a high level of skill but also a dedication to excellence. Continuing to challenge oneself with advanced material in writing, speaking, listening, and reading will further refine the already impressive command of the English language.";
|
||||
}
|
||||
if (score > 0.8) {
|
||||
return "Scoring between 81% and 100% on the English exam demonstrates an outstanding level of proficiency in writing, speaking, listening, and reading. Mastery of key concepts is evident across all language domains, showcasing not only a high level of skill but also a dedication to excellence. Continuing to challenge oneself with advanced material in writing, speaking, listening, and reading will further refine the already impressive command of the English language.";
|
||||
}
|
||||
|
||||
if (score > 0.6) {
|
||||
return "Scoring between 61% and 80% on the English exam, encompassing writing, speaking, listening, and reading, reflects a commendable level of proficiency in each domain. There's evidence of a solid grasp of key concepts, and effective application of skills. Room for refinement and deeper exploration in writing, speaking, listening, and reading remains, presenting an opportunity for further mastery.";
|
||||
}
|
||||
if (score > 0.6) {
|
||||
return "Scoring between 61% and 80% on the English exam, encompassing writing, speaking, listening, and reading, reflects a commendable level of proficiency in each domain. There's evidence of a solid grasp of key concepts, and effective application of skills. Room for refinement and deeper exploration in writing, speaking, listening, and reading remains, presenting an opportunity for further mastery.";
|
||||
}
|
||||
|
||||
if (score > 0.4) {
|
||||
return "Scoring between 41% and 60% on the English exam across writing, speaking, listening, and reading demonstrates a moderate level of understanding in each domain. While there's a commendable grasp of key concepts, refining fundamental skills in writing, speaking, listening, and reading can lead to notable improvement. Consistent effort and targeted focus on weaker areas are recommended.";
|
||||
}
|
||||
if (score > 0.4) {
|
||||
return "Scoring between 41% and 60% on the English exam across writing, speaking, listening, and reading demonstrates a moderate level of understanding in each domain. While there's a commendable grasp of key concepts, refining fundamental skills in writing, speaking, listening, and reading can lead to notable improvement. Consistent effort and targeted focus on weaker areas are recommended.";
|
||||
}
|
||||
|
||||
if (score > 0.2) {
|
||||
return "Scoring between 21% and 40% on the English exam, spanning writing, speaking, listening, and reading, indicates some understanding of key concepts in each domain. However, there's room for improvement in fundamental skills. Strengthening writing, speaking, listening, and reading abilities through consistent effort and focused study will contribute to overall proficiency.";
|
||||
}
|
||||
if (score > 0.2) {
|
||||
return "Scoring between 21% and 40% on the English exam, spanning writing, speaking, listening, and reading, indicates some understanding of key concepts in each domain. However, there's room for improvement in fundamental skills. Strengthening writing, speaking, listening, and reading abilities through consistent effort and focused study will contribute to overall proficiency.";
|
||||
}
|
||||
|
||||
return "This student's performance on the English exam, encompassing writing, speaking, listening, and reading, reflects a significant need for improvement, scoring between 0% and 20%. There's a notable gap in understanding key concepts across all language domains. Strengthening fundamental skills in writing, speaking, listening, and reading is crucial. Developing a consistent study routine and seeking additional support in each area can contribute to substantial progress.";
|
||||
return "This student's performance on the English exam, encompassing writing, speaking, listening, and reading, reflects a significant need for improvement, scoring between 0% and 20%. There's a notable gap in understanding key concepts across all language domains. Strengthening fundamental skills in writing, speaking, listening, and reading is crucial. Developing a consistent study routine and seeking additional support in each area can contribute to substantial progress.";
|
||||
};
|
||||
|
||||
const getLevelSummary = (score: number) => {
|
||||
if (score > 0.8) {
|
||||
return "Scoring between 81% and 100% on the English exam showcases an outstanding level of understanding and proficiency. Your performance reflects a mastery of key concepts, including grammar, vocabulary, and comprehension. You exhibit a high level of skill in applying these elements effectively. Your dedication to excellence is evident, and your consistent, stellar performance is commendable. Continue to challenge yourself with advanced material to further refine your already impressive command of the English language. Your commitment to excellence positions you as a standout student in English studies, and your achievements are a testament to your hard work and capability.";
|
||||
}
|
||||
if (score > 0.8) {
|
||||
return "Scoring between 81% and 100% on the English exam showcases an outstanding level of understanding and proficiency. Your performance reflects a mastery of key concepts, including grammar, vocabulary, and comprehension. You exhibit a high level of skill in applying these elements effectively. Your dedication to excellence is evident, and your consistent, stellar performance is commendable. Continue to challenge yourself with advanced material to further refine your already impressive command of the English language. Your commitment to excellence positions you as a standout student in English studies, and your achievements are a testament to your hard work and capability.";
|
||||
}
|
||||
|
||||
if (score > 0.6) {
|
||||
return "Scoring between 61% and 80% on the English exam reflects a commendable level of understanding and proficiency. You have demonstrated a solid grasp of key concepts, including grammar, vocabulary, and comprehension. There's evidence of effective application of skills, but room for refinement and deeper exploration remains. Consistent effort in honing nuanced aspects of language will contribute to even greater mastery. Continue engaging with challenging material and seeking opportunities for advanced comprehension. With sustained dedication, you have the potential to elevate your performance to an exceptional level and further excel in your English studies.";
|
||||
}
|
||||
if (score > 0.6) {
|
||||
return "Scoring between 61% and 80% on the English exam reflects a commendable level of understanding and proficiency. You have demonstrated a solid grasp of key concepts, including grammar, vocabulary, and comprehension. There's evidence of effective application of skills, but room for refinement and deeper exploration remains. Consistent effort in honing nuanced aspects of language will contribute to even greater mastery. Continue engaging with challenging material and seeking opportunities for advanced comprehension. With sustained dedication, you have the potential to elevate your performance to an exceptional level and further excel in your English studies.";
|
||||
}
|
||||
|
||||
if (score > 0.4) {
|
||||
return "Scoring between 41% and 60% on the English exam reflects a moderate level of understanding. You demonstrate a grasp of some key concepts, but there's room for refinement in areas like grammar, vocabulary, and comprehension. Consistent effort and a strategic focus on weaker areas can lead to notable improvement. Engaging with supplementary resources and seeking feedback will further enhance your skills. With continued dedication, there's a solid foundation to build upon, and achieving a higher level of proficiency is within reach. Keep up the good work and aim for sustained progress in your English studies.";
|
||||
}
|
||||
if (score > 0.4) {
|
||||
return "Scoring between 41% and 60% on the English exam reflects a moderate level of understanding. You demonstrate a grasp of some key concepts, but there's room for refinement in areas like grammar, vocabulary, and comprehension. Consistent effort and a strategic focus on weaker areas can lead to notable improvement. Engaging with supplementary resources and seeking feedback will further enhance your skills. With continued dedication, there's a solid foundation to build upon, and achieving a higher level of proficiency is within reach. Keep up the good work and aim for sustained progress in your English studies.";
|
||||
}
|
||||
|
||||
if (score > 0.2) {
|
||||
return "Scoring between 21% and 40% on the English exam shows some understanding of key concepts, but there's still ample room for improvement. Strengthening foundational skills, such as grammar, vocabulary, and comprehension, is essential. Consistent effort and focused study can help bridge gaps in knowledge and elevate your performance. Consider seeking additional guidance or resources to refine your understanding of the material. With commitment and targeted improvements, you have the potential to make significant strides in your English proficiency.";
|
||||
}
|
||||
if (score > 0.2) {
|
||||
return "Scoring between 21% and 40% on the English exam shows some understanding of key concepts, but there's still ample room for improvement. Strengthening foundational skills, such as grammar, vocabulary, and comprehension, is essential. Consistent effort and focused study can help bridge gaps in knowledge and elevate your performance. Consider seeking additional guidance or resources to refine your understanding of the material. With commitment and targeted improvements, you have the potential to make significant strides in your English proficiency.";
|
||||
}
|
||||
|
||||
return "Your performance on the English exam falls within the 0% to 20% range, indicating a need for improvement. There's room to enhance your grasp of fundamental concepts like grammar, vocabulary, and comprehension. Establishing a consistent study routine and seeking extra support can be beneficial. With dedication and targeted efforts, you have the potential to significantly boost your performance in upcoming assessments.";
|
||||
return "Your performance on the English exam falls within the 0% to 20% range, indicating a need for improvement. There's room to enhance your grasp of fundamental concepts like grammar, vocabulary, and comprehension. Establishing a consistent study routine and seeking extra support can be beneficial. With dedication and targeted efforts, you have the potential to significantly boost your performance in upcoming assessments.";
|
||||
};
|
||||
|
||||
const getPerformanceSummary = (module: Module, score: number) => {
|
||||
if (module === "level") return getLevelSummary(score);
|
||||
return getExamSummary(score);
|
||||
if (module === "level") return getLevelSummary(score);
|
||||
return getExamSummary(score);
|
||||
};
|
||||
interface SkillsFeedbackRequest {
|
||||
code: Module;
|
||||
name: string;
|
||||
grade: number;
|
||||
code: Module;
|
||||
name: string;
|
||||
grade: number;
|
||||
}
|
||||
|
||||
interface SkillsFeedbackResponse extends SkillsFeedbackRequest {
|
||||
evaluation: string;
|
||||
suggestions: string;
|
||||
bullet_points?: string[];
|
||||
evaluation: string;
|
||||
suggestions: string;
|
||||
bullet_points?: string[];
|
||||
}
|
||||
|
||||
const getSkillsFeedback = async (sections: SkillsFeedbackRequest[]) => {
|
||||
const backendRequest = await axios.post(
|
||||
`${process.env.BACKEND_URL}/grading_summary`,
|
||||
{sections},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const backendRequest = await axios.post(
|
||||
`${process.env.BACKEND_URL}/grading_summary`,
|
||||
{ sections },
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return backendRequest.data?.sections;
|
||||
return backendRequest.data?.sections;
|
||||
};
|
||||
|
||||
// perform the request with several retries if needed
|
||||
const handleSkillsFeedbackRequest = async (sections: SkillsFeedbackRequest[]): Promise<SkillsFeedbackResponse[] | null> => {
|
||||
let i = 0;
|
||||
try {
|
||||
const data = await getSkillsFeedback(sections);
|
||||
return data;
|
||||
} catch (err) {
|
||||
if (i < 3) {
|
||||
i++;
|
||||
return handleSkillsFeedbackRequest(sections);
|
||||
}
|
||||
const handleSkillsFeedbackRequest = async (
|
||||
sections: SkillsFeedbackRequest[]
|
||||
): Promise<SkillsFeedbackResponse[] | null> => {
|
||||
let i = 0;
|
||||
try {
|
||||
const data = await getSkillsFeedback(sections);
|
||||
return data;
|
||||
} catch (err) {
|
||||
if (i < 3) {
|
||||
i++;
|
||||
return handleSkillsFeedbackRequest(sections);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
async function getDefaultPDFStream(
|
||||
stats: Stat[],
|
||||
user: User,
|
||||
qrcodeUrl: string
|
||||
) {
|
||||
const [stat] = stats;
|
||||
// generate the QR code for the report
|
||||
const qrcode = await generateQRCode(qrcodeUrl);
|
||||
|
||||
if (!qrcode) {
|
||||
throw new Error("Failed to generate QR code");
|
||||
}
|
||||
|
||||
// stats may contain multiple exams of the same type so we need to aggregate them
|
||||
const results = stats
|
||||
.reduce((accm: ModuleScore[], stat: Stat) => {
|
||||
const { module, score } = stat;
|
||||
|
||||
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) {
|
||||
return {
|
||||
...e,
|
||||
score: e.score + score.correct,
|
||||
total: e.total + score.total,
|
||||
};
|
||||
}
|
||||
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
const value = {
|
||||
module: fixedModuleStr,
|
||||
score: score.correct,
|
||||
total: score.total,
|
||||
code: module,
|
||||
} as ModuleScore;
|
||||
|
||||
return [...accm, value];
|
||||
}, [])
|
||||
.map((moduleScore: 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
|
||||
);
|
||||
|
||||
return {
|
||||
...moduleScore,
|
||||
// generate the closest radial progress png for the score
|
||||
png: getRadialProgressPNG("azul", score, total),
|
||||
bandScore,
|
||||
};
|
||||
});
|
||||
|
||||
// get the skills feedback from the backend based on the module grade
|
||||
const skillsFeedback = (await handleSkillsFeedbackRequest(
|
||||
results.map(({ code, bandScore }) => ({
|
||||
code,
|
||||
name: moduleLabels[code],
|
||||
grade: bandScore,
|
||||
}))
|
||||
)) as SkillsFeedbackResponse[];
|
||||
|
||||
if (!skillsFeedback) {
|
||||
throw new Error("Failed to get skills feedback");
|
||||
}
|
||||
|
||||
// assign the feedback to the results
|
||||
const finalResults = results.map((result) => {
|
||||
const feedback = skillsFeedback.find(
|
||||
(f: SkillsFeedbackResponse) => f.code === result.code
|
||||
);
|
||||
|
||||
if (feedback) {
|
||||
return {
|
||||
...result,
|
||||
evaluation: feedback?.evaluation,
|
||||
suggestions: feedback?.suggestions,
|
||||
bullet_points: feedback?.bullet_points,
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
// 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 overallResult = overallScore / overallTotal;
|
||||
|
||||
const overallPNG = getRadialProgressPNG(
|
||||
"laranja",
|
||||
overallScore,
|
||||
overallTotal
|
||||
);
|
||||
|
||||
// generate the overall detail report
|
||||
const overallDetail = {
|
||||
module: "Overall",
|
||||
score: overallScore,
|
||||
total: overallTotal,
|
||||
png: overallPNG,
|
||||
} as ModuleScore;
|
||||
const testDetails = [overallDetail, ...finalResults];
|
||||
|
||||
// generate the performance summary based on the overall result
|
||||
const performanceSummary = getPerformanceSummary(stat.module, overallResult);
|
||||
|
||||
const title = "ENGLISH SKILLS TEST RESULT REPORT";
|
||||
const details = <SkillExamDetails testDetails={testDetails} />;
|
||||
|
||||
const demographicInformation =
|
||||
user.demographicInformation as DemographicInformation;
|
||||
return ReactPDF.renderToStream(
|
||||
<TestReport
|
||||
title={title}
|
||||
date={moment(stat.date)
|
||||
.tz(user.demographicInformation?.timezone || "UTC")
|
||||
.format("ll HH:mm:ss")}
|
||||
name={user.name}
|
||||
email={user.email}
|
||||
id={user.id}
|
||||
gender={demographicInformation?.gender}
|
||||
summary={performanceSummary}
|
||||
testDetails={testDetails}
|
||||
renderDetails={details}
|
||||
logo={"public/logo_title.png"}
|
||||
qrcode={qrcode}
|
||||
summaryPNG={overallPNG}
|
||||
summaryScore={`${Math.floor(overallResult * 100)}%`}
|
||||
passportId={demographicInformation?.passport_id || ""}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function getPdfUrl(pdfStream: any, docsSnap: any) {
|
||||
// generate the file ref for storage
|
||||
const fileName = `${Date.now().toString()}.pdf`;
|
||||
const refName = `exam_report/${fileName}`;
|
||||
const fileRef = ref(storage, refName);
|
||||
|
||||
// upload the pdf to storage
|
||||
const pdfBuffer = await streamToBuffer(pdfStream);
|
||||
const snapshot = await uploadBytes(fileRef, pdfBuffer, {
|
||||
contentType: "application/pdf",
|
||||
});
|
||||
|
||||
// update the stats entries with the pdf url to prevent duplication
|
||||
docsSnap.docs.forEach(async (doc: any) => {
|
||||
await updateDoc(doc.ref, {
|
||||
pdf: {
|
||||
path: refName,
|
||||
version: process.env.PDF_VERSION,
|
||||
},
|
||||
});
|
||||
});
|
||||
return getDownloadURL(fileRef);
|
||||
}
|
||||
|
||||
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};
|
||||
// fetch stats entries for this particular user with the requested exam session
|
||||
const docsSnap = await getDocs(query(collection(db, "stats"), where("session", "==", id)));
|
||||
// verify if it's a logged user that is trying to export
|
||||
if (req.session.user) {
|
||||
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))
|
||||
);
|
||||
|
||||
if (docsSnap.empty) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
if (docsSnap.empty) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = docsSnap.docs.map((d) => d.data());
|
||||
// verify if the stats already have a pdf generated
|
||||
const hasPDF = stats.find((s) => s.pdf?.path && s.pdf?.version === process.env.PDF_VERSION);
|
||||
// find the user that generated the stats
|
||||
const statIndex = stats.findIndex((s) => s.user);
|
||||
const stats = docsSnap.docs.map((d) => d.data()) as Stat[];
|
||||
// verify if the stats already have a pdf generated
|
||||
const hasPDF = stats.find(
|
||||
(s) => s.pdf?.path && s.pdf?.version === process.env.PDF_VERSION
|
||||
);
|
||||
// find the user that generated the stats
|
||||
const statIndex = stats.findIndex((s) => s.user);
|
||||
|
||||
if(statIndex === -1) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
const userId = stats[statIndex].user;
|
||||
if (statIndex === -1) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const userId = stats[statIndex].user;
|
||||
|
||||
// if (hasPDF) {
|
||||
// // if it does, return the pdf url
|
||||
// const fileRef = ref(storage, hasPDF.pdf!.path);
|
||||
// const url = await getDownloadURL(fileRef);
|
||||
|
||||
if (hasPDF) {
|
||||
// if it does, return the pdf url
|
||||
const fileRef = ref(storage, hasPDF.pdf.path);
|
||||
const url = await getDownloadURL(fileRef);
|
||||
// res.status(200).end(url);
|
||||
// return;
|
||||
// }
|
||||
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// generate the pdf report
|
||||
const docUser = await getDoc(doc(db, "users", userId));
|
||||
|
||||
try {
|
||||
// generate the pdf report
|
||||
const docUser = await getDoc(doc(db, "users", userId));
|
||||
if (docUser.exists()) {
|
||||
// we'll need the user in order to get the user data (name, email, focus, etc);
|
||||
|
||||
if (docUser.exists()) {
|
||||
// we'll need the user in order to get the user data (name, email, focus, etc);
|
||||
const user = docUser.data() as User;
|
||||
const [stat] = stats;
|
||||
|
||||
// generate the QR code for the report
|
||||
const qrcode = await generateQRCode((req.headers.origin || "") + req.url);
|
||||
if (stat.module === "level") {
|
||||
const user = docUser.data() as StudentUser;
|
||||
|
||||
if (!qrcode) {
|
||||
res.status(500).json({ok: false});
|
||||
return;
|
||||
}
|
||||
const uniqueExercises = stats.map((s) => ({
|
||||
name: "Gramar & Vocabulary",
|
||||
result: `${s.score.correct}/${s.score.total}`,
|
||||
}));
|
||||
const dates = stats.map((s) => moment(s.date));
|
||||
const timeSpent = `${
|
||||
stats.reduce((accm, s: Stat) => accm + (s.timeSpent || 0), 0) / 60
|
||||
} minutes`;
|
||||
const score = stats.reduce((accm, s) => accm + s.score.correct, 0);
|
||||
|
||||
// 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);
|
||||
if (accm.find((e: ModuleScore) => e.module === fixedModuleStr)) {
|
||||
return accm.map((e: ModuleScore) => {
|
||||
if (e.module === fixedModuleStr) {
|
||||
return {
|
||||
...e,
|
||||
score: e.score + score.correct,
|
||||
total: e.total + score.total,
|
||||
};
|
||||
}
|
||||
const pdfStream = await ReactPDF.renderToStream(
|
||||
<LevelTestReport
|
||||
date={moment.max(dates).format("DD/MM/YYYY")}
|
||||
name={user.name}
|
||||
email={user.email}
|
||||
id={stat.exam}
|
||||
gender={user.demographicInformation?.gender || ""}
|
||||
passportId={user.demographicInformation?.passport_id || ""}
|
||||
corporateName="TODO"
|
||||
downloadDate={moment().format("DD/MM/YYYY")}
|
||||
userId={userId}
|
||||
uniqueExercises={uniqueExercises}
|
||||
timeSpent={timeSpent}
|
||||
score={score.toString()}
|
||||
/>
|
||||
);
|
||||
|
||||
return e;
|
||||
});
|
||||
}
|
||||
const url = await getPdfUrl(pdfStream, docsSnap);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
|
||||
return [
|
||||
...accm,
|
||||
{
|
||||
module: fixedModuleStr,
|
||||
score: score.correct,
|
||||
total: score.total,
|
||||
code: module,
|
||||
},
|
||||
];
|
||||
}, []) as ModuleScore[]
|
||||
).map((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);
|
||||
return;
|
||||
}
|
||||
const user = docUser.data() as User;
|
||||
|
||||
return {
|
||||
...moduleScore,
|
||||
// generate the closest radial progress png for the score
|
||||
png: getRadialProgressPNG("azul", score, total),
|
||||
bandScore,
|
||||
};
|
||||
});
|
||||
try {
|
||||
const pdfStream = await getDefaultPDFStream(
|
||||
stats,
|
||||
user,
|
||||
`${req.headers.origin || ""}${req.url}`
|
||||
);
|
||||
|
||||
// get the skills feedback from the backend based on the module grade
|
||||
const skillsFeedback = (await handleSkillsFeedbackRequest(
|
||||
results.map(({code, bandScore}) => ({
|
||||
code,
|
||||
name: moduleLabels[code],
|
||||
grade: bandScore,
|
||||
})),
|
||||
)) as SkillsFeedbackResponse[];
|
||||
const url = await getPdfUrl(pdfStream, docsSnap);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!skillsFeedback) {
|
||||
res.status(500).json({ok: false});
|
||||
return;
|
||||
}
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
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);
|
||||
|
||||
if (feedback) {
|
||||
return {
|
||||
...result,
|
||||
evaluation: feedback?.evaluation,
|
||||
suggestions: feedback?.suggestions,
|
||||
bullet_points: feedback?.bullet_points,
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
// 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 overallResult = overallScore / overallTotal;
|
||||
|
||||
const overallPNG = getRadialProgressPNG("laranja", overallScore, overallTotal);
|
||||
|
||||
// generate the overall detail report
|
||||
const overallDetail = {
|
||||
module: "Overall",
|
||||
score: overallScore,
|
||||
total: overallTotal,
|
||||
png: overallPNG,
|
||||
} as ModuleScore;
|
||||
const testDetails = [overallDetail, ...finalResults];
|
||||
|
||||
const [stat] = stats;
|
||||
|
||||
// generate the performance summary based on the overall result
|
||||
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" />,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: "ENGLISH SKILLS TEST RESULT REPORT",
|
||||
details: <SkillExamDetails testDetails={testDetails} />,
|
||||
};
|
||||
};
|
||||
|
||||
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")}
|
||||
name={user.name}
|
||||
email={user.email}
|
||||
id={userId}
|
||||
gender={demographicInformation?.gender}
|
||||
summary={performanceSummary}
|
||||
testDetails={testDetails}
|
||||
renderDetails={details}
|
||||
logo={"public/logo_title.png"}
|
||||
qrcode={qrcode}
|
||||
summaryPNG={overallPNG}
|
||||
summaryScore={`${Math.floor(overallResult * 100)}%`}
|
||||
passportId={demographicInformation?.passport_id || ""}
|
||||
/>,
|
||||
);
|
||||
|
||||
// generate the file ref for storage
|
||||
const fileName = `${Date.now().toString()}.pdf`;
|
||||
const refName = `exam_report/${fileName}`;
|
||||
const fileRef = ref(storage, refName);
|
||||
|
||||
// upload the pdf to storage
|
||||
const pdfBuffer = await streamToBuffer(pdfStream);
|
||||
const snapshot = await uploadBytes(fileRef, pdfBuffer, {
|
||||
contentType: "application/pdf",
|
||||
});
|
||||
|
||||
// update the stats entries with the pdf url to prevent duplication
|
||||
docsSnap.docs.forEach(async (doc) => {
|
||||
await updateDoc(doc.ref, {
|
||||
pdf: {
|
||||
path: refName,
|
||||
version: process.env.PDF_VERSION,
|
||||
},
|
||||
});
|
||||
});
|
||||
const url = await getDownloadURL(fileRef);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
} catch (err) {
|
||||
res.status(500).json({ok: false});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
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();
|
||||
return;
|
||||
}
|
||||
if (docsSnap.empty) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = docsSnap.docs.map((d) => d.data());
|
||||
const stats = docsSnap.docs.map((d) => d.data());
|
||||
|
||||
const hasPDF = stats.find((s) => s.pdf?.path);
|
||||
const hasPDF = stats.find((s) => s.pdf?.path);
|
||||
|
||||
if (hasPDF) {
|
||||
const fileRef = ref(storage, hasPDF.pdf.path);
|
||||
const url = await getDownloadURL(fileRef);
|
||||
return res.redirect(url);
|
||||
}
|
||||
if (hasPDF) {
|
||||
const fileRef = ref(storage, hasPDF.pdf.path);
|
||||
const url = await getDownloadURL(fileRef);
|
||||
return res.redirect(url);
|
||||
}
|
||||
|
||||
res.status(500).end();
|
||||
res.status(500).end();
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ export default function History({user}: {user: User}) {
|
||||
const {assignments} = useAssignments({});
|
||||
|
||||
const {users} = useUsers();
|
||||
const {stats, isLoading: isStatsLoading} = useStats(statsUserId);
|
||||
const {stats, isLoading: isStatsLoading} = useStats(statsUserId || user.id);
|
||||
const {groups: allGroups} = useGroups({});
|
||||
|
||||
const groups = allGroups.filter((x) => x.admin === user.id);
|
||||
|
||||
Reference in New Issue
Block a user