Compare commits
3 Commits
ENCOA-316-
...
feature/tr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22209ee1c1 | ||
|
|
0e2f53db0a | ||
|
|
9177a6b2ac |
@@ -9,7 +9,7 @@ export const userHashStudent = {type: "student"} as {type: Type};
|
||||
export const userHashTeacher = {type: "teacher"} as {type: Type};
|
||||
export const userHashCorporate = {type: "corporate"} as {type: Type};
|
||||
|
||||
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc"}) {
|
||||
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc", searchTerm?: string | undefined}) {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -35,7 +35,7 @@ export default function useUsers(props?: {type?: string; page?: number; size?: n
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction]);
|
||||
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction, props?.searchTerm]);
|
||||
|
||||
return {users, total, isLoading, isError, reload: getData};
|
||||
}
|
||||
|
||||
@@ -1,33 +1,34 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
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 { Type, User, userTypes, CorporateUser, Group } from "@/interfaces/user";
|
||||
import { Popover, Transition } from "@headlessui/react";
|
||||
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {capitalize, reverse} from "lodash";
|
||||
import { capitalize, reverse } 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 { 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 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 { getUserCompanyName, isAgentUser, 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 { 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 usePermissions from "@/hooks/usePermissions";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import Input from "@/components/Low/Input";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
|
||||
@@ -63,17 +64,10 @@ export default function UserList({
|
||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [page, setPage] = useState(0);
|
||||
const [searchTerm, setSearchTerm] = useState<string | undefined>(undefined);
|
||||
|
||||
const userHash = useMemo(
|
||||
() => ({
|
||||
type,
|
||||
size: 16,
|
||||
page,
|
||||
}),
|
||||
[type, page],
|
||||
);
|
||||
const { users, total, isLoading, reload } = useUsers({type: type, size: 16, page: page, searchTerm: searchTerm});
|
||||
|
||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||
const {users: corporates} = useUsers(corporatesHash);
|
||||
|
||||
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
||||
@@ -114,20 +108,20 @@ export default function UserList({
|
||||
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();
|
||||
})
|
||||
.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,
|
||||
})
|
||||
@@ -136,22 +130,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",
|
||||
})
|
||||
@@ -160,18 +153,18 @@ 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}) => {
|
||||
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;
|
||||
@@ -216,7 +209,7 @@ export default function UserList({
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -238,8 +231,7 @@ export default function UserList({
|
||||
) 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())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||
: "N/A",
|
||||
}),
|
||||
@@ -306,7 +298,7 @@ export default function UserList({
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -326,7 +318,7 @@ export default function UserList({
|
||||
<SorterArrow name="email" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
@@ -513,19 +505,17 @@ export default function UserList({
|
||||
return a.id.localeCompare(b.id);
|
||||
};
|
||||
|
||||
const {rows: filteredRows, renderSearch} = useListSearch<User>(searchFields, displayUsers);
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredRows,
|
||||
data: displayUsers,
|
||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
const downloadExcel = () => {
|
||||
const csv = exportListToExcel(filteredRows, users, groups);
|
||||
const csv = exportListToExcel(displayUsers, users, groups);
|
||||
|
||||
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);
|
||||
@@ -627,7 +617,7 @@ export default function UserList({
|
||||
</Modal>
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<div className="w-full flex gap-2 items-end">
|
||||
{renderSearch()}
|
||||
<Input label="Search" type="text" name="search" onChange={setSearchTerm} placeholder="Enter search text" value={searchTerm} />
|
||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
||||
Download List
|
||||
</Button>
|
||||
|
||||
@@ -19,7 +19,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
page,
|
||||
orderBy,
|
||||
direction = "desc",
|
||||
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"};
|
||||
searchTerm
|
||||
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"; searchTerm?: string | undefined};
|
||||
|
||||
const {users, total} = await getLinkedUsers(
|
||||
req.session.user?.id,
|
||||
@@ -29,6 +30,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
size !== undefined ? parseInt(size) : undefined,
|
||||
orderBy,
|
||||
direction,
|
||||
searchTerm
|
||||
);
|
||||
|
||||
res.status(200).json({users, total});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
|
||||
import {getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups} from "./groups.be";
|
||||
import {last, uniq, uniqBy} from "lodash";
|
||||
import {getUserCodes} from "./codes.be";
|
||||
import { CorporateUser, Group, Type, User } from "@/interfaces/user";
|
||||
import { getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups } from "./groups.be";
|
||||
import { last, uniq, uniqBy } from "lodash";
|
||||
import { getUserCodes } from "./codes.be";
|
||||
import moment from "moment";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function getUsers() {
|
||||
}
|
||||
|
||||
export async function getUser(id: string): Promise<User | undefined> {
|
||||
const user = await db.collection("users").findOne<User>({id});
|
||||
const user = await db.collection("users").findOne<User>({ id });
|
||||
return !!user ? user : undefined;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export async function getSpecificUsers(ids: string[]) {
|
||||
|
||||
return await db
|
||||
.collection("users")
|
||||
.find<User>({id: {$in: ids}})
|
||||
.find<User>({ id: { $in: ids } })
|
||||
.toArray();
|
||||
}
|
||||
|
||||
@@ -33,21 +33,32 @@ export async function getLinkedUsers(
|
||||
size?: number,
|
||||
sort?: string,
|
||||
direction?: "asc" | "desc",
|
||||
searchTerm?: string | undefined,
|
||||
) {
|
||||
const filters = {
|
||||
...(!!type ? {type} : {}),
|
||||
};
|
||||
const filters: any = {};
|
||||
|
||||
if (type) {
|
||||
filters.type = type;
|
||||
}
|
||||
|
||||
if (searchTerm) {
|
||||
filters.$or = [
|
||||
{ name: { $regex: searchTerm, $options: 'i' } },
|
||||
{ email: { $regex: searchTerm, $options: 'i' } },
|
||||
{ company: { $regex: searchTerm, $options: 'i' } },
|
||||
];
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -61,17 +72,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) {
|
||||
|
||||
Reference in New Issue
Block a user