All files / pages/admin/CreateAssignment/components ModalSelectAsset.tsx

66.66% Statements 34/51
33.33% Branches 1/3
40% Functions 6/15
66.66% Lines 34/51

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 2403x 3x 3x       3x                   3x 3x   3x                       12x 12x 12x                                 12x   1x         12x 10x               12x                 12x         3x 3x   3x 3x 3x 3x 3x     3x     12x                                                                                     12x                         12x                         12x 1x 1x 1x                     12x         12x                                                                                                                 3x  
import CustomPagination from "@/components/Pagination/CustomPagination";
import SearchFieldComponent from "@/components/SearchFieldComponent/SearchFieldComponent";
import { AssetAPICaller } from "@/services/apis/asset.api";
import APIResponse from "@/types/APIResponse";
import { AssetResponse } from "@/types/Asset";
import AssetSearchParams from "@/types/AssetSearchParams";
import {
  Button,
  Modal,
  Table,
  TableColumnsType,
  TableProps,
  Typography,
  message,
} from "antd";
import { SorterResult } from "antd/es/table/interface";
import { useEffect, useState } from "react";
import { useQuery } from "react-query";
 
const PAGE_SIZE = 10;
 
function ModalSelectAsset({
  isOpen,
  setIsOpenModal,
  setAsset,
}: {
  isOpen: boolean;
  setIsOpenModal: (isOpen: boolean) => void;
  setAsset: (asset: AssetResponse) => void;
}) {
  // state
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const [selectedAsset, setSelectedAsset] = useState<AssetResponse>();
  const [params, setParams] = useState<AssetSearchParams>({
    searchString: "",
    states: "AVAILABLE",
    categoryIds: "",
    orderBy: undefined,
    sortDir: undefined,
    pageNumber: 1,
    pageSize: PAGE_SIZE,
  });
 
  // query
  const {
    data: queryData,
    isError,
    isLoading,
    error,
    refetch,
  } = useQuery(
    ["getAllAssets", { params }],
    () => AssetAPICaller.getSearchAssets(params),
    { enabled: isOpen }
  );
 
  // effect
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
  }, [isError]);
 
  // handlers
  const onSearch = (value: string) => {
    setParams((params) => {
      params.searchString = value;
      params.pageNumber = 1;
      return params;
    });
    refetch();
  };
 
  const handleTableChange: TableProps<AssetResponse>["onChange"] = (
    _pagination,
    _filteers,
    sorter
  ) => {
    sorter = sorter as SorterResult<AssetResponse>;
    const { field, order } = sorter;
 
    const fieldString = field as string;
    setParams((params) => {
      params.orderBy = fieldString;
      params.sortDir = order === "ascend" ? "asc" : "desc";
      return params;
    });
 
    refetch();
  };
 
  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",
      width: "60%",
      render: (assetName: string) => (
        <Typography.Paragraph
          ellipsis={{
            expandable: "collapsible",
          }}
        >
          {assetName}
        </Typography.Paragraph>
      ),
    },
    {
      title: "Category",
      dataIndex: "category",
      showSorterTooltip: true,
      sorter: true,
      key: "category",
      width: "30%",
      render: (assetName: string) => (
        <Typography.Paragraph
          ellipsis={{
            expandable: "collapsible",
          }}
        >
          {assetName}
        </Typography.Paragraph>)
    },
  ];
 
  const rowSelection = {
    onChange: (
      _selectedRowKeys: React.Key[],
      selectedRows: AssetResponse[]
    ) => {
      setIsButtonDisabled(false);
      setSelectedAsset(selectedRows[0]);
    },
    getCheckboxProps: (record: AssetResponse) => ({
      name: record.name,
    }),
  };
 
  const handlePageChange = (page: number) => {
    setParams({
      searchString: "",
      states: "AVAILABLE",
      categoryIds: "",
      orderBy: undefined,
      sortDir: undefined,
      pageNumber: page,
      pageSize: PAGE_SIZE,
    });
    refetch();
  };
 
  const handleCancel = () => {
    setIsButtonDisabled(true);
    setIsOpenModal(false);
    setParams({
      searchString: "",
      states: "AVAILABLE",
      categoryIds: "",
      orderBy: undefined,
      sortDir: undefined,
      pageNumber: 1,
      pageSize: PAGE_SIZE,
    });
  };
 
  const handleSave = () => {
    handleCancel();
    setAsset(selectedAsset as AssetResponse);
  };
 
  return (
    <>
      <Modal
        title={
          <div>
            <p className="text-lg font-semibold primary-color">Select Asset</p>
          </div>
        }
        destroyOnClose={true}
        open={isOpen}
        closable={false}
        okText="Save"
        width={800}
        footer={[
          <Button
            key="save"
            className="text-[#E9424D] mr-2"
            disabled={isButtonDisabled}
            danger
            type="primary"
            onClick={handleSave}
          >
            Save
          </Button>,
          <Button key="cancel" onClick={handleCancel}>
            Cancel
          </Button>,
        ]}
      >
        <div className="my-2 flex justify-end">
          <SearchFieldComponent onSearch={onSearch} />
        </div>
        <Table
          rowSelection={{
            type: "radio",
            ...rowSelection,
          }}
          pagination={false}
          onChange={handleTableChange}
          rowKey={(record) => record.id}
          loading={isLoading}
          dataSource={queryData?.data?.result?.data}
          columns={columns}
        />
        <div className="my-4 flex justify-end">
          <CustomPagination
            totalItems={queryData?.data.result.total}
            pageSize={PAGE_SIZE}
            handleChange={handlePageChange}
            currentPageNumber={params.pageNumber}
          ></CustomPagination>
        </div>
      </Modal>
    </>
  );
}
 
export default ModalSelectAsset;