import { useEffect, useState, useMemo, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { FaChartLine, FaRupeeSign } from 'react-icons/fa';
import { Badge, DatePicker, Popconfirm, Tooltip } from 'antd';
import { isMobile } from 'react-device-detect';
import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin';
import {
getCardDataWithoutSub,
getCardDataWithoutSubmodule,
getLayoutproductCard,
getPreferenceData,
getSelectedFavItems,
GlobalOrderStatus,
GlobalOtherSevices,
GlobalProductCategorie,
GlobalProductSubCategorie,
GlobalSalesDetailData,
PreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import {
dateFormatChange1,
extractLastNumberOrderId,
getSession,
} from '../../../Services/Others';
import { useDateStore } from '../../../Features/BookingScreen/BookingData/DateStore';
import dayjs from 'dayjs';
import moment from 'moment';
import { BsUiChecks } from 'react-icons/bs';
import { FaCheckToSlot } from 'react-icons/fa6';
import PozoKioskIcon from '../Components/UtillComponents/Pozo retail icons/PozoKioskIcon';
import { globalKioskSalesCount } from '../../../Features/Kiosk/kiosk';
import BSKioskCounterPayment from '../Components/UtillComponents/BSKioskCounterPayment';
import BSExpireProductsList from '../Components/UtillComponents/BSExpireProductsList';
import TooltipWrapper from '../../../Components/Tooltip/Tooltip';
import {
getTemplateData,
StoredSessionData,
} from '../../../Features/ThemeChange/ThemeChange';
import BookingCloseIcon from '../Components/UtillComponents/BookingCloseIcon';
import RetailBookingClosing from './RetailBookingClose';
import {
getBookingStatus,
GlobalBookingStatus,
} from '../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail';
import { PutBookingClose } from '../../../Features/BookingScreen/RetailBookingClose';
import BSEwayBillicon from '../../BookingScreen/Components/UtillComponents/BSEwayBillicon.jsx';
import ListOfSalesInvoices from '../Components/BSBillingTables/ListofInvoices/ListOfSalesInvoices.jsx';
import { DefaultModal } from '../../../Components/Modal/DefaultModal.jsx';
import CustomisedInvoiceChange from '../Components/UtillComponents/CustomisedInvoiceChange.jsx';
import ProductPriceChange from '../Components/UtillComponents/ProductPriceChange.jsx';
import { MdCallReceived, MdOutlineCallReceived } from 'react-icons/md';
import {
getReceivedStocks,
PostReceiveStocks,
} from '../../../Features/stockReceivedGodown/ReceivedStock.js';
import { TiTickOutline } from 'react-icons/ti';
import ReceivedStocksModal from '../../../Components/Modal/ReceivedStocksModal.jsx';
import ProductDetailsModal from '../../../Components/Modal/ProductDetailsModal.jsx';
import { GoPackageDependencies } from 'react-icons/go';
import { Messages } from '../../../../ownLib/my-ui-lib.js';
import ShortcutKeyHelper from '../Components/UtillComponents/ShortcutKeyHelper.jsx';
const SalesCountForStandard = ({
DineInAccess,
GlobalsalesDetailData,
PricingAppPricingName,
}) => {
const dispatch = useDispatch();
const AppId = getSession('AppId');
const CompId = getSession('CompId');
const BranchId = getSession('BranchId');
const UserId = getSession('UserId');
const ProdSubCat = useSelector(GlobalProductSubCategorie);
const prodCat = useSelector(GlobalProductCategorie);
const templateData = useSelector(getTemplateData);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [allowDecimal, setAllowDecimal] = useState(false);
const [BookingModalOpen, setBookingModalOpen] = useState(false);
const [ListOfInvoices, setListOfInvoices] = useState(false);
const { selectedDate, setSelectedDate } = useDateStore();
const [Kioskopen, setKioskopen] = useState(false);
const badgeCount = useSelector(globalKioskSalesCount);
const OtherServicesglobal = useSelector(GlobalOtherSevices);
const appPreferences = useSelector(ApplicationPreferences);
const SessionData = useSelector(StoredSessionData);
const OrderStatus = useSelector(GlobalOrderStatus);
const dailySalesData = useSelector(GlobalSalesDetailData);
const [page, setpage] = useState(1);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isNetAmtModalOpen, setIsNetAmtModalOpen] = useState(false);
const [isReceivedModelOpen, setIsReceivedModelOpen] = useState(false);
const [Customisebillno, setCustomisebillno] = useState(false);
const bookings = dailySalesData?.[0]?.BookedDetails;
const orderDetails = dailySalesData?.[0]?.OrderDetails;
const [currentPage, setCurrentPage] = useState(1);
const [TableData, setTableData] = useState([]);
const [ProductDetailsModel, setProductDetailsModel] = useState(false);
const [modalProductDetails, setModalProductDetails] = useState([]);
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
const [SelectedIndex, setSelectedIndex] = useState(null);
const [AutoReceiveStock, setAutoReceiveStock] = useState(false);
const rowsPerPage = 10;
const totalPages = Math.ceil((bookings?.length || 0) / rowsPerPage);
const startIndex = (currentPage - 1) * rowsPerPage;
const currentData = bookings?.slice(startIndex, startIndex + rowsPerPage);
const preferencedata = useSelector(PreferenceData);
console.log(dailySalesData, 'dailySalesDatadailySalesData', bookings);
const bookingTypePreference =
appPreferences?.find((p) => p?.PreferredCatName === 'Booking Type')
?.PreferenceCatDetails || [];
const dinePreference = bookingTypePreference.find(
(p) =>
p?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
p?.PreferredStatus === 'Y'
);
const takeAwayPreference = bookingTypePreference.find(
(p) =>
p?.PreferredSubCatName?.toLowerCase() === 'take away' &&
p?.PreferredStatus === 'Y'
);
const commonModulePreference = appPreferences?.find(
(preference) => preference?.PreferredCatName === 'Common Module'
)?.PreferenceCatDetails;
const sportsAppPreference = commonModulePreference?.find(
(preference) =>
preference?.PreferredSubCatName === 'SportsApp' &&
preference?.PreferredStatus === 'Y'
);
const salespagefields = appPreferences?.find(
(pref) => pref?.PreferredCatName === 'Sales Page Fields'
)?.PreferenceCatDetails;
const AvailableDate = salespagefields?.find(
(type) =>
type?.PreferredSubCatName?.toLowerCase() === 'available date' &&
type?.PreferredStatus === 'Y'
);
const { isBulk, setIsBulk } = useDateStore();
const BookingStatus = useSelector(GlobalBookingStatus);
const CheckBookingStatus =
BookingStatus?.find((item) => item.ScreenType === 'Booking')
?.ScreenStatus ?? 'Open';
const preferenceshortcutkey = preferencedata?.[0]?.[
'SettingDtlDetails'
]?.some(
(item) =>
item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
item.SettingValue === 'Y'
);
const sales = GlobalsalesDetailData?.[0] || {};
const {
DineInOrderCount = 0,
TakeAwayOrderCount = 0,
OverAllOrderCount = 0,
SelfDineInOrderCount = 0,
SelfTakeAwayOrderCount = 0,
DineInAmount = 0,
TakeAwayAmount = 0,
OverAllTakeAwayOfferAmount = 0,
OverAllDineInOfferAmount = 0,
SelfTakeAwayAmount = 0,
SelfDineInAmount = 0,
PreOrderAmount = 0,
} = sales;
useEffect(() => {
// const { data: res } = await dispatch(
// getPreferenceData({ AppId, CompId, BranchId })
// ).unwrap();
const decimalSetting = preferencedata?.[0]?.SettingDtlDetails?.find(
(s) =>
s?.SettingIdName?.toLowerCase() === 'decimal' && s?.SettingValue === 'Y'
);
setAllowDecimal(!!decimalSetting);
let custombillsetting = preferencedata?.[0]?.SettingDtlDetails?.some(
(s) =>
s?.SettingIdName?.toLowerCase() === 'customisedbillnumber' &&
s?.SettingValue === 'Y'
);
setCustomisebillno(custombillsetting);
let AutoReceiveStock = preferencedata?.[0]?.SettingDtlDetails?.some(
(s) =>
s?.SettingIdName?.toLowerCase() === 'autoreceivestock' &&
s?.SettingValue === 'Y'
);
setAutoReceiveStock(!AutoReceiveStock);
}, [preferencedata]);
// useEffect(() => {
// if (!selectedDate || (Array.isArray(selectedDate) && selectedDate.length === 0)) {
// setSelectedDate(dayjs());
// }
// }, [selectedDate, setSelectedDate]);
useEffect(() => {
if (AppId && CompId && BranchId && UserId) {
fetchBookingStatus();
}
getReceivedStock();
}, [AppId, CompId, BranchId, UserId]);
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);
}
};
const columns = [
{
title: 'SL.NO',
key: 'sno',
align: 'center',
width: '40px',
render: (text, object, index) => (
{(page - 1) * 10 + index + 1}
),
},
{
title: 'Req Id',
key: 'RequestId',
align: 'center',
width: '80px',
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',
// title: 'Item ',
dataIndex: 'FromBranchName',
key: 'FromBranchName',
align: 'center',
width: '50px',
render: (text, record, index) => (
{record?.DispatchStockDetails?.length || 0}
),
},
{
title: 'Qty',
// 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',
// 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 onComplete = useCallback(() => {
setMessageData(null);
setMessageType(null);
}, []);
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([]);
};
const safeRound = (value) => {
const num = Number(String(value).replace(/[^0-9.-]+/g, ''));
if (isNaN(num)) return allowDecimal ? '0.00' : '0';
return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
};
const disablePastDates = (current) => {
return current && current < moment().startOf('day');
};
const totalTakeAway =
TakeAwayAmount +
SelfTakeAwayAmount +
PreOrderAmount -
OverAllTakeAwayOfferAmount;
const totalDineIn =
DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount;
const netAmount = totalTakeAway + totalDineIn;
const showSalesTooltip = useMemo(() => {
return (
DineInAccess?.SettingValue === 'Y' &&
DineInOrderCount +
TakeAwayOrderCount +
SelfTakeAwayOrderCount +
SelfDineInOrderCount >
0 &&
(takeAwayPreference || dinePreference)
);
}, [DineInAccess, sales, dinePreference, takeAwayPreference]);
const renderBreakdown = (labelMap) => (
{labelMap.map(
(item) => item.value !== 0 &&
{item.label}
)}
{labelMap.map(
(item) =>
item.value !== 0 && (
{safeRound(item.value)}
)
)}
Total
{safeRound(
labelMap.reduce(
(sum, item) => sum + (item.includeInTotal ? item.value : 0),
0
)
)}
);
// Fix: Convert string dates to dayjs objects for the DatePicker
const getDatePickerValue = () => {
if (!selectedDate) return isBulk ? [] : null;
console.log(selectedDate, 'selectedDate');
if (isBulk) {
// For bulk mode, convert string array to dayjs objects array
if (Array.isArray(selectedDate)) {
return selectedDate.map((date) => dayjs(date));
}
return [];
} else {
// For single date mode, handle both string and dayjs object
if (Array.isArray(selectedDate) && selectedDate.length > 0) {
return dayjs(selectedDate[0]);
}
return dayjs(selectedDate);
}
};
const handleDateChange = (dateOrDates) => {
if (isBulk) {
// For bulk mode, convert dayjs objects to string format
const formattedDates = dateOrDates
? dateOrDates.map((d) => d.format('YYYY-MM-DD'))
: [];
setSelectedDate(formattedDates);
} else {
// For single date mode
if (dateOrDates) {
setSelectedDate(dateOrDates);
} else {
setSelectedDate([]);
}
}
};
const fetchBookingStatus = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
UserId: UserId,
};
await dispatch(getBookingStatus(data));
};
const BookingOpenFun = async (status) => {
let Postdata = {
AppId: AppId,
CompId: CompId,
BranchId: BranchId,
UserId: UserId,
ScreenType: 'Booking',
ScreenStatus: status,
CreatedBy: UserId,
Date: new Date(),
};
let Postresponse = await dispatch(PutBookingClose(Postdata)).unwrap();
if (Postresponse?.data?.statusCode === 1) {
fetchBookingStatus();
} else {
}
};
const openModalKiosk = () => {
setKioskopen(true);
};
const closeModalKiosk = () => {
setKioskopen(false);
};
const OpenBookingModal = () => {
setBookingModalOpen(true);
};
const HandleBookingModalClose = () => {
setBookingModalOpen(false);
};
const OpenListOfInvoices = () => {
setListOfInvoices(true);
};
const handleInvoiceClose = () => {
setListOfInvoices(false);
};
// Table row selection state and handlers
const onSelectChange = (newSelectedRowKeys) => {
setSelectedRowKeys(newSelectedRowKeys);
};
const handleSubmitSelectedRows = () => {
// TODO: replace this with real submit logic
console.log('Submitting selected rows:', selectedRowKeys);
setIsReceivedModelOpen(false);
setSelectedRowKeys([]);
};
const rowSelection = {
selectedRowKeys,
onChange: onSelectChange,
};
return (
{/* { AvailableDate &&
{isBulk ? {
setIsBulk(!isBulk);
setSelectedDate([]);
}} /> : {
setIsBulk(!isBulk);
setSelectedDate([]);
}} />}
} */}
{/*
{AvailableDate && !isBulk &&
}
{isBulk && AvailableDate && (
)}
*/}
{showSalesTooltip ? (
{takeAwayPreference && (
Takeaway:
{TakeAwayOrderCount + SelfTakeAwayOrderCount}
)}
{dinePreference && (
Dine-in:
{DineInOrderCount + SelfDineInOrderCount}
)}
}
onClick={() =>
(OverAllOrderCount || 0) > 0 && setIsModalOpen(true)
}
>
{isMobile ? 'Count' : 'Sales Count'} : {OverAllOrderCount}
) : (
(OverAllOrderCount || 0) > 0 && setIsModalOpen(true)
}
>
{isMobile ? 'Count' : 'Sales Count'} : {OverAllOrderCount}
)}
{/* Rest of your component remains the same */}
{DineInAccess?.SettingValue === 'Y' &&
takeAwayPreference &&
(TakeAwayOrderCount || SelfTakeAwayOrderCount || PreOrderAmount) >
0 && (
{isMobile ? 'TA' : 'Take Away'} :
{`₹ ${safeRound(totalTakeAway)}`}
)}
{DineInAccess?.SettingValue === 'Y' &&
dinePreference &&
(DineInOrderCount || SelfDineInOrderCount) > 0 && (
{isMobile ? 'DI' : 'Dine In'} :
{`₹ ${safeRound(totalDineIn)}`}
)}
netAmount > 0 && setIsNetAmtModalOpen(true)}
style={{ cursor: 'pointer' }}
>
{isMobile ? 'NA' : 'Net Amount'} : ₹ {safeRound(netAmount)}
{TableData?.length > 0 && !sportsAppPreference && AutoReceiveStock && (
setIsReceivedModelOpen(true)}
>
Stock
)}
{preferenceshortcutkey && }
{Customisebillno &&
}
{SessionData?.FeatureAddonData?.FeatureDtls?.find(
(item) => item?.FeatureAddonName?.toLowerCase() === 'kiosk sales'
) &&
!sportsAppPreference && (
0 ? 'none' : 'auto',
opacity: OrderStatus > 0 ? 0.5 : 1,
}}
>
{!OtherServicesglobal && (
openModalKiosk()}
style={{ cursor: 'pointer', fontSize: '1.5rem' }}
className="iconsize"
/>
)}
)}
{Kioskopen && (
)}
{!OtherServicesglobal && !sportsAppPreference && (
{' '}
)}
{!OtherServicesglobal && (
<>
{CheckBookingStatus == 'Open' ? (
{' '}
{/* Booking Close */}
) : (
BookingOpenFun('Open')}
>
)}
{!sportsAppPreference && (
{''}
)}
>
)}
{BookingModalOpen && (
)}
{ListOfInvoices && (
)}
{/* Modal with table for multiple bookings */}
setIsModalOpen(false)}
handleSubmit={() => setIsModalOpen(false)}
width={700}
footer={false}
>
S.No
Order ID
Customer
Mobile
{/* Booked By */}
Payment Type
Amount (₹)
{currentData?.length > 0 ? (
currentData?.map((item, index) => (
(e.currentTarget.style.backgroundColor = '#d6e4ff')
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor =
index % 2 === 0 ? '#f7faff' : '#e9f1ff')
}
>
{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 ? (
''
) : (
setCurrentPage((p) => Math.max(p - 1, 1))}
disabled={currentPage === 1}
style={{
padding: '5px 10px',
backgroundColor: '#003366',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
opacity: currentPage === 1 ? 0.5 : 1,
}}
>
Prev
)}
Page {currentPage} of {totalPages}
setCurrentPage((p) => Math.min(p + 1, totalPages))
}
disabled={currentPage === totalPages}
style={{
padding: '5px 10px',
backgroundColor: '#003366',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor:
currentPage === totalPages ? 'not-allowed' : 'pointer',
opacity: currentPage === totalPages ? 0.5 : 1,
}}
>
Next
)}
{/* Modal with table for multiple Net Amt */}
setIsNetAmtModalOpen(false)}
handleSubmit={() => setIsNetAmtModalOpen(false)}
width={800}
footer={false}
>
Cash
UPI
Card
Credit
Business UPI
Total
Count
Amt
Count
Amt
Count
Amt
Count
Amt
Count
Amt
{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')
}
>
{item.CashCount}
{item.CashAmount}
{item.UpiCount}
{item.UpiAmount}
{item.CardCount}
{item.CardAmount}
{item.CreditCount}
{item.CreditAmount}
{item.BusinessUpiCount}
{item.BusinessUpiAmount}
{total}
);
})}
{
setIsReceivedModelOpen(false);
setSelectedRowKeys([]);
}}
columns={columns}
tableData={TableData}
handlePageChange={handlePageChange}
customTable={false}
/>
setModalProductDetails(d)}
onSubmit={handleModalSubmit}
/>
);
};
export default SalesCountForStandard;