Continued updating the code to work with entities better

This commit is contained in:
Tiago Ribeiro
2024-10-07 15:49:58 +01:00
parent b5200c88fc
commit 1ef4efcacf
36 changed files with 2489 additions and 3012 deletions

View File

@@ -1,132 +1,171 @@
import {app} from "@/firebase";
import {Assignment} from "@/interfaces/results";
import {CorporateUser, Group, GroupWithUsers, MasterCorporateUser, StudentUser, TeacherUser, Type, User} from "@/interfaces/user";
import { app } from "@/firebase";
import { WithEntity } from "@/interfaces/entity";
import { Assignment } from "@/interfaces/results";
import { CorporateUser, Group, GroupWithUsers, MasterCorporateUser, StudentUser, TeacherUser, Type, User } from "@/interfaces/user";
import client from "@/lib/mongodb";
import moment from "moment";
import {getLinkedUsers, getUser} from "./users.be";
import {getSpecificUsers} from "./users.be";
import { getLinkedUsers, getUser } from "./users.be";
import { getSpecificUsers } from "./users.be";
const db = client.db(process.env.MONGODB_DB);
const addEntityToGroupPipeline = [
{
$lookup: {
from: "entities",
localField: "entity",
foreignField: "id",
as: "entity"
}
},
{
$addFields: {
entity: { $arrayElemAt: ["$entity", 0] }
}
},
{
$addFields: {
entity: {
$cond: {
if: { $isArray: "$entity" },
then: undefined,
else: "$entity"
}
}
}
}
]
export const updateExpiryDateOnGroup = async (participantID: string, corporateID: string) => {
const corporate = await db.collection("users").findOne<User>({id: corporateID});
const participant = await db.collection("users").findOne<User>({id: participantID});
const corporate = await db.collection("users").findOne<User>({ id: corporateID });
const participant = await db.collection("users").findOne<User>({ id: participantID });
if (!corporate || !participant) return;
if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;
if (!corporate || !participant) return;
if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;
if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate)
return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: null}});
if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate)
return await db.collection("users").updateOne({ id: participant.id }, { $set: { subscriptionExpirationDate: null } });
const corporateDate = moment(corporate.subscriptionExpirationDate);
const participantDate = moment(participant.subscriptionExpirationDate);
const corporateDate = moment(corporate.subscriptionExpirationDate);
const participantDate = moment(participant.subscriptionExpirationDate);
if (corporateDate.isAfter(participantDate))
return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: corporateDate.toISOString()}});
if (corporateDate.isAfter(participantDate))
return await db.collection("users").updateOne({ id: participant.id }, { $set: { subscriptionExpirationDate: corporateDate.toISOString() } });
return;
return;
};
export const getUserCorporate = async (id: string) => {
const user = await getUser(id);
if (!user) return undefined;
const user = await getUser(id);
if (!user) return undefined;
if (["admin", "developer"].includes(user.type)) return undefined;
if (user.type === "mastercorporate") return user;
if (["admin", "developer"].includes(user.type)) return undefined;
if (user.type === "mastercorporate") return user;
const groups = await getParticipantGroups(id);
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"))
.filter((x) => !!x) as User[];
const groups = await getParticipantGroups(id);
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"))
.filter((x) => !!x) as User[];
if (corporates.length === 0) return undefined;
return corporates.shift() as CorporateUser | MasterCorporateUser;
if (corporates.length === 0) return undefined;
return corporates.shift() as CorporateUser | MasterCorporateUser;
};
export const getGroup = async (id: string) => {
return await db.collection("groups").findOne<Group>({id});
return await db.collection("groups").findOne<Group>({ id });
};
export const getGroups = async () => {
return await db.collection("groups").find<Group>({}).toArray();
export const getGroups = async (): Promise<WithEntity<Group>[]> => {
return await db.collection("groups")
.aggregate<WithEntity<Group>>(addEntityToGroupPipeline).toArray()
};
export const getParticipantGroups = async (id: string) => {
return await db.collection("groups").find<Group>({participants: id}).toArray();
return await db.collection("groups").find<Group>({ participants: id }).toArray();
};
export const getUserGroups = async (id: string): Promise<Group[]> => {
return await db.collection("groups").find<Group>({admin: id}).toArray();
return await db.collection("groups").find<Group>({ admin: id }).toArray();
};
export const getUserNamedGroup = async (id: string, name: string) => {
return await db.collection("groups").findOne<Group>({admin: id, name});
return await db.collection("groups").findOne<Group>({ admin: id, name });
};
export const removeParticipantFromGroup = async (id: string, user: string) => {
return await db.collection("groups").updateOne({id}, {
// @ts-expect-error
$pull: {
participants: user
}
})
}
export const getUsersGroups = async (ids: string[]) => {
return await db
.collection("groups")
.find<Group>({admin: {$in: ids}})
.toArray();
return await db
.collection("groups")
.find<Group>({ admin: { $in: ids } })
.toArray();
};
export const convertToUsers = (group: Group, users: User[]): GroupWithUsers =>
Object.assign(group, {
admin: users.find((u) => u.id === group.admin),
participants: group.participants.map((p) => users.find((u) => u.id === p)).filter((x) => !!x) as User[],
});
Object.assign(group, {
admin: users.find((u) => u.id === group.admin),
participants: group.participants.map((p) => users.find((u) => u.id === p)).filter((x) => !!x) as User[],
});
export const getAllAssignersByCorporate = async (corporateID: string, type: Type): Promise<string[]> => {
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
};
export const getGroupsForEntities = async (ids: string[]) =>
await db
.collection("groups")
.find<Group>({entity: {$in: ids}})
.toArray();
await db
.collection("groups")
.find<Group>({ entity: { $in: ids } })
.toArray();
export const getGroupsForUser = async (admin?: string, participant?: string) => {
if (admin && participant) return await db.collection("groups").find<Group>({admin, participant}).toArray();
if (admin && participant) return await db.collection("groups").find<Group>({ admin, participant }).toArray();
if (admin) return await getUserGroups(admin);
if (participant) return await getParticipantGroups(participant);
if (admin) return await getUserGroups(admin);
if (participant) return await getParticipantGroups(participant);
return await getGroups();
return await getGroups();
};
export const getStudentGroupsForUsersWithoutAdmin = async (admin: string, participants: string[]) => {
return await db
.collection("groups")
.find<Group>({...(admin ? {admin: {$ne: admin}} : {}), ...(participants ? {participants} : {})})
.toArray();
return await db
.collection("groups")
.find<Group>({ ...(admin ? { admin: { $ne: admin } } : {}), ...(participants ? { participants } : {}) })
.toArray();
};
export const getCorporateNameForStudent = async (studentID: string) => {
const groups = await getStudentGroupsForUsersWithoutAdmin("", [studentID]);
if (groups.length === 0) return "";
const groups = await getStudentGroupsForUsersWithoutAdmin("", [studentID]);
if (groups.length === 0) return "";
const adminUserIds = [...new Set(groups.map((g) => g.admin))];
const adminUsersData = (await getSpecificUsers(adminUserIds)).filter((x) => !!x) as User[];
const adminUserIds = [...new Set(groups.map((g) => g.admin))];
const adminUsersData = (await getSpecificUsers(adminUserIds)).filter((x) => !!x) as User[];
if (adminUsersData.length === 0) return "";
const admins = adminUsersData.filter((x) => x.type === "corporate");
if (adminUsersData.length === 0) return "";
const admins = adminUsersData.filter((x) => x.type === "corporate");
if (admins.length > 0) {
return (admins[0] as CorporateUser).corporateInformation.companyInformation.name;
}
if (admins.length > 0) {
return (admins[0] as CorporateUser).corporateInformation.companyInformation.name;
}
return "";
return "";
};
export const getGroupsByEntity = async (id: string) => await db.collection("groups").find<Group>({entity: id}).toArray();
export const getGroupsByEntity = async (id: string) => await db.collection("groups").find<Group>({ entity: id }).toArray();
export const getGroupsByEntities = async (ids: string[]) =>
await db
.collection("groups")
.find<Group>({entity: {$in: ids}})
.toArray();
export const getGroupsByEntities = async (ids: string[]): Promise<WithEntity<Group>[]> =>
await db.collection("groups")
.aggregate<WithEntity<Group>>([
{ $match: { entity: { $in: ids } } },
...addEntityToGroupPipeline
]).toArray()

View File

@@ -44,7 +44,7 @@ export const convertBase64 = (file: File) => {
});
};
export const mapBy = <T>(obj: T[] | undefined, key: keyof T) => (obj || []).map((i) => i[key]);
export const mapBy = <T, K extends keyof T>(obj: T[] | undefined, key: K) => (obj || []).map((i) => i[key] as T[K]);
export const filterBy = <T>(obj: T[], key: keyof T, value: any) => obj.filter((i) => i[key] === value);
export const serialize = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));

