All files / pages/admin/ManageAsset ManageAssetPage.tsx

59.16% Statements 71/120
55.76% Branches 29/52
45.45% Functions 15/33
59.32% Lines 70/118

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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 4391x 1x 1x             1x 1x 1x 1x 1x           1x   1x 1x 1x 1x     10x   9x   9x   9x   9x   9x   9x   9x   9x   9x               9x   9x                                       9x 5x                     9x   9x                             9x                             9x           9x 6x                   9x 6x           6x 2x 2x             2x 2x 2x                   2x 2x           9x 4x           4x               9x 4x                   9x                                                                     2x           2x                                                                               9x         1x 1x 1x 1x 1x   1x   1x 1x 1x   1x                                 9x         9x         9x                               9x                                       4x                                                 6x           2x                                                                                               1x  
import SearchFieldComponent from "@/components/SearchFieldComponent/SearchFieldComponent";
import { Button, Table, TableColumnsType, Badge, message } from "antd";
import {
  NavLink,
  useLocation,
  useNavigate,
  useSearchParams,
} from "react-router-dom";
 
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 { useEffect, useState } from "react";
import type { TableProps } from "antd/es/table";
import APIResponse from "@/types/APIResponse";
import { SorterResult } from "antd/es/table/interface";
import { AssetResponse } from "@/types/Asset";
import AssetSearchParams from "@/types/AssetSearchParams";
import { AssetAPICaller } from "@/services/apis/asset.api";
import { Category } from "@/types/Category";
import { CategoryAPICaller } from "@/services/apis/category.api";
import AssetDetailsModal from "./components/AssetDetailsModal";
import ConfirmationModal from "@/components/ConfirmationModal/ConfirmationModal";
import NotificationModal from "@/components/NotificationModal/NotificationModal";
 
