diff --git a/src/pages/api/payments/[id].ts b/src/pages/api/payments/[id].ts index 90a463a2..58167029 100644 --- a/src/pages/api/payments/[id].ts +++ b/src/pages/api/payments/[id].ts @@ -1,7 +1,6 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type {NextApiRequest, NextApiResponse} from "next"; -import {app, storage} from "@/firebase"; -import {getFirestore, collection, getDocs, getDoc, doc, deleteDoc, setDoc} from "firebase/firestore"; +import {storage} from "@/firebase"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Group} from "@/interfaces/user"; diff --git a/src/pages/api/payments/assigned.ts b/src/pages/api/payments/assigned.ts index a2a17f1d..525161e8 100644 --- a/src/pages/api/payments/assigned.ts +++ b/src/pages/api/payments/assigned.ts @@ -1,7 +1,5 @@ // 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} from "firebase/firestore"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Payment} from "@/interfaces/paypal"; diff --git a/src/pages/api/payments/files/[type]/[paymentId].ts b/src/pages/api/payments/files/[type]/[paymentId].ts index 88f3d5d6..a2bfed36 100644 --- a/src/pages/api/payments/files/[type]/[paymentId].ts +++ b/src/pages/api/payments/files/[type]/[paymentId].ts @@ -1,17 +1,17 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import type {NextApiRequest, NextApiResponse} from "next"; -import {app, storage} from "@/firebase"; -import {getFirestore, getDoc, doc, updateDoc, deleteField, setDoc} from "firebase/firestore"; -import {withIronSessionApiRoute} from "iron-session/next"; -import {sessionOptions} from "@/lib/session"; -import {FilesStorage} from "@/interfaces/storage.files"; +import type { NextApiRequest, NextApiResponse } from "next"; +import { storage } from "@/firebase"; +import client from "@/lib/mongodb"; +import { withIronSessionApiRoute } from "iron-session/next"; +import { sessionOptions } from "@/lib/session"; +import { FilesStorage } from "@/interfaces/storage.files"; -import {Payment} from "@/interfaces/paypal"; +import { Payment } from "@/interfaces/paypal"; import fs from "fs"; -import {ref, uploadBytes, deleteObject, getDownloadURL} from "firebase/storage"; +import { ref, uploadBytes, deleteObject, getDownloadURL } from "firebase/storage"; import formidable from "formidable-serverless"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); const getPaymentField = (type: FilesStorage) => { switch (type) { @@ -25,28 +25,36 @@ const getPaymentField = (type: FilesStorage) => { }; const handleDelete = async (paymentId: string, paymentField: "commissionTransfer" | "corporateTransfer") => { - const paymentRef = doc(db, "payments", paymentId); - const paymentDoc = await getDoc(paymentRef); - const {[paymentField]: paymentFieldPath} = paymentDoc.data() as Payment; - // Create a reference to the file to delete - const documentRef = ref(storage, paymentFieldPath); - await deleteObject(documentRef); - await updateDoc(paymentRef, { - [paymentField]: deleteField(), - isPaid: false, - }); + const paymentDoc = await db.collection("payments").findOne({ id: paymentId }) + + if (paymentDoc) { + const { [paymentField]: paymentFieldPath } = paymentDoc; + + // Create a reference to the file to delete + const documentRef = ref(storage, paymentFieldPath); + await deleteObject(documentRef); + await db.collection("payments").deleteOne({ id: paymentId }); + + await db.collection("payments").updateOne( + { id: paymentId }, + { + $unset: { [paymentField]: "" }, + $set: { isPaid: false } + } + ); + } }; const handleUpload = async (req: NextApiRequest, paymentId: string, paymentField: "commissionTransfer" | "corporateTransfer") => new Promise((resolve, reject) => { - const form = formidable({keepExtensions: true}); + const form = formidable({ keepExtensions: true }); form.parse(req, async (err: any, fields: any, files: any) => { if (err) { reject(err); return; } try { - const {file} = files; + const { file } = files; const fileName = Date.now() + "-" + file.name; const fileRef = ref(storage, fileName); @@ -54,11 +62,13 @@ const handleUpload = async (req: NextApiRequest, paymentId: string, paymentField const snapshot = await uploadBytes(fileRef, binary); fs.rmSync(file.path); - const paymentRef = doc(db, "payments", paymentId); + await db.collection("payments").updateOne( + { id: paymentId }, + { + $set: { [paymentField]: snapshot.ref.fullPath } + } + ); - await updateDoc(paymentRef, { - [paymentField]: snapshot.ref.fullPath, - }); resolve(snapshot.ref.fullPath); } catch (err) { reject(err); @@ -69,7 +79,7 @@ const handleUpload = async (req: NextApiRequest, paymentId: string, paymentField export default withIronSessionApiRoute(handler, sessionOptions); async function handler(req: NextApiRequest, res: NextApiResponse) { if (!req.session.user) { - res.status(401).json({ok: false}); + res.status(401).json({ ok: false }); return; } @@ -82,80 +92,89 @@ async function handler(req: NextApiRequest, res: NextApiResponse) { } async function get(req: NextApiRequest, res: NextApiResponse) { - const {type, paymentId} = req.query as { + const { type, paymentId } = req.query as { type: FilesStorage; paymentId: string; }; const paymentField = getPaymentField(type); if (paymentField === null) { - res.status(500).json({error: "Failed to identify payment field"}); + res.status(500).json({ error: "Failed to identify payment field" }); return; } - const paymentRef = doc(db, "payments", paymentId); - const {[paymentField]: paymentFieldPath} = (await getDoc(paymentRef)).data() as Payment; + const paymentRef = await db.collection("payments").findOne({ id: paymentId }) + if (paymentRef) { + const { [paymentField]: paymentFieldPath } = paymentRef; - // Create a reference to the file to delete - const documentRef = ref(storage, paymentFieldPath); - const url = await getDownloadURL(documentRef); - res.status(200).json({url, name: documentRef.name}); + // Create a reference to the file to delete + const documentRef = ref(storage, paymentFieldPath); + const url = await getDownloadURL(documentRef); + res.status(200).json({ url, name: documentRef.name }); + return; + } } async function post(req: NextApiRequest, res: NextApiResponse) { - const {type, paymentId} = req.query as { + const { type, paymentId } = req.query as { type: FilesStorage; paymentId: string; }; const paymentField = getPaymentField(type); if (paymentField === null) { - res.status(500).json({error: "Failed to identify payment field"}); + res.status(500).json({ error: "Failed to identify payment field" }); return; } try { const ref = await handleUpload(req, paymentId, paymentField); - const updatedDoc = (await getDoc(doc(db, "payments", paymentId))).data() as Payment; - if (updatedDoc.commissionTransfer && updatedDoc.corporateTransfer) { - await setDoc(doc(db, "payments", paymentId), {isPaid: true}, {merge: true}); + const updatedDoc = await db.collection("payments").findOne({ id: paymentId }) + if (updatedDoc && updatedDoc.commissionTransfer && updatedDoc.corporateTransfer) { + await db.collection("payments").updateOne( + { id: paymentId }, + { $set: { isPaid: true } } + ); - await setDoc(doc(db, "users", updatedDoc.corporate), {status: "active"}, {merge: true}); + await db.collection("users").updateOne( + { id: updatedDoc.corporate }, + { $set: { status: "active" } } + ); } - res.status(200).json({ref}); + res.status(200).json({ ref }); } catch (error) { - res.status(500).json({error}); + res.status(500).json({ error }); } } async function del(req: NextApiRequest, res: NextApiResponse) { - const {type, paymentId} = req.query as { + const { type, paymentId } = req.query as { type: FilesStorage; paymentId: string; }; const paymentField = getPaymentField(type); if (paymentField === null) { - res.status(500).json({error: "Failed to identify payment field"}); + res.status(500).json({ error: "Failed to identify payment field" }); return; } try { await handleDelete(paymentId, paymentField); - res.status(200).json({ok: true}); + res.status(200).json({ ok: true }); } catch (err) { console.error(err); - res.status(500).json({error: "Failed to delete file"}); + res.status(500).json({ error: "Failed to delete file" }); } } async function patch(req: NextApiRequest, res: NextApiResponse) { - const {type, paymentId} = req.query as { + const { type, paymentId } = req.query as { type: FilesStorage; paymentId: string; }; const paymentField = getPaymentField(type); if (paymentField === null) { - res.status(500).json({error: "Failed to identify payment field"}); + res.status(500).json({ error: "Failed to identify payment field" }); return; } @@ -163,15 +182,15 @@ async function patch(req: NextApiRequest, res: NextApiResponse) { await handleDelete(paymentId, paymentField); } catch (err) { console.error(err); - res.status(500).json({error: "Failed to delete file"}); + res.status(500).json({ error: "Failed to delete file" }); return; } try { const ref = await handleUpload(req, paymentId, paymentField); - res.status(200).json({ref}); + res.status(200).json({ ref }); } catch (err) { - res.status(500).json({error: "Failed to upload file"}); + res.status(500).json({ error: "Failed to upload file" }); } } diff --git a/src/pages/api/payments/index.ts b/src/pages/api/payments/index.ts index af7f7f92..4fe86cf9 100644 --- a/src/pages/api/payments/index.ts +++ b/src/pages/api/payments/index.ts @@ -1,7 +1,5 @@ // 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, setDoc, doc} from "firebase/firestore"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Group} from "@/interfaces/user"; diff --git a/src/pages/api/payments/paypal.ts b/src/pages/api/payments/paypal.ts index 622b08f7..0d36fc05 100644 --- a/src/pages/api/payments/paypal.ts +++ b/src/pages/api/payments/paypal.ts @@ -1,7 +1,5 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type {NextApiRequest, NextApiResponse} from "next"; -import {app} from "@/firebase"; -import {getFirestore, getDocs, collection} from "firebase/firestore"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import client from "@/lib/mongodb"; diff --git a/src/pages/api/paymob/index.ts b/src/pages/api/paymob/index.ts index 4fddd0c2..c36df429 100644 --- a/src/pages/api/paymob/index.ts +++ b/src/pages/api/paymob/index.ts @@ -1,7 +1,6 @@ // 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, setDoc, doc} from "firebase/firestore"; +import client from "@/lib/mongodb"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Group} from "@/interfaces/user"; @@ -11,7 +10,7 @@ import ShortUniqueId from "short-unique-id"; import axios from "axios"; import {IntentionResult, PaymentIntention} from "@/interfaces/paymob"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); export default withIronSessionApiRoute(handler, sessionOptions); @@ -26,14 +25,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) { } async function get(req: NextApiRequest, res: NextApiResponse) { - const snapshot = await getDocs(collection(db, "payments")); - - res.status(200).json( - snapshot.docs.map((doc) => ({ - id: doc.id, - ...doc.data(), - })), - ); + const snapshot = await db.collection("payments").find().toArray(); + res.status(200).json(snapshot); } async function post(req: NextApiRequest, res: NextApiResponse) { diff --git a/src/pages/api/paymob/webhook.ts b/src/pages/api/paymob/webhook.ts index b4cf1bb4..7b428c6c 100644 --- a/src/pages/api/paymob/webhook.ts +++ b/src/pages/api/paymob/webhook.ts @@ -1,7 +1,5 @@ // 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, setDoc, doc, getDoc, query, where} from "firebase/firestore"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Group, User} from "@/interfaces/user"; @@ -11,8 +9,9 @@ import ShortUniqueId from "short-unique-id"; import axios from "axios"; import {IntentionResult, PaymentIntention, TransactionResult} from "@/interfaces/paymob"; import moment from "moment"; +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 === "POST") await post(req, res); @@ -32,11 +31,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) { duration_unit: DurationUnit; }; - const userSnapshot = await getDoc(doc(db, "users", userID as string)); + const user = await db.collection("users").findOne({ id: userID as string }); - if (!userSnapshot.exists() || !duration || !duration_unit) return res.status(404).json({ok: false}); - - const user = {...userSnapshot.data(), id: userSnapshot.id} as User; + if (!user || !duration || !duration_unit) return res.status(404).json({ok: false}); const subscriptionExpirationDate = user.subscriptionExpirationDate; if (!subscriptionExpirationDate) return res.status(200).json({ok: false}); @@ -45,8 +42,13 @@ async function post(req: NextApiRequest, res: NextApiResponse) { const updatedSubscriptionExpirationDate = moment(initialDate).add(duration, duration_unit).endOf("day").subtract(2, "hours").toISOString(); - await setDoc(userSnapshot.ref, {subscriptionExpirationDate: updatedSubscriptionExpirationDate, status: "active"}, {merge: true}); - await setDoc(doc(db, "paypalpayments", v4()), { + await db.collection("users").updateOne( + { id: userID as string }, + { $set: {subscriptionExpirationDate: updatedSubscriptionExpirationDate, status: "active"} } + ); + + await db.collection("paypalpayments").insertOne({ + id: v4(), createdAt: new Date().toISOString(), currency: transactionResult.transaction.currency, orderId: transactionResult.transaction.id, @@ -59,21 +61,19 @@ async function post(req: NextApiRequest, res: NextApiResponse) { }); if (user.type === "corporate") { - const groupsSnapshot = await getDocs(query(collection(db, "groups"), where("admin", "==", user.id))); - const groups = groupsSnapshot.docs.map((g) => ({...g.data(), id: g.id})) as Group[]; + const groups = await db.collection("groups").find({ admin: user.id }).toArray(); const participants = (await Promise.all( - groups.flatMap((x) => x.participants).map(async (x) => ({...(await getDoc(doc(db, "users", x))).data(), id: x})), + groups.flatMap((x) => x.participants).map(async (x) => ({...(await db.collection("users").findOne({ id: x}))})), )) as User[]; const sameExpiryDateParticipants = participants.filter( (x) => x.subscriptionExpirationDate === subscriptionExpirationDate && x.status !== "disabled", ); for (const participant of sameExpiryDateParticipants) { - await setDoc( - doc(db, "users", participant.id), - {subscriptionExpirationDate: updatedSubscriptionExpirationDate, status: "active"}, - {merge: true}, + await db.collection("users").updateOne( + { id: participant.id }, + { $set: {subscriptionExpirationDate: updatedSubscriptionExpirationDate, status: "active"} } ); } } diff --git a/src/pages/api/stripe.ts b/src/pages/api/stripe.ts index 5e5dbbae..f9cba2e4 100644 --- a/src/pages/api/stripe.ts +++ b/src/pages/api/stripe.ts @@ -1,7 +1,6 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type {NextApiRequest, NextApiResponse} from "next"; -import {app} from "@/firebase"; -import {getFirestore, setDoc, doc, getDocs, query, collection, where} from "firebase/firestore"; +import client from "@/lib/mongodb"; import {withIronSessionApiRoute} from "iron-session/next"; import {sessionOptions} from "@/lib/session"; import {Type, User} from "@/interfaces/user"; @@ -12,7 +11,8 @@ import * as Stripe from "stripe"; import ShortUniqueId from "short-unique-id"; import moment from "moment"; -const db = getFirestore(app); + +const db = client.db(process.env.MONGODB_DB); export default async function handler(req: NextApiRequest, res: NextApiResponse) { const {email, days, key, checkout} = req.body as {email: string; days: string; key: string; checkout: string}; @@ -24,41 +24,44 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const uid = new ShortUniqueId(); const code = uid.randomUUID(6); - const codeCheckerRef = await getDocs(query(collection(db, "codes"), where("checkout", "==", checkout))); - if (codeCheckerRef.docs.length !== 0) { + const codeCheckerRef = await db.collection("codes").find({ checkout: checkout }).toArray(); + if (codeCheckerRef.length !== 0) { res.status(401).json({ok: false}); return; } - const emailCheckerRef = await getDocs(query(collection(db, "users"), where("email", "==", email))); - if (emailCheckerRef.docs.length !== 0) { - const user = emailCheckerRef.docs[0]; - if (!user.data().subscriptionExpirationDate) { + const emailCheckerRef = await db.collection("users").find({ email: email }).toArray(); + if (emailCheckerRef.length !== 0) { + const user = emailCheckerRef[0]; + if (!user.subscriptionExpirationDate) { res.status(200).json({ok: true}); return; } - const codeUserRef = await getDocs(query(collection(db, "codes"), where("userId", "==", user.id))); - const userCode = codeUserRef.docs[0]; + const codeUserRef = await db.collection("codes").find({ userId: user.id }).toArray(); + const userCode = codeUserRef[0]; - if (userCode.data().checkout && userCode.data().checkout === checkout) { + if (userCode.checkout && userCode.checkout === checkout) { res.status(401).json({ok: false}); return; } - - await setDoc( - user.ref, - {subscriptionExpirationDate: moment(user.data().subscriptionExpirationDate).add(days, "days").toISOString()}, - {merge: true}, + await db.collection("users").updateOne( + { id: user.id }, + { $set: {subscriptionExpirationDate: moment(user.subscriptionExpirationDate).add(days, "days").toISOString()} } ); - await setDoc(userCode.ref, {checkout}, {merge: true}); + await db.collection("codes").updateOne( + { id: userCode.id }, + { $set: {checkout} } + ); res.status(200).json({ok: true}); return; } - const codeRef = doc(db, "codes", code); - await setDoc(codeRef, {type: "student", code, expiryDate: moment(new Date()).add(days, "days").toISOString(), checkout}); + await db.collection("codes").updateOne( + { id: code }, + { $set: {type: "student", code, expiryDate: moment(new Date()).add(days, "days").toISOString(), checkout} } + ); const transport = prepareMailer(); const mailOptions = prepareMailOptions( diff --git a/src/pages/api/user.ts b/src/pages/api/user.ts index 1a81f295..c1e8ceac 100644 --- a/src/pages/api/user.ts +++ b/src/pages/api/user.ts @@ -2,7 +2,6 @@ import {PERMISSIONS} from "@/constants/userPermissions"; import {app, adminApp} from "@/firebase"; import {Group, User} from "@/interfaces/user"; import {sessionOptions} from "@/lib/session"; -import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore"; import {getAuth} from "firebase-admin/auth"; import {withIronSessionApiRoute} from "iron-session/next"; import {NextApiRequest, NextApiResponse} from "next"; diff --git a/src/pages/api/users/update.ts b/src/pages/api/users/update.ts index f371fdf0..4f7ba431 100644 --- a/src/pages/api/users/update.ts +++ b/src/pages/api/users/update.ts @@ -1,7 +1,6 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type { NextApiRequest, NextApiResponse } from "next"; import { app, storage } from "@/firebase"; -import { getFirestore, collection, getDocs, getDoc, doc, setDoc, query, where } from "firebase/firestore"; import { withIronSessionApiRoute } from "iron-session/next"; import { sessionOptions } from "@/lib/session"; import { Group, User } from "@/interfaces/user"; diff --git a/src/utils/assignments.be.ts b/src/utils/assignments.be.ts index 61832ab0..e3e9ff45 100644 --- a/src/utils/assignments.be.ts +++ b/src/utils/assignments.be.ts @@ -1,35 +1,28 @@ -import {app} from "@/firebase"; -import {Assignment} from "@/interfaces/results"; -import {collection, getDocs, getFirestore, query, where} from "firebase/firestore"; -import {getAllAssignersByCorporate} from "@/utils/groups.be"; +import client from "@/lib/mongodb"; +import { Assignment } from "@/interfaces/results"; +import { getAllAssignersByCorporate } from "@/utils/groups.be"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); export const getAssignmentsByAssigner = async (id: string, startDate?: Date, endDate?: Date) => { - const {docs} = await getDocs( - query( - collection(db, "assignments"), - ...[ - where("assigner", "==", id), - ...(startDate ? [where("startDate", ">=", startDate.toISOString())] : []), - // firebase doesnt accept compound queries so we have to filter on the server - // ...endDate ? [where("endDate", "<=", endDate)] : [], - ], - ), - ); - if (endDate) { - return docs.map((x) => ({...(x.data() as Assignment), id: x.id})).filter((x) => new Date(x.endDate) <= endDate) as Assignment[]; + let query: any = { assigner: id }; + + if (startDate) { + query.startDate = { $gte: startDate.toISOString() }; } - return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[]; + + if (endDate) { + query.endDate = { $lte: endDate.toISOString() }; + } + + return await db.collection("assignments").find(query).toArray(); }; export const getAssignments = async () => { - const {docs} = await getDocs(collection(db, "assignments")); - return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[]; + return await db.collection("assignments").find({}).toArray(); }; export const getAssignmentsByAssignerBetweenDates = async (id: string, startDate: Date, endDate: Date) => { - const {docs} = await getDocs(query(collection(db, "assignments"), where("assigner", "==", id))); - return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[]; + return await db.collection("assignments").find({assigner: id}).toArray(); }; export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => { diff --git a/src/utils/codes.be.ts b/src/utils/codes.be.ts index 8dd19971..7fed077b 100644 --- a/src/utils/codes.be.ts +++ b/src/utils/codes.be.ts @@ -1,10 +1,8 @@ -import {app} from "@/firebase"; +import client from "@/lib/mongodb"; import {Code} from "@/interfaces/user"; -import {collection, getDocs, getFirestore, query, where} from "firebase/firestore"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); export const getUserCodes = async (id: string): Promise => { - const codeDocs = await getDocs(query(collection(db, "codes"), where("creator", "==", id))); - return codeDocs.docs.map((x) => ({...(x.data() as Code), id})) as Code[]; + return await db.collection("codes").find({creator: id}).toArray(); }; diff --git a/src/utils/grading.be.ts b/src/utils/grading.be.ts index 0edd0cad..391d1ed3 100644 --- a/src/utils/grading.be.ts +++ b/src/utils/grading.be.ts @@ -1,5 +1,3 @@ -import {app} from "@/firebase"; -import {getFirestore, doc, getDoc} from "firebase/firestore"; import {CEFR_STEPS} from "@/resources/grading"; import {getUserCorporate} from "@/utils/groups.be"; import {User} from "@/interfaces/user"; diff --git a/src/utils/groups.be.ts b/src/utils/groups.be.ts index 3091562d..42fe68f9 100644 --- a/src/utils/groups.be.ts +++ b/src/utils/groups.be.ts @@ -1,7 +1,6 @@ import {app} from "@/firebase"; import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, User} from "@/interfaces/user"; import client from "@/lib/mongodb"; -import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore"; import moment from "moment"; import {getUser} from "./users.be"; import {getSpecificUsers} from "./users.be"; diff --git a/src/utils/permissions.be.ts b/src/utils/permissions.be.ts index 93dffcba..b738b902 100644 --- a/src/utils/permissions.be.ts +++ b/src/utils/permissions.be.ts @@ -1,20 +1,19 @@ -import {app, adminApp} from "@/firebase"; -import {getAuth} from "firebase-admin/auth"; - -import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore"; +import client from "@/lib/mongodb"; import {Permission, PermissionType, permissions, PermissionTopic} from "@/interfaces/permissions"; import {v4} from "uuid"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); async function createPermission(topic: string, type: string) { - const permData = doc(db, "permissions", v4()); + /*const permData = doc(db, "permissions", v4()); const permDoc = await getDoc(permData); + if (permDoc.exists()) { return true; - } + }*/ - await setDoc(permData, { + await db.collection("permissions").insertOne({ + id: v4(), type, topic, users: [], @@ -48,7 +47,7 @@ export async function getUserPermissions(id: string) { } export async function bootstrap() { - await permissions + permissions .reduce((accm: PermissionsHelperList[], permissionData) => { return [ ...accm, @@ -64,26 +63,18 @@ export async function bootstrap() { } export async function getPermissionDoc(id: string) { - const docRef = doc(db, "permissions", id); - const docSnap = await getDoc(docRef); + const perm = await db.collection("permissions").findOne({ id: id }); - if (docSnap.exists()) { - return docSnap.data() as Permission; + if (perm) { + return perm; } throw new Error("Permission not found"); } export async function getPermissionDocs() { - const q = query(collection(db, "permissions")); + // TODO: Don't know if this was finished // firebase is missing something like array-not-contains - const snapshot = await getDocs(q); - - const docs = snapshot.docs.map((doc) => ({ - id: doc.id, - ...doc.data(), - })) as Permission[]; - - return docs; + return await db.collection("permissions").find({}).toArray(); } diff --git a/src/utils/propagate.user.changes.ts b/src/utils/propagate.user.changes.ts index 1ec882fe..8756c6b6 100644 --- a/src/utils/propagate.user.changes.ts +++ b/src/utils/propagate.user.changes.ts @@ -1,32 +1,29 @@ // updating specific user changes other users // for example, updating the status of a corporate user should update the status of all users in the same corporate group -import {UserStatus, User} from "../interfaces/user"; -import {getFirestore, collection, getDocs, getDoc, doc, setDoc, query, where} from "firebase/firestore"; -import {app} from "@/firebase"; +import { UserStatus, User } from "../interfaces/user"; +import client from "@/lib/mongodb"; -const db = getFirestore(app); +const db = client.db(process.env.MONGODB_DB); export const propagateStatusChange = (userId: string, status: UserStatus) => new Promise((resolve, reject) => { - getDoc(doc(db, "users", userId)) + db.collection("users").findOne({ id: userId }) .then((docUser) => { - const user = docUser.data() as User; + if (!docUser) return; + const user = docUser; // only update the status of the user's groups if the user is a corporate user if (user.type === "corporate" || user.type === "mastercorporate") { - getDocs(query(collection(db, "groups"), where("admin", "==", userId))).then(async (userGroupsRef) => { - const userGroups = userGroupsRef.docs.map((x) => x.data()); + db.collection("groups").find({ admin: userId }).toArray().then(async (userGroupsRef) => { + const userGroups = userGroupsRef.map((x) => x.data()); const targetUsers = [...new Set(userGroups.flatMap((g) => g.participants).filter((u) => u))]; Promise.all( targetUsers.map(async (targetUserId) => { - const ref = await getDoc(doc(db, "users", targetUserId)); - - if (!ref.exists()) return null; - - const data = ref.data() as User; - return {...data, id: targetUserId}; + const ref = await db.collection("users").findOne({ id: targetUserId }); + if (!ref) return null; + return ref; }), ) .then((data) => { @@ -40,7 +37,7 @@ export const propagateStatusChange = (userId: string, status: UserStatus) => return; } - Promise.all(filtered.map((user: User) => setDoc(doc(db, "users", user.id), {status}, {merge: true}))) + Promise.all(filtered.map((user: User) => db.collection("users").updateOne({ id: user.id }, { $set: { status } }))) .then(() => { resolve(true); }) @@ -69,25 +66,21 @@ export const propagateStatusChange = (userId: string, status: UserStatus) => export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null | undefined, subscriptionExpirationDate: Date | null) => new Promise((resolve, reject) => { - getDoc(doc(db, "users", userId)) - .then((docUser) => { - const user = docUser.data() as User; + db.collection("users").findOne({ id: userId }) + .then((user) => { + if (!user) return; // only update the status of the user's groups if the user is a corporate user if (user.type === "corporate") { - getDocs(query(collection(db, "groups"), where("admin", "==", userId))).then(async (userGroupsRef) => { - const userGroups = userGroupsRef.docs.map((x) => x.data()); + db.collection("groups").find({ admin: userId }).toArray().then(async (userGroupsRef) => { + const userGroups = userGroupsRef.map((x) => x.data()); const targetUsers = [...new Set(userGroups.flatMap((g) => g.participants).filter((u) => u))]; Promise.all( targetUsers.map(async (targetUserId) => { - const ref = await getDoc(doc(db, "users", targetUserId)); - - if (!ref.exists()) return null; - - const data = ref.data() as User; - return {...data, id: ref.id}; + const ref = await db.collection("users").findOne({ id: targetUserId }); + return ref; }), ) .then(async (data) => { @@ -101,7 +94,10 @@ export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Da if (filtered.length === 0) return; for (const user of filtered) { - await setDoc(doc(db, "users", user.id), {subscriptionExpirationDate}, {merge: true}); + await db.collection("users").updateOne( + { id: user.id }, + { $set: { subscriptionExpirationDate } } + ); } resolve(true);