All files / react-app/src/features/user-roles UserManagement.tsx

53.08% Statements 43/81
65.45% Branches 36/55
41.17% Functions 7/17
53.94% Lines 41/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330                                                                                            4x         99x 99x   39x   48x   7x   5x     99x                                                                                                                       4x 12x 12x 12x 12x 12x   12x 12x 12x   12x                                 12x       12x   12x 146x       71x   10x   7x       12x 8x               8x 7x 1x 1x 1x     12x                     12x 8x   4x     4x   4x   8x     12x                                                 12x                                                                                                                                                                                            
import { EllipsisVerticalIcon } from "@heroicons/react/24/outline";
import { ExportToCsv } from "export-to-csv";
import LZ from "lz-string";
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router";
import { formatDate, formatDateToET } from "shared-utils";
import { userRoleMap } from "shared-utils";
 
import { RoleRequest, useGetRoleRequests, useGetUserDetails, useSubmitRoleRequests } from "@/api";
import {
  banner,
  Button,
  ConfirmationDialog,
  LoadingSpinner,
  Popover,
  PopoverContent,
  PopoverTrigger,
  // SubNavHeader,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components";
import { cn } from "@/utils";
 
import { initSortUserData, sortUserData, UserRoleType } from "./utils";
 
type headingType = { [key: string]: keyof UserRoleType | null };
 
type SelectedUser = RoleRequest & { fullName: string };
 
const pendingCircle = (
  <svg
    className="mr-2"
    width="9"
    height="9"
    viewBox="0 0 9 9"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <circle cx="4.5" cy="4.5" r="4.5" fill="#3D94D0" />
  </svg>
);
 
export const renderCellActions = (
  userRole: UserRoleType,
  setModalText: React.Dispatch<React.SetStateAction<string>>,
  setSelectedUserRole: React.Dispatch<React.SetStateAction<object>>,
) => {
  const actions = (function () {
    switch (userRole.status) {
      case "pending":
        return ["Grant Access", "Deny Access"];
      case "active":
        return ["Revoke Access"];
      case "denied":
        return ["Grant Access"];
      case "revoked":
        return ["Grant Access"];
    }
  })();
  const actionChosen = (action: string) => {
    const modalAction = {
      "Grant Access": "grant",
      "Deny Access": "deny",
      "Revoke Access": "revoke",
    };
 
    const requestFor = userRole.status === "pending" ? " request for" : "";
 
    const statusMap = {
      "Grant Access": "active",
      "Deny Access": "denied",
      "Revoke Access": "revoked",
    };
    //  in legacy there is logic to add the territory in front
    setModalText(
      `This will ${modalAction[action]} ${userRole.fullName}'s${requestFor} access to OneMac.`,
    );
    setSelectedUserRole({
      email: userRole.email,
      fullName: userRole.fullName,
      state: userRole.territory,
      role: userRole.role,
      grantAccess: statusMap[action],
      eventType: userRole.eventType,
      group: userRole.group ?? null,
      division: userRole.division ?? null,
      requestRoleChange: false,
    });
    console.log(userRole.role, "USERROLE");
  };
  return (
    <Popover>
      <PopoverTrigger
        disabled={!actions.length}
        className="block ml-3"
        aria-label="Available actions"
      >
        <EllipsisVerticalIcon
          aria-label="record actions"
          className={cn("w-8 ", actions.length ? "text-blue-700" : "text-gray-400")}
        />
      </PopoverTrigger>
      <PopoverContent className="w-auto">
        <div className="flex flex-col">
          {actions.map((action, idx) => (
            <div
              className="text-blue-500 cursor-pointer relative flex select-none items-center rounded-sm px-2 py-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground"
              key={idx}
              onClick={() => actionChosen(action)}
            >
              {action}
            </div>
          ))}
        </div>
      </PopoverContent>
    </Popover>
  );
};
 
export const UserManagement = () => {
  const { data: userDetails } = useGetUserDetails();
  const { data, isLoading, isFetching } = useGetRoleRequests();
  const { mutateAsync: submitRequest, isLoading: processSubmit } = useSubmitRoleRequests();
  const [userRoles, setUserRoles] = useState<UserRoleType[] | null>(null);
  const [selectedUserRole, setSelectedUserRole] = useState<SelectedUser>(null);
 
  const isHelpDesk = userDetails && userDetails?.role === "helpdesk";
  const isStateSystemAdmin = userDetails && userDetails.role === "statesystemadmin";
  const isSystemAdmin = userDetails && userDetails.role === "systemadmin";
 
  const getBannerText = (selectedUser: SelectedUser) => {
    const getStatusText = () => {
      switch (selectedUser.grantAccess) {
        case "active":
          return " has been granted access";
        case "denied":
          return " has been denied access";
        case "revoked":
          return "'s access has been revoked";
        default:
          return "'s access is pending";
      }
    };
 
    return `${selectedUser.fullName}${getStatusText()}`;
  };
 
  const [sortBy, setSortBy] = useState<{
    title: keyof headingType | "";
    direction: boolean;
  }>({ title: "", direction: false });
  const [modalText, setModalText] = useState<string | null>(null);
 
  const renderStatus = (value: string) => {
    switch (value) {
      case "pending":
        return <>{pendingCircle} Pending</>;
      case "active":
        return "Granted";
      case "denied":
        return "Denied";
      case "revoked":
        return "Revoked";
    }
  };
 
  const headings = useMemo(() => {
    const baseHeadings: headingType = {
      Name: "fullName",
      State: "territory",
      Status: "status",
      Role: "role",
      "Last Modified": "lastModifiedDate",
      "Modified By": "doneByName",
    };
    if (isHelpDesk) return baseHeadings;
    if (!isStateSystemAdmin) return { Actions: null, ...baseHeadings };
    delete baseHeadings.State;
    delete baseHeadings.Role;
    return { Actions: null, ...baseHeadings };
  }, [isHelpDesk, isStateSystemAdmin]);
 
  const sortByHeading = (heading: string) => {
    if (heading === "Actions") return;
 
    let direction = false;
    if (sortBy.title === heading) {
      setSortBy({ title: heading, direction: !sortBy.direction });
      direction = !sortBy.direction;
    } else setSortBy({ title: heading, direction: false });
    setUserRoles(sortUserData(headings[heading], direction, userRoles));
  };
 
  useEffect(() => {
    if (data && data.length) {
      let sorted: UserRoleType[];
      Iif (sortBy.title) {
        sorted = sortUserData(headings[sortBy.title], sortBy.direction, [...data]);
      } else {
        sorted = initSortUserData([...data]); // default sort if no column clicked yet
      }
      setUserRoles(sorted);
    }
    Iif (data && !data.length) setUserRoles([]);
  }, [data, sortBy, headings]);
 
  const onAcceptRoleChange = async () => {
    try {
      setModalText(null);
      await submitRequest(selectedUserRole);
      setSelectedUserRole(null);
 
      banner({
        header: "Status Change",
        body: `${getBannerText(selectedUserRole)}, a notification has been sent to their email.`,
        variant: "success",
        pathnameToDisplayOn: window.location.pathname,
      });
      window.scrollTo(0, 0);
    } catch (error) {
      console.error(error);
      banner({
        header: "An unexpected error has occurred:",
        body: error instanceof Error ? error.message : String(error),
        variant: "destructive",
        pathnameToDisplayOn: window.location.pathname,
      });
    }
  };
 
  // Export Section
  const handleExport = async () => {
    const modifiedUserRoles = userRoles.map((role) => ({
      Name: role.fullName,
      Email: role.email,
      State: role.territory,
      Status: role.status,
      Role: role.role,
      ["Last Modified"]: formatDate(role.lastModifiedDate),
      ["Modified By"]: role.doneByName,
    }));
 
    const csvExporter = new ExportToCsv({
      useKeysAsHeaders: true,
      filename: `Role-Requests-${formatDate(Date.now())}`,
    });
 
    csvExporter.generateCsv(modifiedUserRoles);
  };
 
  if (!userDetails || isLoading || processSubmit || isFetching || !userRoles)
    return <LoadingSpinner />;
  return (
    <div>
      <ConfirmationDialog
        open={modalText !== null}
        title="Modify User's Access?"
        body={modalText}
        acceptButtonText="Confirm"
        aria-labelledby="Modify User's Access Modal"
        onAccept={onAcceptRoleChange}
        onCancel={() => setModalText(null)}
      />
      <div className="bg-sky-100" data-testid="sub-nav-header">
        <div className="max-w-screen-xl m-auto px-4 lg:px-8 flex items-center py-4 justify-between">
          <h1 className="text-xl font-medium">User Management</h1>
          {(isHelpDesk || isSystemAdmin) && (
            <Button variant="outline" onClick={handleExport}>
              Export to Excel (CSV)
            </Button>
          )}
        </div>
      </div>
      <div className="py-5 px-10">
        <Table>
          <TableHeader className="[&_tr]:border-b sticky top-0 bg-white">
            <TableRow className="border-b transition-colors hover:bg-muted/50 ">
              {Object.keys(headings).map((title) => (
                <TableHead
                  key={title}
                  className="py-5 px-2 font-bold cursor-pointer max-w-fit"
                  onClick={() => sortByHeading(title)}
                  isActive={sortBy.title === title}
                  desc={sortBy.direction}
                >
                  {title}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {userRoles.map((userRole) => {
              return (
                <TableRow key={userRole.id}>
                  {!isHelpDesk && (
                    <TableCell className="py-5 px-4">
                      {renderCellActions(userRole, setModalText, setSelectedUserRole)}
                    </TableCell>
                  )}
                  <TableCell>
                    <Link
                      to={`/profile/${LZ.compressToEncodedURIComponent(userRole.email).replaceAll("+", "_")}`}
                      className="text-blue-500 flex select-none items-center px-2 py-2"
                    >
                      {userRole.fullName}
                    </Link>
                  </TableCell>
                  {!isStateSystemAdmin && <TableCell>{userRole.territory}</TableCell>}
                  <TableCell>
                    <span className="font-bold flex items-center">
                      {renderStatus(userRole.status)}
                    </span>
                  </TableCell>
                  {!isStateSystemAdmin && <TableCell>{userRoleMap[userRole.role]}</TableCell>}
                  <TableCell>{formatDateToET(userRole.lastModifiedDate)}</TableCell>
                  <TableCell>{userRole.doneByName}</TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>
    </div>
  );
};