VendorListing.js 10.1 KB
import { CheckOutlined, DeleteTwoTone, EyeTwoTone, SearchOutlined, StopOutlined, StopTwoTone } from "@ant-design/icons";
import { Input, Space, Table, Tag } from "antd";
import { getSession } from "next-auth/react";
import { useRouter } from "next/router";
import { Fragment, useEffect, useRef, useState } from "react";
import { Button, Image } from "react-bootstrap";
import Highlighter from "react-highlight-words";
import { useDispatch, useSelector } from "react-redux";
import { loadUser } from "../../redux/actions/userActions";
import { getAllVendors } from "../../redux/actions/vendorActions";
import VendorDetailModal from "./VendorDetailModal";
import VendorDetails from "./VendorDetails";

const VendorListing = () => {
  // Hooks
  const searchInput = useRef(null);

  const dispatch = useDispatch();
  const router = useRouter();
  // useState
  const [session, setSession] = useState();
  const [loading, setLoading] = useState(true);
  const [showMenuIndex, setShowMenuIndex] = useState(null);
  const [restriction, setRestriction] = useState(false);
  const [data, setData] = useState([]);
  const [showDetail, setShowDetail] = useState(false);
  const [detail, setDetail] = useState();
  const [searchedColumn, setSearchedColumn] = useState("");
  const [searchText, setSearchText] = useState("");
  const handleReset = clearFilters => {
    clearFilters();
    setSearchText("");
  };
  // selectors
  const { loadedUser } = useSelector(state => state.loadedUser);
  const { allVendors, loading: vendorLoading, totalCount } = useSelector(state => state.allVendors);
  const toggleMenu = index => {
    setShowMenuIndex(index === showMenuIndex ? null : index);
  };
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    console.log("selectedKeys", selectedKeys);
    if (!loadedUser) return;
    dispatch(getAllVendors({ pageNumber: 1, pageSize: 10, str: selectedKeys[0] }));
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 8
        }}
        onKeyDown={e => e.stopPropagation()}
      >
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => {
            console.log("jere", e.target.value);
            if (e.target.value == "") {
              handleReset(clearFilters);
            }
            setSelectedKeys(e.target.value ? [e.target.value] : []);
          }}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: "block"
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90
            }}
          >
            Search
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90
            }}
          >
            Reset
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            Filter
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            close
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined
        style={{
          color: filtered ? "#1677ff" : undefined
        }}
      />
    ),
    onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownOpenChange: visible => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: text =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: "#ffc069",
            padding: 0
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      )
  });

  // Session
  // useEffect(() => {
  //   const fetchSession = async () => {
  //     setSession(await getSession());
  //   };
  //   fetchSession();
  //   // dispatch(getLoggedInVendor());
  // }, []);
  // useEffects

  useEffect(() => {
    dispatch(loadUser());
    // console.log(">>", loadedUser);
    // if (!loadedUser) {
    //   router.push("/admin/login")
    // }
    if (loadedUser && loadedUser.role.name != "admin") {
      setRestriction(true);
      setLoading(true);
    } else {
      setRestriction(false);

      setLoading(false);
    }
    // if (!loadedUser) {
    //   setRestriction(true);
    //   return
    // }
  }, []);
  // console.log("session", loadedUser);

  const [tableCurrentPage, settableCurrentPage] = useState(1);
  const [tableItemsPerPage, settableItemsPerPage] = useState(10);

  const onChange = (pagination, filters, sorter, extra) => {
    console.log("params", pagination, filters, sorter, extra);
    settableCurrentPage(pagination.current);
    settableItemsPerPage(pagination.pageSize);
    dispatch(getAllVendors({ pageNumber: pagination.current, pageSize: pagination.pageSize, str: searchText }));
  };

  console.log("allVendors", allVendors);
  const [vendorId, setVendorId] = useState(null);
  const [showVendorDetails, setShowVendorDetails] = useState(false);
  const handleShowVendorDetails = () => {
    setShowVendorDetails(true);
  };
  const handleCloseVendorDetails = () => {
    setShowVendorDetails(false);
  };

  // useEffect

  useEffect(() => {
    // setLoading(true);
    let initialData =
      allVendors &&
      allVendors.map(item => {
        // console.log("item", item.attributes.user.data);
        return {
          key: item.id,
          name: item.attributes.name,
          businessName: item.attributes.businessName,
          status: [item.attributes.user.data?.attributes.approved],
          confirmed: item.attributes.user.data?.attributes.confirmed,
          email: item.attributes.email,
          phone: item.attributes.phone
        };
      });
    console.log("initialData", initialData);
    setData(initialData);
    // setLoading(false);
  }, [allVendors]);

  const columns = [
    // {
    //   title: "Vendor ID",
    //   dataIndex: "vendorId",
    //   key: "vendorId",
    //   render: text => <a>{text}</a>,
    //   ...getColumnSearchProps("vendorId")
    // },
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      render: text => <a>{text}</a>,
      ...getColumnSearchProps("name")
    },
    {
      title: "Business Name",
      dataIndex: "businessName",
      key: "businessName"
    },
    {
      title: "Phone",
      dataIndex: "phone",
      key: "phone"
    },
    {
      title: "Email",
      dataIndex: "email",
      key: "email"
    },
    // {
    //   title: "OTP verified",
    //   dataIndex: "confirmed",
    //   key: "confirmed",
    //   render: (_, { confirmed }) => (
    //     <>
    //       <>{confirmed ? <CheckOutlined /> : <StopOutlined />}</>
    //     </>
    //   )
    // },
    {
      title: "Approved",
      key: "status",
      dataIndex: "status",
      render: (_, { status }) => (
        <>
          {status.map(tag => {
            // console.log("tag", tag);
            let color;
            // if (tag === "loser") {
            //   color = "volcano";
            // }
            switch (tag) {
              case "approved":
                color = "green";
                break;
              case "pending":
                color = "orange";
                break;

              case "none":
                color = "red";
                break;

              case "rejected":
                color = "red";
                break;

              default:
                break;
            }
            // console.log("color", color);
            return (
              <Tag color={color} key={tag}>
                {tag?.toString().toUpperCase()}
              </Tag>
            );
          })}
        </>
      )
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          {/* <DeleteTwoTone style={{ fontSize: '22px' }}  twoToneColor="red"/> */}
          <EyeTwoTone
            style={{ fontSize: "22px" }}
            onClick={() => {
              setShowDetail(true);
              setDetail(allVendors.filter(item => item.id == record.key));
            }}
          />
          {/* <StopTwoTone style={{ fontSize: "20px" }} twoToneColor="red" /> */}
        </Space>
      )
    }
  ];

  return (
    <Fragment>
      <div className="p-5">
        <div className={restriction ? "overlay" : ""}>
          {restriction ? (
            <div className="d-flex justify-content-center align-items-center" style={{ color: "#FFF", fontSize: "50px", height: "100%" }}>
              Access restricted! Only admin is allowed to view the data.
            </div>
          ) : (
            <div>
              {!showDetail ? (
                <Table
                  loading={vendorLoading}
                  columns={columns}
                  dataSource={data}
                  onChange={onChange}
                  pagination={{
                    current: tableCurrentPage,
                    pageSize: tableItemsPerPage,
                    total: totalCount
                  }}
                />
              ) : (
                // <VendorDetailModal  />
                <VendorDetails setShowDetail={setShowDetail} showDetail={showDetail} detail={detail} />
              )}
              <div></div>
            </div>
          )}
        </div>
      </div>
    </Fragment>
  );
};

export default VendorListing;