Source

pages/Dashboard/ShareContract/ShareContract.jsx

import axios from "axios";
import React, { useMemo, useRef } from "react";
import baseUrl from "../../../array/base/config";
import "../Sharehistory/sharehistory.css";
import { useState } from "react";
import { NavLink } from "react-router-dom";
import { Modal, Spin } from "antd";
import { toast } from "react-toastify";
import { useGetShareContracts } from "../../../apis/ShareContract";
import LoadingAnimation from "../Loading/LoadingAnimation";
import { usePaymentWithKhalti } from "../../../apis/Payment";
import EmptyData from "../../../component/EmptyData/EmptyData";

/**
 * @description This is the ShareContract functional page  component that will display the share contract of the user
 * @module ShareContract
 * @return {JSX.Element}
 */
const ShareContract = () => {
  /** @description This is the state variable that will store the file that will be uploaded
   *
   * @type {Array}
   * @memberof module:ShareContract
   * @name file
   * @default null
   * */
  const [file, setFile] = useState(null);
  /** @description This is the state variable that will store the id of the contract that will be submitted
   *
   * @type {Unknown}
   * @memberof module:ShareContract
   * @name submitId
   * @default null
   */
  const [submitId, setSubmitId] = useState(null);
  /** @description This is the state variable that will store the state of the filter dropdown
   * @type {Boolean}
   * @memberof module:ShareContract
   * @name filterDropdown
   * @default false
   */
  const [filterDropdown, setFilterDropdown] = useState(false);
  /** @description This is the state variable that will store the state of the modal
   * @type {Boolean}
   * @memberof module:ShareContract
   * @name open
   * @default false
   */
  const [open, setOpen] = useState(false);
  /** @description This is the state variable that will store the state of the product
   * @type {Object}
   * @memberof module:ShareContract
   * @name product
   * @default {}
   */
  const [product, setProduct] = useState({});
  /** @description This is the state variable that will store the state of the contract to pay
   * @type {Object}
   * @memberof module:ShareContract
   * @name contractToPay
   * @default {}
   *
   */
  const [contractToPay, setContractToPay] = useState({});
  /** @description This is the state variable that will store the state of the search input
   * @type {String}
   * @memberof module:ShareContract
   * @name searchInput
   * @default ""
   */
  const [searchInput, setSearchInput] = useState("");
  /** @description This is the state variable that will store the state of the sort by
   * @type {String}
   * @memberof module:ShareContract
   * @name sortBy
   * @default ""
   *
   */
  const [sortBy, setSortBy] = useState("");
  /** React query hook to get the share contracts
   * @memberof module:ShareContract
   * @name useGetShareContracts
   *
   */
  const { data: shareContacts, isLoading: contractLoading } =
    useGetShareContracts();
  /** React query hook to create  payment with khalti
   * @memberof module:ShareContract
   * @name usePaymentWithKhalti
   *
   */
  const { mutate: paymentMutate, isLoading: paymentLoading } =
    usePaymentWithKhalti();
  /** This is the useMemo hook that will filter the share contracts according to the search input and sort by
   * @memberof module:ShareContract
   * @name getShareContracts
   * @type {Array}
   */
  const getShareContracts = useMemo(() => {
    const temp = shareContacts?.data?.data?.results || [];
    if (searchInput) {
      const filteredList = temp.filter((contract) =>
        contract.name.toLowerCase().includes(searchInput.toLowerCase())
      );
      return filteredList.reverse();
    }
    switch (sortBy) {
      case "AZ":
        return [...temp].sort((a, b) => a.name.localeCompare(b.name));
      case "ZA":
        return [...temp].sort((a, b) => a.name.localeCompare(b.name)).reverse();
      case "OLD":
        return [...temp].reverse();
      case "RECENT":
        return temp;
    }
    return temp;
  }, [shareContacts?.data, searchInput, sortBy]);

  /** This is the function that will handle the file change
   * @memberof module:ShareContract
   * @name handleFileChange
   * @function handleFileChange
   * @param e {Event} This is the event that will be passed when the file is changed
   * @param id {Number} This is the id of the contract that will be submitted
   */
  function handleFileChange(e, id) {
    const selectedFile = e.target.files[0];
    console.log(e);
    alert(id);
    if (selectedFile.type === "application/pdf") {
      setFile(selectedFile);
      setSubmitId(id);
    } else {
      alert("Please select a PDF file");
    }
  }

  /** This is the function that will upload the karanama
   * @memberof module:ShareContract
   * @name uploadKaranama
   * @function uploadKaranama
   * @param id {Number} This is the id of the contract that will be submitted
   * @return {Promise<void>}
   */
  const uploadKaranama = async (id) => {
    // alert(`${baseUrl}/api/sharecontract/${id}`);
    try {
      const detail = localStorage.getItem("token");
      const response = await axios({
        method: "patch",
        url: `${baseUrl}/api/sharecontract/${id}/`,
        headers: {
          Authorization: `Token ${detail}`,
          "Content-Type": "multipart/form-data",
        },
        data: {
          signature_karanama_file: file,
        },
      });
      toast.success("File upload successful!", {
        position: "top-right",
        autoClose: 5001,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "light",
      });
      apicall();
    } catch (err) {
      console.log("the error is ", err);
    }
  };

  /** This is the function that will call the api
   * @memberof module:ShareContract
   * @name apicall
   * @function apicall
   * @async
   * @return {Promise<void>}
   */
  const payWithKhalti = async () => {
    let temp = {
      share: product?.name,
      sharecontract: product?.id,
      amount: parseFloat(product?.payment_amount) * 100,
    };
    paymentMutate(temp, {
      onSuccess: (res) => {
        window.open(res?.data?.data?.result?.payment_url, "_blank");
        setOpen(false);
      },
    });
  };

  /** This is the function for opening the modal for payment options
   * @memberof module:ShareContract
   * @name payNow
   * @function payNow
   * @param dat {Object} This is the object that will be passed when the pay now button is clicked
   */
  const payNow = (dat) => {
    setOpen(true);
    setContractToPay(dat);
    setProduct(dat);
  };
  if (contractLoading) {
    return <LoadingAnimation />;
  }
  return (
    <div className="sharehistory_container">
      <h2 className="main-title">
        Share <span>contract</span>
      </h2>

      <div className="sharehistory_heading flex justify-end">
        <div className="sharehistory_search flr-item">
          <div className="left_sharehistory_search">
            {/* <div className="left_sharehistory_search">
              <ion-icon name="search"></ion-icon>
            </div> */}
            <div className="search_input">
              {/* <ion-icon name="search-outline"></ion-icon> */}
              <input
                onChange={(e) => setSearchInput(e.target.value)}
                type="text"
                placeholder="Search"
              />
            </div>
            <div className="left_sharehistory_search">
              <ion-icon name="search"></ion-icon>
            </div>
          </div>
          <div className="right_sharehistory_search">
            <div
              className="sharehistory_filter_div"
              onClick={() => {
                setFilterDropdown(!filterDropdown);
              }}
            >
              <p>Sort by</p>
              {filterDropdown ? (
                <ion-icon name="chevron-up-outline"></ion-icon>
              ) : (
                <ion-icon name="chevron-down-outline"></ion-icon>
              )}
              {filterDropdown && (
                <div className="sharehistory_filter_dropdown">
                  <p onClick={() => setSortBy("AZ")}>A - Z</p>
                  <p onClick={() => setSortBy("ZA")}>Z - A</p>
                  <p onClick={() => setSortBy("RECENT")}>Recent</p>
                  <p onClick={() => setSortBy("OLD")}>Oldest</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      <div className="navigation_for_mobile">
        <div className="left_mobile_navigation">
          <input
            type="text"
            placeholder="search"
            onChange={(e) => setSearchInput(e.target.value)}
          />
          <ion-icon name="search-outline"></ion-icon>
        </div>
        <div className="right_mobile_navigation">
          <ul>
            <li>
              <ion-icon name="options"></ion-icon>
            </li>
          </ul>
        </div>
      </div>
      <>
        <Modal
          title="Payment Options"
          centered
          open={open}
          onOk={() => setOpen(false)}
          okButtonProps={{
            style: {
              display: "none",
            },
          }}
          cancelButtonProps={{
            style: {
              display: "none",
            },
          }}
          onCancel={() => setOpen(false)}
          width={500}
        >
          <h4
            style={{ cursor: "pointer" }}
            className="paymentModal"
            onClick={() => payWithKhalti()}
          >
            {paymentLoading ? <Spin size="small" /> : ""}
            Khalti
          </h4>
          {/* <NavLink to={{pathname: `/dashboard/uploadPaymentProof/${contractToPay.id}`}}> */}
          {/* <NavLink to={`/dashboard/uploadPaymentProof/?scidx=${contractToPay?.id}&company=${contractToPay?.share_data?.company_name}`}> */}
          <NavLink
            to={`/dashboard/uploadPaymentProof/?scidx=${encodeURIComponent(
              contractToPay?.id
            )}&company=${encodeURIComponent(
              contractToPay?.share_data?.company_name
            )}`}
          >
            <h4 className="paymentModal">Bank Deposit</h4>
          </NavLink>
        </Modal>
      </>
      <div className="share_history_body">
        <div className="share_contract_for_desktop">
          <table>
            <thead>
              <tr>
                <th>Shareholder</th>
                <th>Company Name</th>
                <th>Status</th>
                <th>Payment Date</th>
                <th>Kitta</th>
                <th>Total Amount</th>
                {getShareContracts?.share_registration_status ===
                "COMPLETED" ? null : (
                  <th>View Karanama</th>
                )}
                {getShareContracts?.signature_karanama_file ? (
                  getShareContracts?.share_registration_status ===
                    "COMPLETED" &&
                  getShareContracts?.payment_status === "PAID" ? (
                    <th>Upload File</th>
                  ) : (
                    <th>Show File</th>
                  )
                ) : (
                  <th>Show File</th>
                )}
                <th>Invoice</th>
                <th>Pay Status</th>
                <th>Pay Now</th>
              </tr>
            </thead>
            <tbody>
              {!getShareContracts.length ? (
                <EmptyData />
              ) : (
                getShareContracts.map((dat, i) => {
                  return (
                    <tr key={i}>
                      <td>{dat?.name}</td>
                      <td>{dat?.share_data?.company_name}</td>
                      <td>
                        {dat?.share_registration_status === "COMPLETED" ? (
                          <p className="completed">Completed</p>
                        ) : dat?.share_registration_status === "IN_PROGRESS" ? (
                          <p className="Pending">Pending</p>
                        ) : (
                          <></>
                        )}
                      </td>
                      <td>{dat?.payment_date_english}</td>
                      <td>{dat?.committed_kitta}</td>
                      <td>{dat?.payment_amount}</td>
                      <td>
                        {dat?.share_registration_status ===
                        "COMPLETED" ? null : (
                          <NavLink to={`/dashboard/karanama/${dat?.id}`}>
                            <div className="bonus_icon">
                              <ion-icon name="eye"></ion-icon>
                            </div>
                          </NavLink>
                        )}
                      </td>
                      <td>
                        {dat?.signature_karanama_file ? (
                          <div>
                            <NavLink
                              // to={`/dashboard/karanama_file/${dat?.signature_karanama_file}`}
                              // propValue={dat?.signature_karanama_file}
                              to={{
                                pathname: `/dashboard/karanama_file/${dat.id}`,
                                state: {
                                  prop: `${dat.signature_karanama_file}`,
                                },
                              }}
                            >
                              {/* {console.log(dat?.signature_karanama_file)} */}
                              <img
                                src="/pdf_logo.jpg"
                                alt="PDF icon"
                                style={{
                                  height: "50px",
                                  width: "50px",
                                  objectFit: "cover",
                                }}
                              />
                            </NavLink>
                          </div>
                        ) : dat?.share_registration_status == "COMPLETED" &&
                          dat?.payment_status == "PAID" ? (
                          "null"
                        ) : (
                          <>
                            <label htmlFor={`pdfInput-${dat.id}`}>
                              <ion-icon name="cloud-upload-outline"></ion-icon>
                            </label>
                            <input
                              type="file"
                              id={`pdfInput-${dat.id}`}
                              accept="application/pdf"
                              onChange={(e) => {
                                handleFileChange(e, dat.id);
                              }}
                              hidden
                            />
                            <>
                              {submitId == dat.id ? (
                                <button
                                  onClick={() => {
                                    uploadKaranama(dat?.id);
                                  }}
                                >
                                  Submit
                                </button>
                              ) : null}
                            </>
                          </>
                        )}
                      </td>
                      <td>
                        <NavLink to={`../share_invoice/${dat?.id}`}>
                          <ion-icon name="clipboard-outline"></ion-icon>
                        </NavLink>
                      </td>
                      <td>
                        {dat?.payment_status === "PAID" ? (
                          <p className="Paid">Completed</p>
                        ) : dat?.payment_status === "UNPAID" ? (
                          <p className="UnPaid">UnPaid</p>
                        ) : (
                          <></>
                        )}
                      </td>
                      <td>
                        {dat.payment_status == "UNPAID" ? (
                          <button
                            className="paynow_btn"
                            onClick={() => payNow(dat)}
                          >
                            Pay Now
                          </button>
                        ) : null}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
        <div className="share_fontract_for_mobile">
          {!getShareContracts.length ? (
            <EmptyData />
          ) : (
            getShareContracts.map((dat, i) => {
              return (
                <div className="share_fontract_for_mobile_left_col" key={i}>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Share Name</p>
                    <p>{dat?.name}</p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Company Name</p>
                    <p>{dat?.share_data?.company_name}</p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Status</p>
                    <div>
                      {dat?.share_registration_status === "COMPLETED" ? (
                        <p className="mobile_completed">Completed</p>
                      ) : dat?.share_registration_status === "IN_PROGRESS" ? (
                        <p className="mobile_Pending">Pending</p>
                      ) : (
                        <></>
                      )}
                    </div>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Payment Date</p>
                    <p>{dat?.payment_date_english}</p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Kitta</p>
                    <p>{dat?.committed_kitta}</p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Total Amount</p>
                    <p>{dat?.payment_amount}</p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>View Karanama</p>
                    <p>
                      {dat?.share_registration_status === "COMPLETED" ? null : (
                        <NavLink to={`/dashboard/karanama/${dat?.id}`}>
                          <td className="bonus_icon">
                            <ion-icon name="eye"></ion-icon>
                          </td>
                        </NavLink>
                      )}
                    </p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Show File</p>
                    <p>
                      {dat?.signature_karanama_file ? (
                        <img
                          style={{
                            height: "30px",
                            width: "30px",
                            objectFit: "cover",
                          }}
                          src={dat?.signature_karanama_file}
                        />
                      ) : dat?.share_registration_status == "COMPLETED" &&
                        dat?.payment_status == "PAID" ? (
                        "null"
                      ) : (
                        <>
                          <label htmlFor="pdfInput" className="upload_file">
                            Upload File
                          </label>
                          <input
                            type="file"
                            id="pdfInput"
                            accept="application/pdf"
                            onChange={(e) => {
                              handleFileChange(e, dat.id);
                            }}
                            hidden
                          />
                          <>
                            {submitId == dat.id ? (
                              <button
                                onClick={() => {
                                  uploadKaranama(dat?.id);
                                }}
                              >
                                Submit
                              </button>
                            ) : null}
                          </>
                        </>
                      )}
                    </p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Invoice</p>
                    <p>
                      <NavLink to={`../share_invoice/${dat?.id}`}>
                        <ion-icon name="clipboard-outline"></ion-icon>
                      </NavLink>
                    </p>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Pay Status</p>
                    <div>
                      {dat?.payment_status === "PAID" ? (
                        <p className="mobile_Paid">Completed</p>
                      ) : dat?.payment_status === "UNPAID" ? (
                        <p className="mobile_UnPaid">UnPaid</p>
                      ) : (
                        <></>
                      )}
                    </div>
                  </div>
                  <div className="share_fontract_for_mobile_left_col_col">
                    <p>Pay Now</p>
                    <p>
                      {dat.payment_status == "UNPAID" ? (
                        <button
                          // className="mobile_paynow_btn"
                          className="paynow_btn"
                          onClick={() => payNow(dat)}
                        >
                          Pay Now
                        </button>
                      ) : null}
                    </p>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
};
export default ShareContract;