Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
6.5 kB
2
Indexable
Never
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import PARAMS from "../Global/Url";
import { useMemo } from "react";
import Pagination from "./Pagination";
import Footer from "./footer";

export default function Bo() {
  const navigate = useNavigate();
  const [pricing, setPricing] = useState({
    confermation: 0,
    reservation: 0,
    sold: 0,
    followUp: 0,
    aftersail: 0,
    leadCost: 0,
  });
  const [active, setActive] = useState(false);
  const [active2, setActive2] = useState(false);
  const [bosData, setBosData] = useState([]);
  const token = localStorage.getItem("jwt-admin");
  const [searchEmail, setSearchEmail] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 6;
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [selectedBoId, setSelectedBoId] = useState(null);
  const [amountToAdd, setAmountToAdd] = useState(0);

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  useEffect(() => {
    axios
      .get(`${PARAMS.API_URL}/admin/bo/list`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
        withCredentials: true,
      })
      .then((res) => {
        const normalizedBosData = res.data.bos.map((bo) => ({
          ...bo,
          status: bo.status.toLowerCase(),
        }));

        setBosData(normalizedBosData);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [token]);

  const handleChangeAccountStatus = async (id, status) => {
    try {
      const response = await axios.post(
        `${PARAMS.API_URL}/admin/status`,
        {
          id: id,
          status: status,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      const updatedBosData = bosData.map((bo) =>
        bo.id === id ? { ...bo, status: status } : bo
      );

      setBosData(updatedBosData);
    } catch (error) {
      console.error("Error updating status:", error);
    }
  };
  const handleStatusChange = async (id, newStatus) => {
    try {
      await handleChangeAccountStatus(id, newStatus);

      const normalizedStatus = newStatus.toLowerCase();

      const updatedBosData = bosData.map((bo) =>
        bo.id === id ? { ...bo, status: normalizedStatus } : bo
      );

      setBosData(updatedBosData);
    } catch (error) {
      console.error("Error updating status:", error);
    }
  };

  const handleUpdatePriceTag = async (e) => {
    e.preventDefault();

    const updateData = {
      id: selectedBoId,
      confermation: isNaN(Number(pricing.confermation))
        ? 0
        : Number(pricing.confermation),
      reservation: isNaN(Number(pricing.reservation))
        ? 0
        : Number(pricing.reservation),
      sold: isNaN(Number(pricing.sold)) ? 0 : Number(pricing.sold),
      followUp: isNaN(Number(pricing.followUp)) ? 0 : Number(pricing.followUp),
      aftersail: isNaN(Number(pricing.aftersail))
        ? 0
        : Number(pricing.aftersail),
      leadCost: isNaN(Number(pricing.leadCost)) ? 0 : Number(pricing.leadCost),
    };

    try {
      // UPDATE
      const response = await axios.post(
        `${PARAMS.API_URL}/admin/payment/edit`,
        updateData,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      setPricing(response.data);

      setActive(false);
    } catch (error) {
      console.error("Error updating pricing data:", error);
    }
  };

  const handlePriceTagClick = (boId) => {
    setSelectedBoId(boId);
    setActive(true);

    axios
      .get(`${PARAMS.API_URL}/admin/payment/${boId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        setPricing(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const handleLeadInfo = (boId) => {
    setSelectedBoId(boId);
    axios
      .get(`${PARAMS.API_URL}/admin/payment/${boId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        setPricing(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
    navigate(`/leads/${boId}`);
  };

  const filteredBos = useMemo(() => {
    return bosData.filter((bo) =>
      bo.email.toLowerCase().includes(searchEmail.toLowerCase())
    );
  }, [bosData, searchEmail]);

  const handleSearchInputChange = (e) => {
    const inputValue = e.target.value;
    setSearchEmail(inputValue);
  };

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentBos = filteredBos.slice(indexOfFirstItem, indexOfLastItem);

  const handleNextPage = () => {
    const totalPages = Math.ceil(filteredBos.length / itemsPerPage);
    setCurrentPage((prevPage) => Math.min(prevPage + 1, totalPages));
  };
  const handleAddBalance = async () => {
    try {
      const response = await axios.post(
        `${PARAMS.API_URL}/admin/balance`,
        {
          id: selectedBoId,
          amount: amountToAdd,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      const updatedBosData = bosData.map((bo) =>
        bo.id === selectedBoId
          ? { ...bo, balance: bo.balance + amountToAdd }
          : bo
      );

      setBosData(updatedBosData);
      setAmountToAdd(0);
      setActive2(false);
    } catch (error) {
      console.error("Error adding balance:", error);
    }
  };
  const handleCloseModal = () => {
    setActive(false);
    setActive2(false);
  };
  const handleGenerateTokenClick = async (boId) => {
    window.open("http://user.heylead.io/authentification/admin", "_blank");
  };


here's the pagination in JSX 

  <div className="nav">
        <Pagination
          itemsPerPage={itemsPerPage}
          totalItems={filteredBos.length}
          currentPage={currentPage}
          handlePageChange={handlePageChange}
        />
        <span className="next" onClick={handleNextPage}>
          {">"}
        </span>
      </div>
Leave a Comment