Source

pages/Dashboard/ApplyShare/ApplyShare.jsx

import React, { useEffect, useState } from "react";
import axios from "axios";
import baseUrl from "../../../array/base/config";
import { useNavigate, useParams } from "react-router-dom";
import "../ApplyShare/applyshare.css";
import LoadingAnimation from "../Loading/LoadingAnimation";
import { toast } from "react-toastify";

/**
 *
 * Represents a page for applying share
 * @module ApplyShare
 * @param user
 * @returns {JSX.Element}
 */
const ApplyShare = ({ user }) => {
    /**
     * React state for storing share details
     * @name share
     * @type {object}
     * @default {object}
     * @memberof module:ApplyShare
     */
  const [share, setShare] = useState({});
    /**
     * React state for storing commited kitta
     * @name commitedKitta
     * @type {number}
     * @default {0}
     * @memberof module:ApplyShare
     */
  const [commitedKitta, setCommitedKitta] = useState(0);
    /**
     * React state for storing total payment
     * @name totalpayment
     * @type {number}
     * @default {0}
     * @memberof module:ApplyShare
     */
  const [totalpayment, setTotalpayment] = useState(0);
    /**
     * React state for storing loading status
     * @name isLoading
     * @type {boolean}
     * @default {true}
     * @memberof module:ApplyShare
     */
  const [isLoading, setIsLoading] = useState(true);
    /**
     * React state for storing show total status
     * @name showtotal
     * @type {boolean}
     * @default {false}
     * @memberof module:ApplyShare
     */
  const [showtotal, setShowTotal] = useState(false);

    /**
     * React state for storing error message
     * @name errorMessage
     * @type {string}
     * @default {''}
     * @memberof module:ApplyShare
     */
  const [errorMessage, setErrorMessage] = useState('');
    /**
     * id for getting share details
     * @name id
     * @type {string}
     * @memberof module:ApplyShare
     */
  const { id } = useParams();
  const navigate = useNavigate();

  useEffect(() => {
    apicall();
  }, []);

  useEffect(() => {
    const totalprice = share.premium_charge + share.price;
    const tempTotal = commitedKitta * totalprice;
    setTotalpayment(tempTotal);
  }, [commitedKitta]);
    /**
     * Function for handling commited kitta
     * @name handleCommittedKitta
     * @function
     * @memberof module:ApplyShare
     * @param e {Event} Html event object
     */
  const handleCommittedKitta = (e) => {
    setShowTotal(true);
    setCommitedKitta(parseInt(e.target.value));
    if (e.target.value < Math.floor(share?.minimum_kitta)) {
      setErrorMessage(`Minimum kitta to apply share is ${Math.floor(share?.minimum_kitta)}`);
    } else {
      setErrorMessage('');
    }
  };
    /**
     * Function for calling api to get share details
     * @name apicall
     * @function
     * @memberof module:ApplyShare
     *
     */
  const apicall = () => {
    const detail = localStorage.getItem("token");
    axios({
      method: "get",
      url: `${baseUrl}/api/share/${id}/`,
      headers: {
        Authorization: `Token ${detail}`,
      },
    })
      .then((res) => {
        console.log(res?.data?.data)
        setShare(res?.data?.data);
        setIsLoading(false);
      })
      .catch((err) => console.log(err));
  };
    /**
     * Function for handling apply share  submit
     * @name handleSubmit
     * @function
     * @memberof module:ApplyShare
     * @param event
     */
  const handleSubmit = (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append(
      "name",
      `${user?.first_name} ${user?.last_name} ${share?.company_name}`
    );
    formData.append("share", parseInt(id));
    formData.append("committed_kitta", commitedKitta);
    formData.append("payment_amount", totalpayment);
    formData.append("committed_amount", totalpayment);

    const detail = localStorage.getItem("token");
    axios
      .post(`${baseUrl}/api/sharecontract/`, formData, {
        headers: {
          Authorization: `Token ${detail}`,
          "Content-Type": "multipart/form-data",
        },
      })
      .then((response) => {
        navigate("/dashboard/share_contract");
        toast.success(
          "Your share application has been submitted successfully!",
          {
            position: "top-right",
            autoClose: 5001,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "light",
          }
        );
        navigate("/dashboard/share_contract");
      })
      .catch((error) => {
        console.error(error);
        toast.error(
          "Application could not be submitted. Check your info and try again.",
          {
            position: "top-right",
            autoClose: 5001,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "light",
          }
        );
      });
  };

  if (isLoading) {
    return <LoadingAnimation />;
  }
  return (
    <div>
      <form className="my_form">
      </form>
      <div className="apply_share_container">
        <div className="apply_share_card">
          <form onSubmit={handleSubmit}>
            <div className="apply_share_form_group">
              <h3 htmlFor="name">Share Description:</h3>
              <p>{`${share?.description}`}</p>
            </div>
            <div className="apply_share_form_group">
              <label htmlFor="company">Company Name:</label>
              <input
                type="text"
                id="name"
                value={`${share?.company_name}`}
                readOnly
              />
            </div>
            <div className="apply_share_form_group">
              <label htmlFor="committed-kitta">Committed Kitta:</label>
              <input
                type="number"
                id="committed-kitta"
                name="committed-kitta"
                required
                onChange={handleCommittedKitta}
              />
              {errorMessage && <p style={{ color: 'red' }}>{errorMessage}</p>}
            </div>
            {showtotal && (
              <>
                <div className="apply_share_form_group">
                  <label htmlFor="committed-amount">Committed Amount:</label>
                  <input
                    type="number"
                    id="committed-amount"
                    value={totalpayment ? totalpayment : 0}
                    readOnly
                  />
                </div>
                <div className="apply_share_form_group">
                  <label htmlFor="payment-amount">Payment Amount:</label>
                  <input
                    type="number"
                    id="payment-amount"
                    value={totalpayment ? totalpayment : 0}
                    readOnly
                  />
                </div>
              </>
            )}
            <div className="apply_share_form_group">
              <button type="submit" className="apply_share_btn">
                Submit
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ApplyShare;