Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
16 kB
1
Indexable
Never
/* eslint-disable @next/next/no-img-element */
"use client";
import MainLayout from "@/app/components/Layouts/MainLayout";
import { MantineReactTable, useMantineReactTable } from "mantine-react-table";
import moment from "moment/moment";
import { useEffect, useMemo, useState } from "react";
import OrderDetails from "../orderDashboard/components/OrderDetails";
import CardContent from "./components/CardContent";
import "./index.css";

export default function Page() {
  const [allOrders, setAllOrders] = useState([]);
  const [selectedPaymentMode, setSelectedPaymentMode] = useState("all"); // Default to "all" initially
  const [adminData, setAdminData] = useState({
    newOrder: 0,
    runningOrder: 0,
    cancleOrder: 0,
    completedOrder: 0,
    allOrder: 0,
    assignedModerator: 0,

  });
  const [filterOrderId, setFilterOrderId] = useState(""); // Add state for the filter
  const [loading, setLoading] = useState(true); // Add loading state

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_BACKEND_URL}/orders`
        );

        if (response.status === 200) {
          const data = await response.json();
          setAllOrders(data);
          setLoading(false); // Set loading to false regardless of success or failure

        } else {
          console.error("Failed to fetch data");
        }
      } catch (error) {
        console.error("Error:", error);
      }
    };
    fetchData();
  }, []);
  useEffect(() => {
    const fetchNewOrders = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_BACKEND_URL}/orders`
        );

        if (response.status === 200) {
          const data = await response.json();
          const createdOrders = data.filter(
            (order) => order.status === "created"
          );
          const cancleOrders = data.filter(
            (order) => order.status === "canceled"
          );
          const delivaredOrders = data.filter(
            (order) => order.status === "delivered"
          );
          const assignedModerator = data.filter(
            (order) => order.status === "assignedModerator"
          );
          setAdminData((prevData) => ({
            ...prevData,
            newOrder: createdOrders.length,
            cancleOrder: cancleOrders.length,
            completedOrder: delivaredOrders.length,
            allOrder: data.length,
            assignedModerator: assignedModerator.length,

            runningOrder:
              data.length -
              createdOrders.length -
              cancleOrders.length -
              delivaredOrders.length,
          }));
        } else {
          console.error("Failed to fetch new orders");
        }
      } catch (error) {
        console.error("Error fetching new orders:", error);
      } finally {
      }
    };
    fetchNewOrders();
  }, []);
  const updateOrder = (orderId, newStatus) => {
    setAllOrders((prevOrders) => {
      return prevOrders.map((order) => {
        if (order._id === orderId) {
          return {
            ...order,
            totalStatus: [...order.totalStatus, { role: newStatus }],
            status: newStatus
          };
        }
        return order;
      });
    });
  };
  // Function to handle the order ID filter input
  const handleFilterChange = (event) => {
    setFilterOrderId(event.target.value);
  };

  // Function to handle the Payment Mode selection
  const handlePaymentModeChange = (event) => {
    setSelectedPaymentMode(event.target.value);
  };

  // Function to filter orders based on the order ID and Payment Mode
  const filteredOrders = allOrders.filter((order) => {
    const orderIdMatch = order.orderNumber
      .toLowerCase()
      .includes(filterOrderId.toLowerCase());

    if (selectedPaymentMode === "all") {
      return orderIdMatch;
    } else {
      return (
        orderIdMatch &&
        order.paymentMethod.toLowerCase() === selectedPaymentMode
      );
    }
  });

  var seriesData = [{
    name: 'product',
    data: [44, 55, 57, 56, 61, 58, 63, 60, 66.5, 0, 5]
  }, {
    name: 'sel',
    data: [76, 85, 101, 98, 87, 105, 91, 114, 94, 90]
  }, {
    name: 'return',
    data: [35, 41, 36, 26, 45, 48, 52, 53, 41, 50]
  }];



  const columns = useMemo(
    () => [
      {
        accessorKey: "key",
        header: "Index",
        columnDefType: "display",
        enableColumnOrdering: false,
        Cell: ({ row }) => <div className="text-center">{row.index + 1}</div>,
        mantineTableHeadCellProps: {
          align: "center",
        },
        mantineTableBodyCellProps: {
          align: "center",
        },
        size: 90,
      },
      {
        accessorKey: "orderNumber",
        header: "Order Number",
      },
      {
        accessorKey: "total",
        header: "$ Total Cost",
        Cell: ({ row }) => (
          <div>
            {row.original.total} {row.original.defaultCurrency}
          </div>
        ),
      },
      {
        accessorKey: "createdAt",
        header: "Order Date",
        columnDefType: "display",
        enableColumnOrdering: false,
        Cell: ({ row }) => (
          <div>
            {moment(row.original.createdAt).format("YYYY-MM-DD HH:mm:ss")}
          </div>
        ),
      },
      {
        accessorKey: "status",
        header: "Order Status",
        columnDefType: "display",
        enableColumnOrdering: "false",
        Cell: ({ row }) => (
          <div>
            {row.original.status === "created" ? (
              <p className="font-semibold text-yellow-600 ">Order Placed</p>
            ) : (
              ""
            )}
          </div>
        ),
      },
      {
        accessorKey: "customerInfo.name",
        header: "Customer Name",
      },
      {
        accessorKey: "deliveryType",
        header: "Delivery Type",
        columnDefType: "display",
        enableColumnOrdering: "false",
        Cell: ({ row }) => (
          <div>
            {row.original.deliveryType
              ? row.original.deliveryType.method
              : "Digital"}
          </div>
        ),
      },
      {
        accessorKey: "action",
        header: "Action",
        columnDefType: "display",
        enableColumnOrdering: false,
        Cell: ({ row }) => (
          <div>
            <button
              onClick={() =>
                document.getElementById(`${row.original._id}`).showModal()
              }
              className="btn btn-sm bg-[#46ADFA] text-xs text-white hover:bg-[#BBE1FF] hover:text-black"
            >
              View
            </button>

            <OrderDetails
              key={row.original._id}
              orderId={row.original._id}
              order={row.original}
            // updateOrder={updateOrder}
            />
          </div>
        ),
      },
    ],
    []
  );

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

  return (
    <MainLayout>
      <div className="p-4">
        <h1 className="mb-4 text-2xl font-semibold">Order Dashboard</h1>
        <div className="rounded-md bg-white p-4">
          <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
            <CardContent name={'All Orders'} image={'/default/cargo.png'} amount={adminData.allOrder} link={'/'} />
            <CardContent name={'New Orders'} image={'https://cdn-icons-png.flaticon.com/512/9280/9280771.png'} amount={adminData.newOrder} link={'/admin/dashboard/newOrder'} />
            <CardContent name={'Assigned to Moderator'} image={'https://cdn-icons-png.flaticon.com/512/5026/5026068.png'} amount={adminData.assignedModerator} link={'/'} />
            <CardContent name={'Assigned to Studio Partner'} image={'/default/cargo.png'} amount={adminData.allOrder} link={'/'} />
            <CardContent name={'Delivered Orders'} image={'https://cdn-icons-png.flaticon.com/512/9527/9527250.png'} amount={adminData.completedOrder} link={'/'} />
          </div>
        </div>

        <div className="mt-8 overflow-x-auto rounded-t-lg">
          {loading == true ? <div className="mt-16 flex items-center justify-center">
            <div className="flex">
              <span className="loading loading-bars loading-xs"></span>
              <span className="loading loading-bars loading-sm"></span>
              <span className="loading loading-bars loading-md"></span>
              <span className="loading loading-bars loading-lg"></span>
            </div>
          </div> : <MantineReactTable table={table} />}

          {/* <table className="table table-zebra">
            <thead className="bg-[#0098FB] ">
              <tr className="text-white ">
                <th
                  className="text-base font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                  }}
                >
                  No.
                </th>
                <th
                  className="text-sm font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                    width: "15%",
                  }}
                >
                  <div className="flex ">
                    <input
                      type="text"
                      placeholder="Order Number"
                      className="input h-10 w-full bg-[#AFDCFE] pl-2 text-sm  text-black placeholder-black placeholder:bg-opacity-80 placeholder:font-semibold"
                      value={filterOrderId}
                      onChange={handleFilterChange}
                    />
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 24 24"
                      fill="currentColor"
                      className="h-5 w-5 bg-[#BBE1FF] text-black "
                      style={{
                        position: "absolute",
                        marginLeft: "11%",
                        marginTop: "10px",
                        opacity: ".5",
                      }}
                    >
                      <path
                        fillRule="evenodd"
                        d="M10.5 3.75a6.75 6.75 0 100 13.5 6.75 6.75 0 000-13.5zM2.25 10.5a8.25 8.25 0 1114.59 5.28l4.69 4.69a.75.75 0 11-1.06 1.06l-4.69-4.69A8.25 8.25 0 012.25 10.5z"
                        clipRule="evenodd"
                      />
                    </svg>
                  </div>
                </th>
                <th
                  className="text-base font-light tracking-wide"
                  style={{ opacity: "0.9" }}
                >
                  Order Date
                </th>
                <th
                  className="text-base font-light tracking-wide"
                  style={{ opacity: "0.9" }}
                >
                  Total Cost
                </th>
                <th
                  className="text-sm font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                    width: "15%",
                  }}
                >
                  <div>
                    <select
                      className="custom-select change-background select w-full rounded-lg pl-2 text-black"
                      style={{
                        height: "35px",
                        backgroundColor: "#BBE1FF !important",
                      }}
                      value={selectedPaymentMode}
                      onChange={handlePaymentModeChange}
                    >
                      <option value="all">All</option>
                      <option value="cod">COD</option>
                      <option value="online">ONLINE</option>
                    </select>
                  </div>
                </th>
                <th
                  className="text-base font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                    width: "15%",
                  }}
                >
                  <select
                    className="custom-select change-background  select  w-full rounded-lg  pl-2 text-black"
                    style={{
                      height: "35px",
                      backgroundColor: "#BBE1FF !important",
                    }}
                  >
                    <option disabled selected>
                      Delivey Type
                    </option>
                    <option>Homer</option>
                    <option>Marge</option>
                  </select>
                </th>
                <th
                  className="text-base font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                    width: "15%",
                  }}
                >
                  <select
                    className="custom-select change-background  select  w-full rounded-lg  pl-2 text-black"
                    style={{
                      height: "35px",
                      backgroundColor: "#BBE1FF !important",
                    }}
                  >
                    <option disabled selected>
                      Status
                    </option>
                    <option>Homer</option>
                    <option>Marge</option>
                    <option>Bart</option>
                    <option>Lisa</option>
                    <option>Maggie</option>
                  </select>
                </th>
                <th
                  className="text-base font-light tracking-wide"
                  style={{
                    opacity: "0.9",
                  }}
                >
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {filteredOrders.map((order, _index) => (
                <tr key={order._id}>
                  <td className="opacity-60">{_index + 1}</td>
                  <td
                    className="font-semibold"
                    style={{ letterSpacing: ".5px" }}
                  >
                    <span className="ml-2">{order.orderNumber}</span>
                  </td>
                  <td
                    className="font-semibold"
                    style={{ letterSpacing: ".5px" }}
                  >
                    {formatDateTime(order.createdAt)}
                  </td>
                  <td
                    className="font-semibold"
                    style={{ letterSpacing: ".5px" }}
                  >
                    ${order.deliveryType ? order.deliveryType.rate : ""}
                  </td>
                  <td
                    className="font-semibold"
                    style={{ letterSpacing: ".5px" }}
                  >
                    <span className="ml-2">{order.paymentMethod}</span>
                  </td>
                  <td
                    className="font-semibold"
                    style={{ letterSpacing: ".5px" }}
                  >
                    <span className="ml-2">{order.deliveryType ? order.deliveryType.method : "Digital"}</span>
                  </td>
                  <td className="text-base font-bold capitalize text-emerald-500">
                    <span className="ml-2">{order.status}</span>
                  </td>
                  <td>
                    <button
                      className="btn btn-sm bg-[#46ADFA] text-xs text-white hover:bg-[#BBE1FF] hover:text-black"
                      onClick={() =>
                        document.getElementById(`${order._id}`).showModal()
                      }
                    >
                      View
                    </button>

                    <OrderDetails
                      key={order._id}
                      orderId={order._id}
                      order={order}
                      updateOrder={updateOrder}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table> */}

          {/* <ProductGraph seriesData={seriesData} /> */}
        </div>
      </div>
    </MainLayout>
  );
}
Leave a Comment