Skip to content

Commit

Permalink
refactor more code
Browse files Browse the repository at this point in the history
  • Loading branch information
Chakravarthy7102 committed Nov 14, 2023
1 parent 30fb351 commit aaa9619
Show file tree
Hide file tree
Showing 10 changed files with 231 additions and 196 deletions.
2 changes: 1 addition & 1 deletion build/static/css/main.css

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/static/css/main.css.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/static/js/bundle.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/static/js/bundle.js.map

Large diffs are not rendered by default.

126 changes: 31 additions & 95 deletions src/ui/components/userroles/components/RolesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,116 +13,52 @@
* under the License.
*/

import { useContext, useEffect, useState } from "react";
import { useEffect, useState } from "react";

import useRolesService from "../../../../api/userroles/role";
import { ReactComponent as PlusIcon } from "../../../../assets/plus.svg";
import Badge from "../../badge";

import { ReactComponent as TrashIcon } from "../../../../assets/trash.svg";

import { getImageUrl } from "../../../../utils";
import { PopupContentContext } from "../../../contexts/PopupContentContext";
import { PaginationData, USERROLES_PAGINATION_LIMIT } from "../../../pages/userroles";
import Button from "../../button";
import Pagination from "../../pagination";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../table";
import { PlaceholderTableRows } from "../../usersListTable/UsersListTable";
import { Role } from "../types";
import NoRolesFound from "./NoRolesFound";
import CreateNewRole from "./dialogs/CreateNewRole";
import DeleteRolesDialog from "./dialogs/DeleteRoles";
import EditRoleDialog from "./dialogs/EditRole";
import "./rolesTable.scss";

const PAGINATION_LIMIT = 10;

