Refactored pages/api/assignments to mongodb

This commit is contained in:
Carlos Mesquita
2024-09-07 15:13:41 +01:00
parent e8b7c5ff80
commit 6f7ef1abef
14 changed files with 820 additions and 462 deletions

View File

@@ -1,16 +1,7 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app, storage } from "@/firebase";
import {
getFirestore,
doc,
getDoc,
updateDoc,
getDocs,
query,
collection,
where,
documentId,
} from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
@@ -29,6 +20,7 @@ interface GroupScoreSummaryHelper {
}
interface AssignmentData {
_id: ObjectId;
assigner: string;
assignees: string[];
results: any;
@@ -41,7 +33,7 @@ interface AssignmentData {
name: string;
}
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -266,7 +258,7 @@ function commonExcel({
}),
`${Math.ceil(
data.stats.reduce((acc: number, curr: any) => acc + curr.timeSpent, 0) /
60
60
)} minutes`,
data.lastDate.format("DD/MM/YYYY HH:mm"),
data.correct,
@@ -392,9 +384,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
if (req.session.user) {
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const data = docSnap.data() as AssignmentData;
if (!data) {
const assignment = await db.collection("assignments").findOne<AssignmentData>({ _id: new ObjectId(id) });
if (!assignment) {
res.status(400).end();
return;
}
@@ -411,19 +402,16 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// return;
// }
const docsSnap = await getDocs(
query(collection(db, "users"), where(documentId(), "in", data.assignees))
);
const users = docsSnap.docs.map((d) => ({
...d.data(),
id: d.id,
})) as User[];
const objectIds = assignment.assignees.map(id => new ObjectId(id));
const docUser = await getDoc(doc(db, "users", data.assigner));
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 users = await db.collection("users").find({
_id: { $in: objectIds }
}).toArray() as User[] | null;
const user = await db.collection("users").findOne<User>({ _id: new ObjectId(assignment.assigner) });
// we'll need the user in order to get the user data (name, email, focus, etc);
if (user && users) {
// generate the file ref for storage
const fileName = `${Date.now().toString()}.xlsx`;
const refName = `assignment_report/${fileName}`;
@@ -433,11 +421,11 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
switch (user.type) {
case "teacher":
case "corporate":
return corporateAssignment(user as CorporateUser, data, users);
return corporateAssignment(user as CorporateUser, assignment, users);
case "mastercorporate":
return mastercorporateAssignment(
user as MasterCorporateUser,
data,
assignment,
users
);
default:
@@ -447,18 +435,24 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const buffer = await getExcelFn();
// upload the pdf to storage
const snapshot = await uploadBytes(fileRef, buffer, {
await uploadBytes(fileRef, buffer, {
contentType:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
// update the stats entries with the pdf url to prevent duplication
await updateDoc(docSnap.ref, {
excel: {
path: refName,
version: process.env.EXCEL_VERSION,
},
});
await db.collection("assignments").updateOne(
{ _id: assignment._id },
{
$set: {
excel: {
path: refName,
version: process.env.EXCEL_VERSION,
}
}
}
);
const url = await getDownloadURL(fileRef);
res.status(200).end(url);

View File

@@ -1,20 +1,21 @@
import type {NextApiRequest, NextApiResponse} from "next";
import {app, storage} from "@/firebase";
import {getFirestore, doc, getDoc, updateDoc, getDocs, query, collection, where, documentId} 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 client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import ReactPDF from "@react-pdf/renderer";
import GroupTestReport from "@/exams/pdf/group.test.report";
import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
import {Stat, CorporateUser} from "@/interfaces/user";
import {User, DemographicInformation} from "@/interfaces/user";
import {Module} from "@/interfaces";
import {ModuleScore, StudentData} from "@/interfaces/module.scores";
import {SkillExamDetails} from "@/exams/pdf/details/skill.exam";
import {LevelExamDetails} from "@/exams/pdf/details/level.exam";
import {calculateBandScore, getLevelScore} from "@/utils/score";
import {generateQRCode, getRadialProgressPNG, streamToBuffer} from "@/utils/pdf";
import {Group} from "@/interfaces/user";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { Stat, CorporateUser } from "@/interfaces/user";
import { User, DemographicInformation } from "@/interfaces/user";
import { Module } from "@/interfaces";
import { ModuleScore, StudentData } from "@/interfaces/module.scores";
import { SkillExamDetails } from "@/exams/pdf/details/skill.exam";
import { LevelExamDetails } from "@/exams/pdf/details/level.exam";
import { calculateBandScore, getLevelScore } from "@/utils/score";
import { generateQRCode, getRadialProgressPNG, streamToBuffer } from "@/utils/pdf";
import { Group } from "@/interfaces/user";
import moment from "moment-timezone";
interface GroupScoreSummaryHelper {
@@ -22,7 +23,7 @@ interface GroupScoreSummaryHelper {
label: string;
sessions: string[];
}
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -78,14 +79,14 @@ const getPerformanceSummary = (module: Module, score: number) => {
const getScoreAndTotal = (stats: Stat[]) => {
return stats.reduce(
(acc, {score}) => {
(acc, { score }) => {
return {
...acc,
correct: acc.correct + score.correct,
total: acc.total + score.total,
};
},
{correct: 0, total: 0},
{ correct: 0, total: 0 },
);
};
@@ -97,20 +98,21 @@ const getLevelScoreForUserExams = (bandScore: number) => {
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 };
const docSnap = await getDoc(doc(db, "assignments", id));
const data = docSnap.data() as {
const data = await db.collection("assignments").findOne({ _id: new ObjectId(id) }) as {
_id: ObjectId;
assigner: string;
assignees: string[];
results: any;
exams: {module: Module}[];
exams: { module: Module }[];
startDate: string;
pdf: {
path: string,
version: string,
},
};
} | null;
if (!data) {
res.status(400).end();
return;
@@ -125,16 +127,15 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
}
try {
const docUser = await getDoc(doc(db, "users", req.session.user.id));
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 user = await db.collection("users").findOne<User>({ _id: new ObjectId(req.session.user.id) });
// we'll need the user in order to get the user data (name, email, focus, etc);
if (user) {
// generate the QR code for the report
const qrcode = await generateQRCode((req.headers.origin || "") + req.url);
if (!qrcode) {
res.status(500).json({ok: false});
res.status(500).json({ ok: false });
return;
}
@@ -143,17 +144,15 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
return [...accm, ...stats];
}, []) as Stat[];
const docsSnap = await getDocs(query(collection(db, "users"), where(documentId(), "in", data.assignees)));
const users = docsSnap.docs.map((d) => ({
...d.data(),
id: d.id,
})) as User[];
const users = await db.collection("users").find<User>({
_id: { $in: data.assignees.map(id => new ObjectId(id)) }
}).toArray();
const flattenResultsWithGrade = flattenResults.map((e) => {
const focus = users.find((u) => u.id === e.user)?.focus || "academic";
const bandScore = calculateBandScore(e.score.correct, e.score.total, e.module, focus);
return {...e, bandScore};
return { ...e, bandScore };
});
// in order to make sure we are using unique modules, generate the set based on them
@@ -162,7 +161,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const moduleResults = flattenResultsWithGrade.filter((e) => e.module === module);
const baseBandScore = moduleResults.reduce((accm, curr) => accm + curr.bandScore, 0) / moduleResults.length;
const bandScore = isNaN(baseBandScore) ? 0 : baseBandScore;
const {correct, total} = getScoreAndTotal(moduleResults);
const { correct, total } = getScoreAndTotal(moduleResults);
const png = getRadialProgressPNG("azul", correct, total);
return {
@@ -175,7 +174,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
};
}) as ModuleScore[];
const {correct: overallCorrect, total: overallTotal} = getScoreAndTotal(flattenResults);
const { correct: overallCorrect, total: overallTotal } = getScoreAndTotal(flattenResults);
const baseOverallResult = overallCorrect / overallTotal;
const overallResult = isNaN(baseOverallResult) ? 0 : baseOverallResult;
@@ -216,7 +215,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
};
};
const {title, details} = getCustomData();
const { title, details } = getCustomData();
const numberOfStudents = data.assignees.length;
@@ -228,13 +227,13 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
exams.length === 0
? "N/A"
: new Date(exams[0].date).toLocaleDateString(undefined, {
year: "numeric",
month: "numeric",
day: "numeric",
});
year: "numeric",
month: "numeric",
day: "numeric",
});
const bandScore = exams.length === 0 ? 0 : exams.reduce((accm, curr) => accm + curr.bandScore, 0) / exams.length;
const {correct, total} = getScoreAndTotal(exams);
const { correct, total } = getScoreAndTotal(exams);
const result = exams.length === 0 ? "N/A" : `${correct}/${total}`;
@@ -258,7 +257,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const getGroupScoreSummary = () => {
const resultHelper = studentsData.reduce((accm: GroupScoreSummaryHelper[], curr) => {
const {bandScore, id} = curr;
const { bandScore, id } = curr;
const flooredScore = Math.floor(bandScore);
@@ -286,7 +285,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
];
}, []) as GroupScoreSummaryHelper[];
const result = resultHelper.map(({score, label, sessions}) => {
const result = resultHelper.map(({ score, label, sessions }) => {
const finalLabel = showLevel ? getLevelScore(score[0])[1] : label;
return {
label: finalLabel,
@@ -300,36 +299,20 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const getInstitution = async () => {
try {
// due to database inconsistencies, I'll be overprotective here
const assignerUserSnap = await getDoc(doc(db, "users", data.assigner));
if (assignerUserSnap.exists()) {
// we'll need the user in order to get the user data (name, email, focus, etc);
const assignerUser = assignerUserSnap.data() as User;
const assignerUser = await db.collection("users").findOne<User>({ _id: new ObjectId(data.assigner) });
// we'll need the user in order to get the user data (name, email, focus, etc);
if (assignerUser) {
if (assignerUser.type === "teacher") {
// also search for groups where this user belongs
const queryGroups = query(collection(db, "groups"), where("participants", "array-contains", assignerUser.id));
const groupSnapshot = await getDocs(queryGroups);
const groups = groupSnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as Group[];
const groups = await db.collection("groups")
.find<Group>({ participants: assignerUser.id })
.toArray();
if (groups.length > 0) {
const adminQuery = query(
collection(db, "users"),
where(
documentId(),
"in",
groups.map((g) => g.admin),
),
);
const adminUsersSnap = await getDocs(adminQuery);
const admins = adminUsersSnap.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as CorporateUser[];
const admins = await db.collection("users")
.find<CorporateUser>({ _id: { $in: groups.map(g => g.admin).map(id => new ObjectId(id))} })
.toArray();
const adminData = admins.find((a) => a.corporateInformation?.companyInformation?.name);
if (adminData) {
@@ -388,39 +371,44 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
});
// update the stats entries with the pdf url to prevent duplication
await updateDoc(docSnap.ref, {
pdf: {
path: refName,
version: process.env.PDF_VERSION,
},
});
await db.collection("assignments").updateOne(
{ _id: new ObjectId(data._id) },
{
$set: {
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});
res.status(401).json({ ok: false });
return;
} catch (err) {
console.error(err);
res.status(500).json({ok: false});
res.status(500).json({ ok: false });
return;
}
}
}
async function get(req: NextApiRequest, res: NextApiResponse) {
if (req.session.user) {
const {id} = req.query as {id: string};
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const data = docSnap.data();
const data = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
if (!data) {
res.status(400).end();
return;
}
if (data.assigner !== req.session.user.id) {
res.status(401).json({ok: false});
res.status(401).json({ ok: false });
return;
}
@@ -434,6 +422,6 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
return;
}
res.status(401).json({ok: false});
res.status(401).json({ ok: false });
return;
}

View File

@@ -1,10 +1,13 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -12,14 +15,17 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to archive
if (req.session.user) {
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const docSnap = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
if (!docSnap.exists()) {
if (!docSnap) {
res.status(404).json({ ok: false });
return;
}
await setDoc(docSnap.ref, { archived: true }, { merge: true });
await db.collection("assignments").updateOne(
{ _id: new ObjectId(docSnap._id) },
{ $set: { archived: true } }
);
res.status(200).json({ ok: true });
return;
}

View File

@@ -1,12 +1,12 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs, query, where, setDoc, doc, getDoc, deleteDoc} from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -26,15 +26,19 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
async function GET(req: NextApiRequest, res: NextApiResponse) {
const {id} = req.query;
const snapshot = await getDoc(doc(db, "assignments", id as string));
const snapshot = await db.collection("assignments").findOne({ _id: new ObjectId(id as string) });
res.status(200).json({...snapshot.data(), id: snapshot.id});
if (snapshot) {
res.status(200).json({...snapshot, id: snapshot._id});
}
}
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
const {id} = req.query;
await deleteDoc(doc(db, "assignments", id as string));
await db.collection("assignments").deleteOne(
{ _id: new ObjectId(id as string) }
);
res.status(200).json({ok: true});
}
@@ -42,7 +46,10 @@ async function DELETE(req: NextApiRequest, res: NextApiResponse) {
async function PATCH(req: NextApiRequest, res: NextApiResponse) {
const {id} = req.query;
await setDoc(doc(db, "assignments", id as string), {assigner: req.session.user?.id, ...req.body}, {merge: true});
await db.collection("assignments").updateOne(
{ _id: new ObjectId(id as string) },
{ $set: {assigner: req.session.user?.id, ...req.body} }
);
res.status(200).json({ok: true});
}

View File

@@ -1,10 +1,10 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -12,14 +12,18 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to archive
if (req.session.user) {
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const doc = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
if (!docSnap.exists()) {
if (!doc) {
res.status(404).json({ ok: false });
return;
}
await setDoc(docSnap.ref, { released: true }, { merge: true });
await db.collection("assignments").updateOne(
{ _id: new ObjectId(id) },
{ $set: { released: true } }
);
res.status(200).json({ ok: true });
return;
}

View File

@@ -1,11 +1,11 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import moment from "moment";
import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -13,26 +13,25 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to archive
if (req.session.user) {
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const data = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
if (!docSnap.exists()) {
if (!data) {
res.status(404).json({ ok: false });
return;
}
const data = docSnap.data();
if (moment().isAfter(moment(data.startDate))) {
res
.status(400)
.json({ ok: false, message: "Assignmentcan no longer " });
.json({ ok: false, message: "Assignment can no longer " });
return;
}
await setDoc(
docSnap.ref,
{ start: true },
{ merge: true }
await db.collection("assignments").updateOne(
{ _id: new ObjectId(id) },
{ $set: { start: true } }
);
res.status(200).json({ ok: true });
return;
}

View File

@@ -1,33 +1,37 @@
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, doc, getDoc, setDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
async function post(req: NextApiRequest, res: NextApiResponse) {
// verify if it's a logged user that is trying to archive
if (req.session.user) {
const {id} = req.query as {id: string};
const docSnap = await getDoc(doc(db, "assignments", id));
const { id } = req.query as { id: string };
const docSnap = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
if (!docSnap.exists()) {
res.status(404).json({ok: false});
if (!docSnap) {
res.status(404).json({ ok: false });
return;
}
await setDoc(docSnap.ref, {archived: false}, {merge: true});
res.status(200).json({ok: true});
await db.collection("assignments").updateOne(
{ _id: new ObjectId(id) },
{ $set: { archived: false } }
);
res.status(200).json({ ok: true });
return;
}
res.status(401).json({ok: false});
res.status(401).json({ ok: false });
}
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") return post(req, res);
res.status(404).json({ok: false});
res.status(404).json({ ok: false });
}

View File

@@ -1,22 +1,11 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs, query, where, setDoc, doc, getDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {uuidv4} from "@firebase/util";
import {Module} from "@/interfaces";
import {getExams} from "@/utils/exams.be";
import {Exam, InstructorGender, Variant} from "@/interfaces/exam";
import {capitalize, flatten, uniqBy} from "lodash";
import {User} from "@/interfaces/user";
import moment from "moment";
import {sendEmail} from "@/email";
import {uniqBy} from "lodash";
import {getAllAssignersByCorporate} from "@/utils/groups.be";
import {getAssignmentsByAssigners} from "@/utils/assignments.be";
const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {

View File

@@ -1,7 +1,7 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs, query, where, setDoc, doc, getDoc} from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {uuidv4} from "@firebase/util";
@@ -14,7 +14,7 @@ import moment from "moment";
import {sendEmail} from "@/email";
import {release} from "os";
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -31,13 +31,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
async function GET(req: NextApiRequest, res: NextApiResponse) {
const q = query(collection(db, "assignments"));
const snapshot = await getDocs(q);
const docs = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
const docs = await db.collection("assignments").find({}).toArray();
res.status(200).json(docs);
}
@@ -135,7 +129,8 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
return;
}
await setDoc(doc(db, "assignments", uuidv4()), {
await db.collection("assignments").insertOne({
_id: new ObjectId(uuidv4()),
assigner: req.session.user?.id,
assignees,
results: [],
@@ -147,10 +142,10 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ok: true});
for (const assigneeID of assignees) {
const assigneeSnapshot = await getDoc(doc(db, "users", assigneeID));
if (!assigneeSnapshot.exists()) continue;
const assignee = {id: assigneeID, ...assigneeSnapshot.data()} as User;
const assignee = await db.collection("users").findOne<User>({ _id: new ObjectId(assigneeID) });
if (!assignee) continue;
const name = body.name;
const teacher = req.session.user!;
const examModulesLabel = uniqBy(exams, (x) => x.module)

View File

@@ -1,6 +1,5 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app, storage } from "@/firebase";
import { getFirestore } from "firebase/firestore";
import { storage } from "@/firebase";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
@@ -12,11 +11,9 @@ import { checkAccess } from "@/utils/permissions";
import { getAssignmentsForCorporates } from "@/utils/assignments.be";
import { search } from "@/utils/search";
import { getGradingSystem } from "@/utils/grading.be";
import { Exam } from "@/interfaces/exam";
import { User } from "@/interfaces/user";
import { calculateBandScore, getGradingLabel } from "@/utils/score";
import { Module } from "@/interfaces";
const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -229,7 +226,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const refName = `statistical/${fileName}`;
const fileRef = ref(storage, refName);
// upload the pdf to storage
const snapshot = await uploadBytes(fileRef, buffer, {
await uploadBytes(fileRef, buffer, {
contentType:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});