import React, { useMemo, useState, useEffect, useRef, useCallback, } from 'react'; import { Tooltip } from 'antd'; import { dateFormatChange1, extractLastNumberOrderId, getSession, } from '../../../Services/Others'; import { useDispatch } from 'react-redux'; import { getCardDataWithoutSub, getCardDataWithoutSubmodule, getLayoutproductCard, getPreferenceData, getSelectedFavItems, GlobalProductCategorie, GlobalProductSubCategorie, GlobalSalesDetailData, PreferenceData, } from '../../../Features/BookingScreen/BookingData/BookingData'; import './SalesCountComponent.scss'; import { Messages } from '../../../Components/Notifications/Messages'; import { useSelector } from 'react-redux'; import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin'; import { DefaultModal } from '../../../Components/Modal/DefaultModal'; import { Tables } from '../../../Components/Tables/Table'; import CustomisedInvoiceChange from '../Components/UtillComponents/CustomisedInvoiceChange.jsx'; import ProductPriceChange from '../Components/UtillComponents/ProductPriceChange.jsx'; import ReceivedStocksModal from '../../../Components/Modal/ReceivedStocksModal.jsx'; import ProductDetailsModal from '../../../Components/Modal/ProductDetailsModal.jsx'; import { MdOutlineCallReceived } from 'react-icons/md'; import { IoEye } from 'react-icons/io5'; import { TiTickOutline } from 'react-icons/ti'; import { getReceivedStocks, PostReceiveStocks, } from '../../../Features/stockReceivedGodown/ReceivedStock.js'; import { GoPackageDependencies } from 'react-icons/go'; import { getTemplateData } from '../../../Features/ThemeChange/ThemeChange.js'; import ShortcutKeyHelper from '../Components/UtillComponents/ShortcutKeyHelper.jsx'; import AllSalesPageSettings from '../Components/UtillComponents/AllSalesPageSettings.jsx'; const SalesCountComponent = React.memo( ({ DineInAccess, GlobalsalesDetailData }) => { // Destructure to simplify access to required values const { DineInOrderCount, TakeAwayOrderCount, OverAllOrderCount, SelfDineInOrderCount, SelfTakeAwayOrderCount, DineInAmount, TakeAwayAmount, OverAllTakeAwayOfferAmount, OverAllDineInOfferAmount, SelfTakeAwayAmount, SelfDineInAmount, PreOrderAmount, } = GlobalsalesDetailData.length > 0 ? GlobalsalesDetailData[0] : {}; const dispatch = useDispatch(); const appPreferences = useSelector(ApplicationPreferences); const dailySalesData = useSelector(GlobalSalesDetailData); const ProdSubCat = useSelector(GlobalProductSubCategorie); const prodCat = useSelector(GlobalProductCategorie); const templateData = useSelector(getTemplateData); const preferencedata = useSelector(PreferenceData); console.log(preferencedata, 'preferencedatasalescount'); const bookingTypePreference = appPreferences?.find( (preference) => preference?.PreferredCatName === 'Booking Type' )?.PreferenceCatDetails; const dinePreference = bookingTypePreference?.find( (type) => type?.PreferredSubCatName?.toLowerCase() === 'dine in' && type?.PreferredStatus === 'Y' ); const takeAwayPreference = bookingTypePreference?.find( (type) => type?.PreferredSubCatName?.toLowerCase() === 'take away' && type?.PreferredStatus === 'Y' ); const [messageType, setMessageType] = useState(null); const [messageData, setMessageData] = useState(null); const [page, setpage] = useState(1); const formRef = useRef(null); const [allowDecimal, setAllowDecimal] = useState(false); const [isMobile, setIsMobile] = useState(window.innerWidth < 768); const AppId = getSession('AppId'); const CompId = getSession('CompId'); const BranchId = getSession('BranchId'); const UserId = getSession('UserId'); const [TableData, setTableData] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); const [isNetAmtModalOpen, setIsNetAmtModalOpen] = useState(false); const [Customisebillno, setCustomisebillno] = useState(false); const [isReceivedModelOpen, setIsReceivedModelOpen] = useState(false); const [ProductDetailsModel, setProductDetailsModel] = useState(false); const [modalProductDetails, setModalProductDetails] = useState([]); const [AutoReceiveStock, setAutoReceiveStock] = useState(false); const [SelectedIndex, setSelectedIndex] = useState(null); const bookings = dailySalesData?.[0]?.BookedDetails; const orderDetails = dailySalesData?.[0]?.OrderDetails; const [currentPage, setCurrentPage] = useState(1); const rowsPerPage = 10; const totalPages = Math.ceil((bookings?.length || 0) / rowsPerPage); const startIndex = (currentPage - 1) * rowsPerPage; const currentData = bookings?.slice(startIndex, startIndex + rowsPerPage); console.log(dailySalesData, 'dailySalesDatadailySalesData', bookings); function safeRound(amountStr) { if (amountStr == null) return allowDecimal ? '0.00' : '0'; const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ''); const num = Number(cleaned); if (isNaN(num)) return allowDecimal ? '0.00' : '0'; return allowDecimal ? num.toFixed(2) : Math.round(num).toString(); } // Memoize the tooltip content const tooltipContent = useMemo(() => { if ( DineInAccess?.SettingValue === 'Y' && dinePreference && (DineInOrderCount > 0 || TakeAwayOrderCount > 0 || SelfTakeAwayOrderCount > 0 || SelfDineInOrderCount > 0) ) { return ( {takeAwayPreference && (