View File

@@ -1,140 +1,140 @@
import {CorporateUser, Type, User} from "@/interfaces/user";
import {getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups} from "./groups.be";
import {uniq} from "lodash";
import {getUserCodes} from "./codes.be";
import { CorporateUser, Type, User } from "@/interfaces/user";
import { getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups } from "./groups.be";
import { uniq } from "lodash";
import { getUserCodes } from "./codes.be";
import client from "@/lib/mongodb";
import {WithEntity} from "@/interfaces/entity";
import {getEntity} from "./entities.be";
import {getRole} from "./roles.be";
import { WithEntities } from "@/interfaces/entity";
import { getEntity } from "./entities.be";
import { getRole } from "./roles.be";
const db = client.db(process.env.MONGODB_DB);
export async function getUsers() {
return await db
.collection("users")
.find<User>({}, {projection: {_id: 0}})
.toArray();
export async function getUsers(filter?: object) {
return await db
.collection("users")
.find<User>(filter || {}, { projection: { _id: 0 } })
.toArray();
}
export async function getUserWithEntity(id: string): Promise<WithEntity<User> | undefined> {
const user = await db.collection("users").findOne<User>({id: id}, {projection: {_id: 0}});
if (!user) return undefined;
export async function getUserWithEntity(id: string): Promise<WithEntities<User> | undefined> {
const user = await db.collection("users").findOne<User>({ id: id }, { projection: { _id: 0 } });
if (!user) return undefined;
const entities = await Promise.all(
user.entities.map(async (e) => {
const entity = await getEntity(e.id);
const role = await getRole(e.role);
const entities = await Promise.all(
user.entities.map(async (e) => {
const entity = await getEntity(e.id);
const role = await getRole(e.role);
return {entity, role};
}),
);
return { entity, role };
}),
);
return {...user, entities};
return { ...user, entities };
}
export async function getUser(id: string): Promise<User | undefined> {
const user = await db.collection("users").findOne<User>({id: id}, {projection: {_id: 0}});
return !!user ? user : undefined;
const user = await db.collection("users").findOne<User>({ id: id }, { projection: { _id: 0 } });
return !!user ? user : undefined;
}
export async function getSpecificUsers(ids: string[]) {
if (ids.length === 0) return [];
if (ids.length === 0) return [];
return await db
.collection("users")
.find<User>({id: {$in: ids}}, {projection: {_id: 0}})
.toArray();
return await db
.collection("users")
.find<User>({ id: { $in: ids } }, { projection: { _id: 0 } })
.toArray();
}
export async function getEntityUsers(id: string, limit?: number) {
return await db
.collection("users")
.find<User>({"entities.id": id})
.limit(limit || 0)
.toArray();
return await db
.collection("users")
.find<User>({ "entities.id": id })
.limit(limit || 0)
.toArray();
}
export async function countEntityUsers(id: string) {
return await db.collection("users").countDocuments({"entities.id": id});
return await db.collection("users").countDocuments({ "entities.id": id });
}
export async function getEntitiesUsers(ids: string[], limit?: number) {
return await db
.collection("users")
.find<User>({"entities.id": {$in: ids}})
.limit(limit || 0)
.toArray();
export async function getEntitiesUsers(ids: string[], filter?: object, limit?: number) {
return await db
.collection("users")
.find<User>({ "entities.id": { $in: ids }, ...(filter || {}) })
.limit(limit || 0)
.toArray();
}
export async function countEntitiesUsers(ids: string[]) {
return await db.collection("users").countDocuments({"entities.id": {$in: ids}});
return await db.collection("users").countDocuments({ "entities.id": { $in: ids } });
}
export async function getLinkedUsers(
userID?: string,
userType?: Type,
type?: Type,
page?: number,
size?: number,
sort?: string,
direction?: "asc" | "desc",
userID?: string,
userType?: Type,
type?: Type,
page?: number,
size?: number,
sort?: string,
direction?: "asc" | "desc",
) {
const filters = {
...(!!type ? {type} : {}),
};
const filters = {
...(!!type ? { type } : {}),
};
if (!userID || userType === "admin" || userType === "developer") {
const users = await db
.collection("users")
.find<User>(filters)
.sort(sort ? {[sort]: direction === "desc" ? -1 : 1} : {})
.skip(page && size ? page * size : 0)
.limit(size || 0)
.toArray();
if (!userID || userType === "admin" || userType === "developer") {
const users = await db
.collection("users")
.find<User>(filters)
.sort(sort ? { [sort]: direction === "desc" ? -1 : 1 } : {})
.skip(page && size ? page * size : 0)
.limit(size || 0)
.toArray();
const total = await db.collection("users").countDocuments(filters);
return {users, total};
}
const total = await db.collection("users").countDocuments(filters);
return { users, total };
}
const adminGroups = await getUserGroups(userID);
const groups = await getUsersGroups(adminGroups.flatMap((x) => x.participants));
const belongingGroups = await getParticipantGroups(userID);
const adminGroups = await getUserGroups(userID);
const groups = await getUsersGroups(adminGroups.flatMap((x) => x.participants));
const belongingGroups = await getParticipantGroups(userID);
const participants = uniq([
...adminGroups.flatMap((x) => x.participants),
...(userType === "mastercorporate" ? groups.flat().flatMap((x) => x.participants) : []),
...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
]);
const participants = uniq([
...adminGroups.flatMap((x) => x.participants),
...(userType === "mastercorporate" ? groups.flat().flatMap((x) => x.participants) : []),
...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
]);
// [FirebaseError: Invalid Query. A non-empty array is required for 'in' filters.] {
if (participants.length === 0) return {users: [], total: 0};
// [FirebaseError: Invalid Query. A non-empty array is required for 'in' filters.] {
if (participants.length === 0) return { users: [], total: 0 };
const users = await db
.collection("users")
.find<User>({...filters, id: {$in: participants}})
.skip(page && size ? page * size : 0)
.limit(size || 0)
.toArray();
const total = await db.collection("users").countDocuments({...filters, id: {$in: participants}});
const users = await db
.collection("users")
.find<User>({ ...filters, id: { $in: participants } })
.skip(page && size ? page * size : 0)
.limit(size || 0)
.toArray();
const total = await db.collection("users").countDocuments({ ...filters, id: { $in: participants } });
return {users, total};
return { users, total };
}
export async function getUserBalance(user: User) {
const codes = await getUserCodes(user.id);
if (user.type !== "corporate" && user.type !== "mastercorporate") return codes.length;
const codes = await getUserCodes(user.id);
if (user.type !== "corporate" && user.type !== "mastercorporate") return codes.length;
const groups = await getGroupsForUser(user.id);
const participants = uniq(groups.flatMap((x) => x.participants));
const groups = await getGroupsForUser(user.id);
const participants = uniq(groups.flatMap((x) => x.participants));
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 corporateUsers = participantUsers.filter((x) => x?.type === "corporate") as CorporateUser[];
const participantUsers = await Promise.all(participants.map(getUser));
const corporateUsers = participantUsers.filter((x) => x?.type === "corporate") as CorporateUser[];
return (
corporateUsers.reduce((acc, curr) => acc + curr.corporateInformation?.companyInformation?.userAmount || 0, 0) +
corporateUsers.length +
codes.filter((x) => !participants.includes(x.userId || "") && !corporateUsers.map((u) => u.id).includes(x.userId || "")).length
);
return (
corporateUsers.reduce((acc, curr) => acc + curr.corporateInformation?.companyInformation?.userAmount || 0, 0) +
corporateUsers.length +
codes.filter((x) => !participants.includes(x.userId || "") && !corporateUsers.map((u) => u.id).includes(x.userId || "")).length
);
}

View File

@@ -1,45 +1,46 @@
import {Group, User} from "@/interfaces/user";
import {getUserCompanyName, USER_TYPE_LABELS} from "@/resources/user";
import {capitalize} from "lodash";
import { WithLabeledEntities } from "@/interfaces/entity";
import { Group, User } from "@/interfaces/user";
import { getUserCompanyName, USER_TYPE_LABELS } from "@/resources/user";
import { capitalize } from "lodash";
import moment from "moment";
export interface UserListRow {
name: string;
email: string;
type: string;
companyName: string;
expiryDate: string;
verified: string;
country: string;
phone: string;
employmentPosition: string;
gender: string;
name: string;
email: string;
type: string;
entities: string;
expiryDate: string;
verified: string;
country: string;
phone: string;
employmentPosition: string;
gender: string;
}
export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group[]) => {
const rows: UserListRow[] = rowUsers.map((user) => ({
name: user.name,
email: user.email,
type: USER_TYPE_LABELS[user.type],
companyName: getUserCompanyName(user, users, groups),
expiryDate: user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited",
country: user.demographicInformation?.country || "N/A",
phone: user.demographicInformation?.phone || "N/A",
employmentPosition:
(user.type === "corporate" || user.type === "mastercorporate"
? user.demographicInformation?.position
: user.demographicInformation?.employment) || "N/A",
gender: user.demographicInformation?.gender ? capitalize(user.demographicInformation.gender) : "N/A",
verified: user.isVerified?.toString() || "FALSE",
}));
const header = "Name,Email,Type,Company Name,Expiry Date,Country,Phone,Employment/Department,Gender,Verification";
const rowsString = rows.map((x) => Object.values(x).join(",")).join("\n");
export const exportListToExcel = (rowUsers: WithLabeledEntities<User>[]) => {
const rows: UserListRow[] = rowUsers.map((user) => ({
name: user.name,
email: user.email,
type: USER_TYPE_LABELS[user.type],
entities: user.entities.map((e) => e.label).join(', '),
expiryDate: user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited",
country: user.demographicInformation?.country || "N/A",
phone: user.demographicInformation?.phone || "N/A",
employmentPosition:
(user.type === "corporate" || user.type === "mastercorporate"
? user.demographicInformation?.position
: user.demographicInformation?.employment) || "N/A",
gender: user.demographicInformation?.gender ? capitalize(user.demographicInformation.gender) : "N/A",
verified: user.isVerified?.toString() || "FALSE",
}));
const header = "Name,Email,Type,Entities,Expiry Date,Country,Phone,Employment/Department,Gender,Verification";
const rowsString = rows.map((x) => Object.values(x).join(",")).join("\n");
return `${header}\n${rowsString}`;
return `${header}\n${rowsString}`;
};
export const getUserName = (user?: User) => {
if (!user) return "N/A";
if (user.type === "corporate" || user.type === "mastercorporate") return user.corporateInformation?.companyInformation?.name || user.name;
return user.name;
if (!user) return "N/A";
if (user.type === "corporate" || user.type === "mastercorporate") return user.corporateInformation?.companyInformation?.name || user.name;
return user.name;
};