-
+ Name
+
{' '}
@@ -5989,30 +5992,30 @@ const BsBookingitemCard = (props) => {
{slots.map((timeSlot, idx) => {
const isBooked =
timeSlot?.SlotStatus?.toLowerCase() ==
- 'booked' || false;
+ 'booked' || false;
const isBlocked =
timeSlot?.SlotStatus?.toLowerCase() ==
- 'blocked' || false;
+ 'blocked' || false;
const isPartiallyBooked =
timeSlot?.SlotStatus?.toLowerCase() ===
- 'partially booked' || false;
+ 'partially booked' || false;
const isPartiallyBlocked =
timeSlot?.SlotStatus?.toLowerCase() ===
- 'partially blocked' || false;
+ 'partially blocked' || false;
const isSelected =
CartOrderDetails?.some(
(selected) =>
selected.ProdId ===
- timeSlot?.ProdId &&
+ timeSlot?.ProdId &&
selected.InwardDtlId ===
- timeSlot?.InwardDtlId &&
+ timeSlot?.InwardDtlId &&
selected.VariantAvailableFrom ===
- timeSlot?.VariantAvailableFrom &&
+ timeSlot?.VariantAvailableFrom &&
selected.VariantAvailableTo ===
- timeSlot?.VariantAvailableTo &&
+ timeSlot?.VariantAvailableTo &&
selected.BookedDate ===
- timeSlot?.BookedDate
+ timeSlot?.BookedDate
);
const isAlreadyAdded =
@@ -6020,25 +6023,25 @@ const BsBookingitemCard = (props) => {
const itemDate =
item?.BookedDate
? new Date(
- item?.BookedDate
- ).toLocaleDateString()
+ item?.BookedDate
+ ).toLocaleDateString()
: null;
return (
item?.InwardDtlId ===
- timeSlot?.InwardDtlId &&
+ timeSlot?.InwardDtlId &&
item?.VariantAvailableFrom ===
- timeSlot?.VariantAvailableFrom &&
+ timeSlot?.VariantAvailableFrom &&
item?.VariantAvailableTo ===
- timeSlot?.VariantAvailableTo &&
+ timeSlot?.VariantAvailableTo &&
item?.ProdVariantName?.toLowerCase() ===
- timeSlot?.VarientName?.toLowerCase() &&
+ timeSlot?.VarientName?.toLowerCase() &&
itemDate === dataDate &&
(item?.SinglePc === 'Y'
? returnVariantStock(
- data,
- CartOrderDetails
- ) === 0
+ data,
+ CartOrderDetails
+ ) === 0
: true)
);
});
@@ -6051,13 +6054,13 @@ const BsBookingitemCard = (props) => {
selectedSlots?.some(
(selected) =>
selected.InwardDtlId ===
- timeSlot?.InwardDtlId &&
+ timeSlot?.InwardDtlId &&
selected.VariantAvailableFrom ===
- timeSlot?.VariantAvailableFrom &&
+ timeSlot?.VariantAvailableFrom &&
selected.VariantAvailableTo ===
- timeSlot?.VariantAvailableTo &&
+ timeSlot?.VariantAvailableTo &&
selected.TempDate ===
- timeSlot?.BookedDate
+ timeSlot?.BookedDate
);
const isDisabled =
isBooked ||
@@ -6070,25 +6073,26 @@ const BsBookingitemCard = (props) => {
return (
{
@@ -6107,7 +6111,7 @@ const BsBookingitemCard = (props) => {
timeSlot,
product,
onePeiceFlow ||
- isPartiallyBooked,
+ isPartiallyBooked,
!slotEnded
);
}
@@ -6125,7 +6129,7 @@ const BsBookingitemCard = (props) => {
₹
{onePeiceFlow ||
- isPartiallyBooked
+ isPartiallyBooked
? timeSlot?.OnePcsPrice
: timeSlot?.SellPrice || 0}
@@ -6151,15 +6155,15 @@ const BsBookingitemCard = (props) => {
!CartOrderDetails?.some(
(selected) =>
selected.ProdId ===
- timeSlot.ProdId &&
+ timeSlot.ProdId &&
selected.InwardDtlId ===
- timeSlot.InwardDtlId &&
+ timeSlot.InwardDtlId &&
selected.VariantAvailableFrom ===
- timeSlot.VariantAvailableFrom &&
+ timeSlot.VariantAvailableFrom &&
selected.VariantAvailableTo ===
- timeSlot.VariantAvailableTo &&
+ timeSlot.VariantAvailableTo &&
selected.BookedDate ===
- timeSlot.BookedDate
+ timeSlot.BookedDate
)
}
icon={
@@ -6220,30 +6224,29 @@ const BsBookingitemCard = (props) => {
/>
)}
- {
- (timeSlot?.SlotStatus ===
- 'Partially Booked' ||
- timeSlot?.SlotStatus ===
+ {(timeSlot?.SlotStatus ===
+ 'Partially Booked' ||
+ timeSlot?.SlotStatus ===
'Booked') && (
-
{
- e.stopPropagation();
- handleBookedDetails({
- ...timeSlot,
- ProdName:
- product
- ?.ProductDetail?.[0]
- ?.ProdName,
- ProdSubCatName:
- product?.ProdSubCatName,
- });
- }}
- >
-
- {timeSlot?.SlotStatus}
-
-
- )}
+
{
+ e.stopPropagation();
+ handleBookedDetails({
+ ...timeSlot,
+ ProdName:
+ product
+ ?.ProductDetail?.[0]
+ ?.ProdName,
+ ProdSubCatName:
+ product?.ProdSubCatName,
+ });
+ }}
+ >
+
+ {timeSlot?.SlotStatus}
+
+
+ )}
);
})}
@@ -6410,7 +6413,7 @@ const BsBookingitemCard = (props) => {
{customer.CustMobile || 'N/A'}
{customer?.CustBookDetails?.length >
- 1 ? (
+ 1 ? (
@@ -6421,7 +6424,7 @@ const BsBookingitemCard = (props) => {
{customer.CustBookDetails.length})
) : customer?.CustBookDetails
- ?.length === 1 ? (
+ ?.length === 1 ? (
<>
{
{booking.CreatedDate
? dayjs(booking.CreatedDate).format(
- 'DD MMM YYYY hh:mm A'
- )
+ 'DD MMM YYYY hh:mm A'
+ )
: 'N/A'}
{booking.StartTime
? dayjs(booking.StartTime).format(
- 'hh:mm A'
- )
+ 'hh:mm A'
+ )
: '-'}
{booking.EndTime
? dayjs(booking.EndTime).format(
- 'hh:mm A'
- )
+ 'hh:mm A'
+ )
: '-'}
diff --git a/src/Pages/BookingScreen/Components/BSItemCards/RemoveFromCartFunction.jsx b/src/Pages/BookingScreen/Components/BSItemCards/RemoveFromCartFunction.jsx
index cabd0b2..d0150e2 100644
--- a/src/Pages/BookingScreen/Components/BSItemCards/RemoveFromCartFunction.jsx
+++ b/src/Pages/BookingScreen/Components/BSItemCards/RemoveFromCartFunction.jsx
@@ -223,9 +223,9 @@ export const useRemoveFromCart = () => {
AppId: AppId,
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
await dispatch(getSelectedFavItems(data)).unwrap();
@@ -237,9 +237,9 @@ export const useRemoveFromCart = () => {
ProdSubCat: useSelector((state) => state.BookingData.ProductSubCategorie),
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
@@ -250,9 +250,9 @@ export const useRemoveFromCart = () => {
prodCat: useSelector((state) => state.BookingData.ProductCategorie),
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
@@ -345,26 +345,26 @@ export const useRemoveFromCart = () => {
console.log('isItemInCart', isItemInCart);
if (isItemInCart?.OrderQty > 1) {
const UpdatedCartItem =
- // if the item is already in the cart, increase the quantity of the item
- {
- ...isItemInCart,
- OrderQty: isItemInCart?.OrderQty - 1,
- TotalAmt: (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
- TaxAmt: (
- ((isItemInCart?.OrderQty - 1) *
- isItemInCart?.OrderRate *
- isItemInCart?.TaxPercentage) /
- (100 + isItemInCart?.TaxPercentage)
- ).toFixed(2),
- WithoutTaxRate:
- (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
- (
+ // if the item is already in the cart, increase the quantity of the item
+ {
+ ...isItemInCart,
+ OrderQty: isItemInCart?.OrderQty - 1,
+ TotalAmt: (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
+ TaxAmt: (
((isItemInCart?.OrderQty - 1) *
isItemInCart?.OrderRate *
isItemInCart?.TaxPercentage) /
(100 + isItemInCart?.TaxPercentage)
).toFixed(2),
- };
+ WithoutTaxRate:
+ (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
+ (
+ ((isItemInCart?.OrderQty - 1) *
+ isItemInCart?.OrderRate *
+ isItemInCart?.TaxPercentage) /
+ (100 + isItemInCart?.TaxPercentage)
+ ).toFixed(2),
+ };
const UpdatedcardData = [UpdatedCartItem, ...UpdatedData];
if (OfferCheckedInSetup && preferenceOffer) {
diff --git a/src/Pages/BookingScreen/Components/BSNavbar/BSNavBarUserInfo.jsx b/src/Pages/BookingScreen/Components/BSNavbar/BSNavBarUserInfo.jsx
index a0b2f90..c7a2d04 100644
--- a/src/Pages/BookingScreen/Components/BSNavbar/BSNavBarUserInfo.jsx
+++ b/src/Pages/BookingScreen/Components/BSNavbar/BSNavBarUserInfo.jsx
@@ -1,15 +1,16 @@
-import React from 'react';
+import React, { lazy, Suspense } from 'react';
import { MdEdit } from 'react-icons/md';
import { FaUserLarge } from 'react-icons/fa6';
import { BiSolidPhoneCall } from 'react-icons/bi';
import { PiSignOutLight } from 'react-icons/pi';
import user from '../../../../Images/dashboard/user.jpg';
import { clearSession, getSession } from '../../../../Services/Others';
-import UserRelieveManager from '../../Template/RealivingUser';
import { GlobalCompBranchData } from '../../../../Features/BrachLogin/BranchLogin';
import { userDataByUserId } from '../../../../Features/UserAccount/userData';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
+const UserRelieveManager = lazy(() => import('../../Template/RealivingUser'));
+// Scss
import "../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar1.scss"
const subDirectory = import.meta.env.ENV_BASE_URL;
@@ -37,65 +38,67 @@ const BSNavBarUserInfo = ({
navigate(`${subDirectory}app-page/branch-login`);
};
return (
-
-
- {CompBranchData?.length > 1 && (
-
- )}
-
-
- {/* {UserType != 'Employee' && */}
-
- {/* } */}
-
-
-
{
- e.target.onerror = null;
- e.target.src = user;
- }}
- />
-
-
{userProfileData?.UserName || 'Name'}
-
Loading…
}>
+
+
+ {CompBranchData?.length > 1 && (
+
+ )}
+
+
- ({UserType})
+ {/* {UserType != 'Employee' && */}
+
+ {/* } */}
+
+
+
{
+ e.target.onerror = null;
+ e.target.src = user;
+ }}
+ />
+
+
{userProfileData?.UserName || 'Name'}
+
+ ({UserType})
+
+
+
+ {' '}
+ {userProfileData?.MobileNo || 'Number'}
+
+
+ Sign Out
-
- {' '}
- {userProfileData?.MobileNo || 'Number'}
-
-
- Sign Out
-
-
+
);
};
diff --git a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar1.jsx b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar1.jsx
index 9ff6275..603cd61 100644
--- a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar1.jsx
+++ b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar1.jsx
@@ -1,16 +1,20 @@
-import React, { useCallback, useEffect, useRef, useState } from 'react';
+import React, {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ lazy,
+ Suspense,
+} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
-import { Badge, Button, Popconfirm, Popover, Tooltip } from 'antd';
+import { Badge, Popconfirm, Popover, Tooltip } from 'antd';
import {
- FeatureAddon,
GlobalBookingType,
GlobalBookingTypeBoth,
PreferenceData,
- changeCombosearch,
GlobalCombosearch,
getPreferenceData,
- Comboget,
GlobalOrderCardDetails,
changeEstimateBooking,
GlobalOrderStatus,
@@ -31,46 +35,8 @@ import {
changeComboRedirectionToDefaultLayoutForParking,
GlobalCommonPaymentOptions,
GlobalSelCustId,
-} from '../../../../Features/BookingScreen/BookingData/BookingData';
-import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
-import BSNavBarPrinter from '../UtillComponents/BSNavBarPrinter';
-import BSNavBarHand from '../UtillComponents/BSNavBarHand';
-import BSNavBarTable from '../UtillComponents/BSNavBarTable';
-import BSNavBarHandbag from '../UtillComponents/BSNavBarHandbag';
-import BSNavBarOffer from '../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx';
-import BSNavBarAddons from '../UtillComponents/BSNavBarAddons';
-import BSNavBarAddUser from '../UtillComponents/BSNavBarAddUser';
-import BSNavBarQuickAdd from '../UtillComponents/BSNavBarQuickAdd';
-import BSNavBarSearch from '../UtillComponents/BSNavBarSearch';
-import BSNavBarWeightScale from '../UtillComponents/BSNavBarWeightScale';
-import BSNavBarFavItems from '../UtillComponents/BSNavBarFavItems';
-import BSNavBarEstimate from '../UtillComponents/BSNavBarEst.jsx';
-import BSNavBarPreOrder from '../../Components/UtillComponents/BSNavBarPreOrder.jsx';
-import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar1.scss';
-import {
- getSession,
- clearSession,
- sessionStore,
-} from '../../../../Services/Others';
-import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities';
-import BSCustomerSelect from '../UtillComponents/BSSelectCustomer.jsx';
-import PozoHomeIcon from '../UtillComponents/Pozo retail icons/PozoHomeIcon';
-import PozoUserIcon from '../UtillComponents/Pozo retail icons/PozoUserIcon';
-import TimerClock from '../BSCombo/BSTimer.jsx';
-import {
- ApplicationPreferences,
- GenerateLogout,
- GlobalCompBranchData,
- getCompBranchData,
-} from '../../../../Features/BrachLogin/BranchLogin.js';
-import BSPrinterSetting from '../UtillComponents/BSPrinterSetting.jsx';
-import { isMobile } from 'react-device-detect';
-import { FaDisplay } from 'react-icons/fa6';
-import BSNavBarComboSearch from '../UtillComponents/BSNavBarComboSearch.jsx';
-import {
- setCustomerDisplayWindow,
- closeCustomerDisplayWindow,
-} from '../../../../Features/customerDisplayWindow/customerDisplayWindow';
+} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
+// js Files
import {
GlobalPreOrderPendingCount,
PreOrderGet,
@@ -79,49 +45,125 @@ import {
changePreOrderAdditem,
changepreOrderList,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
+import {
+ ApplicationPreferences,
+ GenerateLogout,
+ GlobalCompBranchData,
+ getCompBranchData,
+} from '../../../../Features/BrachLogin/BranchLogin.js';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
-import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
-import PaymentFailedSales from '../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx';
-import PozoComboProductIcon from '../UtillComponents/Pozo retail icons/PozoComboProductIcon.jsx';
-import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
-import PozoPaymentFailesIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
-import PozoMenuIcon from '../UtillComponents/Pozo retail icons/PozoMenuIcon.jsx';
-import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { Global_OfferStatus } from '../../../../Features/Offer/Offer.js';
import {
- getPrintSelectionComponentData,
getTemplate,
getTemplateData,
StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
-import { IoMdClose } from 'react-icons/io';
import { GlobalBookingStatus } from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
import { getEmpAccess } from '../../../../Features/AppPage/CenterPage.js';
-import { useAuth } from '../../../../AuthContext.jsx';
-import BSNavBarDragItems from '../UtillComponents/BSNavBarDragItems.jsx';
import {
getUserProfile,
userDataByUserId,
} from '../../../../Features/UserAccount/userData.js';
-import { FaUserLarge } from 'react-icons/fa6';
-import { BiSolidPhoneCall } from 'react-icons/bi';
-import { PiSignOutLight } from 'react-icons/pi';
-import PozoSwapIcon from '../UtillComponents/Pozo retail icons/PozoSwapIcon.jsx';
-import { MdEdit } from 'react-icons/md';
+import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
+import { clearSession, sessionStore } from '../../../../Services/Others.js';
+import { setCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
+import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';
+
+// Jsx Files
+const BSNavBarOffer = lazy(
+ () => import('../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx')
+);
+
+const BSNavBarPreOrder = lazy(
+ () => import('../../Components/UtillComponents/BSNavBarPreOrder.jsx')
+);
+const BSNavBarEstimate = lazy(
+ () => import('../UtillComponents/BSNavBarEst.jsx')
+);
+const BSCustomerSelect = lazy(
+ () => import('../UtillComponents/BSSelectCustomer.jsx')
+);
+const TimerClock = lazy(() => import('../BSCombo/BSTimer.jsx'));
+const BSPrinterSetting = lazy(
+ () => import('../UtillComponents/BSPrinterSetting.jsx')
+);
+const BSNavBarComboSearch = lazy(
+ () => import('../UtillComponents/BSNavBarComboSearch.jsx')
+);
+const PaymentFailedSales = lazy(
+ () => import('../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx')
+);
+const BSNavBarWholeSale = lazy(
+ () => import('../UtillComponents/BSNavBarWholeSale.jsx')
+);
+const BSScanTemplate = lazy(
+ () => import('../UtillComponents/BSScanTemplate.jsx')
+);
+const VerfiedProducts = lazy(
+ () => import('./verfiedProduct/VerfiedProducts.jsx')
+);
+const BSMembership = lazy(() => import('../UtillComponents/BSMembership.jsx'));
+const BranchName = lazy(() => import('../../Template/BranchName.jsx'));
+const MultipleSearch = lazy(
+ () => import('../UtillComponents/MultipleSearch.jsx')
+);
+const BSNavBarDragItems = lazy(
+ () => import('../UtillComponents/BSNavBarDragItems.jsx')
+);
+const UserRelieveManager = lazy(
+ () => import('../../Template/RealivingUser.jsx')
+);
+const FeaturesFunctionalities = lazy(
+ () => import('../BookingFunctionality/FeaturesFunctionalities.jsx')
+);
+
+import { useAuth } from '../../../../AuthContext.jsx';
+const BSNavBarAddons = lazy(
+ () => import('../UtillComponents/BSNavBarAddons.jsx')
+);
+
+const BSNavBarQuickAdd = lazy(
+ () => import('../UtillComponents/BSNavBarQuickAdd.jsx')
+);
+const BSNavBarAddUser = lazy(
+ () => import('../UtillComponents/BSNavBarAddUser.jsx')
+);
+const BSNavBarSearch = lazy(
+ () => import('../UtillComponents/BSNavBarSearch.jsx')
+);
+
+const BSNavBarWeightScale = lazy(
+ () => import('../UtillComponents/BSNavBarWeightScale.jsx')
+);
+const BSNavBarFavItems = lazy(
+ () => import('../UtillComponents/BSNavBarFavItems.jsx')
+);
+const BSNavBarHand = lazy(() => import('../UtillComponents/BSNavBarHand.jsx'));
+const BSNavBarTable = lazy(
+ () => import('../UtillComponents/BSNavBarTable.jsx')
+);
+const BSNavBarHandbag = lazy(
+ () => import('../UtillComponents/BSNavBarHandbag.jsx')
+);
+
+// Icon Files
+
+import PozoHomeIcon from '../UtillComponents/Pozo retail icons/PozoHomeIcon';
+import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
+import PozoUserIcon from '../UtillComponents/Pozo retail icons/PozoUserIcon';
+import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
+import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
+import PozoPaymentFailesIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
+import PozoMenuIcon from '../UtillComponents/Pozo retail icons/PozoMenuIcon.jsx';
+
+import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
+import { IoMdClose } from 'react-icons/io';
import { CgSearchLoading } from 'react-icons/cg';
-import UserRelieveManager from '../../Template/RealivingUser.jsx';
-import user from '../../../../Images/dashboard/user.jpg';
import BSNavBarUserInfo from './BSNavBarUserInfo';
import { FaParking } from 'react-icons/fa';
-import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
-import BSNavBarWholeSale from '../UtillComponents/BSNavBarWholeSale.jsx';
-import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';
-import BSScanTemplate from '../UtillComponents/BSScanTemplate.jsx';
-import VerfiedProducts from './verfiedProduct/VerfiedProducts.jsx';
-import BSMembership from '../UtillComponents/BSMembership.jsx';
-import BranchName from '../../Template/BranchName.jsx';
-import MultipleSearch from '../UtillComponents/MultipleSearch.jsx';
+import { isMobile } from 'react-device-detect';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
+import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar1.scss';
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;
@@ -221,17 +263,28 @@ const BSNavbar1 = (props) => {
const comboRedirectionToDefaultLayoutForParking = useSelector(
GlobalComboRedirectionToDefaultLayoutForParking
);
- const CartOrderDetails = useSelector(GlobalOrderCardDetails);
+
const divRef = useRef(null);
const handleClickOutside = (event) => {
if (divRef.current && !divRef.current.contains(event.target)) {
setAccIsOpen(false);
}
};
+ useEffect(() => {
+ if (!FeatureAddonData?.FeatureDtls?.length) return;
+
+ const preorderFeature = FeatureAddonData.FeatureDtls.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ );
+
+ if (preorderFeature) {
+ BadgePendingApi();
+ }
+ }, [FeatureAddonData]);
useEffect(() => {
handleOtherData();
- BadgePendingApi();
+
// if (UserType === "Employee") {
// fetchApi()
// }
@@ -558,433 +611,457 @@ const BSNavbar1 = (props) => {
};
return (
-
}>
+
-
-
- {(addcustomer || hold) && (
-
- )}
-
-
-
-
+
+
+
+ {(addcustomer || hold) && (
+
+ )}
+
+
+
+
+
+
+ {OtherServiceStatus && (
+
+ )}
- {OtherServiceStatus && (
-
- )}
-
+
+ {/* Multiple search */}
+
+
+ setMultiple(true)} />
+
+
-
- {/* Multiple search */}
-
-
- setMultiple(true)} />
-
-
-
- {!OtherServicesglobal && (
- <>
- {navbarOptions?.map((item) => (
- <>
- {item?.OptionName == 'Search' &&
- Comboglobal === false &&
- !sportsAppPreference && (
-
-
-
- )}
- >
- ))}
- {Comboglobal === true && (
-
-
-
- )}
- >
- )}
-
-
- {!OtherServicesglobal && (
- <>
- {OpenFailData && (
-
- )}
- >
- )}
-
- {navbarOptions?.map((item) => (
- <>
+ {!OtherServicesglobal && (
<>
- {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
-
-
-
-
-
+ {navbarOptions?.map((item) => (
+ <>
+ {item?.OptionName == 'Search' &&
+ Comboglobal === false &&
+ !sportsAppPreference && (
+
+
+
+ )}
+ >
+ ))}
+ {Comboglobal === true && (
+
+
+
)}
>
- {!OtherServicesglobal && (
- <>
- {item?.OptionName == 'Hold' &&
- OrderType != 'Failed' &&
- OrderType != 'Reorder' &&
- CheckBookingStatus != 'Close' &&
- isHoldEnable &&
- !addnewAccess && (
-
-
-
- )}
- {item?.OptionName == 'QuickAdd' && (
-
-
-
- )}
- {item?.OptionName == 'DineIn' &&
- dinePreference &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'DineIn'
- )?.SettingValue === 'Y' && (
-
-
-
- )}
- {item?.OptionName == 'TakeAway' && takeAwayPreference && (
-
-
-
- )}
+ )}
+
- {item?.OptionName === 'Offer' &&
- GlobEstBooking !== 'OvrAllEst' &&
- GlobEstBooking !== 'ParEst' &&
- GlobEstBooking === 'Sales' &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'Offer'
- )?.SettingValue === 'Y' && (
+ {!OtherServicesglobal && (
+ <>
+ {OpenFailData && (
+
+ )}
+ >
+ )}
+
+ {navbarOptions?.map((item) => (
+ <>
+ <>
+ {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
+
-
+
- )}
- {item?.OptionName == 'ExtraCharge' && (
- // CartOrderDetails?.length > 0 &&
-
-
-
- )}
- {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
- <>
-
-
- >
+
)}
>
- )}
- >
- ))}
-
- {!OtherServicesglobal && (
- <>
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'weight scale'
- ) && (
-
-
-
- )}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
-
-
-
- {
- openPreOrder();
+ {!OtherServicesglobal && (
+ <>
+ {item?.OptionName == 'Hold' &&
+ OrderType != 'Failed' &&
+ OrderType != 'Reorder' &&
+ CheckBookingStatus != 'Close' &&
+ isHoldEnable &&
+ !addnewAccess && (
+
+
+
+ )}
+ {item?.OptionName == 'QuickAdd' && (
+
-
-
-
- )}
- {preOrderOpen && (
-
- )}
- {sportsAppPreference &&
}
- {Estimation?.SettingValue === 'Y' &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- !OrderOfferStatus && (
+ >
+
+
+ )}
+ {item?.OptionName == 'DineIn' &&
+ dinePreference &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'DineIn'
+ )?.SettingValue === 'Y' && (
+
+
+
+ )}
+ {item?.OptionName == 'TakeAway' && takeAwayPreference && (
+
+
+
+ )}
+
+ {item?.OptionName === 'Offer' &&
+ GlobEstBooking !== 'OvrAllEst' &&
+ GlobEstBooking !== 'ParEst' &&
+ GlobEstBooking === 'Sales' &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'Offer'
+ )?.SettingValue === 'Y' && (
+
+
+
+ )}
+ {item?.OptionName == 'ExtraCharge' && (
+ // CartOrderDetails?.length > 0 &&
+
+
+
+ )}
+ {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
+ <>
+
+
+ >
+ )}
+ >
+ )}
+ >
+ ))}
+
+ {!OtherServicesglobal && (
+ <>
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() === 'weight scale'
+ ) && (
-
+
+
+ )}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ ) && (
+
+
+
+ {
+ openPreOrder();
+ }}
+ HandleClose={preOrderHandleclose}
+ />
+
+
+
+ )}
+ {preOrderOpen && (
+
+ )}
+ {sportsAppPreference &&
}
+ {Estimation?.SettingValue === 'Y' &&
+ BookingType !== 'Dine In' &&
+ !BookingTypeBoth &&
+ !OrderOfferStatus && (
+
+
+
+ )}
+ {/* mohan */}
+ {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
+
+ )}
+ {!OtherServicesglobal &&
+ ScanLayoutScreen?.SettingValue === 'Y' &&
}
+ {!sportsAppPreference && (
+
+
)}
- {/* mohan */}
- {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
-
- )}
- {!OtherServicesglobal &&
- ScanLayoutScreen?.SettingValue === 'Y' &&
}
- {!sportsAppPreference && (
-
+
- )}
-
-
-
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'customer display'
- ) && (
-
- {/*
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() === 'customer display'
+ ) && (
+
+ {/*
*/}
-
-
-
-
- )}
- {paymentfeataddon && (
-
- {/* { paymentFailedStatusFun() }}> */}
- {/* { paymentFailedStatusFun() }} /> */}
- {
- paymentFailedStatusFun();
- }}
- className="BSBillingNavBar1-AllIcons"
- style={{ width: '1.4rem', cursor: 'pointer' }}
- >
-
-
-
- )}
+
+
+
+
+ )}
+ {paymentfeataddon && (
+
+ {/* { paymentFailedStatusFun() }}> */}
+ {/* { paymentFailedStatusFun() }} /> */}
+ {
+ paymentFailedStatusFun();
+ }}
+ className="BSBillingNavBar1-AllIcons"
+ style={{ width: '1.4rem', cursor: 'pointer' }}
+ >
+
+
+
+ )}
- {VerifyTheProducts && (
-
-
-
-
-
- )}
- >
- )}
-
- {isMobile && (
-
-
+ {VerifyTheProducts && (
+
+
+
+
+
+ )}
+ >
+ )}
- )}
- {!OtherServicesglobal && (
- <>
-
-
-
- {formattedDate}
-
+ {isMobile && (
+
+
-
-
-
+ )}
+ {!OtherServicesglobal && (
+ <>
+
-
+
+
+
- {/* {isMobile && ( */}
- {/*
+ {/* {isMobile && ( */}
+ {/*
*/}
- {/* )} */}
+ {/* )} */}
- {/* Use BSNavBarUserInfo for the account menu */}
-
}
- Logout={Logout}
- />
- >
- )}
+ {/* Use BSNavBarUserInfo for the account menu */}
+
}
+ Logout={Logout}
+ />
+ >
+ )}
- {/* small screen nav bar */}
- {Navmenu && (
-
-
-
- {OtherServiceStatus && (
-
- )}
- {!OtherServicesglobal &&
- ScanLayoutScreen?.SettingValue === 'Y' &&
}
-
- {!OtherServicesglobal && (
- <>
- {OpenFailData && (
-
+ {/* small screen nav bar */}
+ {Navmenu && (
+
+
+
+ {OtherServiceStatus && (
+
+ )}
+ {!OtherServicesglobal &&
+ ScanLayoutScreen?.SettingValue === 'Y' && (
+
)}
- {/* {ComboDropDown?.length >= 1 && (
+
+ {!OtherServicesglobal && (
+ <>
+ {OpenFailData && (
+
+ )}
+ {/* {ComboDropDown?.length >= 1 && (
@@ -1005,40 +1082,40 @@ const BSNavbar1 = (props) => {
)} */}
- {navbarOptions?.map((item) => (
- <>
- {item?.OptionName == 'RePrint' &&
- !OtherServicesglobal && (
+ {navbarOptions?.map((item) => (
+ <>
+ {item?.OptionName == 'RePrint' &&
+ !OtherServicesglobal && (
+
+
+
+ )}
+ {item?.OptionName == 'Hold' &&
+ OrderType != 'Failed' &&
+ OrderType != 'Reorder' &&
+ CheckBookingStatus != 'Close' &&
+ isHoldEnable &&
+ !addnewAccess && (
+
+
+
+ )}
+ {item?.OptionName == 'QuickAdd' && (
-
+
)}
- {item?.OptionName == 'Hold' &&
- OrderType != 'Failed' &&
- OrderType != 'Reorder' &&
- CheckBookingStatus != 'Close' &&
- isHoldEnable &&
- !addnewAccess && (
-
-
-
- )}
- {item?.OptionName == 'QuickAdd' && (
-
-
-
- )}
- {/* {item?.OptionName == 'Quick Transfer' && (
+ {/* {item?.OptionName == 'Quick Transfer' && (
{
)} */}
- {item?.OptionName == 'DineIn' &&
- dinePreference &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'DineIn'
- )?.SettingValue === 'Y' && (
-
-
-
- )}
- {item?.OptionName == 'TakeAway' && (
-
-
-
- )}
-
- {item?.OptionName === 'Offer' &&
- GlobEstBooking !== 'OvrAllEst' &&
- GlobEstBooking !== 'ParEst' &&
- GlobEstBooking === 'Sales' &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'Offer'
- )?.SettingValue === 'Y' && (
+ {item?.OptionName == 'DineIn' &&
+ dinePreference &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'DineIn'
+ )?.SettingValue === 'Y' && (
+
+
+
+ )}
+ {item?.OptionName == 'TakeAway' && (
-
+
)}
- {item?.OptionName == 'ExtraCharge' && (
- // CartOrderDetails?.length > 0 &&
-
-
-
- )}
- {item?.OptionName == 'AddCustomer' && (
-
item.SettingIdName === 'Offer'
+ )?.SettingValue === 'Y' && (
-
-
+
- }
- trigger="click"
- placement="left"
- open={open}
- onOpenChange={handleOpenChange}
- >
-
-
- )}
- >
- ))}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'Weight Scale'
- ) && (
-
-
-
- )}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
-
-
-
- {
- openPreOrder('small-screen');
+ )}
+ {item?.OptionName == 'ExtraCharge' && (
+ // CartOrderDetails?.length > 0 &&
+
-
-
-
- )}
- {preOrderOpen && (
-
- )}
- {sportsAppPreference &&
}
- {Estimation?.SettingValue == 'Y' &&
- !OrderOfferStatus &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth && (
+ >
+
+
+ )}
+ {item?.OptionName == 'AddCustomer' && (
+
+
+
+
+ }
+ trigger="click"
+ placement="left"
+ open={open}
+ onOpenChange={handleOpenChange}
+ >
+
+
+ )}
+ >
+ ))}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() ===
+ 'Weight Scale'
+ ) && (
-
+
+
+ )}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ ) && (
+
+
+
+ {
+ openPreOrder('small-screen');
+ }}
+ />
+
+
+
+ )}
+ {preOrderOpen && (
+
+ )}
+ {sportsAppPreference &&
}
+ {Estimation?.SettingValue == 'Y' &&
+ !OrderOfferStatus &&
+ BookingType !== 'Dine In' &&
+ !BookingTypeBoth && (
+
+
+
+ )}
+ {SalesMode?.SettingValue === 'Y' &&
+ !OtherServicesglobal &&
}
+
+ {!sportsAppPreference && (
+
+
)}
- {SalesMode?.SettingValue === 'Y' &&
- !OtherServicesglobal &&
}
- {!sportsAppPreference && (
-
+
- )}
-
-
-
-
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() ===
- 'customer display'
- ) && (
-
- {/*
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() ===
+ 'customer display'
+ ) && (
+
+ {/*
*/}
-
-
-
-
- )}
+
+
+
+
+ )}
- {VerifyTheProducts &&
}
+ {VerifyTheProducts &&
}
- {paymentfeataddon && (
-
- {/* PozoPaymentFailesIcon */}
- {
- paymentFailedStatusFun();
- }}
- style={{ width: '1.4rem', cursor: 'pointer' }}
+ {paymentfeataddon && (
+
-
-
-
- )}
- >
- )}
+ {/* PozoPaymentFailesIcon */}
+
{
+ paymentFailedStatusFun();
+ }}
+ style={{ width: '1.4rem', cursor: 'pointer' }}
+ >
+
+
+
+ )}
+ >
+ )}
+
-
- )}
-
-
- {Navmenu ? (
-
- ) : (
-
- )}
-
+ )}
+
+
+ {Navmenu ? (
+
+ ) : (
+
+ )}
+
-
setMultiple(false)}
- destroyOnClose={true}
- children={
- <>
-
- >
- }
- />
-
+ setMultiple(false)}
+ destroyOnClose={true}
+ children={
+ <>
+
+ >
+ }
+ />
+
+
);
};
export default BSNavbar1;
diff --git a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar2.jsx b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar2.jsx
index 2fbb0f7..d8f3e6a 100644
--- a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar2.jsx
+++ b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar2.jsx
@@ -1,4 +1,11 @@
-import React, { useEffect, useRef, useState, useCallback } from 'react';
+import React, {
+ useEffect,
+ useRef,
+ useState,
+ useCallback,
+ lazy,
+ Suspense,
+} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { AiFillHome } from 'react-icons/ai';
@@ -8,14 +15,10 @@ import {
getEditFavItems,
PreferenceData,
getPreferenceData,
- GlobalCustId,
- GlobalOrderCardDetails,
GlobalBookingType,
GlobalBookingTypeBoth,
- FeatureAddon,
changeCombosearch,
GlobalCombosearch,
- Comboget,
changeEstimateBooking,
changeSelectedOption,
changeSelectedCustId,
@@ -37,23 +40,30 @@ import {
GlobalCommonPaymentOptions,
GlobalSelCustId,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
-import BSNavBarSearch from '../UtillComponents/BSNavBarSearch';
-import BSNavBarPrinter from '../UtillComponents/BSNavBarPrinter';
-import BSNavBarHand from '../UtillComponents/BSNavBarHand';
-import BSNavBarTable from '../UtillComponents/BSNavBarTable';
-import BSNavBarHandbag from '../UtillComponents/BSNavBarHandbag';
-import BSNavBarOffer from '../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx';
-import BSNavBarAddons from '../UtillComponents/BSNavBarAddons';
-import BSNavBarAddUser from '../UtillComponents/BSNavBarAddUser';
-import BSNavBarQuickAdd from '../UtillComponents/BSNavBarQuickAdd';
+
+const BSNavBarSearch = lazy(() => import('../UtillComponents/BSNavBarSearch'));
+
+const BSNavBarHand = lazy(() => import('../UtillComponents/BSNavBarHand'));
+
+const BSNavBarHandbag = lazy(
+ () => import('../UtillComponents/BSNavBarHandbag')
+);
+
+const BSNavBarAddons = lazy(() => import('../UtillComponents/BSNavBarAddons'));
+
+const BSNavBarAddUser = lazy(
+ () => import('../UtillComponents/BSNavBarAddUser')
+);
+
+const BSNavBarQuickAdd = lazy(
+ () => import('../UtillComponents/BSNavBarQuickAdd')
+);
+
+const BSNavBarFavItems = lazy(
+ () => import('../UtillComponents/BSNavBarFavItems')
+);
import BSNavBarWeightScale from '../UtillComponents/BSNavBarWeightScale';
-import BSNavBarFavItems from '../UtillComponents/BSNavBarFavItems';
-import BSNavBarPreOrder from '../../Components/UtillComponents/BSNavBarPreOrder.jsx';
-import BSMembership from '../UtillComponents/BSMembership.jsx';
-import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar2.scss';
import { clearSession, sessionStore } from '../../../../Services/Others';
-import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities.jsx';
-import BSCustomerSelect from '../UtillComponents/BSSelectCustomer.jsx';
import PozoUserIcon from '../UtillComponents/Pozo retail icons/PozoUserIcon.jsx';
import {
ApplicationPreferences,
@@ -73,48 +83,61 @@ import {
changePreOrderAdditem,
changepreOrderList,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
+import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
import PaymentFailedSales from '../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx';
-import PozoComboProductIcon from '../UtillComponents/Pozo retail icons/PozoComboProductIcon.jsx';
import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
import PozoPaymentFailesIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { Global_OfferStatus } from '../../../../Features/Offer/Offer.js';
-import { IoMdClose } from 'react-icons/io';
import { isMobile } from 'react-device-detect';
+import { useAuth } from '../../../../AuthContext.jsx';
import {
- getPrintSelectionComponentData,
getTemplate,
getTemplateData,
StoredSessionData,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
+import BSNavBarWholeSale from '../UtillComponents/BSNavBarWholeSale.jsx';
import { GlobalBookingStatus } from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
-import { getEmpAccess } from '../../../../Features/AppPage/CenterPage.js';
-import { useAuth } from '../../../../AuthContext.jsx';
-import { TfiHandDrag } from 'react-icons/tfi';
-import BSNavBarDragItems from '../UtillComponents/BSNavBarDragItems.jsx';
-import { PiSignOutLight } from 'react-icons/pi';
import {
getUserProfile,
userDataByUserId,
} from '../../../../Features/UserAccount/userData.js';
-import { FaUserLarge } from 'react-icons/fa6';
-import { BiSolidPhoneCall } from 'react-icons/bi';
-import PozoSwapIcon from '../UtillComponents/Pozo retail icons/PozoSwapIcon.jsx';
import { CgSearchLoading } from 'react-icons/cg';
-import UserRelieveManager from '../../Template/RealivingUser.jsx';
import { FaParking } from 'react-icons/fa';
import BSNavBarUserInfo from './BSNavBarUserInfo';
import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
-import BSNavBarWholeSale from '../UtillComponents/BSNavBarWholeSale.jsx';
import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';
import BSScanTemplate from '../UtillComponents/BSScanTemplate.jsx';
-import VerfiedProducts from './verfiedProduct/VerfiedProducts';
-import BranchName from '../../Template/BranchName.jsx';
import MultipleSearch from '../UtillComponents/MultipleSearch.jsx';
-import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
+// Jsx Files
+const VerfiedProducts = lazy(() => import('./verfiedProduct/VerfiedProducts'));
+const UserRelieveManager = lazy(
+ () => import('../../Template/RealivingUser.jsx')
+);
+const BranchName = lazy(() => import('../../Template/BranchName.jsx'));
+const BSNavBarOffer = lazy(
+ () => import('../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx')
+);
+const BSNavBarDragItems = lazy(
+ () => import('../UtillComponents/BSNavBarDragItems.jsx')
+);
+const BSNavBarTable = lazy(() => import('../UtillComponents/BSNavBarTable'));
+const BSMembership = lazy(() => import('../UtillComponents/BSMembership.jsx'));
+const BSNavBarPreOrder = lazy(
+ () => import('../../Components/UtillComponents/BSNavBarPreOrder.jsx')
+);
+const FeaturesFunctionalities = lazy(
+ () => import('../BookingFunctionality/FeaturesFunctionalities.jsx')
+);
+const BSCustomerSelect = lazy(
+ () => import('../UtillComponents/BSSelectCustomer.jsx')
+);
+// Scss
+import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar2.scss';
+
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;
@@ -222,6 +245,18 @@ const BSNavbar2 = () => {
(item) =>
item.SettingIdName === 'VerifyProduct' && item?.SettingValue === 'Y'
);
+
+ useEffect(() => {
+ if (!FeatureAddonData?.FeatureDtls?.length) return;
+
+ const preorderFeature = FeatureAddonData.FeatureDtls.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ );
+
+ if (preorderFeature) {
+ BadgePendingApi();
+ }
+ }, [FeatureAddonData]);
useEffect(() => {
handleOtherData();
BadgePendingApi();
@@ -258,7 +293,7 @@ const BSNavbar2 = () => {
setisisHoldEnable(filterPayCounter?.[0]?.ModeDetails?.length > 0);
};
useEffect(() => {
- fetchEditFavItems();
+ // fetchEditFavItems();
dispatch(
getPreferenceData({ CompId: CompId, AppId: AppId, BranchId: BranchId })
);
@@ -294,27 +329,7 @@ const BSNavbar2 = () => {
setaddnewAccess(!hasAccess);
}, [empData, SAAccessCommonMaster, UserType]);
- const fetchApi = async () => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- EmpId: UserId,
- };
- let response = await dispatch(getEmpAccess(data)).unwrap();
- let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
- (item) => item.ConfigName === 'Sales'
- );
- setEmpData(datas?.[0]);
- };
- const fetchEditFavItems = async () => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- };
- await dispatch(getEditFavItems(data)).unwrap();
- };
+
const fetchBranchData = async () => {
if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
await dispatch(
@@ -341,11 +356,6 @@ const BSNavbar2 = () => {
}
};
const getFeatureAddonData = async () => {
- // let featureAddon = await dispatch(
- // FeatureAddon({ AppId: AppId, UserId: UserId })
- // ).unwrap();
- // if (featureAddon?.data?.statusCode === 1) {
- // setFeatureAddonData(featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]);
const hasPaymentFeatures = FeatureAddonData?.FeatureDtls.some(
(item) =>
item.FeatureAddonName === 'Payment Gateway' ||
@@ -575,425 +585,407 @@ const BSNavbar2 = () => {
};
return (
-
-
-
{' '}
-
-
-
- {(addcustomer || hold) && (
-
- )}
- {OtherServiceStatus && (
-
}>
+
+
- {/* Multiple search */}
-
-
- setMultiple(true)} />
-
-
-
- {searchOption &&
- !Comboglobal &&
- !OtherServicesglobal &&
- !sportsAppPreference && (
+ {(addcustomer || hold) && (
+
+ )}
+ {OtherServiceStatus && (
)}
-
- {Comboglobal === true && !OtherServicesglobal && (
-
- )}
-
- {/* {ComboDropDown?.length >= 1 && !OtherServicesglobal && (
-
-
+
+ {/* Multiple search */}
+
+
+ setMultiple(true)} />
+
+
+
+ {searchOption &&
+ !Comboglobal &&
+ !OtherServicesglobal &&
+ !sportsAppPreference && (
-
-
- )} */}
- {OpenFailData && (
-
- )}
+ )}
- {navbarOptions?.map((item) => (
- <>
-
-
-
- <>
- {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
-
-
-
-
-
- )}
- >
+ {Comboglobal === true && !OtherServicesglobal && (
+
+ )}
+ {OpenFailData && (
+
+ )}
- {!OtherServicesglobal && (
+ {navbarOptions?.map((item) => (
+ <>
+
+
+
<>
- {item?.OptionName == 'Hold' &&
- OrderType != 'Failed' &&
- OrderType != 'Reorder' &&
- CheckBookingStatus != 'Close' &&
- isHoldEnable &&
- !addnewAccess && (
-
-
-
- )}
-
- {item?.OptionName == 'QuickAdd' && (
-
-
-
- )}
- >
- )}
-
-
-
- {!OtherServicesglobal && (
- <>
- {item?.OptionName == 'QuickAdd' && dinePreference && (
-
- {' '}
-
{' '}
-
- )}
-
- {(dinePreference || takeAwayPreference) && (
-
-
- {item?.OptionName == 'DineIn' &&
- dinePreference &&
- !BookingTypeBoth &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'DineIn'
- )?.SettingValue === 'Y' && (
-
-
-
- )}
- {item?.OptionName == 'TakeAway' &&
- takeAwayPreference && (
+ {item?.OptionName == 'RePrint' &&
+ !OtherServicesglobal && (
+
-
+
+
+
+ )}
+ >
+
+ {!OtherServicesglobal && (
+ <>
+ {item?.OptionName == 'Hold' &&
+ OrderType != 'Failed' &&
+ OrderType != 'Reorder' &&
+ CheckBookingStatus != 'Close' &&
+ isHoldEnable &&
+ !addnewAccess && (
+
+
)}
+
+ {item?.OptionName == 'QuickAdd' && (
+
+
+
+ )}
+ >
+ )}
+
+
+
+ {!OtherServicesglobal && (
+ <>
+ {item?.OptionName == 'QuickAdd' && dinePreference && (
+
+ {' '}
+
{' '}
-
- )}
+ )}
- {item?.OptionName == 'TakeAway' && takeAwayPreference && (
-
- {' '}
-
{' '}
-
- )}
+ {(dinePreference || takeAwayPreference) && (
+
+
+ {item?.OptionName == 'DineIn' &&
+ dinePreference &&
+ !BookingTypeBoth &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'DineIn'
+ )?.SettingValue === 'Y' && (
+
+
+
+ )}
+ {item?.OptionName == 'TakeAway' &&
+ takeAwayPreference && (
+
+
+
+ )}
+
+
+ )}
-
- {item?.OptionName === 'Offer' &&
- GlobEstBooking !== 'OvrAllEst' &&
- GlobEstBooking !== 'ParEst' &&
- GlobEstBooking === 'Sales' &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'Offer'
- )?.SettingValue === 'Y' && (
+ {item?.OptionName == 'TakeAway' && takeAwayPreference && (
+
+ {' '}
+
{' '}
+
+ )}
+
+
+ {item?.OptionName === 'Offer' &&
+ GlobEstBooking !== 'OvrAllEst' &&
+ GlobEstBooking !== 'ParEst' &&
+ GlobEstBooking === 'Sales' &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'Offer'
+ )?.SettingValue === 'Y' && (
+
+
+
+ )}
+ {item?.OptionName == 'ExtraCharge' && (
-
+
)}
- {item?.OptionName == 'ExtraCharge' && (
-
-
-
- )}
- {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
- <>
-
-
-
-
- >
- )}
-
- >
- )}
-
- >
- ))}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'weight scale'
- ) &&
- !OtherServicesglobal && (
-
-
-
- )}
-
- {!OtherServicesglobal && (
- <>
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
+ {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
+ <>
+
+
+
+
+ >
+ )}
+
+ >
+ )}
+
+ >
+ ))}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'weight scale'
+ ) &&
+ !OtherServicesglobal && (
-
-
- {
- openPreOrder();
- }}
- HandleClose={preOrderHandleclose}
- />
-
-
+
)}
- >
- )}
- {preOrderOpen && (
-
-
-
- )}
- {sportsAppPreference &&
}
- {!OtherServicesglobal && (
- <>
- {Estimation?.SettingValue === 'Y' &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- !OrderOfferStatus && (
+
+ {!OtherServicesglobal && (
+ <>
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ ) && (
+
+
+ {
+ openPreOrder();
+ }}
+ HandleClose={preOrderHandleclose}
+ />
+
+
+
+ )}
+ >
+ )}
+ {preOrderOpen && (
+
+
+
+ )}
+ {sportsAppPreference &&
}
+ {!OtherServicesglobal && (
+ <>
+ {Estimation?.SettingValue === 'Y' &&
+ BookingType !== 'Dine In' &&
+ !BookingTypeBoth &&
+ !OrderOfferStatus && (
+
+
+
+ )}
+ >
+ )}
+ {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
+
+ )}
+ {!OtherServicesglobal && ScanLayoutScreen?.SettingValue === 'Y' && (
+
+ )}
+
+ {!OtherServicesglobal && (
+ <>
+ {!sportsAppPreference && (
+
-
+
)}
- >
- )}
- {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
-
- )}
- {!OtherServicesglobal && ScanLayoutScreen?.SettingValue === 'Y' && (
-
- )}
-
- {!OtherServicesglobal && (
- <>
- {!sportsAppPreference && (
-
+
- )}
-
- {/* dispatch(Changedragging(!Isdragging))} style={{ color: Isdragging ? "green" : "#1292ee",fontSize:"25px" }} /> */}
+ >
+ )}
-
-
- >
- )}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() === 'customer display'
+ ) && (
+
+
+
+
+
+ )}
+ {VerifyTheProducts && (
+
+
+
+
+
+ )}
+ {paymentfeataddon && !OtherServicesglobal && (
+
+ {
+ paymentFailedStatusFun();
+ }}
+ className="BSBillingNavBar1-AllIcons"
+ style={{ width: '1.4rem', cursor: 'pointer' }}
+ >
+
+
+
+ )}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'customer display'
- ) && (
-
- {/*
-
-
*/}
-
-
-
-
- )}
- {VerifyTheProducts && (
-
+ {!OtherServicesglobal && (
-
+ }
+ Logout={Logout}
+ />
-
- )}
- {paymentfeataddon && !OtherServicesglobal && (
-
- {
- paymentFailedStatusFun();
- }}
- className="BSBillingNavBar1-AllIcons"
- style={{ width: '1.4rem', cursor: 'pointer' }}
- >
-
-
-
- )}
+ )}
+ {/* small screen nav bar */}
+ {Navmenu && (
+ <>
+
+
+ {OtherServiceStatus && (
+
+ )}
- {!OtherServicesglobal && (
-
- }
- Logout={Logout}
- />
-
- )}
- {/* small screen nav bar */}
- {Navmenu && (
- <>
-
-
- {OtherServiceStatus && (
-
- )}
-
- {OpenFailData && (
-
- )}
- {/* {ComboDropDown?.length >= 1 && !OtherServicesglobal && (
+ {OpenFailData && (
+
+ )}
+ {/* {ComboDropDown?.length >= 1 && !OtherServicesglobal && (
@@ -1014,31 +1006,32 @@ const BSNavbar2 = () => {
)} */}
- {navbarOptions?.map((item) => (
- <>
- {item?.OptionName == 'RePrint' && !OtherServicesglobal && (
-
-
-
- )}
- {!OtherServicesglobal && (
- <>
- {item?.OptionName == 'Hold' &&
- OrderType != 'Failed' &&
- OrderType != 'Reorder' &&
- CheckBookingStatus != 'Close' &&
- isHoldEnable &&
- !addnewAccess && (
-
-
-
- )}
- {/* {item?.OptionName == 'Quick Transfer' && (
+ {navbarOptions?.map((item) => (
+ <>
+ {item?.OptionName == 'RePrint' &&
+ !OtherServicesglobal && (
+
+
+
+ )}
+ {!OtherServicesglobal && (
+ <>
+ {item?.OptionName == 'Hold' &&
+ OrderType != 'Failed' &&
+ OrderType != 'Reorder' &&
+ CheckBookingStatus != 'Close' &&
+ isHoldEnable &&
+ !addnewAccess && (
+
+
+
+ )}
+ {/* {item?.OptionName == 'Quick Transfer' && (
{
)} */}
- {item?.OptionName == 'QuickAdd' && (
-
-
-
- )}
- {item?.OptionName == 'DineIn' &&
- dinePreference &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'DineIn'
- )?.SettingValue === 'Y' && (
-
-
-
- )}
- {item?.OptionName == 'TakeAway' && (
-
-
-
- )}
- {item?.OptionName === 'Offer' &&
- GlobEstBooking !== 'OvrAllEst' &&
- GlobEstBooking !== 'ParEst' &&
- GlobEstBooking === 'Sales' &&
- PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'Offer'
- )?.SettingValue === 'Y' && (
+ {item?.OptionName == 'QuickAdd' && (
-
+
)}
- {item?.OptionName == 'ExtraCharge' && (
-
-
-
- )}
-
- {item?.OptionName == 'AddCustomer' && (
-
item.SettingIdName === 'DineIn'
+ )?.SettingValue === 'Y' && (
-
-
+
- }
- trigger="click"
- placement="left"
- open={open}
- onOpenChange={handleOpenChange}
- >
-
-
- )}
- >
- )}
- >
- ))}
- {!OtherServicesglobal && (
- <>
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'Weight Scale'
- ) && (
-
-
-
- )}
- {!OtherServicesglobal && (
- <>
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
-
-
-
+
+ )}
+ {item?.OptionName === 'Offer' &&
+ GlobEstBooking !== 'OvrAllEst' &&
+ GlobEstBooking !== 'ParEst' &&
+ GlobEstBooking === 'Sales' &&
+ PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'Offer'
+ )?.SettingValue === 'Y' && (
+
-
{
- openPreOrder('small-screen');
+
+
+ )}
+ {item?.OptionName == 'ExtraCharge' && (
+
+
+
+ )}
+
+ {item?.OptionName == 'AddCustomer' && (
+
-
-
-
- )}
- >
- )}
- {preOrderOpen && (
-
- )}
- {sportsAppPreference &&
}
- {Estimation?.SettingValue === 'Y' &&
- !OrderOfferStatus &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth && (
+ >
+
+
+
+ }
+ trigger="click"
+ placement="left"
+ open={open}
+ onOpenChange={handleOpenChange}
+ >
+
+
+ )}
+ >
+ )}
+ >
+ ))}
+ {!OtherServicesglobal && (
+ <>
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() ===
+ 'Weight Scale'
+ ) && (
-
+
)}
- {SalesMode?.SettingValue === 'Y' &&
- !OtherServicesglobal &&
}
- {!OtherServicesglobal &&
- ScanLayoutScreen?.SettingValue === 'Y' && (
-
+ {!OtherServicesglobal && (
+ <>
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() ===
+ 'preorder'
+ ) && (
+
+
+
+ {
+ openPreOrder('small-screen');
+ }}
+ />
+
+
+
+ )}
+ >
+ )}
+ {preOrderOpen && (
+
+ )}
+ {sportsAppPreference &&
}
+ {Estimation?.SettingValue === 'Y' &&
+ !OrderOfferStatus &&
+ BookingType !== 'Dine In' &&
+ !BookingTypeBoth && (
+
+
+
+ )}
+ {SalesMode?.SettingValue === 'Y' &&
+ !OtherServicesglobal &&
}
+ {!OtherServicesglobal &&
+ ScanLayoutScreen?.SettingValue === 'Y' && (
+
+ )}
+ {!sportsAppPreference && (
+
+
+
)}
- {!sportsAppPreference && (
-
+
- )}
-
-
-
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() ===
- 'customer display'
- ) && (
-
- {/*
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() ===
+ 'customer display'
+ ) && (
+
+ {/*
*/}
-
+
+
+
+ )}
+ {VerifyTheProducts && (
+
-
-
-
- )}
- {VerifyTheProducts && (
-
-
-
-
-
- )}
- {paymentfeataddon && (
-
- {
- paymentFailedStatusFun();
- }}
- style={{ width: '1.4rem', cursor: 'pointer' }}
+
+
+
+
+ )}
+ {paymentfeataddon && (
+
-
-
-
- )}
- >
- )}
+
{
+ paymentFailedStatusFun();
+ }}
+ style={{ width: '1.4rem', cursor: 'pointer' }}
+ >
+
+
+
+ )}
+ >
+ )}
+
+ >
+ )}
+ {isMobile && (
+
+
- >
- )}
- {isMobile && (
-
-
-
- )}
- {!OtherServicesglobal && (
-
-
-
- )}
-
+ )}
+ {!OtherServicesglobal && (
+
+
+
+ )}
+
-
-
-
+
+
+
-
setMultiple(false)}
- destroyOnClose={true}
- children={
- <>
-
- >
- }
- />
-
+
setMultiple(false)}
+ destroyOnClose={true}
+ children={
+ <>
+
+ >
+ }
+ />
+
+
);
};
export default BSNavbar2;
diff --git a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar3.jsx b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar3.jsx
index 83709fd..e103151 100644
--- a/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar3.jsx
+++ b/src/Pages/BookingScreen/Components/BSNavbar/BSNavbar3.jsx
@@ -1,4 +1,12 @@
-import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
+import {
+ useState,
+ useEffect,
+ useRef,
+ useCallback,
+ useMemo,
+ lazy,
+ Suspense,
+} from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import {
@@ -38,7 +46,6 @@ import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar3.scss';
// UI Imports
import { Badge, Popconfirm, Tooltip } from 'antd';
import { AiFillHome } from 'react-icons/ai';
-import { GoClockFill } from 'react-icons/go';
import {
FaPlus,
FaHandPaper,
@@ -48,30 +55,23 @@ import {
FaParking,
} from 'react-icons/fa';
import { CiMenuBurger } from 'react-icons/ci';
-import { IoClose, IoCloseOutline } from 'react-icons/io5';
-import { FaCalendar } from 'react-icons/fa6';
+import { IoCloseOutline } from 'react-icons/io5';
import {
RiFullscreenExitFill,
RiFullscreenFill,
RiPrinterFill,
} from 'react-icons/ri';
import { GiShoppingBag } from 'react-icons/gi';
-import { PiSignOutFill } from 'react-icons/pi';
-import { TfiHandDrag } from 'react-icons/tfi';
-import { CgClose } from 'react-icons/cg';
-
-import { DropDowns } from '../../../../Components/Forms/DropDown';
-import PozoDineInIcon from '../UtillComponents/Pozo retail icons/PozoDineIn.jsx';
-import BSNavBarFavItems from '../UtillComponents/BSNavBarFavItems.jsx';
-import BSNavBarAddUser from '../UtillComponents/BSNavBarAddUser.jsx';
-import BSCustomerSelect from '../UtillComponents/BSSelectCustomer.jsx';
-import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities.jsx';
-import BSNavBarHand from '../UtillComponents/BSNavBarHand.jsx';
-import BSNavBarDragItems from '../UtillComponents/BSNavBarDragItems.jsx';
+const BSNavBarAddUser = lazy(
+ () => import('../UtillComponents/BSNavBarAddUser.jsx')
+);
+const BSCustomerSelect = lazy(
+ () => import('../UtillComponents/BSSelectCustomer.jsx')
+);
+const FeaturesFunctionalities = lazy(
+ () => import('../BookingFunctionality/FeaturesFunctionalities.jsx')
+);
import CustomerDisplayicon from '../UtillComponents/Pozo retail icons/PozoCustomerDisplayicon.jsx';
-
-import BSNavBarPrinter from '../UtillComponents/BSNavBarPrinter.jsx';
-import BSNavBarUserInfo from './BSNavBarUserInfo.jsx';
import {
getUserProfile,
userDataByUserId,
@@ -81,8 +81,6 @@ import {
getSession,
sessionStore,
} from '../../../../Services/Others.js';
-import UserRelieveManager from '../../Template/RealivingUser.jsx';
-import BSNavbarSearchStandard from '../UtillComponents/BSNavbarSearchStandard.jsx';
import {
getTemplate,
getTemplateData,
@@ -92,22 +90,12 @@ import {
CurrentTimeDisplay,
CurrentDateDisplay,
} from '../UtillComponents/CurrentDateTimeDisplay.jsx';
-import BSPrinterSetting from '../UtillComponents/BSPrinterSetting.jsx';
-import BSNavBarTable from '../UtillComponents/BSNavBarTable.jsx';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip.jsx';
import { isMobile } from 'react-device-detect';
import {
getCustomerDisplayWindow,
setCustomerDisplayWindow,
} from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
-import BSMobilePrintSettings from '../UtillComponents/BSMobilePrintSettings.jsx';
-import BSScanTemplate from '../UtillComponents/BSScanTemplate.jsx';
-import VerfiedProducts from './verfiedProduct/VerfiedProducts.jsx';
-import BSMembership from '../UtillComponents/BSMembership.jsx';
-import BranchName from '../../Template/BranchName.jsx';
-import BSNavBarAddons from '../UtillComponents/BSNavBarAddons.jsx';
-import BSNavBarOffer from '../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx';
-import BSNavBarQuickAdd from '../UtillComponents/BSNavBarQuickAdd.jsx';
import BSNavBarPreOrder from '../UtillComponents/BSNavBarPreOrder.jsx';
import {
changepreOrder,
@@ -126,6 +114,49 @@ import { CgSearchLoading } from 'react-icons/cg';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import MultipleSearch from '../UtillComponents/MultipleSearch.jsx';
+// Jsx Files
+const BSNavBarFavItems = lazy(
+ () => import('../UtillComponents/BSNavBarFavItems.jsx')
+);
+const BSNavBarHand = lazy(() => import('../UtillComponents/BSNavBarHand.jsx'));
+const BSNavBarDragItems = lazy(
+ () => import('../UtillComponents/BSNavBarDragItems.jsx')
+);
+const BSNavBarUserInfo = lazy(() => import('./BSNavBarUserInfo.jsx'));
+
+const UserRelieveManager = lazy(
+ () => import('../../Template/RealivingUser.jsx')
+);
+const BSNavbarSearchStandard = lazy(
+ () => import('../UtillComponents/BSNavbarSearchStandard.jsx')
+);
+const BSPrinterSetting = lazy(
+ () => import('../UtillComponents/BSPrinterSetting.jsx')
+);
+const BSNavBarTable = lazy(
+ () => import('../UtillComponents/BSNavBarTable.jsx')
+);
+const BSMobilePrintSettings = lazy(
+ () => import('../UtillComponents/BSMobilePrintSettings.jsx')
+);
+const BSScanTemplate = lazy(
+ () => import('../UtillComponents/BSScanTemplate.jsx')
+);
+const VerfiedProducts = lazy(
+ () => import('./verfiedProduct/VerfiedProducts.jsx')
+);
+const BSMembership = lazy(() => import('../UtillComponents/BSMembership.jsx'));
+const BranchName = lazy(() => import('../../Template/BranchName.jsx'));
+const BSNavBarAddons = lazy(
+ () => import('../UtillComponents/BSNavBarAddons.jsx')
+);
+const BSNavBarOffer = lazy(
+ () => import('../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx')
+);
+const BSNavBarQuickAdd = lazy(
+ () => import('../UtillComponents/BSNavBarQuickAdd.jsx')
+);
+// Api
const subDirectory = import.meta.env.ENV_BASE_URL;
const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;
@@ -156,6 +187,7 @@ const BSNavbar3 = ({ optionNames }) => {
const [isUserAccOpen, setIsUserAccOpen] = useState(false);
const [quickAdd, setQuickAdd] = useState(false);
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
+
const [isFullscreen, setIsFullscreen] = useState(false);
const [multiple, setMultiple] = useState(false);
const GlobEstBooking = useSelector(GlobalEstimateBooking);
@@ -563,568 +595,179 @@ const BSNavbar3 = ({ optionNames }) => {
};
return (
- <>
-
-
-
-
-
- {' '}
-
- {' '}
-
+ Loading…
}>
+ <>
+
+
+
+
+
+ {' '}
+
+ {' '}
+
+
+
+ {OtherServiceStatus && Parking && (
+
+ )}
- {OtherServiceStatus && Parking && (
+ {/* Multiple search */}
+
+
+ setMultiple(true)} />
+
+
+ {!sportsAppPreference && searchOption && (
searchInputRef.current?.focus()}
>
-
-
-
-
-
+
)}
-
- {/* Multiple search */}
-
-
- setMultiple(true)} />
-
-
- {!sportsAppPreference && searchOption && (
-
searchInputRef.current?.focus()}
- >
-
-
- )}
-
- {/* Customer Select - Always visible */}
-
-
+ {/* Customer Select - Always visible */}
{addCustomerOption && (
-
- {renderWithTooltip( , 'Add Customer')}
-
- )}
- {/* */}
-
-
- {offerOption && (
-
- {GlobEstBooking !== 'OvrAllEst' &&
- GlobEstBooking !== 'ParEst' &&
- GlobEstBooking === 'Sales' &&
- preferences?.[0]?.['SettingDtlDetails']?.find(
- (item) => item.SettingIdName === 'Offer'
- )?.SettingValue === 'Y' && (
-
-
-
+
+
+ {addCustomerOption && (
+
+ {renderWithTooltip( , 'Add Customer')}
+
)}
-
- )}
- {extraChargeOption && !sportsAppPreference && (
-
-
-
- )}
-
- {!sportsAppPreference && quickAddOption && (
-
-
-
- )}
- {/* Desktop CustomerActions */}
-
- {/* {(takeAwayPreference && takeAwayOption) && renderWithTooltip(
-
, 'Takeaway')}
- {(dineInPreference && dineIn && dineInOption) && renderWithTooltip(
-
, 'Dine-in')} */}
-
- {dineInPreference && dineIn && dineInOption && (
-
-
)}
- {!OtherServicesglobal && (
- <>
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() !== 'weight scale'
- ) && (
-
-
-
- )}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
-
-
-
- {
- openPreOrder();
- }}
- HandleClose={preOrderHandleclose}
- />
-
-
-
- )}
- >
- )}
- {preOrderOpen && (
-
-
-
- )}
- {sportsAppPreference &&
}
- {!OtherServicesglobal && (
- <>
- {Estimation?.SettingValue === 'Y' &&
- bookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- !OrderOfferStatus && (
+ {offerOption && (
+
+ {GlobEstBooking !== 'OvrAllEst' &&
+ GlobEstBooking !== 'ParEst' &&
+ GlobEstBooking === 'Sales' &&
+ preferences?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'Offer'
+ )?.SettingValue === 'Y' && (
-
+
)}
- >
- )}
-
- {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
-
- )}
-
- {!sportsAppPreference && (
-
- {renderWithTooltip(
- ,
- 'Favourites'
- )}
)}
- {/*
- {!sportsAppPreference &&
- quickAddOption &&
- renderWithTooltip(
-
,
- 'QUICK ADD (SHIFT + Q)'
- )} */}
-
- {holdOption &&
- ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
- (bookingType !== 'Dine In' &&
- Holddata?.length > 0 &&
- OrderCardDetail?.length == 0)) &&
- isHoldEnable &&
- renderWithTooltip(
-
,
- 'Hold'
- )}
- {ScanLayoutScreen?.SettingValue === 'Y' &&
}
-
-
-
- {FeatureAddonData?.FeatureDtls?.find(
- (item) =>
- item?.FeatureAddonName?.toLowerCase() === 'customer display'
- ) && (
-
-
-
-
-
- )}
-
- {reprintOption && (
-
- )}
-
-
- {verifyproduct && (
-
- )}
-
- {isMobile && (
-
-
-
- )}
-
-
-
-
-
-
-
-
+ {extraChargeOption && !sportsAppPreference && (
- {isFullscreen ? : }
-
-
-
-
-
- }
- Logout={Logout}
- />
-
-
- {/* Mobile Toggle Button */}
-
-
-
-
-
-
- {/* Mobile Menu */}
-
-
-
- {isMobileMenuOpen ? (
-
- ) : (
-
- )}
-
-
- {takeAwayPreference && takeAwayOption && (
-
- )}
- {dineInPreference && dineIn && dineInOption && (
-
- )}
- {!sportsAppPreference && (
-
- setDrawerOpen((prev) => ({
- ...prev,
- favourite: !prev?.favourite,
- }))
- }
- >
-
-
Favourite
-
- )}
- {addCustomerOption && (
-
- setDrawerOpen((prev) => ({
- ...prev,
- customer: !prev?.customer,
- }))
- }
- >
-
-
Add Customer
-
- )}
- {quickAddOption && (
-
- {renderWithTooltip(
, 'Quick Add', 'top')}
-
Quick Add
-
- )}
- {holdOption &&
- ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
- (bookingType !== 'Dine In' &&
- Holddata?.length > 0 &&
- isHoldEnable &&
- OrderCardDetail?.length == 0)) && (
-
- setDrawerOpen((prev) => ({ ...prev, hold: !prev?.hold }))
- }
- >
-
-
Hold
-
- )}
- {ScanLayoutScreen?.SettingValue === 'Y' &&
}
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- dragItem: !prev?.dragItem,
- }));
- }
+ className="standard-extra-charges"
+ style={{
+ pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
}}
>
-
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- dragItem: !prev?.dragItem,
- }));
- }
- }}
- >
- Drag Item
-
+
- {reprintOption && (
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- reprint: !prev?.reprint,
- }));
- }
- }}
- >
-
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- reprint: !prev?.reprint,
- }));
- }
- }}
- >
- Re-Print
-
+ )}
+
+ {!sportsAppPreference && quickAddOption && (
+
+
+
+ )}
+ {/* Desktop CustomerActions */}
+
+ {dineInPreference && dineIn && dineInOption && (
+
+
)}
- {verifyproduct && (
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- verifyProduct: !prev?.verifyProduct,
- }));
- }
- }}
- >
-
-
-
+
+ {!OtherServicesglobal && (
+ <>
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() !== 'weight scale'
+ ) && (
+
+
-
-
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- verifyProduct: !prev?.verifyProduct,
- }));
- }
- }}
- >
- Verify Product
-
+ )}
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
+ ) && (
+
+
+
+ {
+ openPreOrder();
+ }}
+ HandleClose={preOrderHandleclose}
+ />
+
+
+
+ )}
+ >
+ )}
+ {preOrderOpen && (
+
+
)}
-
- {sportsAppPreference && (
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- membership: !prev?.membership,
- }));
- }
- }}
- >
-
-
{
- if (e.target === e.currentTarget) {
- setDrawerOpen((prev) => ({
- ...prev,
- membership: !prev?.membership,
- }));
- }
- }}
- >
- Membership
-
-
- )}
-
+ {sportsAppPreference &&
}
{!OtherServicesglobal && (
<>
{Estimation?.SettingValue === 'Y' &&
@@ -1137,31 +780,410 @@ const BSNavbar3 = ({ optionNames }) => {
pointerEvents: orderType === 'Failed' ? 'none' : 'auto',
}}
>
-
+
)}
>
)}
+
{SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
+
+ )}
+
+ {!sportsAppPreference && (
+
+ {renderWithTooltip(
+ ,
+ 'Favourites'
+ )}
+
+ )}
+ {holdOption &&
+ ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
+ (bookingType !== 'Dine In' &&
+ Holddata?.length > 0 &&
+ OrderCardDetail?.length == 0)) &&
+ isHoldEnable &&
+ renderWithTooltip(
+ ,
+ 'Hold'
+ )}
+ {ScanLayoutScreen?.SettingValue === 'Y' && }
+
+
+
+ {FeatureAddonData?.FeatureDtls?.find(
+ (item) =>
+ item?.FeatureAddonName?.toLowerCase() === 'customer display'
+ ) && (
+
+
+
+
+
+ )}
+
+ {reprintOption && (
+
+ )}
+
+
+ {verifyproduct && (
+
+ )}
+
+ {isMobile && (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+
+ {isFullscreen ? : }
+
+
+
+
+
+ }
+ Logout={Logout}
+ />
+
+
+ {/* Mobile Toggle Button */}
+
+
+
+
+
+
+ {/* Mobile Menu */}
+
+
+
+ {isMobileMenuOpen ? (
+
+ ) : (
+
+ )}
+
+
+ {takeAwayPreference && takeAwayOption && (
+
+ )}
+ {dineInPreference && dineIn && dineInOption && (
+
+ )}
+ {!sportsAppPreference && (
+
+ setDrawerOpen((prev) => ({
+ ...prev,
+ favourite: !prev?.favourite,
+ }))
+ }
+ >
+
+
Favourite
+
+ )}
+ {addCustomerOption && (
+
+ setDrawerOpen((prev) => ({
+ ...prev,
+ customer: !prev?.customer,
+ }))
+ }
+ >
+
+
Add Customer
+
+ )}
+ {quickAddOption && (
+
+ {renderWithTooltip(
, 'Quick Add', 'top')}
+
Quick Add
+
+ )}
+ {holdOption &&
+ ((bookingType !== 'Dine In' && OrderCardDetail?.length != 0) ||
+ (bookingType !== 'Dine In' &&
+ Holddata?.length > 0 &&
+ isHoldEnable &&
+ OrderCardDetail?.length == 0)) && (
+
+ setDrawerOpen((prev) => ({ ...prev, hold: !prev?.hold }))
+ }
+ >
+
+
Hold
+
+ )}
+ {ScanLayoutScreen?.SettingValue === 'Y' &&
}
{
if (e.target === e.currentTarget) {
setDrawerOpen((prev) => ({
...prev,
- wholesale: !prev?.wholesale,
+ dragItem: !prev?.dragItem,
}));
}
}}
>
-
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ dragItem: !prev?.dragItem,
+ }));
+ }
+ }}
+ >
+ Drag Item
+
+
+ {reprintOption && (
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ reprint: !prev?.reprint,
+ }));
+ }
+ }}
+ >
+
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ reprint: !prev?.reprint,
+ }));
+ }
+ }}
+ >
+ Re-Print
+
+
+ )}
+ {verifyproduct && (
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ verifyProduct: !prev?.verifyProduct,
+ }));
+ }
+ }}
+ >
+
+
+
+
+
+
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ verifyProduct: !prev?.verifyProduct,
+ }));
+ }
+ }}
+ >
+ Verify Product
+
+
+ )}
+
+ {sportsAppPreference && (
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ membership: !prev?.membership,
+ }));
+ }
+ }}
+ >
+
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ membership: !prev?.membership,
+ }));
+ }
+ }}
+ >
+ Membership
+
+
+ )}
+
+ {!OtherServicesglobal && (
+ <>
+ {Estimation?.SettingValue === 'Y' &&
+ bookingType !== 'Dine In' &&
+ !BookingTypeBoth &&
+ !OrderOfferStatus && (
+
+ )}
+ >
+ )}
+ {SalesMode?.SettingValue === 'Y' && !OtherServicesglobal && (
+
{
if (e.target === e.currentTarget) {
setDrawerOpen((prev) => ({
@@ -1171,34 +1193,49 @@ const BSNavbar3 = ({ optionNames }) => {
}
}}
>
- WholeSale
+
+
{
+ if (e.target === e.currentTarget) {
+ setDrawerOpen((prev) => ({
+ ...prev,
+ wholesale: !prev?.wholesale,
+ }));
+ }
+ }}
+ >
+ WholeSale
+
-
- )}
+ )}
+
-
-
setMultiple(false)}
- destroyOnClose={true}
- children={
- <>
-
- >
- }
- />
- {quickAdd && (
- setMultiple(false)}
+ destroyOnClose={true}
+ children={
+ <>
+
+ >
+ }
/>
- )}
- >
+ {quickAdd && (
+
+ )}
+ >
+
);
};
diff --git a/src/Pages/BookingScreen/Components/BookingFunctionality/CreditCustSplitPayment.jsx b/src/Pages/BookingScreen/Components/BookingFunctionality/CreditCustSplitPayment.jsx
index 27aab6c..2244a10 100644
--- a/src/Pages/BookingScreen/Components/BookingFunctionality/CreditCustSplitPayment.jsx
+++ b/src/Pages/BookingScreen/Components/BookingFunctionality/CreditCustSplitPayment.jsx
@@ -1,4 +1,11 @@
-import { useEffect, useRef, useState, useCallback } from 'react';
+import {
+ useEffect,
+ useRef,
+ useState,
+ useCallback,
+ Suspense,
+ lazy,
+} from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import {
getConfigType,
@@ -43,13 +50,17 @@ import {
validateSafeInput,
} from '../../../../Services/Others.js';
import WpIcon from '../../../../Images/message.png';
-import QrinScreen from '../BookingFunctionality/DynamicScreenQr.jsx';
+const QrinScreen = lazy(
+ () => import('../BookingFunctionality/DynamicScreenQr.jsx')
+);
import {
getTemplateData,
SelectedPrintTemplate,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import '../../../../Styles/BookingScreen/Components/BookingFunctionality/SplitPayment.scss';
-import FeaturesFunctionalities from './FeaturesFunctionalities.jsx';
+const FeaturesFunctionalities = lazy(
+ () => import('./FeaturesFunctionalities.jsx')
+);
import numberToWords from 'number-to-words';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import { getConfigTypeData } from '../../../../Features/ConfigMasterPage/ConfigMasterPage.js';
@@ -93,7 +104,7 @@ const CreditCustSplitPayment = (props) => {
const [UpiPayOption, setUpiPayOption] = useState([]);
const [CardPayOption, setCardPayOption] = useState([]);
const GlobaluseOptions = useSelector(GlobalCommonPaymentOptions);
- const RetailWSSalesType= useSelector(GlobalRetailWSSalesType, shallowEqual);
+ const RetailWSSalesType = useSelector(GlobalRetailWSSalesType, shallowEqual);
const [useOptions, setuseOptions] = useState([]);
const BookingType = useSelector(GlobalBookingType);
const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
@@ -730,7 +741,7 @@ const CreditCustSplitPayment = (props) => {
(item) => item?.ConfigName?.toLowerCase() == 'DEP'.toLowerCase()
);
let postData = {
- SalesMode:RetailWSSalesType || 'R',
+ SalesMode: RetailWSSalesType || 'R',
CompId: CompId,
BranchId: BranchId,
Type: obId?.[0]?.ConfigId,
@@ -1241,139 +1252,141 @@ const CreditCustSplitPayment = (props) => {
: 'Debit amount not available';
return (
- <>
-
-
-
{
- SplitSelPayMode[`PaymentStatus-0`] !== 'S' && HandleModalClose();
- }}
- footer={false}
- width={1000}
- children={
-
-
Total Amount:{TotalAmount}
+
Loading features... }>
+ <>
+
+
+
{
+ SplitSelPayMode[`PaymentStatus-0`] !== 'S' && HandleModalClose();
+ }}
+ footer={false}
+ width={1000}
+ children={
+
+
Total Amount:{TotalAmount}
- <>{calculateField()}>
- {TotalAmount > TotalSplitAmount &&
- SplitSelPayMode[`PaymentStatus-${count}`] === 'S' && (
-
-
-
{calculateField()}>
+ {TotalAmount > TotalSplitAmount &&
+ SplitSelPayMode[`PaymentStatus-${count}`] === 'S' && (
+
+ setCount(count + 1)}
- />
-
-
- )}
-
- }
- />
-
- {TotalAmount == 0 && Success && (
-
-
+ >
+
setCount(count + 1)}
+ />
+
+
+ )}
+
+ }
+ />
- )}
- {TotalAmount > 0 &&
- qrCode &&
- PaymentUpiOptions?.length > 0 &&
- SelUpiId && (
+ {TotalAmount == 0 && Success && (
-
+
)}
- {UpiOpen && (
- {
- Upimodel('Cancel');
- }}
- footer={false}
- children={
-
-
-
-
-
-
-
-
RS :{CurrentPayAmount}
-
-
-
-
- {(selOption || SelCustId) && (
-
- Sent Payment Link
-
-
- )}
-
+ {TotalAmount > 0 &&
+ qrCode &&
+ PaymentUpiOptions?.length > 0 &&
+ SelUpiId && (
+
+
+
+ )}
+ {UpiOpen && (
+
{
+ Upimodel('Cancel');
+ }}
+ footer={false}
+ children={
+
-
}
- handleSubmit={() => {
- Upimodel('Submit');
+
+
+
+
+
+
RS :{CurrentPayAmount}
+
+
+
+
+ {(selOption || SelCustId) && (
+
+ Sent Payment Link
+
+
+ )}
+
+
+ >
+
}
+ handleSubmit={() => {
+ Upimodel('Submit');
+ }}
+ />
+
-
- }
- />
- )}
- {addcustomer && (
-
- )}
- {Object.keys(PrintDatas).length > 0 && (
-
-
-
- )}
- >
+ )}
+ {addcustomer && (
+
+ )}
+ {Object.keys(PrintDatas).length > 0 && (
+
+
+
+ )}
+ >
+
);
};
export default CreditCustSplitPayment;
diff --git a/src/Pages/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx b/src/Pages/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx
index 4a7f74b..4d17dfc 100644
--- a/src/Pages/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx
+++ b/src/Pages/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx
@@ -4,6 +4,7 @@ import React, {
useEffect,
useCallback,
useContext,
+ lazy,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
@@ -16,7 +17,6 @@ import {
Checkbox,
AutoComplete,
Switch,
- Tooltip,
Popconfirm,
Tabs,
} from 'antd';
@@ -58,7 +58,6 @@ import {
ChangeOverAllDiscSales,
PreferenceData,
ChangeComboCarddata,
- getPreferenceData,
getCustomerForHold,
PostBlockSlots,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
@@ -68,7 +67,6 @@ import { ArrowRightOutlined, CloseSquareFilled } from '@ant-design/icons';
import { InputField } from '../../../../Components/Forms/InputField';
import { Messages } from '../../../../Components/Notifications/Messages';
import Buttons from '../../../../Components/Forms/Buttons';
-import ProductForm from '../../../../Pages/BookingScreen/Forms/QuickAdd/QuickAdd.jsx';
import {
GlobalAddCustomerDetails,
getAddCustomerDetails,
@@ -86,7 +84,6 @@ import {
ChangeTotalAmount,
globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
-import WeightScaleComp from '../../../../Components/WeightScale/weightScale.jsx';
import {
gettinghold,
puttinghold,
@@ -98,7 +95,6 @@ import {
getProductsearch,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { AiOutlineDownCircle, AiOutlineUpCircle } from 'react-icons/ai';
-import '../../../../Styles/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.scss';
import {
IoCloseSharp,
IoPersonAddSharp,
@@ -111,7 +107,6 @@ import {
GlobalPreOrderList,
GlobalpreOrderOpen,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
-import Imageupload from '../../../../Components/Forms/Upload.jsx';
import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { getCombolist } from '../../../../Features/ComboMaster/ComboMaster.js';
import {
@@ -122,12 +117,24 @@ import {
import { v4 as uuidv4 } from 'uuid';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';
-import { FaEdit, FaMapMarkedAlt, FaTrash } from 'react-icons/fa';
+import { FaEdit, FaTrash } from 'react-icons/fa';
import { MdHome, MdLocationOn } from 'react-icons/md';
import { RadioGrpButton } from '../../../../Components/Forms/RadioGroup.jsx';
+// jsx Files
+const ProductForm = lazy(
+ () => import('../../../../Pages/BookingScreen/Forms/QuickAdd/QuickAdd.jsx')
+);
+const WeightScaleComp = lazy(
+ () => import('../../../../Components/WeightScale/weightScale.jsx')
+);
+const Imageupload = lazy(
+ () => import('../../../../Components/Forms/Upload.jsx')
+);
+// Scss
+import '../../../../Styles/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.scss';
const FeaturesFunctionalities = (props) => {
- const { closeModal = () => { } } = props;
+ const { closeModal = () => {} } = props;
const applyOffer = useApplyOfferto_CardDetail();
const EditableContext = React.createContext(null);
const EditableContext1 = React.createContext(null);
@@ -141,7 +148,6 @@ const FeaturesFunctionalities = (props) => {
const formRefExtraCharges = useRef();
const ExtraChargesType = useSelector(globalExtraChargesType);
const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
- console.log(GlobalExtraCharge, "GlobalExtraCharge")
const ReorderHoldDetails = useSelector(GlobalReorderHoldDetails);
const BookingType = useSelector(GlobalBookingType);
const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
@@ -370,30 +376,30 @@ const FeaturesFunctionalities = (props) => {
const options = suggestions
? suggestions
- ?.filter((item) =>
- selectedSearchValue === 'CustName' ? item.CustName !== null : item
- )
- .map((item) => ({
- value: item?.CustMobile,
- label:
- selectedSearchValue === 'CustMobile'
- ? `${item?.CustMobile} - ${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`
- : selectedSearchValue === 'CustId'
- ? `${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}${item?.CustName ? ' - ' : ''} ${item?.CustName ? item?.CustName : ''} - ${item?.CustMobile}`
- : selectedSearchValue === 'CustName' &&
- item?.CustName !== null &&
- `${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${item?.CustMobile} - ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`,
- CustMobile: item?.CustMobile,
- CustId: item?.CustId?.match(/-(\d+)$/)?.[1],
- CustName: item?.CustName,
- }))
+ ?.filter((item) =>
+ selectedSearchValue === 'CustName' ? item.CustName !== null : item
+ )
+ .map((item) => ({
+ value: item?.CustMobile,
+ label:
+ selectedSearchValue === 'CustMobile'
+ ? `${item?.CustMobile} - ${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`
+ : selectedSearchValue === 'CustId'
+ ? `${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}${item?.CustName ? ' - ' : ''} ${item?.CustName ? item?.CustName : ''} - ${item?.CustMobile}`
+ : selectedSearchValue === 'CustName' &&
+ item?.CustName !== null &&
+ `${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${item?.CustMobile} - ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`,
+ CustMobile: item?.CustMobile,
+ CustId: item?.CustId?.match(/-(\d+)$/)?.[1],
+ CustName: item?.CustName,
+ }))
: GlobalAddCustomerDetails1?.map((item) => ({
- value: item.CustMobile,
- label: `${item?.CustName} ${item?.CustMobile}`,
- CustMobile: item?.CustMobile,
- CustId: item?.CustId,
- CustName: item?.CustName,
- }));
+ value: item.CustMobile,
+ label: `${item?.CustName} ${item?.CustMobile}`,
+ CustMobile: item?.CustMobile,
+ CustId: item?.CustId,
+ CustName: item?.CustName,
+ }));
const handleYesOrNoChange = (value) => {
setSelectedValue(value);
formRef.current?.setFieldsValue({ OfferActiveStatus: value });
@@ -456,34 +462,34 @@ const FeaturesFunctionalities = (props) => {
},
...(sportsAppPreference
? [
- {
- title: 'Subcategory',
- key: 'productDetails',
- dataIndex: 'productDetails',
- align: 'center',
- width: '150px',
- onCell: (record) => {
- const productDetails = record?.productDetails;
- const Combodtl =
- record?.productDetails?.[0]?.comboDtl?.[0]
- ?.ComboInwardDetails?.[0]?.ComboDetails;
+ {
+ title: 'Subcategory',
+ key: 'productDetails',
+ dataIndex: 'productDetails',
+ align: 'center',
+ width: '150px',
+ onCell: (record) => {
+ const productDetails = record?.productDetails;
+ const Combodtl =
+ record?.productDetails?.[0]?.comboDtl?.[0]
+ ?.ComboInwardDetails?.[0]?.ComboDetails;
- return {
- onClick: () => {
- HoldPutfun(productDetails, record, Combodtl);
- },
- };
+ return {
+ onClick: () => {
+ HoldPutfun(productDetails, record, Combodtl);
+ },
+ };
+ },
+ render: (productDetails, record) => (
+ HoldPutfun(productDetails, record)}
+ >
+ {record?.productDetails?.[0]?.ProdSubCatName}
+
+ ),
},
- render: (productDetails, record) => (
- HoldPutfun(productDetails, record)}
- >
- {record?.productDetails?.[0]?.ProdSubCatName}
-
- ),
- },
- ]
+ ]
: []),
{
title: 'Orders',
@@ -581,13 +587,7 @@ const FeaturesFunctionalities = (props) => {
];
useEffect(() => {
setWeightScale(props.WeightScale);
- }, [props.WeightScale]);
- // useEffect(() => {
- // if (!props.addcustomer) {
- // formRef.current?.resetFields();
- // setZipCodeData(false);
- // }
- // }, [props.addcustomer]);
+ }, [props.WeightScale]);
const ExtTabledata = async () => {
const data = {
CompId: CompId,
@@ -761,7 +761,7 @@ const FeaturesFunctionalities = (props) => {
TaxAmt: formatAmount(
((record.Price * record.TaxPercentage) /
(100 + record.TaxPercentage)) *
- record.QTY
+ record.QTY
),
TaxId: record.TaxId,
TaxPercentage: record.TaxPercentage,
@@ -788,11 +788,11 @@ const FeaturesFunctionalities = (props) => {
const isDuplicate = TableName?.some(
(item) =>
item.InwardDtlId +
- ' ' +
- item.BookingTypeName +
- ' ' +
- item.SinglePc ===
- selectedProduct && item.UniqueId === record.UniqueId
+ ' ' +
+ item.BookingTypeName +
+ ' ' +
+ item.SinglePc ===
+ selectedProduct && item.UniqueId === record.UniqueId
);
if (!isDuplicate) {
@@ -810,7 +810,7 @@ const FeaturesFunctionalities = (props) => {
TaxAmt: formatAmount(
((record.Price * record.TaxPercentage) /
(100 + record.TaxPercentage)) *
- record.QTY
+ record.QTY
),
TaxId: record?.TaxId,
TaxPercentage: record.TaxPercentage,
@@ -1057,7 +1057,7 @@ const FeaturesFunctionalities = (props) => {
...record,
...values,
});
- } catch (errInfo) { }
+ } catch (errInfo) {}
};
let childNode = children;
@@ -1109,7 +1109,7 @@ const FeaturesFunctionalities = (props) => {
return (
record.Price * record.QTY -
((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
- record.QTY
+ record.QTY
);
};
const WithTaxAmountTaxAmount = (record) => {
@@ -1182,10 +1182,10 @@ const FeaturesFunctionalities = (props) => {
onClick={() => addeddata(record)}
disabled={
Object.keys(ReorderHoldDetails).length !== 0 &&
- BookingType === 'Dine In' &&
- GlobalExtraCharge.some(
- (item) => item.ExtraChargeId === record.UniqueId
- )
+ BookingType === 'Dine In' &&
+ GlobalExtraCharge.some(
+ (item) => item.ExtraChargeId === record.UniqueId
+ )
? true
: false
}
@@ -1194,11 +1194,6 @@ const FeaturesFunctionalities = (props) => {
),
},
];
-
- console.log(ReorderHoldDetails,
- BookingType,
- GlobalExtraCharge, "GlobalExtraCharge");
-
const defaultColumns1 = [
{
title: 'ExtraCharge Type',
@@ -1286,7 +1281,7 @@ const FeaturesFunctionalities = (props) => {
QTY: parseInt(row.QTY),
TaxAmt: formatAmount(
((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage)) *
- row.QTY
+ row.QTY
),
TotalAmt: row.Price * row.QTY,
// ((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage) *row.QTY ).toFixed(2),
@@ -1435,12 +1430,12 @@ const FeaturesFunctionalities = (props) => {
{Object.keys(ReorderHoldDetails).length !== 0 &&
- BookingType === 'Dine In' &&
- GlobalExtraCharge?.some(
- (item) =>
- item.ExtraChargeId === record.UniqueId &&
- item.InwardDtlId === record.InwardDtlId
- ) ? (
+ BookingType === 'Dine In' &&
+ GlobalExtraCharge?.some(
+ (item) =>
+ item.ExtraChargeId === record.UniqueId &&
+ item.InwardDtlId === record.InwardDtlId
+ ) ? (
{
dispatch(
changeCustomerID(
response?.data?.CustomerDetails?.[
- response?.data?.CustomerDetails.length - 1
+ response?.data?.CustomerDetails.length - 1
]
)
);
@@ -2194,9 +2189,9 @@ const FeaturesFunctionalities = (props) => {
AppId: AppId,
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
await dispatch(getSelectedFavItems(data)).unwrap();
@@ -2208,9 +2203,9 @@ const FeaturesFunctionalities = (props) => {
ProdSubCat: ProdSubCat,
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
@@ -2221,9 +2216,9 @@ const FeaturesFunctionalities = (props) => {
prodCat: prodCat,
...(AvailableDate && selectedDate
? {
- fromDate: selectedDate?.[0],
- toDate: selectedDate?.[1],
- }
+ fromDate: selectedDate?.[0],
+ toDate: selectedDate?.[1],
+ }
: {}),
};
@@ -2596,7 +2591,7 @@ const FeaturesFunctionalities = (props) => {
e?.stopPropagation();
removeAll();
}}
- // onClick={() => statusFormatter(record,index)}
+ // onClick={() => statusFormatter(record,index)}
>
Clear All
@@ -2723,7 +2718,7 @@ const FeaturesFunctionalities = (props) => {
: selectedSearchValue == 'CustName'
? 'Please Enter Valid Name'
: selectedSearchValue == 'CustId' &&
- 'Please EnterCustomer Id',
+ 'Please EnterCustomer Id',
},
]}
>
@@ -2812,7 +2807,7 @@ const FeaturesFunctionalities = (props) => {
: selectedSearchValue == 'CustName'
? 'Enter Name'
: selectedSearchValue == 'CustId' &&
- 'Enter Customer Id'
+ 'Enter Customer Id'
: ' Mobile Number'}
}
@@ -2994,7 +2989,7 @@ const FeaturesFunctionalities = (props) => {
autocomplete="off"
isOnChange={
formRef.current?.getFieldsValue()?.CustName ||
- inputValue
+ inputValue
? true
: false
}
@@ -3060,9 +3055,9 @@ const FeaturesFunctionalities = (props) => {
Upload Profile
- // formType === 'edit' ? editstate?.EmpPhotoLink : e
- // }
+ // getValueFromEvent={(e) =>
+ // formType === 'edit' ? editstate?.EmpPhotoLink : e
+ // }
>
{
handleRemoveAddress(idx)}
+ onConfirm={() =>
+ handleRemoveAddress(idx)
+ }
okText="Yes, Remove"
cancelText="Cancel"
okType="danger"
@@ -3492,7 +3489,7 @@ const FeaturesFunctionalities = (props) => {
{
style={
offerType == 'P'
? {
- opacity: '1',
- boxShadow:
- 'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
- margin: '3px',
- padding: '5px',
- backgroundColor: '#fff',
- }
+ opacity: '1',
+ boxShadow:
+ 'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
+ margin: '3px',
+ padding: '5px',
+ backgroundColor: '#fff',
+ }
: { opacity: '0.6', boxShadow: 'none' }
}
onClick={() => {
@@ -3557,13 +3554,13 @@ const FeaturesFunctionalities = (props) => {
style={
offerType == 'F'
? {
- opacity: '1',
- boxShadow:
- 'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
- margin: '3px',
- padding: '5px',
- backgroundColor: '#fff',
- }
+ opacity: '1',
+ boxShadow:
+ 'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
+ margin: '3px',
+ padding: '5px',
+ backgroundColor: '#fff',
+ }
: { opacity: '0.6', boxShadow: 'none' }
}
onClick={() => {
@@ -3660,7 +3657,7 @@ const FeaturesFunctionalities = (props) => {
}
isOnChange={
formRef.current?.getFieldsValue()?.CustEmail ||
- inputValue
+ inputValue
? true
: false
}
@@ -3688,7 +3685,7 @@ const FeaturesFunctionalities = (props) => {
autocomplete="off"
isOnChange={
formRef.current?.getFieldsValue()?.CreditLimit ||
- inputValue
+ inputValue
? true
: false
}
@@ -3921,7 +3918,7 @@ const FeaturesFunctionalities = (props) => {
onChange={setActiveTab}
items={[
{ key: 'quickAdd', label: 'Quick Add' },
- { key: 'directSale', label: 'Direct Sale' }
+ { key: 'directSale', label: 'Direct Sale' },
]}
/>
{
buttonText="SAVE"
color="901D77"
icon={ }
- // handleSubmit={() => { globalamount1() }}
+ // handleSubmit={() => { globalamount1() }}
/>
@@ -4059,7 +4056,7 @@ const FeaturesFunctionalities = (props) => {
bordered
dataSource={TableName}
width={'120px'}
- //pagination={column2?.length < "11" ? false : true}
+ //pagination={column2?.length < "11" ? false : true}
>
)}
diff --git a/src/Pages/BookingScreen/Components/BookingFunctionality/SplitPayment.jsx b/src/Pages/BookingScreen/Components/BookingFunctionality/SplitPayment.jsx
index a99cd9a..7ce5902 100644
--- a/src/Pages/BookingScreen/Components/BookingFunctionality/SplitPayment.jsx
+++ b/src/Pages/BookingScreen/Components/BookingFunctionality/SplitPayment.jsx
@@ -1,6 +1,28 @@
-import { useEffect, useRef, useState, useCallback } from 'react';
+import {
+ useEffect,
+ useRef,
+ useState,
+ useCallback,
+ lazy,
+ Suspense,
+} from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
+import { Form, Radio } from 'antd';
+import {
+ ArrowRightOutlined,
+ CheckCircleOutlined,
+ CloseCircleOutlined,
+ PlusOutlined,
+} from '@ant-design/icons';
+import { InputField } from '../../../../Components/Forms/InputField';
+import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
+import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
+import Buttons from '../../../../Components/Forms/Buttons';
+import { Messages } from '../../../../Components/Notifications/Messages';
+import { isMobile } from 'react-device-detect';
+
+// Js files
import {
getConfigType,
GlobalCommonPaymentOptions,
@@ -58,54 +80,61 @@ import {
putSalesBillEdit,
changeBillEditingMode,
changePreviousOrderPayment,
- changePreviousOrderOfferDetail
+ changePreviousOrderOfferDetail,
+ GlobalAllBookingType,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
-import { Form, Radio } from 'antd';
-import {
- ArrowRightOutlined,
- CheckCircleOutlined,
- CloseCircleOutlined,
- PlusOutlined,
-} from '@ant-design/icons';
-import { InputField } from '../../../../Components/Forms/InputField';
-import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
-import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
-import Buttons from '../../../../Components/Forms/Buttons';
-import QrComponent from '../BookingFunctionality/DynamicQr.jsx';
-import { Messages } from '../../../../Components/Notifications/Messages';
import {
extractLastNumberOrderId,
getSession,
printDiv,
validateSafeInput,
} from '../../../../Services/Others.js';
-import WpIcon from '../../../../Images/message.png';
import {
ChangeTotalAmount,
globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
-import QrinScreen from '../BookingFunctionality/DynamicScreenQr.jsx';
-import PaymentPdfBooking from '../../../paymentpdfPage/PaymentPdfBooking.jsx';
-import { isMobile } from 'react-device-detect';
import { PrintStyleFunction } from '../../../paymentpdfPage/PrintStyleFunction.js';
import {
getTemplateData,
GlobalprintDatas,
SelectedPrintTemplate,
} from '../../../../Features/ThemeChange/ThemeChange.js';
-import '../../../../Styles/BookingScreen/Components/BookingFunctionality/SplitPayment.scss';
-import BsBillingCreditCustomer from '../BookingFunctionality/BSBillingCreditCustomer.jsx';
-import MobilePrint from '../BookingFunctionality/MobilePrint.jsx';
-import FeaturesFunctionalities from './FeaturesFunctionalities.jsx';
-import TokensinglePrint from '../../../paymentpdfPage/TokenOnlyPrints/TokeninsinglePrint.jsx';
-import TokenOnlyMobilePrint from './TokenOnlyMobilePrint.jsx';
-import AllProductTokenMobilePrint from './AllProductTokenMobilePrint.jsx';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import { gettinghold } from '../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import { Global_OrderOfferDetail } from '../../../../Features/Offer/Offer.js';
-import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
-import { ChangeFullFreeProductList, changeFullOfferAppliedProducts, GlobalOfferAppliedProducts } from '../../../../Features/Offer/Offernew/BookingOffernew.js';
+import {
+ ChangeFullFreeProductList,
+ changeFullOfferAppliedProducts,
+ GlobalOfferAppliedProducts,
+} from '../../../../Features/Offer/Offernew/BookingOffernew.js';
+
+// jsx
+const QrinScreen = lazy(
+ () => import('../BookingFunctionality/DynamicScreenQr.jsx')
+);
+const MobilePrint = lazy(
+ () => import('../BookingFunctionality/MobilePrint.jsx')
+);
+const FeaturesFunctionalities = lazy(
+ () => import('./FeaturesFunctionalities.jsx')
+);
+const PaymentPdfBooking = lazy(
+ () => import('../../../paymentpdfPage/PaymentPdfBooking.jsx')
+);
+const BsBillingCreditCustomer = lazy(
+ () => import('../BookingFunctionality/BSBillingCreditCustomer.jsx')
+);
+const TokensinglePrint = lazy(
+ () => import('../../../paymentpdfPage/TokenOnlyPrints/TokeninsinglePrint.jsx')
+);
+const QrComponent = lazy(() => import('../BookingFunctionality/DynamicQr.jsx'));
+
+import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
+
+// Style and Icon
+import '../../../../Styles/BookingScreen/Components/BookingFunctionality/SplitPayment.scss';
+import WpIcon from '../../../../Images/message.png';
const subDirectory = import.meta.env.BASE_URL;
const MainHomeUrl = import.meta.env.ENV_MAIN_BASE_URL;
@@ -119,12 +148,13 @@ const SplitPayment = (props) => {
const AppId = getSession('AppId');
const UserId = getSession('UserId');
const appPreferences = useSelector(ApplicationPreferences);
+ const AllBookingType = useSelector(GlobalAllBookingType);
const applyOffer = useApplyOfferto_CardDetail();
const globalTipAmount = useSelector(GlobaltipAmount);
- const TotalNetAmount = (props.hasOwnProperty('TotalNetAmount')
+ const TotalNetAmount = props.hasOwnProperty('TotalNetAmount')
? props['TotalNetAmount']
- : null);
+ : null;
const TableOrderId = props.hasOwnProperty('TableBookingOrderId')
? props['TableBookingOrderId']
: null;
@@ -138,10 +168,16 @@ const SplitPayment = (props) => {
const SelCustId = useSelector(GlobalSelCustId);
const salesBillEdit = useSelector(GlobalSalesBillEdit);
const previousOrderPayment = useSelector(GlobalPreviousOrderPayment);
- const previousOrderOfferDetails = useSelector(GlobalPreviousOrderOfferDetails);
+ const previousOrderOfferDetails = useSelector(
+ GlobalPreviousOrderOfferDetails
+ );
const filteredPayments =
previousOrderPayment?.filter(
- p => p?.LastOrderTran === 'Y' && p?.AfterAdjustment != null && p?.AfterAdjustment !== '' && p?.AfterAdjustment
+ (p) =>
+ p?.LastOrderTran === 'Y' &&
+ p?.AfterAdjustment != null &&
+ p?.AfterAdjustment !== '' &&
+ p?.AfterAdjustment
) || [];
const paymentsToUse =
filteredPayments.length > 0 ? filteredPayments : previousOrderPayment || [];
@@ -150,7 +186,8 @@ const SplitPayment = (props) => {
0
);
const totalPreviouspayment = paymentsToUse?.reduce(
- (acc, payment) => acc + parseFloat(payment.AfterAdjustment || payment.Amount || 0),
+ (acc, payment) =>
+ acc + parseFloat(payment.AfterAdjustment || payment.Amount || 0),
0
);
const [paybtns, setpaybtns] = useState([]);
@@ -193,7 +230,11 @@ const SplitPayment = (props) => {
const OverAllSales = useSelector(GlobalOverAllDiscSales);
const OverAllEstimate = useSelector(GlobalOverAllDiscEstimate);
const printDatas = useSelector(GlobalprintDatas);
- const allowDecimal = SettingDataSelector?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
+ const allowDecimal = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
+ (setting) =>
+ setting?.SettingIdName?.toLowerCase() === 'decimal' &&
+ setting?.SettingValue === 'Y'
+ );
const UomPrint = SettingDataSelector?.[0]?.SettingDtlDetails.filter(
(i) => i.SettingIdName === 'PrintUom'
)?.[0];
@@ -223,7 +264,7 @@ const SplitPayment = (props) => {
(item) => item?.OptionName == 'Offer'
);
const [TotalAmount, setTotalAmount] = useState(0);
- console.log(TotalAmount, "TotalSplitAmount", TotalSplitAmount)
+ console.log(TotalAmount, 'TotalSplitAmount', TotalSplitAmount);
const preferenceOffer =
SettingDataSelector?.[0]?.['SettingDtlDetails']?.find(
(item) => item.SettingIdName === 'Offer'
@@ -237,9 +278,8 @@ const SplitPayment = (props) => {
}, []);
useEffect(() => {
-
if (salesBillEdit) {
- const previousNetAmount = (totalPreviouspayment || 0);
+ const previousNetAmount = totalPreviouspayment || 0;
if (TotalNetAmount > previousNetAmount) {
setTotalAmount(TotalNetAmount - previousNetAmount);
} else {
@@ -248,8 +288,7 @@ const SplitPayment = (props) => {
} else {
setTotalAmount(TotalNetAmount);
}
-
- }, [totalPreviousOfferAmount, totalPreviouspayment, TotalNetAmount])
+ }, [totalPreviousOfferAmount, totalPreviouspayment, TotalNetAmount]);
useEffect(() => {
if (SelCustId) {
@@ -272,7 +311,7 @@ const SplitPayment = (props) => {
}, [Splitpayment]);
useEffect(() => {
const totalPayAmount = Object.keys(SplitSelPayMode)
- .filter(key => key.startsWith('PayAmount-'))
+ .filter((key) => key.startsWith('PayAmount-'))
.reduce((sum, key) => {
const value = parseInt(SplitSelPayMode[key], 10);
return sum + (isNaN(value) ? 0 : value);
@@ -360,20 +399,12 @@ const SplitPayment = (props) => {
setUpiPayOption(options);
};
const getBookingTypeId = async () => {
- let tempconfigdata = await dispatch(
- getConfigType({ TypeName: 'Booking Type' })
- ).unwrap();
+ setConfigDataList(AllBookingType);
+ let configdata = AllBookingType;
+ let checkName = BookingTypeBoth ? 'DineIn,TakeAway' : BookingType;
- if (tempconfigdata?.data?.statusCode == 1) {
- setConfigDataList(tempconfigdata?.data?.data);
- let configdata = tempconfigdata?.data?.data;
- let checkName = BookingTypeBoth ? 'DineIn,TakeAway' : BookingType;
-
- let filterconfigdata = configdata?.find(
- (a) => a?.ConfigName === checkName
- );
- setSelectedBookingType(filterconfigdata?.ConfigId);
- }
+ let filterconfigdata = configdata?.find((a) => a?.ConfigName === checkName);
+ setSelectedBookingType(filterconfigdata?.ConfigId);
};
const gettodaydate = () => {
const currentDate = new Date();
@@ -547,7 +578,8 @@ const SplitPayment = (props) => {
SingleTokenMobilePrint(PrintOrderDetails, SelUpiId, 'Booking');
}
} else {
- MobilePrint(appPreferences,
+ MobilePrint(
+ appPreferences,
PrintOrderDetails,
SelUpiId,
'Booking',
@@ -570,8 +602,9 @@ const SplitPayment = (props) => {
await Promise.all(
PrintOrderDetails?.[0]?.OrderDetails?.map(
async (orderDetail, index) => {
- const groupedTokens = orderDetail?.productDetails?.filter(data => data?.EditTokenAvailable !== 'N')?.reduce(
- (acc, item, idx) => {
+ const groupedTokens = orderDetail?.productDetails
+ ?.filter((data) => data?.EditTokenAvailable !== 'N')
+ ?.reduce((acc, item, idx) => {
if (item.TokenAvailable === 'Y') {
if (!item.CounterName) {
// If CounterName is null or empty
@@ -584,9 +617,7 @@ const SplitPayment = (props) => {
}
}
return acc;
- },
- {}
- );
+ }, {});
// Iterate over grouped tokens and print them
const tokensToPrint = Object.entries(groupedTokens).map(
@@ -605,11 +636,11 @@ const SplitPayment = (props) => {
);
} else {
await Promise.all(
- PrintOrderDetails?.[0]?.OrderDetails?.filter(data => data?.EditTokenAvailable !== 'N')?.map(
- async (orderDetail, index) => {
- await TokenPrint(`${index}-${orderDetail?.OrderId}`);
- }
- )
+ PrintOrderDetails?.[0]?.OrderDetails?.filter(
+ (data) => data?.EditTokenAvailable !== 'N'
+ )?.map(async (orderDetail, index) => {
+ await TokenPrint(`${index}-${orderDetail?.OrderId}`);
+ })
);
setPrintOrderDetails([]);
}
@@ -641,7 +672,7 @@ const SplitPayment = (props) => {
const selectedStyle =
stylesMap[
- printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
+ printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
];
if (selectedStyle) {
@@ -650,8 +681,9 @@ const SplitPayment = (props) => {
async (orderDetail, index) => {
await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print
if (orderDetail?.BookingTypeName !== 'Dine In') {
- const groupedTokens = orderDetail?.productDetails?.filter(data => data?.EditTokenAvailable !== 'N')?.reduce(
- (acc, item, idx) => {
+ const groupedTokens = orderDetail?.productDetails
+ ?.filter((data) => data?.EditTokenAvailable !== 'N')
+ ?.reduce((acc, item, idx) => {
if (item.TokenAvailable === 'Y') {
if (!item.CounterName) {
// If CounterName is null or empty
@@ -664,9 +696,7 @@ const SplitPayment = (props) => {
}
}
return acc;
- },
- {}
- );
+ }, {});
// Iterate over grouped tokens and print them
const tokensToPrint = Object.entries(groupedTokens).map(
@@ -1033,11 +1063,11 @@ const SplitPayment = (props) => {
(SplitSelPayMode[`PaymentStatus-${i}`] === "S" || SplitSelPayMode[`FirstPaymentclick-${i}`] === "Y") ? e.stopPropagation() : onFinish(i)}
+ // onClick={(e) => (SplitSelPayMode[`PaymentStatus-${i}`] === "S" || SplitSelPayMode[`FirstPaymentclick-${i}`] === "Y") ? e.stopPropagation() : onFinish(i)}
>
Pay
@@ -1365,8 +1395,8 @@ const SplitPayment = (props) => {
? 'E'
: GlobEstBooking === 'ParEst'
? GlobProdwisedata?.includes(
- a.InwardDtlId + ' ' + a?.BookingTypeName
- )
+ a.InwardDtlId + ' ' + a?.BookingTypeName
+ )
? 'E'
: 'S'
: 'S',
@@ -1448,7 +1478,14 @@ const SplitPayment = (props) => {
// SalesTableLinkDetails:
// SelectedTableDetails?.length > 0 ? SelectedTableDetails : null,
SalesTableLinkDetails:
- SelectedTableDetails?.length > 0 ? globalTipAmount === 0 ? SelectedTableDetails : SelectedTableDetails?.map(item => ({ ...item, "TipsAmount": globalTipAmount })) : null,
+ SelectedTableDetails?.length > 0
+ ? globalTipAmount === 0
+ ? SelectedTableDetails
+ : SelectedTableDetails?.map((item) => ({
+ ...item,
+ TipsAmount: globalTipAmount,
+ }))
+ : null,
// "Credit": TotalAmount,
// "Debit": 0,
@@ -1472,37 +1509,37 @@ const SplitPayment = (props) => {
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'card'
? SplitSelPayMode[`CardSelection-${i}`]
: SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'default'
+ 'default'
? 'PC'
: SplitSelPayMode[`UPISelection-${i}`],
ModeOfPayment:
SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
? PaymentUpiOptions?.find(
- (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
- )?.UPIDetailId
+ (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
+ )?.UPIDetailId
: null,
AccountDtl:
SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
? useOptions?.[0]?.PaymentDetails?.Payatthecounter?.find(
- (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
- )
+ (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
+ )
: (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'pd') ||
- (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
- 'card' &&
- SplitSelPayMode[`CardSelection-${i}`]?.toLowerCase() ===
- 'pd')
- ? useOptions?.[0]?.PaymentDetails?.PaymentDevice
- : (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
- 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'pg') ||
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
+ 'pd') ||
(SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
'card' &&
SplitSelPayMode[`CardSelection-${i}`]?.toLowerCase() ===
- 'pg')
+ 'pd')
+ ? useOptions?.[0]?.PaymentDetails?.PaymentDevice
+ : (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
+ 'upi' &&
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
+ 'pg') ||
+ (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
+ 'card' &&
+ SplitSelPayMode[`CardSelection-${i}`]?.toLowerCase() ===
+ 'pg')
? useOptions?.[0]?.PaymentDetails?.PaymentGateway
: [],
PaymentStatus:
@@ -1511,9 +1548,9 @@ const SplitPayment = (props) => {
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'credit'
? 'S'
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
- 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'default'
+ 'upi' &&
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
+ 'default'
? 'S'
: 'P',
Debit: 0,
@@ -1527,7 +1564,7 @@ const SplitPayment = (props) => {
};
let PostData = temppostdata;
(i === 0 && SplitSelPayMode[`PaymentStatus-${i}`] === 'F') ||
- (i === 0 && props.hasOwnProperty('TableBookingOrderId'))
+ (i === 0 && props.hasOwnProperty('TableBookingOrderId'))
? PutSplitPayment(i)
: i === 0
? Object.keys(ReportholdData)?.length > 0
@@ -1576,14 +1613,14 @@ const SplitPayment = (props) => {
}
setMessageData(
response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ ' ' +
+ (response?.data?.OrderDetails?.length > 0
+ ? response?.data?.OrderId &&
+ extractLastNumberOrderId(
+ response?.data?.OrderId,
+ response?.data?.OrderDetails?.[0]?.FYStatus
+ )
+ : '')
);
if (response?.data?.OrderDetails?.length > 0) {
setPrintOrderDetails([response?.data]);
@@ -1635,10 +1672,16 @@ const SplitPayment = (props) => {
if (response?.data?.statusCode == 1) {
setSalesOrderId(response?.data?.OrderId);
- const salesEditAmount = response?.data?.PaymentOrderDtl?.find(payment =>
- payment?.LastOrderTran === 'Y' && payment?.AdjustmentType &&
- payment?.AdjustmentType != null && payment?.AfterAdjustment && payment?.BeforeAdjustment && payment?.AfterAdjustment != null && payment?.BeforeAdjustment != null
- )
+ const salesEditAmount = response?.data?.PaymentOrderDtl?.find(
+ (payment) =>
+ payment?.LastOrderTran === 'Y' &&
+ payment?.AdjustmentType &&
+ payment?.AdjustmentType != null &&
+ payment?.AfterAdjustment &&
+ payment?.BeforeAdjustment &&
+ payment?.AfterAdjustment != null &&
+ payment?.BeforeAdjustment != null
+ );
setBeforeAdjAmount(salesEditAmount?.BeforeAdjustment || null);
setAfterAdjAmount(salesEditAmount?.AfterAdjustment || null);
setAdjustmentType(salesEditAmount?.AdjustmentType || null);
@@ -1677,14 +1720,14 @@ const SplitPayment = (props) => {
}
setMessageData(
response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ ' ' +
+ (response?.data?.OrderDetails?.length > 0
+ ? response?.data?.OrderId &&
+ extractLastNumberOrderId(
+ response?.data?.OrderId,
+ response?.data?.OrderDetails?.[0]?.FYStatus
+ )
+ : '')
);
if (response?.data?.OrderDetails?.length > 0) {
setPrintOrderDetails([response?.data]);
@@ -1722,7 +1765,13 @@ const SplitPayment = (props) => {
OrderId: props.hasOwnProperty('TableBookingOrderId')
? TableOrderId
: SalesOrderId,
- ...(i === 0 ? { SalesId: props.hasOwnProperty('TableBookingSalesId') ? TableSalesId : SalesOrderId } : {}),
+ ...(i === 0
+ ? {
+ SalesId: props.hasOwnProperty('TableBookingSalesId')
+ ? TableSalesId
+ : SalesOrderId,
+ }
+ : {}),
PaymentType:
SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi'
? SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pd'
@@ -1743,32 +1792,32 @@ const SplitPayment = (props) => {
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'card'
? SplitSelPayMode[`CardSelection-${i}`]
: SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'default'
+ 'default'
? 'PC'
: SplitSelPayMode[`UPISelection-${i}`],
ModeOfPayment:
SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
? PaymentUpiOptions?.find(
- (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
- )?.UPIDetailId
+ (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
+ )?.UPIDetailId
: null,
AccountDtl:
SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'default'
? useOptions?.[0]?.PaymentDetails?.Payatthecounter?.find(
- (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
- )
+ (upipay) => upipay?.Mode === SplitSelPayMode[`UPIMode-${i}`]
+ )
: (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pd') ||
- (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'card' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pd')
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pd') ||
+ (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'card' &&
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pd')
? useOptions?.[0]?.PaymentDetails?.PaymentDevice
: (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'pg') ||
- (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
- 'card' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pg')
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
+ 'pg') ||
+ (SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() ===
+ 'card' &&
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() === 'pg')
? useOptions?.[0]?.PaymentDetails?.PaymentGateway
: [],
PaymentStatus:
@@ -1777,8 +1826,8 @@ const SplitPayment = (props) => {
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'credit'
? 'S'
: SplitSelPayMode[`PaymentMode-${i}`]?.toLowerCase() === 'upi' &&
- SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
- 'default'
+ SplitSelPayMode[`UPISelection-${i}`]?.toLowerCase() ===
+ 'default'
? 'S'
: 'P',
Debit: 0,
@@ -1789,7 +1838,6 @@ const SplitPayment = (props) => {
BeforeAdjAmount: beforeAdjAmount || null,
AfterAdjAmount: afterAdjAmount || null,
AdjustmentType: adjustmentType || null,
-
};
let response = await dispatch(
@@ -1836,14 +1884,14 @@ const SplitPayment = (props) => {
}
setMessageData(
response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ ' ' +
+ (response?.data?.OrderDetails?.length > 0
+ ? response?.data?.OrderId &&
+ extractLastNumberOrderId(
+ response?.data?.OrderId,
+ response?.data?.OrderDetails?.[0]?.FYStatus
+ )
+ : '')
);
if (response?.data?.OrderDetails?.length > 0) {
setPrintOrderDetails([response?.data]);
@@ -1945,14 +1993,14 @@ const SplitPayment = (props) => {
});
setMessageData(
bookingpaymentupdate?.data?.response +
- ' ' +
- (bookingpaymentupdate?.data?.OrderDetails?.length > 0
- ? bookingpaymentupdate?.data?.OrderId &&
- extractLastNumberOrderId(
- bookingpaymentupdate?.data?.OrderId,
- bookingpaymentupdate?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ ' ' +
+ (bookingpaymentupdate?.data?.OrderDetails?.length > 0
+ ? bookingpaymentupdate?.data?.OrderId &&
+ extractLastNumberOrderId(
+ bookingpaymentupdate?.data?.OrderId,
+ bookingpaymentupdate?.data?.OrderDetails?.[0]?.FYStatus
+ )
+ : '')
);
if (bookingpaymentupdate?.data?.OrderDetails?.length > 0) {
setPrintOrderDetails([bookingpaymentupdate?.data]);
@@ -1970,7 +2018,7 @@ const SplitPayment = (props) => {
if (
Date.now() - startTime >
useOptions?.[0]?.PDConfigDetails?.[0]?.AutoCancelDurationInMinutes *
- 60000
+ 60000
) {
// 60,000 ms = 1 minute
@@ -2125,195 +2173,200 @@ const SplitPayment = (props) => {
}
return (
- <>
-
-
-
{
- SplitSelPayMode[`PaymentStatus-0`] !== 'S' && HandleModalClose();
- }}
- footer={false}
- width={1000}
- className={'splitpaymentModal'}
- children={
-
-
Total Amount : {safeRound(TotalAmount)}
-
- Remaining Balance : {TotalAmount - (isNaN(TotalSplitAmount) ? 0 : TotalSplitAmount)}
+
Loading... }>
+ <>
+
+
+
{
+ SplitSelPayMode[`PaymentStatus-0`] !== 'S' && HandleModalClose();
+ }}
+ footer={false}
+ width={1000}
+ className={'splitpaymentModal'}
+ children={
+
+
Total Amount : {safeRound(TotalAmount)}
+
+ Remaining Balance :{' '}
+ {TotalAmount -
+ (isNaN(TotalSplitAmount) ? 0 : TotalSplitAmount)}{' '}
+
- <>{calculateField()}>
- {TotalAmount > TotalSplitAmount &&
- SplitSelPayMode[`PaymentStatus-${count}`] === 'S' && (
-
-
-
{calculateField()}>
+ {TotalAmount > TotalSplitAmount &&
+ SplitSelPayMode[`PaymentStatus-${count}`] === 'S' && (
+
+ setCount(count + 1)}
- />
-
-
- )}
-
- }
- />
-
- {TotalAmount == 0 && Success && (
-
-
+ >
+
setCount(count + 1)}
+ />
+
+
+ )}
+
+ }
+ />
- )}
- {TotalAmount > 0 &&
- qrCode &&
- PaymentUpiOptions?.length > 0 &&
- SelUpiId && (
+ {TotalAmount == 0 && Success && (
+
+
+
+ )}
+ {TotalAmount > 0 &&
+ qrCode &&
+ PaymentUpiOptions?.length > 0 &&
+ SelUpiId && (
+
+
+
+ )}
+
+ {PaymentUpiOptions?.length > 0 && OrderId && (
)}
-
- {PaymentUpiOptions?.length > 0 && OrderId && (
-
-
-
- )}
- {PrintOrderDetails?.length > 0 &&
- PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
+ {PrintOrderDetails?.length > 0 &&
+ PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
+
+ ))}
+ {CreditCustomer && (
-
{
+ handleCreditCustomer('Cancel');
+ }}
+ handleOk={() => {
+ handleCreditCustomer('Submit');
+ }}
+ SplitPayAmount={SplitSelPayMode[`PayAmount-${count}`]}
/>
- ))}
- {CreditCustomer && (
-
-
{
- handleCreditCustomer('Cancel');
+ )}
+ {PrintOrderDetails?.length > 0 &&
+ (TokenOnly?.SettingValue === 'Y' ||
+ IndividualToken?.SettingValue === 'Y') &&
+ PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
+
+
+
+ ))}
+ {UpiOpen && (
+ {
+ Upimodel('Cancel');
}}
- handleOk={() => {
- handleCreditCustomer('Submit');
- }}
- SplitPayAmount={SplitSelPayMode[`PayAmount-${count}`]}
- />
-
- )}
- {PrintOrderDetails?.length > 0 &&
- (TokenOnly?.SettingValue === 'Y' ||
- IndividualToken?.SettingValue === 'Y') &&
- PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
-
-
-
- ))}
- {UpiOpen && (
-
{
- Upimodel('Cancel');
- }}
- footer={false}
- children={
-
-
-
-
-
-
-
-
RS :{CurrentPayAmount}
-
-
-
- {(selOption || SelCustId) && (
-
- Sent Payment Link
-
-
- )}
+ footer={false}
+ children={
+
-
}
- handleSubmit={() => {
- Upimodel('Submit');
+
+
+
+
+
+
RS :{CurrentPayAmount}
+
+
+
+ {(selOption || SelCustId) && (
+
+ Sent Payment Link
+
+
+ )}
+
+ >
+
}
+ handleSubmit={() => {
+ Upimodel('Submit');
+ }}
+ />
+
-
- }
- />
- )}
- {addcustomer && (
-
- )}
- >
+ }
+ />
+ )}
+ {addcustomer && (
+
+ )}
+ >
+
);
};
export default SplitPayment;
diff --git a/src/Pages/Product/ProductForm.jsx b/src/Pages/Product/ProductForm.jsx
index 2e979ab..1ee090d 100644
--- a/src/Pages/Product/ProductForm.jsx
+++ b/src/Pages/Product/ProductForm.jsx
@@ -85,6 +85,7 @@ import {
} from '../../Features/BrachLogin/BranchLogin.js';
import RackForm from '../Rack/RackForm.jsx';
import { isMobile } from 'react-device-detect';
+import BarCodeScan from '../../Services/BarCodeScan.jsx';
const subDirectory = import.meta.env.ENV_BASE_URL;
const ProductForm = ({ formType }) => {
@@ -818,12 +819,19 @@ const ProductForm = ({ formType }) => {
// dispatch(changeSetup_OfferValue(e?.target?.value))
};
const handleInput = async (val) => {
- if (val?.target?.value?.length >= 5) {
+ // normalize whether we receive an event (e.target.value) or a raw string
+ const inputVal = val && val.target && typeof val.target.value === 'string' ? val.target.value : val;
+ if (!inputVal) return;
+
+ if (inputVal.length >= 5) {
let QRCodeData = await dispatch(
- getQrcodeData({ QRCode: val?.target?.value })
+ getQrcodeData({ QRCode: inputVal })
).unwrap();
+
if (QRCodeData?.data?.statusCode == 0) {
- await setQrcodeFinalVal(val?.target?.value);
+ // valid & unique - update component state and the form field
+ setQrcodeFinalVal(inputVal);
+ formRef.current?.setFieldsValue({ QRCode: inputVal });
} else {
let existsQrcodeData = QRCodeData?.data?.data?.filter(
(item) =>
@@ -831,17 +839,18 @@ const ProductForm = ({ formType }) => {
item.CompId === CompId &&
item.BranchId === BranchId
);
+
if (existsQrcodeData?.length > 0) {
setQrcodeFinalVal(null);
formRef.current?.setFieldsValue({ QRCode: null });
setQrcodeExistsVal(existsQrcodeData?.[0]?.QRCode);
-
setMessageType('error');
setMessageData('Qrcode Already Exists');
} else {
setQrcodeExistsData(QRCodeData.data?.data);
setQrcodeExistsDataOpen(true);
- await setQrcodeFinalVal(val?.target?.value);
+ setQrcodeFinalVal(inputVal);
+ formRef.current?.setFieldsValue({ QRCode: inputVal });
setQrcodeAuto('N');
}
}
@@ -2685,11 +2694,19 @@ const ProductForm = ({ formType }) => {
autoComplete="off"
label="Scanner / AddQrcode"
onKeyPress={handleKeyPress}
+ value={QrcodeFinalVal}
valueData={QrcodeFinalVal}
isOnChange={QrcodeFinalVal ? true : false}
onChange={handleInput}
disabled={editstate?.QRCode ? true : false}
/>
+ {isMobile &&
+ {
+ handleInput(value);
+ }}
+ />
+ }
{QrcodeExistsVal && QrcodeExistsVal}
@@ -2904,6 +2921,7 @@ const ProductForm = ({ formType }) => {
autoComplete="off"
label="Scanner / AddOnePcQrcode"
onKeyPress={handleKeyPressSingle}
+ value={QrcodeSingleFinalVal}
valueData={QrcodeSingleFinalVal}
isOnChange={
QrcodeSingleFinalVal ? true : false
diff --git a/src/check.jsx b/src/check.jsx
index 941f1c0..dca963e 100644
--- a/src/check.jsx
+++ b/src/check.jsx
@@ -1,4608 +1,7758 @@
-import React, { useEffect, useState, useRef } from 'react';
-import { FaWhatsapp, FaPrint, FaParking, FaCartPlus } from 'react-icons/fa';
-import { useDispatch, useSelector } from 'react-redux';
-import { useNavigate } from 'react-router-dom';
+import React, {
+ lazy,
+ Suspense,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
-import { Badge, Popover, Modal, Tooltip } from 'antd';
-import { AiOutlineClose, AiOutlineArrowRight } from 'react-icons/ai';
-import { GiBasket } from 'react-icons/gi';
+import { Badge, Tooltip } from 'antd';
+import defaultimage from '../../../../Images/defaultItemImg.png';
+import FormHeader from '../../../PageComponents/FormHeader';
import {
- UpCircleOutlined,
- UpOutlined,
- TransactionOutlined,
-} from '@ant-design/icons';
-import {
- printDiv,
- extractLastNumberOrderId,
- encryptObject,
-} from '../../../../Services/Others';
-import PaymentPdfBooking from '../../../paymentpdfPage/PaymentPdfBooking';
-import { Messages } from '../../../../Components/Notifications/Messages';
-import { MdMoneyOff } from 'react-icons/md';
-import paygate from '../../../../Images/paygate.png';
-import defaultupi from '../../../../Images/defaultupi.png';
-import paydevice from '../../../../Images/paydevice.png';
-import paymentFailure from '../../../../Images/payment-failure2.png';
-import BSSummery1 from '../BSBillingTables/BSBillingTableSummery/BSSummery';
-import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
+ SelectedGlobalCardColorDetail,
+ SelectedGlobalCardFont,
+ StoredSessionData,
+ getTemplateData,
+} from '../../../../Features/ThemeChange/ThemeChange';
import { Tables } from '../../../../Components/Tables/Table';
-import QrComponent from '../BookingFunctionality/DynamicQr.jsx';
-import QrinScreen from '../BookingFunctionality/DynamicScreenQr.jsx';
-import { ArrowRightOutlined } from '@ant-design/icons';
-import Buttons from '../../../../Components/Forms/Buttons';
-import WpIcon from '../../../../Images/message.png';
-import '../../../../Styles/BookingScreen/Template/BSLayout7/BSC1Payment.scss';
-import '../../../../Styles/BookingScreen/Template/BSLayout7/CustomFloatMenu.scss';
-import PozoPreOrderIcon from '../UtillComponents/Pozo retail icons/PozoPreOrderIcon.jsx';
import {
+ GlobalProductSubCategorie,
+ GlobalItemCard,
+ getLayoutproductCard,
GlobalOrderCardDetails,
changeOrderCardDetails,
- GlobalCustId,
- PostBookingData,
- GlobalSelectedTableDetails,
+ changeSearchedData,
+ ChangeAllItemData,
+ GlobalAllItemData,
+ GlobalCardAccess,
+ getSelectedFavItems,
+ GlobalSelectedDatas,
+ GlobalEditfavItems,
+ GlobalAccessForOthers,
+ GlobalAlldat,
+ Globalothersdata,
+ GlobalProductCategorie,
+ getCardDataWithoutSub,
+ changeothersdata,
+ ChangeNewQrProduct,
+ GlobalWSProduct,
+ GlobalNewQrProduct,
GlobalBookingType,
- changeBookingType,
- getConfigType,
- PutBookingData,
+ GlobalSearchData,
+ getCardDataWithoutSubmodule,
+ changePreviousOrderLength,
+ changeHoldOrderDtl,
GlobalReorderHoldDetails,
- getUnpaidData,
- changeReorderHoldDetails,
- ChangeNavHoldData,
- GlobalReprintModal,
- changeSelectedTableDetails,
- GlobalNavHoldData,
- getPreferenceData,
- changeSelectedCustId,
- GlobalSelCustId,
- changeSelectedOption,
- GlobalSelOption,
- changeCustomerID,
- changeCompoPaymentIconStatus,
- getSalesDetailData,
- SendPaymentLink,
- changeSummeryTotalAmount,
- changeCreditFocus,
- changeUpiIDprint,
- GlobalSelectedCustDisable,
- changeSummeryTotalItems,
- changeSummeryQty,
- changeSummeryTotalWithoutTaxAmount,
- changeSummeryTotalTaxAmount,
- GlobalEstimateBooking,
- GlobalSelProdWiseEst,
- changeSelProdWiseEst,
- changeEstimateBooking,
- GlobalUpiIDprint,
- GlobalUpiIDName,
- GlobalUpiIDoptionId,
- GlobalBookingTypeBoth,
- changeSelectTable,
- changeSelectChair,
+ GlobalWeightScalePort,
+ GlobalWeightScaleWeight,
+ GlobalExpDateforHeight,
GlobalOrderType,
- changeReorderProductDetails,
- FeatureAddon,
- GlobalCommonPaymentOptions,
- PostPaymentdevice,
- changeUpiIDName,
- changeUpiIDoptionId,
- GetPaymentdeviceResponse,
- PutBookingPaymentStatusChange,
- changeCombosearch,
- GlobalCombosearch,
- Comboget,
+ GlobalReorderProductDetails,
+ getConfigType,
GlobalPayementloader,
- changePaymentloader,
- PaymentGatewayGetdetail,
- changePaymentTransactionNumber,
- Globalunpaidflow,
- changeunpaidflow,
- PutPendingPaymentList,
- changealldata,
+ GlobalPaymentTransactionNumber,
PreferenceData,
- changeOrderType,
- putSplitpaymentStatus,
- GlobalFailedTotalAmt,
- GlobalOverAllDiscEstimate,
- GlobalOverAllDiscSales,
- ChangeOverAllDiscSales,
- ChangeOverAllDiscEstimate,
- GlobalUnpaidListData,
- changeUnpaidData,
- getAllCustomer,
- GlobalBranchFinancialStatus,
- changeSummeryComboOfferAmount,
- changeTipAmount,
- GlobaltipAmount,
- GlobalFeatAddOnData,
- GlobalOtherServiceTicketClaim,
- changeOtherServiceTicketClaim,
- GlobalOtherSevices,
- changeOtherServices,
- changeComboRedirectionToDefaultLayoutForParking,
+ changeCardData,
+ GlobaldraggingComponent,
+ GlobalisAlphabeticFormat,
+ GlobalBtoBQuickProductTransfer,
+ changeBtoBQuickProductTransfer,
GlobalRetailWSSalesType,
- GlobalCurrentOrderId,
- changeCurrentOrderId,
- getCreditCustomer,
- ChangeSelectedCustDisable,
+ GlobalisFavClicked,
+ GlobalCategorieData,
+ GlobalSubcategorieData,
+ GlobalProductCardTrigger,
+ GlobalGetmultipleSearchDatas,
+ getmultipleSearch,
+ GlobalAllBookingType,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
-import { PrintStyleFunction } from '../../../paymentpdfPage/PrintStyleFunction.js';
import {
- gettinghold,
- globalholddata,
- changeholddata,
-} from '../../../../Features/BookingScreen/HoldOption/HoldOption';
-
-import {
- changetemplateData,
- SelectedPrintTemplate,
- StoredSessionData,
- GlobalprintDatas,
- GlobalPrinterMappingDtls,
- getPrinterMappingDetails,
- getPrintSelectionComponentData,
-} from '../../../../Features/ThemeChange/ThemeChange';
-import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities';
-import {
- globalExtraTotalAmount,
- ChangeTotalAmount,
-} from '../../../../Features/ExteraCharges/ExtraCharges';
-import {
- getAddCustomerDetails,
- GlobalAddCustomerDetails,
-} from '../../../../Features/BookingScreen/Customer/addCustomer';
-import BSCustomerSelect from '../UtillComponents/BSSelectCustomer.jsx';
-import PozoHoldIcon from '../UtillComponents/Pozo retail icons/PozoHoldIcon';
-import PozoDineInIcon from '../UtillComponents/Pozo retail icons/PozoDineIn.jsx';
-import PozoUnpaidIcon from '../UtillComponents/Pozo retail icons/PozoUnpaidIcon.jsx';
-import PozoBillIcon from '../UtillComponents/Pozo retail icons/PozoBIllIcon.jsx';
-import PozoTakeAway from '../UtillComponents/Pozo retail icons/PozoTakeAwayIcon';
-import PozoQuickAddIcon from '../UtillComponents/Pozo retail icons/PozoQuickAddIcon.jsx';
-import PozoReprintIcon from '../UtillComponents/Pozo retail icons/PozoReprintIcon';
-import PozoExtraChargesIcon from '../UtillComponents/Pozo retail icons/PozoExtraChargesIcon.jsx';
-import PozoAddCustomerIcon from '../UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
-import BsBillingCreditCustomer from '../BookingFunctionality/BSBillingCreditCustomer.jsx';
-import { TfiMoreAlt } from 'react-icons/tfi';
-import BSCreditCustomer from '../UtillComponents/BSCreditCustomer.jsx';
-import PozoAdvanceIcon from '../UtillComponents/Pozo retail icons/PozoAdvanceIcon.jsx';
-import { isMobile } from 'react-device-detect';
-import MobilePrint from '../BookingFunctionality/MobilePrint.jsx';
-import SplitPayment from '../BookingFunctionality/SplitPayment.jsx';
-import BSNavBarEstimate from '../UtillComponents/BSNavBarEst.jsx';
-import CountUp from 'react-countup';
-import BSNavBarPreOrder from '../UtillComponents/BSComboNavBarPreOrder.jsx';
-import { GlobalpreOrderOpen } from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
-import TokensinglePrint from '../../../paymentpdfPage/TokenOnlyPrints/TokeninsinglePrint.jsx';
-import SingleTokenMobilePrint from '../BookingFunctionality/SingleTokenMobilePrint.jsx';
-import IndividualTokenMobilePrint from '../BookingFunctionality/IndividualTokenMobilePrint.jsx';
-import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
-import {
- GlobalPreOrderPendingCount,
- PreOrderGet,
- changePreOrderPendingCount,
- changepreOrder,
- changePreOrderAdditem,
+ GlobalPreOrderAdditem,
+ GlobalPreOrderList,
+ GlobalpreOrderOpen,
changepreOrderList,
- changePreOrderCusName,
- changePreOrderCusMob,
- changePreOrderDate,
- changePreOrderTime,
- changePreOrderAdd1,
- changePreOrderAdd2,
- changePreOrderAdvance,
- changePreOrderzip,
- changePreOrderCity,
- changePreOrderDistrict,
- changePreOrderState,
-} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
-import PaymentFailedSales from '../../../Payment/PaymentFailedDetails/PaymentFailedSales.jsx';
-import PozoSplitPaymentIcon from '../UtillComponents/Pozo retail icons/PozoSplitPaymentIcon.jsx';
-import PozoFailedPaymentsIcon from '../UtillComponents/Pozo retail icons/PozoFailedPaymentsIcon.jsx';
+} from '../../../../Features/BookingScreen/PreOrder/PreOrder';
+import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
+import { Messages } from '../../../../Components/Notifications/Messages';
+import '../../../../Styles/BookingScreen/Components/BSItemCards/BSItemCard.scss';
+import WebFont from 'webfontloader';
+import FeaturesFunctionalities from '../BookingFunctionality/FeaturesFunctionalities';
+import { isMobile } from 'react-device-detect';
import {
- Global_CoupenCodeAmount,
- Global_loyaltyPointsDiscountAmount,
Global_OrderOfferDetail,
- Global_OverallOfferAmount,
- Global_SalesWiseOfferAmount,
-} from '../../../../Features/Offer/Offer.js';
-import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
-import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
-import BSNavBarOffer from '../UtillComponents/BSNavBarOffer/BSNavBarOffer.jsx';
-import { getEmpAccess } from '../../../../Features/AppPage/CenterPage.js';
-import { useAuth } from '../../../../AuthContext.jsx';
-import { GlobalBookingStatus } from '../../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
-import WhatsAppShare from '../../../WhatsAppShare/whatsAppShare.jsx';
-import CryptoJS from 'crypto-js';
-import SMSShare from '../../../WhatsAppShare/SmsShare.jsx';
-import { MdSms } from 'react-icons/md';
+ Global_PromoCodeOffers,
+} from '../../../../Features/Offer/Offer';
import {
- changeSalesPaymentoption,
- GlobalSalesPaymentoption,
-} from '../../../../Features/Payment/Paymentoptions/Paymentoptions.js';
-import Paymentoption from '../../../Payment/PaymentOptions/PaymentOptions.jsx';
-import BSTipAmount from '../UtillComponents/BSTipAmount.jsx';
+ DndContext,
+ useSensor,
+ useSensors,
+ PointerSensor,
+ TouchSensor,
+ closestCenter,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ arrayMove,
+ rectSortingStrategy,
+} from '@dnd-kit/sortable';
+import { v4 as uuidv4 } from 'uuid';
+
+import { useSortable } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import { MdOutlineAddShoppingCart } from 'react-icons/md';
+// Js Files
+import {
+ changeFreeProductForLoyalty,
+ ChangeFreeProductList,
+ ChangeFullFreeProductList,
+ changeFullOfferAppliedProducts,
+ ChangeOfferAppliedProducts,
+ changeOfferAppliedProductsForLoyalty,
+ changeTriggerOfferFree,
+ getOfferinBooking,
+ GlobalFreeProdList,
+ GlobalOfferAppliedProducts,
+ GlobalTriggerOfferFree,
+ RemoveOfferAppliedProduct,
+} from '../../../../Features/Offer/Offernew/BookingOffernew.js';
+import { ExtractDateFormate } from '../../../../Services/Others.js';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
-import BSOtherServiceClaim from '../UtillComponents/BSOtherServiceClaim.jsx';
-import { OtherServicesCardlistdata } from '../../../../Features/OtherServices/OtherServices.js';
-import { MobilePdfPrint } from '../BookingFunctionality/MobilePdfPrint.js';
-import { PublicQrCodepost } from '../../../../Features/ConfigMasterPage/ConfigMasterPage.js';
-import BSMembership from '../UtillComponents/BSMembership.jsx';
-import CardPopover from '../BSBillingTables/StandardTable/Utils/CardPopover.jsx';
-import UpiPopover from '../BSBillingTables/StandardTable/Utils/UpiPopOver.jsx';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';
-import { getPaymentOptionsData } from '../../../../Features/BookingScreen/BookingData/KioskBookingData.js';
-import CustomerOrders from '../BookingFunctionality/CustomerOrders.jsx';
+import { bulkpostdata } from '../../../../Features/ProductPage/ProductPage.js';
+// Jsx Files
+const VoiceToTextItemCard = lazy(
+ () => import('../../../VoiceToText/VoiceToTextItemCard.jsx')
+);
+const validateOffers = lazy(() => import('./ValidateOffer.jsx'));
+const AddProduct = lazy(
+ () => import('../../../../Components/AddProduct/AddProduct.jsx')
+);
+const ProductPriceChange = lazy(
+ () => import('../UtillComponents/ProductPriceChange.jsx')
+);
+const ExpireConfirmModal = lazy(
+ () => import('../BookingFunctionality/ExpireConfirmModal.jsx')
+);
+import { useSaleswiseOfferWatcher } from './SalesWiseOffer.jsx';
-const subDirectory = import.meta.env.ENV_BASE_URL;
-const MainHomeUrl = import.meta.env.ENV_MAIN_BASE_URL;
-const RetailApiurl = import.meta.env.ENV_API_URL;
-
-const currentDateValue = moment().format('YYYY-MM-DD HH:mm:ss');
-
-const BSC1Payment = (props) => {
- const isF4Pressed = useRef(false);
- const applyOffer = useApplyOfferto_CardDetail();
- const { SadminuserAccess } = useAuth();
- let SAAccessCommonMaster = SadminuserAccess?.find(
- (e) => e?.MenuName === 'Sales'
+export function SortableCard({ id, children, item }) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id });
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.5 : 1,
+ userSelect: 'none', // Prevents text selection during drag
+ // Add mobile-specific cursor and visual feedback
+ cursor: isMobile ? 'grab' : 'default',
+ // Add a subtle shadow for mobile to indicate draggability
+ boxShadow: isMobile && !isDragging ? '0 2px 4px rgba(0,0,0,0.1)' : 'none',
+ };
+ const draggingComponent = useSelector(GlobaldraggingComponent);
+ const allowDrag = draggingComponent === 'card';
+ return (
+
+ {children}
+
);
+}
- const dispatch = useDispatch();
- const navigate = useNavigate();
- const SessionData = useSelector(StoredSessionData);
- const BranchFinancialStatus = useSelector(GlobalBranchFinancialStatus);
- const globalTipAmount = useSelector(GlobaltipAmount);
- const OtherServiceTicketClaim = useSelector(GlobalOtherServiceTicketClaim);
- const RetailWSSalesType = useSelector(GlobalRetailWSSalesType);
- const BranchId = SessionData?.BranchId;
- const AppName = SessionData?.AppName;
- const AppId = SessionData?.AppId;
- const CompId = SessionData?.CompId;
- const UserId = SessionData?.UserId;
- const UserType = SessionData?.UserType;
- const AuthToken = SessionData?.AuthToken;
- const SessionMobileNo = SessionData?.SessionMobileNo;
- const [open, setOpen] = useState(false);
- const printerTemplateStyle = useSelector(SelectedPrintTemplate);
- const SelectedTableDetails = useSelector(GlobalSelectedTableDetails);
- const Custdisable = useSelector(GlobalSelectedCustDisable);
- const OrderCardDetail = useSelector(GlobalOrderCardDetails);
- const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
- const ReportholdData = useSelector(GlobalReorderHoldDetails);
- const ReprintModal = useSelector(GlobalReprintModal);
- const GetCustId = useSelector(GlobalCustId);
- const GlobalUpiID = useSelector(GlobalUpiIDprint);
- const SelCustId = useSelector(GlobalSelCustId);
- const selOption = useSelector(GlobalSelOption);
- const Holddata = useSelector(globalholddata);
- const BookingType = useSelector(GlobalBookingType);
- const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
- const OrderType = useSelector(GlobalOrderType);
- const GlobalAddCustomerDetails1 = useSelector(GlobalAddCustomerDetails);
- const SettingDataSelector = useSelector(PreferenceData);
- const GlobalSalesPaymentoptions = useSelector(GlobalSalesPaymentoption);
- const FeatureAddonData = useSelector(GlobalFeatAddOnData);
-
- const allowedNames = ['whatsapp', 'Print', 'SMS'];
-
- const filteredSettingNames = SettingDataSelector?.[0]?.['SettingDtlDetails']
- ?.filter(
- (item) =>
- allowedNames.includes(item?.SettingIdName) && item?.SettingValue === 'Y'
- )
- ?.map((item) => item?.SettingIdName);
-
+const BSItemCard = (props) => {
+ const cardFunction = props?.cardFunctionality;
+ // const applyOffer = useApplyOfferto_CardDetail();
+ const preferenceDatas = useSelector(PreferenceData, shallowEqual);
+ const { selectedDate } = useDateStore();
const preferenceOffer =
- SettingDataSelector?.[0]?.['SettingDtlDetails']?.find(
+ preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
(item) => item.SettingIdName === 'Offer'
)?.SettingValue === 'Y';
- const GlobalUpName = useSelector(GlobalUpiIDName);
- const GlobalUpiIDoptionIdd = useSelector(GlobalUpiIDoptionId);
- const NavHoldData = useSelector(GlobalNavHoldData);
- const GlobEstBooking = useSelector(GlobalEstimateBooking);
- const GlobProdwisedata = useSelector(GlobalSelProdWiseEst);
- const preOrder = useSelector(GlobalpreOrderOpen);
- const Comboglobal = useSelector(GlobalCombosearch);
- const FailedTotalAmt = useSelector(GlobalFailedTotalAmt);
- const OrderOfferDetail = useSelector(Global_OrderOfferDetail);
- const [SelectedUpiOption, setSelectedUpiOption] = useState();
- const [credit, setCredit] = useState(false);
- const [overAllBal, setOverAllBal] = useState(0);
- const [SelectedBookingType, setSelectedBookingType] = useState(null);
- const [TotalItems, setTotalItems] = useState('');
- const [showWhatsAppShare, setShowWhatsAppShare] = useState(false);
- const [showSMSShare, setSMSShare] = useState(false);
- const [TotalWithoutTaxAmount, setTotalWithoutTaxAmount] = useState('');
- const [TotalTaxAmount, setTotalTaxAmount] = useState('');
- const [Qty, setQty] = useState(null);
- const [formattedDate, setFormattedDate] = useState('');
- const [UpiOptionOpen, setUpiOptionOpen] = useState(false);
- const [customerPreviesOrders, setCustomerPreviesOrders] = useState(false);
- const [UpiOption, setUpiOption] = useState('');
- const [UpiId, setUpiId] = useState();
- const [hold, setHold] = useState(false);
- const appPreferences = useSelector(ApplicationPreferences);
- const commonModulePreference = appPreferences?.find(
- (preference) => preference?.PreferredCatName === 'Common Module'
- )?.PreferenceCatDetails;
- const sportsAppPreference = commonModulePreference?.find(
- (preference) => preference?.PreferredSubCatName === 'SportsApp'
- );
- 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 preferenceSingleSales =
+ preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'Single Booking Only'
+ )?.SettingValue === 'Y';
+ const AddProductCard =
+ preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
+ (item) => item.SettingIdName === 'AddProductCard'
+ )?.SettingValue === 'N';
+ // const AddCustomerDetails = useSelector(
+ // GlobalAddCustomerDetails,
+ // shallowEqual
+ // );
- const preferenceshortcutkey = SettingDataSelector?.[0]?.[
- 'SettingDtlDetails'
- ]?.some(
- (item) =>
- item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
- item.SettingValue === 'Y'
+ const offerAppliedProducts = useSelector(
+ GlobalOfferAppliedProducts,
+ shallowEqual
);
-
- const [addcustomer, setAddCustomer] = useState(false);
- const [PrintOrderDetails, setPrintOrderDetails] = useState([]);
- const tabledata = useSelector(GlobalUnpaidListData);
- const [FirstPaymentclick, setFirstPaymentclick] = useState(false);
- const [unpaidopen, setUnpaidOpen] = useState(false);
- const unpaidFlow = useSelector(Globalunpaidflow);
- const [messageType, setMessageType] = useState(null);
- const [messageData, setMessageData] = useState(null);
- const [reprint1, setReprint1] = useState(false);
- const [extraCharges, setExtraCharges] = useState(false);
- const [QuickAdd, setQuickAdd] = useState(false);
- const [DineInPreference, setDineInPreference] = useState({});
- const [UpinotSelected, setUpinotSelected] = useState(false);
- const [qrCode, setQrCode] = useState(false);
- const [paybtns, setpaybtns] = useState([]);
- const [CreditCustomer, setCreditCustomer] = useState(false);
- const [creditCustomerOpen, setcreditCustomerOpen] = useState(false);
- const [Success, SetSuccess] = useState();
- const [brachName, setbrachName] = useState('');
- const [UpiOpen, setUpiOpen] = useState(false);
- const [ConfigDataList, setConfigDataList] = useState([]);
- const BSComboData = props?.hasOwnProperty('optionNames')
- ? props['optionNames']
- : null;
- const BSComboNavbar =
- BSComboData?.BookingLayout?.[0] === 'Combo1'
- ? BSComboData?.BookingCombo1
- : BSComboData?.BookingCombo2;
- const OfferCheckedInSetup = BSComboNavbar?.[1]?.some(
- (some) => some.OptionName === 'Offer'
+ // const SelectedCust = useSelector(GlobalSelOption, shallowEqual);
+ const AllCategoryDatas = useSelector(GlobalCategorieData, shallowEqual);
+ const AllsubcatgoryDatas = useSelector(GlobalSubcategorieData, shallowEqual);
+ const RetailWSSalesType = useSelector(GlobalRetailWSSalesType, shallowEqual);
+ const ConfigDataList = useSelector(GlobalAllBookingType, shallowEqual);
+ const GPreOrderList = useSelector(GlobalPreOrderList, shallowEqual);
+ const [modelQty, setModelQty] = useState(false);
+ const [modelstock, setModelstock] = useState(false);
+ const [ModalVarient, setModalVarient] = useState(false);
+ const [QtyIndex, setQtyIndex] = useState(0);
+ const [VarientIndex, setVarientIndex] = useState(0);
+ const [prodexpir, setProdexpir] = useState(false);
+ const [initialRun, setInitialRun] = useState(false);
+ const [Item, setItem] = useState();
+ const [VarItem, setVarItem] = useState(0);
+ const [StockItem, setStockItem] = useState();
+ const [noSubcatCardData, setNoSubcatCardData] = useState();
+ const [qtydata, setQtydata] = useState();
+ const [products, setProducts] = useState([
+ { id: 1, name: '', price: '', code: '', size: '1', category: '' },
+ ]);
+ const PreOrderAdditem = useSelector(GlobalPreOrderAdditem, shallowEqual);
+ const OrderType = useSelector(GlobalOrderType, shallowEqual);
+ const ProdSubCat = useSelector(GlobalProductSubCategorie);
+ const ItemCard = useSelector(GlobalItemCard, shallowEqual);
+ const globaldata = useSelector(GlobalAlldat, shallowEqual);
+ const { action: quickBranchtoBranchTransfer, selectedProducts } = useSelector(
+ GlobalBtoBQuickProductTransfer
);
- const UomPrint = SettingDataSelector?.[0]?.SettingDtlDetails.filter(
- (i) => i.SettingIdName === 'PrintUom'
- )?.[0];
- const Estimation = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
- (item) => item.SettingIdName == 'Estimation'
+ const preOrder = useSelector(GlobalpreOrderOpen, shallowEqual);
+ const templateData = useSelector(getTemplateData, shallowEqual);
+ const temp5 = templateData?.BookingLayout?.[0] === 'Layout5';
+ const OfferCheckedInSetup = templateData?.BookingNavbar?.[1].some(
+ (item) => item?.OptionName == 'Offer'
);
- const ParkingDisplay = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
- (setting) =>
- setting?.SettingIdName?.toLowerCase() === 'parking' &&
- setting?.SettingValue === 'Y'
+ const globalAllItemdata = useSelector(GlobalAllItemData);
+ const EditfavItems = useSelector(GlobalEditfavItems);
+ const BookingType = useSelector(GlobalBookingType);
+ const ProductSearch = useSelector(GlobalSearchData);
+ const [SelectedProdNames, setSelectedProdNames] = useState(EditfavItems);
+ const [PreOrderSelectedProdNames, setPreOrderSelectedProdNames] = useState(
+ []
);
- const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
- (setting) =>
- setting?.SettingIdName?.toLowerCase() === 'mobilea4' &&
- setting?.SettingValue === 'Y'
+ const [newMoreProductModel, setNewMoreProductModel] = useState(false);
+ const CardAccess = useSelector(GlobalCardAccess, shallowEqual);
+ const globalAccessForOthers = useSelector(
+ GlobalAccessForOthers,
+ shallowEqual
);
- const Weightasquantity = SettingDataSelector?.[0]?.SettingDtlDetails?.some(
- (setting) =>
- setting?.SettingIdName?.toLowerCase() === 'weightasquantity' &&
- setting?.SettingValue === 'Y'
+ const SelectedCardColor = useSelector(
+ SelectedGlobalCardColorDetail,
+ shallowEqual
);
- const [OrderStatus, setOrderStatus] = useState(true);
- // const [FeatureAddonData, setFeatureAddonData] = useState([]);
- const [Splitpayment, setSplitpayment] = useState(false);
- const [urlData, setUrlData] = useState();
- const [PaymentOptions, setPaymentOptions] = useState([]);
- const [paybtnselected, setPaybtnselected] = useState();
- const [Paybtnnameselected, setPaybtnnameselected] = useState();
- const [OtherServiceStatus, setOtherServiceStatus] = useState(false);
- const allowDecimal = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
+ const GetmultipleSearchDatas = useSelector(
+ GlobalGetmultipleSearchDatas,
+ shallowEqual
+ );
+ const SelectedCardFont = useSelector(SelectedGlobalCardFont, shallowEqual);
+ const CartOrderDetails = useSelector(GlobalOrderCardDetails, shallowEqual);
+ const SelectedDatas = useSelector(GlobalSelectedDatas, shallowEqual);
+ const otherscarddata = useSelector(Globalothersdata, shallowEqual);
+ const WSProductdata = useSelector(GlobalWSProduct, shallowEqual);
+ const NewQrProductData = useSelector(GlobalNewQrProduct, shallowEqual);
+ const ReportholdData = useSelector(GlobalReorderHoldDetails, shallowEqual);
+ const ReorderProductData = useSelector(
+ GlobalReorderProductDetails,
+ shallowEqual
+ );
+ const WeightScalePort = useSelector(GlobalWeightScalePort, shallowEqual);
+ const WeightScaleWeight = useSelector(GlobalWeightScaleWeight, shallowEqual);
+ const PaymentTransactionNumber = useSelector(
+ GlobalPaymentTransactionNumber,
+ shallowEqual
+ );
+ const OverAllproductBasedOfferDatas = useSelector(
+ (state) => state?.BookingOFferNew?.OverAllProductBasedProducts,
+ shallowEqual
+ );
+ const PromoCodeOffersDatas = useSelector(
+ Global_PromoCodeOffers,
+ shallowEqual
+ );
+ const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find(
(setting) =>
setting?.SettingIdName?.toLowerCase() === 'decimal' &&
setting?.SettingValue === 'Y'
);
- const Custombill = SettingDataSelector?.[0]?.SettingDtlDetails?.some(
- (setting) =>
- setting?.SettingIdName?.toLowerCase() === 'customisedbillnumber' &&
- setting?.SettingValue === 'Y'
+ const [messageType, setMessageType] = useState(null);
+ const [messageData, setMessageData] = useState(null);
+ const [repeatedModel, setRepeatedModel] = useState(false);
+ const [StockPreferenceDetail, setStockPreferenceDetail] = useState();
+ const [QuickAdd, setQuickAdd] = useState(true);
+ const [onePeiceFlow, setOnePeiceFlow] = useState(false);
+ const [BillOrderPre, setBillOrderPre] = useState();
+ const [qtyExpData, setQtyExpData] = useState();
+ const OrderOfferDetail = useSelector(Global_OrderOfferDetail);
+ // const [freeProductsOffers, setfreeProductsOffers] = useState([]);
+ const [screenWidth, setScreenWidth] = useState(window.innerWidth);
+ // const [screenHeight, setScreenHeight] = useState(window.innerHeight);
+ const ProdCat = useSelector(GlobalProductCategorie, shallowEqual);
+ const paymentloader = useSelector(GlobalPayementloader, shallowEqual);
+ const SessionData = useSelector(StoredSessionData, shallowEqual);
+ const AppId = SessionData?.AppId;
+ const CompId = SessionData?.CompId;
+ const BranchId = SessionData?.BranchId;
+ const UserId = SessionData?.UserId;
+ const dispatch = useDispatch();
+
+ const voiceTriggerRef = useRef(null);
+ const scrollContainerRef = useRef(null);
+ const isDragging = useRef(false);
+ const startX = useRef(0);
+ const scrollLeft = useRef(0);
+ const itemListScrollRef = useRef(null);
+ const [selectedBrand, setSelectedBrand] = useState('Others');
+ const [showLeftButton, setShowLeftButton] = useState(false);
+ const [showRightButton, setShowRightButton] = useState(false);
+ const [ExpiredProduct, setExpiredProduct] = useState();
+
+ const alphabeticFormat = useSelector(GlobalisAlphabeticFormat);
+ // const PricingAppPricingName = useSelector(GlobalPricingAppPricingName);
+ const favouriteCat = useSelector(GlobalisFavClicked, shallowEqual);
+ const FreeProdList = useSelector(GlobalFreeProdList);
+ const triggerOfferFree = useSelector(GlobalTriggerOfferFree);
+ const productCardTrigger = useSelector(GlobalProductCardTrigger);
+ const appPreferences = useSelector(ApplicationPreferences);
+ const [expireModal, setExpireModal] = useState({
+ open: false,
+ title: '',
+ onOk: null,
+ onCancel: null,
+ });
+
+ 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 [SelectedCardOption, setSelectedCardOption] = useState(null);
- const [SelectedUPIPayOption, setSelectedUPIPayOption] = useState('Default');
- const [CardOptionOpen, setCardOptionOpen] = useState(false);
- const [CardoptionnotSelected, setCardoptionnotSelected] = useState(false);
- const [PaymentgatewayCard, setPaymentgatewayCard] = useState([]);
- const [PaymentDeviceCard, setPaymentDeviceCard] = useState([]);
- const [PaymentgatewayUPI, setPaymentgatewayUPI] = useState([]);
- const [PaymentDeviceUPI, setPaymentDeviceUPI] = useState([]);
- const [UpiPayOption, setUpiPayOption] = useState([]);
- const [CardPayOption, setCardPayOption] = useState([]);
- const [PaymentUpiOptions, setPaymentUpiOptions] = useState([]);
- const GlobaluseOptions = useSelector(GlobalCommonPaymentOptions);
- const [useOptions, setuseOptions] = useState([]);
- const CheckOrderType = OrderCardDetail?.filter(
- (a) => a?.BookingTypeName !== BookingType
+
+ const SingleMember = salespagefields?.find(
+ (type) =>
+ type?.PreferredSubCatName?.toLowerCase() === 'single member' &&
+ type?.PreferredStatus === 'Y'
);
- // const [ComboDropDown, setComboDropDown] = useState();
- const paymentloader = useSelector(GlobalPayementloader);
- const TokenOnly = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
- (i) => i.SettingIdName === 'TokenOnly'
- )?.[0];
- const IndividualToken = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
- (i) => i.SettingIdName === 'AllProductindividualToken'
- )?.[0];
- const [UnpaidConfirmation, setUnpaidConfirmation] = useState(false);
- const [unpaidselectedindex, setunpaidselectedindex] = useState();
- const [preOrderOpen, setPreOrderOpen] = useState(false);
- const preOrderPendingCount = useSelector(GlobalPreOrderPendingCount);
- const [failedOrderData, setFailedOrderData] = useState();
- const [OpenFailData, SetOpenFailData] = useState(false);
- const [paymentfeataddon, setpaymentfeataddon] = useState(false);
- const [isFloatMenuOpen, setIsFloatMenuOpen] = useState(false);
- const OverAllSales = useSelector(GlobalOverAllDiscSales);
- const OverAllEstimate = useSelector(GlobalOverAllDiscEstimate);
- const [blink, setBlink] = useState(false);
- const [empData, setEmpData] = useState();
- const [MobileNoWhatsApp, setMobileNoWhatsApp] = useState();
- const printDatas = useSelector(GlobalprintDatas);
- const PrinterDetails = useSelector(GlobalPrinterMappingDtls);
- const [addnewAccess, setaddnewAccess] = useState(true);
- const BookingStatus = useSelector(GlobalBookingStatus);
- const PaymentOptionsModeName =
- PaymentOptions?.find((e) => e.ModeDefault?.toUpperCase() === 'Y')
- ?.ModeName || PaymentOptions?.[0]?.ModeName;
- const PaymentOptionsModeId =
- PaymentOptions?.find((e) => e.ModeDefault?.toUpperCase() === 'Y')?.ModeId ||
- PaymentOptions?.[0]?.ModeId;
+ useSaleswiseOfferWatcher();
- const CheckBookingStatus =
- BookingStatus?.find((item) => item.ScreenType === 'Booking')
- ?.ScreenStatus ?? 'Open';
- const OverallOfferAmount = useSelector(Global_OverallOfferAmount);
+ const TakAwayId = ConfigDataList?.find(
+ (a) => a?.ConfigName === 'TakeAway'
+ )?.ConfigId;
- const [TotalAmount, setTotalAmount] = useState(0);
- // for customised invoice number
- const { invoiceDate, clearInvoiceDate } = useDateStore();
- const CurrentOrderId = useSelector(GlobalCurrentOrderId);
+ const DineinId = ConfigDataList?.find(
+ (a) => a?.ConfigName === 'Dine In'
+ )?.ConfigId;
- console.log(BSComboData, 'BSComboData');
- const canHold =
- unpaidFlow === false &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- OrderCardDetail?.length !== 0 &&
- CheckOrderType?.length === 0 &&
- OrderType !== 'Failed' &&
- CheckBookingStatus !== 'Close' &&
- !addnewAccess &&
- BSComboData?.BookingBilling?.[1]?.some(
- (e) => e?.OptionName?.toLowerCase() == 'hold'
- );
- const canRecall =
- unpaidFlow === false &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- OrderCardDetail?.length == 0 &&
- OrderType !== 'Failed' &&
- Holddata?.length > 0 &&
- CheckBookingStatus !== 'Close' &&
- !addnewAccess &&
- BSComboData?.BookingBilling?.[1]?.some(
- (e) => e?.OptionName?.toLowerCase() == 'hold'
- );
-
- const canExtracharge =
- BSComboNavbar?.[1]?.some(
- (e) => e?.OptionName?.toLowerCase() == 'extracharge'
- ) && OrderCardDetail?.length !== 0;
- const canSplitPayment =
- paybtns?.length > 1 &&
- OrderCardDetail?.length > 0 &&
- CheckBookingStatus !== 'Close' &&
- !addnewAccess;
-
- console.log(canSplitPayment, 'canSplitPayment');
- const canReprint = BSComboNavbar?.[1]?.some(
- (e) => e?.OptionName?.toLowerCase() == 'reprint'
- );
- console.log(
- BSComboData?.BookingBilling?.[1]?.some(
- (e) => e?.OptionName?.toLowerCase() == 'hold'
- ),
- '11111111111111'
- );
- // Usage
useEffect(() => {
- const fetchCreditCustomer = async () => {
- const selectedMode = paybtns?.find(
- (pay) => paybtnselected === pay?.ModeId
- )?.ModeName;
+ itemListScrollRef.current?.scrollTo(0, 0);
+ }, [ProdCat, ProdSubCat, favouriteCat]);
- if (
- selectedMode?.toLowerCase() === 'credit' &&
- (!UpinotSelected || !CardoptionnotSelected)
- ) {
- setCredit(true);
- try {
- const res = await dispatch(
- getCreditCustomer({
- CompId,
- AppId,
- BranchId,
- CustId: selOption?.CustId,
- })
- ).unwrap();
+ useEffect(() => {
+ if (
+ triggerOfferFree &&
+ CartOrderDetails?.length > 0 &&
+ FreeProdList?.length > 0
+ ) {
+ console.log('Before call');
+ let { ModifiedData, UpdatedFreeProdList, AppliedOffers } =
+ handleLoyaltyFreeProducts(CartOrderDetails, FreeProdList);
+ console.log(
+ 'After call',
+ ModifiedData,
+ UpdatedFreeProdList,
+ AppliedOffers
+ );
+ console.log(AppliedOffers, 'AppliedOffers');
+ dispatch(changeOrderCardDetails(ModifiedData));
+ dispatch(ChangeFullFreeProductList(UpdatedFreeProdList));
+ dispatch(changeFullOfferAppliedProducts(AppliedOffers));
+ dispatch(changeTriggerOfferFree(false));
+ }
+ }, [triggerOfferFree]);
- if (res?.data?.statusCode === 1 && res?.data?.data?.length > 0) {
- setOverAllBal(res.data.data[0]?.OverAllBal ?? 0);
- } else {
- setOverAllBal(0);
+ function handleLoyaltyFreeProducts(orderCardDtls, freeProdDtls) {
+ if (!freeProdDtls || freeProdDtls.length === 0) {
+ return {
+ ModifiedData: orderCardDtls,
+ UpdatedFreeProdList: freeProdDtls,
+ AppliedOffers: [],
+ };
+ }
+
+ const updatedFreeProdList = JSON.parse(JSON.stringify(freeProdDtls)); // deep copy
+ const AppliedOffers = [];
+ let ModifiedData = [];
+ let processedItems = new Set(); // Track processed items
+
+ // Helper function to create applied offer object
+ function createAppliedOffer(
+ freeProduct,
+ usedQty,
+ inwardDtlId,
+ orderRate,
+ bookingType
+ ) {
+ const stockDetail =
+ freeProduct.ProdVariantDetails?.[0]?.StockDetails?.[0];
+
+ return {
+ OfferId: freeProduct.OfferId,
+ OfferAmount: usedQty * orderRate,
+ OfferMode: freeProduct.OfferMode,
+ ActualOfferAmount: usedQty * orderRate,
+ OfferValue: usedQty * orderRate,
+ TableName: freeProduct.TableName || 'LoyaltyPointsNew',
+ TableUniqueName: freeProduct.TableUniqueName || 'FreeProduct',
+ TableUniqueId: '',
+ ActualFreeQty: usedQty,
+ Detail: [],
+ OfferCode: '',
+ CustId: freeProduct.CustId || '',
+ UsedCount: (stockDetail?.ProdLoyaltyPoint || 0) * usedQty,
+ AppliesTo: '',
+ BookingType: bookingType === 'Dine In' ? 'DineinId' : 'TakAwayId',
+ FreeProductsList: {
+ FreeProdId: freeProduct.FreeProdId,
+ FreeQty: usedQty,
+ FreeProdName: freeProduct.FreeProdName,
+ ProdVariantDetails: [
+ {
+ FreeProdVariantName: freeProduct.FreeProdVariantName,
+ StockDetails: [
+ {
+ ProdOfferId: stockDetail?.ProdOfferId || '',
+ FreeInwardDtlId: inwardDtlId,
+ ActiveStatus: 'A',
+ ProdLoyaltyPoint: stockDetail?.ProdLoyaltyPoint || '',
+ },
+ ],
+ },
+ ],
+ },
+ ProdId: '',
+ SinglePc: 'N',
+ StockAvailable: 'N',
+ ProdVariantName: '',
+ Type: '',
+ InwardDtlId: '',
+ ProdCat: '',
+ HalfPrice: 'N',
+ MinQty: '',
+ };
+ }
+
+ // First, handle existing paid products that can be converted to free
+ updatedFreeProdList.forEach((freeProduct) => {
+ if (freeProduct.RemainingQty > 0) {
+ // Find matching paid products by InwardDtlId
+ const matchingPaidItems = orderCardDtls.filter(
+ (item) =>
+ freeProduct.ProdVariantDetails?.some((variant) =>
+ variant.StockDetails?.some(
+ (stock) => stock.FreeInwardDtlId === item.InwardDtlId
+ )
+ ) &&
+ (!item.Offer || item.Offer === 0) &&
+ !item.OfferType &&
+ !item.OfferMode &&
+ !processedItems.has(item.localId) &&
+ item?.SinglePc !== 'Y'
+ );
+
+ matchingPaidItems.forEach((paidItem) => {
+ const remainingFreeQty = freeProduct.RemainingQty;
+
+ if (remainingFreeQty <= 0) return;
+
+ if (paidItem.OrderQty === remainingFreeQty) {
+ // Remove paid item and convert entire quantity to free
+ const freeItem = {
+ ...paidItem,
+ Offer: paidItem.OrderQty * paidItem.OrderRate,
+ OfferType: freeProduct.OfferMode,
+ OfferMode: freeProduct.OfferMode,
+ OfferMessage: [
+ {
+ OfferId: freeProduct.OfferId,
+ FreeQty: paidItem.OrderQty,
+ FreeProdId: freeProduct.FreeProdId,
+ FreeProdName: freeProduct.FreeProdName,
+ },
+ ],
+ localId: paidItem.localId + '_converted_free',
+ };
+
+ ModifiedData.push(freeItem);
+
+ // Update free product usage
+ freeProduct.FreeQty =
+ (freeProduct.FreeQty || 0) + paidItem.OrderQty;
+ freeProduct.RemainingQty -= paidItem.OrderQty;
+
+ // Create applied offer
+ AppliedOffers.push(
+ createAppliedOffer(
+ freeProduct,
+ paidItem.OrderQty,
+ paidItem.InwardDtlId,
+ paidItem.OrderRate,
+ paidItem.BookingTypeName
+ )
+ );
+
+ processedItems.add(paidItem.localId);
+ } else if (paidItem.OrderQty > remainingFreeQty) {
+ // Split: convert available free qty to free, keep excess as paid
+ const freeQty = remainingFreeQty;
+ const paidQty = paidItem.OrderQty - remainingFreeQty;
+
+ // Create free item
+ const freeItem = {
+ ...paidItem,
+ OrderQty: freeQty,
+ TotalAmt: freeQty * paidItem.OrderRate,
+ TaxAmt: (
+ (freeQty * paidItem.OrderRate * paidItem.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ freeQty * paidItem.OrderRate -
+ (freeQty * paidItem.OrderRate * paidItem.TaxPercentage) / 100,
+ Offer: freeQty * paidItem.OrderRate,
+ OfferType: freeProduct.OfferMode,
+ OfferMode: freeProduct.OfferMode,
+ OfferMessage: [
+ {
+ OfferId: freeProduct.OfferId,
+ FreeQty: freeQty,
+ FreeProdId: freeProduct.FreeProdId,
+ FreeProdName: freeProduct.FreeProdName,
+ },
+ ],
+ localId: paidItem.localId + '_free_part',
+ };
+
+ // Create updated paid item with reduced quantity
+ const updatedPaidItem = {
+ ...paidItem,
+ OrderQty: paidQty,
+ TotalAmt: paidQty * paidItem.OrderRate,
+ TaxAmt: (
+ (paidQty * paidItem.OrderRate * paidItem.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ paidQty * paidItem.OrderRate -
+ (paidQty * paidItem.OrderRate * paidItem.TaxPercentage) / 100,
+ localId: paidItem.localId + '_paid_part',
+ };
+
+ ModifiedData.push(freeItem);
+ ModifiedData.push(updatedPaidItem);
+
+ // Update free product usage
+ freeProduct.FreeQty = (freeProduct.FreeQty || 0) + freeQty;
+ freeProduct.RemainingQty -= freeQty;
+
+ // Create applied offer
+ AppliedOffers.push(
+ createAppliedOffer(
+ freeProduct,
+ freeQty,
+ paidItem.InwardDtlId,
+ paidItem.OrderRate,
+ paidItem.BookingTypeName
+ )
+ );
+
+ processedItems.add(paidItem.localId);
}
- } catch (error) {
- console.error('Credit fetch failed', error);
- setOverAllBal(0);
- }
- } else {
- setCredit(false);
- setOverAllBal(0);
+ });
}
- };
+ });
- fetchCreditCustomer();
- }, [paybtnselected, selOption, paybtns]);
- useEffect(() => {
- if (!preOrder) {
- const totalSum = OrderCardDetail?.reduce(
- (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0),
- 0
- );
+ // Process remaining cart items
+ orderCardDtls.forEach((item) => {
+ // Skip if already processed
+ if (processedItems.has(item.localId)) {
+ return;
+ }
- const extra = GlobalExtraCharge?.reduce(
- (acc, obj) => acc + (obj.TotalAmt || 0),
- 0
- );
+ // Check if item is currently marked as free (has OfferType/OfferMode and Offer > 0)
+ const isCurrentlyFree =
+ item.Offer > 0 && (item.OfferType || item.OfferMode);
- let withComboSum = 0;
- const withComboOffer_CardDetail = OrderCardDetail?.filter(
- (item) => item.Type === 'C'
- );
- if (withComboOffer_CardDetail?.length > 0) {
- withComboSum = formatAmount(
- withComboOffer_CardDetail.reduce(
- (acc, card) =>
- acc +
- parseFloat(card.OrderRate * card.OrderQty - card.TotalAmt || 0),
- 0
+ if (isCurrentlyFree) {
+ // Find matching free product by InwardDtlId
+ const matchingFreeProduct = updatedFreeProdList.find((freeProd) =>
+ freeProd.ProdVariantDetails?.some((variant) =>
+ variant.StockDetails?.some(
+ (stock) => stock.FreeInwardDtlId === item.InwardDtlId
+ )
)
);
- }
- let Total =
- extra === undefined
- ? totalSum - OverallOfferAmount - withComboSum
- : totalSum + extra - OverallOfferAmount - withComboSum;
+ if (matchingFreeProduct) {
+ const availableFreeQty = matchingFreeProduct.OverAllFreeQty || 0;
- // Subtract OtherServiceTicketClaim?.totalTicketamount if present and > 0
- if (OtherServiceTicketClaim?.TotalAmt > 0) {
- if (Total - OtherServiceTicketClaim.TotalAmt > 0) {
- Total -= OtherServiceTicketClaim.TotalAmt;
- } else {
- dispatch(
- changeOtherServiceTicketClaim({
- TicketId: null,
- TotalAmt: 0,
- ParkingClaimed: false,
- ServiceCategory: null,
- })
- );
- }
- } else if (OtherServiceTicketClaim?.OtherType == 'Remove') {
- dispatch(
- changeOtherServiceTicketClaim({
- TicketId: null,
- TotalAmt: 0,
- ParkingClaimed: false,
- ServiceCategory: null,
- })
- );
- }
+ if (item.OrderQty > availableFreeQty) {
+ // Split: Keep available free qty as free, convert excess to paid
+ const excessQty = item.OrderQty - availableFreeQty;
- let withdiscTotal =
- Total - ((OverAllSales || 0) + (OverAllEstimate || 0));
+ // Create free portion (if any free qty available)
+ if (availableFreeQty > 0) {
+ const freeItem = {
+ ...item,
+ OrderQty: availableFreeQty,
+ TotalAmt: availableFreeQty * item.OrderRate,
+ TaxAmt: (
+ (availableFreeQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ availableFreeQty * item.OrderRate -
+ (availableFreeQty * item.OrderRate * item.TaxPercentage) /
+ 100,
+ Offer: availableFreeQty * item.OrderRate,
+ };
- setTotalAmount(
- withdiscTotal >= 0
- ? (Number(withdiscTotal) + Number(globalTipAmount)).toFixed(2)
- : (Number(Total) + Number(globalTipAmount)).toFixed(2)
- );
+ ModifiedData.push(freeItem);
- dispatch(
- changeSummeryTotalAmount(
- withdiscTotal > 0 ? withdiscTotal : Number(Total)
- )
- );
-
- dispatch(changeSummeryComboOfferAmount(withComboSum));
-
- // if (withdiscTotal <= 0) {
- // dispatch(ChangeOverAllDiscSales(0));
- // dispatch(ChangeOverAllDiscEstimate(0));
- // }
- } else {
- setTotalAmount(0);
- dispatch(changeSummeryTotalAmount(0));
- dispatch(changeSummeryComboOfferAmount(0));
- }
- }, [
- OrderCardDetail,
- GlobalExtraCharge,
- OverAllSales,
- OverAllEstimate,
- globalTipAmount,
- OtherServiceTicketClaim,
- ]);
- useEffect(() => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- UserId: UserId,
- };
- dispatch(getPrinterMappingDetails(data)).unwrap();
- const Data1 = { AppId, CompId, BranchId };
- dispatch(getPrintSelectionComponentData(Data1)).unwrap();
- handleOtherData();
- }, []);
- useEffect(() => {
- if (!preferenceshortcutkey) return;
-
- const handleKeyPress = (event) => {
- if (!event.altKey) return;
-
- const key = event.key.toLowerCase();
-
- switch (key) {
- case 'n':
- event.preventDefault();
- setQuickOpen();
- break;
-
- case 'w':
- event.preventDefault();
- if (canHold) {
- AddBookingDetails('Hold');
- } else if (canRecall) {
- HandleholdModelOpen();
- }
- break;
-
- case 'a':
- if (canExtracharge) {
- event.preventDefault();
- handleextraCharges();
- }
- break;
-
- case 'r':
- if (canReprint) {
- event.preventDefault();
- handleReprint();
- }
- break;
-
- case 's':
- if (canSplitPayment) {
- event.preventDefault();
- SplitPaymentOpen();
- }
- break;
-
- default:
- break;
- }
- };
-
- window.addEventListener('keydown', handleKeyPress);
- return () => {
- window.removeEventListener('keydown', handleKeyPress);
- };
- }, [
- preferenceshortcutkey,
- canHold,
- canRecall,
- canExtracharge,
- canSplitPayment,
- ]);
-
- useEffect(() => {
- if (NavHoldData) {
- AddBookingDetails('Hold');
- }
- }, [NavHoldData]); //change by karthiga
- //mohan stoped data
- useEffect(() => {
- if (
- (BookingType === 'Dine In' ||
- BookingTypeBoth ||
- CheckOrderType?.length > 0) &&
- !unpaidFlow
- ) {
- setOrderStatus(true);
- } else {
- setOrderStatus(false);
- }
- }, [BookingTypeBoth, BookingType, unpaidFlow]);
- //mohan end
- const paymentFailedStatusFun = async () => {
- SetOpenFailData(!OpenFailData);
- };
- // useEffect(() => {
- // const handleKeyPress = (event) => {
- // if (event.shiftKey && event.code === 'KeyM') {
- // if (
- // document.activeElement.tagName !== 'INPUT' &&
- // document.activeElement.tagName !== 'TEXTAREA'
- // ) {
- // event.preventDefault();
- // setBlink(true);
- // }
- // }
- // };
- // const handleClickOutside = (event) => {
- // setBlink(false);
- // };
- // window.addEventListener('keydown', handleKeyPress);
- // window.addEventListener('mousedown', handleClickOutside);
- // return () => {
- // window.removeEventListener('keydown', handleKeyPress);
- // window.addEventListener('mousedown', handleClickOutside);
- // };
- // }, []);
-
- const handleOtherData = async () => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- };
- let response = await dispatch(OtherServicesCardlistdata(data)).unwrap();
- if (response?.data?.statusCode == 1) {
- setOtherServiceStatus(true);
- } else {
- setOtherServiceStatus(false);
- }
- };
-
- useEffect(() => {
- if (SelCustId) {
- setpaybtns(PaymentOptions);
- } else {
- const withoutCustomer = PaymentOptions?.filter?.(
- (item) => item?.ModeName?.toLowerCase() !== 'credit'
- );
- setpaybtns(withoutCustomer);
- }
- }, [PaymentUpiOptions, PaymentOptions, SelCustId]);
-
- useEffect(() => {
- if (CompId && BranchId && AppId) {
- getHolddata();
- getUnpaiddatas();
- getCustomerData();
- }
- }, [CompId, BranchId, AppId]);
-
- useEffect(() => {
- gettodaydate();
- getBookingTypeId();
- getPaymentOptionFeature();
- getPreferenceDinein();
-
- // Combodata();
- BadgePendingApi();
- // if (UserType === "Employee") {
- // fetchApi()
- // }
- }, []);
- useEffect(() => {
- if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
- getFeatureAddonData();
- }
- }, [FeatureAddonData]);
- useEffect(() => {
- if (UserType === 'Employee') {
- fetchApi();
- }
- }, [UserType]);
- useEffect(() => {
- let hasAccess = false;
-
- if (UserType === 'Admin' || UserType === 'Super Admin') {
- hasAccess = true;
- } else if (UserType === 'Employee') {
- hasAccess = empData?.AddAccess === 'Y';
- } else if (UserType === 'Super Admin User') {
- hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
- }
-
- setaddnewAccess(!hasAccess);
- }, [empData, SAAccessCommonMaster, UserType]);
- useEffect(() => {
- getBookingTypeId();
- }, [BookingType, BookingTypeBoth]);
-
- useEffect(() => {
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- ExtraCharges: GlobalExtraCharge,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- }, [GlobalExtraCharge]);
- useEffect(() => {
- if (
- OrderCardDetail?.length === 1 &&
- OrderCardDetail?.[0]?.OrderQty === 1 &&
- !SelCustId
- ) {
- console.log(OrderCardDetail, 'OrderCardDetail');
- closePrintOption();
- setPrintOrderDetails([]);
- }
- }, [OrderCardDetail]);
- useEffect(() => {
- TotalItemsCalculation();
- TotalWithoutTaxRate();
- TotalTaxAmt();
- OrderCardDetail?.length == 0 ? dispatch(changeunpaidflow(false)) : '';
- }, [OrderCardDetail]);
- useEffect(() => {
- let data = selOption != null ? selOption : GetCustId;
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- customer: data,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- }, [selOption, GetCustId]);
- useEffect(() => {
- let data = GlobalUpiID;
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- upi: data,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- setUpiOption(GlobalUpName);
- setSelectedUpiOption(GlobalUpiIDoptionIdd);
- setUpiId(GlobalUpiID);
- }, [GlobalUpiID]);
- useEffect(() => {
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- paymentMethod: Paybtnnameselected,
- Paymentgateway: false,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- }, [Paybtnnameselected]);
- useEffect(() => {
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- }, [PaymentOptions]);
- // useEffect(() => {
- // if (
- // PrintOrderDetails?.length > 0 &&
- // (!filteredSettingNames ||
- // filteredSettingNames?.includes('Print') ||
- // filteredSettingNames?.length === 0) &&
- // ((!filteredSettingNames?.includes('whatsapp') &&
- // (!isMobile || !filteredSettingNames?.includes('SMS'))) ||
- // ((filteredSettingNames?.includes('whatsapp') ||
- // (isMobile && filteredSettingNames?.includes('SMS'))) &&
- // (!MobileNoWhatsApp || Object.keys(MobileNoWhatsApp).length === 0)))
- // ) {
- // handlePrintOrToken();
- // }
- // }, [PrintOrderDetails]);
-
- useEffect(() => {
- if (!PrintOrderDetails?.length) return;
-
- const selectedOptions = filteredSettingNames || [];
- const count = selectedOptions.length;
-
- if (count === 0) {
- handlePrintOrToken();
- return;
- }
- if (count === 1) {
- const option = selectedOptions[0];
-
- switch (option) {
- case 'whatsapp':
- if (!selOption && MobileNoWhatsApp?.value) {
- handleWhatsAppClick();
- } else {
- handlePrintOrToken();
- }
- return;
-
- case 'SMS':
- if (isMobile) handleSMSClick();
- else handlePrintOrToken();
- return;
-
- case 'Print':
- handlePrintOrToken();
- return;
-
- // case "Email":
- // handleEmailClick();
- // return;
-
- default:
- return;
- }
- }
- return;
- }, [PrintOrderDetails]);
-
- useEffect(() => {
- getPaymentOptionFeature();
- }, [GlobaluseOptions]);
- const formatAmount = (value) => {
- return allowDecimal
- ? parseFloat(value || 0).toFixed(2)
- : parseInt(value || 0);
- };
- const handlePrintOrToken = async () => {
- const dinein =
- PrintOrderDetails?.[0]?.OrderDetails?.[0]?.productDetails?.some(
- (product) => product.BookingTypeName === 'Dine In'
- );
- const Tokenthere =
- PrintOrderDetails?.[0]?.OrderDetails?.[0]?.productDetails?.some(
- (product) => product.TokenAvailable === 'Y'
- );
- const PrintLogo = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
- (i) => i.SettingIdName === 'PrintLogo'
- )?.[0];
- const PrintGreeting = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
- (i) => i.SettingIdName === 'PrintGreetings'
- )?.[0];
- const preferenceDetails = SettingDataSelector?.[0]?.SettingDtlDetails;
- if (isMobile) {
- if (MobileA4Print) {
- await MobileMultiPdfPrintTrigger({
- preferenceDetails,
- printerTemplateStyle,
- printDatas,
- PrinterDetails,
- PrintOrderDetails,
- SessionData,
- bookingTypePreference,
- });
- } else {
- if (Tokenthere && TokenOnly?.SettingValue === 'Y' && !dinein) {
- if (IndividualToken?.SettingValue === 'Y' && !dinein) {
- IndividualTokenMobilePrint(PrintOrderDetails, UpiId, 'Booking');
- closePrintOption();
- } else {
- SingleTokenMobilePrint(PrintOrderDetails, UpiId, 'Booking');
- closePrintOption();
- }
- } else {
- MobilePrint(
- appPreferences,
- PrintOrderDetails,
- UpiId,
- 'Booking',
- SettingDataSelector
- );
- closePrintOption();
- }
- }
- } else {
- if (Tokenthere && TokenOnly?.SettingValue === 'Y' && !dinein) {
- AllProductTokenFunction();
- } else {
- Print();
- }
- }
- };
-
- const handleWhatsAppClick = () => {
- setShowWhatsAppShare(true);
- };
- const handleSMSClick = () => {
- setSMSShare(true);
- };
-
- //dhana
- // Function to check if the button is active
- const isButtonActive = () => {
- const baseCondition =
- FirstPaymentclick === false &&
- OrderCardDetail?.length > 0 &&
- paybtnselected &&
- CheckBookingStatus !== 'Close';
- let accessCondition = true;
- if (UserType === 'Employee') {
- accessCondition = empData?.AddAccess === 'Y';
- } else if (UserType === 'Super Admin User') {
- accessCondition = SAAccessCommonMaster?.AddAccess === 'Y';
- }
- return baseCondition && accessCondition;
- };
-
- // Function to handle the button click
- const handleButtonClick = () => {
- if (qrCode && SelectedUPIPayOption === 'Default') {
- UpiPayment();
- } else {
- OrderStatus
- ? AddBookingDetails('Dine-In', false)
- : AddBookingDetails(BookingType, true);
- }
- };
-
- useEffect(() => {
- const handleKeyPress = (event) => {
- if (event.key === 'F4' && isButtonActive() && !isF4Pressed.current) {
- isF4Pressed.current = true;
- // BranchFinancialStatus==='N'? financialYearError():
- handleButtonClick();
- setTimeout(() => {
- isF4Pressed.current = false; // Reset after a short delay
- }, 1000);
- }
- };
-
- window.addEventListener('keydown', handleKeyPress);
- return () => {
- window.removeEventListener('keydown', handleKeyPress);
- };
- }, [
- FirstPaymentclick,
- OrderCardDetail,
- paybtnselected,
- OrderStatus,
- qrCode,
- SelectedUPIPayOption,
- TotalAmount,
- SelectedUpiOption,
- SelectedCardOption,
- ]);
-
- //dhana
- const fetchApi = async () => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- EmpId: UserId,
- };
- let response = await dispatch(getEmpAccess(data)).unwrap();
- let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
- (item) => item.ConfigName === 'Sales'
- );
- setEmpData(datas?.[0]);
- };
- const getCustomerData = async () => {
- await dispatch(
- getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId })
- );
- await dispatch(
- getAddCustomerDetails({
- CompId: CompId,
- AppId: AppId,
- branchId: BranchId,
- })
- );
- };
- const getPaymentOptionFeature = async () => {
- const FiltersalesPayment = GlobaluseOptions?.filter(
- (item) => item.FlowName?.toLowerCase() === 'sales'
- );
- setuseOptions(FiltersalesPayment);
- const filterpaycounter = FiltersalesPayment?.[0]?.OptionDetails?.filter(
- (item) => item?.OptionName?.toLowerCase() === 'pay at the counter'
- );
- const filterpaymentgateway = FiltersalesPayment?.[0]?.OptionDetails?.filter(
- (item) => item?.OptionName?.toLowerCase() === 'payment gateway'
- );
- const filterpaymentdevice = FiltersalesPayment?.[0]?.OptionDetails?.filter(
- (item) => item?.OptionName?.toLowerCase() === 'payment device'
- );
- const cardinpaymentgateway =
- filterpaymentgateway?.[0]?.ModeDetails?.filter((item) =>
- item?.ModeName?.toLowerCase()?.includes('card')
- ) || [];
- const cardinpaymentdevice =
- filterpaymentdevice?.[0]?.ModeDetails?.filter((item) =>
- item?.ModeName?.toLowerCase()?.includes('card')
- ) || [];
- const upiinpaymentgateway =
- filterpaymentgateway?.[0]?.ModeDetails?.filter((item) =>
- item?.ModeName?.toLowerCase()?.includes('upi')
- ) || [];
- const upiinpaymentdevice =
- filterpaymentdevice?.[0]?.ModeDetails?.filter((item) =>
- item?.ModeName?.toLowerCase()?.includes('upi')
- ) || [];
-
- setPaymentOptions(filterpaycounter?.[0]?.ModeDetails);
- setPaymentUpiOptions(
- FiltersalesPayment?.[0]?.PaymentDetails?.Payatthecounter
- );
- setPaymentDeviceCard(cardinpaymentdevice);
- setPaymentgatewayCard(cardinpaymentgateway);
- setPaymentgatewayUPI(upiinpaymentgateway);
- setPaymentDeviceUPI(upiinpaymentdevice);
- const cardoptions = [];
- if (cardinpaymentgateway?.length > 0) {
- cardoptions.push({
- label: 'Payment Gateway',
- value: 'PG',
- imgSrc: paygate,
- });
- }
- if (cardinpaymentdevice?.length > 0) {
- cardoptions.push({
- label: 'Payment Device',
- value: 'PD',
- imgSrc: paydevice,
- });
- }
- setCardPayOption(cardoptions);
- const options = [];
-
- if (FiltersalesPayment?.[0]?.PaymentDetails?.Payatthecounter?.length > 0) {
- options.push({
- label: 'Personal UPI',
- value: 'Default',
- imgSrc: defaultupi,
- });
- }
-
- if (upiinpaymentgateway?.length > 0) {
- options.push({ label: 'Payment Gateway', value: 'PG', imgSrc: paygate });
- }
-
- if (upiinpaymentdevice?.length > 0) {
- options.push({ label: 'Payment Device', value: 'PD', imgSrc: paydevice });
- }
- setUpiPayOption(options);
- // }
- };
-
- const getFeatureAddonData = async () => {
- // let featureAddon = await dispatch(
- // FeatureAddon({ AppId: AppId, UserId: UserId })
- // ).unwrap();
- // if (featureAddon?.data?.statusCode === 1) {
- // setFeatureAddonData(featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]);
- const hasPaymentFeatures = FeatureAddonData?.FeatureDtls?.some(
- (item) =>
- item.FeatureAddonName === 'Payment Gateway' ||
- item.FeatureAddonName === 'Payment Device'
- );
- setpaymentfeataddon(hasPaymentFeatures);
- // } else {
- // setFeatureAddonData([]);
- // setpaymentfeataddon([]);
- // }
- };
- const handlePaymentMode = (id, name) => {
- if (name?.toLowerCase() !== 'credit') {
- setOverAllBal(0);
- setCredit(false);
- }
- if (paymentloader === false) {
- setPaybtnselected(id);
- setPaybtnnameselected(name);
- if (CardPayOption?.length === 1) {
- setSelectedCardOption(CardPayOption?.[0]?.value);
- }
- setUpiOptionOpen(false);
- setQrCode(false);
- setUpinotSelected(false);
- setCardoptionnotSelected(false);
- }
- };
-
- const AddCardOption = (data) => {
- setSelectedCardOption(data);
- setCardOptionOpen(false);
- setCardoptionnotSelected(false);
- };
- const AddUPIPaymentOption = async (data) => {
- setSelectedUpiOption('');
- setUpiOption('');
- setUpiId('');
- await dispatch(changeUpiIDprint(null));
- await dispatch(changeUpiIDName(''));
- await dispatch(changeUpiIDoptionId(null));
- setSelectedUPIPayOption(data);
- setUpinotSelected(false);
- setCardoptionnotSelected(false);
- if (data !== 'Default') {
- setUpiOptionOpen(false);
- }
- };
- const addUpiOption = async (id, name, UPIId) => {
- await dispatch(changeUpiIDprint(UPIId));
- await dispatch(changeUpiIDName(name));
- await dispatch(changeUpiIDoptionId(id));
- setSelectedUpiOption(id);
- setUpiOption(name);
- setUpiId(UPIId);
- setUpinotSelected(false);
- setCardoptionnotSelected(false);
- // setQrCode(true)
- };
- const handleUPIButtonClick = (id, name) => {
- if (paymentloader === false) {
- setPaybtnnameselected(name);
- setPaybtnselected(id);
- let brachName1 = PaymentUpiOptions?.[0]?.BrName;
- setbrachName(brachName1);
- if (UpiPayOption?.length === 1) {
- setSelectedUPIPayOption(UpiPayOption?.[0]?.value);
- if (UpiPayOption?.[0]?.value?.toLowerCase() === 'default') {
- if (PaymentUpiOptions?.length === 1) {
- addUpiOption(
- PaymentUpiOptions?.[0]?.Mode,
- PaymentUpiOptions?.[0]?.ModeName,
- PaymentUpiOptions?.[0]?.UPIId
- );
- }
- }
- }
-
- setQrCode(true);
- SetSuccess(true);
- }
- };
- const EnableUpiOptions = () => {
- setUpiOptionOpen(!UpiOptionOpen);
- };
- const EnableCardOptions = () => {
- setCardOptionOpen(!CardOptionOpen);
- };
- const gettodaydate = () => {
- const currentDate = new Date();
- const day = String(currentDate.getDate()).padStart(2, '0');
- const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Month is 0-based, so we add 1.
- const year = currentDate.getFullYear();
-
- const tempformattedDate = `${year}-${month}-${day}`;
- setFormattedDate(tempformattedDate);
- };
- const getPreferenceDinein = async () => {
- // const response = await dispatch(
- // getPreferenceData({ CompId: CompId, BranchId: BranchId, AppId: AppId })
- // ).unwrap();
- // if (response?.data?.statusCode === 1) { //comment by karthiga
- const PreferenceDineDtl = SettingDataSelector?.[0]?.SettingDtlDetails;
- const DineinPreference = PreferenceDineDtl.find(
- (item) => item.SettingIdName === 'DineIn'
- );
- setDineInPreference(DineinPreference || {});
- // } else {
- // setDineInPreference();
- // }
- };
- const ChangeTakeAway = async () => {
- await dispatch(changeBookingType('TakeAway'));
- };
- const getBookingTypeId = async () => {
- let tempconfigdata = await dispatch(
- getConfigType({ TypeName: 'Booking Type' })
- ).unwrap();
-
- if (tempconfigdata?.data?.statusCode == 1) {
- setConfigDataList(tempconfigdata?.data?.data);
- let configdata = tempconfigdata?.data?.data;
- let checkName = BookingTypeBoth ? 'DineIn,TakeAway' : BookingType;
-
- let filterconfigdata = configdata?.find(
- (a) => a?.ConfigName === checkName
- );
- setSelectedBookingType(filterconfigdata?.ConfigId);
- }
- };
-
- const TokenPrint = async (index) => {
- try {
- console.log(`Starting token print for index ${index}`);
-
- const stylePrint = ``;
- if (TokenOnly?.SettingValue === 'Y') {
- if (IndividualToken?.SettingValue === 'Y') {
- await printDiv(`TokenOnlySingle${index}`, stylePrint);
- } else {
- await printDiv(`TokenOnlyMultiple${index}`, stylePrint);
- }
- } else {
- await printDiv(`TakeawayToken${index}`, stylePrint);
- }
- } catch (error) {
- console.error(`Error printing token for index ${index}:`, error);
- }
- };
- const AllProductTokenFunction = async () => {
- if (IndividualToken?.SettingValue === 'Y') {
- await Promise.all(
- PrintOrderDetails?.[0]?.OrderDetails?.map(
- async (orderDetail, index) => {
- const groupedTokens = orderDetail?.productDetails?.reduce(
- (acc, item, idx) => {
- if (item.TokenAvailable === 'Y') {
- if (!item.CounterName) {
- // If CounterName is null or empty
- acc[`single-${idx}-${item.ProdId}`] = [item]; // Unique entry for each null/empty CounterName item
- } else {
- if (!acc[item.CounterName]) {
- acc[item.CounterName] = [];
- }
- acc[item.CounterName].push(item); // Group by CounterName
- }
- }
- return acc;
- },
- {}
- );
-
- // Iterate over grouped tokens and print them
- const tokensToPrint = Object.entries(groupedTokens).map(
- async ([counterName, items], idx) => {
- // Use the counterName (or unique identifier for individual items) as part of the tokenId
- const tokenId = `${idx}-${items?.[0]?.ProdId}-${counterName}`;
- await TokenPrint(tokenId, items); // Pass all grouped items to the print function
- }
- );
- if (tokensToPrint?.length > 0) {
- await Promise.all(tokensToPrint);
+ // Create applied offer
+ AppliedOffers.push(
+ createAppliedOffer(
+ matchingFreeProduct,
+ availableFreeQty,
+ item.InwardDtlId,
+ item.OrderRate,
+ item.BookingTypeName
+ )
+ );
}
- setPrintOrderDetails([]);
- closePrintOption();
- }
- )
- );
- } else {
- await Promise.all(
- PrintOrderDetails?.[0]?.OrderDetails?.map(
- async (orderDetail, index) => {
- await TokenPrint(`${index}-${orderDetail?.OrderId}`);
- }
- )
- );
- setPrintOrderDetails([]);
- closePrintOption();
- }
- };
- const getHolddata = async () => {
- const data = { CompId: CompId, BranchId: BranchId, AppId: AppId };
- let response = await dispatch(gettinghold(data)).unwrap();
- if (response?.data?.statusCode == 1) {
- dispatch(changeholddata(response?.data?.data));
- } else {
- dispatch(changeholddata([]));
- }
- };
- const getUnpaiddatas = async () => {
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- };
- await dispatch(getUnpaidData(data)).unwrap();
- };
+ // Handle excess quantity - look for existing paid item in original cart
+ const existingPaidItem = orderCardDtls.find(
+ (cartItem) =>
+ cartItem.InwardDtlId === item.InwardDtlId &&
+ cartItem.localId !== item.localId &&
+ (!cartItem.Offer || cartItem.Offer === 0) &&
+ !cartItem.OfferType &&
+ !cartItem.OfferMode
+ );
- const TotalItemsCalculation = async () => {
- let tempTotalitems = OrderCardDetail?.length;
- let OverAllQty = OrderCardDetail?.reduce((acc, item) => {
- const isWeightScale = item?.ScaleType === 'weight';
+ if (
+ existingPaidItem &&
+ !processedItems.has(existingPaidItem.localId)
+ ) {
+ // Merge excess with existing paid item
+ const mergedPaidItem = {
+ ...existingPaidItem,
+ OrderQty: existingPaidItem.OrderQty + excessQty,
+ TotalAmt:
+ (existingPaidItem.OrderQty + excessQty) * item.OrderRate,
+ TaxAmt: (
+ ((existingPaidItem.OrderQty + excessQty) *
+ item.OrderRate *
+ item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ (existingPaidItem.OrderQty + excessQty) * item.OrderRate -
+ ((existingPaidItem.OrderQty + excessQty) *
+ item.OrderRate *
+ item.TaxPercentage) /
+ 100,
+ };
- if (isWeightScale) {
- return (
- acc + (Weightasquantity ? Math.round(Number(item?.OrderQty || 0)) : 1)
- );
- }
+ ModifiedData.push(mergedPaidItem);
+ processedItems.add(existingPaidItem.localId); // Mark as processed
+ } else {
+ // Create new paid item for excess quantity
+ const paidItem = {
+ ...item,
+ OrderQty: excessQty,
+ TotalAmt: excessQty * item.OrderRate,
+ TaxAmt: (
+ (excessQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ excessQty * item.OrderRate -
+ (excessQty * item.OrderRate * item.TaxPercentage) / 100,
+ Offer: 0,
+ OfferType: undefined,
+ OfferMode: undefined,
+ OfferMessage: undefined,
+ localId: item.localId + '_paid',
+ };
- return acc + Math.round(Number(item?.OrderQty || 0));
- }, 0);
- setTotalItems(tempTotalitems);
- setQty(OverAllQty);
- };
- const Print = async () => {
- const style = await PrintStyleFunction(
- printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle,
- 'Sales'
- );
+ ModifiedData.push(paidItem);
+ }
+ } else if (availableFreeQty > 0) {
+ // All quantity can remain free
+ const isAlreadyExists = ModifiedData?.findIndex(
+ (data) =>
+ data?.OfferMode === item?.OfferMode &&
+ data?.InwardDtlId === item?.InwardDtlId &&
+ data?.ProdId === item?.ProdId &&
+ data?.OfferMessage?.[0]?.OfferId ===
+ item?.OfferMessage?.[0]?.OfferId
+ );
- const stylesMap = {
- 'Style 1': 'PrintStyle1',
- 'Style 2': 'PrintStyle2',
- 'Style 3': 'PrintStyle3',
- 'Style 4': 'PrintStyle4',
- 'Style 5': 'PrintStyle5',
- 'Style 6': 'PrintStyle6',
- 'Style 7': 'PrintStyle7',
- 'Style 8': 'PrintStyle8',
- 'Style 9': 'PrintStyle9',
- 'Style 10': 'PrintStyle10',
- 'Style 11': 'PrintStyle11',
- 'Style 12': 'PrintStyle12',
- 'Style 13': 'RePrint',
- A4: 'PrintStyleA4',
- A5: 'PrintStyleA5',
- A4Standard: 'A4Standard',
- TaxInvoice: 'TaxInvoice',
- };
+ if (isAlreadyExists !== -1) {
+ // Merge with existing free item
+ ModifiedData[isAlreadyExists] = {
+ ...ModifiedData[isAlreadyExists],
+ OrderQty:
+ ModifiedData[isAlreadyExists].OrderQty + item.OrderQty,
+ TotalAmt:
+ (ModifiedData[isAlreadyExists].OrderQty + item.OrderQty) *
+ item.OrderRate,
+ TaxAmt: (
+ ((ModifiedData[isAlreadyExists].OrderQty + item.OrderQty) *
+ item.OrderRate *
+ item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ (ModifiedData[isAlreadyExists].OrderQty + item.OrderQty) *
+ item.OrderRate -
+ ((ModifiedData[isAlreadyExists].OrderQty + item.OrderQty) *
+ item.OrderRate *
+ item.TaxPercentage) /
+ 100,
+ Offer:
+ (ModifiedData[isAlreadyExists].OrderQty + item.OrderQty) *
+ item.OrderRate,
+ };
+ } else {
+ // Create new free item
+ const newFreeItem = {
+ ...item,
+ TotalAmt: item.OrderQty * item.OrderRate,
+ TaxAmt: (
+ (item.OrderQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ item.OrderQty * item.OrderRate -
+ (item.OrderQty * item.OrderRate * item.TaxPercentage) / 100,
+ Offer: item.OrderQty * item.OrderRate,
+ };
- const selectedStyle =
- stylesMap[
- printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
- ];
+ ModifiedData.push(newFreeItem);
+ }
- if (selectedStyle) {
- await Promise.all(
- PrintOrderDetails?.[0]?.OrderDetails?.map(
- async (orderDetail, index) => {
- await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print
- if (orderDetail?.BookingTypeName !== 'Dine In') {
- const groupedTokens = orderDetail?.productDetails?.reduce(
- (acc, item, idx) => {
- if (item.TokenAvailable === 'Y') {
- if (!item.CounterName) {
- // If CounterName is null or empty
- acc[`individual-${idx}-${item.ProdId}`] = [item]; // Unique entry for each null/empty CounterName item
- } else {
- if (!acc[item.CounterName]) {
- acc[item.CounterName] = [];
- }
- acc[item.CounterName].push(item); // Group by CounterName
- }
- }
- return acc;
+ const appliedOfferAlreadyExists = AppliedOffers.findIndex(
+ (offer) =>
+ offer?.FreeProductsList?.FreeProdId ===
+ matchingFreeProduct?.FreeProdId &&
+ offer?.TableName === matchingFreeProduct?.TableName &&
+ offer?.TableUniqueName ===
+ matchingFreeProduct?.TableUniqueName &&
+ offer?.OfferId === matchingFreeProduct?.OfferId &&
+ offer?.OfferMode === matchingFreeProduct?.OfferMode &&
+ offer?.FreeProductsList?.ProdVariantDetails?.[0]
+ ?.StockDetails?.[0]?.FreeInwardDtlId === item?.InwardDtlId
+ );
+
+ if (appliedOfferAlreadyExists !== -1) {
+ AppliedOffers[appliedOfferAlreadyExists] = {
+ ...AppliedOffers[appliedOfferAlreadyExists],
+ ActualOfferAmount:
+ AppliedOffers[appliedOfferAlreadyExists].ActualOfferAmount +
+ item.OrderQty * item.OrderRate,
+ ActualFreeQty:
+ AppliedOffers[appliedOfferAlreadyExists].ActualFreeQty +
+ item.OrderQty,
+ OfferAmount:
+ (AppliedOffers[appliedOfferAlreadyExists].ActualFreeQty +
+ item.OrderQty) *
+ item.OrderRate,
+ OfferValue:
+ (AppliedOffers[appliedOfferAlreadyExists].ActualFreeQty +
+ item.OrderQty) *
+ item.OrderRate,
+ UsedCount:
+ (matchingFreeProduct?.ProdVariantDetails?.[0]
+ ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0) *
+ (AppliedOffers[appliedOfferAlreadyExists].ActualFreeQty +
+ item.OrderQty),
+ FreeProductsList: {
+ ...AppliedOffers[appliedOfferAlreadyExists].FreeProductsList,
+ FreeQty:
+ AppliedOffers[appliedOfferAlreadyExists].FreeProductsList
+ .FreeQty + item.OrderQty,
},
- {}
+ };
+ } else {
+ // Create applied offer
+ AppliedOffers.push(
+ createAppliedOffer(
+ matchingFreeProduct,
+ item.OrderQty,
+ item.InwardDtlId,
+ item.OrderRate,
+ item.BookingTypeName
+ )
);
-
- // Iterate over grouped tokens and print them
- const tokensToPrint = Object.entries(groupedTokens).map(
- async ([counterName, items], idx) => {
- // Use the counterName (or unique identifier for individual items) as part of the tokenId
- const tokenId = `${idx}-${items?.[0]?.ProdId}-${counterName}`;
- await TokenPrint(tokenId, items); // Pass all grouped items to the print function
- }
- );
- if (tokensToPrint?.length > 0) {
- await Promise.all(tokensToPrint);
- }
}
- }
- )
- );
+ } else {
+ // No free quantity available, convert to paid
+ const paidItem = {
+ ...item,
+ Offer: 0,
+ OfferType: undefined,
+ OfferMode: undefined,
+ OfferMessage: undefined,
+ TotalAmt: item.OrderQty * item.OrderRate,
+ TaxAmt: (
+ (item.OrderQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ item.OrderQty * item.OrderRate -
+ (item.OrderQty * item.OrderRate * item.TaxPercentage) / 100,
+ };
- setPrintOrderDetails([]);
- closePrintOption();
- }
+ ModifiedData.push(paidItem);
+ }
+ } else {
+ // No matching free product found, convert to paid
+ const paidItem = {
+ ...item,
+ Offer: 0,
+ OfferType: undefined,
+ OfferMode: undefined,
+ OfferMessage: undefined,
+ };
+
+ ModifiedData.push(paidItem);
+ }
+ } else {
+ // Item is not currently free, check if it can become free
+ const matchingFreeProduct = updatedFreeProdList.find(
+ (freeProd) =>
+ freeProd.ProdVariantDetails?.some((variant) =>
+ variant.StockDetails?.some(
+ (stock) => stock.FreeInwardDtlId === item.InwardDtlId
+ )
+ ) && freeProd.RemainingQty > 0
+ );
+
+ if (matchingFreeProduct) {
+ const availableFreeQty = Math.min(
+ item.OrderQty,
+ matchingFreeProduct.RemainingQty
+ );
+
+ if (availableFreeQty > 0) {
+ // Create free item for available free quantity
+ const freeItem = {
+ ...item,
+ OrderQty: availableFreeQty,
+ TotalAmt: availableFreeQty * item.OrderRate,
+ TaxAmt: (
+ (availableFreeQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ availableFreeQty * item.OrderRate -
+ (availableFreeQty * item.OrderRate * item.TaxPercentage) / 100,
+ Offer: availableFreeQty * item.OrderRate,
+ OfferType: matchingFreeProduct.OfferMode,
+ OfferMode: matchingFreeProduct.OfferMode,
+ OfferMessage: [
+ {
+ OfferId: matchingFreeProduct.OfferId,
+ FreeQty: availableFreeQty,
+ FreeProdId: matchingFreeProduct.FreeProdId,
+ FreeProdName: matchingFreeProduct.FreeProdName,
+ },
+ ],
+ localId: item.localId + '_free',
+ };
+
+ ModifiedData.push(freeItem);
+
+ // Update free product usage
+ matchingFreeProduct.FreeQty =
+ (matchingFreeProduct.FreeQty || 0) + availableFreeQty;
+ matchingFreeProduct.RemainingQty -= availableFreeQty;
+
+ // Create applied offer
+ AppliedOffers.push(
+ createAppliedOffer(
+ matchingFreeProduct,
+ availableFreeQty,
+ item.InwardDtlId,
+ item.OrderRate,
+ item.BookingTypeName
+ )
+ );
+
+ // If there's remaining paid quantity
+ if (item.OrderQty > availableFreeQty) {
+ const paidQty = item.OrderQty - availableFreeQty;
+ const paidItem = {
+ ...item,
+ OrderQty: paidQty,
+ TotalAmt: paidQty * item.OrderRate,
+ TaxAmt: (
+ (paidQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate:
+ paidQty * item.OrderRate -
+ (paidQty * item.OrderRate * item.TaxPercentage) / 100,
+ };
+
+ ModifiedData.push(paidItem);
+ }
+ } else {
+ // No free quantity available, keep as paid
+ ModifiedData.push(item);
+ }
+ } else {
+ // No matching free product or no remaining free quantity
+ ModifiedData.push(item);
+ }
+ }
+
+ processedItems.add(item.localId);
+ });
+
+ return {
+ ModifiedData,
+ UpdatedFreeProdList: updatedFreeProdList,
+ AppliedOffers,
+ };
+ }
+
+ const openExpireModal = ({ title, onOk, onCancel }) => {
+ setExpireModal({
+ open: true,
+ title,
+ onOk,
+ onCancel,
+ });
};
+ const closeExpireModal = () => {
+ setExpireModal((prev) => ({ ...prev, open: false }));
+ };
+
+ async function getOffers() {
+ await dispatch(
+ getOfferinBooking({ AppId: AppId, CompId: CompId, BranchId: BranchId })
+ ).unwrap();
+ }
+
+ useEffect(() => {
+ const filteredOffers = OrderOfferDetail?.filter(
+ ({ TableName, TableUniqueName, OfferCode, Type, FreeProductsList }) => {
+ if (
+ (TableName === 'LoyaltyPoints' &&
+ TableUniqueName === 'UniqueId' &&
+ Type === 'A') ||
+ ((TableName === 'CustomerPromo' ||
+ TableName === 'CustomerCoupon' ||
+ TableName === 'OfferCode') &&
+ OfferCode != null &&
+ TableUniqueName === 'UniqueId')
+ ) {
+ return FreeProductsList?.ExistingList?.length > 0;
+ }
+ if (TableName === 'BuyXGetXOffers') return true;
+ }
+ );
+ // setfreeProductsOffers(filteredOffers);
+
+ getOffers();
+ }, [OrderOfferDetail]);
+
+ useEffect(() => {
+ if (SelectedCardFont) {
+ WebFont.load({
+ google: {
+ families: [SelectedCardFont], // Load the selected font
+ },
+ });
+ }
+ }, [SelectedCardFont]);
+
+ const cardData = !globalAccessForOthers
+ ? CardAccess
+ ? SelectedDatas?.length > 1
+ ? SelectedDatas
+ : SelectedDatas?.[0]?.AppId === 0 && SelectedDatas?.[0]?.CompId === 0
+ ? []
+ : SelectedDatas
+ : ItemCard?.length == 0 ||
+ (ItemCard?.[0]?.AppId === 0 && ItemCard?.[0]?.CompId === 0)
+ ? noSubcatCardData
+ : ItemCard
+ : '';
+
+ const cardDataForNewPrd = !globalAccessForOthers
+ ? CardAccess
+ ? SelectedDatas
+ : ItemCard?.length == 0
+ ? noSubcatCardData
+ : ItemCard
+ : '';
+ //
+
function safeRound(amountStr) {
- if (amountStr == null) return '0.00';
+ if (amountStr == null) return allowDecimal ? '0.00' : '0';
const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
const num = Number(cleaned);
- return isNaN(num) ? '0.00' : num.toFixed(2); // return as string with 2 decimals
+ if (isNaN(num)) return allowDecimal ? '0.00' : '0';
+
+ return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
}
- const TotalWithoutTaxRate = async () => {
- const totalwithouttax = OrderCardDetail?.reduce((accumulator, card) => {
- return accumulator + parseFloat(card.WithoutTaxRate || 0);
- }, 0);
- setTotalWithoutTaxAmount(totalwithouttax.toFixed(2));
- await dispatch(
- changeSummeryTotalWithoutTaxAmount(totalwithouttax.toFixed(2))
- );
- };
- const TotalTaxAmt = async () => {
- const totaltax = OrderCardDetail?.reduce((accumulator, card) => {
- return accumulator + parseFloat(card.TaxAmt || 0);
- }, 0);
- setTotalTaxAmount(totaltax.toFixed(2));
- await dispatch(changeSummeryTotalTaxAmount(totaltax.toFixed(2)));
- };
- const HandleholdModelOpen = () => {
- setHold(true);
- };
-
- const handleHoldCancel = () => {
- setHold(false);
- };
- const handleAddCustomer = () => {
- if (Custdisable === false) {
- setAddCustomer(true);
+ useEffect(() => {
+ // fetchedit();
+ getPreferenceStock();
+ // dispatch(changepreOrder(false)); Commented to Add Normal Produts After Adding the Combo Pack !!!!!! Dont Touch Without Shifayath Permission
+ }, [preferenceDatas]);
+ useEffect(() => {
+ if (AppId && CompId && BranchId) {
+ // fetchedit();
+ GetmultipleSearchData();
}
- };
- const handleAddCustomerCancel = () => {
- setAddCustomer(false);
- };
- const handleOpenChange = (newOpen) => {
- setOpen(newOpen);
- };
- const hide = () => {
- setOpen(false);
- };
- const hideDefault = () => {
- setUpiOptionOpen(false);
- };
- const handlePopoverVisibleChange = (visible) => {
- setUpiOptionOpen(visible);
- };
+ // dispatch(changepreOrder(false)); Commented to Add Normal Produts After Adding the Combo Pack !!!!!! Dont Touch Without Shifayath Permission
+ }, [AppId, CompId, BranchId]);
- const handleextraCharges = () => {
- setExtraCharges(true);
- };
- const handleextraChargesCancel = () => {
- setExtraCharges(false);
- };
-
- const handleQuickCancel = async () => {
- await dispatch(changeCompoPaymentIconStatus(false));
- //
- setQuickAdd(false);
- };
- const setQuickOpen = async () => {
- await dispatch(changeCompoPaymentIconStatus(true));
- setQuickAdd(true);
- };
-
- const ProductSummary = (salesData) => {
- // Create a map to store the aggregated values for each unique product
- const productMap = new Map();
- // Iterate over the sales data to aggregate values
- salesData.forEach((item) => {
- const key = `${item.ProdId}-${item.InwardDtlId}-${item.BookingType}-${item.SinglePc}-${item.OrderRate}`;
- if (productMap.has(key)) {
- const existingItem = productMap.get(key);
- existingItem.OrderQty += item.OrderQty || 0;
- existingItem.TotalAmt += item.TotalAmt || 0;
- existingItem.TaxAmt =
- parseFloat(existingItem.TaxAmt) + parseFloat(item.TaxAmt) || 0;
- // existingItem.WithoutTaxRate += parseFloat(item.WithoutTaxRate) || 0;
- } else {
- // If the key doesn't exist, add a new entry
- productMap.set(key, { ...item });
- }
- });
-
- // Convert the map values back to an array
- const aggregatedProducts = Array.from(productMap.values());
-
- return aggregatedProducts;
- };
- const handleCreditCustomer = (type) => {
- setCreditCustomer(false);
- if (type == 'Submit') {
- Booking(BookingType, true);
- }
- if (type == 'Cancel') {
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- }
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedRemovedData = {
- type: 'remove',
- keyValue: 'OrderTotalAmount',
- };
- customerDisplayWindow.postMessage(updatedRemovedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- };
- const BadgePendingApi = async () => {
- let Data = {
- compId: CompId,
- branchId: BranchId,
- appId: AppId,
- deliveryStatus: 'P',
+ const GetmultipleSearchData = async () => {
+ const data = {
+ AppId,
+ CompId,
+ BranchId,
};
- let PendingResponse = await dispatch(PreOrderGet(Data)).unwrap();
- if (PendingResponse?.data?.statusCode === 1) {
- await dispatch(
- changePreOrderPendingCount(PendingResponse?.data?.data?.length)
- );
+
+ try {
+ const response = await dispatch(getmultipleSearch(data));
+ } catch (error) {
+ console.error('Get Search Terms Error:', error);
}
};
useEffect(() => {
- if (OrderCardDetail?.length <= 0) {
- dispatch(changeCustomerID(null));
- dispatch(changeSelectedCustId(null));
- dispatch(changeSelectedOption(null));
- dispatch(ChangeSelectedCustDisable(false));
- }
- }, [OrderCardDetail]);
-
- const ClearAllGlobalStateDatas = async (value) => {
- if (OfferCheckedInSetup && preferenceOffer) {
- await applyOffer([]);
- } else {
- dispatch(changeOrderCardDetails([]));
- }
- dispatch(changeTipAmount(0));
- await dispatch(ChangeTotalAmount([]));
- await dispatch(changeReorderHoldDetails({}));
- await dispatch(changeReorderProductDetails([]));
- setFirstPaymentclick(false);
- await dispatch(ChangeNavHoldData(false));
- await dispatch(changeCustomerID(null));
- await dispatch(changeSelectedCustId(null));
- await dispatch(changeSelectedOption(null));
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- setQrCode(false);
- setUpinotSelected(false);
- getHolddata();
- getUnpaiddatas();
- await dispatch(changeBookingType('TakeAway'));
- await dispatch(changeSelProdWiseEst([]));
- await dispatch(ChangeOverAllDiscSales(0));
- await dispatch(ChangeOverAllDiscEstimate(0));
- // await dispatch(changeEstimateBooking(null))
- // clearInvoiceDate
- clearInvoiceDate();
- dispatch(changeCurrentOrderId(null));
- await dispatch(changeSelectTable([]));
- await dispatch(changeSelectChair([]));
- await dispatch(changeSelectedTableDetails([]));
- await dispatch(changeOrderType());
- if (value === 'Dine-In') {
- navigate(`${subDirectory}sales/dine-in`);
- }
- let data = {
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- UserId: UserId,
- FromDate: currentDateValue,
- ToDate: currentDateValue,
- };
- await dispatch(getSalesDetailData(data));
- };
-
- const AddBookingDetails = async (value, pay) => {
- const customerDisplayWindow = getCustomerDisplayWindow();
-
- const OnUpiSelected = PaymentOptions?.find(
- (item) => item.ModeId === paybtnselected
- );
+ setPreOrderSelectedProdNames([]);
+ // dispatch(changePreOrderAdditem(null));
+ }, [preOrder]);
+ useEffect(() => {
if (
- OnUpiSelected?.ModeName?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'default'
+ ProdCat &&
+ ProdSubCat !== NaN &&
+ initialRun &&
+ 'BookingSubCategory' in templateData
) {
- SetSuccess(false);
- setTimeout(function () {
- SetSuccess(true);
- // Add your state change code here
- // For example:
- // setNewState(newValue);
- }, 3000);
- if (SelectedUpiOption) {
- Booking(value, pay);
- } else {
- setUpinotSelected(true);
- setMessageType('error');
- setMessageData('Please Select Upi Option');
+ productCardList();
+ }
+ }, [ProdSubCat, productCardTrigger]);
+ useEffect(() => {
+ if (
+ !initialRun &&
+ (!ProdSubCat || ProdSubCat != NaN || ProdSubCat === 'NaN') &&
+ ProdCat
+ ) {
+ setInitialRun(true);
+ productCardList();
+ }
+ if (
+ initialRun &&
+ !('BookingSubCategory' in templateData) &&
+ (!ProdSubCat || ProdSubCat != NaN || ProdSubCat === 'NaN') &&
+ ProdCat
+ ) {
+ productCardList();
+ }
+ }, [ProdCat, initialRun]);
+ useEffect(() => {
+ if (noSubcatCardData) {
+ setNoSubcatCardData();
+ }
+
+ if (
+ ProductSearch?.length > 5 &&
+ GetmultipleSearchDatas.some((e) => e.toLowerCase() === 'qrcode')
+ ) {
+ setQuickAdd(true);
+ }
+ }, [ProductSearch, GetmultipleSearchDatas]);
+
+ const productCardList = async () => {
+ //condition
+ if (
+ (templateData?.BookingLayout?.[1]?.some(
+ (item) => item?.OptionName === 'SubCategory'
+ ) ||
+ templateData?.BookingCategory?.[0] == 'Category5') &&
+ ProdSubCat &&
+ ProdCat
+ ) {
+ let data = {
+ CompId: CompId,
+ BranchId: BranchId,
+ AppId: AppId,
+ ProdSubCat: ProdSubCat,
+ ...(AvailableDate && selectedDate
+ ? {
+ date: Array.isArray(selectedDate)
+ ? selectedDate
+ .map((d) => (d?.format ? d.format('YYYY-MM-DD') : d))
+ .join(',')
+ : selectedDate?.format
+ ? selectedDate.format('YYYY-MM-DD')
+ : selectedDate,
+ }
+ : {}),
+ };
+ //mohan
+ let response = await dispatch(getLayoutproductCard(data)).unwrap();
+ if (response?.data?.statusCode == 1) {
+ setNoSubcatCardData(response?.data?.data);
}
} else if (
- OnUpiSelected?.ModeName?.toLowerCase() === 'card' &&
- PaymentgatewayCard?.length > 0 &&
- PaymentDeviceCard?.length > 0
+ !templateData?.BookingLayout?.[1]?.some(
+ (item) => item?.OptionName === 'SubCategory'
+ ) &&
+ templateData?.BookingCategory?.[0] != 'Category5' &&
+ ProdCat
) {
- if (SelectedCardOption) {
- if (SelectedCardOption?.toLowerCase() === 'pg') {
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- if (SelCustId) {
- Booking(value, pay);
+ let data = {
+ compId: CompId,
+ branchId: BranchId,
+ appId: AppId,
+ prodCat: ProdCat,
+ };
+
+ // 👇 only add date if AvailableDate is true
+ if (AvailableDate && selectedDate) {
+ data.date = selectedDate;
+ }
+
+ let response = await dispatch(getCardDataWithoutSubmodule(data)).unwrap();
+
+ if (response?.data?.statusCode == 1) {
+ setNoSubcatCardData(response?.data?.data);
+ }
+ } else if (
+ (templateData?.BookingLayout?.[1]?.some(
+ (item) => item?.OptionName === 'SubCategory'
+ ) ||
+ templateData?.BookingCategory?.[0] == 'Category5') &&
+ !ProdSubCat &&
+ ProdCat &&
+ ProdSubCat != 'NaN'
+ ) {
+ let data = {
+ compId: CompId,
+ branchId: BranchId,
+ appId: AppId,
+ prodCat: ProdCat,
+ ...(AvailableDate && selectedDate
+ ? {
+ date: Array.isArray(selectedDate)
+ ? selectedDate
+ .map((d) => (d?.format ? d.format('YYYY-MM-DD') : d))
+ .join(',')
+ : selectedDate?.format
+ ? selectedDate.format('YYYY-MM-DD')
+ : selectedDate,
+ }
+ : {}),
+ };
+
+ let response = await dispatch(getCardDataWithoutSub(data)).unwrap();
+
+ if (response?.data?.statusCode == 1) {
+ setNoSubcatCardData(response?.data?.data);
+ }
+ }
+ };
+
+ useEffect(() => {
+ DispatchData();
+ }, [SelectedProdNames]);
+ const DispatchData = async () => {
+ await dispatch(ChangeAllItemData(SelectedProdNames));
+ };
+
+ useEffect(() => {
+ if (Object.keys(WSProductdata)?.length > 0) {
+ AddOrderDetails(WSProductdata);
+ }
+ }, [WSProductdata]);
+
+ useEffect(() => {
+ if (ItemCard?.[0]?.QrBasedSearch === 'Y') {
+ if (ItemCard?.[0]?.OverAllExpStatus == 'Y' && ExpiredProduct) {
+ openExpireModal({
+ title: 'Product Expires',
+ onOk: () => expFun(Item),
+ });
+ setItem(ItemCard?.[0]);
+ } else {
+ setQtydata(ItemCard?.[0]);
+ SingleQuantity(ItemCard?.[0], false);
+ }
+ } else if (ItemCard?.[0]?.OnePcQRBased === 'Y') {
+ if (ItemCard?.[0]?.OverAllExpStatus == 'Y' && ExpiredProduct) {
+ openExpireModal({
+ title: 'Product Expires',
+ onOk: () => expFun(Item),
+ });
+ setItem(ItemCard?.[0]);
+ setOnePeiceFlow(true);
+ } else {
+ setQtydata(ItemCard?.[0]);
+ SingleQuantity(ItemCard?.[0], true);
+ }
+ }
+ }, [ItemCard]);
+
+ useEffect(() => {
+ // let data = otherscarddata
+ if (Object.keys(otherscarddata)?.length > 0) {
+ let data = {
+ Type: otherscarddata?.Type ? otherscarddata?.Type : 'P',
+ OverallQuantity: otherscarddata?.OverAllQty,
+ ActiveStatus: otherscarddata?.ActiveStatus,
+ AvailableFrom: otherscarddata?.AvailableFrom,
+ AvailableTo: otherscarddata?.AvailableTo,
+ Cess: otherscarddata?.Cess,
+ ExpDate: otherscarddata?.ExpDate,
+ HSNCode: otherscarddata?.HSNCode,
+ ManufDate: otherscarddata?.ManufDate,
+ OpeningQty: otherscarddata?.OpeningQty,
+ ProdType: otherscarddata?.ProdType,
+ PartNumber: otherscarddata?.PartNumber,
+ ProdId: otherscarddata?.ProdId,
+ ProdLogo: otherscarddata?.ProdLogo,
+ ProdName: otherscarddata?.ProdName,
+ QRCode: otherscarddata?.QRCode,
+ QtyBasedPrice: otherscarddata?.QtyBasedPrice,
+ Rack: otherscarddata?.Rack,
+ Size: otherscarddata?.Size,
+ StockAvailable: otherscarddata?.StockAvailable,
+ TaxId: otherscarddata?.TaxId,
+ TaxPercentage: otherscarddata?.TaxPercentage,
+ TaxName: otherscarddata?.TaxIdName,
+ UniqueId: otherscarddata?.UniqueId,
+ UomName: otherscarddata?.UomName,
+ ProdVariantName: otherscarddata?.ProdVariantName, //sri
+ BalanceQty: otherscarddata?.BalanceQty,
+ BatchRef: otherscarddata?.BatchRef,
+ ModelNumber: otherscarddata?.ModelNumber, //sri
+ FullProductIdentifierDtls: otherscarddata?.FullProductIdentifierDtls, //sri
+ InwardDate: otherscarddata?.InwardDate,
+ InwardDtlId: otherscarddata?.InwardDtlId,
+ InwardId: otherscarddata?.InwardId,
+ MRP: otherscarddata?.MRP,
+ Offer: otherscarddata?.OfferPrice,
+ OrderRate: otherscarddata?.SellPrice,
+ SellingPrice: otherscarddata?.SellPrice, // edit srii
+ SuppId: otherscarddata?.SuppId,
+ SuppName: otherscarddata?.SuppName,
+ OrderQty: otherscarddata?.Quantity,
+ OtherProduct: otherscarddata?.OtherProduct,
+ // 'ProdVariantName': otherscarddata?.ProdVariantName,
+ BookingTypeName: BookingType,
+ CounterName: '', //sri
+ };
+ AddOrderDetails(data);
+ }
+ // data["OrderRate"] = otherscarddata?.SellPrice
+ }, [otherscarddata]);
+
+ useEffect(() => {
+ if (Object.keys(NewQrProductData)?.length > 0) {
+ let addQrProductData = { ...NewQrProductData };
+ addQrProductData['OrderRate'] = addQrProductData['SellPrice'];
+ addQrProductData['OrderQty'] = addQrProductData['Quantity'];
+ addQrProductData['SellingPrice'] = addQrProductData['SellPrice'];
+ addQrProductData['BookingTypeName'] = BookingType;
+ AddOrderDetails(addQrProductData);
+ }
+ }, [NewQrProductData]);
+
+ const getPreferenceStock = async () => {
+ const PreferenceStckDtl = preferenceDatas?.[0]?.SettingDtlDetails;
+ const StockPreference = PreferenceStckDtl?.find(
+ (item) => item.SettingIdName === 'StockSelection'
+ );
+ setStockPreferenceDetail(StockPreference);
+ const BillOrder = PreferenceStckDtl?.find(
+ (item) => item.SettingIdName === 'BillItemsOrder'
+ );
+ setBillOrderPre(BillOrder?.SettingValue);
+
+ const expiredDate =
+ PreferenceStckDtl?.find(
+ (item) => item.SettingIdName === 'ExpiredSelection'
+ )?.SettingValue === 'Y';
+ setExpiredProduct(expiredDate);
+ };
+
+ const CloseModal = () => {
+ setModelQty(false);
+ setRepeatedModel(false);
+ setProdexpir(false);
+ setOnePeiceFlow(false);
+ setSelectedBrand('Others');
+ };
+ const CloseModal1 = () => {
+ setModelstock(false);
+ setRepeatedModel(false);
+ setProdexpir(false);
+ setOnePeiceFlow(false);
+ };
+ const CloseVarientModal = () => {
+ setModalVarient(false);
+ setRepeatedModel(false);
+ setProdexpir(false);
+ setOnePeiceFlow(false);
+ };
+
+ const Quantity = () => {
+ setModelQty(true);
+ };
+ const SingleQuantity = (item, onePcs) => {
+ let count = item?.ProductDetail?.[0]?.ProdVariantDetails?.length;
+ if (count > 1) {
+ setModalVarient(true);
+ } else {
+ setVarientIndex(0);
+ SingleStockfun(item, onePcs);
+ }
+ };
+ const SingleStockfun = (item, onePcs) => {
+ let count =
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
+ ?.StockDetails?.length;
+ if (
+ StockPreferenceDetail?.SettingValue === 'Y' &&
+ item?.ProductDetail?.[QtyIndex]?.StockAvailable == 'Y'
+ ) {
+ if (count > 1) {
+ setModelstock(true);
+ } else {
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePcs) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(item, 0, 0, 0, onePcs);
} else {
- setMessageType('error');
- setMessageData('Please Select Customer');
+ dataTransfer(item, 0, 0, 1, onePcs);
}
} else {
- setMessageType('error');
- setMessageData('Please Set the customer display');
+ dataTransfer(item, 0, 0, 0, onePcs);
}
} else {
- Booking(value, pay);
+ if (Isincart && Isincart?.StockAvailable === 'Y') {
+ if (Isincart?.BalanceQty > Isincart?.OrderQty) {
+ dataTransfer(item, 0, 0, 0, onePcs);
+ } else {
+ dataTransfer(item, 0, 0, 1, onePcs);
+ }
+ } else {
+ dataTransfer(item, 0, 0, 0, onePcs);
+ }
+ }
+ }
+ } else {
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
+ ?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
+ ?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePcs) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId === item?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(item, 0, 0, 0, onePcs);
+ } else {
+ dataTransfer(item, 0, 0, 1, onePcs);
+ }
+ } else {
+ dataTransfer(item, 0, 0, 0, onePcs);
}
} else {
- setCardoptionnotSelected(true);
- setMessageType('error');
- setMessageData('Please Select Card Option');
- }
- } else if (OnUpiSelected?.ModeName?.toLowerCase() === 'credit') {
- if (!SelCustId) {
- setMessageType('error');
- setMessageData('Please Select Customer');
- } else {
- setCreditCustomer(true);
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- OrderTotalAmount: TotalAmount,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
+ if (Isincart && Isincart?.StockAvailable === 'Y') {
+ if (Isincart?.BalanceQty > Isincart?.OrderQty) {
+ dataTransfer(item, 0, 0, 0, onePcs);
+ } else {
+ dataTransfer(item, 0, 0, 1, onePcs);
+ }
} else {
- console.error(
- 'Customer display window is not available or has been closed.'
+ dataTransfer(item, 0, 0, 0, onePcs);
+ }
+ }
+ }
+ };
+
+ const Stockfun = (index) => {
+ setVarientIndex(index.key);
+ const variantDetails =
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[index.key] || {};
+ const overallExpStatus = variantDetails.OverAllExpStatus;
+ const count = variantDetails.StockDetails?.length || 0;
+
+ if (
+ StockPreferenceDetail?.SettingValue === 'Y' &&
+ qtydata?.ProductDetail?.[QtyIndex]?.StockAvailable == 'Y'
+ ) {
+ if (count > 1) {
+ if (
+ overallExpStatus === 'N' ||
+ (overallExpStatus === 'Y' && prodexpir)
+ ) {
+ setModalVarient(false);
+ setModelstock(true);
+ setVarItem(index.key);
+ if (overallExpStatus === 'Y' && prodexpir) {
+ setRepeatedModel(true);
+ }
+ } else if (overallExpStatus === 'Y' && ExpiredProduct) {
+ setVarItem(index.key);
+ openExpireModal({
+ title: 'Variant Expires',
+ onOk: () => expVerFun(VarItem),
+ onCancel: () => {
+ setRepeatedModel(false);
+ setProdexpir(false);
+ },
+ });
+ }
+ } else {
+ if (
+ overallExpStatus === 'N' ||
+ (overallExpStatus === 'Y' && prodexpir)
+ ) {
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePeiceFlow) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
+ }
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ }
+ } else {
+ if (Isincart && Isincart?.StockAvailable === 'Y') {
+ if (Isincart?.BalanceQty > Isincart?.OrderQty) {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
+ }
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ }
+ }
+
+ setModelQty(false);
+ setSelectedBrand('Others');
+ setVarItem(index.key);
+ if (overallExpStatus === 'Y' && prodexpir) {
+ setProdexpir(false);
+ setRepeatedModel(true);
+ return;
+ }
+ } else if (overallExpStatus === 'Y' && ExpiredProduct) {
+ setVarItem(index.key);
+ openExpireModal({
+ title: 'Variant Expires',
+ onOk: () => expVerFun(VarItem),
+ onCancel: () => {
+ setRepeatedModel(false);
+ setProdexpir(false);
+ },
+ });
+ return;
+ }
+ }
+ } else {
+ if (overallExpStatus === 'N' || (overallExpStatus === 'Y' && prodexpir)) {
+ const stockDetails =
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[index.key]
+ ?.StockDetails;
+ console.log(stockDetails, CartOrderDetails, 'currIndex');
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePeiceFlow) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId === qtydata?.ProductDetail?.[QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ index.key
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * (card.NoOfPcs ? card.NoOfPcs : 1)
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 1, onePeiceFlow);
+ }
+ } else {
+ dataTransfer(qtydata, QtyIndex, index.key, 0, onePeiceFlow);
+ }
+ } else {
+ const findNextAvailableStockIndex = (
+ stockDetails,
+ CartOrderDetails,
+ prodId
+ ) => {
+ if (!stockDetails || stockDetails.length === 0) return 0;
+
+ for (let i = 0; i < stockDetails.length; i++) {
+ const stock = stockDetails[i];
+
+ // Find if this specific stock is already in cart
+ const cartItem = CartOrderDetails?.find(
+ (item) =>
+ item?.ProdId === prodId &&
+ item?.InwardDtlId === stock?.InwardDtlId &&
+ item?.OrderRate === stock?.SellPrice &&
+ !item?.SalesId
+ );
+
+ // If not in cart, this stock has full balance available - use this
+ if (!cartItem) {
+ return i;
+ }
+
+ // If in cart and NOT fully utilized, continue using this stock
+ if (cartItem && cartItem?.OrderQty < cartItem?.BalanceQty) {
+ return i;
+ }
+
+ // If OrderQty === BalanceQty (fully utilized), move to next stock
+ // Continue the loop...
+ }
+
+ // If all stocks are exhausted, return the last index
+ return stockDetails.length - 1;
+ };
+
+ const currentProdId = qtydata?.ProductDetail?.[QtyIndex]?.ProdId;
+
+ // Find the next available stock index dynamically
+ const nextAvailableIndex = findNextAvailableStockIndex(
+ stockDetails,
+ CartOrderDetails,
+ currentProdId
+ );
+
+ dataTransfer(
+ qtydata,
+ QtyIndex,
+ index.key,
+ nextAvailableIndex,
+ onePeiceFlow
+ );
+ }
+
+ setModelQty(false);
+ setSelectedBrand('Others');
+ setVarItem(index.key);
+ if (overallExpStatus === 'Y' && prodexpir) {
+ setProdexpir(false);
+ setRepeatedModel(true);
+ return;
+ }
+ } else if (overallExpStatus === 'Y' && ExpiredProduct) {
+ setVarItem(index.key);
+ openExpireModal({
+ title: 'Variant Expires',
+ onOk: () => expVerFun(VarItem),
+ onCancel: () => {
+ setRepeatedModel(false);
+ setProdexpir(false);
+ },
+ });
+ return;
+ }
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ };
+ const VarientFun = (index) => {
+ const QtyExpire = index?.ProdVariantDetails.every(
+ (item) => item.OverAllExpStatus === 'Y'
+ );
+ if (QtyExpire && ExpiredProduct) {
+ openExpireModal({
+ title: 'Quantity Expires',
+ onOk: () => expQtyFun(qtyExpData),
+ onCancel: () => {
+ setRepeatedModel(false);
+ (setProdexpir(false), closeExpireModal());
+ },
+ });
+ setQtyExpData(index);
+ } else {
+ const selectedProIndex = qtydata?.ProductDetail?.findIndex(
+ (item) =>
+ item?.ProdId === index?.ProdId &&
+ item?.Size === index?.Size &&
+ item?.UomName === index?.UomName &&
+ item?.Brand === index?.Brand
+ );
+
+ if (selectedProIndex !== -1) {
+ const count =
+ qtydata?.ProductDetail[selectedProIndex]?.ProdVariantDetails
+ ?.length || 0;
+
+ if (count > 1) {
+ setModelQty(false);
+ setSelectedBrand('Others');
+ setModalVarient(true);
+ } else {
+ const item = { QtyIndex: selectedProIndex, VarientIndex: 0 };
+ singleVarient(item);
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ }
+
+ setQtyIndex(selectedProIndex);
+ setVarientIndex(0);
+ setRepeatedModel(false);
+ }
+ };
+ const singleVarient = (item) => {
+ let count =
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.length;
+
+ if (
+ StockPreferenceDetail?.SettingValue === 'Y' &&
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.StockAvailable == 'Y'
+ ) {
+ if (count > 1) {
+ setModalVarient(false);
+ setModelstock(true);
+ // setVarientIndex(index.key)
+ } else {
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePeiceFlow) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 1,
+ onePeiceFlow
+ );
+ }
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ }
+ } else {
+ if (Isincart && Isincart?.StockAvailable === 'Y') {
+ if (Isincart?.BalanceQty > Isincart?.OrderQty) {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 1,
+ onePeiceFlow
+ );
+ }
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ }
+ }
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ } else {
+ let Isincart = CartOrderDetails?.find(
+ (cartItem) =>
+ cartItem?.ProdId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ cartItem?.OrderRate ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.SellPrice &&
+ !cartItem?.SalesId
+ );
+
+ if (onePeiceFlow) {
+ let Isincartonepc = CartOrderDetails?.filter(
+ (cartItem) =>
+ cartItem?.ProdId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
+ cartItem?.InwardDtlId ===
+ qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
+ item?.VarientIndex
+ ]?.StockDetails?.[0]?.InwardDtlId &&
+ // (cartItem?.OrderRate === item?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.StockDetails?.[0]?.SellPrice)
+ !cartItem?.SalesId
+ );
+ let totalOrderQty = Isincartonepc?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ if (Isincartonepc && Isincartonepc?.[0]?.StockAvailable === 'Y') {
+ if (Isincartonepc?.[0]?.OverAllPcs > totalOrderQty) {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 1,
+ onePeiceFlow
+ );
+ }
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ }
+ } else {
+ if (Isincart && Isincart?.StockAvailable === 'Y') {
+ if (Isincart?.BalanceQty > Isincart?.OrderQty) {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
+ );
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 1,
+ onePeiceFlow
+ );
+ }
+ } else {
+ dataTransfer(
+ qtydata,
+ item?.QtyIndex,
+ item?.VarientIndex,
+ 0,
+ onePeiceFlow
);
}
}
- } else if (
- OnUpiSelected?.ModeName?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'pg'
- ) {
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- if (SelCustId) {
- Booking(value, pay);
- } else {
- setMessageType('error');
- setMessageData('Please Select Customer');
- }
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ };
+ const StockSelected = (item) => {
+ const stockDetails =
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
+ ?.StockDetails?.[item.key] || {};
+ const overallExpStatus = stockDetails?.OverAllExpStatus;
+
+ if (overallExpStatus === 'N' || overallExpStatus === 'Y') {
+ const firstStockDetails =
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[0]
+ ?.StockDetails?.[item.key] || {};
+ const firstOverallExpStatus = firstStockDetails.OverAllExpStatus;
+
+ if (
+ overallExpStatus === 'N' ||
+ (firstOverallExpStatus === 'Y' && prodexpir)
+ ) {
+ dataTransfer(qtydata, QtyIndex, VarientIndex, item.key, onePeiceFlow);
+ } else if (overallExpStatus === 'Y' && repeatedModel) {
+ dataTransfer(qtydata, QtyIndex, VarientIndex, item.key, onePeiceFlow);
} else {
- setMessageType('error');
- setMessageData('Please Set the customer display');
+ openExpireModal({
+ title: 'Stock Expires',
+ onOk: () => expStockFun(StockItem),
+ onCancel: () => {
+ setRepeatedModel(false);
+ setProdexpir(false);
+ },
+ });
+ setStockItem(item.key);
}
- } else if (
- OnUpiSelected?.ModeName?.toLowerCase() === 'card' &&
- SelectedCardOption?.toLowerCase() === 'pg'
- ) {
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- if (SelCustId) {
- Booking(value, pay);
- } else {
- setMessageType('error');
- setMessageData('Please Select Customer');
- }
+ }
+
+ setProdexpir(false);
+ setRepeatedModel(false);
+ };
+
+ const [priceChangeProduct, setPriceChangeProduct] = useState([]);
+ const [productPriceChange, setProductPriceChange] = useState(false);
+
+ const CardOnclick = async (item, Parameter) => {
+ setOnePeiceFlow(Parameter === 'OnePeiceProduct');
+
+ const transformedItem = {
+ ...item,
+ ProductDetail: item.ProductDetail
+ // .filter((detail) => detail.OnePcsAvailable === "Y")
+ .map(({ ProdId, ProdName, ProdVariantDetails, ...rest }) => ({
+ ProdId,
+ ProdName,
+ ProdVariantDetails,
+ ...rest,
+ })),
+ };
+
+ const modiffiedData =
+ Parameter === 'OnePeiceProduct' ? transformedItem : item;
+ setQtydata(modiffiedData);
+ if (modiffiedData.OverAllExpStatus === 'Y' && ExpiredProduct) {
+ openExpireModal({
+ title: 'Product Expires',
+ onOk: () => expFun(modiffiedData),
+ });
+ setItem(modiffiedData);
+ } else if (modiffiedData) {
+ setQtydata(modiffiedData);
+ let count = modiffiedData?.ProductDetail?.length;
+ if (count > 1) {
+ Quantity(modiffiedData);
} else {
- setMessageType('error');
- setMessageData('Please Set the customer display');
+ setQtyIndex(0);
+ SingleQuantity(modiffiedData, Parameter === 'OnePeiceProduct');
}
+ }
+ };
+ const StockDate = (date) => {
+ let dateVal = moment(date, ['YYYY-MM-DDTHH:mm:ss']).format('DD-MM-YYYY');
+ return dateVal;
+ };
+
+ const AddOrderDetails = async (item) => {
+ if (preOrder) {
+ await handlePreOrder(item);
} else {
- Booking(value, pay);
+ await handleRegularOrder(item);
}
};
- const extrachargesbookingtype = (extradata) => {
- const TakAwayId = ConfigDataList?.find(
- (a) => a?.ConfigName === 'TakeAway'
- )?.ConfigId;
- const DineinId = ConfigDataList?.find(
- (a) => a?.ConfigName === 'Dine In'
- )?.ConfigId;
- let tempdata = extradata?.map((data) => ({
- ...data,
- BookingType: data?.BookingTypeName === 'Dine In' ? DineinId : TakAwayId,
- }));
- return tempdata;
+ const handlePreOrder = async (item) => {
+ let Response = await dispatch(
+ getConfigType({ TypeName: 'Booking Type' })
+ ).unwrap();
+
+ let BookingTypeID;
+ if (Response?.data?.statusCode == 1) {
+ BookingTypeID = Response?.data?.data?.find(
+ (item) => item?.ConfigName === 'Dine In'
+ )?.ConfigId;
+ }
+
+ let Condition = PreOrderSelectedProdNames?.some(
+ (obj) =>
+ obj?.InwardDtlId === item?.InwardDtlId &&
+ obj?.SinglePc === item?.SinglePc
+ );
+
+ if (PreOrderAdditem !== 'AddItems') {
+ setMessageData('Have To choose Add Item Before select Any Item ');
+ setMessageType('error');
+ return;
+ }
+
+ if (Condition) {
+ setMessageData('Duplicate Data');
+ setMessageType('error');
+ return;
+ }
+
+ const calculateWithoutTaxRate = (qty, rate, taxPercentage) => {
+ const totalAmount = qty * rate;
+ const taxAmount = (
+ (totalAmount * taxPercentage) /
+ (100 + taxPercentage)
+ ).toFixed(2);
+ const withoutTaxRate = (totalAmount - taxAmount).toFixed(2);
+
+ return parseFloat(withoutTaxRate);
+ };
+
+ const SelectedProduct = {
+ ProdId: item?.ProdId,
+ InwardDtlId: item?.InwardDtlId,
+ ProdNameQty: item?.ProdName + ' ' + item?.Size + ' ' + item?.UomName,
+ ProdName: item?.ProdName,
+ Size: item?.Size,
+ UomName: item?.UomName,
+ OrderQty: 1,
+ OrderRate: item?.OrderRate,
+ TotalAmt: item?.OrderRate,
+ Image: null,
+ Description: null,
+ Type: item?.Type,
+ TaxAmt: 0,
+ RefundQty: 0,
+ TaxId: item?.TaxId,
+ OrderStatus: 'O',
+ OrderType: 'PRE',
+ SinglePc: item?.SinglePc,
+ BookingType: BookingTypeID,
+ WithoutTaxRate: calculateWithoutTaxRate(
+ 1,
+ item?.OrderRate,
+ item?.TaxPercentage
+ ),
+ StockAvailable: item?.StockAvailable,
+ };
+
+ const Data =
+ PreOrderSelectedProdNames?.length > 0
+ ? [SelectedProduct, ...PreOrderSelectedProdNames]
+ : [SelectedProduct];
+
+ await setPreOrderSelectedProdNames(Data);
+ await dispatch(changepreOrderList(Data));
};
- const Booking = async (value, pay) => {
- const TakAwayId = ConfigDataList?.find(
- (a) => a?.ConfigName === 'TakeAway'
- )?.ConfigId;
- const DineinId = ConfigDataList?.find(
- (a) => a?.ConfigName === 'Dine In'
- )?.ConfigId;
+ const handleRegularOrder = async (item) => {
+ const isHoldOrder = OrderType === 'Hold';
+ const addFirst = BillOrderPre === 'Y';
+ const hasOffer = OfferCheckedInSetup && preferenceOffer;
- setFirstPaymentclick(true);
- let temporderdetail = OrderCardDetail?.map((a) => ({
- ProdId: a.ProdId,
- Type: a.Type,
- OrderQty: a.OrderQty,
- OrderRate: a.OrderRate,
- TotalAmt: a.OrderQty * a.OrderRate,
- TaxAmt: a.TaxAmt,
- RefundQty: 0,
- InwardDtlId: a.InwardDtlId,
- TaxId: a.TaxId,
- ProdNameQty:
- UomPrint?.SettingValue === 'N'
- ? `${a.ProdName} ${a.UomName?.toLowerCase() === 'half' ? '(Half)' : ''}`
- : `${a.ProdName} ${a.Size} ${a.UomName}`,
- OrderStatus: 'O',
- OrderType:
- BookingType === 'Dine In' ||
- BookingTypeBoth ||
- Estimation?.SettingValue == 'N'
- ? 'S'
- : GlobEstBooking === 'OvrAllEst'
- ? 'E'
- : GlobEstBooking === 'ParEst'
- ? GlobProdwisedata?.includes(
- a.InwardDtlId + ' ' + a?.BookingTypeName
+ const isExistsInFreeProdList = hasOffer
+ ? FreeProdList?.filter(
+ (f) =>
+ f?.FreeProdId === item?.ProdId &&
+ f?.ProdVariantDetails?.some((variant) =>
+ variant?.StockDetails?.some(
+ (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
)
- ? 'E'
- : 'S'
- : 'S',
- SinglePc: a.SinglePc,
- BookingType: a.BookingTypeName === 'Dine In' ? DineinId : TakAwayId,
- OfferValue: a?.Type === 'C' ? a?.OfferPrice : a.Offer,
- OfferAmt: a?.Type === 'C' ? a?.TotalAmt : a.Offer,
- OfferType: a?.Type === 'C' ? a?.OfferType : '',
- CounterName: a?.TokenAvailable === 'Y' ? a?.CounterName : null,
- ProductIdentifierDtls: a.ProductIdentifierDtls,
- ModelNumber: a.ModelNumber,
- BatchRef: a.BatchRef,
- PackageDtl: a.PackageDtl,
- }));
- const NotSlectedTypeFind = temporderdetail?.find(
- (a) => a?.BookingType != SelectedBookingType
+ ) &&
+ f?.RemainingQty > 0
+ )
+ : [];
+
+ const calculateTaxAmounts = (qty, rate, taxPercentage) => {
+ const totalAmount = qty * rate;
+ const taxAmount = (
+ (totalAmount * taxPercentage) /
+ (100 + taxPercentage)
+ ).toFixed(2);
+ const withoutTaxRate = (totalAmount - taxAmount).toFixed(2);
+
+ return {
+ TotalAmt: totalAmount,
+ TaxAmt: parseFloat(taxAmount),
+ WithoutTaxRate: parseFloat(withoutTaxRate),
+ };
+ };
+
+ // Helper function to create updated cart item
+ const createUpdatedCartItem = (cartItem, newQty = null) => {
+ const quantity = newQty || cartItem.OrderQty + 1;
+ const taxAmounts = calculateTaxAmounts(
+ quantity,
+ cartItem.OrderRate,
+ cartItem.TaxPercentage
+ );
+
+ return {
+ ...cartItem,
+ OrderQty: quantity,
+ ...taxAmounts,
+ };
+ };
+
+ // Helper function to create new item for cart
+ const createNewCartItem = (item, quantity = 1) => {
+ const taxAmounts = calculateTaxAmounts(
+ quantity,
+ item.OrderRate,
+ item.TaxPercentage
+ );
+
+ return {
+ ...item,
+ localId: uuidv4(),
+ OrderQty: quantity,
+ ...taxAmounts,
+ };
+ };
+
+ dispatch(changeHoldOrderDtl(false));
+ dispatch(changePreviousOrderLength(CartOrderDetails?.length));
+
+ const itemMatchCondition = (cartItem) =>
+ cartItem.ProdId === item.ProdId &&
+ cartItem.InwardDtlId === item.InwardDtlId &&
+ cartItem.OrderRate === item.OrderRate &&
+ cartItem.BookingTypeName === item.BookingTypeName &&
+ cartItem.ScaleType === item.ScaleType;
+ // item.WeightscaleProd !== 'Y';
+ const isItemInCart = CartOrderDetails?.find(
+ (cartItem) =>
+ itemMatchCondition(cartItem) &&
+ !cartItem.SalesId &&
+ ((cartItem?.OfferModeType && cartItem?.OfferMode === 'B'
+ ? true
+ : cartItem?.OfferMode !== 'B') &&
+ cartItem?.OfferMode !== 'P' &&
+ cartItem?.OfferMode !== 'C' &&
+ cartItem?.OfferMode !== 'O' &&
+ cartItem?.OfferMode !== 'L'
+ ? true
+ : cartItem?.Offer === 0)
);
- let updatedOfferDetails = OrderOfferDetail;
- if (GlobEstBooking !== 'Sales') {
- updatedOfferDetails = OrderOfferDetail?.filter(
- (item) =>
- !(
- item.TableName === 'LoyaltyPoints' &&
- item.TableUniqueName === 'UniqueId' &&
- item.Type === 'A'
+
+ const isItemInCartHold = CartOrderDetails?.find(
+ (cartItem) =>
+ itemMatchCondition(cartItem) &&
+ ((cartItem?.OfferModeType && cartItem?.OfferMode === 'B'
+ ? true
+ : cartItem?.OfferMode !== 'B') &&
+ cartItem?.OfferMode !== 'P' &&
+ cartItem?.OfferMode !== 'C' &&
+ cartItem?.OfferMode !== 'O' &&
+ cartItem?.OfferMode !== 'L'
+ ? true
+ : cartItem?.Offer === 0)
+ );
+
+ // Filter cart items
+ const otherOrderDataForNormal = CartOrderDetails?.filter(
+ (cartItem) =>
+ !(
+ itemMatchCondition(cartItem) &&
+ !cartItem.SalesId &&
+ ((cartItem?.OfferModeType && cartItem?.OfferMode === 'B'
+ ? true
+ : cartItem?.OfferMode !== 'B') &&
+ cartItem?.OfferMode !== 'P' &&
+ cartItem?.OfferMode !== 'C' &&
+ cartItem?.OfferMode !== 'O' &&
+ cartItem?.OfferMode !== 'L'
+ ? true
+ : cartItem?.Offer === 0)
+ )
+ );
+
+ const otherOrderDataForNormalWithoutSalesId = CartOrderDetails?.filter(
+ (cartItem) =>
+ !(
+ itemMatchCondition(cartItem) &&
+ ((cartItem?.OfferModeType && cartItem?.OfferMode === 'B'
+ ? true
+ : cartItem?.OfferMode !== 'B') &&
+ cartItem?.OfferMode !== 'P' &&
+ cartItem?.OfferMode !== 'C' &&
+ cartItem?.OfferMode !== 'O' &&
+ cartItem?.OfferMode !== 'L'
+ ? true
+ : cartItem?.Offer === 0)
+ )
+ );
+
+ try {
+ // CASE 1: Item exists in cart, not Dine In, not Hold order
+
+ if (isItemInCart && !isHoldOrder) {
+ if (
+ isExistsInFreeProdList?.length > 0 &&
+ hasOffer &&
+ item?.SinglePc !== 'Y'
+ ) {
+ handleFreeProduct(item, isExistsInFreeProdList, addFirst);
+ } else {
+ const updatedCartItem = createUpdatedCartItem(
+ isItemInCart,
+ item?.OtherProduct === 'Others' || item?.ScaleType === 'weight'
+ ? (
+ (item?.OrderQty || 0) + parseFloat(isItemInCart?.OrderQty)
+ )?.toFixed(3)
+ : null
+ );
+ const updatedData = addFirst
+ ? [updatedCartItem, ...otherOrderDataForNormal]
+ : [...otherOrderDataForNormal, updatedCartItem];
+ if (OverAllproductBasedOfferDatas?.ProdDtl?.length > 0 && hasOffer) {
+ handleFreeProductAvailable(updatedCartItem, updatedData, addFirst);
+ } else {
+ dispatch(changeOrderCardDetails(updatedData));
+ }
+ }
+ }
+ // CASE 2: Item exists in cart (hold), is Hold order
+ else if (isItemInCartHold && isHoldOrder) {
+ if (
+ isExistsInFreeProdList?.length > 0 &&
+ hasOffer &&
+ item?.SinglePc !== 'Y'
+ ) {
+ handleFreeProduct(item, isExistsInFreeProdList, addFirst);
+ } else {
+ const updatedCartItem = createUpdatedCartItem(
+ isItemInCartHold,
+ item?.OtherProduct === 'Others' || item?.ScaleType === 'weight'
+ ? (
+ (item?.OrderQty || 0) + parseFloat(isItemInCartHold?.OrderQty)
+ )?.toFixed(3)
+ : null
+ );
+ const updatedData = addFirst
+ ? [updatedCartItem, ...otherOrderDataForNormalWithoutSalesId]
+ : [...otherOrderDataForNormalWithoutSalesId, updatedCartItem];
+ if (OverAllproductBasedOfferDatas?.ProdDtl?.length > 0 && hasOffer) {
+ handleFreeProductAvailable(updatedCartItem, updatedData, addFirst);
+ } else {
+ dispatch(changeOrderCardDetails(updatedData));
+ }
+ }
+ }
+ // CASE 3: New item - not in cart
+ else {
+ if (item.OtherProduct === 'Others' || item.ScaleType == 'weight') {
+ const newCartItem = createNewCartItem(item, item.OrderQty);
+ const updatedData = addFirst
+ ? [newCartItem, ...CartOrderDetails]
+ : [...CartOrderDetails, newCartItem];
+
+ dispatch(changeOrderCardDetails(updatedData));
+ } else {
+ if (
+ isExistsInFreeProdList?.length > 0 &&
+ hasOffer &&
+ item?.SinglePc !== 'Y'
+ ) {
+ handleFreeProduct(item, isExistsInFreeProdList, addFirst);
+ } else {
+ const newCartItem = createNewCartItem(item, 1);
+ const updatedData = addFirst
+ ? [newCartItem, ...CartOrderDetails]
+ : [...CartOrderDetails, newCartItem];
+ if (
+ OverAllproductBasedOfferDatas?.ProdDtl?.length > 0 &&
+ hasOffer
+ ) {
+ handleFreeProductAvailable(newCartItem, updatedData, addFirst);
+ } else {
+ dispatch(changeOrderCardDetails(updatedData));
+ }
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error updating order details:', error);
+ } finally {
+ // Clean up dispatch calls
+ dispatch(changeothersdata({}));
+ dispatch(ChangeNewQrProduct({}));
+ }
+ };
+
+ const handleFreeProduct = (item, filteredFreeProdList, addFirst) => {
+ if (!filteredFreeProdList?.length) return;
+
+ const offerMode = filteredFreeProdList[0]?.OfferMode;
+
+ // --- helper functions ---
+ const calcTax = (qty, rate, taxPerc) =>
+ ((qty * rate * taxPerc) / 100).toFixed(2);
+
+ const calcWithoutTax = (qty, rate, taxPerc) =>
+ qty * rate - ((qty * rate * taxPerc) / 100).toFixed(2);
+
+ const updateFreeProductMeta = (base, qty, rate) => ({
+ ...base,
+ FreeQty: qty,
+ discount: qty * rate,
+ RemainingQty: base.OverAllFreeQty - qty,
+ ProdVariantDetails: base.ProdVariantDetails.map((variant) => ({
+ ...variant,
+ StockDetails: variant.StockDetails.map((stock) => ({
+ ...stock,
+ UsedFree: qty,
+ RemainingFree: stock.RemainingFree - qty,
+ })),
+ })),
+ });
+
+ const applyOffer = (offerList, updatedItem) => {
+ if (offerMode === 'L') {
+ const updated = loyaltyOfferApply(
+ offerList,
+ updatedItem,
+ DineinId,
+ TakAwayId
+ );
+ dispatch(changeOfferAppliedProductsForLoyalty(updated));
+ dispatch(changeFreeProductForLoyalty(offerList[0]));
+ } else if (offerMode === 'P' || offerMode === 'C' || offerMode === 'O') {
+ const updated = buildOfferFromChangesForPromoCodes(
+ PromoCodeOffersDatas?.[0],
+ offerList,
+ updatedItem,
+ DineinId,
+ TakAwayId
+ );
+ dispatch(changeOfferAppliedProductsForLoyalty(updated));
+ dispatch(changeFreeProductForLoyalty(offerList[0]));
+ } else {
+ const updated = buildOfferFromChanges(
+ OverAllproductBasedOfferDatas,
+ offerList,
+ updatedItem,
+ DineinId,
+ TakAwayId
+ );
+ dispatch(ChangeOfferAppliedProducts(updated));
+ dispatch(ChangeFreeProductList(offerList[0]));
+ }
+ };
+
+ // --- main logic ---
+ let UpdatedData = [];
+ const existing = CartOrderDetails?.find(
+ (c) =>
+ c.ProdId === item.ProdId &&
+ c.InwardDtlId === item.InwardDtlId &&
+ c.OrderRate === item.OrderRate &&
+ c.BookingTypeName === item.BookingTypeName &&
+ c.OfferMode === offerMode &&
+ c.Offer > 0
+ );
+
+ const existsInOther = CartOrderDetails?.find(
+ (c) =>
+ c.ProdId === item.ProdId &&
+ c.InwardDtlId === item.InwardDtlId &&
+ c.OrderRate === item.OrderRate &&
+ c.BookingTypeName !== item.BookingTypeName &&
+ c.OfferMode === offerMode &&
+ c.Offer > 0
+ );
+
+ if (existing) {
+ let newQty = existing.OrderQty + 1;
+ const UpdatedCartItem = {
+ ...existing,
+ OrderQty: newQty,
+ TotalAmt: existing.TotalAmt + existing.OrderRate,
+ Offer: existing.Offer + existing.OrderRate,
+ TaxAmt: calcTax(newQty, existing.OrderRate, existing.TaxPercentage),
+ WithoutTaxRate: calcWithoutTax(
+ newQty,
+ existing.OrderRate,
+ existing.TaxPercentage
+ ),
+ OfferMessage: [
+ {
+ OfferId: filteredFreeProdList[0].OfferId,
+ FreeQty: newQty,
+ FreeProdId: filteredFreeProdList[0].FreeProdId,
+ FreeProdName: filteredFreeProdList[0].FreeProdName,
+ },
+ ],
+ };
+ if (existsInOther) {
+ newQty = newQty + existsInOther?.OrderQty;
+ }
+ const updatedOfferList = [
+ updateFreeProductMeta(filteredFreeProdList[0], newQty, item.OrderRate),
+ ];
+
+ UpdatedData = CartOrderDetails.map((c) =>
+ c === existing ? UpdatedCartItem : c
+ );
+
+ applyOffer(updatedOfferList, UpdatedCartItem);
+ } else {
+ let newQty = 1;
+ const UpdatedCartItem = {
+ ...item,
+ localId: uuidv4(),
+ OrderQty: newQty,
+ TotalAmt: item.OrderRate,
+ Offer: item.OrderRate,
+ OfferType: offerMode,
+ OfferMode: offerMode,
+ TaxAmt: calcTax(1, item.OrderRate, item.TaxPercentage),
+ WithoutTaxRate: calcWithoutTax(1, item.OrderRate, item.TaxPercentage),
+ OfferMessage: [
+ {
+ OfferId: filteredFreeProdList[0].OfferId,
+ FreeQty: 1,
+ FreeProdId: filteredFreeProdList[0].FreeProdId,
+ FreeProdName: filteredFreeProdList[0].FreeProdName,
+ },
+ ],
+ };
+
+ if (existsInOther) {
+ newQty = newQty + existsInOther?.OrderQty;
+ }
+
+ const updatedOfferList = [
+ updateFreeProductMeta(filteredFreeProdList[0], newQty, item.OrderRate),
+ ];
+
+ UpdatedData = addFirst
+ ? [UpdatedCartItem, ...CartOrderDetails]
+ : [...CartOrderDetails, UpdatedCartItem];
+ applyOffer(updatedOfferList, UpdatedCartItem);
+ }
+
+ dispatch(changeOrderCardDetails(UpdatedData));
+ };
+
+ const handleFreeProductAvailable = async (item, cartData, addFirst) => {
+ const offers = chooseOfferFun(item, cartData);
+
+ if (!offers?.length) {
+ const indexToCheck = addFirst ? 0 : cartData.length - 1;
+ const productToCheck = cartData?.[addFirst ? 0 : cartData?.length - 1];
+ let updatedCartData = cartData;
+ if (productToCheck?.OfferMode && productToCheck?.Offer > 0) {
+ dispatch(
+ RemoveOfferAppliedProduct({
+ ProdId: productToCheck?.ProdId,
+ InwardDtlId: productToCheck?.InwardDtlId,
+ OfferType: productToCheck?.OfferMode,
+ })
+ );
+ updatedCartData = cartData.map((item, idx) =>
+ idx === indexToCheck
+ ? {
+ ...item,
+ Offer: null,
+ OfferMessage: undefined,
+ OfferMode: undefined,
+ OfferModeType: false,
+ OfferType: undefined,
+ OfferValue: null,
+ }
+ : item
+ );
+ }
+
+ const {
+ updatedOrderCardDetails,
+ updatedFreeProdList,
+ updatedOfferAppliedProducts,
+ hasChanges,
+ } = processFreeProducts(updatedCartData, FreeProdList);
+
+ if (hasChanges) {
+ dispatch(changeOrderCardDetails(updatedOrderCardDetails));
+ dispatch(ChangeFreeProductList(updatedFreeProdList));
+ dispatch(ChangeOfferAppliedProducts(updatedOfferAppliedProducts));
+ } else {
+ dispatch(changeOrderCardDetails(updatedOrderCardDetails));
+ }
+ return;
+ }
+
+ let bestOffer = null;
+ let OfferNeedToApply = true;
+ let updatedFreeProductList = [];
+ let sameProduct = false;
+ for (const offer of offers) {
+ if (offer.OfferMode === 'B') {
+ const {
+ OfferAmount,
+ OfferMessage,
+ OfferApply,
+ updatedFreeProdList,
+ ProductOfferType,
+ } = applyBuyNGetFreeOffer(cartData, offer, item);
+
+ offer.OfferAmount = OfferAmount;
+ offer.OfferMessage = OfferMessage;
+ OfferNeedToApply = OfferApply;
+ updatedFreeProductList = updatedFreeProdList;
+ sameProduct = ProductOfferType;
+ }
+ if (!bestOffer || offer.OfferAmount > bestOffer.OfferAmount) {
+ bestOffer = offer;
+ }
+ }
+
+ const UpdatedCartItemWithOffer = {
+ ...item,
+ Offer:
+ sameProduct ||
+ bestOffer?.OfferMode === 'I' ||
+ bestOffer?.OfferMode === 'Q'
+ ? bestOffer?.OfferAmount || item.Offer
+ : item.Offer || bestOffer?.OfferAmount,
+ OfferType: item?.OfferType || bestOffer?.OfferType,
+ OfferMessage: item?.OfferMessage || bestOffer?.OfferMessage,
+ OfferMode: item?.OfferMode || bestOffer?.OfferMode,
+ OfferModeType: sameProduct,
+ };
+
+ const shouldRemove = (c) =>
+ c.ProdId === item.ProdId &&
+ c.InwardDtlId === item.InwardDtlId &&
+ c.OrderRate === item.OrderRate &&
+ c.BookingTypeName === item.BookingTypeName &&
+ ((c?.OfferModeType && c?.OfferMode === 'B'
+ ? true
+ : c?.OfferMode !== 'B') &&
+ c?.OfferMode !== 'P' &&
+ c?.OfferMode !== 'C' &&
+ c?.OfferMode !== 'O' &&
+ c?.OfferMode !== 'L'
+ ? true
+ : c?.Offer === 0);
+
+ const filteredCart = CartOrderDetails.filter((c) => !shouldRemove(c));
+
+ const UpdatedDataAfterOffer = addFirst
+ ? [UpdatedCartItemWithOffer, ...filteredCart]
+ : [...filteredCart, UpdatedCartItemWithOffer];
+
+ if (bestOffer && OfferNeedToApply) {
+ dispatch(ChangeOfferAppliedProducts(bestOffer));
+ }
+
+ const {
+ updatedOrderCardDetails,
+ updatedFreeProdList,
+ updatedOfferAppliedProducts,
+ hasChanges,
+ } = processFreeProducts(UpdatedDataAfterOffer, updatedFreeProductList);
+
+ // Update the states
+ dispatch(changeOrderCardDetails(updatedOrderCardDetails));
+
+ if (hasChanges) {
+ dispatch(ChangeFullFreeProductList(updatedFreeProdList));
+ dispatch(ChangeOfferAppliedProducts(updatedOfferAppliedProducts));
+ } else {
+ dispatch(ChangeFullFreeProductList(updatedFreeProductList));
+ }
+ };
+
+ function buildOfferFromChangesForPromoCodes(
+ PromoCodeOffersDatas,
+ ChangesHappenList,
+ item,
+ DineinId,
+ TakAwayId
+ ) {
+ const results = [];
+ ChangesHappenList.forEach((change) => {
+ const offer = PromoCodeOffersDatas.ProdOfferDetails.find(
+ (o) => o.OfferId === change.OfferId
+ );
+ if (offer) {
+ // 🛠️ Build normalized object
+ const formatted = {
+ OfferId: offer?.OfferId || '',
+ OfferAmount: change?.discount || 0,
+ OfferType: offer?.OfferType || '', // I / Q / B
+ ActualOfferAmount: offer?.OfferAmt || 0,
+ OfferValue: offer?.OfferAmt || 0,
+ TableName: change?.TableName || '',
+ TableUniqueName: change?.TableUniqueName || '',
+ TableUniqueId: change?.TableUniqueId || '',
+ // OfferType: offer?.ValueType || "", // F / P
+ Detail: offer?.Detail || [],
+ OfferCode: offer?.OfferCode || PromoCodeOffersDatas?.OfferCode || '',
+ CustId: offer?.CustId || '',
+ UsedCount: offer?.UsedCount || 0,
+ AppliesTo: offer?.AppliesTo || '',
+ BookingType:
+ item?.BookingTypeName === 'Dine In' ? DineinId : TakAwayId,
+ ActualFreeQty: change?.FreeQty,
+
+ // ✅ Merge FreeProducts from offer + update with ChangesHappenList
+ FreeProductsList: {
+ FreeProdId: change?.FreeProdId,
+ FreeQty: change?.FreeQty,
+ FreeProdName: change?.FreeProdName,
+ OfferId: offer?.OfferId,
+ OverAllFreeQty: change?.OverAllFreeQty,
+ ProdVariantDetails: change?.ProdVariantDetails?.map((e) => {
+ return {
+ FreeProdVariantName: e?.FreeProdVariantName,
+ StockDetails: e?.StockDetails?.map((exp) => {
+ return {
+ ProdOfferId: exp?.ProdOfferId,
+ FreeInwardDtlId: exp?.FreeInwardDtlId,
+ ActiveStatus: exp?.ActiveStatus,
+ };
+ }),
+ };
+ }),
+ },
+ // ✅ Always include product-level fields
+ ProdId: '',
+ SinglePc: '',
+ StockAvailable: '',
+ ProdVariantName: '',
+ Type: '',
+ InwardDtlId: '',
+ ProdCat: '',
+ HalfPrice: 'N',
+ MinQty: 0,
+ };
+
+ results.push(formatted);
+ }
+ });
+
+ return results;
+ }
+
+ function buildOfferFromChanges(
+ OverAllproductBasedOfferDatas,
+ ChangesHappenList,
+ item,
+ DineinId,
+ TakeAwayId
+ ) {
+ const offersById = new Map(
+ OverAllproductBasedOfferDatas.ProdDtl.map((o) => [o.OfferId, o])
+ );
+
+ return ChangesHappenList.flatMap((change) => {
+ const offer = offersById.get(change.OfferId);
+ if (!offer) return [];
+
+ const getFreeProductsList = () => {
+ const freeProducts = offer.FreeProducts || offer.FreeProductsList || [];
+ const normalizedList = Array.isArray(freeProducts)
+ ? freeProducts
+ : [freeProducts];
+
+ return normalizedList.map((fp) => {
+ if (!change?.ProdVariantDetails) {
+ return {
+ FreeProdId: fp?.FreeProdId || '',
+ FreeQty: fp?.FreeQty || 0,
+ FreeProdName: fp?.FreeProdName || '',
+ ProdVariantDetails: fp?.ProdVariantDetails || [],
+ };
+ }
+
+ // Merge variant + stock details with change
+ const updatedVariants = fp.ProdVariantDetails?.map((variant) => {
+ const changedVariant = change.ProdVariantDetails.find(
+ (v) => v.FreeProdVariantName === variant.ProdVariantName
+ );
+
+ if (!changedVariant) return variant;
+
+ const updatedStock = variant.StockDetails.map((stock) => {
+ const changedStock = changedVariant.StockDetails.find(
+ (s) => s.InwardDtlId === stock.InwardDtlId
+ );
+
+ if (changedStock) {
+ const { InwardDtlId, ...rest } = { ...stock, ...changedStock };
+ return { ...rest, FreeInwardDtlId: stock.InwardDtlId };
+ }
+
+ const { InwardDtlId, ...rest } = stock;
+ return { ...rest, FreeInwardDtlId: stock.InwardDtlId };
+ });
+
+ return { ...variant, StockDetails: updatedStock };
+ });
+
+ return {
+ FreeProdId: fp?.FreeProdId || '',
+ FreeQty: change?.FreeQty ?? (fp?.FreeQty || 0),
+ FreeProdName: fp?.FreeProdName || '',
+ ProdVariantDetails: updatedVariants || [],
+ };
+ });
+ };
+
+ return {
+ OfferId: offer.OfferId || '',
+ OfferAmount: change?.discount || 0,
+ OfferMode: offer.OfferType || '', // I / Q / B
+ ActualOfferAmount: offer.OfferAmt || 0,
+ OfferValue: offer.OfferAmt || 0,
+ TableName: offer.TableName || '',
+ TableUniqueName: offer.TableUniqueName || '',
+ TableUniqueId: offer.TableUniqueId || '',
+ ActualFreeQty: change?.FreeQty || 0,
+ Detail: offer.Detail || [],
+ OfferCode: offer.OfferCode || '',
+ CustId: offer.CustId || '',
+ UsedCount: offer.UsedCount || 0,
+ AppliesTo: offer.AppliesTo || '',
+ BookingType:
+ item?.BookingTypeName === 'Dine In' ? DineinId : TakeAwayId,
+ FreeProductsList: getFreeProductsList(),
+
+ // Product-level fields
+ ProdId: change?.ProdId || '',
+ SinglePc: change?.SinglePc || '',
+ StockAvailable: change?.StockAvailable || '',
+ ProdVariantName: change?.ProdVariantName || '',
+ Type: item?.Type || '',
+ InwardDtlId: change?.InwardDtlId || '',
+ ProdCat: change?.ProdCat || '',
+ HalfPrice: offer.HalfPrice || 'N',
+ MinQty: offer.MinQty || 0,
+ };
+ });
+ }
+
+ const loyaltyOfferApply = (ChangesHappenList, item, DineinId, TakAwayId) => {
+ const result = [];
+ const change = ChangesHappenList?.[0];
+ const formatted = {
+ OfferId: change?.OfferId,
+ OfferAmount: change?.discount || 0,
+ OfferValue: change?.OfferAmt || 0,
+ TableName: change?.TableName || '',
+ TableUniqueName: change?.TableUniqueName || '',
+ TableUniqueId: change?.TableUniqueId || '',
+ ProdId: change?.ProdId || '',
+ SinglePc: change?.SinglePc || '',
+ StockAvailable: change?.StockAvailable || '',
+ ProdVariantName: change?.ProdVariantName || '',
+ ActualFreeQty: change?.FreeQty || 0,
+ Type: '',
+ BookingType: item?.BookingTypeName === 'Dine In' ? DineinId : TakAwayId,
+ InwardDtlId: change?.InwardDtlId || '',
+ OfferType: change?.OfferMode || '',
+ Detail: [{}],
+ ProdCat: change?.ProdCat || '',
+ CustId: change?.CustId || '',
+ UsedCount:
+ change?.ProdVariantDetails?.reduce(
+ (sum, variant) =>
+ sum +
+ (variant?.StockDetails?.reduce(
+ (variantSum, stock) =>
+ variantSum + (stock?.ProdLoyaltyPoint * stock?.UsedFree || 0),
+ 0
+ ) || 0),
+ 0
+ ) || 0,
+ FreeProductsList: change,
+ };
+ result?.push(formatted);
+ return result;
+ };
+
+ function chooseOfferFun(item, CartData) {
+ return validateOffers(
+ item,
+ OverAllproductBasedOfferDatas,
+ CartData,
+ TakAwayId,
+ DineinId
+ );
+ }
+
+ const handleBulkUpload = async () => {
+ console.log(
+ AllCategoryDatas,
+ AllsubcatgoryDatas,
+ 'AllsubcatgoryDatas',
+ ProdSubCat
+ );
+
+ let ProdcatName =
+ AllCategoryDatas?.find((cat) => cat?.ProdCat == ProdCat)?.ProdCatName ||
+ 'General';
+ let ProdsubcatName =
+ AllsubcatgoryDatas?.find((subcat) => subcat?.ProdSubCat == ProdSubCat)
+ ?.ProdSubCatName || 'General';
+ const Postdata = products?.map((e, index) => {
+ if (e?.name == null || e?.name === '') {
+ setMessageData(`Product Name is missing at Row ${index + 1} `);
+ setMessageType('error');
+ throw new Error(`Product Name is missing at Row ${index + 1} `);
+ }
+ if (e?.price == null || e?.price === '') {
+ setMessageData(
+ `Price is missing for product at Row ${index + 1} (${e?.name || 'Unknown'})`
+ );
+ setMessageType('error');
+ throw new Error(
+ `Price is missing for product at index ${index} (${e?.name || 'Unknown'})`
+ );
+ }
+
+ return {
+ AppId,
+ CompId,
+ BranchId,
+ CreatedBy: UserId,
+ ProdName: e?.name,
+ ProdVariantName: '',
+ ProdCat: ProdcatName,
+ ProdSubCat: ProdsubcatName,
+ Brand: '',
+ PartNumber: '',
+ HSNCode: '',
+ ProdNameCode: e?.code,
+ UOM: e?.UOMName,
+ Size: e?.size || 1,
+ MRP: e.price,
+ SellPrice: e.price,
+ WhSalePrice: '',
+ TaxId: 'NIL - 0%',
+ StockAvailable: 'No',
+ OnePcsAvailable: 'No',
+ TokenAvailable: 'No',
+ AutoGenerateQr: 'No',
+ AutoGenerateSingleQr: 'No',
+ OnePcQR: '',
+ QRCode: '',
+ Rack: '',
+ AvailableFrom: null,
+ AvailableTo: null,
+ ManufDate: null,
+ ExpDate: null,
+ };
+ });
+
+ const response = await dispatch(
+ bulkpostdata({ ProdDetails: Postdata })
+ ).unwrap();
+ if (response?.data?.statusCode === 1) {
+ productCardList();
+ setMessageData(response?.data?.message);
+ setMessageType('success');
+ setNewMoreProductModel(false);
+ setProducts([
+ { id: 1, name: '', price: '', code: '', size: '1', category: '' },
+ ]);
+ } else {
+ setMessageData(response?.data?.message);
+ setMessageType('error');
+ }
+ };
+ function changeFreeProductList(FreeProdList, newFreeProd) {
+ if (!newFreeProd || !newFreeProd.ProdId || !newFreeProd.InwardDtlId) {
+ return FreeProdList; // 🚫 Skip invalid payload
+ }
+
+ const index = FreeProdList.findIndex(
+ (f) =>
+ f.ProdId === newFreeProd.ProdId &&
+ f.InwardDtlId === newFreeProd.InwardDtlId
+ );
+
+ if (index !== -1) {
+ let existing = JSON.parse(JSON.stringify(FreeProdList[index])); // deep clone
+
+ if (newFreeProd.ProdVariantDetails) {
+ newFreeProd.ProdVariantDetails.forEach((newVariant) => {
+ const existingVariant = existing.ProdVariantDetails?.find(
+ (v) => v.VariantName === newVariant.VariantName
+ );
+
+ if (existingVariant) {
+ newVariant.StockDetails.forEach((newStock) => {
+ const existingStock = existingVariant.StockDetails?.find(
+ (s) => s.InwardDtlId === newStock.InwardDtlId
+ );
+
+ if (existingStock) {
+ // ✅ Create a new object instead of mutating
+ existingStock.EligibleFree =
+ (existingStock.EligibleFree || 0) +
+ (newStock.EligibleFree || 0);
+ existingStock.UsedFree =
+ (existingStock.UsedFree || 0) + (newStock.UsedFree || 0);
+ existingStock.RemainingFree =
+ (existingStock.RemainingFree || 0) +
+ (newStock.RemainingFree || 0);
+ } else {
+ existingVariant.StockDetails = [
+ ...existingVariant.StockDetails,
+ { ...newStock },
+ ];
+ }
+ });
+ } else {
+ if (!existing.ProdVariantDetails) existing.ProdVariantDetails = [];
+ existing.ProdVariantDetails = [
+ ...existing.ProdVariantDetails,
+ { ...newVariant },
+ ];
+ }
+ });
+ }
+
+ return FreeProdList.map((f, i) =>
+ i === index
+ ? {
+ ...existing,
+ ...newFreeProd,
+ ProdVariantDetails: existing.ProdVariantDetails,
+ }
+ : f
+ );
+ } else {
+ return [...FreeProdList, { ...newFreeProd }];
+ }
+ }
+
+ function applyBuyNGetFreeOffer(cartItem, offer, item) {
+ const freeList = offer.FreeProductsList || [];
+ let totalDiscount = 0;
+ let offerMessage = '';
+ let OfferApply = true;
+ let sameProductOffer = false;
+ let updatedFreeProdList = [...FreeProdList];
+ freeList.forEach((freeProd) => {
+ let data = updatedFreeProdList?.find(
+ (e) =>
+ e.FreeProdId === freeProd.FreeProdId &&
+ e.InwardDtlId === item?.InwardDtlId
+ );
+ // find matching item in cart
+ const freeCartItem = cartItem.filter(
+ (c) =>
+ c.ProdId === freeProd.FreeProdId &&
+ freeProd?.ProdVariantDetails?.some((pv) =>
+ pv?.StockDetails?.some((s) => s.InwardDtlId === c.InwardDtlId)
)
);
- }
-
- let temppostdata = {
- SalesMode: RetailWSSalesType || 'R',
- CompId: CompId,
- BranchId: BranchId,
- AppId: AppId,
- OrderDate: Custombill ? invoiceDate : null,
- CustomOrderNo: Custombill ? CurrentOrderId : null,
- OrderType:
- Object.keys(ReportholdData)?.length > 0
- ? ReportholdData?.OrderType
- : 'S',
- CustSuppId: SelCustId ? SelCustId : null,
- Reference: 'test',
- BookingType:
- NotSlectedTypeFind && !BookingTypeBoth
- ? NotSlectedTypeFind?.BookingType
- : SelectedBookingType,
- // (NotSlectedTypeFind?.length>0 && !BookingTypeBoth)?NotSlectedTypeFind?.[0]?.BookingTypeName:
-
- ServiceProvider: 0,
- ActiveStatus: 'A',
- CreatedBy: UserId,
- AddlInfo: 'test',
- BillAmount: TotalWithoutTaxAmount,
- OverallDiscSales: OverAllSales > 0 ? OverAllSales : 0,
- OverallDiscEst: OverAllEstimate > 0 ? OverAllEstimate : 0,
- TaxAmount: TotalTaxAmount,
- VatAmount: 0,
- NetAmount: Math.round(TotalAmount),
- PaymentType:
- Paybtnnameselected?.toLowerCase() === 'upi'
- ? SelectedUPIPayOption?.toLowerCase() === 'pd'
- ? PaymentDeviceUPI?.[0]?.ModeId
- : SelectedUPIPayOption?.toLowerCase() === 'pg'
- ? PaymentgatewayUPI?.[0]?.ModeId
- : paybtnselected
- : paybtnselected
- ? paybtnselected
- : null,
- GivenAmt: 0,
- BalGiven: 0,
- BookingMedia: 'DW',
- RefundAmount: 0,
- ServiceCategory: OtherServiceTicketClaim?.ServiceCategory || null,
- OtherServiceTicketId: OtherServiceTicketClaim?.TicketId || null,
- OtherServiceTicketAmount: OtherServiceTicketClaim?.TotalAmt || null,
- PaymentStatus:
- Paybtnnameselected?.toLowerCase() === 'cash'
- ? 'S'
- : Paybtnnameselected?.toLowerCase() === 'credit'
- ? 'S'
- : Paybtnnameselected?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'default'
- ? 'S'
- : 'P',
- OrderDtlDetails:
- Object.keys(ReportholdData)?.length > 0
- ? ProductSummary(temporderdetail)
- : temporderdetail,
- // (BookingType === "Dine In" || BookingTypeBoth)
- ExtraChargeDetails:
- GlobalExtraCharge?.length > 0
- ? extrachargesbookingtype(GlobalExtraCharge)
- : null,
- SalesTableLinkDetails:
- SelectedTableDetails?.length > 0
- ? globalTipAmount === 0
- ? SelectedTableDetails
- : SelectedTableDetails?.map((item) => ({
- ...item,
- TipsAmount: globalTipAmount,
- }))
- : null,
- // "Credit": TotalAmount,
- // "Debit": 0,
- SalesPaymentType: 'normal',
- PaymentDetail: [
- {
- PaymentType:
- Paybtnnameselected?.toLowerCase() === 'upi'
- ? SelectedUPIPayOption?.toLowerCase() === 'pd'
- ? PaymentDeviceUPI?.[0]?.ModeId
- : SelectedUPIPayOption?.toLowerCase() === 'pg'
- ? PaymentgatewayUPI?.[0]?.ModeId
- : paybtnselected
- : paybtnselected
- ? paybtnselected
- : null,
- // SelectedUPIPayOption?.toLowerCase() === "pg" ?
- Amount: Math.round(TotalAmount),
- PaymentOptionType:
- Paybtnnameselected?.toLowerCase() === 'cash'
- ? 'PC'
- : Paybtnnameselected?.toLowerCase() === 'credit'
- ? 'PC'
- : Paybtnnameselected?.toLowerCase() === 'card'
- ? SelectedCardOption
- : Paybtnnameselected?.toLowerCase() === 'upi'
- ? SelectedUPIPayOption?.toLowerCase() === 'default'
- ? 'PC'
- : SelectedUPIPayOption
- : null,
- ModeOfPayment:
- SelectedUPIPayOption?.toLowerCase() === 'default'
- ? PaymentUpiOptions?.find((upipay) => upipay?.UPIId === UpiId)
- ?.UPIDetailId
- : null,
- AccountDtl:
- Paybtnnameselected?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'default'
- ? useOptions?.[0]?.PaymentDetails?.Payatthecounter?.find(
- (upipay) => upipay?.UPIId === UpiId
- )
- : (Paybtnnameselected?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'pd') ||
- (Paybtnnameselected?.toLowerCase() === 'card' &&
- SelectedCardOption?.toLowerCase() === 'pd')
- ? useOptions?.[0]?.PaymentDetails?.PaymentDevice
- : (Paybtnnameselected?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'pg') ||
- (Paybtnnameselected?.toLowerCase() === 'card' &&
- SelectedCardOption?.toLowerCase() === 'pg')
- ? useOptions?.[0]?.PaymentDetails?.PaymentGateway
- : [],
- PaymentStatus:
- Paybtnnameselected?.toLowerCase() === 'cash'
- ? 'S'
- : Paybtnnameselected?.toLowerCase() === 'credit'
- ? 'S'
- : Paybtnnameselected?.toLowerCase() === 'upi' &&
- SelectedUPIPayOption?.toLowerCase() === 'default'
- ? 'S'
- : 'P',
- Debit: 0,
- Credit:
- Paybtnnameselected?.toLowerCase() === 'credit'
- ? Math.round(TotalAmount)
- : 0,
- },
- ],
- OrderOfferDetail: updatedOfferDetails,
- };
- let PostData = temppostdata;
-
- if (value === 'Dine-In') {
- PostData['PaymentStatus'] = pay ? 'S' : 'P';
- PostData['PaymentDetail'] = !pay && [];
- PostData['PaymentType'] = !pay && '';
- } else if (value === 'Hold') {
- ((PostData['PaymentStatus'] = pay ? 'S' : 'P'),
- (PostData['PaymentDetail'] = !pay && []));
- PostData['PaymentType'] = !pay && '';
- PostData['ActiveStatus'] = pay ? 'A' : 'D';
- } else if (value === 'Unpaid') {
- PostData['PaymentStatus'] = pay ? 'S' : 'P';
- PostData['PaymentDetail'] = !pay && [];
- PostData['PaymentType'] = !pay && '';
- PostData['PrintType'] = 'Y';
- }
-
- Object.keys(ReportholdData)?.length > 0
- ? OrderType === 'Failed'
- ? PutFailedPayment(PostData, value, pay)
- : PutBooking(PostData, value, pay)
- : PostBooking(PostData, value);
- };
- const PostBooking = async (PostData, value) => {
- let response = await dispatch(PostBookingData(PostData)).unwrap();
- if (response?.data?.statusCode == 1) {
- let Paymentdevicefilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pd' &&
- item?.PaymentStatus === 'P'
- );
- let PaymentGatewayfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pg' &&
- item?.PaymentStatus === 'P'
- );
- let PayatCounterfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) => item?.PaymentOptionType?.toLowerCase() === 'pc'
- );
- if (
- PayatCounterfilter?.length === 1 ||
- response?.data?.PaymentOrderDtl?.length === 0
- ) {
- setMessageType('success');
- setMessageData(
- response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ // check if it's same product + inward
+ const isSameProduct =
+ offer.ProdId === freeProd.FreeProdId &&
+ freeProd?.ProdVariantDetails?.some((fpv) =>
+ fpv?.StockDetails?.some(
+ (fs) => fs.InwardDtlId === freeCartItem?.[0]?.InwardDtlId
+ )
);
- response?.data?.OrderDetails?.length > 0 &&
- setPrintOrderDetails([response?.data]);
- CustomerDisplay(value);
- filteredSettingNames?.includes('whatsapp') &&
- MobileNoWhatsApp?.value &&
- handleURL([response?.data]);
- ClearAllGlobalStateDatas(value);
+
+ if (!isSameProduct) {
+ const buyQty = offer.BuyQty || 1;
+ const getQty = freeProd.FreeQty || 0;
+
+ // 🔥 Find how many buy-product are in cart
+ const buyCartItem = cartItem.find((c) => c.ProdId === offer.ProdId);
+
+ if (buyCartItem) {
+ const eligibleCycles = Math.floor(buyCartItem.OrderQty / buyQty);
+ const totalFreeEligible = eligibleCycles * getQty;
+
+ if (totalFreeEligible > 0) {
+ offerMessage = `Add ${totalFreeEligible} ${freeProd.FreeProdName} free`;
+ }
+ }
}
- if (Paymentdevicefilter?.length === 1) {
- if (
- Paymentdevicefilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pd'
- ) {
- PaymentDeviceFlow(Paymentdevicefilter, value);
- }
+ if (offer.HalfPrice === 'Y' && isSameProduct) {
+ // 🔥 Half price for same product
+ totalDiscount +=
+ freeCartItem?.reduce((acc, fc) => acc + (fc?.OrderQty || 0), 0) *
+ freeCartItem?.[0]?.OrderRate *
+ 0.5;
+ sameProductOffer = true;
+ } else if (isSameProduct) {
+ // 🔥 Buy N Get M (same product)
+ const buyQty = offer.BuyQty || 1;
+ const getQty = freeProd.FreeQty || 0;
+
+ const cycleSize = buyQty + getQty;
+ const fullCycles = Math.floor(
+ freeCartItem?.reduce((acc, fc) => acc + (fc?.OrderQty || 0), 0) /
+ cycleSize
+ );
+ const totalFreeQty = fullCycles * getQty;
+
+ totalDiscount += totalFreeQty * freeCartItem?.[0].OrderRate;
+ sameProductOffer = true;
+ // offerMessage = `${freeProd.FreeProdName} -> ${Math.ceil(totalFreeQty / 2)} qty Free Eligible`;
} else {
- console.log('more pd data');
+ // 🔥 Different product free
+ const buyQty = offer.BuyQty || 1;
+ const getQty = freeProd.FreeQty;
+
+ // find buy product qty in cart
+ const buyCartItem = cartItem.filter(
+ (c) =>
+ c?.ProdId === offer?.ProdId &&
+ (offer?.InwardDtlId ? c?.InwardDtlId === offer?.InwardDtlId : true)
+ );
+
+ const buyOrderQty = buyCartItem?.reduce(
+ (acc, fc) => acc + (fc?.OrderQty || 0),
+ 0
+ );
+
+ // ✅ total eligible free qty (cycles of Buy X Get Y)
+ const eligibleCycles = Math.floor(buyOrderQty / buyQty);
+ const totalFreeQty = eligibleCycles * getQty;
+
+ totalDiscount += 0;
+
+ // 🟢 Offer message handling
+ if (buyOrderQty === 0) {
+ offerMessage = `No free eligible right now`;
+ } else if (buyOrderQty % buyQty !== 0) {
+ const remainingToNext = buyQty - (buyOrderQty % buyQty);
+ offerMessage = `Buy ${remainingToNext} more ${offer.ProdName} to get ${getQty} ${freeProd.FreeProdName} free`;
+ } else if (totalFreeQty > 0) {
+ offerMessage = `${freeProd.FreeProdName} -> ${totalFreeQty} qty Free Eligible`;
+ } else {
+ offerMessage = `No free eligible right now`;
+ }
+
+ const usedFree = data?.FreeQty || 0;
+ const remainingFree = Math.max(totalFreeQty - usedFree, 0);
+
+ const FreeProdList = {
+ OfferId: offer.OfferId,
+ ProdId: item?.ProdId,
+ ProdVariantName: item?.ProdVariantName,
+ StockAvailable: item?.StockAvailable,
+ OfferMode: offer.OfferMode,
+ TableName: offer.TableName,
+ TableUniqueName: offer.TableUniqueName,
+ InwardDtlId: item?.InwardDtlId || null,
+ FreeProdId: freeProd.FreeProdId,
+ FreeProdName: freeProd.FreeProdName,
+ ProdCat: item?.ProdCat,
+ SinglePc: item?.SinglePc,
+ BatchRef: item?.BatchRef,
+ OverAllFreeQty: totalFreeQty,
+ FreeQty: usedFree,
+ RemainingQty: remainingFree,
+
+ ProdVariantDetails: freeProd.ProdVariantDetails.map((variant) => ({
+ FreeProdVariantName: variant.ProdVariantName,
+ StockDetails: variant.StockDetails.map((stock) => {
+ // 🔎 inward-based usage
+ const matchedCartItem = cartItem.find(
+ (c) =>
+ c.ProdId === freeProd.FreeProdId &&
+ c.InwardDtlId === stock.InwardDtlId
+ );
+
+ const usedFreeForStock = matchedCartItem?.OrderQty || 0;
+ const remainingFreeForStock = Math.max(
+ totalFreeQty - usedFreeForStock,
+ 0
+ );
+
+ return {
+ FreeInwardDtlId: stock.InwardDtlId,
+ ProdOfferId: stock.ProdOfferId,
+ ActiveStatus: stock.ActiveStatus,
+ EligibleFree: totalFreeQty, // still overall, can later split if needed
+ UsedFree: usedFreeForStock,
+ RemainingFree: remainingFreeForStock,
+ };
+ }),
+ })),
+ };
+
+ updatedFreeProdList = changeFreeProductList(
+ updatedFreeProdList,
+ FreeProdList
+ );
+
+ OfferApply = false;
}
- if (PaymentGatewayfilter?.length === 1) {
- if (
- PaymentGatewayfilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pg'
- ) {
- await dispatch(changePaymentloader(true));
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- OrderBookingId: PaymentGatewayfilter?.[0]?.OrderId,
- Paymentgateway: true,
- OrderPaymentId: PaymentGatewayfilter?.[0]?.PaymentOrderId,
- OrderTotalAmount: PaymentGatewayfilter?.[0]?.Amount,
+ });
+
+ return {
+ OfferAmount: totalDiscount,
+ OfferMessage: offerMessage,
+ OfferApply: OfferApply,
+ updatedFreeProdList: updatedFreeProdList,
+ ProductOfferType: sameProductOffer ? true : false,
+ };
+ }
+
+ const processFreeProducts = (updatedData, freeProdList) => {
+ if (!freeProdList || freeProdList.length === 0) {
+ return {
+ updatedOrderCardDetails: updatedData,
+ updatedFreeProdList: freeProdList,
+ updatedOfferAppliedProducts: [],
+ hasChanges: false,
+ };
+ }
+ // Filter only free products with remaining quantity
+ const availableFreeProdList = freeProdList?.filter(
+ (prod) => prod?.RemainingQty > 0
+ );
+
+ let updatedOrderCardDetails = [];
+ let updatedFreeProdList = [...freeProdList]; // Create a copy to avoid mutations
+ let updatedOfferAppliedProducts = []; // Track offer applied products
+ let hasChanges = false;
+
+ updatedData?.forEach((item) => {
+ // STEP 1: Check if item is already a free product (with offer applied)
+ const foundInFreeProdList = freeProdList?.filter(
+ (prod) =>
+ prod?.OfferId === item?.OfferMessage?.[0]?.OfferId &&
+ prod?.FreeProdId === item?.ProdId &&
+ prod?.OfferMode === item?.OfferMode &&
+ prod?.ProdVariantDetails?.some((variant) =>
+ variant?.StockDetails?.some(
+ (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
+ )
+ )
+ );
+
+ // STEP 2: Check if item is a paid product that can be converted to free
+ const availableFreeProduct = updatedFreeProdList?.find(
+ (prod) =>
+ prod?.FreeProdId === item?.ProdId &&
+ prod?.RemainingQty > 0 &&
+ prod?.ProdVariantDetails?.some((variant) =>
+ variant?.StockDetails?.some(
+ (stock) => stock?.FreeInwardDtlId === item?.InwardDtlId
+ )
+ ) &&
+ item?.SinglePc !== 'Y'
+ );
+
+ const isPaidProductThatCanBeFree =
+ availableFreeProduct &&
+ (!item.OfferMode || item.OfferMode?.trim() === '') &&
+ (item.Offer === 0 || !item.Offer);
+
+ // STEP 3: Handle paid product conversion to free
+ if (isPaidProductThatCanBeFree) {
+ hasChanges = true; // Mark that changes occurred
+
+ const maxFreeQty = Math.min(
+ item.OrderQty,
+ availableFreeProduct.RemainingQty
+ );
+ const remainingPaidQty = Math.max(
+ item.OrderQty - availableFreeProduct.RemainingQty,
+ 0
+ );
+
+ // Create free item
+ if (maxFreeQty > 0) {
+ const freeItem = {
+ ...item,
+ OrderQty: maxFreeQty,
+ TotalAmt: maxFreeQty * item.OrderRate,
+ Offer: maxFreeQty * item.OrderRate, // Full discount
+ OfferType: availableFreeProduct.OfferMode,
+ OfferMode: availableFreeProduct.OfferMode,
+ TaxAmt: (
+ (maxFreeQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate: (
+ maxFreeQty * item.OrderRate -
+ (maxFreeQty * item.OrderRate * item.TaxPercentage) / 100
+ ).toFixed(2),
+ OfferMessage: [
+ {
+ OfferId: availableFreeProduct.OfferId,
+ FreeQty: maxFreeQty,
+ FreeProdId: availableFreeProduct.FreeProdId,
+ FreeProdName: availableFreeProduct.FreeProdName,
+ },
+ ],
+ };
+
+ // Check if free version already exists in updatedOrderCardDetails
+ const existingFreeIndex = updatedOrderCardDetails.findIndex(
+ (od) =>
+ od.ProdId === freeItem.ProdId &&
+ od.InwardDtlId === freeItem.InwardDtlId &&
+ od.OrderRate === freeItem.OrderRate &&
+ od.BookingTypeName === freeItem.BookingTypeName &&
+ od.OfferMode === freeItem.OfferMode &&
+ od.Offer > 0 &&
+ od.MRP === freeItem.MRP
+ );
+
+ if (existingFreeIndex !== -1) {
+ // Merge with existing free item
+ const existing = updatedOrderCardDetails[existingFreeIndex];
+ updatedOrderCardDetails[existingFreeIndex] = {
+ ...existing,
+ OrderQty: existing.OrderQty + freeItem.OrderQty,
+ TotalAmt: existing.TotalAmt + freeItem.TotalAmt,
+ Offer: existing.Offer + freeItem.Offer,
+ WithoutTaxRate: (
+ parseFloat(existing.WithoutTaxRate) +
+ parseFloat(freeItem.WithoutTaxRate)
+ ).toFixed(2),
+ TaxAmt: (
+ parseFloat(existing.TaxAmt) + parseFloat(freeItem.TaxAmt)
+ ).toFixed(2),
};
- customerDisplayWindow.postMessage(updatedData, '*');
} else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
+ freeItem.localId = uuidv4();
+ updatedOrderCardDetails.push(freeItem);
}
- const checkPaymentStatus = async () => {
- const intervalId = setInterval(async () => {
- try {
- let getpaymentgatewaydetail = await dispatch(
- PaymentGatewayGetdetail(PaymentGatewayfilter?.[0]?.OrderId)
- ).unwrap();
- if (getpaymentgatewaydetail?.data?.statusCode === 1) {
- let paymentdataget =
- getpaymentgatewaydetail?.data?.PaymentOrderDtl?.find(
- (item) =>
- item?.PaymentOrderId ===
- PaymentGatewayfilter?.[0]?.PaymentOrderId
- )?.PaymentStatus;
+ // Update the free product list (create new object to avoid mutation)
+ const freeProductIndex = updatedFreeProdList.findIndex(
+ (f) =>
+ f.OfferId === availableFreeProduct.OfferId &&
+ f.FreeProdId === availableFreeProduct.FreeProdId
+ );
- if (paymentdataget === 'S') {
- setMessageType('success');
- setMessageData('Payment Success');
- await dispatch(changePaymentloader(false));
- if (
- getpaymentgatewaydetail?.data?.OrderDetails?.length > 0
- ) {
- setPrintOrderDetails([getpaymentgatewaydetail?.data]);
- CustomerDisplay(value);
- ClearAllGlobalStateDatas(value);
- }
- clearInterval(intervalId); // Stop the loop when payment is successful
- } else if (paymentdataget === 'F') {
- setMessageType('error');
- setMessageData('Payment Failed');
- await dispatch(changePaymentloader(false));
- setFirstPaymentclick(false);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- clearInterval(intervalId); // Stop the loop when payment fails
- CustomerDisplayRemovedData();
- ClearAllGlobalStateDatas(value);
+ if (freeProductIndex !== -1) {
+ updatedFreeProdList[freeProductIndex] = {
+ ...updatedFreeProdList[freeProductIndex],
+ FreeQty:
+ (updatedFreeProdList[freeProductIndex].FreeQty || 0) +
+ maxFreeQty,
+ RemainingQty:
+ updatedFreeProdList[freeProductIndex].RemainingQty - maxFreeQty,
+ ProdVariantDetails: updatedFreeProdList[
+ freeProductIndex
+ ].ProdVariantDetails.map((variant) => ({
+ ...variant,
+ StockDetails: variant.StockDetails.map((stock) => {
+ if (stock.FreeInwardDtlId === item.InwardDtlId) {
+ return {
+ ...stock,
+ UsedFree: (stock.UsedFree || 0) + maxFreeQty,
+ RemainingFree: Math.max(
+ (stock.RemainingFree || 0) - maxFreeQty,
+ 0
+ ),
+ };
}
- }
- } catch (error) {
- console.error('Error fetching payment details: ', error);
- }
- }, 3000); // Call the API every 3 seconds
+ return stock;
+ }),
+ })),
+ discount:
+ (updatedFreeProdList[freeProductIndex].discount || 0) +
+ maxFreeQty * item.OrderRate,
+ };
+ }
+
+ const filteredOfferAppliedProduct = offerAppliedProducts?.find(
+ (op) =>
+ op.OfferId === availableFreeProduct.OfferId &&
+ op.ProdId === availableFreeProduct.ProdId &&
+ op.InwardDtlId === availableFreeProduct.InwardDtlId &&
+ op.OfferMode === availableFreeProduct.OfferMode
+ );
+ // Create offer applied product entry
+ const offerAppliedProduct = {
+ OfferId: availableFreeProduct.OfferId,
+ ProdId: availableFreeProduct.ProdId,
+ InwardDtlId: availableFreeProduct.InwardDtlId,
+ OfferAmount:
+ (filteredOfferAppliedProduct?.OfferAmount || 0) +
+ maxFreeQty * item.OrderRate, // Total discount amount
+ OfferMode: availableFreeProduct.OfferMode,
+ OfferType: availableFreeProduct.OfferType,
+ TableName: availableFreeProduct.TableName,
+ TableUniqueName: availableFreeProduct.TableUniqueName,
+ ActualOfferAmount:
+ (filteredOfferAppliedProduct?.OfferAmount || 0) +
+ maxFreeQty * item.OrderRate,
+ OfferValue:
+ (filteredOfferAppliedProduct?.OfferValue || 0) +
+ maxFreeQty * item.OrderRate,
+ ActualFreeQty:
+ (filteredOfferAppliedProduct?.ActualFreeQty || 0) + maxFreeQty,
+ AppliesTo: item.ProdId,
+ BookingType:
+ item.BookingType ||
+ (item.BookingTypeName === 'Dine In' ? DineinId : TakAwayId),
+ FreeProductsList: [
+ {
+ FreeProdId: availableFreeProduct.FreeProdId,
+ FreeQty:
+ (filteredOfferAppliedProduct?.FreeProductsList?.[0]
+ ?.FreeQty || 0) + maxFreeQty,
+ FreeProdName: availableFreeProduct.FreeProdName,
+ ProdVariantDetails:
+ availableFreeProduct.ProdVariantDetails || [],
+ },
+ ],
+ // Product-level fields
+ SinglePc: item.SinglePc,
+ StockAvailable: item.StockAvailable,
+ ProdVariantName: item.ProdVariantName,
+ Type: item.Type,
+ ProdCat: item.ProdCat,
+ HalfPrice: availableFreeProduct.HalfPrice,
+ MinQty: availableFreeProduct.MinQty,
};
- // Call the function to start checking payment status
- checkPaymentStatus();
+ updatedOfferAppliedProducts.push(offerAppliedProduct);
}
- } else {
- console.log('more pg data');
- }
- } else {
- setMessageType('error');
- setMessageData(response?.data?.response);
- setFirstPaymentclick(false);
- // clearInvoiceDate
- clearInvoiceDate();
- dispatch(changeCurrentOrderId(null));
- }
- };
- const PutBooking = async (putdatas, value, pay) => {
- let putdata = putdatas;
- putdata['OrderId'] = ReportholdData?.OrderId;
- putdata['SalesId'] = ReportholdData?.SalesId;
- putdata['UpdatedBy'] = UserId;
- if (value === 'Dine-In') {
- putdata['PaymentStatus'] = pay ? 'S' : 'P';
- putdata['PaymentDetail'] = !pay && [];
- putdata['PaymentType'] = !pay && '';
- } else if (value === 'Hold') {
- ((putdata['PaymentStatus'] = pay ? 'S' : 'P'),
- (putdata['PaymentDetail'] = !pay && []));
- putdata['PaymentType'] = !pay && '';
- putdata['ActiveStatus'] = pay ? 'A' : 'D';
- } else if (value === 'Unpaid') {
- putdata['PaymentStatus'] = pay ? 'S' : 'P';
- putdata['PaymentDetail'] = !pay && [];
- putdata['PaymentType'] = !pay && '';
- putdata['PrintType'] = 'Y';
- }
- let response = await dispatch(PutBookingData(putdata)).unwrap();
- let PayatCounterfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) => item?.PaymentOptionType?.toLowerCase() === 'pc'
- );
- if (value !== 'Unpaid') {
- if (response?.data?.statusCode == 1) {
- let Paymentdevicefilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pd' &&
- item?.PaymentStatus === 'P'
- );
- let PaymentGatewayfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pg' &&
- item?.PaymentStatus === 'P'
- );
+ // Create paid item for remaining quantity
+ if (remainingPaidQty > 0) {
+ const paidItem = {
+ ...item,
+ OrderQty: remainingPaidQty,
+ TotalAmt: remainingPaidQty * item.OrderRate,
+ TaxAmt: (
+ (remainingPaidQty * item.OrderRate * item.TaxPercentage) /
+ 100
+ ).toFixed(2),
+ WithoutTaxRate: (
+ remainingPaidQty * item.OrderRate -
+ (remainingPaidQty * item.OrderRate * item.TaxPercentage) / 100
+ ).toFixed(2),
+ Offer: 0,
+ OfferType: '',
+ OfferMessage: [],
+ OfferMode: '',
+ };
- if (
- PayatCounterfilter?.length === 1 ||
- response?.data?.PaymentOrderDtl?.length === 0
- ) {
- setMessageType('success');
- setMessageData(
- response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
+ // Remove offer-related properties
+ delete paidItem.OfferType;
+ delete paidItem.OfferMessage;
+ delete paidItem.OfferMode;
+
+ // Check if paid version already exists
+ const existingPaidIndex = updatedOrderCardDetails.findIndex(
+ (od) =>
+ od.ProdId === paidItem.ProdId &&
+ od.InwardDtlId === paidItem.InwardDtlId &&
+ od.OrderRate === paidItem.OrderRate &&
+ !od.SalesId &&
+ (od.Offer === 0 || !od.Offer) &&
+ od.MRP === paidItem.MRP
);
- response?.data?.OrderDetails?.length > 0 &&
- setPrintOrderDetails([response?.data]);
- CustomerDisplay(value);
- ClearAllGlobalStateDatas(value);
+
+ if (existingPaidIndex !== -1) {
+ // Merge with existing paid item
+ const existing = updatedOrderCardDetails[existingPaidIndex];
+ updatedOrderCardDetails[existingPaidIndex] = {
+ ...existing,
+ OrderQty: existing.OrderQty + paidItem.OrderQty,
+ TotalAmt: existing.TotalAmt + paidItem.TotalAmt,
+ WithoutTaxRate: (
+ parseFloat(existing.WithoutTaxRate) +
+ parseFloat(paidItem.WithoutTaxRate)
+ ).toFixed(2),
+ TaxAmt: (
+ parseFloat(existing.TaxAmt) + parseFloat(paidItem.TaxAmt)
+ ).toFixed(2),
+ };
+ } else {
+ paidItem.localId = uuidv4();
+ updatedOrderCardDetails.push(paidItem);
+ }
}
- if (Paymentdevicefilter?.length === 1) {
- if (
- Paymentdevicefilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pd'
- ) {
- PaymentDeviceFlow(Paymentdevicefilter, value);
+
+ return; // Skip the rest of processing for this item
+ }
+
+ // STEP 4: Handle existing free products (original logic)
+ if (foundInFreeProdList?.length > 0) {
+ const freeProduct = foundInFreeProdList[0];
+
+ if (freeProduct?.RemainingQty !== 0) {
+ // If there are remaining free quantities, push the original item
+ const isAlreadyExists = updatedOrderCardDetails.findIndex(
+ (od) =>
+ od.ProdId === item.ProdId &&
+ od.InwardDtlId === item.InwardDtlId &&
+ od.OrderRate === item.OrderRate &&
+ od.BookingTypeName === item.BookingTypeName &&
+ !od.SalesId &&
+ od.OfferMode === item.OfferMode &&
+ od.Offer > 0 &&
+ od.MRP === item.MRP
+ );
+
+ if (isAlreadyExists !== -1) {
+ updatedOrderCardDetails[isAlreadyExists] = {
+ ...updatedOrderCardDetails[isAlreadyExists],
+ OrderQty:
+ updatedOrderCardDetails[isAlreadyExists].OrderQty +
+ item.OrderQty,
+ TotalAmt:
+ updatedOrderCardDetails[isAlreadyExists].TotalAmt +
+ item.TotalAmt,
+ WithoutTaxRate:
+ updatedOrderCardDetails[isAlreadyExists].WithoutTaxRate +
+ item.WithoutTaxRate,
+ Offer:
+ updatedOrderCardDetails[isAlreadyExists].Offer + item.Offer,
+ OfferMessage:
+ updatedOrderCardDetails[isAlreadyExists]?.OfferMessage?.[0]
+ ?.FreeQty > item?.OfferMessage?.[0]?.FreeQty
+ ? updatedOrderCardDetails[isAlreadyExists]?.OfferMessage
+ : item?.OfferMessage,
+ };
+ } else {
+ updatedOrderCardDetails.push(item);
+ }
+ } else if (
+ freeProduct?.RemainingQty === 0 &&
+ item?.OrderQty > freeProduct?.FreeQty
+ ) {
+ // Split the item into free and paid portions
+ const freeQty = freeProduct.FreeQty;
+ const paidQty = item.OrderQty - freeProduct.FreeQty;
+
+ // Create free item (with original offer details)
+ const freeItem = {
+ ...item,
+ OrderQty: freeQty,
+ WithoutTaxRate: freeQty * item.OrderRate,
+ TotalAmt: freeQty * item.OrderRate,
+ Offer: freeQty * item.OrderRate,
+ };
+
+ // Create paid item (without offer details)
+ const paidItem = {
+ ...item,
+ OrderQty: paidQty,
+ TotalAmt: paidQty * (item.SellingPrice || item.OrderRate),
+ WithoutTaxRate: paidQty * item.OrderRate,
+ Offer: 0,
+ OfferType: '',
+ OfferMessage: [],
+ OfferMode: '',
+ };
+
+ delete paidItem.OfferType;
+ delete paidItem.OfferMessage;
+ delete paidItem.OfferMode;
+
+ updatedOrderCardDetails.push(freeItem);
+
+ const isAlreadyExists = updatedOrderCardDetails.findIndex(
+ (od) =>
+ od.ProdId === paidItem.ProdId &&
+ od.InwardDtlId === paidItem.InwardDtlId &&
+ od.OrderRate === paidItem.OrderRate &&
+ !od.SalesId &&
+ (od.Offer === 0 || !od.Offer)
+ );
+
+ if (isAlreadyExists !== -1) {
+ const existingItem = updatedOrderCardDetails[isAlreadyExists];
+ updatedOrderCardDetails[isAlreadyExists] = {
+ ...existingItem,
+ OrderQty: existingItem.OrderQty + paidItem.OrderQty,
+ TotalAmt: existingItem.TotalAmt + paidItem.TotalAmt,
+ WithoutTaxRate:
+ existingItem.WithoutTaxRate + paidItem.WithoutTaxRate,
+ };
+ } else {
+ paidItem.localId = uuidv4();
+ updatedOrderCardDetails.push(paidItem);
}
} else {
- console.log('more pd data');
- }
- if (PaymentGatewayfilter?.length === 1) {
- await PaymentGatewayFlow(PaymentGatewayfilter);
- } else {
- console.log('more pg data');
+ updatedOrderCardDetails.push(item);
}
} else {
- // clearInvoiceDate
- clearInvoiceDate();
- dispatch(changeCurrentOrderId(null));
+ // STEP 5: No matching free product found, push original item
+ updatedOrderCardDetails.push(item);
}
- } else {
- setPrintOrderDetails([response?.data]);
+ });
- if (OfferCheckedInSetup && preferenceOffer) {
- await applyOffer([]);
- } else {
- dispatch(changeOrderCardDetails([]));
- }
- await dispatch(changeReorderHoldDetails({}));
- await dispatch(changeReorderProductDetails([]));
- setFirstPaymentclick(false);
- await dispatch(changeBookingType('TakeAway'));
- await dispatch(changeSelectTable([]));
- await dispatch(changeSelectChair([]));
- getUnpaiddatas();
- }
- };
- const PutFailedPayment = async (PayData, value, pay) => {
- console.log(PayData?.PaymentDetail?.[0]?.PaymentType, 'mohanPayData');
- let tempsplitdata = {
- CompId: PayData?.CompId,
- BranchId: PayData?.BranchId,
- AppId: PayData?.AppId,
- CustSuppId: PayData?.SelCustId ? SelCustId : null,
- UpdatedBy: UserId,
- OrderId: ReportholdData?.OrderId,
- PaymentType: PayData?.PaymentDetail?.[0]?.PaymentType,
- Amount: FailedTotalAmt,
- PaymentOptionType: PayData?.PaymentDetail?.[0]?.PaymentOptionType,
- ModeOfPayment: PayData?.PaymentDetail?.[0]?.ModeOfPayment,
- AccountDtl: PayData?.PaymentDetail?.[0]?.AccountDtl,
- PaymentStatus: PayData?.PaymentDetail?.[0]?.PaymentStatus,
- Debit: PayData?.PaymentDetail?.[0]?.Debit,
- Credit: PayData?.PaymentDetail?.[0]?.Credit,
+ return {
+ updatedOrderCardDetails,
+ updatedFreeProdList,
+ updatedOfferAppliedProducts,
+ hasChanges,
};
-
- let response = await dispatch(
- putSplitpaymentStatus(tempsplitdata)
- ).unwrap();
- if (response?.data?.statusCode == 1) {
- let Paymentdevicefilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pd' &&
- item?.PaymentStatus === 'P'
- );
- let PaymentGatewayfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pg' &&
- item?.PaymentStatus === 'P'
- );
- let PayatCounterfilter = response?.data?.PaymentOrderDtl?.filter(
- (item) =>
- item?.PaymentOptionType?.toLowerCase() === 'pc' &&
- item?.PaymentType === PayData?.PaymentDetail?.[0]?.PaymentType
- );
- if (
- PayatCounterfilter?.length > 0 ||
- response?.data?.PaymentOrderDtl?.length === 0
- ) {
- setMessageType('success');
-
- // setSplitSelPayMode({...SplitSelPayMode,...{[`PaymentStatus-${i}`]:"S"}})
-
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- upi: null,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- setMessageData(
- response?.data?.response +
- ' ' +
- (response?.data?.OrderDetails?.length > 0
- ? response?.data?.OrderId &&
- extractLastNumberOrderId(
- response?.data?.OrderId,
- response?.data?.OrderDetails?.[0]?.FYStatus
- )
- : '')
- );
- if (response?.data?.OrderDetails?.length > 0) {
- setPrintOrderDetails([response?.data]);
- CustomerDisplay();
- ClearAllGlobalStateDatas();
- }
- }
- if (Paymentdevicefilter?.length === 1) {
- if (
- Paymentdevicefilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pd'
- ) {
- PaymentDeviceFlow(Paymentdevicefilter, value);
- }
- }
-
- if (PaymentGatewayfilter?.length === 1) {
- if (
- PaymentGatewayfilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pg'
- ) {
- PaymentGatewayFlow(PaymentGatewayfilter, value);
- }
- }
- }
};
- const PaymentDeviceFlow = async (Paymentdevicefilter, value) => {
- await dispatch(changePaymentloader(true));
- await dispatch(
- changePaymentTransactionNumber(Paymentdevicefilter?.[0]?.PaymentOrderId)
+
+ const returnCount = (ProdName, currentQty, orderDetails, overallpcs) => {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdName === ProdName
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ },
+ 0
);
- let paymentdetail = {
- TransactionNumber: Paymentdevicefilter?.[0]?.PaymentOrderId,
- SequenceNumber: 1,
- AllowedPaymentMode:
- Paymentdevicefilter?.[0]?.PaymentTypeName?.toLowerCase() === 'card'
- ? '1'
- : Paymentdevicefilter?.[0]?.PaymentTypeName?.toLowerCase() === 'upi'
- ? '10'
- : '',
- Amount: `${parseInt(Paymentdevicefilter?.[0]?.Amount) * 100}`,
- ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
- StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
- UserID: useOptions?.[0]?.PDConfigDetails?.[0]?.UserId,
- MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
- SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
- IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
- AutoCancelDurationInMinutes:
- useOptions?.[0]?.PDConfigDetails?.[0]?.AutoCancelDurationInMinutes,
- };
- let apiresponse = await dispatch(PostPaymentdevice(paymentdetail)).unwrap();
- if (apiresponse?.ResponseMessage?.toLowerCase() === 'approved') {
- let pendingPaymentList = {
- MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
- SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
- ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
- StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
- IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
- PlutusTransactionReferenceId: apiresponse?.PlutusTransactionReferenceID,
- PaymentOrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
- UpdatedBy: UserId,
- };
- await dispatch(PutPendingPaymentList(pendingPaymentList)).unwrap();
- let isApproved = false;
- const startTime = Date.now();
- let postpaymentdata = {
- MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
- SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
- ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
- StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
- IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
- PlutusTransactionReferenceID: apiresponse?.PlutusTransactionReferenceID,
- };
- // Loop to call the second API every 3 seconds
- while (!isApproved) {
- let ApiResponseget = await dispatch(
- GetPaymentdeviceResponse(postpaymentdata)
- ).unwrap();
-
- if (ApiResponseget?.ResponseMessage?.toLowerCase() === 'txn approved') {
- let putbookingdata = {
- OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
- OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
- PaymentStatus: 'S',
- Amount: Paymentdevicefilter?.[0]?.Amount,
- ResponseDtl: [ApiResponseget],
- PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
- UpdatedBy: UserId,
- };
-
- let bookingpaymentupdate = await dispatch(
- PutBookingPaymentStatusChange(putbookingdata)
- ).unwrap();
- if (bookingpaymentupdate?.data?.statusCode === 1) {
- setMessageType('success');
- setMessageData(
- bookingpaymentupdate?.data?.response +
- ' ' +
- (bookingpaymentupdate?.data?.OrderDetails?.length > 0
- ? bookingpaymentupdate?.data?.OrderId &&
- extractLastNumberOrderId(
- bookingpaymentupdate?.data?.OrderId,
- bookingpaymentupdate?.data?.OrderDetail?.[0]?.FYStatus
- )
- : '')
- );
- bookingpaymentupdate?.data?.OrderDetails?.length > 0 &&
- setPrintOrderDetails([bookingpaymentupdate?.data]);
- CustomerDisplay(value);
- ClearAllGlobalStateDatas(value);
- dispatch(changePaymentloader(false));
- }
- isApproved = true;
- console.log('Transaction Approved!');
- // Exit the loop
- break;
- }
-
- // Check if 1 minute has passed
- if (
- Date.now() - startTime >
- useOptions?.[0]?.PDConfigDetails?.[0]?.AutoCancelDurationInMinutes *
- 60000
- ) {
- // 60,000 ms = 1 minute
-
- let putbookingdata = {
- OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
- OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
- PaymentStatus: 'F',
- Amount: Paymentdevicefilter?.[0]?.Amount,
- ResponseDtl: [ApiResponseget],
- PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
- UpdatedBy: UserId,
- };
-
- let bookingpaymentupdate = await dispatch(
- PutBookingPaymentStatusChange(putbookingdata)
- ).unwrap();
- if (bookingpaymentupdate?.data?.statusCode === 1) {
- setMessageType('error');
- setMessageData(
- `Payment Failed. Your Transaction Number is ${Paymentdevicefilter?.[0]?.PaymentOrderId}`
- );
- setFirstPaymentclick(false);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- dispatch(changePaymentloader(false));
- CustomerDisplayRemovedData();
- ClearAllGlobalStateDatas(value);
- }
-
- console.error('Transaction not approved within 1 minute.');
- // Send an error message or handle the timeout
- // You can dispatch an action, show a notification, etc.
- break;
- }
-
- // Wait for 3 seconds before making the next call
- await new Promise((resolve) => setTimeout(resolve, 3000));
- }
- } else {
- let putbookingdata = {
- OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
- OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
- PaymentStatus: 'F',
- Amount: Paymentdevicefilter?.[0]?.Amount,
- PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
- UpdatedBy: UserId,
- };
- let bookingpaymentupdate = await dispatch(
- PutBookingPaymentStatusChange(putbookingdata)
- ).unwrap();
- if (bookingpaymentupdate?.data?.statusCode === 1) {
- setMessageType('error');
- setMessageData(apiresponse?.ResponseMessage);
- setFirstPaymentclick(false);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- dispatch(changePaymentloader(false));
- CustomerDisplayRemovedData();
- ClearAllGlobalStateDatas(value);
- }
- }
- };
- const PaymentGatewayFlow = async (PaymentGatewayfilter) => {
- if (PaymentGatewayfilter?.[0]?.PaymentOptionType?.toLowerCase() === 'pg') {
- await dispatch(changePaymentloader(true));
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- OrderBookingId: PaymentGatewayfilter?.[0]?.OrderId,
- Paymentgateway: true,
- OrderPaymentId: PaymentGatewayfilter?.[0]?.PaymentOrderId,
- OrderTotalAmount: PaymentGatewayfilter?.[0]?.Amount,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- const checkPaymentStatus = async () => {
- const intervalId = setInterval(async () => {
- try {
- let getpaymentgatewaydetail = await dispatch(
- PaymentGatewayGetdetail(PaymentGatewayfilter?.[0]?.OrderId)
- ).unwrap();
-
- if (getpaymentgatewaydetail?.data?.statusCode === 1) {
- let paymentdataget =
- getpaymentgatewaydetail?.data?.PaymentOrderDtl?.find(
- (item) =>
- item?.PaymentOrderId ===
- PaymentGatewayfilter?.[0]?.PaymentOrderId
- )?.PaymentStatus;
-
- if (paymentdataget === 'S') {
- setMessageType('success');
- setMessageData('Payment Success');
- await dispatch(changePaymentloader(false));
- if (getpaymentgatewaydetail?.data?.OrderDetails?.length > 0) {
- setPrintOrderDetails([getpaymentgatewaydetail?.data]);
- CustomerDisplay(value);
-
- ClearAllGlobalStateDatas(value);
- }
- clearInterval(intervalId); // Stop the loop when payment is successful
- } else if (paymentdataget === 'F') {
- setMessageType('error');
- setMessageData('Payment Failed');
- await dispatch(changePaymentloader(false));
- setFirstPaymentclick(false);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- clearInterval(intervalId); // Stop the loop when payment fails
- CustomerDisplayRemovedData();
- ClearAllGlobalStateDatas(value);
- // const customerDisplayWindow = getCustomerDisplayWindow();
- // if (customerDisplayWindow && !customerDisplayWindow.closed) {
- // const updatedData = {
- // userData: OrderCardDetail,
- // ExtraCharges: GlobalExtraCharge,
- // upi: GlobalUpiID,
- // customer: selOption != null ? selOption : GetCustId,
- // paymentMethod: Paybtnnameselected,
- // Paymentgateway: false,
- // OrderTotalAmount:PaymentGatewayfilter?.[0]?.Amount
-
- // };
- // customerDisplayWindow.postMessage(updatedData, '*');
- // }
+ // Include combo consumption from ReorderProductData (SetCount == 0)
+ try {
+ const reorderComboLines = (ReorderProductData || []).filter(
+ (a) => a?.Type === 'C'
+ );
+ if (reorderComboLines?.length > 0) {
+ const reorderComboConsumed = reorderComboLines.reduce(
+ (sum, comboLine) => {
+ const setZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!setZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((inner, d) => {
+ const nameMatches =
+ d?.ProdName === ProdName || d?.ProductName === ProdName;
+ if (nameMatches && d?.StockAvailable === 'Y') {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return inner + orderQty * (isNaN(compQty) ? 1 : compQty);
}
+ return inner;
+ }, 0);
+ return sum + consumed;
+ },
+ 0
+ );
+ totalSelectedProductQty =
+ parseInt(totalSelectedProductQty || 0) +
+ parseInt(reorderComboConsumed || 0);
+ }
+ } catch (_) {}
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdName === ProdName
+ );
+ let ComboProdDtl = orderDetails?.filter((a) => a?.Type === 'C');
+ if (overallpcs === 'Y' && ComboProdDtl?.length > 0) {
+ getCurrentProdDtl = getCurrentProdDtl?.filter((a) => a?.Type !== 'C');
+ }
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ }, 0);
+
+ // Combo adjustment:
+ // If combos (Type === 'C') include this product and that component has SetCount == 0
+ // and StockAvailable === 'Y', treat each occurrence as consuming one unit.
+ if (Array.isArray(ComboProdDtl) && ComboProdDtl.length > 0) {
+ try {
+ const comboExtraQty = ComboProdDtl.reduce((sum, comboLine) => {
+ // Use combo-level SetCount when detail-level SetCount is absent
+ const comboSetCountZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!comboSetCountZero) return sum;
+ const details = comboLine?.ProdDetail;
+ if (!Array.isArray(details)) return sum;
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((innerSum, d) => {
+ const nameMatches =
+ d?.ProdName === ProdName || d?.ProductName === ProdName;
+ const stockYes = d?.StockAvailable === 'Y';
+ if (nameMatches && stockYes) {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return innerSum + orderQty * (isNaN(compQty) ? 1 : compQty);
}
- } catch (error) {
- console.error('Error fetching payment details: ', error);
- }
- }, 3000); // Call the API every 3 seconds
- };
+ return innerSum;
+ }, 0);
+ return sum + consumed;
+ }, 0);
+ totalOrderQty =
+ parseInt(totalOrderQty || 0) + parseInt(comboExtraQty || 0);
+ } catch (e) {
+ // ignore structure mismatches
+ }
+ }
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object?.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object?.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
- // Call the function to start checking payment status
- checkPaymentStatus();
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
}
};
- const CustomerDisplayRemovedData = () => {
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- userData: [],
- ExtraCharges: [],
- Paymentgateway: false,
- type: 'remove',
- keyValue: 'customer',
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- const updatedRemovedData = {
- type: 'remove',
- keyValue: 'OrderTotalAmount',
- };
- customerDisplayWindow.postMessage(updatedRemovedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
+ const returnOnepcCount = (ProdName, currentQty, orderDetails, overallpcs) => {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdName === ProdName
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ },
+ 0
+ );
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdName === ProdName
+ );
+
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
);
+ }, 0);
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
}
};
- const CustomerDisplay = (value) => {
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (value == 'TakeAway') {
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- userData: [],
- ExtraCharges: [],
- Paymentgateway: false,
- upioption1: 'okk',
- type: 'remove',
- keyValue: 'customer',
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- const updatedRemovedData = {
- type: 'remove',
- keyValue: 'OrderTotalAmount',
- };
- customerDisplayWindow.postMessage(updatedRemovedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
+ const returnQtyCount = (ProdId, item, orderDetails) => {
+ if (onePeiceFlow) {
+ let ItemQuantity = item?.ProdVariantDetails?.reduce(
+ (accumulator, card) => {
+ return accumulator + parseInt(card.OverAllPcs || 0);
+ },
+ 0
+ );
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ },
+ 0
+ );
+
+ // Include combo consumption from ReorderProductData (pieces flow)
+ try {
+ const reorderComboLines = (ReorderProductData || []).filter(
+ (a) => a?.Type === 'C'
);
+ if (reorderComboLines?.length > 0) {
+ const reorderComboConsumed = reorderComboLines.reduce(
+ (sum, comboLine) => {
+ const setZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!setZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((inner, d) => {
+ if (d?.ProdId === ProdId && d?.StockAvailable === 'Y') {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return inner + orderQty * (isNaN(compQty) ? 1 : compQty);
+ }
+ return inner;
+ }, 0);
+ return sum + consumed;
+ },
+ 0
+ );
+ totalSelectedProductQty =
+ parseInt(totalSelectedProductQty || 0) +
+ parseInt(reorderComboConsumed || 0);
+ }
+ } catch (_) {}
+ let getCurrentProdDtl = orderDetails?.filter((a) => a?.ProdId === ProdId);
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+ // Include combo consumption for pieces flow
+ try {
+ const comboLines = orderDetails?.filter((a) => a?.Type === 'C') || [];
+ const comboConsumed = comboLines.reduce((sum, comboLine) => {
+ const comboSetZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!comboSetZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumedForThisCombo = details.reduce((inner, d) => {
+ if (d?.ProdId === ProdId && d?.StockAvailable === 'Y') {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return inner + orderQty * (isNaN(compQty) ? 1 : compQty);
+ }
+ return inner;
+ }, 0);
+ return sum + consumedForThisCombo;
+ }, 0);
+ totalOrderQty =
+ parseInt(totalOrderQty || 0) + parseInt(comboConsumed || 0);
+ } catch (_) {}
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(ItemQuantity) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(ItemQuantity) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
}
} else {
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- type: 'remove',
- keyValue: 'customer',
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
+ let ItemQuantity = item?.ProdVariantDetails?.reduce(
+ (accumulator, card) => {
+ return accumulator + parseInt(card.OverAllQty || 0);
+ },
+ 0
+ );
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ },
+ 0
+ );
+
+ // Include combo consumption from ReorderProductData (quantity flow)
+ try {
+ const reorderComboLines = (ReorderProductData || []).filter(
+ (a) => a?.Type === 'C'
);
+ if (reorderComboLines?.length > 0) {
+ const reorderComboConsumed = reorderComboLines.reduce(
+ (sum, comboLine) => {
+ const setZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!setZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((inner, d) => {
+ if (d?.ProdId === ProdId && d?.StockAvailable === 'Y') {
+ return inner + orderQty;
+ }
+ return inner;
+ }, 0);
+ return sum + consumed;
+ },
+ 0
+ );
+ totalSelectedProductQty =
+ parseInt(totalSelectedProductQty || 0) +
+ parseInt(reorderComboConsumed || 0);
+ }
+ } catch (_) {}
+ let getCurrentProdDtl = orderDetails?.filter((a) => a?.ProdId === ProdId);
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ }, 0);
+ // Include combo consumption for quantity flow
+ try {
+ const comboLines = orderDetails?.filter((a) => a?.Type === 'C') || [];
+ const comboConsumed = comboLines.reduce((sum, comboLine) => {
+ const comboSetZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!comboSetZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumedForThisCombo = details.reduce((inner, d) => {
+ if (d?.ProdId === ProdId && d?.StockAvailable === 'Y') {
+ return inner + orderQty;
+ }
+ return inner;
+ }, 0);
+ return sum + consumedForThisCombo;
+ }, 0);
+ totalOrderQty =
+ parseInt(totalOrderQty || 0) + parseInt(comboConsumed || 0);
+ } catch (_) {}
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(ItemQuantity) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(ItemQuantity) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
}
}
};
- const columns = [
+
+ const returnCountStock = (
+ ProdId,
+ currentQty,
+ orderDetails,
+ InwardDtlId,
+ onepcavailable,
+ overallpcs
+ ) => {
+ if (onepcavailable === 'Y') {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ },
+ 0
+ );
+
+ // Include combo consumption from ReorderProductData (pieces + batch)
+ try {
+ const reorderComboLines = (ReorderProductData || []).filter(
+ (a) => a?.Type === 'C'
+ );
+ if (reorderComboLines?.length > 0) {
+ const reorderComboConsumed = reorderComboLines.reduce(
+ (sum, comboLine) => {
+ const setZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!setZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((inner, d) => {
+ if (
+ d?.ProdId === ProdId &&
+ d?.InwardDtlId === InwardDtlId &&
+ d?.StockAvailable === 'Y'
+ ) {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return inner + orderQty * (isNaN(compQty) ? 1 : compQty);
+ }
+ return inner;
+ }, 0);
+ return sum + consumed;
+ },
+ 0
+ );
+ totalSelectedProductQty =
+ parseInt(totalSelectedProductQty || 0) +
+ parseInt(reorderComboConsumed || 0);
+ }
+ } catch (_) {}
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
+ );
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+
+ // Include combo consumption (no one-piece logic for combos)
+ try {
+ const comboLines = orderDetails?.filter((a) => a?.Type === 'C') || [];
+ const comboConsumed = comboLines.reduce((sum, comboLine) => {
+ const comboSetZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!comboSetZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumedForThisCombo = details.reduce((inner, d) => {
+ if (
+ d?.ProdId === ProdId &&
+ d?.InwardDtlId === InwardDtlId &&
+ d?.StockAvailable === 'Y'
+ ) {
+ const compQty = parseInt(d?.ProductQty ?? 1);
+ return inner + orderQty * (isNaN(compQty) ? 1 : compQty);
+ }
+ return inner;
+ }, 0);
+ return sum + consumedForThisCombo;
+ }, 0);
+ totalOrderQty =
+ parseInt(totalOrderQty || 0) + parseInt(comboConsumed || 0);
+ } catch (_) {}
+
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
+ }
+ } else {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ },
+ 0
+ );
+
+ // Include combo consumption from ReorderProductData (quantity + batch)
+ try {
+ const reorderComboLines = (ReorderProductData || []).filter(
+ (a) => a?.Type === 'C'
+ );
+ if (reorderComboLines?.length > 0) {
+ const reorderComboConsumed = reorderComboLines.reduce(
+ (sum, comboLine) => {
+ const setZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!setZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumed = details.reduce((inner, d) => {
+ if (
+ d?.ProdId === ProdId &&
+ d?.InwardDtlId === InwardDtlId &&
+ d?.StockAvailable === 'Y'
+ ) {
+ return inner + orderQty;
+ }
+ return inner;
+ }, 0);
+ return sum + consumed;
+ },
+ 0
+ );
+ totalSelectedProductQty =
+ parseInt(totalSelectedProductQty || 0) +
+ parseInt(reorderComboConsumed || 0);
+ }
+ } catch (_) {}
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdId === ProdId && a?.InwardDtlId === InwardDtlId
+ );
+
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ }, 0);
+
+ // Include combo consumption for quantity flow
+ try {
+ const comboLines = orderDetails?.filter((a) => a?.Type === 'C') || [];
+ const comboConsumed = comboLines.reduce((sum, comboLine) => {
+ const comboSetZero =
+ comboLine?.SetCount === 0 || comboLine?.SetCount === '0';
+ if (!comboSetZero) return sum;
+ const details = Array.isArray(comboLine?.ProdDetail)
+ ? comboLine?.ProdDetail
+ : [];
+ const orderQty = parseInt(comboLine?.OrderQty || 1);
+ const consumedForThisCombo = details.reduce((inner, d) => {
+ if (
+ d?.ProdId === ProdId &&
+ d?.InwardDtlId === InwardDtlId &&
+ d?.StockAvailable === 'Y'
+ ) {
+ return inner + orderQty;
+ }
+ return inner;
+ }, 0);
+ return sum + consumedForThisCombo;
+ }, 0);
+ totalOrderQty =
+ parseInt(totalOrderQty || 0) + parseInt(comboConsumed || 0);
+ } catch (_) {}
+
+ let OverallProdQty = totalOrderQty - totalSelectedProductQty;
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? OverallProdQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
+ }
+ }
+ };
+
+ const returnVariantStock = (
+ ProdId,
+ currentQty,
+ orderDetails,
+ ProdVariantName
+ ) => {
+ if (onePeiceFlow) {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ },
+ 0
+ );
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
+ );
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty * card.NoOfPcs
+ : card.OrderQty
+ : 0
+ )
+ );
+ }, 0);
+
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? totalOrderQty - totalSelectedProductQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? totalOrderQty - totalSelectedProductQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
+ }
+ } else {
+ let SelectedProduct = ReorderProductData?.filter(
+ (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
+ );
+ let totalSelectedProductQty = SelectedProduct?.reduce(
+ (accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ },
+ 0
+ );
+ let getCurrentProdDtl = orderDetails?.filter(
+ (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
+ );
+ let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
+ return (
+ accumulator +
+ parseInt(
+ card?.StockAvailable === 'Y'
+ ? card.SinglePc !== 'Y'
+ ? card.OrderQty
+ : card.OverAllPcs % card.NoOfPcs >= card.OrderQty
+ ? 0
+ : card.OrderQty % card.NoOfPcs === 0
+ ? Math.floor(card.OrderQty / card.NoOfPcs)
+ : Math.floor(card.OrderQty / card.NoOfPcs) + 1
+ : 0
+ )
+ );
+ }, 0);
+
+ if (
+ parseInt(currentQty) >
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? totalOrderQty - totalSelectedProductQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ )
+ ) {
+ let count =
+ parseInt(currentQty) -
+ parseInt(
+ Object.keys(ReportholdData)?.length > 0 && totalOrderQty
+ ? totalOrderQty - totalSelectedProductQty
+ : getCurrentProdDtl
+ ? totalOrderQty
+ : 0
+ );
+ return parseInt(count);
+ } else {
+ let count = 0;
+ return count;
+ }
+ }
+ };
+
+ const varientcolumns = [
{
- title: 'Sl.No',
- key: 'sno',
- align: 'center',
- width: '100px',
- render: (text, object, index) => (
-
{index + 1}
+ title: 'Variant Name',
+ dataIndex: 'VarientName',
+ key: 'VarientName',
+ align: 'left',
+ render: (_, record, index) => (
+
0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record.VarientName}
+
),
- },
- {
- title: 'Table Name/Chair Name',
- dataIndex: 'TableName',
- key: 'TableName',
- width: '150px',
- onCell: (_, record, index) => {
+ onCell: (record) => {
return {
onClick: () => {
- Unpaidfun(record);
+ if (
+ record.StockCount > 0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ) {
+ Stockfun(record);
+ }
},
};
},
},
{
- title: 'Order Id',
- dataIndex: 'OrderID',
- key: 'OrderID',
- width: '150px',
- align: 'right',
- onCell: (_, record, index) => {
+ title: 'Stock Count',
+ dataIndex: 'StockCount',
+ key: 'StockCount',
+ align: 'Right',
+ render: (_, record, index) => (
+
0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record.StockCount}
+
+ ),
+ onCell: (record) => {
return {
onClick: () => {
- Unpaidfun(record);
- },
- };
- },
- },
- {
- title: "Item's",
- dataIndex: 'ProductName',
- key: 'ProductName',
- width: '250px',
- onCell: (_, record, index) => {
- return {
- onClick: () => {
- Unpaidfun(record);
+ if (
+ record.StockCount > 0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ) {
+ Stockfun(record);
+ }
},
};
},
},
{
title: 'Amount',
- dataIndex: 'TotalAmount',
- key: 'TotalAmount',
- width: '150px',
+ dataIndex: 'Amount',
+ key: 'Amount',
align: 'right',
- render: (text) =>
{safeRound(text)} ,
- onCell: (_, record, index) => {
+ render: (_, record, index) => (
+
0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record.Amount}
+
+ ),
+ onCell: (record) => {
return {
onClick: () => {
- Unpaidfun(record);
+ if (
+ record.StockCount > 0 ||
+ record.StockCount === 'Stock Not Maintained'
+ ) {
+ Stockfun(record);
+ }
},
};
},
},
];
+ const stockcolumns = [
+ {
+ title: 'Batch No',
+ dataIndex: 'Batch No',
+ key: 'Batch No',
+ align: 'center',
+ render: (text, record, index) => (
+
0
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record?.['Batch No']}
+
+ ),
+ onCell: (record) => {
+ return {
+ onClick: () => {
+ if (record.StockCount > 0) {
+ StockSelected(record);
+ }
+ },
+ };
+ },
+ },
+ {
+ title: 'Stock Count',
+ dataIndex: 'StockCount',
+ key: 'StockCount',
+ align: 'center',
+ render: (_, record, index) => (
+
0
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record.StockCount}
+
+ ),
+ onCell: (record) => {
+ return {
+ onClick: () => {
+ if (record.StockCount > 0) {
+ StockSelected(record);
+ }
+ },
+ };
+ },
+ },
+ {
+ title: 'Stock Date',
+ dataIndex: 'Stock Date',
+ key: 'Stock Date',
+ align: 'center',
+ render: (_, record, index) => (
+
0
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record?.['Stock Date']}
+
+ ),
+ onCell: (record) => {
+ return {
+ onClick: () => {
+ if (record.StockCount > 0) {
+ StockSelected(record);
+ }
+ },
+ };
+ },
+ },
+ {
+ title: 'Exp Date',
+ dataIndex: 'ExpDate',
+ key: 'ExpDate',
+ align: 'center',
+ render: (_, record, index) => (
+
0
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {record.ExpDate}
+
+ ),
+ onCell: (record) => {
+ return {
+ onClick: () => {
+ if (record.StockCount > 0) {
+ StockSelected(record);
+ }
+ },
+ };
+ },
+ },
+ {
+ title: 'Price',
+ dataIndex: 'Price',
+ key: 'Price',
+ align: 'center',
+ render: (_, record, index) => (
+
0
+ ? { color: '#000', cursor: 'pointer' }
+ : { color: '#f49898', cursor: 'not-allowed' }
+ }
+ >
+ {safeRound(record.Price)}
+
+ ),
+ onCell: (record) => {
+ return {
+ onClick: () => {
+ if (record.StockCount > 0) {
+ StockSelected(record);
+ }
+ },
+ };
+ },
+ },
+ ];
+ const qtydataSource = [];
- const TableData = [];
- tabledata?.map((item) =>
- TableData.push({
- TableName: item.SalesTableLinkDetails?.map((item) =>
- item.ChairName == null ? item.TableName : item.ChairName
- )?.join(','),
- OrderID: extractLastNumberOrderId(item?.OrderId, item?.FYStatus),
- ProductName: item.productDetails
- ?.map(
- (item) =>
- item?.ProdName +
- '-' +
- (item?.Type != 'C' ? item?.OrderQty : '1 Combo')
+ qtydata?.ProductDetail?.map((item, index) => {
+ qtydataSource.push({
+ key: index,
+ Quantity: item?.Size + ' ' + item?.UomName,
+ Amount: item?.ProdVariantDetails?.[0]?.StockDetails?.[0]?.SellPrice,
+ });
+ });
+ const varientdataSource = [];
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.map((item, index) => {
+ varientdataSource.push({
+ key: index,
+ VarientName: item?.ProdVariantName,
+ Amount: onePeiceFlow
+ ? item?.StockDetails?.[0]?.OnePcsPrice
+ : item?.StockDetails?.[0]?.SellPrice,
+ StockCount:
+ qtydata?.ProductDetail?.[QtyIndex]?.StockAvailable === 'Y'
+ ? onePeiceFlow
+ ? returnVariantStock(
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdId,
+ item?.OverAllPcs,
+ CartOrderDetails,
+ item?.ProdVariantName
+ )
+ : returnVariantStock(
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdId,
+ item?.OverAllQty,
+ CartOrderDetails,
+ item?.ProdVariantName
+ )
+ : 'Stock Not Maintained',
+ VariantAvailableFrom: item?.AvailableFrom,
+ VariantAvailableTo: item?.AvailableTo,
+ SlotStatus: item?.StockDetails?.[0]?.SlotStatus,
+ InwardDtlId: item?.StockDetails?.[0]?.InwardDtlId,
+ BookedDate: selectedDate,
+ BookedQty: item?.StockDetails?.[0]?.BookedQty,
+ TotalSlotQty: item?.StockDetails?.[0]?.TotalSlotQty,
+ });
+ });
+
+ const stockdataSource = [];
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.StockDetails?.map((item, index) => {
+ const expDate = new Date(item?.ExpDate);
+ stockdataSource.push({
+ key: index,
+ 'Batch No': item?.BatchRef,
+ StockCount: onePeiceFlow
+ ? returnCountStock(
+ item?.ProdId,
+ item?.OverAllPcs,
+ CartOrderDetails,
+ item?.InwardDtlId,
+ 'Y'
+ )
+ : returnCountStock(
+ item?.ProdId,
+ item?.BalanceQty,
+ CartOrderDetails,
+ item?.InwardDtlId,
+ 'N',
+ item?.OverAllPcs
+ ),
+ 'Stock Date': ExtractDateFormate(item?.InwardDate),
+ Price: onePeiceFlow ? item?.OnePcsPrice : item?.SellPrice,
+ ExpDate:
+ expDate != 'Invalid Date' || null || undefined || ''
+ ? ExtractDateFormate(item?.ExpDate)
+ : '-',
+ });
+ });
+
+ const extractProductDetails = (a, QtyIndex, VarientIndex, stockIndex) => {
+ const detail = a?.ProductDetail?.[QtyIndex];
+ const variant = detail?.ProdVariantDetails?.[VarientIndex];
+ const stock = variant?.StockDetails?.[stockIndex];
+
+ return { detail, variant, stock };
+ };
+
+ const buildOrderData = (
+ a,
+ detail,
+ variant,
+ stock,
+ size,
+ orderRate,
+ onePcs,
+ weightscale
+ ) => {
+ const { ProdCat, Type, OverAllQty: OverallQuantity, CounterName } = a || {};
+ const {
+ ActiveStatus,
+ AvailableFrom,
+ AvailableTo,
+ Cess,
+ HSNCode,
+ BrandName,
+ OpeningQty,
+ PartNumber,
+ ProdId,
+ ProdLogo,
+ ProdName,
+ QRCode,
+ QtyBasedPrice,
+ Rack,
+ StockAvailable,
+ TokenAvailable,
+ TaxId,
+ TaxPercentage,
+ TaxIdName: TaxName,
+ UniqueId,
+ UomName,
+ DiscountLimitType,
+ DiscountLimit,
+ } = detail || {};
+
+ const {
+ NoOfPcs,
+ BalanceQty,
+ BatchRef,
+ ModelNumber,
+ ProductIdentifierDtls: FullProductIdentifierDtls,
+ InwardDate,
+ InwardDtlId,
+ ExpDate,
+ InwardId,
+ MRP,
+ OnePcsPrice,
+ SellPrice,
+ SuppId,
+ SuppName,
+ OverAllPcs,
+ OfferPrice: Offer,
+ TotalSlotQty,
+ BookedQty,
+ } = stock || {};
+ const BalanceBookedQty = TotalSlotQty || 0 - BookedQty || 0;
+
+ const {
+ ProdVariantName,
+ AvailableFrom: VariantAvailableFrom,
+ AvailableTo: VariantAvailableTo,
+ } = variant || {};
+
+ return {
+ ProdCat,
+ Type,
+ OverallQuantity,
+ ActiveStatus,
+ AvailableFrom,
+ AvailableTo,
+ Cess,
+ HSNCode,
+ BrandName,
+ OpeningQty,
+ PartNumber,
+ ProdId,
+ ProdLogo,
+ ProdName,
+ QRCode,
+ QtyBasedPrice,
+ Rack,
+ Size: size,
+ StockAvailable,
+ TokenAvailable,
+ TaxId,
+ TaxPercentage,
+ TaxName,
+ UniqueId,
+ UomName: onePcs ? 'PCS' : UomName,
+ SinglePc: onePcs ? 'Y' : 'N',
+ NoOfPcs,
+ ProdVariantName,
+ VariantAvailableFrom,
+ VariantAvailableTo,
+ BalanceQty,
+ BatchRef,
+ ModelNumber,
+ FullProductIdentifierDtls,
+ InwardDate,
+ InwardDtlId,
+ ExpDate,
+ InwardId,
+ MRP: onePcs ? OnePcsPrice : MRP,
+ OrderRate: orderRate,
+ SellingPrice: orderRate,
+ SuppId,
+ SuppName,
+ OverAllPcs,
+ Offer,
+ BookingTypeName: BookingType,
+ CounterName,
+ DiscountLimitType,
+ DiscountLimit,
+ BookedDate: selectedDate,
+ BalanceBookedQty,
+ ScaleType: weightscale ? weightscale : '',
+ };
+ };
+
+ const resetProductModal = () => {
+ setModelQty(false);
+ setSelectedBrand('Others');
+ setModalVarient(false);
+ setModelstock(false);
+ setQtyIndex(0);
+ setVarientIndex(0);
+ setVarItem(0);
+ setItem();
+ setStockItem();
+ dispatch(changeSearchedData(''));
+ setOnePeiceFlow(false);
+ };
+
+ const dataTransfer = async (
+ a,
+ QtyIndex,
+ VarientIndex,
+ stockIndex,
+ onePcs
+ ) => {
+ const { detail, variant, stock } = extractProductDetails(
+ a,
+ QtyIndex,
+ VarientIndex,
+ stockIndex
+ );
+
+ console.log(stock, 'stock in dataTransfer');
+ // mohan 05-08-2025
+ const price = onePcs
+ ? stock?.OnePcsPrice
+ : RetailWSSalesType === 'W'
+ ? stock?.WhSalePrice || stock?.SellPrice
+ : stock?.SellPrice;
+ const size = onePcs ? '1' : detail?.Size;
+ if (quickBranchtoBranchTransfer) {
+ const data = buildOrderData(
+ a,
+ detail,
+ variant,
+ stock,
+ size,
+ price,
+ onePcs
+ );
+ if (!selectedProducts?.some((s) => s.ProdId === detail?.ProdId)) {
+ dispatch(
+ changeBtoBQuickProductTransfer({
+ action: quickBranchtoBranchTransfer,
+ selectedProducts: [
+ ...selectedProducts,
+ {
+ ...data,
+ OrderQty: 1,
+ TotalAmt: parseFloat(detail?.OrderRate).toFixed(2),
+ },
+ ],
+ })
+ );
+ } else {
+ setMessageType('error');
+ setMessageData('Product already added');
+ }
+ } else {
+ const isKgsProduct =
+ (detail?.UomName?.toLowerCase() === 'kgs' ||
+ detail?.UomName?.toLowerCase() === 'kg') &&
+ detail?.Size === '1';
+ console.log(
+ isKgsProduct,
+ WeightScalePort,
+ WeightScaleWeight,
+ 'isKgsProduct'
+ );
+ if (
+ WeightScalePort === true &&
+ isKgsProduct &&
+ WeightScaleWeight > 0.005 &&
+ WeightScaleWeight !== null
+ ) {
+ let weightscale = 'weight';
+ // if (isKgsProduct) {
+ // if (WeightScaleWeight > 0 && WeightScaleWeight !== null) {
+ const basePrice = onePcs ? stock?.OnePcsPrice : stock?.SellPrice;
+ const totalRate = (
+ (basePrice / 1000) *
+ (parseFloat(WeightScaleWeight) * 1000)
+ ).toFixed(2);
+ let orderqty = parseFloat(WeightScaleWeight);
+ const data = buildOrderData(
+ a,
+ detail,
+ variant,
+ stock,
+ detail?.Size,
+ basePrice,
+ onePcs,
+ weightscale
+ );
+ let fulldata = {
+ ...data,
+ OrderQty: orderqty,
+ };
+
+ await AddOrderDetails(fulldata);
+ // dispatch(changeWeightScaleWeight(null));
+ setRepeatedModel(false);
+ setProdexpir(false);
+ resetProductModal();
+ } else {
+ const isValidPcs =
+ onePcs && stock?.NoOfPcs > 0 && stock?.OnePcsPrice > 0;
+ const allowNonPcs =
+ !onePcs ||
+ (detail?.StockAvailable !== 'Y' && onePcs && stock?.OnePcsPrice > 0);
+
+ if (isValidPcs || allowNonPcs) {
+ const data = buildOrderData(
+ a,
+ detail,
+ variant,
+ stock,
+ size,
+ price,
+ onePcs
+ );
+
+ resetProductModal();
+ AddOrderDetails(data);
+ } else {
+ setMessageType('error');
+ setMessageData(
+ 'Please add No.of pieces Inside the box in Product master'
+ );
+ resetProductModal();
+ }
+ }
+ }
+ };
+
+ useEffect(() => {
+ setPreOrderSelectedProdNames(GPreOrderList);
+ }, [GPreOrderList]);
+
+ const pickData = (e, item) => {
+ if (e.target.checked === true) {
+ setSelectedProdNames([
+ ...globalAllItemdata,
+ {
+ ProdName: item.ProdName,
+ ProdId: item.ProductDetail?.[0]?.ProdId,
+ ProdCat: item.ProdCat,
+ ProdCatName: item.ProdCatName,
+ },
+ ]);
+ } else {
+ console.log('SelectedProdNames', SelectedProdNames);
+ setSelectedProdNames(
+ SelectedProdNames?.filter(
+ (data) =>
+ !(data?.ProdName == item.ProdName && data?.ProdCat == item.ProdCat)
)
- ?.join(','),
- TotalAmount: item.NetAmount,
+ );
+ }
+ };
+
+ const handleQuickCancel = async () => {
+ setQuickAdd(false);
+ dispatch(changeSearchedData(''));
+
+ // Base data for all calls
+ let baseData = {
+ CompId,
+ BranchId,
+ AppId,
+ };
+
+ // 👇 Only add date if AvailableDate and selectedDate exist
+ if (AvailableDate && selectedDate) {
+ baseData.Date = selectedDate;
+ }
+ // 1️⃣ Favourite items
+ await dispatch(getSelectedFavItems(baseData)).unwrap();
+
+ // 2️⃣ For layout with SubCategory
+ let data1 = {
+ ...baseData,
+ ProdSubCat,
+ };
+
+ // 3️⃣ For layout without SubCategory
+ let data2 = {
+ compId: CompId,
+ branchId: BranchId,
+ appId: AppId,
+ prodCat: ProdCat,
+ ...(AvailableDate && selectedDate ? { date: selectedDate } : {}), // conditionally add
+ };
+
+ 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 expFun = (item) => {
+ console.log(item, 'itemitemitemitemitemitemitemitem');
+ let count = item?.ProductDetail?.length;
+ if (count > 1) {
+ Quantity();
+ } else {
+ setVarItem(0);
+ SingleQuantity(item, onePeiceFlow);
+ }
+
+ closeExpireModal();
+ setProdexpir(true);
+ setQtydata(item);
+ };
+ let brandMapping = {};
+ // Group product details by Brand ID
+ qtydata?.ProductDetail?.forEach((item) => {
+ const brandId = item?.BrandName;
+ if (!brandMapping[brandId]) {
+ brandMapping[brandId] = [];
+ }
+ brandMapping[brandId].push(item);
+ });
+ const BrandCheckresult = qtydata?.ProductDetail?.every((product) => {
+ return product.BrandName === null || product.BrandName === undefined;
+ });
+ const ItemSellingPrice = (item) => {
+ // const variantWithDetails = item?.ProductDetail?.find((variant) => variant?.ProdVariantDetails?.length > 0);
+
+ if (preferenceSingleSales && item.OnePcsAvailable === 'Y') {
+ return (
+ item?.ProductDetail?.[0]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
+ ?.OnePcsPrice || null
+ );
+ // OnePcsPrice
+ }
+
+ const variantWithDetails = item?.ProductDetail?.find(
+ (variant) =>
+ variant?.ProdVariantDetails?.length > 0 &&
+ variant?.ProdVariantDetails?.[0]?.StockDetails?.[0]?.SellPrice
+ );
+ if (variantWithDetails) {
+ // Access the details of the first variant with ProdVariantDetails
+ const firstVariantDetails =
+ variantWithDetails?.ProdVariantDetails?.[0]?.StockDetails?.[0]
+ ?.SellPrice;
+ return firstVariantDetails;
+ } else {
+ // Handle the case where no variant satisfies the condition
+ return null; // or any other value you want to return
+ }
+ };
+
+ const ItemSize = (item) => {
+ if (preferenceSingleSales && item?.OnePcsAvailable === 'Y') {
+ return 1;
+ }
+ const variantWithDetails = item?.ProductDetail?.find(
+ (variant) => variant?.ProdVariantDetails?.length > 0
+ );
+
+ if (variantWithDetails) {
+ // Access the details of the first variant with ProdVariantDetails
+ const firstVariantDetails = variantWithDetails?.Size;
+ return firstVariantDetails;
+ } else {
+ // Handle the case where no variant satisfies the condition
+ return null; // or any other value you want to return
+ }
+ };
+ const ItemUomName = (item) => {
+ if (preferenceSingleSales && item?.OnePcsAvailable === 'Y') {
+ return 'PCS';
+ }
+ const variantWithDetails = item?.ProductDetail?.find(
+ (variant) => variant?.ProdVariantDetails?.length > 0
+ );
+
+ if (variantWithDetails) {
+ // Access the details of the first variant with ProdVariantDetails
+ const firstVariantDetails = variantWithDetails?.UomName;
+ return firstVariantDetails;
+ } else {
+ // Handle the case where no variant satisfies the condition
+ return null; // or any other value you want to return
+ }
+ };
+ const expQtyFun = (index) => {
+ const selectedProIndex = qtydata?.ProductDetail?.findIndex(
+ (item) =>
+ item?.ProdId === index?.ProdId &&
+ item?.Size === index?.Size &&
+ item?.UomName === index?.UomName &&
+ item?.Brand === index?.Brand
+ );
+
+ if (selectedProIndex !== -1) {
+ const count =
+ qtydata?.ProductDetail[selectedProIndex]?.ProdVariantDetails?.length ||
+ 0;
+
+ if (count > 1) {
+ setModelQty(false);
+ setSelectedBrand('Others');
+ setModalVarient(true);
+ } else {
+ const item = { QtyIndex: selectedProIndex, VarientIndex: 0 };
+ singleVarient(item);
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ }
+
+ setQtyIndex(selectedProIndex);
+ setRepeatedModel(true);
+ closeExpireModal();
+ };
+
+ const expVerFun = (item) => {
+ let count =
+ qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[item]
+ ?.StockDetails?.length;
+ if (count > 1) {
+ setRepeatedModel(true);
+ setModalVarient(false);
+ setModelstock(true);
+ } else {
+ setRepeatedModel(true);
+ dataTransfer(qtydata, QtyIndex, item, 0, onePeiceFlow);
+ setModelQty(false);
+ setSelectedBrand('Others');
+ }
+ closeExpireModal();
+ };
+
+ const expStockFun = (item) => {
+ dataTransfer(qtydata, QtyIndex, VarientIndex, item, onePeiceFlow);
+ closeExpireModal();
+ };
+
+ const getMaxBrandWidth = () => {
+ let maxBrandDataLength = 0;
+
+ // Iterate through each brand and find the maximum length of the specified key
+ Object.values(brandMapping).forEach((brand) => {
+ const keyDataLength = brand.length;
+ if (keyDataLength > maxBrandDataLength) {
+ maxBrandDataLength = keyDataLength;
+ }
+ });
+
+ // Set your width logic here based on the maxBrandDataLength
+ const maxWidth = maxBrandDataLength >= 5 ? 750 : 'max-content';
+
+ return maxWidth;
+ };
+
+ useEffect(() => {
+ function handleResize() {
+ setScreenWidth(window.innerWidth);
+ }
+
+ window.addEventListener('resize', handleResize);
+
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ };
+ }, []);
+
+ // Example usage for checking the length of 'ProdVariantDetails'
+ const widthBasedOnProdVariantDetails = getMaxBrandWidth();
+ const ExpDate = useSelector(GlobalExpDateforHeight);
+ let containerHeight = '';
+
+ if (templateData?.BookingLayout?.[0] === 'Layout1') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 340}px`
+ : '63vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 350}px`
+ : '62vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '63vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '62vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '60vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '59vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '60vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '59vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '60vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '59vh'
+ : '76vh';
+ }
+ } else if (templateData?.BookingLayout?.[0] === 'Layout2') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '60vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '63vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '62vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '63vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '62vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '61vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '59vh'
+ : '74vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 310}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : '75vh';
+ }
+ } else if (templateData?.BookingLayout?.[0] === 'Layout3') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 390}px`
+ : '58vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 400}px`
+ : '57vh'
+ : '73vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 390}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 400}px`
+ : '56vh'
+ : '73vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 395}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 400}px`
+ : '56vh'
+ : '73vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 390}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 400}px`
+ : '56vh'
+ : '75vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 385}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 395}px`
+ : '56vh'
+ : '72vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 385}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 395}px`
+ : '56vh'
+ : '72vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 390}px`
+ : '57vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 400}px`
+ : '56vh'
+ : '72vh';
+ }
+ } else if (templateData?.BookingLayout?.[0] === 'Layout4') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 220}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 230}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 230}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 240}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 230}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 240}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '73vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : '88vh';
+ }
+ } else if (templateData?.BookingLayout?.[0] === 'Layout5') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 280}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 290}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 280}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 280}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '70vh'
+ : '88vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 270}px`
+ : '72vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 280}px`
+ : '70vh'
+ : '88vh';
+ }
+ } else if (templateData?.BookingLayout?.[0] === 'Layout6') {
+ if (templateData?.BookingBilling?.[0] == 'Billing1') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 340}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing2') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 260}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 370}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing3') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing4') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing5') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 290}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 300}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing6') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 320}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 330}px`
+ : '60vh'
+ : '76vh';
+ } else if (templateData?.BookingBilling?.[0] == 'Billing7') {
+ containerHeight = isMobile
+ ? ExpDate >= 7
+ ? screenWidth < 600
+ ? `${props?.screenHeight - 280}px`
+ : '61vh'
+ : screenWidth < 600
+ ? `${props?.screenHeight - 290}px`
+ : '60vh'
+ : '76vh';
+ }
+ }
+
+ //new
+ const [draggableCardData, setDraggableCardData] = useState([]);
+ useEffect(() => {
+ if (Array.isArray(cardData)) {
+ const withIds = cardData.map((item, idx) => ({
+ ...item,
+ id: item?.ProductDetail?.[0]?.ProdName + '-' + idx,
+ }));
+ setDraggableCardData(withIds);
+ }
+ }, [cardData, alphabeticFormat]);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, {
+ activationConstraint: {
+ distance: isMobile ? 5 : 8, // <- reduced distance for mobile
+ },
+ }),
+ useSensor(TouchSensor, {
+ activationConstraint: {
+ delay: isMobile ? 50 : 100, // <- even faster response for mobile
+ tolerance: isMobile ? 10 : 8, // <- more tolerance for mobile touch
+ },
})
);
- const Unpaidfun = async (event) => {
- const UpdatedData = tabledata?.[event]?.productDetails;
- dispatch(changeunpaidflow(true));
- if (
- OrderCardDetail?.length > 0 &&
- (BookingType === 'Dine In' || BookingTypeBoth)
- ) {
- if (OfferCheckedInSetup && preferenceOffer) {
- await applyOffer([]);
- } else {
- dispatch(changeOrderCardDetails([]));
- }
- // await dispatch(changeOrderCardDetails([]))
- // await dispatch(changeOrderCardDetails(tabledata?.[event]?.productDetails))
- // await dispatch(ChangeTotalAmount(tabledata?.[event]?.ExtraChargeDetails))
- // await dispatch(changeUnpaidData(true))
- // await dispatch(changeReorderHoldDetails([tabledata?.[event]]?.[0]));
- // await dispatch(changeReorderProductDetails(tabledata?.[event]?.productDetails))
- // setUnpaidOpen(false)
- setUnpaidConfirmation(true);
- setunpaidselectedindex(event);
- } else {
- if (OfferCheckedInSetup && preferenceOffer) {
- await applyOffer(UpdatedData);
- } else {
- dispatch(changeOrderCardDetails(UpdatedData));
- }
- dispatch(changeReorderHoldDetails([tabledata?.[event]]?.[0]));
- await dispatch(
- changeReorderProductDetails(tabledata?.[event]?.productDetails)
- );
- dispatch(ChangeTotalAmount(tabledata?.[event]?.ExtraChargeDetails));
- setUnpaidOpen(false);
+ const handleDragEnd = (event) => {
+ const { active, over } = event;
+
+ // Ensure `over` is not null
+ if (!over) return;
+
+ if (active.id !== over.id) {
+ const oldIndex = draggableCardData.findIndex((i) => i.id === active.id);
+ const newIndex = draggableCardData.findIndex((i) => i.id === over.id);
+
+ const updatedData = arrayMove(draggableCardData, oldIndex, newIndex);
+
+ setDraggableCardData(updatedData);
+
+ dispatch(changeCardData(updatedData));
}
};
- const UnpaidOk = async () => {
- setOrderStatus(false);
- await dispatch(changeSelectedTableDetails([]));
- await dispatch(changeSelectTable([]));
- await dispatch(changeSelectChair([]));
- await dispatch(changeBookingType('TakeAway'));
- await dispatch(
- changeOrderCardDetails(tabledata?.[unpaidselectedindex]?.productDetails)
- );
- await dispatch(
- changeReorderProductDetails(
- tabledata?.[unpaidselectedindex]?.productDetails
- )
- );
- await dispatch(
- changeReorderHoldDetails([tabledata?.[unpaidselectedindex]]?.[0])
- );
- await dispatch(
- ChangeTotalAmount(tabledata?.[unpaidselectedindex]?.ExtraChargeDetails)
- );
- await dispatch(changeUnpaidData(true));
- setUnpaidOpen(false);
- setUnpaidConfirmation(false);
- };
- const Unpaidclose = async () => {
- dispatch(changeunpaidflow(false));
- setUnpaidOpen(false);
- setUnpaidConfirmation(false);
- };
+ const updateScrollButtons = () => {
+ const container = scrollContainerRef.current;
+ if (!container) return;
- const Recipt = async () => {
- AddBookingDetails('Unpaid', false);
- };
- const navigateDineIn = async () => {
- navigate(`${subDirectory}sales/dine-in`);
- await dispatch(changeBookingType('Dine In'));
- await dispatch(changeEstimateBooking('Sales'));
- if (OrderType === 'Hold') {
- await dispatch(changeReorderHoldDetails({}));
- await dispatch(changeReorderProductDetails([]));
+ const { scrollLeft, scrollWidth, clientWidth } = container;
- if (OfferCheckedInSetup && preferenceOffer) {
- await applyOffer([]);
- } else {
- dispatch(changeOrderCardDetails([]));
- }
- }
+ console.log(
+ container,
+ 'sl:',
+ scrollLeft,
+ 'w:',
+ scrollWidth,
+ 'cw:',
+ clientWidth
+ );
+
+ setShowLeftButton(scrollLeft > 5);
+ setShowRightButton(scrollLeft + clientWidth < scrollWidth - 5);
};
useEffect(() => {
- if (ReprintModal === true) {
- setReprint1(false);
- }
- }, [ReprintModal]);
- const handleReprint = () => {
- // setReprint1(true)
- window.dispatchEvent(new Event('CLICK REPRINT'));
- };
- const handleReprintCancel = () => {
- setReprint1(false);
- };
- const today = new Date();
- const year = today.getFullYear();
- // Note: Months are zero-based, so we add 1 to get the actual month
- const month = today.getMonth() + 1;
- const day = today.getDate();
+ const container = scrollContainerRef.current;
+ if (!container) return;
- // Creating a formatted date string (in the format YYYY-MM-DD)
- const Todaydate = `${day < 10 ? '0' : ''}${day}-${month < 10 ? '0' : ''}${month}-${year}`;
- const OrderId = PrintOrderDetails?.[0]?.OrderDetails?.[0]?.OrderId;
- let MobileNo = selOption?.value;
- useEffect(() => {
- if (selOption) {
- closePrintOption();
- setMobileNoWhatsApp(selOption);
- }
- }, [selOption]);
- const UpiPayment = () => {
- if (OrderStatus) {
- AddBookingDetails('Dine-In', false);
- } else {
- if (SelectedUpiOption && TotalAmount == 0) {
- Upimodel('Submit');
- } else if (SelectedUpiOption) {
- setUpiOpen(true);
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- OrderTotalAmount: TotalAmount,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- } else {
- setUpinotSelected(true);
- setMessageType('error');
- setMessageData('Please Select Upi Option');
- }
- }
- };
+ // ✅ Call once after layout
+ requestAnimationFrame(() => {
+ updateScrollButtons();
+ });
- const onFinalSubmit = async () => {
- let url = `${MainHomeUrl}payment-page?amt=${TotalAmount}&Id=${MobileNo}&cus=${SelCustId} &CusN=${selOption?.CustName}&Br=${brachName}`;
- let response = await dispatch(SendPaymentLink({ MobileNo, url })).unwrap();
- if (response?.data?.statusCode === 1) {
- setMessageType('success');
- setMessageData('Link Sent Successfully');
- }
- };
- const Upimodel = (type) => {
- setUpiOpen(false);
- if (type == 'Submit') {
- AddBookingDetails(BookingType, true);
- }
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedRemovedData = {
- type: 'remove',
- keyValue: 'OrderTotalAmount',
- };
- customerDisplayWindow.postMessage(updatedRemovedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- };
- const CreditCustomerHAndleCancel = async () => {
- setcreditCustomerOpen(false);
- await dispatch(changeCreditFocus(false));
- };
+ container.addEventListener('scroll', updateScrollButtons);
+ window.addEventListener('resize', updateScrollButtons);
- const CreditCustomerFun = async () => {
- if (
- OrderCardDetail?.length === 0 &&
- (selOption?.value !== undefined ||
- GlobalAddCustomerDetails1.length > 0 ||
- GetCustId.CustMobile !== undefined)
- ) {
- setcreditCustomerOpen(true);
- await dispatch(changeCreditFocus(true));
- } else {
- if (selOption?.value == undefined) {
- setMessageType('warning');
- setMessageData('Please Select the Customer');
- }
- }
- };
- const changeOrderStatus = () => {
- setOrderStatus(!OrderStatus);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- };
- // split payments
- const SplitPaymentOpen = () => {
- if (OrderCardDetail?.length > 0) {
- const updatedData = {
- userData: OrderCardDetail,
- ExtraCharges: GlobalExtraCharge,
- customer: selOption != null ? selOption : GetCustId,
- Paymentgateway: false,
- };
- setFailedOrderData(updatedData);
- setSplitpayment(true);
- } else {
- setMessageType('warning');
- setMessageData('Please Select the Product');
- }
- };
+ const resizeObserver = new ResizeObserver(updateScrollButtons);
+ resizeObserver.observe(container);
- const handlePopoverVisibleChangeCard = (visible) => {
- setCardOptionOpen(visible);
- };
-
- const handlesplitpaymentclose = () => {
- setSplitpayment(false);
- setPaybtnnameselected(PaymentOptionsModeName);
- setPaybtnselected(PaymentOptionsModeId);
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedData = {
- paymentMethod: PaymentOptions?.[0]?.ModeName,
- Paymentgateway: false,
- };
- customerDisplayWindow.postMessage(updatedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- };
- // const handleClick = async () => {
- // if (Comboglobal == false) {
- // await dispatch(changeCombosearch(true));
- // } else {
- // await dispatch(changeCombosearch(false));
- // }
- // };
-
- // const Combodata = async () => {
- // let data = {
- // AppId: AppId,
- // CompId: CompId,
- // BranchId: BranchId,
- // ActiveStatus: 'A',
- // };
-
- // let Response = await dispatch(Comboget(data)).unwrap();
- // if (Response?.data?.statusCode == 1) {
- // setComboDropDown(Response?.data?.data);
- // }
- // };
-
- const openPreOrder = async () => {
- setPreOrderOpen((prevState) => !prevState);
- if (preOrderOpen) {
- const customerDisplayWindow = getCustomerDisplayWindow();
- if (customerDisplayWindow && !customerDisplayWindow.closed) {
- const updatedRemovedData = {
- userData: [],
- ExtraCharges: [],
- paymentMethod: 'Cash',
- type: 'remove',
- keyValue: 'customer',
- };
- customerDisplayWindow.postMessage(updatedRemovedData, '*');
- } else {
- console.error(
- 'Customer display window is not available or has been closed.'
- );
- }
- await dispatch(changeBookingType('TakeAway'));
- await dispatch(changepreOrder(false));
- await dispatch(changepreOrderList(null));
- await dispatch(changePreOrderCusName(null));
- await dispatch(changePreOrderCusMob(null));
- await dispatch(changePreOrderDate());
- await dispatch(changePreOrderTime(null));
- await dispatch(changePreOrderAdd1(null));
- await dispatch(changePreOrderAdd2(null));
- await dispatch(changePreOrderAdvance(null));
- await dispatch(changePreOrderzip(null));
- await dispatch(changePreOrderCity(null));
- await dispatch(changePreOrderDistrict(null));
- await dispatch(changePreOrderState(null));
- await dispatch(changePreOrderAdditem('AddDetails'));
- await dispatch(changeSelectedOption(null));
- await dispatch(changeCustomerID(null));
- await dispatch(changealldata(false));
- await dispatch(changeSelectedCustId(null));
- }
- };
-
- const closePrintOption = () => {
- setShowWhatsAppShare(false);
- setSMSShare(false);
- setPrintOrderDetails([]);
- setMobileNoWhatsApp();
- };
-
- // const orderIdsArray =
- // PrintOrderDetails?.[0]?.OrderDetails?.map(
- // (orderDetail) => orderDetail?.OrderId
- // ) || [];
-
- const handleURL = async (PrintOrderDetails) => {
- let orderIdsArray = PrintOrderDetails?.[0]?.OrderDetails?.map(
- (orderDetail) => orderDetail?.OrderId
- );
- const encrypted = encryptObject(orderIdsArray);
-
- const postData = {
- Url: encrypted,
- CreatedBy: UserId,
+ return () => {
+ container.removeEventListener('scroll', updateScrollButtons);
+ window.removeEventListener('resize', updateScrollButtons);
+ resizeObserver.disconnect();
};
- if (orderIdsArray) {
- const res = await dispatch(PublicQrCodepost(postData)).unwrap();
- const urlData = res?.data?.ReferenceNo;
- setUrlData(urlData);
+ }, [modelstock, ModalVarient, modelQty]);
+
+ const handleScrollClickLeft = (scrollOffset) => {
+ scrollContainerRef.current.scrollBy({
+ left: -scrollOffset,
+ behavior: 'smooth',
+ });
+ };
+
+ const handleScrollClickRight = (scrollOffset) => {
+ scrollContainerRef.current.scrollBy({
+ left: scrollOffset,
+ behavior: 'smooth',
+ });
+ };
+ // const isDragging = useRef(false);
+
+ // MOUSE EVENTS
+ const handleMouseDown = (e) => {
+ isDragging.current = true;
+ startX.current = e.pageX - scrollContainerRef.current.offsetLeft;
+ scrollLeft.current = scrollContainerRef.current.scrollLeft;
+ scrollContainerRef.current.style.cursor = 'grabbing';
+ };
+
+ const handleMouseMove = (e) => {
+ if (!isDragging.current) return;
+ e.preventDefault(); // Important: prevents text selection and smooth scroll interference
+ const x = e.pageX - scrollContainerRef.current.offsetLeft;
+ const walk = (x - startX.current) * 0.8; // Adjust multiplier for speed
+ scrollContainerRef.current.scrollLeft = scrollLeft.current - walk;
+ };
+
+ const handleMouseUp = () => {
+ isDragging.current = false;
+ scrollContainerRef.current.style.cursor = 'grab';
+ };
+
+ // TOUCH EVENTS
+ const handleTouchStart = (e) => {
+ isDragging.current = true;
+ startX.current = e.touches[0].pageX - scrollContainerRef.current.offsetLeft;
+ scrollLeft.current = scrollContainerRef.current.scrollLeft;
+ };
+
+ const handleTouchMove = (e) => {
+ if (!isDragging.current) return;
+ e.preventDefault(); // Prevents native scrolling
+ const x = e.touches[0].pageX - scrollContainerRef.current.offsetLeft;
+ const walk = (x - startX.current) * 0.8; // Adjust multiplier as needed
+ scrollContainerRef.current.scrollLeft = scrollLeft.current - walk;
+ };
+
+ const handleTouchEnd = () => {
+ isDragging.current = false;
+ };
+
+ const allProducts = Object.values(brandMapping).flat();
+
+ const brandGroups = {};
+ allProducts.forEach((product) => {
+ const brandName =
+ product.BrandName &&
+ product.BrandName !== 'null' &&
+ product.BrandName !== 'undefined' &&
+ product.BrandName.trim() !== ''
+ ? product.BrandName
+ : 'Others';
+
+ if (!brandGroups[brandName]) {
+ brandGroups[brandName] = [];
}
+
+ brandGroups[brandName].push(product);
+ });
+
+ useEffect(() => {
+ const brandKeys = Object.keys(brandGroups || {});
+ if (brandKeys.length === 0) return;
+ // Only set if selectedBrand is not present in the new brandGroups
+ if (!brandKeys.includes(selectedBrand)) {
+ if (brandKeys.includes('Others')) {
+ setSelectedBrand('Others');
+ } else {
+ setSelectedBrand(brandKeys[0]);
+ }
+ }
+ }, [brandGroups]);
+
+ const sortedBrandNames = Object.keys(brandGroups).sort((a, b) =>
+ a === 'Others' ? -1 : b === 'Others' ? 1 : 0
+ );
+
+ const [prodname, setprodname] = useState('');
+ const [prodQty, setprodQty] = useState(0);
+ const normalize = (str) => str?.toLowerCase()?.replace(/\s+/g, ' ')?.trim();
+
+ const result = prodname
+ ? (cardData || [])?.filter(
+ (item) =>
+ normalize(item.ProdName).includes(normalize(prodname)) ||
+ normalize(item.ProdCatName).includes(normalize(prodname)) ||
+ item.ProductDetail?.some((detail) =>
+ normalize(detail.ProdName).includes(normalize(prodname))
+ )
+ )
+ : cardData;
+
+ console.log(prodQty, 'cardDatacardData', result, prodname);
+ const AddnewProduct = () => {
+ setNewMoreProductModel(true);
};
+ useEffect(() => {
+ const item = result?.[0];
+ const detail = item?.ProductDetail?.[0];
- const customerNameOrMobile = MobileNoWhatsApp?.CustName?.trim()
- ? `Dear ${MobileNoWhatsApp?.CustName}`
- : `Dear ${MobileNoWhatsApp?.value}`;
- const documentUrl = `${MainHomeUrl}viewbill?code=${urlData}`;
- const encodedMessage = `${customerNameOrMobile},\n\n🙏 Thank you for being a valuable customer!\n\n🧾 To view your bill, please click the link below:\n${documentUrl}`;
- const handlepaymentoptions = async () => {
- await dispatch(changeSalesPaymentoption(true));
- await dispatch(
- getPaymentOptionsData({
- AppId: AppId,
- CompId: CompId,
- BranchId: BranchId,
- })
- );
- };
+ const isInStock =
+ detail?.StockAvailable === 'Y' && item?.OverAllQty > prodQty;
+ const isStockNotTracked = detail?.StockAvailable === 'N';
- const handleotherservices = () => {
- dispatch(changeOtherServices(true));
- dispatch(changeComboRedirectionToDefaultLayoutForParking(true));
- dispatch(
- changetemplateData({
- AppName,
- SelectedApplication: AppId,
- Type: 'ParkingRedirect',
- })
- );
- };
+ if (result?.length > 0 && prodname && (isInStock || isStockNotTracked)) {
+ // CardOnclick(item,(item?.OnePcsAvailable && preferenceSingleSales) && 'OnePeiceProduct' );
+ CardOnclick(
+ result?.[0],
+ result?.[0]?.OnePcsAvailable === 'Y' &&
+ preferenceSingleSales &&
+ 'OnePeiceProduct'
+ );
+ // AddOrderDetails2(result?.[0])
+ } else if (item?.OverAllQty < prodQty) {
+ setMessageType('error');
+ setMessageData('NoStack');
+ }
+ }, [prodname]);
+ function getClassNameBasedOnCard(type) {
+ switch (type) {
+ case 'Card1':
+ return 'AddNewProductSalesBTNCard1';
+ case 'Card2':
+ return 'AddNewProductSalesBTNCard2';
+ case 'Card3':
+ return 'AddNewProductSalesBTNCard3';
+ case 'Card4':
+ return 'AddNewProductSalesBTNCard4';
+ default:
+ return 'AddNewProductSalesBTNCard1';
+ }
+ }
- return (
- <>
-
-
-
-
- {BSComboNavbar?.[1]?.map((item) => (
- <>
- {item?.OptionName == 'QuickAdd' && (
-
-
-
-
- Quick Add
-
- (Alt + N)
-
-
-
-
- )}
- {item?.OptionName == 'DineIn' &&
- DineInPreference?.SettingValue === 'Y' &&
- dinePreference && (
-
-
-
- )}
- {item?.OptionName == 'TakeAway' && takeAwayPreference && (
-
-
- BookingType !== 'TakeAway' && ChangeTakeAway()
- }
- style={{
- pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
- }}
- >
-
- {/* TAKE AWAY */}
- Take Away
-
-
- )}
- >
- ))}
+ function encrypt(code, key) {
+ let encrypted = (
+
Suspense Loading... }>
+ <>
+
+ {messageType && messageData && (
+
+ )}
- {OtherServiceStatus && (
+
{
+ // trigger child function
+ voiceTriggerRef?.current?.listening();
+ }}
+ style={{
+ position: 'absolute',
+ zIndex: '12',
+ top:
+ templateData?.BookingLayout?.[0] === 'Layout5' ||
+ templateData?.BookingLayout?.[0] === 'Layout4' ||
+ templateData?.BookingLayout?.[0] === 'Layout6'
+ ? '2.5rem'
+ : '',
+ }}
+ >
+ {
+ setprodname(data.product);
+ setprodQty(data.qty);
+ }}
+ />
+
+ {/*
{prodname}
*/}
+
-
+ {/* */}
+ {cardData?.length > 0 ? (
+ <>
+
+ item.id)}
+ strategy={rectSortingStrategy}
+ >
+
+ {AddProductCard && !favouriteCat && ProdCat && (
+
+
+ Add Product
+
+ )}
+ {draggableCardData.map((item) => (
+
+ {templateData?.BookingCard?.[0] != 'Card4' ? (
+ 0) ||
+ item?.ProductDetail?.some(
+ (item) => item?.StockAvailable !== 'Y'
+ )
+ ? 'BkPrdCardActive'
+ : 'BkPrdCardDeActive'
+ }
+ >
+ {!isMobile ? (
+
+ {globaldata && (
+ pickData(e, item)}
+ style={{
+ position: 'absolute',
+ zIndex: 1,
+ transform: 'scale(1.5)',
+ cursor: 'pointer',
+ }}
+ checked={(
+ globalAllItemdata || EditfavItems
+ )?.some(
+ // (a) => a?.ProdName === item?.ProdName
+ (a) =>
+ a?.ProdName === item?.ProdName &&
+ a?.ProdCat === item?.ProdCat
+ )}
+ />
+ )}
+
+
+ // handleMouseDownItemCard(e, item)
+ // }
+ // onMouseUp={(e) =>
+ // handleMouseUpItemCard(e, item)
+ // }
+ // onMouseLeave={handleMouseLeave}
+ // onTouchStart={(e) =>
+ // handleTouchStartItemCard(e, item)
+ // }
+ // onTouchEnd={(e) =>
+ // handleTouchEndItemCard(e, item)
+ // }
+ // onTouchCancel={handleTouchCancelItemCard}
+ // onContextMenu={(e) => e.preventDefault()}
+ onClick={(e) => {
+ if (
+ !(
+ (item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ )
+ )
+ ) {
+ e.stopPropagation();
+ } else {
+ CardOnclick(
+ item,
+ item?.OnePcsAvailable === 'Y' &&
+ preferenceSingleSales &&
+ 'OnePeiceProduct'
+ );
+ }
+ }}
+ data-aos="zoom-in"
+ data-aos-duration="600"
+ >
+ {(cardFunction?.BigImage ||
+ cardFunction?.SmallImage) && (
+
+ )}
+
+
+ {item?.ProdName}{' '}
+ {(item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails,
+ item
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ ) ? (
+ ''
+ ) : (
+
+ No Stock
+
+ )}
+
+ {cardFunction?.Price &&
+ ((item?.OverAllQty !== undefined &&
+ (!preferenceSingleSales
+ ? item?.OverAllQty !== 0
+ : item?.OverAllPcs !== 0) &&
+ item?.OverAllQty !== null) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ )) && (
+
+ ₹ {ItemSellingPrice(item)}
+
+ <>
+ ({ItemSize(item)}{' '}
+ {ItemUomName(item)})
+ >
+
+
+ )}
+
+
+ {cardFunction?.StockCount &&
+ item?.OverAllQty !== undefined &&
+ (!preferenceSingleSales
+ ? item?.OverAllQty !== 0
+ : item?.OverAllPcs !== 0) && (
+
+ {item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable === 'Y'
+ ) &&
+ item?.OverAllQty !== null && (
+
+ )}
+
+ )}
+
+
+ {item?.ProductDetail?.filter(
+ (item) => item.OnePcsAvailable == 'Y'
+ ).length !== 0 &&
+ !preferenceSingleSales && (
+ {
+ if (
+ !(
+ (item?.OverAllQty !==
+ undefined &&
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !==
+ 'Y'
+ )
+ )
+ ) {
+ e.stopPropagation();
+ } else {
+ CardOnclick(
+ item,
+ 'OnePeiceProduct'
+ );
+ }
+ }}
+ style={{
+ fontFamily:
+ SelectedCardFont || '',
+ backgroundColor:
+ SelectedCardColor?.FontColor ||
+ '#ffffff',
+ color:
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0 ||
+ item?.ProductDetail?.some(
+ (product) =>
+ product?.StockAvailable !==
+ 'Y'
+ )
+ ? cardFunction?.Background
+ ? SelectedCardColor?.BackgroundColor ||
+ '#000000'
+ : '#fff'
+ : '#ff4d4f',
+ }}
+ >
+ {SingleMember ? 'Single' : '1 PCS'}
+
+ )}
+
+ ) : (
+ <>
+ {globaldata && (
+
pickData(e, item)}
+ style={{
+ position: 'absolute',
+ zIndex: 1,
+ transform: 'scale(1.5)',
+ cursor: 'pointer',
+ }}
+ checked={(
+ globalAllItemdata || EditfavItems
+ )?.some(
+ // (a) => a?.ProdName === item?.ProdName
+ (a) =>
+ a?.ProdName === item?.ProdName &&
+ a?.ProdCat === item?.ProdCat
+ )}
+ />
+ )}
+
+
{
+ if (
+ !(
+ (item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ )
+ )
+ ) {
+ e.stopPropagation();
+ } else {
+ CardOnclick(
+ item,
+ item?.OnePcsAvailable === 'Y' &&
+ preferenceSingleSales &&
+ 'OnePeiceProduct'
+ );
+ }
+ }}
+ // data-aos="zoom-in" data-aos-duration="600"
+ >
+ {(cardFunction?.BigImage ||
+ cardFunction?.SmallImage) && (
+
+ )}
+
+
+ {item?.ProdName}{' '}
+ {(item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails,
+ item
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ ) ? (
+ ''
+ ) : (
+
+ No Stock
+
+ )}
+
+ {cardFunction?.Price &&
+ ((item?.OverAllQty !== undefined &&
+ (!preferenceSingleSales
+ ? item?.OverAllQty !== 0
+ : item?.OverAllPcs !== 0) &&
+ item?.OverAllQty !== null) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ )) && (
+
+ ₹ {ItemSellingPrice(item)}
+ {/* {item?.ProductDetail?.[0]?.ProdVariantDetails?.[0]?.StockDetails?.[0]?.SellPrice} */}
+ {/* {ItemSellingPrice(item)} */}
+
+ ({ItemSize(item)}{' '}
+ {ItemUomName(item)})
+
+
+ )}
+
+
+ {cardFunction?.StockCount &&
+ item?.OverAllQty !== undefined &&
+ (!preferenceSingleSales
+ ? item?.OverAllQty !== 0
+ : item?.OverAllPcs !== 0) && (
+
+ {item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable === 'Y'
+ ) &&
+ item?.OverAllQty !== null && (
+
+ )}
+
+ )}
+
+ {item?.ProductDetail?.filter(
+ (item) => item.OnePcsAvailable == 'Y'
+ ).length !== 0 &&
+ !preferenceSingleSales && (
+
{
+ if (
+ !(
+ (item?.OverAllQty !==
+ undefined &&
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !==
+ 'Y'
+ )
+ )
+ ) {
+ e.stopPropagation();
+ } else {
+ CardOnclick(
+ item,
+ 'OnePeiceProduct'
+ );
+ }
+ }}
+ style={{
+ fontFamily:
+ SelectedCardFont || '',
+ backgroundColor:
+ SelectedCardColor?.FontColor ||
+ '#ffffff',
+ color:
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0 ||
+ item?.ProductDetail?.some(
+ (product) =>
+ product?.StockAvailable !==
+ 'Y'
+ )
+ ? cardFunction?.Background
+ ? SelectedCardColor?.BackgroundColor ||
+ '#000000'
+ : '#fff'
+ : '#ff4d4f',
+ }}
+ >
+ {SingleMember ? 'Single' : '1 PCS'}
+
+ )}
+ >
+ )}
+
+ ) : (
+ 0) ||
+ item?.ProductDetail?.some(
+ (item) => item?.StockAvailable !== 'Y'
+ )
+ ? 'card4Main card4Main-active'
+ : 'card4Main card4Main-deactive'
+ }
+ // onMouseDown={(e) =>
+ // handleMouseDownItemCard(e, item)
+ // }
+ // onMouseUp={(e) =>
+ // handleMouseUpItemCard(e, item, true)
+ // }
+ // onMouseLeave={handleMouseLeave}
+ // onTouchStart={(e) =>
+ // handleTouchStartItemCard(e, item)
+ // }
+ // onTouchEnd={(e) =>
+ // handleTouchEndItemCard(e, item, true)
+ // }
+ // onTouchCancel={handleTouchCancelItemCard}
+ // onContextMenu={(e) => e.preventDefault()}
+ onClick={(e) => {
+ if (
+ !(
+ (item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) => item?.StockAvailable !== 'Y'
+ )
+ )
+ ) {
+ e.stopPropagation(); // Prevent event bubbling if no stock or condition isn't met
+ } else {
+ // Ensure this only runs if the "One Piece" condition isn't triggered
+ if (
+ !e.target.closest('.card4Main-onepiece')
+ ) {
+ CardOnclick(
+ item,
+ item?.OnePcsAvailable === 'Y' &&
+ preferenceSingleSales &&
+ 'OnePeiceProduct'
+ );
+ // This will trigger if you're clicking outside the "One Piece" button
+ }
+ }
+ }}
+ >
+ {/* Global Data Checkbox */}
+ {globaldata && (
+
e.stopPropagation()}
+ onChange={(e) => {
+ e.stopPropagation();
+ pickData(e, item);
+ }}
+ style={{
+ position: 'absolute',
+ zIndex: 1,
+ transform: 'scale(1.5)',
+ cursor: 'pointer',
+ }}
+ checked={(
+ globalAllItemdata || EditfavItems
+ )?.some(
+ (a) =>
+ a?.ProdName === item?.ProdName &&
+ a?.ProdCat === item?.ProdCat
+ )}
+ />
+ )}
+
+ {/* Tooltip for Product Name */}
+
+
+
+
+
+
+
+
+ {item?.ProdName}
+ {(item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails,
+ item
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) => item?.StockAvailable !== 'Y'
+ ) ? (
+ ''
+ ) : (
+
+ No Stock
+
+ )}
+
+ {((item?.OverAllQty !== undefined &&
+ !preferenceSingleSales
+ ? returnCount(
+ item?.ProductDetail?.[0]?.ProdName,
+ item?.OverAllQty,
+ CartOrderDetails,
+ item
+ )
+ : returnOnepcCount(
+ item?.ProductDetail?.[0]?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) => item?.StockAvailable !== 'Y'
+ )) && (
+
+
+ ₹ {ItemSellingPrice(item)}
+
+
+
+ <>
+ ({ItemSize(item)}{' '}
+ {ItemUomName(item)})
+ >
+
+
+ )}
+
+
+ {/* Stock Count Badge */}
+ {cardFunction?.StockCount &&
+ item?.OverAllQty !== undefined &&
+ (!preferenceSingleSales
+ ? item?.OverAllQty !== 0
+ : item?.OverAllPcs !== 0) && (
+
+ {item?.ProductDetail?.some(
+ (item) => item?.StockAvailable === 'Y'
+ ) &&
+ item?.OverAllQty !== null && (
+
+ )}
+
+ )}
+
+ {/* One Piece Button */}
+ {item?.ProductDetail?.filter(
+ (item) => item.OnePcsAvailable == 'Y'
+ ).length !== 0 &&
+ !preferenceSingleSales && (
+
{
+ e.stopPropagation(); // Stop event propagation to the parent div
+
+ if (
+ !(
+ (item?.OverAllQty !== undefined &&
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0) ||
+ item?.ProductDetail?.some(
+ (item) =>
+ item?.StockAvailable !== 'Y'
+ )
+ )
+ ) {
+ return; // Don't proceed if the condition isn't met
+ } else {
+ CardOnclick(
+ item,
+ 'OnePeiceProduct'
+ ); // This only runs when you click the "One Piece" button
+ }
+ }}
+ style={{
+ fontFamily: SelectedCardFont || '',
+ backgroundColor:
+ SelectedCardColor?.FontColor ||
+ '#ffffff',
+ color:
+ returnOnepcCount(
+ item?.ProductDetail?.[0]
+ ?.ProdName,
+ item?.OverAllPcs,
+ CartOrderDetails
+ ) > 0 ||
+ item?.ProductDetail?.some(
+ (product) =>
+ product?.StockAvailable !== 'Y'
+ )
+ ? cardFunction?.Background
+ ? SelectedCardColor?.BackgroundColor ||
+ '#000000'
+ : '#fff'
+ : '#ff4d4f',
+ }}
+ >
+ {SingleMember ? 'Single' : '1 PCS'}
+
+ )}
+
+ )}
+
+ ))}
+
+
+
+ >
+ ) : ProductSearch?.length > 5 &&
+ GetmultipleSearchDatas.some(
+ (e) => e.toLowerCase() === 'qrcode'
+ ) &&
+ (cardData?.length == 0 || cardData == undefined) ? (
+
+ {/* cardData mohan 18-04-2025 */}
+
+
+ ) : (
+ <>
+
+ >
+ )}
+ {paymentloader === true && (
+
+
+
+
+
+
+
+ {' '}
+ Please wait while we process your payment
+
+ {PaymentTransactionNumber != null && (
+
+ Transaction Number : {PaymentTransactionNumber}
+
+ )}
+
+
+ )}
+
+
+
+ {expireModal?.open && (
+
{
+ expireModal.onOk?.();
+ closeExpireModal();
+ }}
+ onCancel={() => {
+ expireModal.onCancel?.();
+ closeExpireModal();
+ }}
+ />
+ )}
+
+ {modelQty && (
+
+
+
+ }
+ open={modelQty}
+ width={800}
+ handleCancel={CloseModal}
+ footer={null}
+ maskTransitionName=""
+ transitionName=""
+ children={
+
+
+
+
+
+ {qtydata?.ProdName}
+
+
+
+ {/* Horizontal scroll container */}
+
+
+ {/* Left Scroll Button */}
+ {showLeftButton && (
+
handleScrollClickLeft(200)}
+ style={{
+ position: 'absolute',
+ left: 0,
+ top: '35%',
+ transform: 'translateY(-50%)',
+ zIndex: 10,
+ background: '#fff',
+ padding: '0.5rem',
+ cursor: 'pointer',
+ boxShadow: '0 0 5px rgba(0,0,0,0.2)',
+ }}
+ >
+ ◄
+
+ )}
+
+ {/* Scroll Container */}
+
+ {Object.keys(brandGroups)
+ .sort((a, b) =>
+ a === 'Others' ? -1 : b === 'Others' ? 1 : 0
+ )
+ .map((brand) => (
+
setSelectedBrand(brand)}
+ style={{
+ minWidth: '150px',
+ background:
+ selectedBrand === brand
+ ? '#cce5ff'
+ : '#f4f4f4',
+ borderRadius: '8px',
+ padding: '0.8rem',
+ flexShrink: 0,
+ cursor: 'pointer',
+ userSelect: 'none',
+ textAlign: 'center',
+ fontWeight:
+ selectedBrand === brand ? 'bold' : 'normal',
+ }}
+ >
+ {brand === 'Others' ? 'Others' : brand}
+
+ ))}
+
+
+ {/* Right Scroll Button */}
+ {showRightButton && (
+
handleScrollClickRight(200)}
+ style={{
+ position: 'absolute',
+ right: 0,
+ top: '35%',
+ transform: 'translateY(-50%)',
+ zIndex: 10,
+ background: '#fff',
+ padding: '0.5rem',
+ cursor: 'pointer',
+ boxShadow: '0 0 5px rgba(0,0,0,0.2)',
+ }}
+ >
+ ►
+
+ )}
+
+ {/* Selected brand products */}
+
+
+ {selectedBrand === 'Others' ? 'Others' : selectedBrand}{' '}
+ Products
+
+
+ {(brandGroups[selectedBrand] || []).map(
+ (product, index) => {
+ const qtyCount = returnQtyCount(
+ product?.ProdId,
+ product,
+ CartOrderDetails
+ );
+ const isAvailable = product?.StockAvailable !== 'Y';
+ const isDisabled = qtyCount > 0 || isAvailable;
+
+ return (
+
+
VarientFun(product)}
+ >
+
+
+
+
+
+
+
+
+
+ {product?.Size + ' ' + product?.UomName}
+
+ {!isDisabled && (
+
+ No Stock
+
+ )}
+ {isDisabled && (
+
+
+ ₹
+
+
+ {safeRound(
+ product?.ProdVariantDetails?.[0]
+ ?.StockDetails?.[0]?.SellPrice
+ )}
+
+ )}
+
+
+
+ );
+ }
+ )}
+
+
+
+ {Object.keys(brandMapping).length === 0 && (
+
No product details available
+ )}
+
+
+ }
+ />
+ )}
+ {modelstock && (
+
+
+
+ }
+ open={modelstock}
+ // width={500}
+ footer={null}
+ top={0}
+ handleCancel={CloseModal1}
+ maskTransitionName=""
+ transitionName=""
+ children={
+
+
-
- Other Services
-
-
-
- )}
-
-
-
- {BSComboNavbar?.[1]?.map((item) => (
- <>
- {item?.OptionName == 'Offer' && (
-
-
-
- )}
- {item?.OptionName == 'ExtraCharge' && (
-
-
-
-
- {/* EXTRA CHARGE */}
- Extra Charge
+
+
-
-
- (Alt + A)
+
+
+ {qtydata?.ProdName}{' '}
+ {!qtydata?.ProductDetail?.[
+ QtyIndex
+ ]?.ProdVariantDetails?.[
+ VarientIndex
+ ]?.ProdVariantName?.toLowerCase()?.includes(
+ 'variant'
+ ) && (
+
+ (
+ {
+ qtydata?.ProductDetail?.[QtyIndex]
+ ?.ProdVariantDetails?.[VarientIndex]
+ ?.ProdVariantName
+ }
+ ){' '}
+
+ )}
+
-
- )}
- {item?.OptionName == 'RePrint' && (
-
-
-
-
- Re-Print
+
+
+
+
+ {qtydata?.ProductDetail?.[QtyIndex]?.Size}{' '}
+ {onePeiceFlow
+ ? 'PCS'
+ : qtydata?.ProductDetail?.[QtyIndex]?.UomName}
+
-
-
- (Alt + R)
-
-
- )}
- >
- ))}
- {/* {reprint1 && (
-
- )} */}
- {extraCharges && (
-
- )}
- {QuickAdd && (
-
- )}
- {creditCustomerOpen && (
-
- )}
- {TotalAmount == 0 && Success && (
-
-
-
- )}
- {TotalAmount > 0 &&
- qrCode &&
- PaymentUpiOptions?.length > 0 &&
- SelectedUpiOption && (
-
-
+
+
- )}
-
- {PaymentUpiOptions?.length > 0 && OrderId && (
-
-
-
- )}
-
-
-
-
-
-
setIsFloatMenuOpen(!isFloatMenuOpen)}
- >
-
-
-
- {isFloatMenuOpen && (
-
- {!OtherServiceStatus && (
-
- )}
- {BSComboNavbar?.[1]?.map((item) => (
- <>
- {item?.OptionName == 'QuickAdd' && (
-
-
-
-
-
- Quick Add (Alt +N)
-
-
-
-
- )}
- {item?.OptionName == 'DineIn' &&
- DineInPreference?.SettingValue === 'Y' && (
- <>
-
- {FirstPaymentclick === false &&
- !addnewAccess &&
- !OrderStatus && (
-
-
-
- )}
- >
- )}
- {item?.OptionName == 'TakeAway' && (
-
- )}
- {item?.OptionName == 'Offer' && (
-
-
-
- )}
- {item?.OptionName == 'ExtraCharge' && (
-
- )}
- {item?.OptionName == 'RePrint' && (
-
- )}
- >
- ))}
-
- )}
-
-
-
-
-
- 0) &&
- !unpaidFlow &&
- OrderStatus
- ? 'none'
- : 'auto',
- opacity:
- (BookingType === 'Dine In' ||
- BookingTypeBoth ||
- CheckOrderType?.length > 0) &&
- !unpaidFlow &&
- OrderStatus
- ? 0.5
- : 1,
- }}
- >
- {paybtns?.length > 0 ? (
- paybtns?.map((payment) => (
-
-
- payment?.ModeName?.toLowerCase() === 'upi' // Change the condition to payment.Id
- ? handleUPIButtonClick(payment.ModeId, payment.ModeName)
- : handlePaymentMode(payment.ModeId, payment.ModeName)
- }
- >
- {/* {UpiOption === "" && payment?.ModeName?.toLowerCase() === "upi" && UPI
} */}
-
-
- {payment.ModeName}
- {payment?.ModeName?.toLowerCase() === 'card' && (
-
- )}
- {payment?.ModeName?.toLowerCase() === 'upi' && (
-
- )}
-
-
-
- ))
- ) : (
-
- Please Set Payment Options
-
- )}
-
- {paybtns?.length > 1 && (
-
0) &&
- !unpaidFlow &&
- OrderStatus
- ? 'none'
- : 'auto',
- opacity:
- (BookingType === 'Dine In' ||
- BookingTypeBoth ||
- CheckOrderType?.length > 0) &&
- !unpaidFlow &&
- OrderStatus
- ? 0.5
- : 1,
- }}
- >
-
- {' '}
-
-
-
- )}
-
-
-
- {/*
-
- CASH
- CARD
- UPI
-
-
*/}
-
-
-
-
-
-
-
-
Items
-
:
-
- {' '}
- {TotalItems}{' '}
-
-
-
-
-
-
-
-
-
- {(addcustomer || hold) && (
-
setHold(false)}
+ }
/>
)}
-
- {Estimation?.SettingValue == 'Y' &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth && (
-
-
-
- )}
- {BSComboData?.BookingBilling?.[1]?.map((item) => (
- <>
- {/* {item?.OptionName=="Hold" && */}
- {unpaidFlow == false
- ? item?.OptionName == 'Hold' &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- OrderCardDetail?.length != 0 &&
- CheckOrderType?.length === 0 &&
- OrderType != 'Failed' &&
- CheckBookingStatus != 'Close' &&
- !addnewAccess && (
-
- {' '}
-
-
AddBookingDetails('Hold')}
- style={{
- cursor: 'pointer',
- // color: '' ? '#52c41a' : '#1292EE',
- }}
- />{' '}
- Hold
-
-
- )
- : ''}
-
- {unpaidFlow == false
- ? item?.OptionName == 'Hold' &&
- BookingType !== 'Dine In' &&
- !BookingTypeBoth &&
- Holddata?.length > 0 &&
- OrderCardDetail?.length == 0 &&
- CheckBookingStatus != 'Close' &&
- !addnewAccess && (
-
- {' '}
-
-
-
HandleholdModelOpen()}
- style={{
- cursor: 'pointer',
- // color: Holddata ? '#52c41a' : 'default',
- pointerEvents:
- OrderType === 'Failed' ? 'none' : 'auto',
- }}
- />
-
-
-
- )
- : ''}
- {tabledata?.length > 0 && dinePreference && (
- <>
- {item?.OptionName == 'UnpaidBill' && (
-
- {' '}
-
-
{
- (setUnpaidOpen(true), getUnpaiddatas());
- }}
- />
-
-
- )}
- >
- )}
- >
- ))}
- {BSComboData?.BookingBilling?.[1]?.filter(
- (item) => item.OptionName === 'AddCustomer'
- ).length === 1 ? (
- <>
- {Object.keys(useOptions)?.length > 0 &&
- useOptions?.some((flow) =>
- flow.OptionDetails.some(
- (option) =>
- option.OptionName === 'Pay at the counter' &&
- option.ModeDetails.some(
- (mode) => mode.ModeName === 'Credit'
- )
- )
- ) && (
-
-
- 0 ||
- (selOption?.value === undefined &&
- GlobalAddCustomerDetails1?.length === 0 &&
- GetCustId?.CustMobile === undefined)
- ? 'gray'
- : '#1292eeff',
- color: '#fff',
- height: '40px',
- width: '45px',
- borderRadius: '6px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- padding: '8px 8px 12px 8px',
- }}
- >
- {' '}
-
0 && 'not-allowed',
- // color:
- // OrderCardDetail?.length > 0 ||
- // (selOption?.value === undefined &&
- // GlobalAddCustomerDetails1?.length === 0 &&
- // GetCustId?.CustMobile === undefined)
- // ? 'gray'
- // : '#1292eeff',
- fontSize: '28px',
- }}
- />{' '}
- Adv Amt
-
-
-
- )}
- >
- ) : (
- ''
- )}
-
- {/* Customer Orders */}
- {GetCustId && (
-
- {' '}
- {
- if (
- CheckBookingStatus !== 'Close' &&
- !addnewAccess &&
- !(OrderCardDetail?.length > 0)
- ) {
- setCustomerPreviesOrders(true);
- }
- }}
- style={{
- cursor: OrderCardDetail?.length > 0 && 'not-allowed',
- color:
- OrderCardDetail?.length > 0 ||
- (OrderCardDetail?.length > 0 &&
- GetCustId?.CustMobile === undefined)
- ? 'gray'
- : 'rgb(255, 255, 255)',
- color: '#fff',
- height: '40px',
- width: '45px',
- borderRadius: '6px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- padding: '5px 5px 6px 5px',
- background: 'rgb(18, 146, 238)'
- }}
- >
- Cust Orders
-
-
- )}
- {FeatureAddonData?.FeatureDtls?.find(
- (item) => item?.FeatureAddonName?.toLowerCase() === 'preorder'
- ) && (
- <>
- {
-
0 || OrderType === 'Failed'
- ? 'none'
- : 'auto',
- opacity: OrderCardDetail?.length > 0 ? 0.5 : 1,
- }}
- >
-
-
- {
- openPreOrder();
- }}
- />
-
-
-
- }
- >
- )}
- {preOrderOpen &&
}
- {sportsAppPreference &&
}
- {dinePreference &&
- (BookingType === 'Dine In' ||
- BookingTypeBoth ||
- CheckOrderType?.length > 0) &&
- !unpaidFlow && (
- <>
-
- {' '}
-
- FirstPaymentclick === false && !addnewAccess
- ? changeOrderStatus()
- : ''
- }
- style={{
- pointerEvents: OrderType === 'Failed' ? 'none' : 'auto',
- }}
- />
-
- {FirstPaymentclick === false &&
- !addnewAccess &&
- !OrderStatus &&
}
- >
- )}
- {OrderCardDetail?.length > 0 && ParkingDisplay && (
-
-
-
- )}
- {unpaidFlow == true ? (
-
- {
- Recipt();
- }}
- />
-
- ) : (
- ''
- )}
- {/*
-
-
- >
- }
- trigger="click"
- open={open}
- onOpenChange={handleOpenChange}
- >
-
-
-
*/}
- {/* {ComboDropDown?.length >= 1 && (
-
-
-
+
-
-
- )} */}
- {paymentfeataddon && (
-
- {
- paymentFailedStatusFun();
- }}
- style={{
- width: '27px',
- cursor: 'pointer',
- fontWeight: '600',
- color: 'rgb(18, 146, 238)',
- }}
- >
-
-
- )}
- {OpenFailData && (
-
- )}
-
-
-
- {BSComboData?.BookingBilling?.[1]?.map((item) => (
- <>
- {item?.OptionName == 'AddCustomer' && !preOrderOpen && (
-
- )}
- >
- ))}
-
-
-
- 0 &&
- paybtnselected &&
- CheckBookingStatus != 'Close'
- ? !OrderStatus
- ? 'BSC1Payment-div4-button'
- : 'BSC1Payment-div4-button Order'
- : 'BSC1Payment-div4-button-disable'
- }
- // onClick={() => {
- // (qrCode && SelectedUPIPayOption === "Default") ? UpiPayment() : OrderStatus ? AddBookingDetails("Dine-In") : AddBookingDetails(BookingType, true);
- // }}
- onClick={handleButtonClick}
- style={{ borderRadius: '6px 0 0 6px' }}
- >
- {!OrderStatus ? (
- <>
- {isMobile ? (
- `₹ ${safeRound(
- OrderType === 'Failed'
- ? FailedTotalAmt
- : credit && overAllBal >= 0
- ? Math.max(0, TotalAmount - overAllBal)
- : TotalAmount
- )}`
- ) : (
-
- ₹
-
= 0
- ? Math.max(0, TotalAmount - overAllBal)
- : TotalAmount
- )}
- />
+ }
+ open={ModalVarient}
+ width={500}
+ top={0}
+ footer={null}
+ handleCancel={CloseVarientModal}
+ maskTransitionName=""
+ transitionName=""
+ children={
+
+
+
+
- )}
-
- >
- ) : (
-
ORDER
- )}
-
-
-
+
+ {qtydata?.ProdName}
+
+
+
+
+
+
+
+ {qtydata?.ProductDetail?.[QtyIndex]?.Size}{' '}
+ {onePeiceFlow
+ ? 'PCS'
+ : qtydata?.ProductDetail?.[QtyIndex]?.UomName}
+
+
+
+
+
+
+
+ }
+ />
+ )}
+ {productPriceChange && priceChangeProduct?.length > 0 && (
+
+ )}
+
+ {newMoreProductModel && (
+ setNewMoreProductModel(false)}
+ children={
<>
-
-
-
-
+
>
}
- trigger="click"
- open={open}
- onOpenChange={handleOpenChange}
- >
-
-
-
-
-
-
- {PrintOrderDetails?.length > 0 &&
- PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
-
- ))}
- {PrintOrderDetails?.length > 0 &&
- (TokenOnly?.SettingValue === 'Y' ||
- IndividualToken?.SettingValue === 'Y') &&
- PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
-
-
-
- ))}
- {CreditCustomer && (
-
- {
- handleCreditCustomer('Cancel');
- }}
- handleOk={() => {
- handleCreditCustomer('Submit');
- }}
- />
-
- )}
-
- {UpiOpen && (
-
{
- Upimodel('Cancel');
- }}
- footer={false}
- children={
-
- {/*
UPI PAYMENT */}
-
-
-
-
-
-
-
-
- {' '}
- RS :
- {OrderType === 'Failed'
- ? FailedTotalAmt
- : Math.round(TotalAmount)}{' '}
-
-
-
-
-
- {(selOption || SelCustId) && (
-
- Sent Payment Link
-
- {/*
*/}
-
- )}
-
-
- }
- handleSubmit={() => {
- Upimodel('Submit');
- }}
- />
-
-
-
- }
- />
- )}
- {unpaidopen && (
- {
- setUnpaidOpen(false);
- }}
- footer={false}
- children={
-
- }
- />
- )}
- {/*
-
- */}
- {UnpaidConfirmation && (
-
-
- You have already selected a table. If you click 'OK,' the table
- selection will be removed, and the unpaid flow will continue. If
- you click 'Cancel,' the dine-in flow will proceed as selected.
-
- >
- }
- onOk={UnpaidOk}
- onCancel={Unpaidclose}
- />
- )}
- {Splitpayment && (
-
- )}
- {PrintOrderDetails?.length > 0 && (
-
- {filteredSettingNames?.includes('whatsapp') &&
- MobileNoWhatsApp?.value && (
-
- )}
-
-
-
- {filteredSettingNames?.includes('SMS') && isMobile && (
-
)}
- {/* WhatsAppShare modal/component */}
- {showWhatsAppShare && (
- closePrintOption(false)}
- />
- )}
- {showSMSShare && isMobile && (
- closePrintOption(false)}
- />
- )}
-
- )}
- {
- dispatch(changeSalesPaymentoption(false));
- }}
- footer={false}
- children={
-
- }
- />
- {customerPreviesOrders && (
- setCustomerPreviesOrders(false)}
- footer={false}
- width={700}
- className={'ModalPaymentGatewayEmbedded'}
- children={
- <>
- setCustomerPreviesOrders(false)}
- />
- >
- }
- />
- )}
- >
- );
+ >
+
+ );
+ for (let i = 0; i < code?.length; i++) {
+ encrypted += String.fromCharCode(
+ code.charCodeAt(i) ^ key.charCodeAt(i % key.length)
+ );
+ }
+ return encrypted;
+ }
+
+ function decrypt(encrypted, key) {
+ // Implement decryption logic
+ let decrypted = encrypt();
+ for (let i = 0; i < encrypted?.length; i++) {
+ decrypted += String.fromCharCode(
+ encrypted.charCodeAt(i) ^ key.charCodeAt(i % key.length)
+ );
+ }
+ return decrypted;
+ }
+
+ const encryptedCode = encrypt(); // Encrypted React component code
+ const decryptionKey = decrypt(); // Decryption key (keep it secure)
+ const decryptedCode = decrypt(encryptedCode, decryptionKey);
+
+ return <>{encrypt()}>;
};
-export default BSC1Payment;
+export default React.memo(BSItemCard);
diff --git a/src/routesConfig.jsx b/src/routesConfig.jsx
index d90267a..f48462a 100644
--- a/src/routesConfig.jsx
+++ b/src/routesConfig.jsx
@@ -684,7 +684,7 @@ const initSession = () => {
sessionStorage.setItem(
'auth',
- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiOTM2MDY0MjI0NCIsIlBhc3N3b3JkIjoiWkB6MTIzNCIsImF1ZCI6WyJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTMiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTIiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTQiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTMiXSwiZXhwIjoxNzcwOTIyMDEyLCJpc3MiOiJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMDEifQ.8iuEF8S7kW1OvVUda3YAx9v7ilp-uy9PVfbBvCPoq20'
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiOTM2MDY0MjI0NCIsIlBhc3N3b3JkIjoiWkB6MTIzNCIsImF1ZCI6WyJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTMiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTIiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTQiLCJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMTMiXSwiZXhwIjoxNzcxODcyOTYwLCJpc3MiOiJodHRwOi8vMTkyLjE2OC4xLjM3OjgwMDEifQ.tRA41-3-m2VYm_jkndGPLzB-jxzuO1XvG94Fmf6NTGQ'
);
};