export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (value: boolean) => void }) {
const { getRoles } = useRolesService();
const { showToast } = useContext(PopupContentContext);
// used to stores roles data from response.
const [roles, setRoles] = useState<Role[]>([]);

type RolesTableProps = {
roles: Role[];
isFetchingRoles: boolean;
currentActivePage: number;
paginationData?: PaginationData;
setCurrentActivePage: (page: number) => void;
fetchRoles: () => void;
setRoles: (roles: Role[]) => void;
};

export function RolesTable({
roles,
isFetchingRoles,
currentActivePage,
paginationData,
setCurrentActivePage,
fetchRoles,
setRoles,
}: RolesTableProps) {
// used to determine what role does user have selected
const [selectedRole, setSelectedRole] = useState<Role | undefined>(undefined);
const [currentlySelectedRole, setCurrentlySelectedRole] = useState<Role | undefined>(undefined);

// used to control opening and closing dialog
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showCreateNewRoleDialogOpen, setShowCreateNewRoleDialogOpen] = useState(false);
const [showEditDialog, setShowEditDialog] = useState(false);

// data used to track pagination
const [currentActivePage, setCurrentActivePage] = useState(1);
const [paginationData, setPaginationData] = useState<
| {
totalPages: number;
rolesCount: number;
}
| undefined
>(undefined);
// managed fetchRoles http loading state.
const [isLoading, setIsLoading] = useState(false);

const fetchRoles = async () => {
setIsLoading(true);
setRoles([]);
try {
const response = await getRoles({ limit: PAGINATION_LIMIT.toString(), page: currentActivePage.toString() });

if (response !== undefined) {
if (response.status === "OK" && response.totalPages !== undefined) {
if (response.roles.length < 1 && currentActivePage !== 1) {
setCurrentActivePage(currentActivePage - 1);
return;
}
setRoles(response.roles);
setPaginationData({
rolesCount: response.rolesCount,
totalPages: response.totalPages,
});
}

if (response.status === "FEATURE_NOT_ENABLED_ERROR") {
setIsFeatureEnabled(false);
}
} else {
showToast({
iconImage: getImageUrl("form-field-error-icon.svg"),
toastType: "error",
children: <>Something went wrong Please try again!</>,
});
}
} catch (_) {
showToast({
iconImage: getImageUrl("form-field-error-icon.svg"),
toastType: "error",
children: <>Something went wrong Please try again!</>,
});
} finally {
setIsLoading(false);
}
};

useEffect(() => {
void fetchRoles();
}, [currentActivePage]);

return (
<>
<div className="search-add-role-container">
<Button
onClick={() => setShowCreateNewRoleDialogOpen(true)}
color="secondary">
<PlusIcon />
Add Role
</Button>
{showCreateNewRoleDialogOpen ? (
<CreateNewRole
refetchRoles={fetchRoles}
onCloseDialog={() => setShowCreateNewRoleDialogOpen(false)}
/>
) : null}
</div>
{isLoading === false && roles.length < 1 && currentActivePage === 1 ? (
{isFetchingRoles === false && roles.length < 1 && currentActivePage === 1 ? (
<NoRolesFound />
) : (
<div className="margin-bottom-36">
Expand All @@ -134,7 +70,7 @@ export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (valu
className="roles-list-pagination"
handleNext={() => setCurrentActivePage(currentActivePage + 1)}
handlePrevious={() => setCurrentActivePage(currentActivePage - 1)}
limit={PAGINATION_LIMIT}
limit={USERROLES_PAGINATION_LIMIT}
currentActivePage={currentActivePage}
totalPages={paginationData.totalPages}
offset={roles.length}
Expand All @@ -151,7 +87,7 @@ export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (valu
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
{isFetchingRoles ? (
<PlaceholderTableRows
rowCount={14}
colSpan={3}
Expand All @@ -163,7 +99,7 @@ export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (valu
<TableRow
key={role}
onClick={(e) => {
setSelectedRole(roles[index]);
setCurrentlySelectedRole(roles[index]);
setShowEditDialog(true);
}}>
<TableCell>{role}</TableCell>
Expand All @@ -174,7 +110,7 @@ export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (valu
onClick={(e) => {
e.stopPropagation();
setShowDeleteDialog(true);
setSelectedRole(roles[index]);
setCurrentlySelectedRole(roles[index]);
}}
className="delete-role">
<TrashIcon />
Expand All @@ -186,18 +122,18 @@ export function RolesTable({ setIsFeatureEnabled }: { setIsFeatureEnabled: (valu
})}
</TableBody>
</Table>
{showDeleteDialog && selectedRole !== undefined ? (
{showDeleteDialog && currentlySelectedRole !== undefined ? (
<DeleteRolesDialog
refetchRoles={fetchRoles}
onCloseDialog={() => setShowDeleteDialog(false)}
selectedRole={selectedRole?.role}
currentlySelectedRoleName={currentlySelectedRole.role}
/>
) : null}
{showEditDialog && selectedRole !== undefined ? (
{showEditDialog && currentlySelectedRole !== undefined ? (
<EditRoleDialog
roles={roles}
setRoles={setRoles}
selectedRole={selectedRole}
currentlySelectedRole={currentlySelectedRole}
onCloseDialog={() => setShowEditDialog(false)}
/>
) : null}
Expand Down
6 changes: 3 additions & 3 deletions src/ui/components/userroles/components/SelectPermissions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export default function SelectPermissions({
permissions,
permissionsToDelete,
setPermissionsToDelete,
addPermissions,
addPermission,
openDeletePermissionsDialog,
}: {
permissions: string[];
addPermissions: (permissions: string[]) => void;
addPermission: (permissions: string) => void;
permissionsToDelete: string[];
setPermissionsToDelete: (permissions: string[]) => void;
openDeletePermissionsDialog: () => void;
Expand All @@ -40,7 +40,7 @@ export default function SelectPermissions({
if (e.key === "Enter") {
const newTag = e.currentTarget.value.trim();
if (newTag !== "" && permissions.includes(newTag) === false) {
addPermissions([newTag]);
addPermission(newTag);
}
e.currentTarget.value = "";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,80 +13,20 @@
* under the License.
*/

import { useContext, useState } from "react";
import { usePermissionsService } from "../../../../../api/userroles/role/permissions";
import { getImageUrl } from "../../../../../utils";
import { PopupContentContext } from "../../../../contexts/PopupContentContext";
import Button from "../../../button";
import { Dialog, DialogContent, DialogFooter } from "../../../dialog";
import { Role } from "../../types";

export default function DeletePermissionDialog({
roles,
selectedRole,
selectedPermissions,
setRoles,
isDeletingRoles,
onCloseDialog,
updatePermissions,
resetPermissionsToDelete,
handleDeletePermissions,
}: {
roles: Role[];
selectedPermissions: string[];
selectedRole: Role;
onCloseDialog: () => void;
setRoles: (roles: Role[]) => void;
resetPermissionsToDelete: () => void;
updatePermissions: (permissions: string[]) => void;
handleDeletePermissions: () => void;
isDeletingRoles: boolean;
}) {
const { showToast } = useContext(PopupContentContext);

const { removePermissionsFromRole } = usePermissionsService();

const [isDeletingRoles, setIsDeletingRoles] = useState(false);

const { permissions, role } = selectedRole;

async function handleDeleteRoles() {
if (selectedPermissions.length === 0) {
return;
}
setIsDeletingRoles(true);

try {
await removePermissionsFromRole(role, selectedPermissions);

const filteredPermissions = permissions.filter((p) => selectedPermissions.includes(p) === false);

const updatedRolesData = roles.map((role) => {
if (role.role === selectedRole.role) {
role.permissions = filteredPermissions;
}
return role;
});

setRoles(updatedRolesData);
updatePermissions(filteredPermissions);
resetPermissionsToDelete();
showToast({
iconImage: getImageUrl("checkmark-green.svg"),
toastType: "success",
children:
selectedPermissions.length === 1
? "Permission deleted successfully!"
: "Permissions deleted successfully!",
});
onCloseDialog();
} catch (_) {
showToast({
iconImage: getImageUrl("form-field-error-icon.svg"),
toastType: "error",
children: <>Something went wrong Please try again!</>,
});
} finally {
setIsDeletingRoles(false);
}
}

return (
<Dialog
title="Delete Permission?"
Expand All @@ -106,7 +46,7 @@ export default function DeletePermissionDialog({
color="danger"
isLoading={isDeletingRoles}
disabled={isDeletingRoles}
onClick={handleDeleteRoles}>
onClick={handleDeletePermissions}>
Yes, Delete
</Button>
</DialogFooter>
Expand Down
13 changes: 5 additions & 8 deletions src/ui/components/userroles/components/dialogs/DeleteRoles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ import { Dialog, DialogContent, DialogFooter } from "../../../dialog";
import "./deleteRoles.scss";

export default function DeleteRolesDialog({
selectedRole,
currentlySelectedRoleName,
refetchRoles,
onCloseDialog,
}: {
selectedRole: string;
currentlySelectedRoleName: string;
refetchRoles: () => void;
onCloseDialog: () => void;
}) {
Expand All @@ -38,13 +38,10 @@ export default function DeleteRolesDialog({
const [isDeletingRoles, setIsDeletingRoles] = useState(false);

async function handleDeleteRoles() {
if (typeof selectedRole !== "string") {
return;
}
setIsDeletingRoles(true);

try {
await deleteRole(selectedRole);
await deleteRole(currentlySelectedRoleName);
showToast({
iconImage: getImageUrl("checkmark-green.svg"),
toastType: "success",
Expand All @@ -69,8 +66,8 @@ export default function DeleteRolesDialog({
onCloseDialog={onCloseDialog}>
<DialogContent>
<p className="you-sure-text">
Are you sure you want to delete Role: <span className="red">{selectedRole}</span>? This action is
irreversible.
Are you sure you want to delete Role: <span className="red">{currentlySelectedRoleName}</span>? This
action is irreversible.
</p>
<DialogFooter border="border-none">
<Button
Expand Down
Loading

0 comments on commit aaa9619

Please sign in to comment.