Take Away:{' '} {TakeAwayOrderCount + SelfTakeAwayOrderCount || 0}

)}

Dine In: {DineInOrderCount + SelfDineInOrderCount || 0}

} >

(OverAllOrderCount || 0 > 0) && setIsModalOpen(true) } > {isMobile ? 'SC' : 'Sales Count'}:{' '} {OverAllOrderCount || 0}

); } return (

(OverAllOrderCount || 0) > 0 && setIsModalOpen(true)} > {isMobile ? 'SC' : 'Sales Count'}:{' '} {OverAllOrderCount || 0}

); }, [ DineInAccess?.SettingValue, DineInOrderCount, TakeAwayOrderCount, OverAllOrderCount, isMobile, ]); useEffect(() => { getPreference(); getReceivedStock(); let AutoReceiveStock = preferencedata?.[0]?.SettingDtlDetails?.some( (s) => s?.SettingIdName?.toLowerCase() === 'autoreceivestock' && s?.SettingValue === 'Y' ); setAutoReceiveStock(!AutoReceiveStock); }, [preferencedata]); const getPreference = async () => { // const data = { AppId: AppId, CompId: CompId, BranchId: BranchId }; // const { data: res } = await dispatch(getPreferenceData(data)).unwrap(); const decimalSetting = preferencedata?.[0]?.SettingDtlDetails?.find( (setting) => setting?.SettingIdName?.toLowerCase() === 'decimal' && setting?.SettingValue === 'Y' ); if (decimalSetting) { setAllowDecimal(true); } let custombillsetting = preferencedata?.[0]?.SettingDtlDetails?.some( (s) => s?.SettingIdName?.toLowerCase() === 'customisedbillnumber' && s?.SettingValue === 'Y' ); setCustomisebillno(custombillsetting); }; const getReceivedStock = async () => { try { const response = await dispatch( getReceivedStocks({ CompId, BranchId, AppId }) ).unwrap(); if (response?.data?.statusCode === 1) { setTableData( response.data.data?.map((e) => { return { ...e, DispatchStockDetails: e?.DispatchStockDetails?.map((e) => { return { ...e, AcceptedQty: e?.DispatchedQty, }; }), }; }) ); } else { setTableData([]); console.warn('API returned unsuccessful status', response); } } catch (error) { console.error('Failed to fetch received stock:', error); } }; useEffect(() => { const handleResize = () => setIsMobile(window.innerWidth < 768); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); const onComplete = useCallback(() => { setMessageData(null); setMessageType(null); }, []); const columns = [ { title: 'SL.NO', key: 'sno', align: 'center', width: '50px', render: (text, object, index) => ( {(page - 1) * 10 + index + 1} ), }, { title: 'Req Id', key: 'RequestId', align: 'center', width: '70px', render: (text, record, index) => ( record?.RequestId?.split('-')?.pop() ), }, { title: 'Date & Time', dataIndex: 'dateTime', key: 'dateTime', align: 'center', width: '150px', render: (text, record, index) => dateFormatChange1(record.CreatedDate), }, { title: 'Received From', dataIndex: 'FromBranchName', key: 'FromBranchName', align: 'center', width: '120px', }, { title: 'Item', dataIndex: 'FromBranchName', key: 'FromBranchName', align: 'center', width: '50px', render: (text, record, index) => ( {record?.DispatchStockDetails?.length || 0} ), }, { title: 'Qty', dataIndex: 'FromBranchName', key: 'FromBranchName', align: 'center', width: '50px', render: (text, record, index) => (
{(record?.DispatchStockDetails ?? []).reduce( (total, item) => total + (item?.DispatchedQty || 0), 0 )}
), }, { title: 'dispatched By', dataIndex: 'DispatcherName', key: 'DispatcherName', align: 'center', width: '120px', }, // { // title: 'Product Details', // dataIndex: 'ProductDetails', // key: 'ProductDetails', // width: '120px', // align: 'center', // render: (text, record, index) => ( // { // handleModalOpen(index) // }} // > // // // ), // }, { title: 'Actions', dataIndex: 'fromBranch', key: 'fromBranch', align: 'center', width: '100px', render: (_, record, index) => (
handleModalOpen(index)} > Receive
), } ]; const handlePageChange = (current) => { setpage(current); }; const getstockbadge = async () => { let data = { CompId: CompId, BranchId: BranchId, AppId: AppId, }; await dispatch(getSelectedFavItems(data)).unwrap(); let data1 = { CompId: CompId, BranchId: BranchId, AppId: AppId, ProdSubCat: ProdSubCat, }; let data2 = { compId: CompId, branchId: BranchId, appId: AppId, prodCat: prodCat, }; if ( templateData?.BookingLayout?.[1]?.some( (item) => item?.OptionName === 'SubCategory' ) && ProdSubCat ) { await dispatch(getLayoutproductCard(data1)).unwrap(); } else if ( !templateData?.BookingLayout?.[1]?.some( (item) => item?.OptionName === 'SubCategory' ) ) { await dispatch(getCardDataWithoutSubmodule(data2)).unwrap(); } else { await dispatch(getCardDataWithoutSub(data2)).unwrap(); } }; const postApi = async (data, index) => { try { let postData = { AppId: AppId, CompId: CompId, FromLocationId: data?.FromLocationId, ToLocationId: data?.ToLocationId, RequestId: data?.RequestId, DispatchId: data?.DispatchId, ReceiveStockDetails: data?.DispatchStockDetails?.map((e) => { return { ProdId: e?.ProdId, InwardDtlId: e?.InwardDtlId, ReceivedQty: e?.DispatchedQty, AcceptedQty: e?.AcceptedQty, CreatedBy: UserId, }; }), CreatedBy: UserId, }; let res = await dispatch(PostReceiveStocks(postData))?.unwrap(); if (res?.data?.statusCode == 1) { setMessageData(res?.data?.response); setMessageType('success'); await getReceivedStock(); await getstockbadge(); } else { setMessageData(res?.data?.response); setMessageType('error'); } } catch (error) { console.log(error); } }; const handleModalOpen = (index) => { setSelectedIndex(index); const pd = TableData?.[index]?.DispatchStockDetails || []; setModalProductDetails( Array.isArray(pd) ? JSON.parse(JSON.stringify(pd)) : [] ); setProductDetailsModel(true); setIsReceivedModelOpen(false); }; const handleModalCancel = () => { setProductDetailsModel(false); setModalProductDetails([]); setIsReceivedModelOpen(true); }; const handleModalSubmit = () => { const updatedData = { ...TableData[SelectedIndex], DispatchStockDetails: modalProductDetails, }; setTableData((prev) => { const copy = Array.isArray(prev) ? [...prev] : []; const idx = SelectedIndex ?? 0; if (copy[idx]) { copy[idx] = updatedData; } return copy; }); setProductDetailsModel(false); // setIsReceivedModelOpen(true) postApi(updatedData, SelectedIndex); setModalProductDetails([]); }; return ( <>
{tooltipContent} {DineInAccess?.SettingValue === 'Y' && takeAwayPreference && (TakeAwayOrderCount > 0 || SelfTakeAwayOrderCount > 0 || PreOrderAmount > 0) && (

Admin + Staff :

{SelfTakeAwayAmount != 0 &&

Self Booking :

} {PreOrderAmount != 0 &&

Preorder :

} {OverAllTakeAwayOfferAmount != 0 &&

Offer(-) :

}

{safeRound(TakeAwayAmount)}

{SelfTakeAwayAmount != 0 && (

{safeRound(SelfTakeAwayAmount)}

)} {PreOrderAmount != 0 && (

{safeRound(PreOrderAmount)}

)} {OverAllTakeAwayOfferAmount != 0 && (

{safeRound(OverAllTakeAwayOfferAmount)}

)}
Total
{safeRound( TakeAwayAmount + SelfTakeAwayAmount + PreOrderAmount - OverAllTakeAwayOfferAmount )}
} >

{isMobile ? 'TA' : 'Take Away'}:{' '} {safeRound( (TakeAwayAmount || 0 + SelfTakeAwayAmount || 0 + PreOrderAmount || 0) - OverAllTakeAwayOfferAmount )}

{/*

Take Away: {Math.round(((TakeAwayAmount + SelfTakeAwayAmount + PreOrderAmount) - OverAllTakeAwayOfferAmount)) || 0}

*/} )} {DineInAccess?.SettingValue === 'Y' && dinePreference && (DineInOrderCount > 0 || SelfDineInOrderCount > 0) && (

Admin + Staff :

{SelfDineInAmount != 0 &&

Self Booking :

} {OverAllDineInOfferAmount != 0 &&

Offer(-) :

}

{safeRound(DineInAmount)}

{SelfDineInAmount != 0 && (

{safeRound(SelfDineInAmount)}

)} {OverAllDineInOfferAmount != 0 && (

{safeRound(OverAllDineInOfferAmount)}

)}
Total
{safeRound( DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount )}
} >

{isMobile ? 'DI' : 'Dine In'}:{' '} {safeRound( DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount )}

{/*

Dine In: {Math.round(((DineInAmount + SelfDineInAmount) - OverAllDineInOfferAmount)) || 0}

*/}
)}

