Refactored /api/paypal, /api/permissions, /api/reset /api/sessions, /api/stats
This commit is contained in:
@@ -1,15 +1,6 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app, storage } from "@/firebase";
|
||||
import {
|
||||
getFirestore,
|
||||
doc,
|
||||
getDoc,
|
||||
updateDoc,
|
||||
getDocs,
|
||||
query,
|
||||
collection,
|
||||
where,
|
||||
} from "firebase/firestore";
|
||||
import { storage } from "@/firebase";
|
||||
import client from "@/lib/mongodb";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import ReactPDF from "@react-pdf/renderer";
|
||||
@@ -35,7 +26,8 @@ import {
|
||||
} from "@/utils/pdf";
|
||||
import moment from "moment-timezone";
|
||||
import { getCorporateNameForStudent } from "@/utils/groups.be";
|
||||
const db = getFirestore(app);
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -281,19 +273,22 @@ async function getPdfUrl(pdfStream: any, docsSnap: any) {
|
||||
|
||||
// upload the pdf to storage
|
||||
const pdfBuffer = await streamToBuffer(pdfStream);
|
||||
const snapshot = await uploadBytes(fileRef, pdfBuffer, {
|
||||
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,
|
||||
},
|
||||
});
|
||||
});
|
||||
await db.collection("stats").updateOne(
|
||||
{ id: docsSnap.id },
|
||||
{
|
||||
$set: {
|
||||
pdf: {
|
||||
path: refName,
|
||||
version: process.env.PDF_VERSION,
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
return getDownloadURL(fileRef);
|
||||
}
|
||||
|
||||
@@ -302,16 +297,13 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
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))
|
||||
);
|
||||
const stats = await db.collection("stats").find<Stat>({ session: id }).toArray();
|
||||
|
||||
if (docsSnap.empty) {
|
||||
if (stats.length == 0) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -336,26 +328,25 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
try {
|
||||
// generate the pdf report
|
||||
const docUser = await getDoc(doc(db, "users", userId));
|
||||
const docUser = await db.collection("users").findOne<User>({ id: userId});
|
||||
|
||||
if (docUser.exists()) {
|
||||
if (docUser) {
|
||||
// we'll need the user in order to get the user data (name, email, focus, etc);
|
||||
|
||||
const [stat] = stats;
|
||||
|
||||
if (stat.module === "level") {
|
||||
const user = docUser.data() as StudentUser;
|
||||
const user = docUser as StudentUser;
|
||||
|
||||
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 timeSpent = `${stats.reduce((accm, s: Stat) => accm + (s.timeSpent || 0), 0) / 60
|
||||
} minutes`;
|
||||
const score = stats.reduce((accm, s) => accm + s.score.correct, 0);
|
||||
const corporateName = await getCorporateNameForStudent(userId);
|
||||
const corporateName = await getCorporateNameForStudent(userId);
|
||||
const pdfStream = await ReactPDF.renderToStream(
|
||||
<LevelTestReport
|
||||
date={moment.max(dates).format("DD/MM/YYYY")}
|
||||
@@ -373,11 +364,11 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
/>
|
||||
);
|
||||
|
||||
const url = await getPdfUrl(pdfStream, docsSnap);
|
||||
const url = await getPdfUrl(pdfStream, docUser);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
}
|
||||
const user = docUser.data() as User;
|
||||
const user = docUser as User;
|
||||
|
||||
try {
|
||||
const pdfStream = await getDefaultPDFStream(
|
||||
@@ -386,7 +377,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
`${req.headers.origin || ""}${req.url}`
|
||||
);
|
||||
|
||||
const url = await getPdfUrl(pdfStream, docsSnap);
|
||||
const url = await getPdfUrl(pdfStream, docUser);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
} catch (err) {
|
||||
@@ -411,21 +402,17 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
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 stats = await db.collection("stats").find<Stat>({ session: id }).toArray();
|
||||
|
||||
if (docsSnap.empty) {
|
||||
if (stats.length == 0) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = docsSnap.docs.map((d) => d.data());
|
||||
|
||||
const hasPDF = stats.find((s) => s.pdf?.path);
|
||||
|
||||
if (hasPDF) {
|
||||
const fileRef = ref(storage, hasPDF.pdf.path);
|
||||
const fileRef = ref(storage, hasPDF.pdf!.path);
|
||||
const url = await getDownloadURL(fileRef);
|
||||
return res.redirect(url);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
// 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 {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {uuidv4} from "@firebase/util";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return GET(req, res);
|
||||
@@ -17,8 +13,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query;
|
||||
|
||||
const snapshot = await getDoc(doc(db, "stats", id as string));
|
||||
if (!snapshot.exists()) return res.status(404).json({id: snapshot.id});
|
||||
const snapshot = await db.collection("stats").findOne({ id: id as string});
|
||||
if (!snapshot) return res.status(404).json({id: id as string});
|
||||
|
||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// 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, doc, setDoc, addDoc, getDoc, deleteDoc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {groupBy} from "lodash";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import client from "@/lib/mongodb";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Stat } from "@/interfaces/user";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import { groupBy } from "lodash";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -19,33 +18,28 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const snapshot = await db.collection("stats").find<Stat>({}).toArray();
|
||||
|
||||
const q = query(collection(db, "stats"));
|
||||
|
||||
const snapshot = await getDocs(q);
|
||||
|
||||
res.status(200).json(
|
||||
snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})),
|
||||
);
|
||||
res.status(200).json(snapshot);
|
||||
}
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = req.body as Stat[];
|
||||
await stats.forEach(async (stat) => await setDoc(doc(db, "stats", stat.id), stat));
|
||||
await stats.forEach(async (stat) => {
|
||||
const sessionDoc = await getDoc(doc(db, "sessions", stat.session));
|
||||
if (sessionDoc.exists()) await deleteDoc(sessionDoc.ref);
|
||||
stats.forEach(async (stat) => await db.collection("stats").updateOne(
|
||||
{ id: stat.id },
|
||||
{ $set: stat },
|
||||
{ upsert: true }
|
||||
));
|
||||
stats.forEach(async (stat) => {
|
||||
await db.collection("sessions").deleteOne({ id: stat.session })
|
||||
});
|
||||
|
||||
const groupedStatsByAssignment = groupBy(
|
||||
@@ -55,22 +49,23 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (Object.keys(groupedStatsByAssignment).length > 0) {
|
||||
const assignments = Object.keys(groupedStatsByAssignment);
|
||||
|
||||
await assignments.forEach(async (assignmentId) => {
|
||||
assignments.forEach(async (assignmentId) => {
|
||||
const assignmentStats = groupedStatsByAssignment[assignmentId] as Stat[];
|
||||
|
||||
const assignmentSnapshot = await getDoc(doc(db, "assignments", assignmentId));
|
||||
await setDoc(
|
||||
doc(db, "assignments", assignmentId),
|
||||
const assignmentSnapshot = await db.collection("assignments").findOne<Assignment>({ id: assignmentId });
|
||||
await db.collection("assignments").updateOne(
|
||||
{ id: assignmentId },
|
||||
{
|
||||
results: [
|
||||
...(assignmentSnapshot.data() as Assignment).results,
|
||||
{user: req.session.user?.id, type: req.session.user?.focus, stats: assignmentStats},
|
||||
],
|
||||
},
|
||||
{merge: true},
|
||||
$set: {
|
||||
results: [
|
||||
...assignmentSnapshot ? assignmentSnapshot.results : [],
|
||||
{ user: req.session.user?.id, type: req.session.user?.focus, stats: assignmentStats },
|
||||
],
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
res.status(200).json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -6,29 +6,25 @@ import {sessionOptions} from "@/lib/session";
|
||||
import {calculateBandScore} from "@/utils/score";
|
||||
import {groupByModule, groupBySession} from "@/utils/stats";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import {getAuth} from "firebase/auth";
|
||||
import {collection, doc, getDoc, getDocs, getFirestore, query, updateDoc, where} from "firebase/firestore";
|
||||
import client from "@/lib/mongodb";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {groupBy} from "lodash";
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(update, sessionOptions);
|
||||
|
||||
async function update(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.session.user) {
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
const docUser = await db.collection("users").findOne({ id: req.session.user.id });
|
||||
|
||||
if (!docUser) {
|
||||
res.status(401).json(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const q = query(collection(db, "stats"), where("user", "==", req.session.user.id));
|
||||
const stats = (await getDocs(q)).docs.map((doc) => ({
|
||||
...(doc.data() as Stat),
|
||||
id: doc.id,
|
||||
})) as Stat[];
|
||||
const stats = await db.collection("stats").find<Stat>({ user: req.session.user.id }).toArray();
|
||||
|
||||
const groupedStats = groupBySession(stats);
|
||||
const sessionLevels: {[key in Module]: {correct: number; total: number}}[] = Object.keys(groupedStats).map((key) => {
|
||||
@@ -102,9 +98,11 @@ async function update(req: NextApiRequest, res: NextApiResponse) {
|
||||
level: calculateBandScore(levelLevel.correct, levelLevel.total, "level", req.session.user.focus),
|
||||
};
|
||||
|
||||
const userDoc = doc(db, "users", req.session.user.id);
|
||||
await updateDoc(userDoc, {levels});
|
||||
|
||||
await db.collection("users").updateOne(
|
||||
{ id: req.session.user.id},
|
||||
{ $set: {levels} }
|
||||
);
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
} else {
|
||||
res.status(401).json(undefined);
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// 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, doc, setDoc, addDoc} from "firebase/firestore";
|
||||
import client from "@/lib/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);
|
||||
|
||||
@@ -16,14 +15,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
}
|
||||
|
||||
const {user} = req.query;
|
||||
const q = query(collection(db, "stats"), where("user", "==", user));
|
||||
const snapshot = await db.collection("stats").find({ user: user }).toArray();
|
||||
|
||||
const snapshot = await getDocs(q);
|
||||
|
||||
res.status(200).json(
|
||||
snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})),
|
||||
);
|
||||
res.status(200).json(snapshot);
|
||||
}
|
||||
Reference in New Issue
Block a user