Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
14 kB
2
Indexable
Never
"use client";

/* eslint-disable @next/next/no-img-element */
import DeliveryInfo from "@/app/admin/dashboard/components/DeliveryInfo";
import OrderInfo from "@/app/admin/dashboard/components/OrderInfo";
import DropdonwItemList from "@/app/components/Global/DropdonwItemList";
import NotsList from "@/app/components/Global/NotsList";
import { useAuth } from "@/app/hooks/Authcontext";
import axios from "axios";
import { saveAs } from "file-saver";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FaAddressCard, FaShoppingCart } from "react-icons/fa";
import { LuUserCheck } from "react-icons/lu";
import { MdSpeakerNotes } from "react-icons/md";
import OrderStatusList from "../../../components/OrderStatusList";
import ImageUplodeAndItemList from "./ImageUplodeAndItemList";
import NoteSubmit from "./NoteSubmit";

export default function OrderDetails({ orderId }) {
    const router = useRouter();
    const searchParams = useSearchParams()
    const redirect = searchParams.get('redirect')


    // console.log('searchParams url', redirect,);
    const [reassignedLoadingBtn, setreassignedLoadingBtn] = useState(false);
    const [digitaprocessbtn, setDigitalProcessBtn] = useState(false);
    const [selectedImages, setSelectedImages] = useState({});
    const [uploadbtnLoading, setUploadbtnLoading] = useState(false);

    const { user } = useAuth();

    const [order, setOrder] = useState();
    const [loading, setLoading] = useState(true); // Add loading state

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

                // if (response.status === 200) {
                const data = await response.json();

                // Filter orders with status "created"
                console.log("data=====", data);
                setOrder(data.data);
                // } else {
                //   console.error("Failed to fetch new orders");
                // }
            } catch (error) {
                console.error("Error fetching new orders:", error);
            } finally {
                setLoading(false); // Set loading to false regardless of success or failure
            }
        };
        fetchNewOrders();
    }, [orderId]);


    const updateOrder = useCallback(
        (orderId, newStatus) => {
            // setOrder((prevOrders) => {
            //   // Update the order with the matching orderId
            //   const updatedOrders = prevOrders.map((order) => {
            //     if (order._id === orderId) {
            //       // Check if 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;
            //   });

            //   // Filter out orders with status other than "created"
            //   const filteredOrders = updatedOrders.filter((order) => order.status === "created");

            //   console.log("Updated orders:", filteredOrders);
            //   return filteredOrders;
            // });
        },
        [setOrder]
    );



    const downloadImage = (url) => {
        var link = document.createElement("a");
        link.href = url;
        link.download = "image.jpg";
        link.target = "_blank";
        saveAs(url, Date.now() + ".jpg");
    };

    const memoizedFetchData = useCallback(async () => {
        try {
            const response = await fetch(
                `${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/byModerator/${user?._id}`
            );

            if (response.ok) {
                const data = await response.json();
                console.log("data", data);
                // const filteredData = data.filter(
                //     (order) => order.status === "assignedModerator"
                // );
                // setOrder(filteredData);
            } else {
                console.error("Failed to fetch data");
            }
        } catch (error) {
            console.error("Error:", error);
        } finally {
            setLoading(false); // Set loading to false regardless of success or failure
        }
    }, [user?._id]);

    const handleImageSelection = (orderId, imageId, file) => {
        setSelectedImages((prevSelectedImages) => ({
            ...prevSelectedImages,
            [`${orderId}-${imageId}`]: file,
        }));
    };
    async function handleImageChange(orderId, imageId, file) {
        try {
            if (!file) {
                alert("Please select an image to upload as a custom edit image.");
                return;
            }

            setUploadbtnLoading(true);

            const formData = new FormData();
            formData.append("orderId", orderId);
            formData.append("imageId", imageId);
            formData.append("editedImg", file);

            const response = await axios.post(
                `${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/addCustomEditImage`,
                formData,
                { headers: { "Content-Type": "multipart/form-data" } }
            );

            if (response.status === 200) {
                toast.success("Image has been uploaded");

                const response = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/details/${orderId}`);

                // if (response.status === 200) {
                const data = await response.json();

                // Filter orders with status "created"
                // console.log("face data=====", data);
                setOrder(data.data);
                // } else {
                //   console.error("Failed to fetch new orders");
                // }

                // toast.success("Image has been uploaded");
                setUploadbtnLoading(false);
                memoizedFetchData(); // Update the allOrders state using the updated data
            }
        } catch (error) {
            console.error("Error adding custom edit image:", error);
            setUploadbtnLoading(false);
        }
    }

    const reassignOrder = async (orderId) => {
        try {
            setreassignedLoadingBtn(true);
            const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/reassignOrder`, { orderId });

            if (response.status === 200) {
                updateOrder(orderId, "reassignedtoMod", "assignedModerator");
                setreassignedLoadingBtn(false);
            } else {
                // Handle the case where reassignment failed
                console.error("Reassignment failed");
                toast.error("Reassignment failed");
                setreassignedLoadingBtn(false);
            }
        } catch (error) {
            // Handle errors
            console.error("Error reassigning order:", error);
            setreassignedLoadingBtn(false);
        }
    };

    const processDigitalOrder = async (orderId) => {
        try {
            setDigitalProcessBtn(true);
            const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_URL}/orders/processDigitalOrder`, {
                orderId
            });

            if (response.status === 200) {
                // Update the order status or perform any other actions based on your requirements
                updateOrder(orderId, "delivered");
                toast.success("Digital order processed successfully");
                setDigitalProcessBtn(false);
                router.push("/admin/dashboard/compleatedOrder");
            } else {
                console.error("Digital order processing failed");
                toast.error("Digital order processing failed");
                setDigitalProcessBtn(false);
            }
        } catch (error) {
            console.error("Error processing digital order:", error);
            setDigitalProcessBtn(false);

            console.error("Error details:", error.response ? error.response.data : error.message); // Log error details
            toast.error("Error processing digital order");
        }
    };
    const foundStatus = order?.totalStatus?.findLast((status) => status.role === "refinedbyMod");
    const lastTwoStatuses = order?.totalStatus?.slice(-2);
    // Map the notes of last two statuses
    const note = lastTwoStatuses?.map(status => status.note);
    console.log(note);
    return loading ? (
        <div className='flex justify-center'>
            <span className='loading loading-ring loading-lg'>Loading...</span>
        </div>
    ) : (
        <div className='w-full'>
            <div>
                <div>
                    <DropdonwItemList
                        icon={<FaShoppingCart />}
                        title="Order Details"
                        isActive={false}
                    >
                        {/* Render data for each country */}
                        <div className=" w-full">
                            <div className="mx-2">
                                <a
                                    className="relative block  overflow-hidden rounded-lg"
                                >
                                    <div className="">
                                        <OrderInfo loading={loading} order={order} />
                                    </div>

                                </a>
                            </div>
                        </div>
                    </DropdonwItemList>
                </div>
                <div>
                    <DropdonwItemList
                        icon={<FaAddressCard />
                        }
                        title="Delivery Address"
                        isActive={false}
                    >
                        {/* Render data for each country */}
                        <div className=" w-full">
                            <div className="mx-2 ">
                                <a
                                    className="relative block  overflow-hidden rounded-lg  p-3 sm:p-4 lg:p-5"
                                >
                                    <div className="">
                                        <DeliveryInfo delivery={order?.address} loading={loading} />
                                    </div>

                                </a>
                            </div>
                        </div>
                    </DropdonwItemList>
                </div>

                <div className="w-full">
                    <DropdonwItemList
                        icon={<MdSpeakerNotes />}
                        title="Assigned to Notes"
                        isActive={false}
                    >
                        {/* Render data for each country */}
                        <div className=" w-full">
                            <div className="mx-2 ">
                                <a
                                    className="relative block  overflow-hidden rounded-lg  p-3 sm:p-4 lg:p-5"
                                >
                                    <div className="">
                                        <div className="my-3 flex justify-center items-center md:w-full">

                                            {note && (order?.status === "reassignedtoMod" || order?.status === "assignedModerator" || order?.status === "refinedbyMod") ? (
                                                <NotsList note={note} />
                                            ) : (
                                                <div>No note available</div>
                                            )}
                                        </div>

                                    </div>

                                </a>
                            </div>
                        </div>
                    </DropdonwItemList>
                </div>
                {/* Order Status List  */}
                <div className="mb-5 mt-2 w-full ">
                    <div className="rounded-lg border-spacing-1 bg-white shadow-md">
                        <OrderStatusList order={order} />
                    </div>
                </div>
                <div className='flex flex-wrap'>
                    <div className='max-h-96  w-1/2 overflow-auto'>
                        <div>
                            {order.items.map((image, index) => (
                                <ImageUplodeAndItemList key={index} image={image} order={order} handleImageSelection={handleImageSelection} handleImageChange={handleImageChange} uploadbtnLoading={uploadbtnLoading} />
                            ))}
                        </div>
                    </div>
                </div>
            </div>
            <div className='modal-action mt-4'>
                <div className='flex'></div>
                <form method='dialog'>
                    {order.status !== "assignedModerator" && order.status !== "reassignedtoMod" ? (
                        <></>
                    ) : order.items.every((item) => item.editedImg) ? (
                        <>
                            <button
                                type='button'
                                className='btn btn-primary btn-sm mr-2'
                                onClick={() => {
                                    document.getElementById(`modAssignModal${order._id}`).showModal();
                                }}
                            >
                                Assign To Admin <LuUserCheck className='text-lg' />
                            </button>
                            <NoteSubmit orderId={order._id} redirect={redirect} />
                        </>
                    ) : (
                        <></>
                    )}

                    {/* <button className='btn btn-error btn-sm text-white'>Close</button> */}
                </form>
            </div>
        </div>
    );
}
Leave a Comment