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

59.7% Statements 40/67
14.28% Branches 1/7
40% Functions 8/20
59.7% Lines 40/67

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 2393x 3x 3x       3x                   3x 3x   3x                       13x 13x 13x                               13x   1x         13x 12x               13x                 13x         4x 4x   4x 4x 4x 4x     4x 4x 4x 4x                           4x     13x                                                                         13x               13x                   13x 1x 1x 1x 1x 1x 1x           13x         13x                                                                                                                 3x  
import CustomPagination from "@/components/Pagination/CustomPagination";
import SearchFieldComponent from "@/components/SearchFieldComponent/SearchFieldComponent";
import { UserAPICaller } from "@/services/apis/user.api";
import APIResponse from "@/types/APIResponse";
import { User } from "@/types/User";
import UserSearchParams from "@/types/UserSearchParams";
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 ModalSelectUser({
  isOpen,
  setIsOpenModal,
  setUserSelected,
}: {
  isOpen: boolean;
  setIsOpenModal: (isOpen: boolean) => void;
  setUserSelected: (user: User) => void;
}) {
  // state
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const [selectedUser, setSelectedUser] = useState<User>();
  const [params, setParams] = useState<UserSearchParams>({
    searchString: "",
    type: "",
    orderBy: null,
    sortDir: null,
    pageNumber: 1,
    pageSize: PAGE_SIZE,
  });
 
  // query
  const {
    data: queryData,
    isError,
    isLoading,
    error,
    refetch,
  } = useQuery(
    ["getUserAssign", { params }],
    () => UserAPICaller.getUserAssign(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<User>["onChange"] = (
    _pagination,
    _filteers,
    sorter
  ) => {
    sorter = sorter as SorterResult<User>;
    const { field, order } = sorter;
 
    const fieldString = field as string;
    setParams((params) => {
      params.orderBy = fieldString;
      return params;
    });
 
    if (order === "ascend") {
      setParams((params) => {
        params.sortDir = "asc";
        return params;
      });
    } else Eif (order === "descend") {
      setParams((params) => {
        params.sortDir = "desc";
        return params;
      });
    } else {
      setParams((params) => {
        params.sortDir = null;
        params.orderBy = null;
        return params;
      });
    }
    refetch();
  };
 
  const columns: TableColumnsType<User> = [
    {
      title: "Staff Code",
      dataIndex: "staffCode",
      showSorterTooltip: true,
      sorter: true, // add API later
      key: "staffCode",
    },
    {
      title: "Full Name",
      dataIndex: "fullName",
      showSorterTooltip: true,
      sorter: true, // add API later
      width: "60%",
      render: (_text, record) => (
        <Typography.Paragraph
          ellipsis={{
            expandable: "collapsible",
          }}
        >
          {
        `${record.firstName} ${record.lastName}`}
        </Typography.Paragraph>),
      key: "fullName",
    },
    {
      key: "type",
      title: "Type",
      dataIndex: "type",
      showSorterTooltip: true,
      sorter: true, // add API later
      render: (_text, record) => {
        return record.type === "ADMIN" ? "Admin" : "Staff";
      },
    },
  ];
 
  const handlePageChange = (page : number) =>{
    setParams((params) => {
      params.pageNumber = page;
      return params;
    });
    refetch();
  }
 
  const rowSelection = {
    onChange: (_selectedRowKeys: React.Key[], selectedRows: User[]) => {
      setSelectedUser(selectedRows[0]);
      setIsButtonDisabled(false);
    },
    getCheckboxProps: (record: User) => ({
      name: record.firstName,
    }),
  };
 
  const handleCancel = () => {
    setIsButtonDisabled(true);
    setIsOpenModal(false);
    setParams((params) => {
      params.searchString = "";
      params.pageNumber = 1;
      return params;
    });
  };
 
  
 
  const handleSave = () => {
    handleCancel();
    setUserSelected(selectedUser as User);
  };
 
  return (
    <>
      <Modal
        title={
          <div>
            <p className="text-lg font-semibold primary-color">Select User</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 ModalSelectUser;