/* eslint-disable @typescript-eslint/no-explicit-any */ import React from "react"; import { downloadBulkStickerPrint, getPackages } from "../../../Api/OrderApi"; import HourGlassLoader from "../../Loader/Loader"; import AddressPrintTemplate from "./Containers/AddressPrintTemplate"; import { useSearchParams } from "next/navigation"; import { OrderFlowType, UserTypes } from "@/Constant/enums"; import { getFormattedAddress } from "../../../lib/Helper"; import AddressPrintTemplateSmall from "./Containers/AddressPrintTemplateSmall"; import AddressPrintTemplateA4 from "./Containers/AddressPrintTemplateA4"; import { toast } from "react-toastify"; interface AddressLabelProps { order?: any; orderId?: string; printSize?: string; } const AddressLabel: React.FC = ({ order: propOrder, orderId, printSize = "" }) => { const [orders, setOrders] = React.useState(propOrder ? [propOrder] : []); const searchParams: any = useSearchParams(); const pkgId = searchParams.get("pkg"); const latestOrderLength = searchParams.get("len") || ""; const hasQueryParams = typeof window !== "undefined" && window.location.search.length > 0; const storedUser = localStorage.getItem("ALL_DATA"); const allData = storedUser ? JSON.parse(storedUser)?.data : null; const getFormattedAddressLines = (value?: any) => { return getFormattedAddress(value); }; React.useEffect(() => { const fetchOrderData = async () => { if ((orderId || pkgId) && !propOrder) { try { const response = await getPackages({ list_all: true }); let filtered = response; if (pkgId) { filtered = response.filter( (pkg: any) => pkg?.id === parseInt(pkgId) ); } else if (orderId) { filtered = response.filter( (pkg: any) => pkg?.order?.id === parseInt(orderId) ); } setOrders(filtered || []); } catch (error) { console.error("Error fetching packages:", error); } } }; fetchOrderData(); }, [orderId, pkgId, propOrder]); if (!orders || orders.length === 0) { return ; } return ( <> {orders.map((order, index) => { const formattedAddressLines = (allData?.addressFormatType?.name === "Standard") ? getFormattedAddressLines({ flatDetails: order?.order?.pickup_flat_or_office_number ?? order?.order?.pickupFlatOrOfficeNumber ?? "", buildingDetails: order?.order?.pickup_building_details, blockDetails: order?.order?.pickup_block_details, roadDetails: order?.order?.pickup_road_details, }) : order?.order?.sender_address || getFormattedAddressLines({ flatDetails: order?.order?.pickup_flat_or_office_number ?? order?.order?.pickupFlatOrOfficeNumber ?? "", buildingDetails: order?.order?.pickup_building_details, blockDetails: order?.order?.pickup_block_details, roadDetails: order?.order?.pickup_road_details, });; const recipientAddress = allData?.addressFormatType?.name === "Standard" ? getFormattedAddressLines({ flatDetails: order?.order?.destination_flat_or_office_number ?? order?.order?.destinationFlatOrOfficeNumber ?? "", buildingDetails: order?.order?.destination_building_details, blockDetails: order?.order?.destination_block_details, roadDetails: order?.order?.destination_road_details, }) : order?.order?.destination_address || getFormattedAddressLines({ flatDetails: order?.order?.destination_flat_or_office_number ?? order?.order?.destinationFlatOrOfficeNumber ?? "", buildingDetails: order?.order?.destination_building_details, blockDetails: order?.order?.destination_block_details, roadDetails: order?.order?.destination_road_details, }); const recipientPhoneNumber = [ order?.order?.destination_mobile_number, order?.order?.destination_alternate_number, ].filter(Boolean).join(" / "); const senderPhoneNumber = [ order?.order?.pickup_mobile_number, order?.order?.pickup_alternate_number, ].filter(Boolean).join(" / "); const templateOrder = { ...order, shipByDate: order?.shipByDate, weight: order?.totalWeight?.toString(), orderId: order?.customerInputOrderId, parcelInfo: order?.order?.service_type?.name || "---", paymentType: order?.order?.created_by_details?.userType?.id === UserTypes?.NormalCustomer ? "Prepaid" : order?.order?.cod_amount > 0 ? "COD" : "INV", recipientName: order?.order?.order_flow_type === OrderFlowType.Return ? order?.order?.created_by_details?.companyName || `${order?.order?.created_by_details?.firstName} ${order?.order?.created_by_details?.lastName}` || "---": order?.order?.destination_customer_name || "---", senderName: order?.order?.order_flow_type === OrderFlowType.Return ? order?.order?.destination_customer_name || "---" : order?.order?.created_by_details?.companyName || `${order?.order?.created_by_details?.firstName} ${order?.order?.created_by_details?.lastName}` || "---", recipientAddress: recipientAddress, senderAddress: formattedAddressLines, recipientPhone: order?.destinationCustomerPhone, boxInfo: order?.generated_order_package_id || "---", blockNo: order?.order?.destination_block_details?.code || order?.order?.destination_block_details?.name || "---", packageDescription: order?.package_description || "---", senderPostcode: order?.senderPostcode, amount: order?.amount?.toString(), deliveryType: order?.order?.service_type?.name || "", trackingNumber: order?.trackingNumber, recipientPhoneNumber: recipientPhoneNumber || "", senderPhoneNumber: senderPhoneNumber || "", isReturnOrder: order?.order?.order_flow_type === OrderFlowType.Return ? true : false }; return (
{printSize === "80x55" ? ( ) : printSize === "A4" ? ( ) : ( )} {orders.length > 1 &&
}
); })} ); }; export default function AddressPrint() { const [orders, setOrders] = React.useState([]); const [isLoading, setIsLoading] = React.useState(false); const [printSize, setPrintSize] = React.useState("6x4"); // Default size const addressRef = React.useRef(null); const searchParams: any = useSearchParams(); const orderId = searchParams.get("id"); const latestOrderLength = searchParams.get("len") || ""; React.useEffect(() => { const fetchOrders = async () => { setIsLoading(true); try { const orderList: any = await getPackages({ list_all: latestOrderLength ? false : true, limit: latestOrderLength, }); setOrders(orderList); } catch (error) { console.error("Failed to fetch orders:", error); } finally { setIsLoading(false); } }; fetchOrders(); }, [latestOrderLength]); // const handlePrintOld = () => { // if (addressRef.current) { // const printWindow = window.open("", "_blank", "width=400,height=600"); // let printStyle = ""; // if (printSize === "6x4") { // printStyle = ` // // `; // } else if (printSize === "80x55") { // printStyle = ` // // `; // } // printWindow?.document.write( // `Print${printStyle}` // ); // printWindow?.document.write(addressRef.current.innerHTML); // printWindow?.document.write(""); // printWindow?.document.close(); // printWindow?.focus(); // printWindow?.print(); // } // }; const handlePrint = () => { const content = document.getElementById("print-content"); const printWindow: any = window.open("", "_blank", "width=700,height=700"); const itemsHTML = Array.from(content?.children || []) .filter((child) => child?.innerHTML.trim() !== "") .map((child, index, arr) => { const isLast = index === arr.length - 1; return ` `; }).join(""); printWindow.document.write(` Print ${itemsHTML} `); printWindow.document.close(); printWindow.onload = () => { const images = printWindow.document.images; let loadedCount = 0; const checkAllImagesLoaded = () => { loadedCount++; if (loadedCount === images.length) { printWindow.focus(); printWindow.print(); printWindow.close(); } }; if (images.length === 0) { printWindow.focus(); printWindow.print(); printWindow.close(); } else { for (const img of images) { if (img.complete) { checkAllImagesLoaded(); } else { img.onload = checkAllImagesLoaded; img.onerror = checkAllImagesLoaded; } } } }; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars const [isDownloading, setIsDownloading] = React.useState(false); // eslint-disable-next-line @typescript-eslint/no-unused-vars const handleDownloadStickers = async () => { try { setIsDownloading(true); // Call API with the selected print size const size = printSize.replace("x", "*"); const response = await downloadBulkStickerPrint(size ?? ""); // Convert response to Blob const blob = new Blob([response], { type: "application/pdf" }); const url = window.URL.createObjectURL(blob); // Create a temporary link to download const link = document.createElement("a"); link.href = url; link.setAttribute("download", `bulk-stickers-${printSize}.pdf`); document.body.appendChild(link); link.click(); link.parentNode?.removeChild(link); toast.success("Stickers downloaded successfully"); } catch (error: any) { console.error("Error downloading stickers:", error); toast.error( error?.response?.data?.message || "Failed to download stickers. Please try again." ); } finally { setIsDownloading(false); } }; return ( <>
{/* */}
); }