Merge branch 'migration-mongodb' of https://bitbucket.org/ecropdev/ielts-ui into migration-mongodb
This commit is contained in:
@@ -15,7 +15,7 @@ import {Grading} from "@/interfaces";
|
|||||||
import {getGroupsForUser} from "@/utils/groups.be";
|
import {getGroupsForUser} from "@/utils/groups.be";
|
||||||
import {uniq} from "lodash";
|
import {uniq} from "lodash";
|
||||||
import {getUser} from "@/utils/users.be";
|
import {getUser} from "@/utils/users.be";
|
||||||
import { getGradingSystem } from "@/utils/grading.be";
|
import {getGradingSystem} from "@/utils/grading.be";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const participants = uniq(groups.flatMap((x) => x.participants));
|
const participants = uniq(groups.flatMap((x) => x.participants));
|
||||||
|
|
||||||
const participantUsers = await Promise.all(participants.map(getUser));
|
const participantUsers = await Promise.all(participants.map(getUser));
|
||||||
const corporateUsers = participantUsers.filter((x) => x.type === "corporate") as CorporateUser[];
|
const corporateUsers = participantUsers.filter((x) => x?.type === "corporate") as CorporateUser[];
|
||||||
|
|
||||||
await Promise.all(corporateUsers.map(async (g) => await setDoc(doc(db, "grading", g.id), body)));
|
await Promise.all(corporateUsers.map(async (g) => await setDoc(doc(db, "grading", g.id), body)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
|
|||||||
import ShortUniqueId from "short-unique-id";
|
import ShortUniqueId from "short-unique-id";
|
||||||
import {getUserCorporate, getUserGroups} from "@/utils/groups.be";
|
import {getUserCorporate, getUserGroups} from "@/utils/groups.be";
|
||||||
import {uniq} from "lodash";
|
import {uniq} from "lodash";
|
||||||
import {getUser} from "@/utils/users.be";
|
import {getSpecificUsers, getUser} from "@/utils/users.be";
|
||||||
|
|
||||||
const DEFAULT_DESIRED_LEVELS = {
|
const DEFAULT_DESIRED_LEVELS = {
|
||||||
reading: 9,
|
reading: 9,
|
||||||
@@ -32,9 +32,10 @@ export default withIronSessionApiRoute(handler, sessionOptions);
|
|||||||
|
|
||||||
const getUsersOfType = async (admin: string, type: Type) => {
|
const getUsersOfType = async (admin: string, type: Type) => {
|
||||||
const groups = await getUserGroups(admin);
|
const groups = await getUserGroups(admin);
|
||||||
const users = await Promise.all(uniq(groups.flatMap((x) => x.participants)).map(getUser));
|
const participants = groups.flatMap((x) => x.participants);
|
||||||
|
const users = await getSpecificUsers(participants);
|
||||||
|
|
||||||
return users.filter((x) => x.type === type).map((x) => x.id);
|
return users.filter((x) => x?.type === type).map((x) => x?.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import {app} from "@/firebase";
|
|||||||
import {sessionOptions} from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
||||||
import {CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
import {Code, CorporateInformation, DemographicInformation, Group, Type} from "@/interfaces/user";
|
||||||
import {addUserToGroupOnCreation} from "@/utils/registration";
|
import {addUserToGroupOnCreation} from "@/utils/registration";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {v4} from "uuid";
|
import {v4} from "uuid";
|
||||||
|
import client from "@/lib/mongodb";
|
||||||
|
|
||||||
const auth = getAuth(app);
|
const auth = getAuth(app);
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(register, sessionOptions);
|
export default withIronSessionApiRoute(register, sessionOptions);
|
||||||
|
|
||||||
@@ -45,24 +46,13 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
code?: string;
|
code?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const codeQuery = query(collection(db, "codes"), where("code", "==", code));
|
const codeDoc = await db.collection("codes").findOne<Code>({code});
|
||||||
const codeDocs = (await getDocs(codeQuery)).docs.filter((x) => !Object.keys(x.data()).includes("userId"));
|
|
||||||
|
|
||||||
if (code && code.length > 0 && codeDocs.length === 0) {
|
if (code && code.length > 0 && !!codeDoc) {
|
||||||
res.status(400).json({error: "Invalid Code!"});
|
res.status(400).json({error: "Invalid Code!"});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const codeData =
|
|
||||||
codeDocs.length > 0
|
|
||||||
? (codeDocs[0].data() as {
|
|
||||||
code: string;
|
|
||||||
type: Type;
|
|
||||||
creator?: string;
|
|
||||||
expiryDate: Date | null;
|
|
||||||
})
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
createUserWithEmailAndPassword(auth, email.toLowerCase(), password)
|
createUserWithEmailAndPassword(auth, email.toLowerCase(), password)
|
||||||
.then(async (userCredentials) => {
|
.then(async (userCredentials) => {
|
||||||
const userId = userCredentials.user.uid;
|
const userId = userCredentials.user.uid;
|
||||||
@@ -70,31 +60,32 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const user = {
|
const user = {
|
||||||
...req.body,
|
...req.body,
|
||||||
|
id: userId,
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
||||||
levels: DEFAULT_LEVELS,
|
levels: DEFAULT_LEVELS,
|
||||||
bio: "",
|
bio: "",
|
||||||
isFirstLogin: codeData ? codeData.type === "student" : true,
|
isFirstLogin: codeDoc ? codeDoc.type === "student" : true,
|
||||||
profilePicture: "/defaultAvatar.png",
|
profilePicture: "/defaultAvatar.png",
|
||||||
focus: "academic",
|
focus: "academic",
|
||||||
type: email.endsWith("@ecrop.dev") ? "developer" : codeData ? codeData.type : "student",
|
type: email.endsWith("@ecrop.dev") ? "developer" : codeDoc ? codeDoc.type : "student",
|
||||||
subscriptionExpirationDate: codeData ? codeData.expiryDate : moment().subtract(1, "days").toISOString(),
|
subscriptionExpirationDate: codeDoc ? codeDoc.expiryDate : moment().subtract(1, "days").toISOString(),
|
||||||
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
||||||
registrationDate: new Date().toISOString(),
|
registrationDate: new Date().toISOString(),
|
||||||
status: code ? "active" : "paymentDue",
|
status: code ? "active" : "paymentDue",
|
||||||
};
|
};
|
||||||
|
|
||||||
await setDoc(doc(db, "users", userId), user);
|
await db.collection("users").insertOne(user);
|
||||||
|
|
||||||
if (codeDocs.length > 0 && codeData) {
|
if (!!codeDoc) {
|
||||||
await setDoc(codeDocs[0].ref, {userId: userId}, {merge: true});
|
await db.collection("codes").updateOne({code: codeDoc.code}, {$set: {userId}});
|
||||||
if (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator);
|
if (codeDoc.creator) await addUserToGroupOnCreation(userId, codeDoc.type, codeDoc.creator);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.session.user = {...user, id: userId};
|
req.session.user = user;
|
||||||
await req.session.save();
|
await req.session.save();
|
||||||
|
|
||||||
res.status(200).json({user: {...user, id: userId}});
|
res.status(200).json({user});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
@@ -116,6 +107,7 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const user = {
|
const user = {
|
||||||
...req.body,
|
...req.body,
|
||||||
|
id: userId,
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
||||||
levels: DEFAULT_LEVELS,
|
levels: DEFAULT_LEVELS,
|
||||||
@@ -152,15 +144,13 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
disableEditing: true,
|
disableEditing: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
await setDoc(doc(db, "users", userId), user);
|
await db.collection("users").insertOne(user);
|
||||||
await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
|
await db.collection("groups").insertMany([defaultCorporateGroup, defaultStudentsGroup, defaultTeachersGroup]);
|
||||||
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
|
|
||||||
await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
|
|
||||||
|
|
||||||
req.session.user = {...user, id: userId};
|
req.session.user = user;
|
||||||
await req.session.save();
|
await req.session.save();
|
||||||
|
|
||||||
res.status(200).json({user: {...user, id: userId}});
|
res.status(200).json({user});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
|||||||
@@ -1,75 +1,73 @@
|
|||||||
import {app} from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser} from "@/interfaces/user";
|
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 {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {getUser} from "./users.be";
|
import {getUser} from "./users.be";
|
||||||
import {getSpecificUsers} from "./users.be";
|
import {getSpecificUsers} from "./users.be";
|
||||||
const db = getFirestore(app);
|
|
||||||
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export const updateExpiryDateOnGroup = async (participantID: string, corporateID: string) => {
|
export const updateExpiryDateOnGroup = async (participantID: string, corporateID: string) => {
|
||||||
const corporateRef = await getDoc(doc(db, "users", corporateID));
|
const corporate = await db.collection("users").findOne<User>({id: corporateID});
|
||||||
const participantRef = await getDoc(doc(db, "users", participantID));
|
const participant = await db.collection("users").findOne<User>({id: participantID});
|
||||||
|
|
||||||
if (!corporateRef.exists() || !participantRef.exists()) return;
|
|
||||||
|
|
||||||
const corporate = {
|
|
||||||
...corporateRef.data(),
|
|
||||||
id: corporateRef.id,
|
|
||||||
} as CorporateUser;
|
|
||||||
const participant = {...participantRef.data(), id: participantRef.id} as StudentUser | TeacherUser;
|
|
||||||
|
|
||||||
|
if (!corporate || !participant) return;
|
||||||
if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;
|
if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;
|
||||||
|
|
||||||
if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate) {
|
if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate)
|
||||||
return await setDoc(doc(db, "users", participant.id), {subscriptionExpirationDate: null}, {merge: true});
|
return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: null}});
|
||||||
}
|
|
||||||
|
|
||||||
const corporateDate = moment(corporate.subscriptionExpirationDate);
|
const corporateDate = moment(corporate.subscriptionExpirationDate);
|
||||||
const participantDate = moment(participant.subscriptionExpirationDate);
|
const participantDate = moment(participant.subscriptionExpirationDate);
|
||||||
|
|
||||||
if (corporateDate.isAfter(participantDate))
|
if (corporateDate.isAfter(participantDate))
|
||||||
return await setDoc(doc(db, "users", participant.id), {subscriptionExpirationDate: corporateDate.toISOString()}, {merge: true});
|
return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: corporateDate.toISOString()}});
|
||||||
|
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getUserCorporate = async (id: string) => {
|
export const getUserCorporate = async (id: string) => {
|
||||||
const user = await getUser(id);
|
const user = await getUser(id);
|
||||||
|
if (!user) return undefined;
|
||||||
|
|
||||||
if (["admin", "developer"].includes(user.type)) return undefined;
|
if (["admin", "developer"].includes(user.type)) return undefined;
|
||||||
if (user.type === "mastercorporate") return user;
|
if (user.type === "mastercorporate") return user;
|
||||||
|
|
||||||
const groups = await getParticipantGroups(id);
|
const groups = await getParticipantGroups(id);
|
||||||
const admins = await Promise.all(groups.map((x) => x.admin).map(getUser));
|
const admins = await Promise.all(groups.map((x) => x.admin).map(getUser));
|
||||||
const corporates = admins.filter((x) => (user.type === "corporate" ? x.type === "mastercorporate" : x.type === "corporate"));
|
const corporates = admins
|
||||||
|
.filter((x) => (user.type === "corporate" ? x?.type === "mastercorporate" : x?.type === "corporate"))
|
||||||
|
.filter((x) => !!x) as User[];
|
||||||
|
|
||||||
if (corporates.length === 0) return undefined;
|
if (corporates.length === 0) return undefined;
|
||||||
return corporates.shift() as CorporateUser | MasterCorporateUser;
|
return corporates.shift() as CorporateUser | MasterCorporateUser;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getGroups = async () => {
|
export const getGroups = async () => {
|
||||||
const groupDocs = await getDocs(collection(db, "groups"));
|
return await db.collection("groups").find<Group>({}).toArray();
|
||||||
return groupDocs.docs.map((x) => ({...x.data(), id: x.id})) as Group[];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getParticipantGroups = async (id: string) => {
|
export const getParticipantGroups = async (id: string) => {
|
||||||
const snapshot = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
return await db.collection("groups").find<Group>({participants: id}).toArray();
|
||||||
|
|
||||||
const groups = snapshot.docs.map((doc) => ({
|
|
||||||
id: doc.id,
|
|
||||||
...doc.data(),
|
|
||||||
})) as Group[];
|
|
||||||
|
|
||||||
return groups;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getUserGroups = async (id: string): Promise<Group[]> => {
|
export const getUserGroups = async (id: string): Promise<Group[]> => {
|
||||||
const groupDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
|
return await db.collection("groups").find<Group>({admin: id}).toArray();
|
||||||
return groupDocs.docs.map((x) => ({...x.data(), id})) as Group[];
|
};
|
||||||
|
|
||||||
|
export const getUsersGroups = async (ids: string[]) => {
|
||||||
|
return await db
|
||||||
|
.collection("groups")
|
||||||
|
.find<Group>({admin: {$in: ids}})
|
||||||
|
.toArray();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
||||||
const groups = await getUserGroups(corporateID);
|
const groups = await getUserGroups(corporateID);
|
||||||
const groupUsers = (await Promise.all(groups.map(async (g) => await Promise.all(g.participants.map(getUser))))).flat();
|
const groupUsers = (await Promise.all(groups.map(async (g) => await Promise.all(g.participants.map(getUser)))))
|
||||||
|
.flat()
|
||||||
|
.filter((x) => !!x) as User[];
|
||||||
const teacherPromises = await Promise.all(
|
const teacherPromises = await Promise.all(
|
||||||
groupUsers.map(async (u) =>
|
groupUsers.map(async (u) =>
|
||||||
u.type === "teacher" ? u.id : u.type === "corporate" ? [...(await getAllAssignersByCorporate(u.id)), u.id] : undefined,
|
u.type === "teacher" ? u.id : u.type === "corporate" ? [...(await getAllAssignersByCorporate(u.id)), u.id] : undefined,
|
||||||
@@ -80,42 +78,19 @@ export const getAllAssignersByCorporate = async (corporateID: string): Promise<s
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const getGroupsForUser = async (admin?: string, participant?: string) => {
|
export const getGroupsForUser = async (admin?: string, participant?: string) => {
|
||||||
try {
|
if (admin && participant) return await db.collection("groups").find<Group>({admin, participant}).toArray();
|
||||||
const queryConstraints = [
|
|
||||||
...(admin ? [where("admin", "==", admin)] : []),
|
|
||||||
...(participant ? [where("participants", "array-contains", participant)] : []),
|
|
||||||
];
|
|
||||||
const snapshot = await getDocs(queryConstraints.length > 0 ? query(collection(db, "groups"), ...queryConstraints) : collection(db, "groups"));
|
|
||||||
const groups = snapshot.docs.map((doc) => ({
|
|
||||||
id: doc.id,
|
|
||||||
...doc.data(),
|
|
||||||
})) as Group[];
|
|
||||||
|
|
||||||
return groups;
|
if (admin) return await getUserGroups(admin);
|
||||||
} catch (e) {
|
if (participant) return await getParticipantGroups(participant);
|
||||||
console.error(e);
|
|
||||||
return [];
|
return await getGroups();
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getStudentGroupsForUsersWithoutAdmin = async (admin: string, participants: string[]) => {
|
export const getStudentGroupsForUsersWithoutAdmin = async (admin: string, participants: string[]) => {
|
||||||
try {
|
return await db
|
||||||
const queryConstraints = [
|
.collection("groups")
|
||||||
...(admin ? [where("admin", "!=", admin)] : []),
|
.find<Group>({...(admin ? {admin: {$ne: admin}} : {}), ...(participants ? {participants} : {})})
|
||||||
...(participants ? [where("participants", "array-contains-any", participants)] : []),
|
.toArray();
|
||||||
where("name", "==", "Students"),
|
|
||||||
];
|
|
||||||
const snapshot = await getDocs(queryConstraints.length > 0 ? query(collection(db, "groups"), ...queryConstraints) : collection(db, "groups"));
|
|
||||||
const groups = snapshot.docs.map((doc) => ({
|
|
||||||
id: doc.id,
|
|
||||||
...doc.data(),
|
|
||||||
})) as Group[];
|
|
||||||
|
|
||||||
return groups;
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCorporateNameForStudent = async (studentID: string) => {
|
export const getCorporateNameForStudent = async (studentID: string) => {
|
||||||
@@ -123,7 +98,7 @@ export const getCorporateNameForStudent = async (studentID: string) => {
|
|||||||
if (groups.length === 0) return "";
|
if (groups.length === 0) return "";
|
||||||
|
|
||||||
const adminUserIds = [...new Set(groups.map((g) => g.admin))];
|
const adminUserIds = [...new Set(groups.map((g) => g.admin))];
|
||||||
const adminUsersData = await getSpecificUsers(adminUserIds);
|
const adminUsersData = (await getSpecificUsers(adminUserIds)).filter((x) => !!x) as User[];
|
||||||
|
|
||||||
if (adminUsersData.length === 0) return "";
|
if (adminUsersData.length === 0) return "";
|
||||||
const admins = adminUsersData.filter((x) => x.type === "corporate");
|
const admins = adminUsersData.filter((x) => x.type === "corporate");
|
||||||
|
|||||||
@@ -2,30 +2,28 @@ import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} fr
|
|||||||
import {app} from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {Group, Type, User} from "@/interfaces/user";
|
import {Group, Type, User} from "@/interfaces/user";
|
||||||
import {uuidv4} from "@firebase/util";
|
import {uuidv4} from "@firebase/util";
|
||||||
|
import client from "@/lib/mongodb";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
|
export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
|
||||||
const creatorDoc = await getDoc(doc(db, "users", creatorId));
|
const creator = await db.collection("users").findOne<User>({id: creatorId});
|
||||||
if (!creatorDoc.exists()) return false;
|
if (!creator) return false;
|
||||||
|
|
||||||
const creator = {...creatorDoc.data(), id: creatorDoc.id} as User;
|
const creatorGroup = await db.collection("groups").findOne<Group>({admin: creator.id, name: type === "student" ? "Students" : "Teachers"});
|
||||||
|
|
||||||
const creatorGroupsDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", creator.id)));
|
if (!!creatorGroup) {
|
||||||
const typeGroup = creatorGroupsDocs.docs.find((x) => (x.data() as Group).name === (type === "student" ? "Students" : "Teachers"));
|
await db.collection("groups").updateOne({id: creatorGroup.id}, {$set: {participants: [...creatorGroup.participants, userId]}});
|
||||||
|
|
||||||
if (typeGroup && typeGroup.exists()) {
|
|
||||||
await setDoc(typeGroup.ref, {participants: [...typeGroup.data().participants, userId]}, {merge: true});
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupId = uuidv4();
|
const groupId = uuidv4();
|
||||||
await setDoc(doc(db, "groups", groupId), {
|
await db.collection("groups").insertOne({
|
||||||
admin: creatorId,
|
admin: creatorId,
|
||||||
name: type === "student" ? "Students" : "Teachers",
|
name: type === "student" ? "Students" : "Teachers",
|
||||||
id: groupId,
|
id: groupId,
|
||||||
participants: [userId],
|
participants: [userId],
|
||||||
disableEditing: true,
|
disableEditing: true,
|
||||||
} as Group);
|
});
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -18,67 +18,46 @@ import {
|
|||||||
where,
|
where,
|
||||||
} from "firebase/firestore";
|
} from "firebase/firestore";
|
||||||
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
|
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
|
||||||
import {getGroupsForUser} from "./groups.be";
|
import {getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups} from "./groups.be";
|
||||||
import {last, uniq, uniqBy} from "lodash";
|
import {last, uniq, uniqBy} from "lodash";
|
||||||
import {getUserCodes} from "./codes.be";
|
import {getUserCodes} from "./codes.be";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
const db = getFirestore(app);
|
import client from "@/lib/mongodb";
|
||||||
|
|
||||||
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export async function getUsers() {
|
export async function getUsers() {
|
||||||
const snapshot = await getDocs(collection(db, "users"));
|
return await db.collection("users").find<User>({}).toArray();
|
||||||
|
|
||||||
return snapshot.docs.map((doc) => ({
|
|
||||||
...doc.data(),
|
|
||||||
id: doc.id,
|
|
||||||
registrationDate: moment(doc.data().registrationDate).toISOString(),
|
|
||||||
})) as unknown as User[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUser(id: string) {
|
export async function getUser(id: string): Promise<User | undefined> {
|
||||||
const userDoc = await getDoc(doc(db, "users", id));
|
const user = await db.collection("users").findOne<User>({id});
|
||||||
|
return !!user ? user : undefined;
|
||||||
return {...userDoc.data(), id, registrationDate: moment(userDoc.data()?.registrationDate).toISOString()} as unknown as User;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getSpecificUsers(ids: string[]) {
|
export async function getSpecificUsers(ids: string[]) {
|
||||||
if (ids.length === 0) return [];
|
if (ids.length === 0) return [];
|
||||||
|
|
||||||
const snapshot = await getDocs(query(collection(db, "users"), where("id", "in", ids)));
|
return await db
|
||||||
|
.collection("users")
|
||||||
const groups = snapshot.docs.map((doc) => ({
|
.find<User>({id: {$in: ids}})
|
||||||
...doc.data(),
|
.toArray();
|
||||||
id: doc.id,
|
|
||||||
registrationDate: moment(doc.data().registrationDate).toISOString(),
|
|
||||||
})) as unknown as User[];
|
|
||||||
|
|
||||||
return groups;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getLinkedUsers(userID?: string, userType?: Type, type?: Type, firstID?: string, lastID?: string, size?: number) {
|
export async function getLinkedUsers(userID?: string, userType?: Type, type?: Type, firstID?: string, lastID?: string, size?: number) {
|
||||||
const q = [
|
const filters = {
|
||||||
...(!!type ? [where("type", "==", type)] : []),
|
...(!!type ? {type} : {}),
|
||||||
orderBy("registrationDate"),
|
};
|
||||||
...(!!firstID && !lastID ? [endBefore(firstID)] : []),
|
|
||||||
...(!!lastID && !firstID ? [startAfter(lastID)] : []),
|
|
||||||
...(!!size ? [limit(size)] : []),
|
|
||||||
];
|
|
||||||
|
|
||||||
const totalQ = [...(!!type ? [where("type", "==", type)] : []), orderBy(documentId())];
|
|
||||||
|
|
||||||
if (!userID || userType === "admin" || userType === "developer") {
|
if (!userID || userType === "admin" || userType === "developer") {
|
||||||
const snapshot = await getDocs(query(collection(db, "users"), ...q));
|
const users = await db.collection("users").find<User>(filters).toArray();
|
||||||
const users = snapshot.docs.map((doc) => ({
|
const total = await db.collection("users").countDocuments(filters);
|
||||||
id: doc.id,
|
return {users, total};
|
||||||
...doc.data(),
|
|
||||||
})) as User[];
|
|
||||||
|
|
||||||
const total = await getCountFromServer(query(collection(db, "users"), ...totalQ));
|
|
||||||
return {users, total: total.data().count};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const adminGroups = await getGroupsForUser(userID);
|
const adminGroups = await getUserGroups(userID);
|
||||||
const groups = await Promise.all(adminGroups.flatMap((x) => x.participants).map(async (x) => await getGroupsForUser(x)));
|
const groups = await getUsersGroups(adminGroups.flatMap((x) => x.participants));
|
||||||
const belongingGroups = await getGroupsForUser(undefined, userID);
|
const belongingGroups = await getParticipantGroups(userID);
|
||||||
|
|
||||||
const participants = uniq([
|
const participants = uniq([
|
||||||
...adminGroups.flatMap((x) => x.participants),
|
...adminGroups.flatMap((x) => x.participants),
|
||||||
@@ -89,33 +68,13 @@ export async function getLinkedUsers(userID?: string, userType?: Type, type?: Ty
|
|||||||
// ⨯ [FirebaseError: Invalid Query. A non-empty array is required for 'in' filters.] {
|
// ⨯ [FirebaseError: Invalid Query. A non-empty array is required for 'in' filters.] {
|
||||||
if (participants.length === 0) return {users: [], total: 0};
|
if (participants.length === 0) return {users: [], total: 0};
|
||||||
|
|
||||||
if (participants.length < 30) {
|
const users = await db
|
||||||
const snapshot = await getDocs(query(collection(db, "users"), ...[where(documentId(), "in", participants), ...q]));
|
.collection("users")
|
||||||
const users = snapshot.docs.map((doc) => ({
|
.find<User>({...filters, id: {$in: participants}})
|
||||||
id: doc.id,
|
.toArray();
|
||||||
...doc.data(),
|
const total = await db.collection("users").countDocuments({...filters, id: {$in: participants}});
|
||||||
})) as User[];
|
|
||||||
|
|
||||||
const total = await getCountFromServer(query(collection(db, "users"), ...[where(documentId(), "in", participants), ...totalQ]));
|
return {users, total};
|
||||||
|
|
||||||
return {
|
|
||||||
users,
|
|
||||||
total: total.data().count,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const snapshot = await getDocs(query(collection(db, "users"), ...q));
|
|
||||||
const users = snapshot.docs.map((doc) => ({
|
|
||||||
id: doc.id,
|
|
||||||
...doc.data(),
|
|
||||||
})) as User[];
|
|
||||||
|
|
||||||
const participantUsers = users.filter((x) => participants.includes(x.id));
|
|
||||||
|
|
||||||
return {
|
|
||||||
users: participantUsers,
|
|
||||||
total: participantUsers.length,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUserBalance(user: User) {
|
export async function getUserBalance(user: User) {
|
||||||
@@ -128,7 +87,7 @@ export async function getUserBalance(user: User) {
|
|||||||
if (user.type === "corporate") return participants.length + codes.filter((x) => !participants.includes(x.userId || "")).length;
|
if (user.type === "corporate") return participants.length + codes.filter((x) => !participants.includes(x.userId || "")).length;
|
||||||
|
|
||||||
const participantUsers = await Promise.all(participants.map(getUser));
|
const participantUsers = await Promise.all(participants.map(getUser));
|
||||||
const corporateUsers = participantUsers.filter((x) => x.type === "corporate") as CorporateUser[];
|
const corporateUsers = participantUsers.filter((x) => x?.type === "corporate") as CorporateUser[];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
corporateUsers.reduce((acc, curr) => acc + curr.corporateInformation?.companyInformation?.userAmount || 0, 0) +
|
corporateUsers.reduce((acc, curr) => acc + curr.corporateInformation?.companyInformation?.userAmount || 0, 0) +
|
||||||
|
|||||||
Reference in New Issue
Block a user