Source

pages/Dashboard/ShareContract/PaymentProofForm.jsx

import axios from "axios";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";
import baseUrl from "../../../array/base/config";
import { useLocation } from "react-router-dom";

/**
 * Represents  PaymentProofForm component
 * @module PaymentProofForm
 * @param props
 * @return {JSX.Element}
 */
const PaymentProofForm = (props) => {
  /**
   * React useState for bank name
   * @name bankName
   * @memberof module:PaymentProofForm
   * @type {String}
   * @default ""
   */
  const [bankName, setBankName] = useState("");
  /**
   * React useState for document file
   * @name document_file
   * @memberof module:PaymentProofForm
   * @type {String}
   * @default null
   */
  const [document_file, setDocument_file] = useState(null);
  /**
   * React useState for bank list
   * @name bankList
   * @memberof module:PaymentProofForm
   * @type {Array}
   * @default []
   */
  const [bankList, setBankList] = useState([]);
  /**
   * React useLocation for location
   * @name location
   * @memberof module:PaymentProofForm
   * @type {Location}
   */
  let location = useLocation();
  /**
   * React URLSearchParams for searchParams
   * @name searchParams
   * @memberof module:PaymentProofForm
   * @type {URLSearchParams}
   * @default new URLSearchParams(location.search)
   * @type {module:url.URLSearchParams}
   */
  const searchParams = new URLSearchParams(location.search);

  // Access the individual query parameters
  /**
   * React URLSearchParams for scidx
   * @name scidx
   * @memberof module:PaymentProofForm
   * @type {string}
   */
  const scidx = searchParams.get("scidx");
  /**
   * React URLSearchParams for company
   * @name company
   * @memberof module:PaymentProofForm
   * @type {string}
   */
  const company = searchParams.get("company");

  // Decode the values
  /**
   * React URLSearchParams for decodedCompany
   * @name decodedCompany
   * @memberof module:PaymentProofForm
   * @type {string}
   */
  const decodedCompany = decodeURIComponent(company);
  /**
   * React URLSearchParams for decodedId
   * @name decodedId
   * @memberof module:PaymentProofForm
   * @type {string}
   */
  const decodedId = decodeURIComponent(scidx);


  useEffect(() => {
    getBank();
  }, []);
  /**
   * Function for filter bank
   * @name filterBank
   * @memberof module:PaymentProofForm
   * @function filterBank
   * @param banks {Array} - Array of banks
   * @return {void}
   */
  const filterBank = (banks) => {
    console.log("the banks", banks);
    const filteredBanks = banks.filter(
      (dat) => dat.company.name == decodedCompany
    );
    // console.log('the filtered banks', filteredBanks)
    setBankList(filteredBanks);
  };
  /**
   * Function for get bank
   * @name getBank
   * @memberof module:PaymentProofForm
   * @function getBank
   * @return {void}
   * @type {axios.AxiosRequestConfig}
   */
  const getBank = () => {
    const token = localStorage.getItem("token");
    axios({
      method: "get",
      url: `${baseUrl}/api/companybank/`,
      headers: {
        Authorization: `Token ${token}`,
      },
    })
      .then((res) => {
        // setBankList(res);
        filterBank(res.data.data.results);
      })
      .catch((err) => console.log(err));
  };

  /**
   * Function for handle file change
   * @name handleFileChange
   * @memberof module:PaymentProofForm
   * @function handleFileChange
   * @param e {Event} - Html event object
   */
  const handleFileChange = (e) => {
    const document = e.target.files[0];
    setDocument_file(document);
  };

  /**
   * Function for handle submit
   * @name handleSubmit
   * @memberof module:PaymentProofForm
   * @function handleSubmit
   * @param e {Event} - Html event object
   */
  const handleSubmit = (e) => {
    e.preventDefault();

    const formData = new FormData();
    bankName && formData.append("bank", bankName);
    document_file && formData.append("bank_deposit_slip_file", document_file);
    console.log(bankName, document_file);
    const detail = localStorage.getItem("token");
    axios
      .patch(`${baseUrl}/api/sharecontract/${decodedId}/`, formData, {
        headers: {
          Authorization: `Token ${detail}`,
          "Content-Type": "multipart/form-data",
        },
      })
      .then((response) => {
        console.log(response);
        toast.success("Payment Verification Document uploaded successfully!", {
          position: "top-right",
          autoClose: 5001,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "light",
        });
      })
      .catch((error) => {
        console.log(error);
        toast.error(
          "Payment verification document could not be added. Please try again.",
          {
            position: "top-right",
            autoClose: 5001,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "light",
          }
        );
      });
  };
  return (
    <>
      <h1>Payment Verification</h1>

      <div className="sharetransfer_card">
        <form onSubmit={handleSubmit}>
          <label htmlFor="bankName">Bank Name:</label>
          {/* <div className="sharetransfer_form_group">
            <input type="text" id="bankName" onChange={handleBankNameChange} />
          </div> */}
          <div className="sharetransfer_form_group">
            <select id="bankName" onChange={(e) => setBankName(e.target.value)}>
              <option value="">Choose the name of the bank</option>
              {bankList &&
                bankList.map((dat, i) => {
                  return (
                    <option key={i} value={dat.bank.name}>
                      {dat.bank.name}
                    </option>
                  );
                })}
            </select>
          </div>

          <label style={{ marginRight: "10px" }} htmlFor="file">
            Voucher File:
          </label>
          {document_file && (
            <input type="file" id="file" onChange={handleFileChange} />
          )}
          <div className="sharetransfer_form_group_img">
            {document_file ? (
              document_file?.name?.split(".").pop() === "pdf" ? (
                <img src="/pdf_logo.jpg" alt="PDF icon" />
              ) : (
                <img
                  src={URL.createObjectURL(document_file)}
                  alt="Selected file"
                />
              )
            ) : (
              <input type="file" id="file" onChange={handleFileChange} />
            )}
          </div>

          <div className="sharetransfer_form_group">
            <button type="submit">Add</button>
          </div>
        </form>
      </div>
    </>
  );
};
export default PaymentProofForm;