Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
6.0 kB
2
Indexable
Never
/* eslint-disable @next/next/no-img-element */
"use client";

import CardContent from "@/app/admin/dashboard/orderDashboard/components/CardContent";
import MainLayout from "@/app/components/Layouts/MainLayout";
import OrderStatusColor from "@/app/components/OrderStatusColor";
import { useAuth } from "@/app/hooks/Authcontext";
import { formatDateTime } from "@/app/utils/timeFormater";
import { MantineReactTable, useMantineReactTable } from "mantine-react-table";
import { useEffect, useState } from "react";
import DeliveryOrderDetails from "./neworder/DeliveryOrderDetails";

const Page = () => {
  const { user, token } = useAuth();
  const [allOrders, setAllOrders] = useState([]);
  const [deliveryBoys, setDeliveryBoys] = useState([]);
  const [orderId, setOrderId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [deliveryPartner, setDeliveryPartner] = useState({
    newOrder: 0,
    pastorder: 0,
  });
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/byDeliverPartner/${user._id}`
        );

        if (response.ok) {
          const data = await response.json();
          setAllOrders(data);
          setLoading(false);
          const newOrders = data.filter(
            (order) => order.status === "assignedDeliveryPartner"
          );

          const pastorder = data.filter(
            (order) => order.status !== "assignedDeliveryPartner"
          );
          const updatedDashboardData = {
            newOrder: newOrders.length,
            pastorder: pastorder.length,
          };
          localStorage.setItem("deliveryPartner", JSON.stringify(updatedDashboardData));
        } else {
          console.error("Failed to fetch data"); // Handle the error appropriately
          setLoading(false);
        }
      } catch (error) {
        console.error("Error:", error); // Handle any network or fetch errors
        setLoading(false);
      }
    };
    fetchData();
    const storedDashboardData = localStorage.getItem("deliveryPartner");
    if (storedDashboardData) {
      setDeliveryPartner(JSON.parse(storedDashboardData));
    }
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (user && user._id) {
          // Check if user and user._id are defined
          const response = await fetch(
            `${process.env.NEXT_PUBLIC_BACKEND_URL}/users/deliveryboy/${user._id}`,
            {
              headers: {
                Authorization: `${token}`,
              },
            }
          );

          if (response.ok) {
            const data = await response.json();
            setDeliveryBoys(data);
          } else {
            console.error("Failed to fetch data");
          }
        }
      } catch (error) {
        console.error("Error:", error);
      }
    };

    if (user && user._id) {
      fetchData(); // Only make the request if user and user._id are defined
    }
  }, [token, user]);

  const updateOrder = (orderId, newStatus) => {
    setAllOrders((prevOrders) => {
      return prevOrders.map((order) => {
        if (order._id === orderId) {
          // Ensure totalStatus is an array, if not, initialize it as an empty array
          const totalStatus = Array.isArray(order.totalStatus)
            ? order.totalStatus
            : [];

          return {
            ...order,
            totalStatus: [...totalStatus, { role: newStatus }],
            status: newStatus,
          };
        }
        return order;
      });
    });
  };

  // Define columns for the MantineReactTable
  const columns = [
    { accessorKey: "orderNumber", header: "Order Number" },
    {
      accessorKey: "createdAt",
      header: "Order Date",
      Cell: ({ row }) => formatDateTime(row.original.createdAt),
    },
    {
      accessorKey: "total",
      header: "Total Cost",
      Cell: ({ row }) => (
        <div>
          {row.original.total} {row.original.defaultCurrency}
        </div>
      ),
    },
    {
      accessorKey: "deliveryType.method",
      header: "Delivery Type",
      Cell: ({ row }) => (
        <div>
          {row.original.deliveryType
            ? row.original.deliveryType.method
            : "Digital"}
        </div>
      ),
    },
    {
      accessorKey: "status",
      header: "Status",
      Cell: ({ row }) => <OrderStatusColor status={row.original.status} />,
    },
    {
      accessorKey: "action",
      header: "Action",
      Cell: ({ row }) => (
        <div>
          <button
            className="btn btn-sm bg-[#46ADFA] text-xs text-white hover:bg-[#BBE1FF] hover:text-black"
            onClick={() =>
              document.getElementById(`${row.original._id}`).showModal()
            }
          >
            View Details
          </button>

          <DeliveryOrderDetails
            deliveryBoys={deliveryBoys}
            order={row.original}
            orderId={orderId}
            setOrderId={setOrderId}
            updateOrder={updateOrder}
            key={row.original._id}
          />
        </div>
      ),
    },
  ];

  const table = useMantineReactTable({
    columns,
    data: allOrders,
    state: { isLoading: loading },
  });

  return (
    <MainLayout>
      <div className="grid grid-cols-1 gap-6 md:grid-cols-3 mb-10">
        <CardContent
          name={"New Orders"}
          image={"https://cdn-icons-png.flaticon.com/512/9280/9280771.png"}
          amount={deliveryPartner.newOrder}
          link={"/deliveryboy/dashboard/orders"}
        />
        <CardContent
          name={"Past Order"}
          image={"/default/cargo.png"}
          amount={deliveryPartner.pastorder}
          link={"/deliveryboy/dashboard/pastorders"}
        />
      </div>
      <div className="mt-8 overflow-x-auto rounded-t-lg">
        <MantineReactTable table={table} />
      </div>
    </MainLayout>
  );
};

export default Page;
Leave a Comment