Finished refactoring

This commit is contained in:
Carlos Mesquita
2024-09-07 22:39:14 +01:00
parent c2b4bb29d6
commit 6e4ef249b8
16 changed files with 169 additions and 188 deletions

View File

@@ -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<Assignment>(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<Assignment>({}).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<Assignment>({assigner: id}).toArray();
};
export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => {

View File

@@ -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<Code[]> => {
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<Code>({creator: id}).toArray();
};

View File

@@ -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";

View File

@@ -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";

View File

@@ -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<Permission>({ 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<Permission>({}).toArray();
}

View File

@@ -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<User>({ 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<User>({ 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<User>({ 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<User>({ 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);