safeRound( (TakeAwayAmount + SelfTakeAwayAmount + PreOrderAmount - OverAllTakeAwayOfferAmount || 0) + (DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount) ) > 0 && setIsNetAmtModalOpen(true) } > {isMobile ? 'NA' : 'Net Amt'}:{' '} {safeRound( (TakeAwayAmount + SelfTakeAwayAmount + PreOrderAmount - OverAllTakeAwayOfferAmount || 0) + (DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount) )}

{Customisebillno && } {/* Modal with table for multiple bookings */} setIsModalOpen(false)} handleSubmit={() => setIsModalOpen(false)} width={700} footer={false} >
{/* */} {currentData?.length > 0 ? ( currentData?.map((item, index) => ( (e.currentTarget.style.backgroundColor = '#d6e4ff') } onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = index % 2 === 0 ? '#f7faff' : '#e9f1ff') } > {/* */} )) ) : ( )}
S.No Order ID Customer Mobile Booked By Payment Type Amount (₹)
{startIndex + index + 1} {extractLastNumberOrderId(item.OrderId)} {item.CustName || '—'} {item.CustMobile || '—'} {item.BookedBy || "—"} {item.PaymentTypeName || '—'} ₹{item.Amount?.toLocaleString()}
No booking data available
{/* Pagination */} {totalPages > 1 && (
{currentPage == 1 ? ( '' ) : ( )} Page {currentPage} of {totalPages}
)}
{/* Modal with table for multiple Net Amt */} setIsNetAmtModalOpen(false)} handleSubmit={() => setIsNetAmtModalOpen(false)} width={800} footer={false} >
{orderDetails?.map((item, index) => { const total = (item.CashAmount || 0) + (item.UpiAmount || 0) + (item.CardAmount || 0) + (item.CreditAmount || 0); return ( (e.currentTarget.style.backgroundColor = '#e6f2ff') } onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = index % 2 === 0 ? '#f7faff' : '#ffffff') } > ); })}
Cash UPI Card Credit Business UPI Total
Count Amt Count Amt Count Amt Count Amt Count Amt
{item.CashCount} {item.CashAmount} {item.UpiCount} {item.UpiAmount} {item.CardCount} {item.CardAmount} {item.CreditCount} {item.CreditAmount} {item.BusinessUpiCount} {item.BusinessUpiAmount} {total}
{TableData?.length > 0 && AutoReceiveStock && ( )} { setIsReceivedModelOpen(false); }} columns={columns} tableData={TableData} handlePageChange={handlePageChange} customTable={false} /> setModalProductDetails(d)} onSubmit={handleModalSubmit} /> ); } ); export default SalesCountComponent;