function ManageAssetPage() {
  const [searchParams, setSearchParams] = useSearchParams();
 
  const [items, setItems] = useState<AssetResponse[]>([]);
 
  const [showModal, setShowModal] = useState(false);
 
  const [assetData, setAssetData] = useState<AssetResponse>();
 
  const location = useLocation();
 
  const { asset } = location.state || {};
 
  const [openNotificationModal, setOpenNotificationModal] = useState(false);
 
  const [openConfirmationModal, setOpenConfirmationModal] = useState(false);
 
  const navigate = useNavigate();
 
  const onSearch = (value: string) => {
    setSearchParams((p) => {
      p.set("search", value);
      p.delete("page");
      return p;
    });
  };
 
  const [idAsset, setIdAsset] = useState<number>(0);
 
  const params: AssetSearchParams = {
    searchString: searchParams.get("search") || "",
    states: searchParams.get("states") || "",
    categoryIds: searchParams.get("category") || "",
    orderBy: searchParams.get("orderBy") || undefined,
    sortDir: searchParams.get("sortDir") || undefined,
    pageNumber: Number(searchParams.get("page") || "1"),
    pageSize: Number("20"),
  };
 
  // UseQuery For Asset
 
  const {
    data: queryData,
    isSuccess,
    isError,
    isLoading,
    error,
    isFetching,
    refetch,
  } = useQuery(["getAllAssets", { params }], () =>
    AssetAPICaller.getSearchAssets(params)
  );
 
  // UseQuery For Category
 
  const {
    data: categoryData,
    isLoading: isLoadingCategory,
    isSuccess: isSuccessCategory,
    isError: isErrorCategory,
    error: errorCategory,
  } = useQuery(["getAllCategory"], () => CategoryAPICaller.getAll());
 
  const displayState = {
    AVAILABLE: "Available",
    NOT_AVAILABLE: "Not Available",
    ASSIGNED: "Assigned",
    WAITING_FOR_RECYCLE: "Waiting for recycle",
    RECYCLED: "Recycled",
  };
 
  // UseQuery For History
 
  const {
    data: historyData,
    isSuccess: isSuccessHistory,
    isError: isErrorHistory,
    refetch: refetchHistory,
  } = useQuery(
    ["getHistoryAsset", { idAsset }],
    () => AssetAPICaller.getAssetHistory(idAsset),
    {
      enabled: false,
    }
  );
 
  //  useMutation For Delete Asset
 
  const {
    isSuccess: isSuccessDelete,
    isError: isErrorDelete,
    error: errorDelete,
    mutate: deleteMutate,
  } = useMutation(["deleteAsset", { idAsset }], () =>
    AssetAPICaller.deleteAsset(idAsset)
  );
 
  // useEffect for Category
 
  useEffect(() => {
    Iif (isErrorCategory) {
      const errorResponse = (
        errorCategory as { response: { data: APIResponse } }
      ).response.data;
      message.error(errorResponse.message);
    }
  }, [isErrorCategory, isSuccessCategory, categoryData, errorCategory]);
 
  // useEffect for Asset
 
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    if (isSuccess) {
      let temp = [...queryData.data.result.data];
      Iif (asset) {
        temp = temp.filter((item: AssetResponse) => asset.id !== item.id);
        temp = [asset, ...temp];
        while (temp.length > 20) {
          temp.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;
        });
      }
      window.history.replaceState({}, "");
      setItems(temp);
    }
  }, [error, isError, isSuccess, queryData]);
 
  // useEffect for Delete Asset
 
  useEffect(() => {
    Iif (isErrorDelete) {
      const errorResponse = (errorDelete as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccessDelete) {
      message.success("Delete asset successfully");
      refetch();
    }
  }, [isErrorDelete, isSuccessDelete, errorDelete]);
 
  //useEffect for History
 
  useEffect(() => {
    Iif (isSuccessHistory) {
      if (historyData.data.result == true) {
        setOpenNotificationModal(true);
      } else {
        setOpenConfirmationModal(true);
      }
    }
    // setEnable(false);
  }, [isSuccessHistory, isErrorHistory, historyData]);
 
  const columns: TableColumnsType<AssetResponse> = [
    {
      title: "Asset Code",
      dataIndex: "assetCode",
      showSorterTooltip: true,
      sorter: true, // add API later
      key: "assetCode",
    },
    {
      title: "Asset Name",
      dataIndex: "name",
      showSorterTooltip: true,
      sorter: true, // add API later
      key: "Name",
      ellipsis: true,
    },
    {
      title: "Category",
      dataIndex: "category",
      showSorterTooltip: true,
      sorter: true,
      key: "category",
    },
    {
      key: "State",
      title: "State",
      dataIndex: "state",
      showSorterTooltip: true,
      sorter: true, // add API later
      render: (
        state:
          | "AVAILABLE"
          | "NOT_AVAILABLE"
          | "WAITING_FOR_RECYCLE"
          | "RECYCLED"
      ) => displayState[state],
    },
    {
      title: "",
      dataIndex: "action",
      render: (_text, record) => (
        <div className="flex space-x-5">
          <button
            disabled={record.state == "ASSIGNED"}
            onClick={(e) => {
              e.stopPropagation();
              navigate(`/admin/assets/edit-asset/${record.id}`);
            }}
            className={
              record.state == "ASSIGNED"
                ? "cursor-not-allowed"
                : "hover:opacity-70 hover:text-red-600"
            }
          >
            <EditOutlined
              data-testid="edit-assignment"
              style={{ color: record.state == "ASSIGNED" ? "gray" : "black" }}
            />
          </button>
 
          {/* <Button disabled={true}> */}
          <button
            disabled={record.state == "ASSIGNED"}
            onClick={(e) => {
              e.stopPropagation();
              handleDeleteButton(record.id);
            }}
          >
            <CloseCircleOutlined
              data-testid="delete-asset"
              style={{ color: record.state == "ASSIGNED" ? "black" : "red" }}
            />
          </button>
          {/* </Button> */}
          {asset && asset.id === record.id && <Badge count={"New"} />}
        </div>
      ),
      key: "action",
    },
  ];
 
  const handleTableChange: TableProps<AssetResponse>["onChange"] = (
    _pagination,
    _filteers,
    sorter
  ) => {
    sorter = sorter as SorterResult<AssetResponse>;
    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 Eif (order === "descend") {
      setSearchParams((searchParams) => {
        searchParams.set("sortDir", "desc");
 
        return searchParams;
      });
    } else
      setSearchParams((searchParams) => {
        searchParams.delete("sortDir");
        searchParams.delete("orderBy");
 
        return searchParams;
      });
  };
 
  const handleDeleteButton = async (id: number) => {
    await setIdAsset(id);
    refetchHistory();
  };
 
  const handleDelete = () => {
    deleteMutate();
    setOpenConfirmationModal(false);
  };
 
  const baseAsset = {
    id: 1,
    name: "",
    specification: "",
    category: "",
    assetCode: "",
    installDate: new Date(),
    state: "ASSIGNED",
    location: {
      id: 1,
      name: "Ho Chi Minh",
      code: "HCM",
    },
    EAssetSate: "",
  } as AssetResponse;
 
  return (
    <div className="">
      <h1 className="text-3xl font-bold text-red-500">Asset List</h1>
      <div className="flex  pt-2 ">
        <div className="flex space-x-3">
          <Filter
            title={"State"}
            options={[
              { label: "Assigned", value: "ASSIGNED" },
              { label: "Available", value: "AVAILABLE" },
              { label: "Not Available", value: "NOT_AVAILABLE" },
              { label: "Waiting for recycle", value: "WAITING_FOR_RECYCLE" },
              { label: "Recycled", value: "RECYCLED" },
            ]}
            paramName={"states"}
            allowedMultiple={true}
          />
          <Filter
            title={"Category"}
            options={
              categoryData?.data?.result.map((category: Category) => ({
                label: category.name,
                value: category.id,
              })) || []
            }
            paramName={"category"}
            allowedMultiple={true}
          />
        </div>
        <div className=" flex flex-1 justify-end space-x-5">
          <SearchFieldComponent onSearch={onSearch} />
          <Button
            danger
            type="primary"
            color="#CF2338"
            onClick={() => navigate("create-asset")}
          >
            Create new asset
          </Button>
        </div>
      </div>
      <div className="pt-8">
        <Table
          columns={columns}
          pagination={false}
          rowKey={(record) => record.id}
          onChange={handleTableChange}
          loading={isLoading && isLoadingCategory}
          dataSource={items}
          rowClassName={"cursor-pointer"}
          onRow={(_, index) => {
            return {
              onClick: (e) => {
                e.stopPropagation();
                setAssetData(items[index || 0]);
                setShowModal(true);
              },
            };
          }}
        ></Table>
        <div className="pt-8 flex justify-end">
          <CustomPagination
            totalItems={queryData?.data.result.total}
          ></CustomPagination>
        </div>
      </div>
      <AssetDetailsModal
        assetData={assetData || baseAsset}
        show={showModal}
        handleClose={() => {
          setShowModal(false);
        }}
      />
      <ConfirmationModal
        isOpen={openConfirmationModal}
        title={<p className="text-[#e9424d]">Are you sure?</p>}
        message={<p>Do you want to delete thist asset?</p>}
        onCancel={() => setOpenConfirmationModal(false)}
        buttontext="Delete"
        onConfirm={() => {
          handleDelete();
        }}
      />
      <NotificationModal
        isOpen={openNotificationModal}
        title={<p className="text-[#e9424d]">Cannot Delete Asset</p>}
        message={
          <p>
            Cannot delete the asset because it belongs to one or more historical
            assignments. If the asset is not able to be used anymore, please
            update its state in <NavLink className="underline text-blue-500" to={`/admin/assets/edit-asset/${idAsset}`}>Edit Asset Page</NavLink>
          </p>
        }
        onCancel={() => setOpenNotificationModal(false)}
      />
    </div>
  );
}
 
export default ManageAssetPage;