Continued updating the code to work with entities better
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import {useListSearch} from "@/hooks/useListSearch";
|
||||
import usePagination from "@/hooks/usePagination";
|
||||
import { clsx } from "clsx";
|
||||
import {ReactNode} from "react";
|
||||
import Checkbox from "../Low/Checkbox";
|
||||
import Separator from "../Low/Separator";
|
||||
@@ -10,20 +11,21 @@ interface Props<T> {
|
||||
pageSize?: number;
|
||||
firstCard?: () => ReactNode;
|
||||
renderCard: (item: T) => ReactNode;
|
||||
className?: string
|
||||
}
|
||||
|
||||
export default function CardList<T>({list, searchFields, renderCard, firstCard, pageSize = 20}: Props<T>) {
|
||||
export default function CardList<T>({list, searchFields, renderCard, firstCard, className, pageSize = 20}: Props<T>) {
|
||||
const {rows, renderSearch} = useListSearch(searchFields, list);
|
||||
|
||||
const {items, page, renderMinimal} = usePagination(rows, pageSize);
|
||||
const {items, page, render, renderMinimal} = usePagination(rows, pageSize);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-4 w-full">
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
{searchFields.length > 0 && renderSearch()}
|
||||
{searchFields.length > 0 ? renderMinimal() : render()}
|
||||
</div>
|
||||
<div className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div className={clsx("w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4", className)}>
|
||||
{page === 0 && !!firstCard && firstCard()}
|
||||
{items.map(renderCard)}
|
||||
</div>
|
||||
|
||||
107
src/components/High/Table.tsx
Normal file
107
src/components/High/Table.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import { useListSearch } from "@/hooks/useListSearch"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, PaginationState, useReactTable } from "@tanstack/react-table"
|
||||
import clsx from "clsx"
|
||||
import { useState } from "react"
|
||||
import { BsArrowDown, BsArrowUp } from "react-icons/bs"
|
||||
import Button from "../Low/Button"
|
||||
|
||||
interface Props<T> {
|
||||
data: T[]
|
||||
columns: ColumnDef<any, any>[]
|
||||
searchFields: string[][]
|
||||
size?: number
|
||||
onDownload?: (rows: T[]) => void
|
||||
}
|
||||
|
||||
export default function Table<T>({ data, columns, searchFields, size = 16, onDownload }: Props<T>) {
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: 16,
|
||||
})
|
||||
|
||||
const { rows, renderSearch } = useListSearch<T>(searchFields, data);
|
||||
|
||||
const table = useReactTable({
|
||||
data: rows,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
onPaginationChange: setPagination,
|
||||
state: {
|
||||
pagination
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<div className="w-full flex gap-2 items-end">
|
||||
{renderSearch()}
|
||||
{onDownload && (
|
||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={() => onDownload(rows)}>
|
||||
Download List
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
|
||||
<div className="w-full flex gap-2 justify-between items-center">
|
||||
<div className="flex items-center gap-4 w-fit">
|
||||
<Button className="w-[200px] h-fit" disabled={!table.getCanPreviousPage()} onClick={() => table.previousPage()}>
|
||||
Previous Page
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 w-fit">
|
||||
<span className="flex items-center gap-1">
|
||||
<div>Page</div>
|
||||
<strong>
|
||||
{table.getState().pagination.pageIndex + 1} of{' '}
|
||||
{table.getPageCount().toLocaleString()}
|
||||
</strong>
|
||||
<div>| Total: {table.getRowCount().toLocaleString()}</div>
|
||||
</span>
|
||||
<Button className="w-[200px]" disabled={!table.getCanNextPage()} onClick={() => table.nextPage()}>
|
||||
Next Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="py-4 px-4 text-left" key={header.id} colSpan={header.colSpan}>
|
||||
<div
|
||||
className={clsx(header.column.getCanSort() && 'cursor-pointer select-none', 'flex items-center gap-2')}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
{{
|
||||
asc: <BsArrowUp />,
|
||||
desc: <BsArrowDown />,
|
||||
}[header.column.getIsSorted() as string] ?? null}
|
||||
</div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="px-2 w-full">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2 items-center w-fit" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { User } from "@/interfaces/user";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import Select from "../Low/Select";
|
||||
import { ReactNode, useEffect, useState } from "react";
|
||||
import { ReactNode, useEffect, useMemo, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useRecordStore from "@/stores/recordStore";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { mapBy } from "@/utils";
|
||||
|
||||
|
||||
type TimeFilter = "months" | "weeks" | "days";
|
||||
@@ -13,6 +15,8 @@ type Filter = TimeFilter | "assignments" | undefined;
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
entities: EntityWithRoles[]
|
||||
users: User[]
|
||||
filterState: {
|
||||
filter: Filter,
|
||||
setFilter: React.Dispatch<React.SetStateAction<Filter>>
|
||||
@@ -28,83 +32,41 @@ const defaultSelectableCorporate = {
|
||||
|
||||
const RecordFilter: React.FC<Props> = ({
|
||||
user,
|
||||
entities,
|
||||
users,
|
||||
filterState,
|
||||
assignments = true,
|
||||
children
|
||||
}) => {
|
||||
const { filter, setFilter } = filterState;
|
||||
|
||||
const [statsUserId, setStatsUserId] = useRecordStore((state) => [
|
||||
const [entity, setEntity] = useState<string>()
|
||||
|
||||
const [, setStatsUserId] = useRecordStore((state) => [
|
||||
state.selectedUser,
|
||||
state.setSelectedUser
|
||||
]);
|
||||
|
||||
const { users } = useUsers();
|
||||
const { groups: allGroups } = useGroups({});
|
||||
const { groups } = useGroups({ admin: user?.id, userType: user?.type });
|
||||
const entityUsers = useMemo(() => !entity ? users : users.filter(u => mapBy(u.entities, 'id').includes(entity)), [users, entity])
|
||||
|
||||
useEffect(() => setStatsUserId(user.id), [setStatsUserId, user.id])
|
||||
|
||||
const toggleFilter = (value: "months" | "weeks" | "days" | "assignments") => {
|
||||
setFilter((prev) => (prev === value ? undefined : value));
|
||||
};
|
||||
|
||||
const selectableCorporates = [
|
||||
defaultSelectableCorporate,
|
||||
...users
|
||||
.filter((x) => groups.flatMap((g) => [g.admin, ...g.participants]).includes(x.id))
|
||||
.filter((x) => x.type === "corporate")
|
||||
.map((x) => ({
|
||||
value: x.id,
|
||||
label: `${x.name} - ${x.email}`,
|
||||
})),
|
||||
];
|
||||
|
||||
const [selectedCorporate, setSelectedCorporate] = useState<string>(defaultSelectableCorporate.value);
|
||||
|
||||
const getUsersList = (): User[] => {
|
||||
if (selectedCorporate) {
|
||||
const selectedCorporateGroups = allGroups.filter((x) => x.admin === selectedCorporate);
|
||||
const selectedCorporateGroupsParticipants = selectedCorporateGroups.flatMap((x) => x.participants);
|
||||
|
||||
const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => users.find((y) => y.id === x)) as User[];
|
||||
return userListWithUsers.filter((x) => x);
|
||||
}
|
||||
|
||||
return user.type !== "mastercorporate" ? users : users.filter((x) => groups.flatMap((g) => [g.admin, ...g.participants]).includes(x.id));
|
||||
};
|
||||
|
||||
const corporateFilteredUserList = getUsersList();
|
||||
|
||||
const getSelectedUser = () => {
|
||||
if (selectedCorporate) {
|
||||
const userInCorporate = corporateFilteredUserList.find((x) => x.id === statsUserId);
|
||||
return userInCorporate || corporateFilteredUserList[0];
|
||||
}
|
||||
|
||||
return users.find((x) => x.id === statsUserId) || user;
|
||||
};
|
||||
|
||||
const selectedUser = getSelectedUser();
|
||||
const selectedUserSelectValue = selectedUser
|
||||
? {
|
||||
value: selectedUser.id,
|
||||
label: `${selectedUser.name} - ${selectedUser.email}`,
|
||||
}
|
||||
: {
|
||||
value: "",
|
||||
label: "",
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex -xl:flex-col -xl:gap-4 justify-between items-center">
|
||||
<div className="xl:w-3/4">
|
||||
<div className="xl:w-3/4 flex gap-2">
|
||||
{checkAccess(user, ["developer", "admin", "mastercorporate"]) && !children && (
|
||||
<>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Corporate</label>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Entity</label>
|
||||
|
||||
<Select
|
||||
options={selectableCorporates}
|
||||
value={selectableCorporates.find((x) => x.value === selectedCorporate)}
|
||||
onChange={(value) => setSelectedCorporate(value?.value || "")}
|
||||
options={entities.map((e) => ({value: e.id, label: e.label}))}
|
||||
onChange={(value) => setEntity(value?.value || undefined)}
|
||||
isClearable
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
option: (styles, state) => ({
|
||||
@@ -112,15 +74,17 @@ const RecordFilter: React.FC<Props> = ({
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}></Select>
|
||||
}} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">User</label>
|
||||
|
||||
<Select
|
||||
options={corporateFilteredUserList.map((x) => ({
|
||||
options={entityUsers.map((x) => ({
|
||||
value: x.id,
|
||||
label: `${x.name} - ${x.email}`,
|
||||
}))}
|
||||
value={selectedUserSelectValue}
|
||||
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
|
||||
onChange={(value) => setStatsUserId(value?.value!)}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
@@ -131,20 +95,20 @@ const RecordFilter: React.FC<Props> = ({
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && !children && (
|
||||
<>
|
||||
{(user.type === "corporate" || user.type === "teacher") && !children && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="font-normal text-base text-mti-gray-dim">User</label>
|
||||
|
||||
<Select
|
||||
options={users
|
||||
.filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
|
||||
.map((x) => ({
|
||||
value: x.id,
|
||||
label: `${x.name} - ${x.email}`,
|
||||
}))}
|
||||
value={selectedUserSelectValue}
|
||||
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
|
||||
onChange={(value) => setStatsUserId(value?.value!)}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
@@ -155,7 +119,7 @@ const RecordFilter: React.FC<Props> = ({
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
|
||||
30
src/components/UserDisplayList.tsx
Normal file
30
src/components/UserDisplayList.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
/** eslint-disable @next/next/no-img-element */
|
||||
import { User } from "@/interfaces/user"
|
||||
|
||||
interface Props {
|
||||
users: User[]
|
||||
title: string;
|
||||
}
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default function UserDisplayList({ title, users }: Props) {
|
||||
return (<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">{title}</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.slice(0, 10)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>)
|
||||
}
|
||||
23
src/hooks/useEntities.tsx
Normal file
23
src/hooks/useEntities.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Discount } from "@/interfaces/paypal";
|
||||
import { Code, Group, User } from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function useEntities(creator?: string) {
|
||||
const [entities, setEntities] = useState<EntityWithRoles[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<EntityWithRoles[]>("/api/entities?showRoles=true")
|
||||
.then((response) => setEntities(response.data))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [creator]);
|
||||
|
||||
return { entities, isLoading, isError, reload: getData };
|
||||
}
|
||||
23
src/hooks/useEntitiesGroups.tsx
Normal file
23
src/hooks/useEntitiesGroups.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { EntityWithRoles, WithEntity, WithLabeledEntities } from "@/interfaces/entity";
|
||||
import { Discount } from "@/interfaces/paypal";
|
||||
import { Code, Group, Type, User } from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function useEntitiesGroups() {
|
||||
const [groups, setGroups] = useState<WithEntity<Group>[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<WithEntity<Group>[]>(`/api/entities/groups`)
|
||||
.then((response) => setGroups(response.data))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, []);
|
||||
|
||||
return { groups, isLoading, isError, reload: getData };
|
||||
}
|
||||
23
src/hooks/useEntitiesUsers.tsx
Normal file
23
src/hooks/useEntitiesUsers.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { EntityWithRoles, WithLabeledEntities } from "@/interfaces/entity";
|
||||
import { Discount } from "@/interfaces/paypal";
|
||||
import { Code, Group, Type, User } from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function useEntitiesUsers(type?: Type) {
|
||||
const [users, setUsers] = useState<WithLabeledEntities<User>[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<WithLabeledEntities<User>[]>(`/api/entities/users${type ? "?type=" + type : ""}`)
|
||||
.then((response) => setUsers(response.data))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [type]);
|
||||
|
||||
return { users, isLoading, isError, reload: getData };
|
||||
}
|
||||
@@ -12,8 +12,17 @@ export interface Role {
|
||||
|
||||
export interface EntityWithRoles extends Entity {
|
||||
roles: Role[];
|
||||
}
|
||||
};
|
||||
|
||||
export type WithEntity<T> = T extends {entities: {id: string; role: string}[]}
|
||||
? Omit<T, "entities"> & {entities: {entity?: Entity; role?: Role}[]}
|
||||
export type WithLabeledEntities<T> = T extends { entities: { id: string; role: string }[] }
|
||||
? Omit<T, "entities"> & { entities: { id: string; label?: string; role: string, roleLabel?: string }[] }
|
||||
: T;
|
||||
|
||||
|
||||
export type WithEntity<T> = T extends { entity?: string }
|
||||
? Omit<T, "entity"> & { entity: Entity }
|
||||
: T;
|
||||
|
||||
export type WithEntities<T> = T extends { entities: { id: string; role: string }[] }
|
||||
? Omit<T, "entities"> & { entities: { entity?: Entity; role?: Role }[] }
|
||||
: T;
|
||||
|
||||
@@ -3,49 +3,30 @@ import Input from "@/components/Low/Input";
|
||||
import Modal from "@/components/Modal";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {CorporateUser, Group, User} from "@/interfaces/user";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import { CorporateUser, Group, User } from "@/interfaces/user";
|
||||
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import {capitalize, uniq} from "lodash";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {BsPencil, BsQuestionCircleFill, BsTrash} from "react-icons/bs";
|
||||
import { capitalize, uniq } from "lodash";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BsPencil, BsQuestionCircleFill, BsTrash } from "react-icons/bs";
|
||||
import Select from "react-select";
|
||||
import {toast} from "react-toastify";
|
||||
import { toast } from "react-toastify";
|
||||
import readXlsxFile from "read-excel-file";
|
||||
import {useFilePicker} from "use-file-picker";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import {isAgentUser, isCorporateUser, USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import { useFilePicker } from "use-file-picker";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import { isAgentUser, isCorporateUser, USER_TYPE_LABELS } from "@/resources/user";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import {useListSearch} from "@/hooks/useListSearch";
|
||||
import { useListSearch } from "@/hooks/useListSearch";
|
||||
import Table from "@/components/High/Table";
|
||||
import useEntitiesGroups from "@/hooks/useEntitiesGroups";
|
||||
import useEntitiesUsers from "@/hooks/useEntitiesUsers";
|
||||
import { WithEntity } from "@/interfaces/entity";
|
||||
const searchFields = [["name"]];
|
||||
|
||||
const columnHelper = createColumnHelper<Group>();
|
||||
const columnHelper = createColumnHelper<WithEntity<Group>>();
|
||||
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
|
||||
|
||||
const LinkedCorporate = ({userId, users, groups}: {userId: string; users: User[]; groups: Group[]}) => {
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const user = users.find((u) => u.id === userId);
|
||||
if (!user) return setCompanyName("");
|
||||
|
||||
if (isCorporateUser(user)) return setCompanyName(user.corporateInformation?.companyInformation?.name || user.name);
|
||||
if (isAgentUser(user)) return setCompanyName(user.agentInformation?.companyName || user.name);
|
||||
|
||||
const belongingGroups = groups.filter((x) => x.participants.includes(userId));
|
||||
const belongingGroupsAdmins = belongingGroups.map((x) => users.find((u) => u.id === x.admin)).filter((x) => !!x && isCorporateUser(x));
|
||||
|
||||
if (belongingGroupsAdmins.length === 0) return setCompanyName("");
|
||||
|
||||
const admin = belongingGroupsAdmins[0] as CorporateUser;
|
||||
setCompanyName(admin.corporateInformation?.companyInformation.name || admin.name);
|
||||
}, [userId, users, groups]);
|
||||
|
||||
return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
|
||||
};
|
||||
|
||||
interface CreateDialogProps {
|
||||
user: User;
|
||||
users: User[];
|
||||
@@ -53,13 +34,13 @@ interface CreateDialogProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
|
||||
const [name, setName] = useState<string | undefined>(group?.name || undefined);
|
||||
const [admin, setAdmin] = useState<string>(group?.admin || user.id);
|
||||
const [participants, setParticipants] = useState<string[]>(group?.participants || []);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const {openFilePicker, filesContent, clear} = useFilePicker({
|
||||
const { openFilePicker, filesContent, clear } = useFilePicker({
|
||||
accept: ".xlsx",
|
||||
multiple: false,
|
||||
readAs: "ArrayBuffer",
|
||||
@@ -108,7 +89,7 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
user.type !== "teacher"
|
||||
? "Added all teachers and students found in the file you've provided!"
|
||||
: "Added all students found in the file you've provided!",
|
||||
{toastId: "upload-success"},
|
||||
{ toastId: "upload-success" },
|
||||
);
|
||||
setIsLoading(false);
|
||||
});
|
||||
@@ -125,7 +106,7 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
return;
|
||||
}
|
||||
|
||||
(group ? axios.patch : axios.post)(group ? `/api/groups/${group.id}` : "/api/groups", {name, admin, participants})
|
||||
(group ? axios.patch : axios.post)(group ? `/api/groups/${group.id}` : "/api/groups", { name, admin, participants })
|
||||
.then(() => {
|
||||
toast.success(`Group "${name}" ${group ? "edited" : "created"} successfully`);
|
||||
return true;
|
||||
@@ -163,13 +144,13 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
value: x,
|
||||
label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
|
||||
}))}
|
||||
options={availableUsers.map((x) => ({value: x.id, label: `${x.email} - ${x.name}`}))}
|
||||
options={availableUsers.map((x) => ({ value: x.id, label: `${x.email} - ${x.name}` }))}
|
||||
onChange={(value) => setParticipants(value.map((x) => x.value))}
|
||||
isMulti
|
||||
isSearchable
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
control: (styles) => ({
|
||||
...styles,
|
||||
backgroundColor: "white",
|
||||
@@ -198,34 +179,21 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
);
|
||||
};
|
||||
|
||||
const filterTypes = ["corporate", "teacher", "mastercorporate"];
|
||||
|
||||
export default function GroupList({user}: {user: User}) {
|
||||
export default function GroupList({ user }: { user: User }) {
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [editingGroup, setEditingGroup] = useState<Group>();
|
||||
const [viewingAllParticipants, setViewingAllParticipants] = useState<string>();
|
||||
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
const { permissions } = usePermissions(user?.id || "");
|
||||
|
||||
const {users} = useUsers();
|
||||
const {groups, reload} = useGroups({
|
||||
admin: user && filterTypes.includes(user?.type) ? user.id : undefined,
|
||||
userType: user?.type,
|
||||
});
|
||||
|
||||
const {groups: corporateGroups} = useGroups({
|
||||
admin: user && filterTypes.includes(user?.type) ? user.id : undefined,
|
||||
userType: user?.type,
|
||||
adminAdmins: user?.id,
|
||||
});
|
||||
|
||||
const {rows: filteredRows, renderSearch} = useListSearch<Group>(searchFields, groups);
|
||||
const { users } = useEntitiesUsers();
|
||||
const { groups, reload } = useEntitiesGroups();
|
||||
|
||||
const deleteGroup = (group: Group) => {
|
||||
if (!confirm(`Are you sure you want to delete "${group.name}"?`)) return;
|
||||
|
||||
axios
|
||||
.delete<{ok: boolean}>(`/api/groups/${group.id}`)
|
||||
.delete<{ ok: boolean }>(`/api/groups/${group.id}`)
|
||||
.then(() => toast.success(`Group "${group.name}" deleted successfully`))
|
||||
.catch(() => toast.error("Something went wrong, please try again later!"))
|
||||
.finally(reload);
|
||||
@@ -248,9 +216,9 @@ export default function GroupList({user}: {user: User}) {
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("admin", {
|
||||
header: "Linked Corporate",
|
||||
cell: (info) => <LinkedCorporate userId={info.getValue()} users={users} groups={groups} />,
|
||||
columnHelper.accessor("entity.label", {
|
||||
header: "Entity",
|
||||
cell: (info) => info.getValue(),
|
||||
}),
|
||||
columnHelper.accessor("participants", {
|
||||
header: "Participants",
|
||||
@@ -281,7 +249,7 @@ export default function GroupList({user}: {user: User}) {
|
||||
{
|
||||
header: "",
|
||||
id: "actions",
|
||||
cell: ({row}: {row: {original: Group}}) => {
|
||||
cell: ({ row }: { row: { original: Group } }) => {
|
||||
return (
|
||||
<>
|
||||
{user && (checkAccess(user, ["developer", "admin"]) || user.id === row.original.admin) && (
|
||||
@@ -304,12 +272,6 @@ export default function GroupList({user}: {user: User}) {
|
||||
},
|
||||
];
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredRows,
|
||||
columns: defaultColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
const closeModal = () => {
|
||||
setIsCreating(false);
|
||||
setEditingGroup(undefined);
|
||||
@@ -323,45 +285,10 @@ export default function GroupList({user}: {user: User}) {
|
||||
group={editingGroup}
|
||||
user={user}
|
||||
onClose={closeModal}
|
||||
users={
|
||||
checkAccess(user, ["corporate", "teacher", "mastercorporate"])
|
||||
? users.filter(
|
||||
(u) =>
|
||||
groups
|
||||
.filter((g) => g.admin === user.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(u.id) ||
|
||||
(user?.type === "teacher" ? corporateGroups : groups).flatMap((g) => g.participants).includes(u.id),
|
||||
)
|
||||
: users
|
||||
}
|
||||
users={users}
|
||||
/>
|
||||
</Modal>
|
||||
{renderSearch()}
|
||||
<table className="bg-mti-purple-ultralight/40 w-full rounded-xl">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="py-4" key={header.id}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="px-2">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="even:bg-mti-purple-ultralight/40 rounded-lg py-2 odd:bg-white" key={row.id}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<Table data={groups} columns={defaultColumns} searchFields={searchFields} />
|
||||
|
||||
{checkAccess(user, ["teacher", "corporate", "mastercorporate", "admin", "developer"], permissions, "createGroup") && (
|
||||
<button
|
||||
|
||||
@@ -1,52 +1,32 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {Type, User, userTypes, CorporateUser, Group} from "@/interfaces/user";
|
||||
import {Popover, Transition} from "@headlessui/react";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { Type, User } from "@/interfaces/user";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {capitalize, reverse} from "lodash";
|
||||
import { capitalize } from "lodash";
|
||||
import moment from "moment";
|
||||
import {Fragment, useEffect, useState, useMemo} from "react";
|
||||
import {BsArrowDown, BsArrowDownUp, BsArrowUp, BsCheck, BsCheckCircle, BsEye, BsFillExclamationOctagonFill, BsPerson, BsTrash} from "react-icons/bs";
|
||||
import {toast} from "react-toastify";
|
||||
import {countries, TCountries} from "countries-list";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BsCheck, BsCheckCircle, BsFillExclamationOctagonFill, BsTrash } from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import { countries, TCountries } from "countries-list";
|
||||
import countryCodes from "country-codes-list";
|
||||
import Modal from "@/components/Modal";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import {getUserCompanyName, isAgentUser, USER_TYPE_LABELS} from "@/resources/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import {useRouter} from "next/router";
|
||||
import {isCorporateUser} from "@/resources/user";
|
||||
import {useListSearch} from "@/hooks/useListSearch";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import {asyncSorter} from "@/utils";
|
||||
import {exportListToExcel, UserListRow} from "@/utils/users";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import { useRouter } from "next/router";
|
||||
import { mapBy } from "@/utils";
|
||||
import { exportListToExcel } from "@/utils/users";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import usePagination from "@/hooks/usePagination";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
import useEntitiesUsers from "@/hooks/useEntitiesUsers";
|
||||
import { WithLabeledEntities } from "@/interfaces/entity";
|
||||
import Table from "@/components/High/Table";
|
||||
|
||||
const corporatesHash = {
|
||||
type: "corporate",
|
||||
};
|
||||
|
||||
const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => {
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const name = getUserCompanyName(user, users, groups);
|
||||
setCompanyName(name);
|
||||
}, [user, users, groups]);
|
||||
|
||||
return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
|
||||
};
|
||||
const columnHelper = createColumnHelper<WithLabeledEntities<User>>();
|
||||
const searchFields = [["name"], ["email"], ["entities", ""]];
|
||||
|
||||
export default function UserList({
|
||||
user,
|
||||
@@ -60,28 +40,12 @@ export default function UserList({
|
||||
renderHeader?: (total: number) => JSX.Element;
|
||||
}) {
|
||||
const [showDemographicInformation, setShowDemographicInformation] = useState(false);
|
||||
const [sorter, setSorter] = useState<string>();
|
||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
|
||||
const userHash = useMemo(
|
||||
() => ({
|
||||
type,
|
||||
}),
|
||||
[type],
|
||||
);
|
||||
const { users, reload } = useEntitiesUsers(type)
|
||||
|
||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||
const {users: corporates} = useUsers(corporatesHash);
|
||||
|
||||
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
||||
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
const {balance} = useUserBalance();
|
||||
const {groups} = useGroups({
|
||||
admin: user && ["corporate", "teacher", "mastercorporate"].includes(user?.type) ? user.id : undefined,
|
||||
userType: user?.type,
|
||||
});
|
||||
const { permissions } = usePermissions(user?.id || "");
|
||||
const { balance } = useUserBalance();
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
@@ -96,36 +60,26 @@ export default function UserList({
|
||||
if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (users && users.length > 0) {
|
||||
const filteredUsers = filters.reduce((d, f) => d.filter(f), users);
|
||||
// const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
||||
|
||||
setDisplayUsers([...filteredUsers]);
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [users, sorter]);
|
||||
const displayUsers = useMemo(() => filters.length > 0 ? filters.reduce((d, f) => d.filter(f), users) : users, [filters, users])
|
||||
|
||||
const deleteAccount = (user: User) => {
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) return;
|
||||
|
||||
axios
|
||||
.delete<{ok: boolean}>(`/api/user?id=${user.id}`)
|
||||
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`)
|
||||
.then(() => {
|
||||
toast.success("User deleted successfully!");
|
||||
reload();
|
||||
reload()
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "delete-error"});
|
||||
toast.error("Something went wrong!", { toastId: "delete-error" });
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const verifyAccount = (user: User) => {
|
||||
axios
|
||||
.post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
isVerified: true,
|
||||
})
|
||||
@@ -134,22 +88,21 @@ export default function UserList({
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "update-error"});
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const toggleDisableAccount = (user: User) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${
|
||||
user.name
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${user.name
|
||||
}'s account? This change is usually related to their payment state.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
axios
|
||||
.post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
status: user.status === "disabled" ? "active" : "disabled",
|
||||
})
|
||||
@@ -158,18 +111,11 @@ export default function UserList({
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "update-error"});
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const SorterArrow = ({name}: {name: string}) => {
|
||||
if (sorter === name) return <BsArrowUp />;
|
||||
if (sorter === reverseString(name)) return <BsArrowDown />;
|
||||
|
||||
return <BsArrowDownUp />;
|
||||
};
|
||||
|
||||
const actionColumn = ({row}: {row: {original: User}}) => {
|
||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
||||
const updateUserPermission = PERMISSIONS.updateUser[row.original.type] as {
|
||||
list: Type[];
|
||||
perm: PermissionType;
|
||||
@@ -208,13 +154,8 @@ export default function UserList({
|
||||
|
||||
const demographicColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
|
||||
<span>Name</span>
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -228,26 +169,15 @@ export default function UserList({
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.country", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "country"))}>
|
||||
<span>Country</span>
|
||||
<SorterArrow name="country" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Country",
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${
|
||||
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||
: "N/A",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.phone", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "phone"))}>
|
||||
<span>Phone</span>
|
||||
<SorterArrow name="phone" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Phone",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
@@ -256,32 +186,17 @@ export default function UserList({
|
||||
x.type === "corporate" || x.type === "mastercorporate" ? x.demographicInformation?.position : x.demographicInformation?.employment,
|
||||
{
|
||||
id: "employment",
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "employment"))}>
|
||||
<span>Employment</span>
|
||||
<SorterArrow name="employment" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Employment",
|
||||
cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "N/A",
|
||||
enableSorting: true,
|
||||
},
|
||||
),
|
||||
columnHelper.accessor("lastLogin", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "lastLogin"))}>
|
||||
<span>Last Login</span>
|
||||
<SorterArrow name="lastLogin" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Last Login",
|
||||
cell: (info) => (!!info.getValue() ? moment(info.getValue()).format("YYYY-MM-DD HH:mm") : "N/A"),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.gender", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "gender"))}>
|
||||
<span>Gender</span>
|
||||
<SorterArrow name="gender" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Gender",
|
||||
cell: (info) => capitalize(info.getValue()) || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
@@ -293,18 +208,14 @@ export default function UserList({
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false
|
||||
},
|
||||
];
|
||||
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
|
||||
<span>Name</span>
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -318,13 +229,8 @@ export default function UserList({
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "email"))}>
|
||||
<span>E-mail</span>
|
||||
<SorterArrow name="email" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
header: "E-mail",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
@@ -336,39 +242,19 @@ export default function UserList({
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("type", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "type"))}>
|
||||
<span>Type</span>
|
||||
<SorterArrow name="type" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Type",
|
||||
cell: (info) => USER_TYPE_LABELS[info.getValue()],
|
||||
}),
|
||||
columnHelper.accessor("studentID", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "studentID"))}>
|
||||
<span>Student ID</span>
|
||||
<SorterArrow name="studentID" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Student ID",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("corporateInformation.companyInformation.name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "companyName"))}>
|
||||
<span>Company</span>
|
||||
<SorterArrow name="companyName" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => <CompanyNameCell user={info.row.original} users={totalUsers} groups={groups} />,
|
||||
columnHelper.accessor("entities", {
|
||||
header: "Entities",
|
||||
cell: ({ getValue }) => mapBy(getValue(), 'label').join(', '),
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "expiryDate"))}>
|
||||
<span>Expiration</span>
|
||||
<SorterArrow name="expiryDate" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Expiration",
|
||||
cell: (info) => (
|
||||
<span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
|
||||
{!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
@@ -376,12 +262,7 @@ export default function UserList({
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("isVerified", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "verification"))}>
|
||||
<span>Verified</span>
|
||||
<SorterArrow name="verification" />
|
||||
</button>
|
||||
) as any,
|
||||
header: "Verified",
|
||||
cell: (info) => (
|
||||
<div className="flex gap-3 items-center text-mti-gray-dim text-sm self-center">
|
||||
<div
|
||||
@@ -403,131 +284,15 @@ export default function UserList({
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false
|
||||
},
|
||||
];
|
||||
|
||||
const reverseString = (str: string) => reverse(str.split("")).join("");
|
||||
|
||||
const selectSorter = (previous: string | undefined, name: string) => {
|
||||
if (!previous) return name;
|
||||
if (previous === name) return reverseString(name);
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const sortFunction = async (a: User, b: User) => {
|
||||
if (sorter === "name" || sorter === reverseString("name"))
|
||||
return sorter === "name" ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name);
|
||||
|
||||
if (sorter === "email" || sorter === reverseString("email"))
|
||||
return sorter === "email" ? a.email.localeCompare(b.email) : b.email.localeCompare(a.email);
|
||||
|
||||
if (sorter === "type" || sorter === reverseString("type"))
|
||||
return sorter === "type"
|
||||
? userTypes.findIndex((t) => a.type === t) - userTypes.findIndex((t) => b.type === t)
|
||||
: userTypes.findIndex((t) => b.type === t) - userTypes.findIndex((t) => a.type === t);
|
||||
|
||||
if (sorter === "studentID" || sorter === reverseString("studentID"))
|
||||
return sorter === "studentID"
|
||||
? (a.type === "student" ? a.studentID || "N/A" : "N/A").localeCompare(b.type === "student" ? b.studentID || "N/A" : "N/A")
|
||||
: (b.type === "student" ? b.studentID || "N/A" : "N/A").localeCompare(a.type === "student" ? a.studentID || "N/A" : "N/A");
|
||||
|
||||
if (sorter === "verification" || sorter === reverseString("verification"))
|
||||
return sorter === "verification"
|
||||
? a.isVerified.toString().localeCompare(b.isVerified.toString())
|
||||
: b.isVerified.toString().localeCompare(a.isVerified.toString());
|
||||
|
||||
if (sorter === "expiryDate" || sorter === reverseString("expiryDate")) {
|
||||
if (!a.subscriptionExpirationDate && b.subscriptionExpirationDate) return sorter === "expiryDate" ? -1 : 1;
|
||||
if (a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return sorter === "expiryDate" ? 1 : -1;
|
||||
if (!a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return 0;
|
||||
if (moment(a.subscriptionExpirationDate).isAfter(b.subscriptionExpirationDate)) return sorter === "expiryDate" ? -1 : 1;
|
||||
if (moment(b.subscriptionExpirationDate).isAfter(a.subscriptionExpirationDate)) return sorter === "expiryDate" ? 1 : -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (sorter === "lastLogin" || sorter === reverseString("lastLogin")) {
|
||||
if (!a.lastLogin && b.lastLogin) return sorter === "lastLogin" ? -1 : 1;
|
||||
if (a.lastLogin && !b.lastLogin) return sorter === "lastLogin" ? 1 : -1;
|
||||
if (!a.lastLogin && !b.lastLogin) return 0;
|
||||
if (moment(a.lastLogin).isAfter(b.lastLogin)) return sorter === "lastLogin" ? -1 : 1;
|
||||
if (moment(b.lastLogin).isAfter(a.lastLogin)) return sorter === "lastLogin" ? 1 : -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (sorter === "country" || sorter === reverseString("country")) {
|
||||
if (!a.demographicInformation?.country && b.demographicInformation?.country) return sorter === "country" ? -1 : 1;
|
||||
if (a.demographicInformation?.country && !b.demographicInformation?.country) return sorter === "country" ? 1 : -1;
|
||||
if (!a.demographicInformation?.country && !b.demographicInformation?.country) return 0;
|
||||
|
||||
return sorter === "country"
|
||||
? a.demographicInformation!.country.localeCompare(b.demographicInformation!.country)
|
||||
: b.demographicInformation!.country.localeCompare(a.demographicInformation!.country);
|
||||
}
|
||||
|
||||
if (sorter === "phone" || sorter === reverseString("phone")) {
|
||||
if (!a.demographicInformation?.phone && b.demographicInformation?.phone) return sorter === "phone" ? -1 : 1;
|
||||
if (a.demographicInformation?.phone && !b.demographicInformation?.phone) return sorter === "phone" ? 1 : -1;
|
||||
if (!a.demographicInformation?.phone && !b.demographicInformation?.phone) return 0;
|
||||
|
||||
return sorter === "phone"
|
||||
? a.demographicInformation!.phone.localeCompare(b.demographicInformation!.phone)
|
||||
: b.demographicInformation!.phone.localeCompare(a.demographicInformation!.phone);
|
||||
}
|
||||
|
||||
if (sorter === "employment" || sorter === reverseString("employment")) {
|
||||
const aSortingItem =
|
||||
a.type === "corporate" || a.type === "mastercorporate" ? a.demographicInformation?.position : a.demographicInformation?.employment;
|
||||
const bSortingItem =
|
||||
b.type === "corporate" || b.type === "mastercorporate" ? b.demographicInformation?.position : b.demographicInformation?.employment;
|
||||
|
||||
if (!aSortingItem && bSortingItem) return sorter === "employment" ? -1 : 1;
|
||||
if (aSortingItem && !bSortingItem) return sorter === "employment" ? 1 : -1;
|
||||
if (!aSortingItem && !bSortingItem) return 0;
|
||||
|
||||
return sorter === "employment" ? aSortingItem!.localeCompare(bSortingItem!) : bSortingItem!.localeCompare(aSortingItem!);
|
||||
}
|
||||
|
||||
if (sorter === "gender" || sorter === reverseString("gender")) {
|
||||
if (!a.demographicInformation?.gender && b.demographicInformation?.gender) return sorter === "employment" ? -1 : 1;
|
||||
if (a.demographicInformation?.gender && !b.demographicInformation?.gender) return sorter === "employment" ? 1 : -1;
|
||||
if (!a.demographicInformation?.gender && !b.demographicInformation?.gender) return 0;
|
||||
|
||||
return sorter === "gender"
|
||||
? a.demographicInformation!.gender.localeCompare(b.demographicInformation!.gender)
|
||||
: b.demographicInformation!.gender.localeCompare(a.demographicInformation!.gender);
|
||||
}
|
||||
|
||||
if (sorter === "companyName" || sorter === reverseString("companyName")) {
|
||||
const aCorporateName = getUserCompanyName(a, users, groups);
|
||||
const bCorporateName = getUserCompanyName(b, users, groups);
|
||||
if (!aCorporateName && bCorporateName) return sorter === "companyName" ? -1 : 1;
|
||||
if (aCorporateName && !bCorporateName) return sorter === "companyName" ? 1 : -1;
|
||||
if (!aCorporateName && !bCorporateName) return 0;
|
||||
|
||||
return sorter === "companyName" ? aCorporateName.localeCompare(bCorporateName) : bCorporateName.localeCompare(aCorporateName);
|
||||
}
|
||||
|
||||
return a.id.localeCompare(b.id);
|
||||
};
|
||||
|
||||
const {rows: filteredRows, renderSearch, text: searchText} = useListSearch<User>(searchFields, displayUsers);
|
||||
const {items, setPage, render: renderPagination} = usePagination<User>(filteredRows, 16);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => setPage(0), [searchText]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: items,
|
||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
const downloadExcel = () => {
|
||||
const csv = exportListToExcel(filteredRows, users, groups);
|
||||
const downloadExcel = (rows: WithLabeledEntities<User>[]) => {
|
||||
const csv = exportListToExcel(rows);
|
||||
|
||||
const element = document.createElement("a");
|
||||
const file = new Blob([csv], {type: "text/csv"});
|
||||
const file = new Blob([csv], { type: "text/csv" });
|
||||
element.href = URL.createObjectURL(file);
|
||||
element.download = "users.csv";
|
||||
document.body.appendChild(element);
|
||||
@@ -537,16 +302,10 @@ export default function UserList({
|
||||
|
||||
const viewStudentFilter = (x: User) => x.type === "student";
|
||||
const viewTeacherFilter = (x: User) => x.type === "teacher";
|
||||
const belongsToAdminFilter = (x: User) => {
|
||||
if (!selectedUser) return false;
|
||||
return groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id);
|
||||
};
|
||||
const belongsToAdminFilter = (x: User) => x.entities.some(({ id }) => mapBy(selectedUser?.entities || [], 'id').includes(id));
|
||||
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) => x.type === "student" && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) => x.type === "teacher" && belongsToAdminFilter(x);
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) => viewStudentFilter(x) && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) => viewTeacherFilter(x) && belongsToAdminFilter(x);
|
||||
|
||||
const renderUserCard = (selectedUser: User) => {
|
||||
const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin);
|
||||
@@ -599,11 +358,7 @@ export default function UserList({
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => [g.admin, ...g.participants])
|
||||
.includes(x.id),
|
||||
filter: belongsToAdminFilter
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
@@ -622,44 +377,17 @@ export default function UserList({
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderHeader && renderHeader(total)}
|
||||
{renderHeader && renderHeader(displayUsers.length)}
|
||||
<div className="w-full">
|
||||
<Modal isOpen={!!selectedUser} onClose={() => setSelectedUser(undefined)}>
|
||||
{selectedUser && renderUserCard(selectedUser)}
|
||||
</Modal>
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<div className="w-full flex gap-2 items-end">
|
||||
{renderSearch()}
|
||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
||||
Download List
|
||||
</Button>
|
||||
</div>
|
||||
{renderPagination()}
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="py-4 px-4 text-left" key={header.id}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="px-2 w-full">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2 items-center w-fit" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Table<WithLabeledEntities<User>>
|
||||
data={displayUsers}
|
||||
columns={(!showDemographicInformation ? defaultColumns : demographicColumns) as any}
|
||||
searchFields={searchFields}
|
||||
onDownload={downloadExcel}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,28 +1,30 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import {CorporateUser, TeacherUser, Type, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { CorporateUser, TeacherUser, Type, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {capitalize, uniqBy} from "lodash";
|
||||
import { capitalize, uniqBy } from "lodash";
|
||||
import moment from "moment";
|
||||
import {useEffect, useState} from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import {toast} from "react-toastify";
|
||||
import { toast } from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import Input from "@/components/Low/Input";
|
||||
import CountrySelect from "@/components/Low/CountrySelect";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {getUserName} from "@/utils/users";
|
||||
import { getUserName } from "@/utils/users";
|
||||
import Select from "@/components/Low/Select";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import useEntitiesGroups from "@/hooks/useEntitiesGroups";
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: {perm: PermissionType | undefined; list: Type[]};
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
@@ -57,11 +59,12 @@ const USER_TYPE_PERMISSIONS: {
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[]
|
||||
permissions: PermissionType[];
|
||||
onFinish: () => void;
|
||||
}
|
||||
|
||||
export default function UserCreator({user, users, permissions, onFinish}: Props) {
|
||||
export default function UserCreator({ user, users, entities = [], permissions, onFinish }: Props) {
|
||||
const [name, setName] = useState<string>();
|
||||
const [email, setEmail] = useState<string>();
|
||||
const [phone, setPhone] = useState<string>();
|
||||
@@ -69,8 +72,6 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
const [studentID, setStudentID] = useState<string>();
|
||||
const [country, setCountry] = useState(user?.demographicInformation?.country);
|
||||
const [group, setGroup] = useState<string | null>();
|
||||
const [availableCorporates, setAvailableCorporates] = useState<User[]>([]);
|
||||
const [selectedCorporate, setSelectedCorporate] = useState<string | null>();
|
||||
const [password, setPassword] = useState<string>();
|
||||
const [confirmPassword, setConfirmPassword] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
@@ -80,22 +81,14 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const [position, setPosition] = useState<string>();
|
||||
const [entity, setEntity] = useState((entities || [])[0]?.id || undefined)
|
||||
|
||||
const {groups} = useGroups({admin: ["developer", "admin"].includes(user?.type) ? undefined : user?.id, userType: user?.type});
|
||||
const { groups } = useEntitiesGroups();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
|
||||
useEffect(() => {
|
||||
setAvailableCorporates(
|
||||
uniqBy(
|
||||
users.filter((u) => u.type === "corporate" && groups.flatMap((g) => g.participants).includes(u.id)),
|
||||
"id",
|
||||
),
|
||||
);
|
||||
}, [users, groups]);
|
||||
|
||||
const createUser = () => {
|
||||
if (!name || name.trim().length === 0) return toast.error("Please enter a valid name!");
|
||||
if (!email || email.trim().length === 0) return toast.error("Please enter a valid e-mail address!");
|
||||
@@ -110,7 +103,7 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
email,
|
||||
password,
|
||||
groupID: group,
|
||||
corporate: selectedCorporate || user.id,
|
||||
entity,
|
||||
type,
|
||||
studentID: type === "student" ? studentID : undefined,
|
||||
expiryDate,
|
||||
@@ -135,7 +128,7 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
setStudentID("");
|
||||
setCountry(user?.demographicInformation?.country);
|
||||
setGroup(null);
|
||||
setSelectedCorporate(null);
|
||||
setEntity((entities || [])[0]?.id || undefined)
|
||||
setExpiryDate(user?.subscriptionExpirationDate ? moment(user?.subscriptionExpirationDate).toDate() : null);
|
||||
setIsExpiryDateEnabled(true);
|
||||
setType("student");
|
||||
@@ -188,38 +181,30 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
</>
|
||||
)}
|
||||
|
||||
{["student", "teacher"].includes(type) && !["corporate", "teacher"].includes(user?.type) && (
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Corporate</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Entity</label>
|
||||
<Select
|
||||
options={availableCorporates.map((u) => ({value: u.id, label: getUserName(u)}))}
|
||||
isClearable
|
||||
onChange={(e) => setSelectedCorporate(e?.value || undefined)}
|
||||
defaultValue={{ value: (entities || [])[0]?.id, label: (entities || [])[0]?.label }}
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) => setEntity(e?.value || undefined)}
|
||||
isClearable={checkAccess(user, ["admin", "developer"])}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{["corporate", "mastercorporate"].includes(type) && (
|
||||
<Input type="text" name="department" label="Department" onChange={setPosition} value={position} placeholder="Department" />
|
||||
)}
|
||||
|
||||
{!(type === "corporate" && user.type === "corporate") && (
|
||||
<div
|
||||
className={clsx(
|
||||
"flex flex-col gap-4",
|
||||
(!["student", "teacher"].includes(type) || ["corporate", "teacher"].includes(user?.type)) &&
|
||||
!["corporate", "mastercorporate"].includes(type) &&
|
||||
"col-span-2",
|
||||
)}>
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Group</label>
|
||||
<Select
|
||||
options={groups
|
||||
.filter((x) => (!selectedCorporate ? true : x.admin === selectedCorporate))
|
||||
.map((g) => ({value: g.id, label: g.name}))}
|
||||
.filter((x) => x.entity?.id === entity)
|
||||
.map((g) => ({ value: g.id, label: g.name }))}
|
||||
onChange={(e) => setGroup(e?.value || undefined)}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={clsx(
|
||||
@@ -235,7 +220,7 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white">
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, getTypesOfUser(list), permissions, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { FirebaseScrypt } from 'firebase-scrypt';
|
||||
import { firebaseAuthScryptParams } from "@/firebase";
|
||||
import crypto from 'crypto';
|
||||
@@ -11,13 +11,13 @@ export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") return post(req, res);
|
||||
|
||||
return res.status(404).json({ok: false});
|
||||
return res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
const maker = req.session.user;
|
||||
if (!maker) {
|
||||
return res.status(401).json({ok: false, reason: "You must be logged in to make user!"});
|
||||
return res.status(401).json({ ok: false, reason: "You must be logged in to make user!" });
|
||||
}
|
||||
|
||||
const scrypt = new FirebaseScrypt(firebaseAuthScryptParams)
|
||||
@@ -36,6 +36,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
passport_id?: string;
|
||||
phone: string;
|
||||
};
|
||||
entity?: string
|
||||
entities: { id: string, role: string }[]
|
||||
passwordHash: string | undefined;
|
||||
passwordSalt: string | undefined;
|
||||
}[];
|
||||
@@ -45,6 +47,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
const salt = crypto.randomBytes(16).toString('base64');
|
||||
const hash = await scrypt.hash(user.passport_id, salt);
|
||||
|
||||
currentUser.entities = [{ id: currentUser.entity!, role: "90ce8f08-08c8-41e4-9848-f1500ddc3930" }]
|
||||
delete currentUser.entity
|
||||
|
||||
currentUser.email = currentUser.email.toLowerCase();
|
||||
currentUser.passwordHash = hash;
|
||||
currentUser.passwordSalt = salt;
|
||||
|
||||
32
src/pages/api/entities/groups.ts
Normal file
32
src/pages/api/entities/groups.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { getEntities, getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { Entity, WithEntities, WithEntity, WithLabeledEntities } from "@/interfaces/entity";
|
||||
import { v4 } from "uuid";
|
||||
import { mapBy } from "@/utils";
|
||||
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
|
||||
import { Group, User } from "@/interfaces/user";
|
||||
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return await get(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const user = req.session.user;
|
||||
|
||||
const groups: WithEntity<Group>[] = ["admin", "developer"].includes(user.type)
|
||||
? await getGroups()
|
||||
: await getGroupsByEntities(mapBy(user.entities || [], 'id'))
|
||||
|
||||
res.status(200).json(groups);
|
||||
}
|
||||
47
src/pages/api/entities/users.ts
Normal file
47
src/pages/api/entities/users.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { getEntities, getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { Entity, WithEntities, WithLabeledEntities } from "@/interfaces/entity";
|
||||
import { v4 } from "uuid";
|
||||
import { mapBy } from "@/utils";
|
||||
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
|
||||
import { User } from "@/interfaces/user";
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return await get(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const user = req.session.user;
|
||||
|
||||
const { type } = req.query as { type: string }
|
||||
const entities = await getEntitiesWithRoles(mapBy(user.entities || [], 'id'))
|
||||
|
||||
const filter = !type ? undefined : { type }
|
||||
const users = ["admin", "developer"].includes(user.type)
|
||||
? await getUsers(filter)
|
||||
: await getEntitiesUsers(mapBy(entities, 'id') as string[], filter)
|
||||
|
||||
const usersWithEntities: WithLabeledEntities<User>[] = users.map((u) => {
|
||||
return {
|
||||
...u, entities: (u.entities || []).map((e) => {
|
||||
const entity = entities.find((x) => x.id === e.id)
|
||||
if (!entity) return e
|
||||
|
||||
const role = entity.roles.find((x) => x.id === e.role)
|
||||
return { id: e.id, label: entity.label, role: e.role, roleLabel: role?.label }
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
res.status(200).json(usersWithEntities);
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {v4} from "uuid";
|
||||
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
|
||||
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { v4 } from "uuid";
|
||||
import { CorporateUser, Group, Type, User } from "@/interfaces/user";
|
||||
import { createUserWithEmailAndPassword, getAuth } from "firebase/auth";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import {getGroup, getGroups, getUserCorporate, getUserGroups, getUserNamedGroup} from "@/utils/groups.be";
|
||||
import {uniq} from "lodash";
|
||||
import {getSpecificUsers, getUser} from "@/utils/users.be";
|
||||
import { getGroup, getGroups, getUserCorporate, getUserGroups, getUserNamedGroup } from "@/utils/groups.be";
|
||||
import { uniq } from "lodash";
|
||||
import { getSpecificUsers, getUser } from "@/utils/users.be";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const DEFAULT_DESIRED_LEVELS = {
|
||||
@@ -30,50 +30,41 @@ const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
const getUsersOfType = async (admin: string, type: Type) => {
|
||||
const groups = await getUserGroups(admin);
|
||||
const participants = groups.flatMap((x) => x.participants);
|
||||
const users = await getSpecificUsers(participants);
|
||||
|
||||
return users.filter((x) => x?.type === type).map((x) => x?.id);
|
||||
};
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") return post(req, res);
|
||||
|
||||
return res.status(404).json({ok: false});
|
||||
return res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
const maker = req.session.user;
|
||||
if (!maker) {
|
||||
return res.status(401).json({ok: false, reason: "You must be logged in to make user!"});
|
||||
return res.status(401).json({ ok: false, reason: "You must be logged in to make user!" });
|
||||
}
|
||||
|
||||
const corporateCorporate = await getUserCorporate(maker.id);
|
||||
|
||||
const {email, passport_id, password, type, groupID, expiryDate, corporate} = req.body as {
|
||||
const { email, passport_id, password, type, groupID, entity, expiryDate, corporate } = req.body as {
|
||||
email: string;
|
||||
password?: string;
|
||||
passport_id: string;
|
||||
type: string;
|
||||
entity: string;
|
||||
groupID?: string;
|
||||
corporate?: string;
|
||||
expiryDate: null | Date;
|
||||
};
|
||||
|
||||
// cleaning data
|
||||
delete req.body.passport_id;
|
||||
delete req.body.groupID;
|
||||
delete req.body.expiryDate;
|
||||
delete req.body.password;
|
||||
delete req.body.corporate;
|
||||
delete req.body.entity
|
||||
|
||||
await createUserWithEmailAndPassword(auth, email.toLowerCase(), !!password ? password : passport_id)
|
||||
.then(async (userCredentials) => {
|
||||
const userId = userCredentials.user.uid;
|
||||
|
||||
const profilePicture = !corporateCorporate ? "/defaultAvatar.png" : corporateCorporate.profilePicture;
|
||||
|
||||
const user = {
|
||||
...req.body,
|
||||
bio: "",
|
||||
@@ -82,11 +73,12 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
focus: "academic",
|
||||
status: "active",
|
||||
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
||||
profilePicture,
|
||||
profilePicture: "/defaultAvatar.png",
|
||||
levels: DEFAULT_LEVELS,
|
||||
isFirstLogin: false,
|
||||
isVerified: true,
|
||||
registrationDate: new Date(),
|
||||
entities: [{ id: entity, role: "90ce8f08-08c8-41e4-9848-f1500ddc3930" }],
|
||||
subscriptionExpirationDate: expiryDate || null,
|
||||
...((maker.type === "corporate" || maker.type === "mastercorporate") && type === "corporate"
|
||||
? {
|
||||
@@ -113,115 +105,22 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
userId,
|
||||
email: email.toLowerCase(),
|
||||
name: req.body.name,
|
||||
...(!!passport_id ? {passport_id} : {}),
|
||||
...(!!passport_id ? { passport_id } : {}),
|
||||
});
|
||||
|
||||
if (type === "corporate") {
|
||||
const students = maker.type === "corporate" ? await getUsersOfType(maker.id, "student") : [];
|
||||
const teachers = maker.type === "corporate" ? await getUsersOfType(maker.id, "teacher") : [];
|
||||
|
||||
const defaultTeachersGroup: Group = {
|
||||
admin: userId,
|
||||
id: v4(),
|
||||
name: "Teachers",
|
||||
participants: teachers,
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
const defaultStudentsGroup: Group = {
|
||||
admin: userId,
|
||||
id: v4(),
|
||||
name: "Students",
|
||||
participants: students,
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await db.collection("groups").insertMany([defaultStudentsGroup, defaultTeachersGroup]);
|
||||
}
|
||||
|
||||
if (!!corporate) {
|
||||
const corporateUser = await db.collection("users").findOne<CorporateUser>({email: corporate.trim().toLowerCase()});
|
||||
|
||||
if (!!corporateUser) {
|
||||
await db.collection("codes").updateOne({code}, {$set: {creator: corporateUser.id}});
|
||||
const typeGroup = await db
|
||||
.collection("groups")
|
||||
.findOne<Group>({creator: corporateUser.id, name: type === "student" ? "Students" : "Teachers"});
|
||||
|
||||
if (!!typeGroup) {
|
||||
if (!typeGroup.participants.includes(userId)) {
|
||||
await db.collection("groups").updateOne({id: typeGroup.id}, {$set: {participants: [...typeGroup.participants, userId]}});
|
||||
}
|
||||
} else {
|
||||
const defaultGroup: Group = {
|
||||
admin: corporateUser.id,
|
||||
id: v4(),
|
||||
name: type === "student" ? "Students" : "Teachers",
|
||||
participants: [userId],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await db.collection("groups").insertOne(defaultGroup);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (maker.type === "corporate") {
|
||||
await db.collection("codes").updateOne({code}, {$set: {creator: maker.id}});
|
||||
const typeGroup = await getUserNamedGroup(maker.id, type === "student" ? "Students" : "Teachers");
|
||||
|
||||
if (!!typeGroup) {
|
||||
if (!typeGroup.participants.includes(userId)) {
|
||||
await db.collection("groups").updateOne({id: typeGroup.id}, {$set: {participants: [...typeGroup.participants, userId]}});
|
||||
}
|
||||
} else {
|
||||
const defaultGroup: Group = {
|
||||
admin: maker.id,
|
||||
id: v4(),
|
||||
name: type === "student" ? "Students" : "Teachers",
|
||||
participants: [userId],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await db.collection("groups").insertOne(defaultGroup);
|
||||
}
|
||||
}
|
||||
|
||||
if (!!corporateCorporate && corporateCorporate.type === "mastercorporate" && type === "corporate") {
|
||||
const corporateGroup = await getUserNamedGroup(corporateCorporate.id, "Corporate");
|
||||
|
||||
if (!!corporateGroup) {
|
||||
if (!corporateGroup.participants.includes(userId)) {
|
||||
await db
|
||||
.collection("groups")
|
||||
.updateOne({id: corporateGroup.id}, {$set: {participants: [...corporateGroup.participants, userId]}});
|
||||
}
|
||||
} else {
|
||||
const defaultGroup: Group = {
|
||||
admin: corporateCorporate.id,
|
||||
id: v4(),
|
||||
name: "Corporate",
|
||||
participants: [userId],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await db.collection("groups").insertOne(defaultGroup);
|
||||
}
|
||||
}
|
||||
|
||||
if (!!groupID) {
|
||||
const group = await getGroup(groupID);
|
||||
if (!!group) await db.collection("groups").updateOne({id: group.id}, {$set: {participants: [...group.participants, userId]}});
|
||||
if (!!group) await db.collection("groups").updateOne({ id: group.id }, { $set: { participants: [...group.participants, userId] } });
|
||||
}
|
||||
|
||||
console.log(`Returning - ${email}`);
|
||||
return res.status(200).json({ok: true});
|
||||
return res.status(200).json({ ok: true });
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.code.includes("email-already-in-use")) return res.status(403).json({error, message: "E-mail is already in the platform."});
|
||||
if (error.code.includes("email-already-in-use")) return res.status(403).json({ error, message: "E-mail is already in the platform." });
|
||||
|
||||
console.log(`Failing - ${email}`);
|
||||
console.log(error);
|
||||
return res.status(401).json({error});
|
||||
return res.status(401).json({ error });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
import {getPermissions, getPermissionDocs} from "@/utils/permissions.be";
|
||||
import client from "@/lib/mongodb";
|
||||
import {getGroupsForUser, getParticipantGroups} from "@/utils/groups.be";
|
||||
import {getGroupsForUser, getParticipantGroups, removeParticipantFromGroup} from "@/utils/groups.be";
|
||||
import { mapBy } from "@/utils";
|
||||
|
||||
const auth = getAuth(adminApp);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
@@ -41,20 +42,6 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
|
||||
const groups = await getGroupsForUser(user.id, targetUser.id);
|
||||
await Promise.all([
|
||||
...groups
|
||||
.filter((x) => x.admin === user.id)
|
||||
.map(
|
||||
async (x) =>
|
||||
await db.collection("groups").updateOne({id: x.id}, {$set: {participants: x.participants.filter((y: string) => y !== id)}}),
|
||||
),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await auth.deleteUser(id);
|
||||
await db.collection("users").deleteOne({id: targetUser.id});
|
||||
await db.collection("codes").deleteMany({userId: targetUser.id});
|
||||
@@ -63,9 +50,8 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
const groups = await getParticipantGroups(targetUser.id);
|
||||
await Promise.all(
|
||||
groups.map(
|
||||
async (x) => await db.collection("groups").updateOne({id: x.id}, {$set: {participants: x.participants.filter((y: string) => y !== id)}}),
|
||||
),
|
||||
groups
|
||||
.map(async (g) => await removeParticipantFromGroup(g.id, targetUser.id)),
|
||||
);
|
||||
|
||||
res.json({ok: true});
|
||||
|
||||
195
src/pages/dashboard/admin.tsx
Normal file
195
src/pages/dashboard/admin.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import { Module } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import { Group, Stat, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { dateSorter, filterBy, mapBy, serialize } from "@/utils";
|
||||
import { getAssignments, getEntitiesAssignments } from "@/utils/assignments.be";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import { getStatsByUsers } from "@/utils/stats.be";
|
||||
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { uniqBy } from "lodash";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
BsBank,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsPaperclip,
|
||||
BsPencilSquare,
|
||||
BsPeople,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
} from "react-icons/bs";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const users = await getUsers();
|
||||
const entities = await getEntitiesWithRoles();
|
||||
const assignments = await getAssignments();
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroups();
|
||||
|
||||
return { props: serialize({ user, users, entities, assignments, stats, groups }) };
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({ user, users, entities, assignments, stats, groups }: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
|
||||
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
|
||||
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/list/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/list/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/list/users?type=corporate")}
|
||||
label="Corporates"
|
||||
value={corporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/list/users?type=mastercorporate")}
|
||||
label="Master Corporates"
|
||||
value={masterCorporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
||||
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={teachers.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Teachers"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))}
|
||||
title="Highest level students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={
|
||||
students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import {Module} from "@/interfaces";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {Group, Stat, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {dateSorter, filterBy, mapBy, serialize} from "@/utils";
|
||||
import {getAssignments, getEntitiesAssignments} from "@/utils/assignments.be";
|
||||
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import {getStatsByUsers} from "@/utils/stats.be";
|
||||
import {getEntitiesUsers, getUsers} from "@/utils/users.be";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {uniqBy} from "lodash";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import {useRouter} from "next/router";
|
||||
import {useMemo} from "react";
|
||||
import {
|
||||
BsBank,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsPaperclip,
|
||||
BsPencilSquare,
|
||||
BsPeople,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const users = await getUsers();
|
||||
const entities = await getEntitiesWithRoles();
|
||||
const assignments = await getAssignments();
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroups();
|
||||
|
||||
return {props: serialize({user, users, entities, assignments, stats, groups})};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({user, users, entities, assignments, stats, groups}: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
|
||||
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
|
||||
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/lists/users?type=corporate")}
|
||||
label="Corporates"
|
||||
value={corporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/lists/users?type=mastercorporate")}
|
||||
label="Master Corporates"
|
||||
value={masterCorporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
||||
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{teachers
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import { Module } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
@@ -136,14 +137,14 @@ export default function Dashboard({ user, users, entities, assignments, stats, g
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 place-items-center gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=student")}
|
||||
onClick={() => router.push("/list/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=teacher")}
|
||||
onClick={() => router.push("/list/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
@@ -178,50 +179,29 @@ export default function Dashboard({ user, users, entities, assignments, stats, g
|
||||
</div>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{teachers
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={teachers.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Teachers"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))}
|
||||
title="Highest level students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={
|
||||
students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
201
src/pages/dashboard/developer.tsx
Normal file
201
src/pages/dashboard/developer.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import { Module } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import { Group, Stat, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { dateSorter, filterBy, mapBy, serialize } from "@/utils";
|
||||
import { getAssignments, getEntitiesAssignments } from "@/utils/assignments.be";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import { getStatsByUsers } from "@/utils/stats.be";
|
||||
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { uniqBy } from "lodash";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
BsBank,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsPaperclip,
|
||||
BsPencilSquare,
|
||||
BsPeople,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
} from "react-icons/bs";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const users = await getUsers();
|
||||
const entities = await getEntitiesWithRoles();
|
||||
const assignments = await getAssignments();
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroups();
|
||||
|
||||
return { props: serialize({ user, users, entities, assignments, stats, groups }) };
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({ user, users, entities, assignments, stats, groups }: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
|
||||
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
|
||||
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/list/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/list/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/list/users?type=corporate")}
|
||||
label="Corporates"
|
||||
value={corporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/list/users?type=mastercorporate")}
|
||||
label="Master Corporates"
|
||||
value={masterCorporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPeople}
|
||||
onClick={() => router.push("/entities")}
|
||||
label="Classrooms"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={teachers.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Teachers"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))}
|
||||
title="Highest level students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={
|
||||
students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import {Module} from "@/interfaces";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {Group, Stat, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {dateSorter, filterBy, mapBy, serialize} from "@/utils";
|
||||
import {getAssignments, getEntitiesAssignments} from "@/utils/assignments.be";
|
||||
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import {getStatsByUsers} from "@/utils/stats.be";
|
||||
import {getEntitiesUsers, getUsers} from "@/utils/users.be";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {uniqBy} from "lodash";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import {useRouter} from "next/router";
|
||||
import {useMemo} from "react";
|
||||
import {
|
||||
BsBank,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsPaperclip,
|
||||
BsPencilSquare,
|
||||
BsPeople,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const users = await getUsers();
|
||||
const entities = await getEntitiesWithRoles();
|
||||
const assignments = await getAssignments();
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroups();
|
||||
|
||||
return {props: serialize({user, users, entities, assignments, stats, groups})};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({user, users, entities, assignments, stats, groups}: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
|
||||
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
|
||||
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/lists/users?type=corporate")}
|
||||
label="Corporates"
|
||||
value={corporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/lists/users?type=mastercorporate")}
|
||||
label="Master Corporates"
|
||||
value={masterCorporates.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
||||
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{teachers
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import { Module } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
@@ -133,21 +134,21 @@ export default function Dashboard({ user, users, entities, assignments, stats, g
|
||||
<Layout user={user}>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=student")}
|
||||
onClick={() => router.push("/list/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={students.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=teacher")}
|
||||
onClick={() => router.push("/list/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={teachers.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/lists/users?type=corporate")} Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" />
|
||||
onClick={() => router.push("/list/users?type=corporate")} Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" />
|
||||
<IconCard onClick={() => router.push("/classrooms")} Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
||||
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
@@ -169,50 +170,29 @@ export default function Dashboard({ user, users, entities, assignments, stats, g
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{teachers
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={teachers.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Teachers"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))}
|
||||
title="Highest level students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={
|
||||
students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
170
src/pages/dashboard/teacher.tsx
Normal file
170
src/pages/dashboard/teacher.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import { Module } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import { Group, Stat, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { dateSorter, filterBy, mapBy, serialize } from "@/utils";
|
||||
import { getEntitiesAssignments } from "@/utils/assignments.be";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { getGroupsByEntities } from "@/utils/groups.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import { getStatsByUsers } from "@/utils/stats.be";
|
||||
import { getEntitiesUsers } from "@/utils/users.be";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { uniqBy } from "lodash";
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import { BsClipboard2Data, BsEnvelopePaper, BsPaperclip, BsPeople, BsPersonFill } from "react-icons/bs";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer", "teacher"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const entityIDS = mapBy(user.entities, "id") || [];
|
||||
|
||||
const users = await getEntitiesUsers(entityIDS);
|
||||
const entities = await getEntitiesWithRoles(entityIDS);
|
||||
const assignments = await getEntitiesAssignments(entityIDS);
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroupsByEntities(entityIDS);
|
||||
|
||||
return { props: serialize({ user, users, entities, assignments, stats, groups }) };
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({ user, users, entities, assignments, stats, groups }: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<div className="w-full flex flex-col gap-4">
|
||||
{entities.length > 0 && (
|
||||
<div className="w-fit self-end bg-neutral-200 px-2 rounded-lg py-1">
|
||||
<b>{mapBy(entities, "label")?.join(", ")}</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 place-items-center gap-4 text-center">
|
||||
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
onClick={() => router.push("/classrooms")}
|
||||
Icon={BsPeople}
|
||||
label="Classrooms"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))}
|
||||
title="Latest Students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={students.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))}
|
||||
title="Highest level students"
|
||||
/>
|
||||
<UserDisplayList
|
||||
users={
|
||||
students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Layout from "@/components/High/Layout";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import {Module} from "@/interfaces";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {Group, Stat, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {dateSorter, filterBy, mapBy, serialize} from "@/utils";
|
||||
import {getEntitiesAssignments} from "@/utils/assignments.be";
|
||||
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {getGroupsByEntities} from "@/utils/groups.be";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import {getStatsByUsers} from "@/utils/stats.be";
|
||||
import {getEntitiesUsers} from "@/utils/users.be";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {uniqBy} from "lodash";
|
||||
import Head from "next/head";
|
||||
import {useRouter} from "next/router";
|
||||
import {useMemo} from "react";
|
||||
import {BsClipboard2Data, BsEnvelopePaper, BsPaperclip, BsPeople, BsPersonFill} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
assignments: Assignment[];
|
||||
stats: Stat[];
|
||||
groups: Group[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer", "teacher"]))
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const entityIDS = mapBy(user.entities, "id") || [];
|
||||
|
||||
const users = await getEntitiesUsers(entityIDS);
|
||||
const entities = await getEntitiesWithRoles(entityIDS);
|
||||
const assignments = await getEntitiesAssignments(entityIDS);
|
||||
const stats = await getStatsByUsers(users.map((u) => u.id));
|
||||
const groups = await getGroupsByEntities(entityIDS);
|
||||
|
||||
return {props: serialize({user, users, entities, assignments, stats, groups})};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({user, users, entities, assignments, stats, groups}: Props) {
|
||||
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
|
||||
const router = useRouter();
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: students.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<Layout user={user}>
|
||||
<div className="w-full flex flex-col gap-4">
|
||||
{entities.length > 0 && (
|
||||
<div className="w-fit self-end bg-neutral-200 px-2 rounded-lg py-1">
|
||||
<b>{mapBy(entities, "label")?.join(", ")}</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 place-items-center gap-4 text-center">
|
||||
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
||||
<IconCard
|
||||
onClick={() => router.push("/classrooms")}
|
||||
Icon={BsPeople}
|
||||
label="Classrooms"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
|
||||
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignments.filter((a) => !a.archived).length}
|
||||
color="purple"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white border shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,21 @@
|
||||
import Layout from "@/components/High/Layout";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Type, User } from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { serialize } from "@/utils";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import Head from "next/head";
|
||||
import {useRouter} from "next/router";
|
||||
import {useEffect} from "react";
|
||||
import {BsArrowLeft} from "react-icons/bs";
|
||||
import {BsArrowLeft, BsChevronLeft} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import UserList from "../(admin)/Lists/UserList";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res, query}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
const envVariables: {[key: string]: string} = {};
|
||||
Object.keys(process.env)
|
||||
.filter((x) => x.startsWith("NEXT_PUBLIC"))
|
||||
.forEach((x: string) => {
|
||||
envVariables[x] = process.env[x]!;
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
@@ -30,17 +25,22 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
const {type} = query as {type?: Type}
|
||||
|
||||
return {
|
||||
props: {user: req.session.user, envVariables},
|
||||
props: serialize({user: req.session.user, type}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function UsersListPage() {
|
||||
const {user} = useUser();
|
||||
interface Props {
|
||||
user: User
|
||||
type?: Type
|
||||
}
|
||||
|
||||
export default function UsersListPage({ user, type }: Props) {
|
||||
const [filters, clearFilters] = useFilterStore((state) => [state.userFilters, state.clearUserFilters]);
|
||||
|
||||
const router = useRouter();
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -59,19 +59,19 @@ export default function UsersListPage() {
|
||||
<Layout user={user}>
|
||||
<UserList
|
||||
user={user}
|
||||
type={type}
|
||||
filters={filters.map((f) => f.filter)}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
clearFilters();
|
||||
router.back();
|
||||
clearFilters()
|
||||
router.back()
|
||||
}}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Users ({total})</h2>
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||
<BsChevronLeft />
|
||||
</button>
|
||||
<h2 className="font-bold text-2xl">Users ({ total })</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
import Layout from "@/components/High/Layout";
|
||||
import List from "@/components/List";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {Type, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import {mapBy, serialize} from "@/utils";
|
||||
import {getEntitiesUsers, getEntityUsers} from "@/utils/users.be";
|
||||
import {createColumnHelper} from "@tanstack/react-table";
|
||||
import clsx from "clsx";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import Head from "next/head";
|
||||
import {useRouter} from "next/router";
|
||||
import {useEffect, useState} from "react";
|
||||
import {BsArrowLeft, BsCheck, BsChevronLeft} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import UserList from "../(admin)/Lists/UserList";
|
||||
import {countries, TCountries} from "countries-list";
|
||||
import countryCodes from "country-codes-list";
|
||||
import {capitalize} from "lodash";
|
||||
import moment from "moment";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {getEntities, getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
|
||||
const expirationDateColor = (date: Date) => {
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
|
||||
if (today.isAfter(momentDate)) return "!text-mti-red-light font-bold line-through";
|
||||
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
|
||||
if (today.add(2, "weeks").isAfter(momentDate)) return "!text-mti-rose-light";
|
||||
if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
|
||||
};
|
||||
|
||||
const SEARCH_FIELDS = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res, query}) => {
|
||||
const user = req.session.user as User | undefined;
|
||||
|
||||
if (!user)
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
const {type} = query as {type?: Type};
|
||||
const users = await getEntitiesUsers(mapBy(user.entities, "id"));
|
||||
const entities = await getEntitiesWithRoles();
|
||||
|
||||
const filters: ((u: User) => boolean)[] = [];
|
||||
if (type) filters.push((u) => u.type === type);
|
||||
|
||||
return {
|
||||
props: serialize({user, users: filters.reduce((d, f) => d.filter(f), users), entities}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
}
|
||||
|
||||
export default function UsersList({user, users, entities}: Props) {
|
||||
const [showDemographicInformation, setShowDemographicInformation] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Name</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>E-mail</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||
}),
|
||||
columnHelper.accessor("type", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Type</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => USER_TYPE_LABELS[info.getValue()],
|
||||
}),
|
||||
columnHelper.accessor("studentID", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Student ID</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("entities", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Entities</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({getValue}) =>
|
||||
getValue()
|
||||
.map((e) => entities.find((x) => x.id === e.id)?.label)
|
||||
.join(", "),
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Expiration</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (
|
||||
<span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
|
||||
{!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("isVerified", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Verified</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (
|
||||
<div className="flex gap-3 items-center text-mti-gray-dim text-sm self-center">
|
||||
<div
|
||||
className={clsx(
|
||||
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
info.getValue() && "!bg-mti-purple-light ",
|
||||
)}>
|
||||
<BsCheck color="white" className="w-full h-full" />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: () => "",
|
||||
},
|
||||
];
|
||||
|
||||
const demographicColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Name</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.country", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Country</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${
|
||||
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||
: "N/A",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.phone", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Phone</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
columnHelper.accessor(
|
||||
(x) =>
|
||||
x.type === "corporate" || x.type === "mastercorporate" ? x.demographicInformation?.position : x.demographicInformation?.employment,
|
||||
{
|
||||
id: "employment",
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Employment</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "N/A",
|
||||
enableSorting: true,
|
||||
},
|
||||
),
|
||||
columnHelper.accessor("lastLogin", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Last Login</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (!!info.getValue() ? moment(info.getValue()).format("YYYY-MM-DD HH:mm") : "N/A"),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.gender", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center">
|
||||
<span>Gender</span>
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => capitalize(info.getValue()) || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: () => "",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
|
||||
<Layout user={user} className="!gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => router.back()}
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||
<BsChevronLeft />
|
||||
</button>
|
||||
<h2 className="font-bold text-2xl">User List</h2>
|
||||
</div>
|
||||
<List<User> data={users} searchFields={SEARCH_FIELDS} columns={showDemographicInformation ? demographicColumns : defaultColumns} />
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import Head from "next/head";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Stat, User} from "@/interfaces/user";
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import {useEffect, useMemo, useRef, useState} from "react";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
import {groupByDate} from "@/utils/stats";
|
||||
import moment from "moment";
|
||||
@@ -22,9 +22,18 @@ import RecordFilter from "@/components/Medium/RecordFilter";
|
||||
import {useRouter} from "next/router";
|
||||
import useTrainingContentStore from "@/stores/trainingContentStore";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {getUsers} from "@/utils/users.be";
|
||||
import {getAssignments, getAssignmentsByAssigner} from "@/utils/assignments.be";
|
||||
import {getEntitiesUsers, getUsers} from "@/utils/users.be";
|
||||
import {getAssignments, getAssignmentsByAssigner, getEntitiesAssignments} from "@/utils/assignments.be";
|
||||
import useGradingSystem from "@/hooks/useGrading";
|
||||
import { mapBy, serialize } from "@/utils";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
|
||||
import { getGradingSystemByEntity } from "@/utils/grading.be";
|
||||
import { Grading } from "@/interfaces";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { useListSearch } from "@/hooks/useListSearch";
|
||||
import CardList from "@/components/High/CardList";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
@@ -47,11 +56,16 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
const users = await getUsers();
|
||||
const assignments = await getAssignments();
|
||||
const entityIDs = mapBy(user.entities, 'id')
|
||||
|
||||
const entities = await getEntitiesWithRoles(checkAccess(user, ["admin", "developer"]) ? undefined : entityIDs)
|
||||
const users = await (checkAccess(user, ["admin", "developer"]) ? getUsers() : getEntitiesUsers(mapBy(entities, 'id')))
|
||||
const groups = await (checkAccess(user, ["admin", "developer"]) ? getGroups() : getGroupsByEntities(mapBy(entities, 'id')))
|
||||
const assignments = await (checkAccess(user, ["admin", "developer"]) ? getAssignments() : getEntitiesAssignments(mapBy(entities, 'id')))
|
||||
const gradingSystems = await Promise.all(entityIDs.map(getGradingSystemByEntity))
|
||||
|
||||
return {
|
||||
props: {user, users, assignments},
|
||||
props: serialize({user, users, assignments, entities, gradingSystems}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
@@ -61,9 +75,13 @@ interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
assignments: Assignment[];
|
||||
gradingSystems: Grading[]
|
||||
entities: EntityWithRoles[]
|
||||
}
|
||||
|
||||
export default function History({user, users, assignments}: Props) {
|
||||
const MAX_TRAINING_EXAMS = 10;
|
||||
|
||||
export default function History({user, users, assignments, entities, gradingSystems}: Props) {
|
||||
const router = useRouter();
|
||||
const [statsUserId, setStatsUserId, training, setTraining] = useRecordStore((state) => [
|
||||
state.selectedUser,
|
||||
@@ -72,8 +90,6 @@ export default function History({user, users, assignments}: Props) {
|
||||
state.setTraining,
|
||||
]);
|
||||
|
||||
// const [statsUserId, setStatsUserId] = useState<string | undefined>(user.id);
|
||||
const [groupedStats, setGroupedStats] = useState<{[key: string]: Stat[]}>();
|
||||
const [filter, setFilter] = useState<Filter>();
|
||||
|
||||
const {data: stats, isLoading: isStatsLoading} = useFilterRecordsByUser<Stat[]>(statsUserId || user?.id);
|
||||
@@ -87,12 +103,10 @@ export default function History({user, users, assignments}: Props) {
|
||||
const setTimeSpent = useExamStore((state) => state.setTimeSpent);
|
||||
const renderPdfIcon = usePDFDownload("stats");
|
||||
|
||||
useEffect(() => setStatsUserId(user.id), [setStatsUserId, user]);
|
||||
const [selectedTrainingExams, setSelectedTrainingExams] = useState<string[]>([]);
|
||||
const setTrainingStats = useTrainingContentStore((state) => state.setStats);
|
||||
|
||||
useEffect(() => {
|
||||
if (stats && !isStatsLoading) {
|
||||
setGroupedStats(
|
||||
groupByDate(
|
||||
const groupedStats = useMemo(() => groupByDate(
|
||||
stats.filter((x) => {
|
||||
if (
|
||||
(x.module === "writing" || x.module === "speaking") &&
|
||||
@@ -102,15 +116,19 @@ export default function History({user, users, assignments}: Props) {
|
||||
return false;
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [stats, isStatsLoading]);
|
||||
), [stats])
|
||||
|
||||
// useEffect(() => {
|
||||
// // just set this initially
|
||||
// if (!statsUserId) setStatsUserId(user.id);
|
||||
// }, []);
|
||||
useEffect(() => setStatsUserId(user.id), [setStatsUserId, user]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
setTraining(false);
|
||||
};
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
};
|
||||
}, [router.events, setTraining]);
|
||||
|
||||
const filterStatsByDate = (stats: {[key: string]: Stat[]}) => {
|
||||
if (filter && filter !== "assignments") {
|
||||
@@ -139,11 +157,7 @@ export default function History({user, users, assignments}: Props) {
|
||||
return stats;
|
||||
};
|
||||
|
||||
const MAX_TRAINING_EXAMS = 10;
|
||||
const [selectedTrainingExams, setSelectedTrainingExams] = useState<string[]>([]);
|
||||
const setTrainingStats = useTrainingContentStore((state) => state.setStats);
|
||||
|
||||
const handleTrainingContentSubmission = () => {
|
||||
const handleTrainingContentSubmission = () => {
|
||||
if (groupedStats) {
|
||||
const groupedStatsByDate = filterStatsByDate(groupedStats);
|
||||
const allStats = Object.keys(groupedStatsByDate);
|
||||
@@ -157,21 +171,15 @@ export default function History({user, users, assignments}: Props) {
|
||||
setTrainingStats(Object.values(selectedStats).flat());
|
||||
router.push("/training");
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
setTraining(false);
|
||||
};
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
};
|
||||
}, [router.events, setTraining]);
|
||||
const filteredStats = useMemo(() =>
|
||||
Object.keys(filterStatsByDate(groupedStats))
|
||||
.sort((a, b) => parseInt(b) - parseInt(a)),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[groupedStats, filter])
|
||||
|
||||
const customContent = (timestamp: string) => {
|
||||
if (!groupedStats) return <></>;
|
||||
|
||||
const dateStats = groupedStats[timestamp];
|
||||
|
||||
return (
|
||||
@@ -212,7 +220,7 @@ export default function History({user, users, assignments}: Props) {
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<Layout user={user}>
|
||||
<RecordFilter user={user} filterState={{filter: filter, setFilter: setFilter}}>
|
||||
<RecordFilter user={user} users={users} entities={entities} filterState={{filter: filter, setFilter: setFilter}}>
|
||||
{training && (
|
||||
<div className="flex flex-row">
|
||||
<div className="font-semibold text-2xl mr-4">
|
||||
@@ -231,14 +239,12 @@ export default function History({user, users, assignments}: Props) {
|
||||
</div>
|
||||
)}
|
||||
</RecordFilter>
|
||||
{groupedStats && Object.keys(groupedStats).length > 0 && !isStatsLoading && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full gap-4 xl:gap-6">
|
||||
{Object.keys(filterStatsByDate(groupedStats))
|
||||
.sort((a, b) => parseInt(b) - parseInt(a))
|
||||
.map(customContent)}
|
||||
</div>
|
||||
|
||||
|
||||
{filteredStats.length > 0 && !isStatsLoading && (
|
||||
<CardList list={filteredStats} renderCard={customContent} searchFields={[]} pageSize={30} className="lg:!grid-cols-3" />
|
||||
)}
|
||||
{groupedStats && Object.keys(groupedStats).length === 0 && !isStatsLoading && (
|
||||
{filteredStats.length === 0 && !isStatsLoading && (
|
||||
<span className="font-semibold ml-1">No record to display...</span>
|
||||
)}
|
||||
{isStatsLoading && (
|
||||
|
||||
@@ -1,36 +1,39 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import Layout from "@/components/High/Layout";
|
||||
import CodeGenerator from "./(admin)/CodeGenerator";
|
||||
import ExamLoader from "./(admin)/ExamLoader";
|
||||
import {Tab} from "@headlessui/react";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import Lists from "./(admin)/Lists";
|
||||
import BatchCodeGenerator from "./(admin)/BatchCodeGenerator";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import ExamGenerator from "./(admin)/ExamGenerator";
|
||||
import BatchCreateUser from "./(admin)/BatchCreateUser";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import {useState} from "react";
|
||||
import { useState } from "react";
|
||||
import Modal from "@/components/Modal";
|
||||
import IconCard from "@/dashboards/IconCard";
|
||||
import {BsCode, BsCodeSquare, BsGearFill, BsPeopleFill, BsPersonFill} from "react-icons/bs";
|
||||
import { BsCode, BsCodeSquare, BsGearFill, BsPeopleFill, BsPersonFill } from "react-icons/bs";
|
||||
import UserCreator from "./(admin)/UserCreator";
|
||||
import CorporateGradingSystem from "./(admin)/CorporateGradingSystem";
|
||||
import useGradingSystem from "@/hooks/useGrading";
|
||||
import {CEFR_STEPS} from "@/resources/grading";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {getUserPermissions} from "@/utils/permissions.be";
|
||||
import {Permission, PermissionType} from "@/interfaces/permissions";
|
||||
import {getUsers} from "@/utils/users.be";
|
||||
import { CEFR_STEPS } from "@/resources/grading";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { getUserPermissions } from "@/utils/permissions.be";
|
||||
import { Permission, PermissionType } from "@/interfaces/permissions";
|
||||
import { getUsers } from "@/utils/users.be";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { getEntitiesWithRoles, getEntityWithRoles } from "@/utils/entities.be";
|
||||
import { mapBy, serialize } from "@/utils";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = req.session.user as User;
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
@@ -50,20 +53,22 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
}
|
||||
|
||||
const permissions = await getUserPermissions(user.id);
|
||||
const entities = await getEntitiesWithRoles(mapBy(user.entities, 'id')) || []
|
||||
|
||||
return {
|
||||
props: {user, permissions},
|
||||
props: serialize({ user, permissions, entities }),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
permissions: PermissionType[];
|
||||
entities: EntityWithRoles[]
|
||||
}
|
||||
|
||||
export default function Admin({user, permissions}: Props) {
|
||||
const {gradingSystem, mutate} = useGradingSystem();
|
||||
const {users} = useUsers();
|
||||
export default function Admin({ user, entities, permissions }: Props) {
|
||||
const { gradingSystem, mutate } = useGradingSystem();
|
||||
const { users } = useUsers();
|
||||
|
||||
const [modalOpen, setModalOpen] = useState<string>();
|
||||
|
||||
@@ -90,14 +95,14 @@ export default function Admin({user, permissions}: Props) {
|
||||
<CodeGenerator user={user} permissions={permissions} onFinish={() => setModalOpen(undefined)} />
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "createUser"} onClose={() => setModalOpen(undefined)}>
|
||||
<UserCreator user={user} users={users} permissions={permissions} onFinish={() => setModalOpen(undefined)} />
|
||||
<UserCreator user={user} entities={entities} users={users} permissions={permissions} onFinish={() => setModalOpen(undefined)} />
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "gradingSystem"} onClose={() => setModalOpen(undefined)}>
|
||||
<CorporateGradingSystem
|
||||
user={user}
|
||||
defaultSteps={gradingSystem?.steps || CEFR_STEPS}
|
||||
mutate={(steps) => {
|
||||
mutate({user: user.id, steps});
|
||||
mutate({ user: user.id, steps });
|
||||
setModalOpen(undefined);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -17,22 +17,28 @@ import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {countExamModules, countFullExams, MODULE_ARRAY, sortByModule} from "@/utils/moduleUtils";
|
||||
import {Chart} from "react-chartjs-2";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import Select from "react-select";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import DatePicker from "react-datepicker";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import ProfileSummary from "@/components/ProfileSummary";
|
||||
import moment from "moment";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {Group, Stat, User} from "@/interfaces/user";
|
||||
import {Divider} from "primereact/divider";
|
||||
import Badge from "@/components/Low/Badge";
|
||||
import { mapBy, serialize } from "@/utils";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
|
||||
import Select from "@/components/Low/Select";
|
||||
|
||||
ChartJS.register(LinearScale, CategoryScale, PointElement, LineElement, LineController, Legend, Tooltip);
|
||||
|
||||
const COLORS = ["#1EB3FF", "#FF790A", "#3D9F11", "#EF5DA8", "#414288"];
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user as User;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
@@ -52,13 +58,25 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
const entityIDs = mapBy(user.entities, 'id')
|
||||
const entities = await getEntitiesWithRoles(checkAccess(user, ["admin", "developer"]) ? undefined : entityIDs)
|
||||
const users = await (checkAccess(user, ["admin", "developer"]) ? getUsers() : getEntitiesUsers(mapBy(entities, 'id')))
|
||||
const groups = await (checkAccess(user, ["admin", "developer"]) ? getGroups() : getGroupsByEntities(mapBy(entities, 'id')))
|
||||
|
||||
return {
|
||||
props: {user: req.session.user},
|
||||
props: serialize({user, entities, users, groups}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Stats() {
|
||||
const [statsUserId, setStatsUserId] = useState<string>();
|
||||
interface Props {
|
||||
user: User
|
||||
users: User[]
|
||||
entities: EntityWithRoles[]
|
||||
groups: Group[]
|
||||
}
|
||||
|
||||
export default function Stats({ user, entities, users, groups }: Props) {
|
||||
const [statsUserId, setStatsUserId] = useState<string>(user.id);
|
||||
const [startDate, setStartDate] = useState<Date | null>(moment(new Date()).subtract(1, "weeks").toDate());
|
||||
const [endDate, setEndDate] = useState<Date | null>(new Date());
|
||||
const [initialStatDate, setInitialStatDate] = useState<Date>();
|
||||
@@ -69,15 +87,8 @@ export default function Stats() {
|
||||
const [dailyScoreDate, setDailyScoreDate] = useState<Date | null>(new Date());
|
||||
const [intervalDates, setIntervalDates] = useState<Date[]>([]);
|
||||
|
||||
const {user} = useUser({redirectTo: "/login"});
|
||||
const {users} = useUsers();
|
||||
const {groups} = useGroups({admin: user?.id});
|
||||
const {data: stats} = useFilterRecordsByUser<Stat[]>(statsUserId, !statsUserId);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) setStatsUserId(user.id);
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
setInitialStatDate(
|
||||
stats
|
||||
@@ -190,16 +201,7 @@ export default function Stats() {
|
||||
className="w-full"
|
||||
options={users.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
|
||||
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
|
||||
onChange={(value) => setStatsUserId(value?.value)}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
onChange={(value) => setStatsUserId(value?.value || user.id)}
|
||||
/>
|
||||
)}
|
||||
{["corporate", "teacher", "mastercorporate"].includes(user.type) && groups.length > 0 && (
|
||||
@@ -209,16 +211,7 @@ export default function Stats() {
|
||||
.filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
|
||||
.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
|
||||
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
|
||||
onChange={(value) => setStatsUserId(value?.value)}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
onChange={(value) => setStatsUserId(value?.value || user.id)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -20,9 +20,15 @@ import TrainingScore from "@/training/TrainingScore";
|
||||
import ModuleBadge from "@/components/ModuleBadge";
|
||||
import RecordFilter from "@/components/Medium/RecordFilter";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
import { mapBy, serialize } from "@/utils";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { getAssignmentsByAssignee } from "@/utils/assignments.be";
|
||||
import { getEntitiesUsers } from "@/utils/users.be";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user as User;
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
@@ -42,12 +48,16 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
const entityIDs = mapBy(user.entities, 'id')
|
||||
const entities = await getEntitiesWithRoles(entityIDs)
|
||||
const users = await getEntitiesUsers(entityIDs)
|
||||
|
||||
return {
|
||||
props: {user: req.session.user},
|
||||
props: serialize({user, users, entities}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
const Training: React.FC<{user: User}> = ({user}) => {
|
||||
const Training: React.FC<{user: User, entities: EntityWithRoles[], users: User[] }> = ({user, entities, users}) => {
|
||||
const [recordUserId, setRecordTraining] = useRecordStore((state) => [state.selectedUser, state.setTraining]);
|
||||
const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
|
||||
|
||||
@@ -193,7 +203,7 @@ const Training: React.FC<{user: User}> = ({user}) => {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<RecordFilter user={user} filterState={{filter: filter, setFilter: setFilter}} assignments={false}>
|
||||
<RecordFilter users={users} entities={entities} user={user} filterState={{filter: filter, setFilter: setFilter}} assignments={false}>
|
||||
{user.type === "student" && (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
export const AVATARS = [
|
||||
{
|
||||
name: "Matthew Noah",
|
||||
id: "5912afa7c77c47d3883af3d874047aaf",
|
||||
gender: "male",
|
||||
},
|
||||
{
|
||||
name: "Vera Cerise",
|
||||
id: "9e58d96a383e4568a7f1e49df549e0e4",
|
||||
name: "Gia",
|
||||
id: "gia.business",
|
||||
gender: "female",
|
||||
},
|
||||
{
|
||||
name: "Edward Tony",
|
||||
id: "d2cdd9c0379a4d06ae2afb6e5039bd0c",
|
||||
name: "Vadim",
|
||||
id: "vadim.business",
|
||||
gender: "male",
|
||||
},
|
||||
{
|
||||
name: "Tanya Molly",
|
||||
id: "045cb5dcd00042b3a1e4f3bc1c12176b",
|
||||
gender: "female",
|
||||
},
|
||||
{
|
||||
name: "Kayla Abbi",
|
||||
id: "1ae1e5396cc444bfad332155fdb7a934",
|
||||
gender: "female",
|
||||
},
|
||||
{
|
||||
name: "Jerome Ryan",
|
||||
id: "0ee6aa7cc1084063a630ae514fccaa31",
|
||||
name: "Orhan",
|
||||
id: "orhan.business",
|
||||
gender: "male",
|
||||
},
|
||||
{
|
||||
name: "Tyler Christopher",
|
||||
id: "5772cff935844516ad7eeff21f839e43",
|
||||
name: "Flora",
|
||||
id: "flora.business",
|
||||
gender: "female",
|
||||
},
|
||||
{
|
||||
name: "Scarlett",
|
||||
id: "scarlett.business",
|
||||
gender: "female",
|
||||
},
|
||||
{
|
||||
name: "Parker",
|
||||
id: "parker.casual",
|
||||
gender: "male",
|
||||
},
|
||||
{
|
||||
name: "Ethan",
|
||||
id: "ethan.business",
|
||||
gender: "male",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,28 +1,56 @@
|
||||
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.subscriptionExpirationDate || !participant.subscriptionExpirationDate)
|
||||
return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: null}});
|
||||
return await db.collection("users").updateOne({ id: participant.id }, { $set: { subscriptionExpirationDate: null } });
|
||||
|
||||
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()}});
|
||||
return await db.collection("users").updateOne({ id: participant.id }, { $set: { subscriptionExpirationDate: corporateDate.toISOString() } });
|
||||
|
||||
return;
|
||||
};
|
||||
@@ -45,29 +73,39 @@ export const getUserCorporate = async (id: string) => {
|
||||
};
|
||||
|
||||
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}})
|
||||
.find<Group>({ admin: { $in: ids } })
|
||||
.toArray();
|
||||
};
|
||||
|
||||
@@ -87,11 +125,11 @@ export const getAllAssignersByCorporate = async (corporateID: string, type: Type
|
||||
export const getGroupsForEntities = async (ids: string[]) =>
|
||||
await db
|
||||
.collection("groups")
|
||||
.find<Group>({entity: {$in: ids}})
|
||||
.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);
|
||||
@@ -102,7 +140,7 @@ export const getGroupsForUser = async (admin?: string, participant?: string) =>
|
||||
export const getStudentGroupsForUsersWithoutAdmin = async (admin: string, participants: string[]) => {
|
||||
return await db
|
||||
.collection("groups")
|
||||
.find<Group>({...(admin ? {admin: {$ne: admin}} : {}), ...(participants ? {participants} : {})})
|
||||
.find<Group>({ ...(admin ? { admin: { $ne: admin } } : {}), ...(participants ? { participants } : {}) })
|
||||
.toArray();
|
||||
};
|
||||
|
||||
@@ -123,10 +161,11 @@ export const getCorporateNameForStudent = async (studentID: string) => {
|
||||
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()
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
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() {
|
||||
export async function getUsers(filter?: object) {
|
||||
return await db
|
||||
.collection("users")
|
||||
.find<User>({}, {projection: {_id: 0}})
|
||||
.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}});
|
||||
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(
|
||||
@@ -25,15 +25,15 @@ export async function getUserWithEntity(id: string): Promise<WithEntity<User> |
|
||||
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}});
|
||||
const user = await db.collection("users").findOne<User>({ id: id }, { projection: { _id: 0 } });
|
||||
return !!user ? user : undefined;
|
||||
}
|
||||
|
||||
@@ -42,32 +42,32 @@ export async function getSpecificUsers(ids: string[]) {
|
||||
|
||||
return await db
|
||||
.collection("users")
|
||||
.find<User>({id: {$in: ids}}, {projection: {_id: 0}})
|
||||
.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})
|
||||
.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) {
|
||||
export async function getEntitiesUsers(ids: string[], filter?: object, limit?: number) {
|
||||
return await db
|
||||
.collection("users")
|
||||
.find<User>({"entities.id": {$in: ids}})
|
||||
.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(
|
||||
@@ -80,20 +80,20 @@ export async function getLinkedUsers(
|
||||
direction?: "asc" | "desc",
|
||||
) {
|
||||
const filters = {
|
||||
...(!!type ? {type} : {}),
|
||||
...(!!type ? { type } : {}),
|
||||
};
|
||||
|
||||
if (!userID || userType === "admin" || userType === "developer") {
|
||||
const users = await db
|
||||
.collection("users")
|
||||
.find<User>(filters)
|
||||
.sort(sort ? {[sort]: direction === "desc" ? -1 : 1} : {})
|
||||
.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};
|
||||
return { users, total };
|
||||
}
|
||||
|
||||
const adminGroups = await getUserGroups(userID);
|
||||
@@ -107,17 +107,17 @@ export async function getLinkedUsers(
|
||||
]);
|
||||
|
||||
// ⨯ [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 };
|
||||
|
||||
const users = await db
|
||||
.collection("users")
|
||||
.find<User>({...filters, id: {$in: participants}})
|
||||
.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 total = await db.collection("users").countDocuments({ ...filters, id: { $in: participants } });
|
||||
|
||||
return {users, total};
|
||||
return { users, total };
|
||||
}
|
||||
|
||||
export async function getUserBalance(user: User) {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
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;
|
||||
entities: string;
|
||||
expiryDate: string;
|
||||
verified: string;
|
||||
country: string;
|
||||
@@ -16,12 +17,12 @@ export interface UserListRow {
|
||||
gender: string;
|
||||
}
|
||||
|
||||
export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group[]) => {
|
||||
export const exportListToExcel = (rowUsers: WithLabeledEntities<User>[]) => {
|
||||
const rows: UserListRow[] = rowUsers.map((user) => ({
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
type: USER_TYPE_LABELS[user.type],
|
||||
companyName: getUserCompanyName(user, users, groups),
|
||||
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",
|
||||
@@ -32,7 +33,7 @@ export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group
|
||||
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 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}`;
|
||||
|
||||
Reference in New Issue
Block a user