All files / pages/admin/ManageUser ManageUserPage.tsx

58.26% Statements 67/115
43.9% Branches 18/41
38.7% Functions 12/31
58.26% Lines 67/115

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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 3591x   1x 1x 1x 1x 1x 1x 1x 1x   1x       1x 1x 1x 1x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x 1x 1x 1x 1x       12x                                 12x 7x               12x                         12x       12x 5x                 12x 5x           5x                                                         12x 5x           5x           12x                                 12x                                                                                                                                       12x         6x 6x   6x 6x 6x   6x   6x 4x 4x   4x   2x 1x 1x   1x     1x 1x 1x   1x       12x       12x                 12x                                                                                                                                                                     1x  
import SearchFieldComponent from "@/components/SearchFieldComponent/SearchFieldComponent";
import { User } from "@/types/User";
import { Button, Table, TableColumnsType, message, Badge } from "antd";
import { useSearchParams } from "react-router-dom";
import "./ManageUserPage.css";
import { CloseCircleOutlined, EditOutlined } from "@ant-design/icons";
import Filter from "@/components/FilterComponent/Filter";
import CustomPagination from "@/components/Pagination/CustomPagination";
import { useMutation, useQuery } from "react-query";
import { UserAPICaller } from "@/services/apis/user.api";
import UserSearchParams from "@/types/UserSearchParams";
import { useEffect, useState } from "react";
import type { TableProps } from "antd/es/table";
import APIResponse from "@/types/APIResponse";
import { SorterResult } from "antd/es/table/interface";
import UserDetailsModal from "./components/UserDetailsModal";
import { useNavigate, useLocation } from "react-router-dom";
import NotificationModal from "@/components/NotificationModal/NotificationModal";
import ConfirmationModal from "@/components/ConfirmationModal/ConfirmationModal";
function ManageUserPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const location = useLocation();
  const { newUser } = location.state || {};
  const [showModal, setShowModal] = useState<boolean>(false);
  const [userData, setUserData] = useState<User>();
  const [items, setItems] = useState<User[]>([]);
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [openNotiModal, setOpenNotiModal] = useState(false);
  const [userDeleteId, setUserDeleteId] = useState<number>(0);
 
  const onSearch = (value: string) => {
    setSearchParams((p) => {
      p.set("search", value);
      p.delete("page");
      return p;
    });
  };
 
  const params: UserSearchParams = {
    searchString: searchParams.get("search") || "",
    type: searchParams.get("type") || "",
    orderBy: searchParams.get("orderBy") || undefined,
    sortDir: searchParams.get("sortDir") || undefined,
    pageNumber: Number(searchParams.get("page") || "1"),
    pageSize: Number("20"),
  };
 
  const {
    data: queryData,
    isSuccess,
    isError,
    isLoading,
    isFetching,
    error,
    refetch,
  } = useQuery(["getAllUsers", { params }], () =>
    UserAPICaller.getSearchUser(params)
  );
 
  const {
    data: validAssignData,
    isSuccess: isSuccessValidAssign,
    isError: isErrorValidAssign,
    refetch: refetchValidAssign,
  } = useQuery(
    ["getHistoryAsset", { userDeleteId }],
    () => UserAPICaller.checkValidAssignment(userDeleteId),
    {
      enabled: false,
    }
  );
 
  const {
    isSuccess: isSuccessDelete,
    isError: isErrorDelete,
    error: errorDelete,
    mutate: deleteMutate,
  } = useMutation(["deleteAsset", { userDeleteId }], () =>
    UserAPICaller.deleteUser(userDeleteId)
  );
 
  useEffect(() => {
    Iif (isSuccessValidAssign) {
      if (validAssignData.data.result === true) {
        setOpenNotiModal(true);
      } else {
        setOpenConfirmModal(true);
      }
    }
  }, [isSuccessValidAssign, isErrorValidAssign, validAssignData]);
 
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccess) {
      let updatedItems = queryData.data.result.data;
      Iif (newUser) {
        updatedItems = updatedItems.filter(
          (item: User) => item.id !== newUser.id
        );
        updatedItems = [newUser, ...updatedItems];
        while (updatedItems.length > 20) {
          updatedItems.pop();
        }
      }
      const pageCount = Math.ceil(queryData?.data.result.total / 20);
      const currentPage = Number(searchParams.get("page")) || 1;
      Iif (
        pageCount < currentPage &&
        searchParams.get("page") !== "1" &&
        !isFetching
      ) {
        setSearchParams((p) => {
          p.set("page", pageCount === 0 ? "1" : pageCount.toString());
          return p;
        });
        refetch();
      }
      window.history.replaceState({}, "");
      setItems(updatedItems);
    }
  }, [error, isError, isSuccess, queryData]);
 
  useEffect(() => {
    Iif (isErrorDelete) {
      const errorResponse = (errorDelete as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccessDelete) {
      message.success("Disable user successfully");
      refetch();
    }
  }, [isErrorDelete, isSuccessDelete, errorDelete]);
 
  const baseUser: User = {
    id: 0,
    staffCode: "",
    firstName: "",
    lastName: "",
    username: "",
    joinDate: new Date(),
    dob: new Date(),
    gender: "",
    status: "",
    type: "",
    location: {
      id: 0,
      name: "",
    },
  };
 
  const columns: TableColumnsType<User> = [
    {
      title: "Staff Code",
      dataIndex: "staffCode",
      showSorterTooltip: true,
      sorter: true, // add API later
      key: "staffCode",
    },
    {
      title: "Name",
      dataIndex: "fullName",
      showSorterTooltip: true,
      sorter: true, // add API later
      render: (_text, record) => `${record.firstName} ${record.lastName}`,
      key: "Name",
      ellipsis: true,
    },
    {
      title: "Username",
      dataIndex: "username",
      showSorterTooltip: true,
      key: "username",
      ellipsis: true,
    },
    {
      title: "Joined Date",
      dataIndex: "joinDate",
      showSorterTooltip: true,
      sorter: true,
      key: "joinDate",
    },
    {
      key: "type",
      title: "Type",
      dataIndex: "type",
      showSorterTooltip: true,
      sorter: true,
      ellipsis: true, // add API later
      render: (_text, record) => {
        return record.type === "ADMIN" ? "Admin" : "Staff";
      },
    },
    {
      title: "",
      dataIndex: "action",
      render: (_, record) => (
        <div className="flex space-x-5">
          <EditOutlined
            onClick={(e) => {
              e.stopPropagation();
              handleEditUser(record.id);
            }}
          />
          <CloseCircleOutlined
            style={{ color: "red" }}
            onClick={async (e) => {
              e.stopPropagation();
              await setUserDeleteId(record.id);
              refetchValidAssign();
            }}
          />
          {newUser && newUser.id === record.id && <Badge count={"New"} />}
        </div>
      ),
      key: "action",
    },
  ];
 
  const handleTableChange: TableProps<User>["onChange"] = (
    _pagination,
    _filteers,
    sorter
  ) => {
    sorter = sorter as SorterResult<User>;
    const { field, order } = sorter;
 
    const fieldString = field as string;
    setSearchParams((searchParams) => {
      searchParams.set("orderBy", fieldString);
 
      return searchParams;
    });
    if (order === "ascend") {
      setSearchParams((searchParams) => {
        searchParams.set("sortDir", "asc");
 
        return searchParams;
      });
    } else if (order === "descend") {
      setSearchParams((searchParams) => {
        searchParams.set("sortDir", "desc");
 
        return searchParams;
      });
    } else
      setSearchParams((searchParams) => {
        searchParams.delete("sortDir");
        searchParams.delete("orderBy");
 
        return searchParams;
      });
  };
 
  const handleCreateUser = () => {
    navigate("/admin/users/createUser");
  };
 
  const handleEditUser = (id: number) => {
    navigate(`/admin/users/edit-user/${id}`);
  };
 
  function handleDelete() {
    deleteMutate();
    setOpenConfirmModal(false);
  }
 
  return (
    <div className="">
      <h1 className="text-3xl font-bold text-red-500">User List</h1>
      <div className="flex  pt-2 ">
        <div>
          <Filter
            title={"Type"}
            options={[
              { label: "Admin", value: "ADMIN" },
              { label: "Staff", value: "STAFF" },
            ]}
            paramName={"type"}
          />
        </div>
        <div className=" flex flex-1 justify-end space-x-5">
          <SearchFieldComponent onSearch={onSearch} />
          <Button
            danger
            type="primary"
            color="#CF2338"
            onClick={handleCreateUser}
          >
            Create new user
          </Button>
        </div>
      </div>
      <div className="pt-8">
        <Table
          columns={columns}
          pagination={false}
          loading={isLoading}
          dataSource={items}
          rowKey={(record) => record.id}
          rowClassName={"cursor-pointer"}
          onChange={handleTableChange}
          onRow={(_, index) => {
            return {
              onClick: (e) => {
                e.stopPropagation();
                setUserData(items[index || 0]);
                setShowModal(true);
              },
            };
          }}
        ></Table>
        <div className="pt-8 flex justify-end">
          <CustomPagination
            totalItems={queryData?.data.result.total}
          ></CustomPagination>
        </div>
      </div>
      <UserDetailsModal
        show={showModal}
        data={userData || baseUser}
        handleClose={() => {
          setShowModal(false);
        }}
      />
      <NotificationModal
        isOpen={openNotiModal}
        title={<p className="text-[#e9424d]">Can not disable user</p>}
        message={
          <p>
            There are valid assignments belonging to this user. Please close all
            assignment before disabling user.
          </p>
        }
        onCancel={() => setOpenNotiModal(false)}
      />
      <ConfirmationModal
        isOpen={openConfirmModal}
        title={<p className="text-[#e9424d]">Are you sure?</p>}
        message={<p>Do you want to disable this user?</p>}
        onCancel={() => setOpenConfirmModal(false)}
        buttontext="Disable"
        onConfirm={() => {
          handleDelete();
        }}
      />
    </div>
  );
}
 
export default ManageUserPage;