Continued creating the entity system

This commit is contained in:
Tiago Ribeiro
2024-10-01 17:39:43 +01:00
parent bae02e5192
commit 564e6438cb
37 changed files with 2522 additions and 130 deletions

View File

@@ -0,0 +1,343 @@
/* eslint-disable @next/next/no-img-element */
import CardList from "@/components/High/CardList";
import Layout from "@/components/High/Layout";
import Tooltip from "@/components/Low/Tooltip";
import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Entity, EntityWithRoles, Role} from "@/interfaces/entity";
import {GroupWithUsers, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {USER_TYPE_LABELS} from "@/resources/user";
import {getEntityWithRoles} from "@/utils/entities.be";
import {convertToUsers, getGroup} from "@/utils/groups.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {getUserName} from "@/utils/users";
import {getEntityUsers, getLinkedUsers, getSpecificUsers} from "@/utils/users.be";
import axios from "axios";
import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next";
import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {useEffect, useMemo, useState} from "react";
import {
BsChevronLeft,
BsClockFill,
BsEnvelopeFill,
BsFillPersonVcardFill,
BsPlus,
BsSquare,
BsStopwatchFill,
BsTag,
BsTrash,
BsX,
} from "react-icons/bs";
import {toast, ToastContainer} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(async ({req, params}) => {
const user = req.session.user as User;
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (shouldRedirectHome(user)) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
const {id} = params as {id: string};
const entityWithRoles = await getEntityWithRoles(id);
if (!entityWithRoles || (checkAccess(user, getTypesOfUser(["admin", "developer"])) && !user.entities.map((x) => x.id).includes(id))) {
return {
redirect: {
destination: "/entities",
permanent: false,
},
};
}
const {entity, roles} = entityWithRoles;
const linkedUsers = await getLinkedUsers(user.id, user.type);
const entityUsers = await getEntityUsers(id);
const usersWithRole = entityUsers.map((u) => {
const e = u.entities.find((e) => e.id === id);
return {...u, role: roles.find((r) => r.id === e?.role)};
});
return {
props: {
user,
entity: JSON.parse(JSON.stringify(entity)),
roles: JSON.parse(JSON.stringify(roles)),
users: JSON.parse(JSON.stringify(usersWithRole)),
linkedUsers: JSON.parse(JSON.stringify(linkedUsers.users)),
},
};
}, sessionOptions);
type UserWithRole = User & {role?: Role};
interface Props {
user: User;
entity: Entity;
roles: Role[];
users: UserWithRole[];
linkedUsers: User[];
}
export default function Home({user, entity, roles, users, linkedUsers}: Props) {
const [isAdding, setIsAdding] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
const router = useRouter();
const allowEntityEdit = useMemo(() => checkAccess(user, ["admin", "developer"]), [user]);
const toggleUser = (u: User) => setSelectedUsers((prev) => (prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]));
const removeParticipants = () => {
if (selectedUsers.length === 0) return;
if (!allowEntityEdit) return;
if (!confirm(`Are you sure you want to remove ${selectedUsers.length} member${selectedUsers.length === 1 ? "" : "s"} from this entity?`))
return;
setIsLoading(true);
axios
.patch(`/api/entities/${entity.id}/users`, {add: false, members: selectedUsers})
.then(() => {
toast.success("The entity has been updated successfully!");
router.replace(router.asPath);
setSelectedUsers([]);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const addParticipants = () => {
if (selectedUsers.length === 0) return;
if (!allowEntityEdit || !isAdding) return;
if (!confirm(`Are you sure you want to add ${selectedUsers.length} member${selectedUsers.length === 1 ? "" : "s"} to this entity?`)) return;
setIsLoading(true);
axios
.patch(`/api/entities/${entity.id}/users`, {add: true, members: selectedUsers, role: "90ce8f08-08c8-41e4-9848-f1500ddc3930"})
.then(() => {
toast.success("The entity has been updated successfully!");
router.replace(router.asPath);
setIsAdding(false);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const renameGroup = () => {
if (!allowEntityEdit) return;
const name = prompt("Rename this entity:", entity.label);
if (!name) return;
setIsLoading(true);
axios
.patch(`/api/entities/${entity.id}`, {name})
.then(() => {
toast.success("The entity has been updated successfully!");
router.replace(router.asPath);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const deleteGroup = () => {
if (!allowEntityEdit) return;
if (!confirm("Are you sure you want to delete this entity?")) return;
setIsLoading(true);
axios
.delete(`/api/entities/${entity.id}`)
.then(() => {
toast.success("This entity has been successfully deleted!");
router.replace("/entities");
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const renderCard = (u: UserWithRole) => {
return (
<button
onClick={() => toggleUser(u)}
disabled={!allowEntityEdit}
key={u.id}
className={clsx(
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
"hover:border-mti-purple transition ease-in-out duration-300",
selectedUsers.includes(u.id) && "border-mti-purple",
)}>
<div className="flex items-center gap-2">
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
<img src={u.profilePicture} alt={u.name} />
</div>
<div className="flex flex-col">
<span className="font-semibold">{getUserName(u)}</span>
<span className="opacity-80 text-sm">
{USER_TYPE_LABELS[u.type]} {u.role && `- ${u.role.label}`}
</span>
</div>
</div>
<div className="flex flex-col gap-1">
<span className="flex items-center gap-2">
<Tooltip tooltip="E-mail address">
<BsEnvelopeFill />
</Tooltip>
{u.email}
</span>
<span className="flex items-center gap-2">
<Tooltip tooltip="Expiration Date">
<BsStopwatchFill />
</Tooltip>
{u.subscriptionExpirationDate ? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited"}
</span>
<span className="flex items-center gap-2">
<Tooltip tooltip="Last Login">
<BsClockFill />
</Tooltip>
{u.lastLogin ? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm") : "N/A"}
</span>
</div>
</button>
);
};
useEffect(() => setSelectedUsers([]), [isAdding]);
return (
<>
<Head>
<title>{entity.label} | 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 />
{user && (
<Layout user={user}>
<section className="flex flex-col gap-0">
<div className="flex flex-col gap-3">
<div className="flex items-end justify-between">
<div className="flex items-center gap-2">
<Link
href="/entities"
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">{entity.label}</h2>
</div>
</div>
{allowEntityEdit && !isAdding && (
<div className="flex items-center gap-2">
<button
onClick={renameGroup}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTag />
<span className="text-xs">Rename Entity</span>
</button>
<button
onClick={deleteGroup}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTrash />
<span className="text-xs">Delete Entity</span>
</button>
</div>
)}
</div>
<Divider />
<div className="flex items-center justify-between mb-4">
<span className="font-semibold text-xl">Members ({users.length})</span>
{allowEntityEdit && !isAdding && (
<div className="flex items-center gap-2">
<button
onClick={() => setIsAdding(true)}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsPlus />
<span className="text-xs">Add Members</span>
</button>
<button
onClick={removeParticipants}
disabled={selectedUsers.length === 0 || isLoading}
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTrash />
<span className="text-xs">Remove Members</span>
</button>
</div>
)}
{allowEntityEdit && isAdding && (
<div className="flex items-center gap-2">
<button
onClick={() => setIsAdding(false)}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-rose bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsX />
<span className="text-xs">Discard Selection</span>
</button>
<button
onClick={addParticipants}
disabled={selectedUsers.length === 0 || isLoading}
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsPlus />
<span className="text-xs">Add Members ({selectedUsers.length})</span>
</button>
</div>
)}
</div>
<CardList<User | UserWithRole>
list={isAdding ? linkedUsers : users}
renderCard={renderCard}
searchFields={[["name"], ["corporateInformation", "companyInformation", "name"], ["role", "label"], ["type"]]}
/>
</section>
</Layout>
)}
</>
);
}

View File

@@ -0,0 +1,232 @@
/* eslint-disable @next/next/no-img-element */
import CardList from "@/components/High/CardList";
import Layout from "@/components/High/Layout";
import Tooltip from "@/components/Low/Tooltip";
import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Entity, EntityWithRoles, Role} from "@/interfaces/entity";
import {GroupWithUsers, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {USER_TYPE_LABELS} from "@/resources/user";
import {getEntityWithRoles} from "@/utils/entities.be";
import {convertToUsers, getGroup} from "@/utils/groups.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {getUserName} from "@/utils/users";
import {getEntityUsers, getLinkedUsers, getSpecificUsers} from "@/utils/users.be";
import axios from "axios";
import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next";
import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {useEffect, useMemo, useState} from "react";
import {
BsChevronLeft,
BsClockFill,
BsEnvelopeFill,
BsFillPersonVcardFill,
BsPlus,
BsSquare,
BsStopwatchFill,
BsTag,
BsTrash,
BsX,
} from "react-icons/bs";
import {toast, ToastContainer} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(async ({req, params}) => {
const user = req.session.user as User;
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (shouldRedirectHome(user)) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
const {id} = params as {id: string};
const entityWithRoles = await getEntityWithRoles(id);
if (!entityWithRoles || (checkAccess(user, getTypesOfUser(["admin", "developer"])) && !user.entities.map((x) => x.id).includes(id))) {
return {
redirect: {
destination: "/entities",
permanent: false,
},
};
}
const {entity, roles} = entityWithRoles;
const linkedUsers = await getLinkedUsers(user.id, user.type);
const users = await getEntityUsers(id);
return {
props: {
user,
entity: JSON.parse(JSON.stringify(entity)),
roles: JSON.parse(JSON.stringify(roles)),
users: JSON.parse(JSON.stringify(users)),
linkedUsers: JSON.parse(JSON.stringify(linkedUsers.users)),
},
};
}, sessionOptions);
interface Props {
user: User;
entity: Entity;
roles: Role[];
users: User[];
linkedUsers: User[];
}
export default function Home({user, entity, roles, users, linkedUsers}: Props) {
const [isEditing, setIsEditing] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const allowEntityEdit = useMemo(() => checkAccess(user, ["admin", "developer"]), [user]);
const renameGroup = () => {
if (!allowEntityEdit) return;
const name = prompt("Rename this entity:", entity.label);
if (!name) return;
setIsLoading(true);
axios
.patch(`/api/entities/${entity.id}`, {name})
.then(() => {
toast.success("The entity has been updated successfully!");
router.replace(router.asPath);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const deleteGroup = () => {
if (!allowEntityEdit) return;
if (!confirm("Are you sure you want to delete this entity?")) return;
setIsLoading(true);
axios
.delete(`/api/entities/${entity.id}`)
.then(() => {
toast.success("This entity has been successfully deleted!");
router.replace("/entities");
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const firstCard = () => (
<Link
href={`/entities/${entity.id}/role`}
className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
<BsPlus size={40} />
<span className="font-semibold">Create Role</span>
</Link>
);
const renderCard = (role: Role) => {
const usersWithRole = users.filter((x) => x.entities.map((x) => x.role).includes(role.id));
return (
<button
disabled={!allowEntityEdit}
key={role.id}
className={clsx(
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 text-left cursor-pointer",
"hover:border-mti-purple transition ease-in-out duration-300",
)}>
<div className="flex flex-col">
<span className="font-semibold">{role.label}</span>
<span className="opacity-80 text-sm">{usersWithRole.length} members</span>
</div>
<b>Permissions ({role.permissions.length}): </b>
<span>
{role.permissions.slice(0, 5).join(", ")}
{role.permissions.length > 5 ? <span className="opacity-60"> and {role.permissions.length - 5} more</span> : ""}
</span>
</button>
);
};
return (
<>
<Head>
<title>{entity.label} | 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 />
{user && (
<Layout user={user}>
<section className="flex flex-col gap-0">
<div className="flex flex-col gap-3">
<div className="flex items-end justify-between">
<div className="flex items-center gap-2">
<Link
href={`/entities/${entity.id}`}
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">{entity.label}</h2>
</div>
</div>
{allowEntityEdit && !isEditing && (
<div className="flex items-center gap-2">
<button
onClick={renameGroup}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTag />
<span className="text-xs">Rename Entity</span>
</button>
<button
onClick={deleteGroup}
disabled={isLoading}
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTrash />
<span className="text-xs">Delete Entity</span>
</button>
</div>
)}
</div>
<Divider />
<span className="font-semibold text-xl mb-4">Roles</span>
<CardList list={roles} searchFields={[["label"]]} renderCard={renderCard} firstCard={firstCard} />
</section>
</Layout>
)}
</>
);
}

View File

@@ -0,0 +1,116 @@
/* 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 Layout from "@/components/High/Layout";
import {GroupWithUsers, User} from "@/interfaces/user";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {getUserName} from "@/utils/users";
import {convertToUsers, getGroupsForUser} from "@/utils/groups.be";
import {countEntityUsers, getEntityUsers, getSpecificUsers} from "@/utils/users.be";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import Link from "next/link";
import {uniq} from "lodash";
import {BsPlus} from "react-icons/bs";
import CardList from "@/components/High/CardList";
import {getEntitiesWithRoles} from "@/utils/entities.be";
import {EntityWithRoles} from "@/interfaces/entity";
import Separator from "@/components/Low/Separator";
type EntitiesWithCount = {entity: EntityWithRoles; users: User[]; count: number};
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
const user = req.session.user;
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (shouldRedirectHome(user)) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
const entities = await getEntitiesWithRoles(
checkAccess(user, getTypesOfUser(["admin", "developer"])) ? user.entities.map((x) => x.id) : undefined,
);
const entitiesWithCount = await Promise.all(
entities.map(async (e) => ({entity: e, count: await countEntityUsers(e.id), users: await getEntityUsers(e.id, 5)})),
);
return {
props: {user, entities: JSON.parse(JSON.stringify(entitiesWithCount))},
};
}, sessionOptions);
const SEARCH_FIELDS: string[][] = [["entity", "label"]];
interface Props {
user: User;
entities: EntitiesWithCount[];
}
export default function Home({user, entities}: Props) {
const renderCard = ({entity, users, count}: EntitiesWithCount) => (
<Link
href={`/entities/${entity.id}`}
key={entity.id}
className="p-4 border rounded-xl flex flex-col gap-2 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
<span>
<b>Entity: </b>
{entity.label}
</span>
<b>Members ({count}): </b>
<span>
{users.map(getUserName).join(", ")}
{count > 5 ? <span className="opacity-60"> and {count - 5} more</span> : ""}
</span>
</Link>
);
const firstCard = () => (
<Link
href={`/entities/create`}
className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
<BsPlus size={40} />
<span className="font-semibold">Create Entity</span>
</Link>
);
return (
<>
<Head>
<title>Entities | 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 />
{user && (
<Layout user={user} className="!gap-4">
<section className="flex flex-col gap-4 w-full h-full">
<div className="flex flex-col gap-4">
<h2 className="font-bold text-2xl">Entities</h2>
<Separator />
</div>
<CardList<EntitiesWithCount> list={entities} searchFields={SEARCH_FIELDS} renderCard={renderCard} firstCard={firstCard} />
</section>
</Layout>
)}
</>
);
}