From fcb0df018c7c03146d04b093f0aadeee1c93da8d Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:16:52 +0530 Subject: [PATCH 01/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable7/BSBilling7Payment.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable7/BSBilling7Payment.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable7/BSBilling7Payment.jsx index 83380f9..f8400af 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable7/BSBilling7Payment.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable7/BSBilling7Payment.jsx @@ -570,7 +570,8 @@ const BSBilling7Payment = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2086,7 +2087,8 @@ const BSBilling7Payment = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From 56634645371abc636f681ad1b8d0f6d37daa4ab6 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:17:57 +0530 Subject: [PATCH 02/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable6/BST6Payment.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable6/BST6Payment.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable6/BST6Payment.jsx index 7d29254..9a02c94 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable6/BST6Payment.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable6/BST6Payment.jsx @@ -551,7 +551,8 @@ const BST6Payment = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2118,7 +2119,8 @@ const BST6Payment = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From 1eaebabb04cdd242d75db049a88667d54209ac73 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:18:17 +0530 Subject: [PATCH 03/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable5/BSBillingTable5.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable5/BSBillingTable5.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable5/BSBillingTable5.jsx index a126a4f..c4ee9cb 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable5/BSBillingTable5.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable5/BSBillingTable5.jsx @@ -579,7 +579,8 @@ const BSBillingTable5 = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2077,7 +2078,8 @@ const BSBillingTable5 = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From d8b9b15b57eb2119b6eef2458587373ef07c6bac Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:18:39 +0530 Subject: [PATCH 04/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable4/BSBilling4Payment.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable4/BSBilling4Payment.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable4/BSBilling4Payment.jsx index cf0e76f..9cee205 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable4/BSBilling4Payment.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable4/BSBilling4Payment.jsx @@ -591,7 +591,8 @@ const BSBilling4Payment = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2062,7 +2063,8 @@ const BSBilling4Payment = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From 4db2916809b16e837b164d2cb5218147e88ad986 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:19:00 +0530 Subject: [PATCH 05/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable3/BSBillingTable3pay.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable3/BSBillingTable3pay.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable3/BSBillingTable3pay.jsx index 75d52dc..116745e 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable3/BSBillingTable3pay.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable3/BSBillingTable3pay.jsx @@ -534,7 +534,8 @@ const BSBillingTable3Pay = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), //sree + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2180,7 +2181,8 @@ const BSBillingTable3Pay = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, //sri + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From 9dd65d23be0d6cd0cdeb5b11a92a3afbdc7ffa36 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:19:29 +0530 Subject: [PATCH 06/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable2/BSBillingTable2.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable2/BSBillingTable2.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable2/BSBillingTable2.jsx index 6ab8ec1..f6d92d8 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable2/BSBillingTable2.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable2/BSBillingTable2.jsx @@ -539,7 +539,8 @@ const BSBillingTable2 = () => { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -2034,7 +2035,8 @@ const BSBillingTable2 = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From f5f2655b3b022bf5bfde67fe38fdea4e25a4a12f Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:19:48 +0530 Subject: [PATCH 07/46] in this component i have change total amt --- .../BSBillingTables/BSBillingTable1/BST1Payment.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable1/BST1Payment.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable1/BST1Payment.jsx index 21270cd..d7fba48 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable1/BST1Payment.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingTable1/BST1Payment.jsx @@ -505,7 +505,8 @@ export default function BST1Payment() { useEffect(() => { if (!preOrder) { const totalSum = OrderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -1994,7 +1995,8 @@ export default function BST1Payment() { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From 006c6dd1e16c0b3a56cf9158fb81bc652be6cba1 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:20:06 +0530 Subject: [PATCH 08/46] in this component i have change total amt --- .../BSBillingTables/StandardTable/StandardTablePayment.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/StandardTable/StandardTablePayment.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/StandardTable/StandardTablePayment.jsx index 8af94a4..3878da4 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/StandardTable/StandardTablePayment.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/StandardTable/StandardTablePayment.jsx @@ -841,7 +841,8 @@ const StandardTablePayment = () => { if (!preOrder) { const totalSum = orderCardDetail?.reduce( - (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + // (acc, card) => acc + parseFloat(card.OrderRate * card.OrderQty || 0), + (acc, card) => acc + parseFloat(card.TotalAmt || 0), 0 ); @@ -1417,7 +1418,8 @@ const StandardTablePayment = () => { Type: a.Type, OrderQty: a.OrderQty, OrderRate: a.OrderRate, - TotalAmt: a.OrderQty * a.OrderRate, + // TotalAmt: a.OrderQty * a.OrderRate, + TotalAmt: a.TotalAmt, TaxAmt: a.TaxAmt, RefundQty: 0, InwardDtlId: a.InwardDtlId, From da669b3f44079bd786d898f9b17e675b77bcbc01 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:20:22 +0530 Subject: [PATCH 09/46] in this component i have change total amt --- .../BSBillingEditQuantity.jsx | 346 +++--------------- 1 file changed, 57 insertions(+), 289 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.jsx index ddefcd5..073cbf6 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.jsx @@ -40,6 +40,7 @@ import { } from '../../../../../Features/Offer/Offernew/BookingOffernew.js'; import { validateOffers } from '../../BSItemCards/ValidateOffer.jsx'; import { v4 as uuidv4 } from 'uuid'; +import WeightCalculatePrice from './WeightCalculatePrice.jsx'; const BSBillingEditQuantity = (props) => { const dispatch = useDispatch(); @@ -678,12 +679,12 @@ const BSBillingEditQuantity = (props) => { const handleEditQuantity = async ( editedProduct, editedProductIndex, - newPrice + newPrice, + overrideQty = null ) => { - // check itself is a offer product - - const editedQty = - props?.Productdata?.ScaleType !== 'weight' + const editedQty = overrideQty !== null + ? overrideQty + : props?.Productdata?.ScaleType !== 'weight' ? parseInt(Quantity) : props.Productdata.OrderQty; const addFirst = BillOrderPre === 'Y'; @@ -3096,9 +3097,10 @@ const BSBillingEditQuantity = (props) => { newPrice = 0, offerApply = false ) => { + const fixedQty = Number(qty.toFixed(3)); const updatedProduct = { ...editedProduct, - OrderQty: qty, + OrderQty: fixedQty, OrderRate: newPrice > 0 ? newPrice : editedProduct?.OrderRate, ...calculateTaxAmounts({ qty: qty, @@ -3236,289 +3238,6 @@ const BSBillingEditQuantity = (props) => { OfferValue: offerValue, }; }; - - // const AddProductQuantity = async () => { - // let NewPrice = NewPrice1 > 0 ? NewPrice1 : props.Productdata.OrderRate; - // await dispatch(changeHoldOrderDtl(false)); - // await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); - // const OtherOrderDatas = CartOrderDetails?.filter( - // (cartItem) => - // !( - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem.InwardDtlId === props?.Productdata?.InwardDtlId && - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName - // ) && !cartItem?.SalesId - // ); - - // const OtherOrderDatawithsales = CartOrderDetails?.filter( - // (cartItem) => cartItem?.SalesId - // ); - // const OtherorderDataforNormal = CartOrderDetails?.filter( - // (cartItem) => - // !( - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName && - // !cartItem?.SalesId - // ) - // ); - - // const isItemInCart = CartOrderDetails?.find( - // (cartItem) => - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName && - // !cartItem?.SalesId - // ); // check if the item is already in the cart - // // changing for one piece stock checking - // const isItemInCartfilter = CartOrderDetails?.filter( - // (cartItem) => - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // !( - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName - // ) && - // !cartItem?.SalesId - // ); // check if the item is already in the cart - // let OverallQuantity = CalculateOverallQty(isItemInCart, isItemInCartfilter); - // const BookingTypeProd = props?.Productdata?.BookingTypeName; - // const isItemInCartHold = CartOrderDetails?.find( - // (cartItem) => - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName - // ); // check if the item is already in the cart - // const isItemInCartHoldfilter = CartOrderDetails?.filter( - // (cartItem) => - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // !( - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName - // ) - // ); // check if the item is already in the cart - // const holddataproduct = ReorderProductData?.filter( - // (cartItem) => - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId - // ); - // let totalSelectedProductQty = holddataproduct?.reduce( - // (accumulator, card) => { - // return ( - // accumulator + - // parseInt( - // card?.StockAvailable === 'Y' - // ? props?.Productdata?.SinglePc === 'Y' - // ? card.SinglePc !== 'Y' - // ? card.OrderQty * card.NoOfPcs - // : card.OrderQty - // : 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 OverallQuantityhold = - // CalculateOverallQty(isItemInCartHold, isItemInCartHoldfilter) + - // totalSelectedProductQty; - // const OtherorderDataforNormalWithoutSalesId = CartOrderDetails?.filter( - // (cartItem) => - // !( - // cartItem?.ProdId === props?.Productdata?.ProdId && - // cartItem?.InwardDtlId === props?.Productdata?.InwardDtlId && - // cartItem?.OrderRate === props?.Productdata?.OrderRate && - // cartItem?.BookingTypeName === props?.Productdata?.BookingTypeName - // ) - // ); - - // if (parseInt(Quantity) === 0 || Quantity === '') { - // setMessageType('error'); - // setMessageData('Please enter valid quantity'); - // setQuantity(''); - // } - // else { - // if (isItemInCart && BookingTypeProd != 'Dine In' && OrderType != 'Hold') { - // if (isItemInCart?.StockAvailable === 'Y') { - // let Condition = OverallQuantity >= Quantity; - // if (Condition) { - // const UpdatedCartItem = await createUpdatedCartItem( - // isItemInCart, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherorderDataforNormal - // ); - // await dispatch(changeOrderCardDetails(Cartdata)); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } else { - // setMessageType('error'); - // setMessageData('Stock Not Available'); - // setQuantity(''); - // } - // } else { - // if ( - // isItemInCart && - // BookingTypeProd != 'Dine In' && - // OrderType != 'Hold' - // ) { - // const UpdatedCartItem = createUpdatedCartItem( - // isItemInCart, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherorderDataforNormal - // ); - // await dispatch(changeOrderCardDetails(Cartdata)); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - // } - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } - // } - // else if (isItemInCartHold && OrderType === 'Hold') { - // if (isItemInCartHold?.StockAvailable === 'Y') { - // let Condition = OverallQuantityhold >= Quantity; - // if (Condition) { - // const UpdatedCartItem = createUpdatedCartItem( - // isItemInCartHold, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherorderDataforNormalWithoutSalesId - // ); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - // await dispatch(changeOrderCardDetails(Cartdata)); - - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } else { - // setMessageType('error'); - // setMessageData('Stock Not Available'); - // setQuantity(''); - // } - // } else { - // if (isItemInCartHold && OrderType === 'Hold') { - // const UpdatedCartItem = createUpdatedCartItem( - // isItemInCartHold, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherorderDataforNormalWithoutSalesId - // ); - // await dispatch(changeOrderCardDetails(Cartdata)); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - // } - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } - // } - // else if ( - // isItemInCart && - // BookingTypeProd === 'Dine In' && - // OrderType != 'Hold' - // ) { - // if (isItemInCart?.StockAvailable === 'Y') { - // let Condition = OverallQuantity >= Quantity; - // if (Condition) { - // const UpdatedCartItem = createUpdatedCartItem( - // isItemInCart, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherOrderDatas - // ); - // await dispatch( - // changeOrderCardDetails([...OtherOrderDatawithsales, ...Cartdata]) - // ); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } else { - // setMessageType('error'); - // setMessageData('Stock Not Available'); - // setQuantity(''); - // } - // } - // else { - // if ( - // isItemInCart && - // BookingTypeProd === 'Dine In' && - // OrderType != 'Hold' - // ) { - // const UpdatedCartItem = createUpdatedCartItem( - // isItemInCart, - // Quantity, - // NewPrice - // ); - // const Cartdata = MergecardItem( - // UpdatedCartItem, - // BillOrderPre, - // OtherorderDataforNormal - // ); - // await dispatch(changeOrderCardDetails(Cartdata)); - // if (OfferCheckedInSetup && preferenceOffer) { - // await applyOffer(Cartdata); - // } else { - // dispatch(changeOrderCardDetails(Cartdata)); - // } - // } - // props.handleEditQuantityCancel(); - // setClearQuantity(false); - // } - // } - // } - // }; const CloseModal = () => { props.handleEditQuantityCancel(); setClearQuantity(false); @@ -3706,6 +3425,33 @@ const BSBillingEditQuantity = (props) => { setPackageDtl(data || []); }; + const handleWeightCalculation = async (data) => { + const { price, quantity } = data; + setQuantity(quantity); + setEditedPrice(price); + await handleWeightSubmit(quantity, price); + }; + + const handleWeightSubmit = async (qty, price) => { + await dispatch(changeHoldOrderDtl(false)); + await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); + let localId = props.Index; + let editedProductIndex = CartOrderDetails?.findIndex( + (e) => e?.localId == localId + ); + const editedProduct = { + ...CartOrderDetails[editedProductIndex], + OrderQty: qty + }; + + await handleEditQuantity(editedProduct, editedProductIndex, editedProduct.OrderRate, qty); + props.handleEditQuantityCancel(); + setClearQuantity(false); + }; + const isKg = + props?.Productdata?.Size == 1 && + ["KG", "KGS"].includes(props?.Productdata?.UomName?.toUpperCase()); + return (
{ > Packing + + {isKg && ()} +
{RadioBtnSelection == 'Quantity' && ( @@ -4007,6 +3766,15 @@ const BSBillingEditQuantity = (props) => { /> )} + {RadioBtnSelection == 'AddWeight' && ( + <> + + + )}
{((RadioBtnSelection == 'Price' && disableSubmitButton) || RadioBtnSelection == 'Quantity') && ( From 971affbf924d167f348881bf3337b14ffec6bf35 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:21:53 +0530 Subject: [PATCH 10/46] create new component amt and qnt calculation --- .../WeightCalculatePrice.jsx | 3801 +++++++++++++++++ 1 file changed, 3801 insertions(+) create mode 100644 src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx new file mode 100644 index 0000000..f4b35e8 --- /dev/null +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx @@ -0,0 +1,3801 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { shallowEqual, useDispatch, useSelector } from 'react-redux'; +import { DefaultModal } from '../../../../../Components/Modal/DefaultModal'; +import FormHeader from '../../../../PageComponents/FormHeader.jsx'; +import { Form } from 'antd'; +import { + GlobalOrderCardDetails, + changeOrderCardDetails, + changeHoldOrderDtl, + changePreviousOrderLength, + GlobalOrderType, + GlobalReorderProductDetails, + PreferenceData, + getConfigType, +} from '../../../../../Features/BookingScreen/BookingData/BookingData'; +import { ArrowRightOutlined } from '@ant-design/icons'; +import { Messages } from '../../../../../Components/Notifications/Messages'; +import '../../../../../Styles/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.scss'; +import { settingDataSelector } from '../../../../../Features/PreferenceMaster/PreferenceMaster.js'; +import { RadioGrpButton } from '../../../../../Components/Forms/RadioGroup.jsx'; +import Buttons from '../../../../../Components/Forms/Buttons.jsx'; +import { InputField } from '../../../../../Components/Forms/InputField.jsx'; +import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx'; +import { + getTemplateData, + StoredSessionData, +} from '../../../../../Features/ThemeChange/ThemeChange.js'; +import { validateSafeInput } from '../../../../../Services/Others.js'; +import { GlobalEmpAccessDetail } from '../../../../../Features/AppPage/CenterPage.js'; +import Packing from './BSPacking.jsx'; +// import { ApplicationPreferences } from '../../../../../Features/BrachLogin/BranchLogin.js'; +import { + ChangeFullFreeProductList, + changeFullOfferAppliedProducts, + ChangeOfferAppliedProducts, + changeOfferAppliedProductsForLoyalty, + GlobalFreeProdList, + GlobalOfferAppliedProducts, + RemoveOfferAppliedProduct, +} from '../../../../../Features/Offer/Offernew/BookingOffernew.js'; +import { validateOffers } from '../../BSItemCards/ValidateOffer.jsx'; +import { v4 as uuidv4 } from 'uuid'; +import WeightCalculatePrice from './WeightCalculatePrice.jsx'; + +const BSBillingEditQuantity = (props) => { + console.log(props?.Productdata.UomName, 'hfghfvbufvbfdviv', props?.Productdata.Size); + + const dispatch = useDispatch(); + const formRef = useRef(null); + const quantityInputRef = useRef(null); + const priceChangeInputRef = useRef(null); + const reductionInputRef = useRef(null); + + const { setIndex = () => { } } = props; + + + const [disableSubmitButton, setDisableSubmitButton] = useState(false); + const SessionData = useSelector(StoredSessionData); + // const AppId = SessionData?.AppId; + // const CompId = SessionData?.CompId; + // const BranchId = SessionData?.BranchId; + const UserType = SessionData?.UserType; + const applyOffer = useApplyOfferto_CardDetail(); + const preferenceDatas = useSelector(PreferenceData); + const EmpAccessDetail = useSelector(GlobalEmpAccessDetail); + const OverAllproductBasedOfferDatas = useSelector( + (state) => state?.BookingOFferNew?.OverAllProductBasedProducts, + shallowEqual + ); + const preferenceOffer = + preferenceDatas?.[0]?.['SettingDtlDetails']?.find( + (item) => item.SettingIdName === 'Offer' + )?.SettingValue === 'Y'; + const preferenceshortcutkey = preferenceDatas?.[0]?.[ + 'SettingDtlDetails' + ]?.some( + (item) => + item.SettingIdName.toLowerCase() === 'shortcutkeys' && + item.SettingValue === 'Y' + ); + console.log(preferenceshortcutkey, 'preferenceshortcutkey'); + const [PriceChangeaccess, setPriceChangeaccess] = useState(true); + + const [ConfigDataList, setConfigDataList] = useState([]); + const [messageType, setMessageType] = useState(null); + const [messageData, setMessageData] = useState(null); + const [EditOpen, setEditOpen] = useState(props?.BSBillingEditQuantity); + const [ItemData, setItemData] = useState(props?.Productdata); + const [Quantity, setQuantity] = useState( + props?.Productdata?.ScaleType !== 'weight' + ? parseInt(props.Productdata.OrderQty) + : props.Productdata.OrderQty + ); + const ReorderProductData = useSelector(GlobalReorderProductDetails); + const templateData = useSelector(getTemplateData); + const OfferCheckedInSetup = + templateData?.BookingNavbar?.[1].some( + (item) => item?.OptionName == 'Offer' + ) || + templateData?.BookingCombo1?.[1]?.some( + (item) => item?.OptionName == 'Offer' + ); + const [ClearQuantity, setClearQuantity] = useState(false); + const CartOrderDetails = useSelector(GlobalOrderCardDetails); + const SettingDataSelector = useSelector(PreferenceData); + const OrderType = useSelector(GlobalOrderType); + const [BillOrderPre, setBillOrderPre] = useState(null); + const [RadioBtnSelection, setRadioBtnSelection] = useState( + props?.shortKeyMethod == 'price' + ? 'Price' + : ItemData?.ScaleType !== 'weight' + ? 'Quantity' + : PriceChangeaccess + ? 'Price' + : 'Parcel' + ); + const [PercentageSelection, setPercentageSelection] = useState('Fixed'); + const [RadioDetails, setRadioDetails] = useState(false); + const [editedPrice, setEditedPrice] = useState(0); + const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find( + (setting) => + setting?.SettingIdName?.toLowerCase() === 'decimal' && + setting?.SettingValue === 'Y' + ); + const [PackageDtl, setPackageDtl] = useState([]); + // const appPreferences = useSelector(ApplicationPreferences); + // 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 OfferAppliedProducts = useSelector( + GlobalOfferAppliedProducts, + shallowEqual + ); + const FreeProdList = useSelector(GlobalFreeProdList); + console.log(CartOrderDetails, 'CartOrderDetails'); + + const TakAwayId = ConfigDataList?.find( + (a) => a?.ConfigName === 'TakeAway' + )?.ConfigId; + + const DineinId = ConfigDataList?.find( + (a) => a?.ConfigName === 'Dine In' + )?.ConfigId; + + const hasOffer = preferenceOffer && OfferCheckedInSetup; + + useEffect(() => { + if (ConfigDataList?.length === 0) { + getBookingTypeId(); + } + }, []); + + useEffect( + () => { + setEditOpen(props.BSBillingEditQuantity); + setItemData(props.Productdata); + setQuantity( + props?.Productdata?.ScaleType !== 'weight' + ? parseInt(props.Productdata.OrderQty) + : props.Productdata.OrderQty + ); + }, + [props.BSBillingEditQuantity], + [props.Productdata] + ); + + useEffect(() => { + if (preferenceshortcutkey) { + if (props.BSBillingEditQuantity && RadioBtnSelection === 'Quantity') { + setTimeout(() => { + quantityInputRef.current?.focus(); + }, 100); + } + + if (props.BSBillingEditQuantity && RadioBtnSelection === 'Price') { + setTimeout(() => { + if (RadioDetails) { + const inputElement = + reductionInputRef.current?.querySelector('input'); + inputElement?.focus(); + } else { + const inputElement = + priceChangeInputRef.current?.querySelector('input'); + inputElement?.focus(); + } + }, 100); + } + } + }, [ + RadioBtnSelection, + props.BSBillingEditQuantity, + RadioDetails, + preferenceshortcutkey, + ]); + + useEffect(() => { + const handleKeyDown = (event) => { + if (preferenceshortcutkey && event.shiftKey && event.key === 'E') { + event.preventDefault(); + if (PriceChangeaccess && props.Productdata?.Offer <= 0) { + onRadioBtnChange('Price'); + } + } + }; + + if (EditOpen) { + document.addEventListener('keydown', handleKeyDown); + } + + return () => { + document.removeEventListener('keydown', handleKeyDown); + }; + }, [ + EditOpen, + preferenceshortcutkey, + PriceChangeaccess, + props.Productdata?.Offer, + ]); + + useEffect(() => { + const BillOrder = SettingDataSelector?.[0]?.SettingDtlDetails?.find( + (item) => item.SettingIdName === 'BillItemsOrder' + ); + setBillOrderPre(BillOrder?.SettingValue); + }, []); + + useEffect(() => { + if (UserType == 'Employee') { + const Pricechange = EmpAccessDetail?.filter( + (item) => item.ConfigName === 'Sales Discount' + ); + + setPriceChangeaccess(Pricechange?.[0]?.AddAccess != 'Y' ? false : true); + } + }, [EmpAccessDetail]); + + useEffect(() => { + if (PackageDtl.length > 0) { + AddProductQuantity(); + } + }, [PackageDtl]); + + const getBookingTypeId = async () => { + let tempconfigdata = await dispatch( + getConfigType({ TypeName: 'Booking Type' }) + ).unwrap(); + + if (tempconfigdata?.data?.statusCode == 1) { + setConfigDataList(tempconfigdata?.data?.data); + } + }; + + function safeRound(amountStr) { + if (amountStr == null) return allowDecimal ? '0.00' : '0'; + + const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ''); + const num = Number(cleaned); + + if (isNaN(num)) return allowDecimal ? '0.00' : '0'; + + return allowDecimal ? num.toFixed(2) : Math.round(num).toString(); + } + const AddQuantity = (value) => { + if (ClearQuantity === false) { + setQuantity(value); + setClearQuantity(true); + } else { + setQuantity(Quantity.toString() + value.toString()); + if (Quantity?.length > 10) { + setMessageType('error'); + setMessageData('Quantity is to long'); + setQuantity(''); + } + } + }; + const Removevalue = () => { + let tempremovedata = Quantity.toString().substring(0, Quantity?.length - 1); + setQuantity(tempremovedata); + }; + const openRadioDetails = () => { + setDisableSubmitButton(false); + setRadioDetails(!RadioDetails); + setEditedPrice(0); + }; + + // const AddQuantityonly = () => { + // setMessageType('success'); + // setMessageData('Quantity Added'); + // }; + + const createUpdatedCartItem = (cartItem, quantity, newPrice) => { + const qty = parseInt(quantity); + const rate = parseFloat(newPrice); + const offerType = cartItem?.OfferType; + const offerPrice = cartItem?.OfferPrice || 0; + const taxPercent = cartItem?.TaxPercentage || 0; + + const baseAmount = qty * rate; + + const offerValue = + offerType === 'F' ? qty * offerPrice : (baseAmount * offerPrice) / 100; + + const totalAmt = + cartItem?.OfferPrice > 0 ? baseAmount - offerValue : baseAmount; + + const taxAmt = (baseAmount * taxPercent) / (100 + taxPercent); + const withoutTax = baseAmount - taxAmt; + + return { + ...cartItem, + OrderQty: qty, + OrderRate: rate, + TotalAmt: totalAmt, + OfferValue: offerValue, + TaxAmt: taxAmt.toFixed(2), + WithoutTaxRate: withoutTax.toFixed(2), + PackageDtl: PackageDtl, + }; + }; + + const calculateOverAllQty = (item, filterItems) => { + if (!item) return 0; + + const totalUsedQty = + filterItems?.reduce((acc, card) => { + if (card?.StockAvailable !== 'Y') return acc; + + const isSinglePcItem = item?.SinglePc === 'Y'; + const isSinglePcCard = card?.SinglePc === 'Y'; + + let qty = 0; + if (isSinglePcItem) { + qty = isSinglePcCard ? card.OrderQty : card.OrderQty * card.NoOfPcs; + } else { + if (isSinglePcCard) { + const remainder = card?.OverAllPcs % card?.NoOfPcs; + qty = + remainder >= card?.OrderQty + ? 0 + : Math.ceil(card?.OrderQty / card?.NoOfPcs); + } else { + qty = card.OrderQty; + } + } + return acc + qty; + }, 0) || 0; + + const availableQty = + item?.SinglePc === 'Y' ? item?.OverAllPcs : item?.BalanceQty; + return availableQty - totalUsedQty; + }; + + const MergecardItem = (cartItem, BillOrderPre, OtherorderDataforNormal) => { + const updatedCart = {}; + let updatedItemKey = null; + + // Add existing items to the map + OtherorderDataforNormal?.forEach((item) => { + const key = `${item?.ProdId}-${item?.InwardDtlId}-${item?.BookingTypeName}-${item?.OrderRate}`; + if (!updatedCart[key]) { + updatedCart[key] = { ...item }; + } + }); + + // Merge or add new item + const key = `${cartItem?.ProdId}-${cartItem?.InwardDtlId}-${cartItem?.BookingTypeName}-${cartItem?.OrderRate}`; + if (updatedCart[key]) { + updatedCart[key].OrderQty += cartItem?.OrderQty; + } else { + updatedCart[key] = { ...cartItem }; + } + updatedItemKey = key; + + // Recalculate total amounts + Object.values(updatedCart).forEach((item) => { + const orderQty = item.OrderQty; + const orderRate = item.OrderRate; + const taxPercentage = item?.TaxPercentage || 0; + item.TotalAmt = orderQty * orderRate; + item.TaxAmt = ( + (orderQty * orderRate * taxPercentage) / + (100 + taxPercentage) + ).toFixed(2); + item.WithoutTaxRate = orderQty * orderRate - parseFloat(item.TaxAmt); + }); + + let updatedArray = Object.values(updatedCart); + + // Ensure updated item appears first + if (BillOrderPre === 'Y' && updatedItemKey) { + const updatedItem = updatedCart[updatedItemKey]; + updatedArray = [ + updatedItem, + ...updatedArray?.filter((item) => item !== updatedItem), + ]; + } + + return updatedArray; + }; + + const AddProductQuantity = async () => { + let newPrice = editedPrice > 0 ? editedPrice : props.Productdata.OrderRate; + await dispatch(changeHoldOrderDtl(false)); + await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); + + if ( + (parseInt(Quantity) === 0 || Quantity === '') && + props?.Productdata?.ScaleType !== 'weight' + ) { + setMessageType('error'); + setMessageData('Please enter valid quantity'); + setQuantity(''); + } else { + let localId = props.Index; + const editedQty = + props?.Productdata?.ScaleType !== 'weight' + ? parseInt(Quantity) + : props.Productdata.OrderQty; + let editedProductIndex = CartOrderDetails?.findIndex( + (e) => e?.localId == localId + ); + const editedProduct = CartOrderDetails[editedProductIndex]; + const productBookingType = editedProduct?.BookingTypeName; + const isItemInCart = CartOrderDetails?.find( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + !cartItem?.SalesId + ); + // changing for one piece stock checking + const isItemInCartfilter = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate !== editedProduct?.OrderRate && + !cartItem?.SalesId + ); + + const isItemInCartHold = CartOrderDetails?.find( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ); // check if the item is already in the cart + const isItemInCartHoldfilter = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + !( + (cartItem?.OrderRate === editedProduct?.OrderRate) + // && cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ) + ); + + if ( + (isItemInCart && + productBookingType !== 'Dine In' && + OrderType != 'Hold') || + (isItemInCart && + productBookingType === 'Dine In' && + OrderType != 'Hold') + ) { + // let onePcsQtyOther = 0; + // if (editedProduct?.SinglePc === 'Y') { + // // check if there is same rate product in other booking type + // const sameRateProductInOtherBookingType = CartOrderDetails?.find( + // (cartItem) => + // cartItem?.ProdId === editedProduct?.ProdId && + // cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + // cartItem?.OrderRate === editedProduct?.OrderRate && + // cartItem?.BookingTypeName !== editedProduct?.BookingTypeName && + // !cartItem?.SalesId + // ) + // if (sameRateProductInOtherBookingType?.StockAvailable === 'Y') { + // onePcsQtyOther = sameRateProductInOtherBookingType?.OrderQty; + // } + // } + const overAllQuantity = calculateOverAllQty( + isItemInCart, + isItemInCartfilter + ); + let totalUsedQty = 0; + const sameProductInOtherBookingType = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName && + !cartItem?.SalesId + ); + if (editedProduct?.Offer > 0) { + // check same product available in paid product + const sameProductAsPaidInSameBookingType = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + !cartItem?.SalesId && + !cartItem?.OfferMode && + cartItem?.Offer === 0 + ); + + if (sameProductAsPaidInSameBookingType?.length > 0) { + const stockAvailable = sameProductAsPaidInSameBookingType?.some( + (item) => item?.StockAvailable === 'Y' + ); + if (stockAvailable) { + totalUsedQty = sameProductAsPaidInSameBookingType?.reduce( + (acc, item) => { + if (item?.StockAvailable === 'Y') { + return acc + parseInt(item?.OrderQty); + } + return acc; + }, + 0 + ); + } + } + } else if (!editedProduct?.Offer) { + const sameProductAsFree = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + !cartItem?.SalesId && + cartItem?.Offer > 0 && + cartItem?.OfferMode + ); + + if (sameProductAsFree?.length > 0) { + const stockAvailable = sameProductAsFree?.some( + (item) => item?.StockAvailable === 'Y' + ); + if (stockAvailable) { + totalUsedQty = sameProductAsFree?.reduce((acc, item) => { + if (item?.StockAvailable === 'Y') { + return acc + parseInt(item?.OrderQty); + } + return acc; + }, 0); + } + } + } + + if (sameProductInOtherBookingType?.length > 0) { + const stockAvailable = sameProductInOtherBookingType?.some( + (item) => item?.StockAvailable === 'Y' + ); + if (stockAvailable) { + totalUsedQty += sameProductInOtherBookingType?.reduce( + (acc, item) => { + if (item?.StockAvailable === 'Y') { + return acc + parseInt(item?.OrderQty); + } + return acc; + }, + 0 + ); + } + } + + if ( + overAllQuantity < editedQty + (totalUsedQty || 0) && + isItemInCart?.StockAvailable === 'Y' + ) { + setMessageType('error'); + setMessageData('Stock Not Available'); + return; + } + } else if (isItemInCartHold && OrderType === 'Hold') { + const holddataproduct = ReorderProductData?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId + ); + + let totalSelectedProductQty = holddataproduct?.reduce( + (accumulator, card) => { + return ( + accumulator + + parseInt( + card?.StockAvailable === 'Y' + ? editedProduct?.SinglePc === 'Y' + ? card.SinglePc !== 'Y' + ? card.OrderQty * card.NoOfPcs + : card.OrderQty + : 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 totalUsedQty = 0; + + const sameProductInOtherBookingType = CartOrderDetails?.filter( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + + if (editedProduct?.Offer > 0) { + // check same product available in paid product + const sameProductAsPaid = CartOrderDetails?.find( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + !cartItem?.OfferMode && + cartItem?.Offer === 0 + ); + + if (sameProductAsPaid?.StockAvailable === 'Y') { + totalUsedQty = sameProductAsPaid?.OrderQty; + } + } else if (!editedProduct?.Offer) { + const sameProductAsFree = CartOrderDetails?.find( + (cartItem) => + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + cartItem?.Offer > 0 && + cartItem?.OfferMode + ); + if (sameProductAsFree?.StockAvailable === 'Y') { + totalUsedQty = sameProductAsFree?.OrderQty; + } + } + + if (sameProductInOtherBookingType?.length > 0) { + const stockAvailable = sameProductInOtherBookingType?.some( + (item) => item?.StockAvailable === 'Y' + ); + if (stockAvailable) { + totalUsedQty += sameProductInOtherBookingType?.reduce( + (acc, item) => { + if (item?.StockAvailable === 'Y') { + return acc + parseInt(item?.OrderQty); + } + return acc; + }, + 0 + ); + } + } + + let overAllQuantityHold = + calculateOverAllQty(isItemInCartHold, isItemInCartHoldfilter) + + totalSelectedProductQty; + if ( + isItemInCartHold?.StockAvailable === 'Y' && + overAllQuantityHold < editedQty + (totalUsedQty || 0) + ) { + setMessageType('error'); + setMessageData('Stock Not Available'); + return; + } + } + await handleEditQuantity(editedProduct, editedProductIndex, newPrice); + props.handleEditQuantityCancel(); + setClearQuantity(false); + } + setIndex(null); + }; + + const handleEditQuantity = async ( + editedProduct, + editedProductIndex, + newPrice, + overrideQty = null + ) => { + const editedQty = overrideQty !== null + ? overrideQty + : props?.Productdata?.ScaleType !== 'weight' + ? parseInt(Quantity) + : props.Productdata.OrderQty; + const addFirst = BillOrderPre === 'Y'; + const isExistsInFreeProdList = FreeProdList?.find( + (product) => + product?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) && + editedProduct?.OfferMessage?.[0]?.OfferId === product?.OfferId && + editedProduct?.OfferMode === product?.OfferMode + ); + console.log(FreeProdList, 'FreeProdList'); + + if ( + isExistsInFreeProdList && + editedProduct?.Offer > 0 && + hasOffer && + editedProduct?.SinglePc !== 'Y' + ) { + const freeProductInOtherBooking = CartOrderDetails?.find((cartItem) => { + return ( + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OfferMessage?.[0]?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + cartItem?.OfferMode === editedProduct?.OfferMode && + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + }); + + const finalOrderQty = + (freeProductInOtherBooking?.OrderQty || 0) + editedQty; + + if (isExistsInFreeProdList?.RemainingQty === 0) { + // need to split the free product and paid product + + if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) { + const paidQty = + finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty; + const isAlreadyExistsInCart = CartOrderDetails?.findIndex( + (cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + !cartItem?.OfferMode && + cartItem?.Offer === 0 && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + cartItem?.OrderRate === editedProduct?.OrderRate + ); + } + ); + + let updatedCart = [...CartOrderDetails]; + + if (isAlreadyExistsInCart !== -1) { + // update the existing paid product in cart + const existingItem = updatedCart[isAlreadyExistsInCart]; + const updatedItem = { + ...existingItem, + OrderQty: existingItem?.OrderQty + paidQty, + ...calculateTaxAmounts({ + qty: existingItem?.OrderQty + paidQty, + rate: existingItem?.OrderRate, + taxPercentage: existingItem?.TaxPercentage, + }), + }; + updatedCart?.splice(isAlreadyExistsInCart, 1); + updatedCart = addFirst + ? [updatedItem, ...updatedCart] + : [...updatedCart, updatedItem]; + } else { + // add new paid product in cart + const paidProduct = { + localId: uuidv4(), + ...editedProduct, + OrderQty: paidQty, + Offer: 0, + OfferMode: null, + OfferMessage: null, + OfferType: null, + ...calculateTaxAmounts({ + qty: paidQty, + rate: editedProduct.OrderRate, + taxPercentage: editedProduct.TaxPercentage, + }), + }; + updatedCart = addFirst + ? [paidProduct, ...updatedCart] + : [...updatedCart, paidProduct]; + } + dispatch(changeOrderCardDetails(updatedCart)); + } else { + // Check if there is any same product but No offer applied in OrderCardDtls in same BookingType + // In Same BookingType Have Enough Free Qty Just only Update Qty in Same Booking Type OtherWise need to update in Other Booking Type Qty also if exists in Other Booking Type + const isAlreadyExistsInCart = CartOrderDetails?.find((cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + !cartItem?.OfferMode && + cartItem?.Offer === 0 + ); + }); + + const freeQtyNeeded = + isExistsInFreeProdList?.OverAllFreeQty - finalOrderQty; + const paidQtySame = isAlreadyExistsInCart?.OrderQty || 0; + + if (paidQtySame >= freeQtyNeeded) { + const remainingPaidQty = (paidQtySame || 0) - freeQtyNeeded; + if (remainingPaidQty === 0) { + // Just need to update the Free Qty and Remove the Paid Product from Cart + const updatedCart = CartOrderDetails?.filter( + (cartItem) => cartItem !== isAlreadyExistsInCart + ); + dispatch( + changeOrderCardDetails( + updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + PackageDtl: PackageDtl, + }; + } + return cartItem; + }) + ) + ); + } else { + // need to update the Paid Qty to Remaining Qty + const updatedCart = CartOrderDetails?.map((cartItem) => { + if (cartItem === isAlreadyExistsInCart) { + return { + ...cartItem, + OrderQty: remainingPaidQty, + ...calculateTaxAmounts({ + qty: remainingPaidQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + dispatch(changeOrderCardDetails(updatedCart)); + } + } else { + // check if the same product exists in other booking type as paid product + // need to calculate how much qty going to be updated in other booking type and same booking type + + const diffBookingTypeProduct = CartOrderDetails?.find( + (cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName !== + editedProduct?.BookingTypeName && + !cartItem?.OfferMode && + cartItem?.Offer === 0 + ); + } + ); + + const diffBookingTypeFreeProduct = CartOrderDetails?.find( + (cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.OrderRate === editedProduct?.OrderRate && + cartItem?.BookingTypeName !== + editedProduct?.BookingTypeName && + cartItem?.OfferMode === editedProduct?.OfferMode && + cartItem?.Offer > 0 + ); + } + ); + + const paidQtyOther = diffBookingTypeProduct?.OrderQty || 0; + const sameBookTypeUpdateQty = freeQtyNeeded - paidQtySame; + const otherBookTypePaidUpdateQty = + paidQtyOther - sameBookTypeUpdateQty; + const totalPaidQty = paidQtySame + paidQtyOther; + + if (paidQtySame || paidQtyOther) { + let updatedCart = [...CartOrderDetails]; + + // Remove paid product in same booking type if needed + if (paidQtySame) { + updatedCart = updatedCart.filter( + (cartItem) => cartItem !== isAlreadyExistsInCart + ); + updatedCart = updatedCart.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty + paidQtySame, + ...calculateTaxAmounts({ + qty: editedQty + paidQtySame, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + ...(cartItem?.Offer > 0 && { + Offer: (editedQty + paidQtySame) * cartItem.OrderRate, + }), + }; + } + return cartItem; + }); + } + + // Remove/update paid product in other booking type if needed + if (paidQtyOther) { + if (otherBookTypePaidUpdateQty <= 0) { + // Remove paid product from other booking type + updatedCart = updatedCart.filter( + (cartItem) => cartItem !== diffBookingTypeProduct + ); + updatedCart = updatedCart.map((cartItem) => { + if (cartItem === diffBookingTypeFreeProduct) { + return { + ...cartItem, + OrderQty: paidQtyOther + cartItem?.OrderQty, + ...calculateTaxAmounts({ + qty: paidQtyOther + cartItem?.OrderQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: + (paidQtyOther + cartItem?.OrderQty) * + cartItem?.OrderRate, + }; + } else if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: editedQty * cartItem?.OrderRate, + }; + } + return cartItem; + }); + } else if (otherBookTypePaidUpdateQty > 0) { + updatedCart = updatedCart.map((cartItem) => { + if (cartItem === diffBookingTypeFreeProduct) { + return { + ...cartItem, + OrderQty: cartItem?.OrderQty + sameBookTypeUpdateQty, + ...calculateTaxAmounts({ + qty: cartItem?.OrderQty + sameBookTypeUpdateQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: + (cartItem?.OrderQty + sameBookTypeUpdateQty) * + cartItem?.OrderRate, + }; + } else if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: editedQty * cartItem?.OrderRate, + }; + } else if (cartItem === diffBookingTypeProduct) { + return { + ...cartItem, + OrderQty: otherBookTypePaidUpdateQty, + ...calculateTaxAmounts({ + qty: otherBookTypePaidUpdateQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + }; + } + return cartItem; + }); + } + } + + // Only one dispatch after all updates + dispatch(changeOrderCardDetails(updatedCart)); + + if (totalPaidQty < freeQtyNeeded) { + const additionalFreeQtyNeeded = freeQtyNeeded - totalPaidQty; + + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.FreeProdId === editedProduct?.ProdId && + product?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) && + product?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + product?.OfferMode === editedProduct?.OfferMode + ) { + const freeQty = + product?.OverAllFreeQty - additionalFreeQtyNeeded; + return { + ...product, + FreeQty: freeQty, + RemainingQty: additionalFreeQtyNeeded, + discount: freeQty * editedProduct?.OrderRate, + }; + } + return product; + }); + + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + offerProduct?.OfferMode === editedProduct?.OfferMode; + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + const freeQty = + matchingFreeProduct?.FreeQty - additionalFreeQtyNeeded; + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: freeQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: freeQty, + ActualOfferAmount: freeQty * editedProduct?.OrderRate, + OfferAmount: freeQty * editedProduct?.OrderRate, + OfferValue: freeQty * editedProduct?.OrderRate, + FreeProductsList: updatedFreeProductsList, + UsedCount: freeQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } + } else { + // no paid product exists in other booking type and same booking type + // Just need to update the Free Qty in FreeProductList + // Need to update the Qty in Edited Product + // Need to update the FreeQty in OfferAppliedProducts + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice, + true + ); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.FreeProdId === editedProduct?.ProdId && + product?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) && + product?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + product?.OfferMode === editedProduct?.OfferMode + ) { + return { + ...product, + FreeQty: finalOrderQty, + RemainingQty: product?.OverAllFreeQty - finalOrderQty, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + offerProduct?.OfferMode === editedProduct?.OfferMode; + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: + finalOrderQty * editedProduct?.OrderRate, + OfferAmount: finalOrderQty * editedProduct?.OrderRate, + OfferValue: finalOrderQty * editedProduct?.OrderRate, + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } + } + } + } else if (isExistsInFreeProdList?.RemainingQty > 0) { + // perform normal edit qty operation + // console.log(editedProduct?.OrderQty, "editedProduct") + // await handleNormalEditQuantity(editedProduct, editedProductIndex); + + if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) { + // split paid and free product + const paidProdQty = + finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty; + const freeProdQty = editedQty - paidProdQty; + const isAlreadyExistsInCart = CartOrderDetails?.findIndex( + (cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + !cartItem?.OfferMode && + cartItem?.Offer === 0 && + cartItem?.BookingTypeName === editedProduct?.BookingTypeName && + cartItem?.OrderRate === editedProduct?.OrderRate + ); + } + ); + + let updatedCart = [...CartOrderDetails]; + + if (isAlreadyExistsInCart !== -1) { + // update the existing paid product in cart + updatedCart[isAlreadyExistsInCart] = { + ...updatedCart[isAlreadyExistsInCart], + OrderQty: + updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty, + ...calculateTaxAmounts({ + qty: updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty, + rate: updatedCart[isAlreadyExistsInCart]?.OrderRate, + taxPercentage: + updatedCart[isAlreadyExistsInCart]?.TaxPercentage, + }), + }; + } else { + // add new paid product in cart + const paidProduct = { + localId: uuidv4(), + ...editedProduct, + OrderQty: paidProdQty, + Offer: 0, + OfferMode: null, + OfferMessage: null, + OfferType: null, + ...calculateTaxAmounts({ + qty: paidProdQty, + rate: editedProduct?.OrderRate, + taxPercentage: editedProduct?.TaxPercentage, + }), + }; + updatedCart = [...updatedCart, paidProduct]; + } + + dispatch( + changeOrderCardDetails( + updatedCart?.map((prod) => { + if (prod === editedProduct) { + return { + ...prod, + OrderQty: freeProdQty, + ...calculateTaxAmounts({ + qty: freeProdQty, + rate: prod.OrderRate, + taxPercentage: prod.TaxPercentage, + }), + ...(prod?.Offer > 0 && { + Offer: freeProdQty * prod.OrderRate, + }), + }; + } + return prod; + }) + ) + ); + } else if (finalOrderQty === isExistsInFreeProdList?.OverAllFreeQty) { + // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice, + true + ); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.FreeProdId === editedProduct?.ProdId && + product?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) && + product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId && + product?.OfferMode === editedProduct?.OfferMode + ) { + return { + ...product, + FreeQty: finalOrderQty, + RemainingQty: 0, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + offerProduct?.OfferMode === editedProduct?.OfferMode; + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate, + OfferAmount: finalOrderQty * editedProduct?.OrderRate, + OfferValue: finalOrderQty * editedProduct?.OrderRate, + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts)); + } else if (finalOrderQty < isExistsInFreeProdList?.OverAllFreeQty) { + // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice, + true + ); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.FreeProdId === editedProduct?.ProdId && + product?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) && + product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId && + product?.OfferMode === editedProduct?.OfferMode + ) { + return { + ...product, + FreeQty: finalOrderQty, + RemainingQty: product?.OverAllFreeQty - finalOrderQty, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + editedProduct?.OfferMessage?.[0]?.OfferId && + offerProduct?.OfferMode === editedProduct?.OfferMode; + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === editedProduct?.InwardDtlId + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + editedProduct?.InwardDtlId + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate, + OfferAmount: finalOrderQty * editedProduct?.OrderRate, + OfferValue: finalOrderQty * editedProduct?.OrderRate, + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts)); + } + } + } else { + // check is there any free product applicable for the edited product + const isFreeProductApplicable = FreeProdList?.find((product) => { + return ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId + ); + }); + + const sameProductInOtherBooking = CartOrderDetails?.find((cartItem) => { + return ( + cartItem?.ProdId === editedProduct?.ProdId && + cartItem?.InwardDtlId === editedProduct?.InwardDtlId && + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + }); + + const finalOrderQty = + (sameProductInOtherBooking?.OrderQty || 0) + editedQty; + + if (isFreeProductApplicable && hasOffer) { + const applicableFreeProducts = + isFreeProductApplicable?.ProdVariantDetails; + + const freeProductVariants = applicableFreeProducts?.map((variant) => { + return { + ...variant, + FreeProdId: isFreeProductApplicable?.FreeProdId, + OfferId: isFreeProductApplicable?.OfferId, + OfferMode: isFreeProductApplicable?.OfferMode, + }; + }); + + if (isFreeProductApplicable?.OverAllFreeQty > finalOrderQty) { + if (isFreeProductApplicable?.FreeQty === 0) { + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice + ); + // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty) + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId + ) { + return { + ...product, + FreeQty: 0, + OverAllFreeQty: finalOrderQty, + RemainingQty: finalOrderQty, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + } else if (isFreeProductApplicable?.FreeQty <= finalOrderQty) { + // check if there is any applicable free product in cart + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice + ); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId + ) { + return { + ...product, + OverAllFreeQty: finalOrderQty, + RemainingQty: finalOrderQty - product?.FreeQty, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + } else if (isFreeProductApplicable?.FreeQty > finalOrderQty) { + // need to split free product and paid product + let remainingPaidQty = + isFreeProductApplicable?.FreeQty - finalOrderQty; + const applicableFreeInCart = CartOrderDetails?.filter( + (cartItem) => { + return ( + freeProductVariants?.some( + (variant) => + variant.FreeProdId === cartItem.ProdId && + variant?.StockDetails?.some( + (stock) => + stock.FreeInwardDtlId === cartItem.InwardDtlId + ) + ) && + cartItem?.Offer && + isFreeProductApplicable?.OfferId === + cartItem?.OfferMessage?.[0]?.OfferId + ); + } + ); + const applicableFreeInCartAsPaid = CartOrderDetails?.filter( + (cartItem) => { + return ( + freeProductVariants?.some( + (variant) => + variant.FreeProdId === cartItem.ProdId && + variant?.StockDetails?.some( + (stock) => + stock.FreeInwardDtlId === cartItem.InwardDtlId + ) + ) && !cartItem?.Offer + ); + } + ); + const sameBookingTypeProduct = applicableFreeInCart?.find( + (cartItem) => { + return ( + cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ); + } + ); + const otherBookingTypeProduct = applicableFreeInCart?.find( + (cartItem) => { + return ( + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + } + ); + const sameBookingTypeProductAsPaid = + applicableFreeInCartAsPaid?.find((cartItem) => { + return ( + cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ); + }); + const otherBookingTypeProductAsPaid = + applicableFreeInCartAsPaid?.find((cartItem) => { + return ( + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + }); + let updatedCart = [...CartOrderDetails]; + if (sameBookingTypeProduct) { + if (sameBookingTypeProductAsPaid) { + if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== sameBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProductAsPaid) { + const newItem = { + ...cartItem, + OrderQty: + cartItem.OrderQty + sameBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: 0, + }; + + delete newItem.OfferMode; + delete newItem.OfferMessage; + delete newItem.OfferType; + + return newItem; + } + return cartItem; + }); + } else if ( + sameBookingTypeProduct?.OrderQty > remainingPaidQty + ) { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty - remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty - remainingPaidQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem?.OrderQty - remainingPaidQty) * + cartItem?.OrderRate, + }; + } else if (cartItem === sameBookingTypeProductAsPaid) { + return { + ...cartItem, + OrderQty: cartItem?.OrderQty + remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem?.OrderQty + remainingPaidQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + }; + } + return cartItem; + }); + } + } else { + if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + const newPaidProd = { + ...cartItem, + Offer: 0, + }; + + delete newPaidProd.OfferMode; + delete newPaidProd.OfferMessage; + delete newPaidProd.OfferType; + return newPaidProd; + } + return cartItem; + }); + } else if ( + sameBookingTypeProduct?.OrderQty > remainingPaidQty + ) { + const newPaidProduct = { + ...sameBookingTypeProduct, + OrderQty: remainingPaidQty, + Offer: 0, + }; + delete newPaidProduct.OfferMode; + delete newPaidProduct.OfferMessage; + delete newPaidProduct.OfferType; + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty - remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem?.OrderQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: + (cartItem?.OrderQty - remainingPaidQty) * + cartItem?.OrderRate, + }; + } + return cartItem; + }); + updatedCart = [...updatedCart, newPaidProduct]; + } + } + remainingPaidQty = + remainingPaidQty - sameBookingTypeProduct?.OrderQty; + } + + if (otherBookingTypeProduct && remainingPaidQty > 0) { + if (otherBookingTypeProductAsPaid) { + if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== otherBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProductAsPaid) { + const newItem = { + ...cartItem, + OrderQty: + cartItem.OrderQty + otherBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: 0, + }; + + delete newItem.OfferMode; + delete newItem.OfferMessage; + delete newItem.OfferType; + + return newItem; + } + return cartItem; + }); + } else if ( + otherBookingTypeProduct?.OrderQty > remainingPaidQty + ) { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty - remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty - remainingPaidQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem?.OrderQty - remainingPaidQty) * + cartItem?.OrderRate, + }; + } else if (cartItem === otherBookingTypeProductAsPaid) { + return { + ...cartItem, + OrderQty: cartItem?.OrderQty + remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem?.OrderQty + remainingPaidQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + }; + } + return cartItem; + }); + } + } else { + if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + const newPaidProd = { + ...cartItem, + Offer: 0, + }; + delete newPaidProd.OfferMode; + delete newPaidProd.OfferMessage; + delete newPaidProd.OfferType; + return newPaidProd; + } + return cartItem; + }); + } else if ( + otherBookingTypeProduct?.OrderQty > remainingPaidQty + ) { + const newPaidProduct = { + ...otherBookingTypeProduct, + OrderQty: + otherBookingTypeProduct?.OrderQty - remainingPaidQty, + Offer: 0, + }; + delete newPaidProduct.OfferMode; + delete newPaidProduct.OfferMessage; + delete newPaidProduct.OfferType; + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty - remainingPaidQty, + ...calculateTaxAmounts({ + qty: cartItem?.OrderQty, + rate: cartItem?.OrderRate, + taxPercentage: cartItem?.TaxPercentage, + }), + Offer: + (cartItem?.OrderQty - remainingPaidQty) * + cartItem?.OrderRate, + }; + } + return cartItem; + }); + updatedCart = [...updatedCart, newPaidProduct]; + } + } + } + + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + + dispatch(changeOrderCardDetails(updatedCart)); + + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId && + product?.OfferId === + (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) && + product?.OfferMode === + (sameBookingTypeProduct?.OfferMode || + otherBookingTypeProduct?.OfferMode) + ) { + return { + ...product, + FreeQty: finalOrderQty, + OverAllFreeQty: finalOrderQty, + RemainingQty: 0, + discount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) && + offerProduct?.OfferMode === + (sameBookingTypeProduct?.OfferMode || + otherBookingTypeProduct?.OfferMode); + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferValue: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } + } else { + if (isFreeProductApplicable?.FreeQty === 0) { + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice + ); + // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty) + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId + ) { + return { + ...product, + FreeQty: 0, + OverAllFreeQty: finalOrderQty, + RemainingQty: finalOrderQty, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + } else if (isFreeProductApplicable?.FreeQty === finalOrderQty) { + dispatch( + changeOrderCardDetails( + updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + PackageDtl: PackageDtl, + }; + } + return cartItem; + }) + ) + ); + return; + } else if (isFreeProductApplicable?.FreeQty < finalOrderQty) { + // check if there is any applicable free product in cart + console.log(freeProductVariants, 'freeProductVariants'); + const applicableFreeInCart = CartOrderDetails?.filter( + (cartItem) => { + return ( + freeProductVariants?.some( + (variant) => + variant.FreeProdId === cartItem.ProdId && + variant?.StockDetails?.some( + (stock) => + stock.FreeInwardDtlId === cartItem.InwardDtlId + ) + ) && !cartItem?.Offer + ); + } + ); + + const applicableOfferAppliedFreeInCart = CartOrderDetails?.filter( + (cartItem) => { + return ( + freeProductVariants?.some( + (variant) => + variant.FreeProdId === cartItem.ProdId && + variant?.StockDetails?.some( + (stock) => + stock.FreeInwardDtlId === cartItem.InwardDtlId + ) + ) && + cartItem?.Offer > 0 && + isFreeProductApplicable?.OfferMode === cartItem?.OfferMode && + isFreeProductApplicable?.OfferId === + cartItem?.OfferMessage?.[0]?.OfferId + ); + } + ); + + if (applicableFreeInCart?.length > 0) { + console.log(applicableFreeInCart, 'applicableFreeInCart'); + const sameBookingTypeProduct = applicableFreeInCart?.find( + (cartItem) => { + return ( + cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ); + } + ); + const otherBookingTypeProduct = applicableFreeInCart?.find( + (cartItem) => { + return ( + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + } + ); + const sameBookingTypeFreeProduct = + applicableOfferAppliedFreeInCart?.find((cartItem) => { + return ( + cartItem?.BookingTypeName === editedProduct?.BookingTypeName + ); + }); + const otherBookingTypeFreeProduct = + applicableOfferAppliedFreeInCart?.find((cartItem) => { + return ( + cartItem?.BookingTypeName !== editedProduct?.BookingTypeName + ); + }); + // find how many qty need to be updated as free product + const totalFreeQtyInCart = applicableFreeInCart?.reduce( + (acc, item) => acc + item.OrderQty, + 0 + ); + const freeQtyNeeded = + finalOrderQty - isFreeProductApplicable?.OverAllFreeQty; + if (totalFreeQtyInCart === freeQtyNeeded) { + let updatedCart = [...CartOrderDetails]; + if (sameBookingTypeProduct) { + if (sameBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== sameBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeFreeProduct) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + Offer: + sameBookingTypeProduct?.OrderQty * + cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } + + if (otherBookingTypeProduct) { + if (otherBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== otherBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === otherBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + otherBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + otherBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + otherBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + Offer: + otherBookingTypeProduct?.OrderQty * + cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + ...(cartItem?.Offer > 0 && { + Offer: editedQty * cartItem.OrderRate, + }), + }; + } + return cartItem; + }); + dispatch(changeOrderCardDetails(updatedCart)); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId && + product?.OfferId === + (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeFreeProduct?.OfferMessage?.[0] + ?.OfferId) && + product?.OfferMode === + (sameBookingTypeFreeProduct?.OfferMode || + otherBookingTypeFreeProduct?.OfferMode) + ) { + return { + ...product, + FreeQty: finalOrderQty, + OverAllFreeQty: finalOrderQty, + RemainingQty: 0, + discount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeFreeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + (sameBookingTypeFreeProduct?.OfferMessage?.[0] + ?.OfferId || + otherBookingTypeFreeProduct?.OfferMessage?.[0] + ?.OfferId) && + offerProduct?.OfferMode === + (sameBookingTypeFreeProduct?.OfferMode || + otherBookingTypeFreeProduct?.OfferMode); + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferValue: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } else if (totalFreeQtyInCart > freeQtyNeeded) { + let updatedCart = [...CartOrderDetails]; + if (sameBookingTypeProduct) { + // if available same booking type product qty is more than or equal to freeQtyNeeded. + // if more than then we need to update both free and paid product= + if (sameBookingTypeProduct?.OrderQty === freeQtyNeeded) { + if (sameBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== sameBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === sameBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + sameBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + sameBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + sameBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + Offer: + sameBookingTypeProduct?.OrderQty * + cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } else if (sameBookingTypeProduct?.OrderQty > freeQtyNeeded) { + if (sameBookingTypeFreeProduct) { + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === sameBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + sameBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + sameBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + sameBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty + freeQtyNeeded, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty + freeQtyNeeded, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + freeQtyNeeded) * + cartItem.OrderRate, + }; + } else if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + OrderQty: cartItem.OrderQty - freeQtyNeeded, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty - freeQtyNeeded, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + } else { + const remainingPaidQty = + sameBookingTypeProduct?.OrderQty - freeQtyNeeded; + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + OrderQty: remainingPaidQty, + ...calculateTaxAmounts({ + qty: remainingPaidQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + const freeProduct = { + ...sameBookingTypeProduct, + OrderQty: freeQtyNeeded, + ...calculateTaxAmounts({ + qty: freeQtyNeeded, + rate: sameBookingTypeProduct.OrderRate, + taxPercentage: sameBookingTypeProduct.TaxPercentage, + }), + Offer: freeQtyNeeded * sameBookingTypeProduct.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + localId: uuidv4(), + }; + updatedCart = [...updatedCart, freeProduct]; + } + } + } + + if ( + otherBookingTypeProduct && + freeQtyNeeded > (sameBookingTypeProduct?.OrderQty || 0) + ) { + const remainingFreeQtyNeeded = + freeQtyNeeded - (sameBookingTypeProduct?.OrderQty || 0); + if ( + remainingFreeQtyNeeded === otherBookingTypeProduct?.OrderQty + ) { + if (otherBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== otherBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === otherBookingTypeProduct.ProdId && + cartItem?.InwardDtlId === + otherBookingTypeProduct.InwardDtlId && + cartItem?.BookingTypeName === + otherBookingTypeProduct.BookingTypeName && + cartItem?.OrderRate === + otherBookingTypeProduct.OrderRate && + cartItem?.OfferMode && + cartItem?.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === otherBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + otherBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + otherBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + otherBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + Offer: cartItem.OrderQty * cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } else if ( + otherBookingTypeProduct?.OrderQty > remainingFreeQtyNeeded + ) { + if (otherBookingTypeFreeProduct) { + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === otherBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + otherBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + otherBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + otherBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + remainingFreeQtyNeeded, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty + remainingFreeQtyNeeded, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + remainingFreeQtyNeeded) * + cartItem.OrderRate, + }; + } else if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty - remainingFreeQtyNeeded, + ...calculateTaxAmounts({ + qty: cartItem.OrderQty - remainingFreeQtyNeeded, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + } else { + const remainingPaidQty = + otherBookingTypeProduct?.OrderQty - + remainingFreeQtyNeeded; + const newFreeProduct = { + ...otherBookingTypeProduct, + OrderQty: remainingFreeQtyNeeded, + ...calculateTaxAmounts({ + qty: remainingFreeQtyNeeded, + rate: otherBookingTypeProduct.OrderRate, + taxPercentage: otherBookingTypeProduct.TaxPercentage, + }), + Offer: + remainingFreeQtyNeeded * + otherBookingTypeProduct.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + localId: uuidv4(), + }; + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + OrderQty: remainingPaidQty, + ...calculateTaxAmounts({ + qty: remainingPaidQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + }; + } + return cartItem; + }); + updatedCart = [...updatedCart, newFreeProduct]; + } + } + } + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + ...(cartItem?.Offer > 0 && { + Offer: editedQty * cartItem.OrderRate, + }), + }; + } + return cartItem; + }); + dispatch(changeOrderCardDetails(updatedCart)); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId && + product?.OfferId === + (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeFreeProduct?.OfferMessage?.[0] + ?.OfferId) && + product?.OfferMode === + (sameBookingTypeFreeProduct?.OfferMode || + otherBookingTypeFreeProduct?.OfferMode) + ) { + return { + ...product, + FreeQty: finalOrderQty, + OverAllFreeQty: finalOrderQty, + RemainingQty: 0, + discount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeProduct?.OfferMessage?.[0] + ?.OfferId) && + offerProduct?.OfferMode === + (sameBookingTypeProduct?.OfferMode || + otherBookingTypeProduct?.OfferMode); + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty, + ActualOfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferAmount: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferValue: + finalOrderQty * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + FreeProductsList: updatedFreeProductsList, + UsedCount: finalOrderQty * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } else if (totalFreeQtyInCart < freeQtyNeeded) { + let updatedCart = [...CartOrderDetails]; + if (sameBookingTypeProduct) { + if (sameBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== sameBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === sameBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + sameBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + sameBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + sameBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === sameBookingTypeProduct) { + return { + ...cartItem, + Offer: + (cartItem.OrderQty + + sameBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } + + if (otherBookingTypeProduct) { + if (otherBookingTypeFreeProduct) { + updatedCart = updatedCart?.filter( + (cartItem) => cartItem !== otherBookingTypeProduct + ); + updatedCart = updatedCart?.map((cartItem) => { + if ( + cartItem.ProdId === otherBookingTypeProduct.ProdId && + cartItem.InwardDtlId === + otherBookingTypeProduct.InwardDtlId && + cartItem.BookingTypeName === + otherBookingTypeProduct.BookingTypeName && + cartItem.OrderRate === + otherBookingTypeProduct.OrderRate && + cartItem.OfferMode && + cartItem.Offer > 0 + ) { + return { + ...cartItem, + OrderQty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + ...calculateTaxAmounts({ + qty: + cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + Offer: + (cartItem.OrderQty + + otherBookingTypeProduct?.OrderQty) * + cartItem.OrderRate, + }; + } + return cartItem; + }); + } else { + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === otherBookingTypeProduct) { + return { + ...cartItem, + Offer: + otherBookingTypeProduct?.OrderQty * + cartItem.OrderRate, + OfferMode: isFreeProductApplicable?.OfferMode, + OfferType: isFreeProductApplicable?.OfferType, + OfferMessage: [ + { + OfferId: isFreeProductApplicable?.OfferId, + OfferName: isFreeProductApplicable?.OfferName, + OfferDescription: + isFreeProductApplicable?.OfferDescription, + }, + ], + }; + } + return cartItem; + }); + } + } + updatedCart = updatedCart?.map((cartItem) => { + if (cartItem === editedProduct) { + return { + ...cartItem, + OrderQty: editedQty, + ...calculateTaxAmounts({ + qty: editedQty, + rate: cartItem.OrderRate, + taxPercentage: cartItem.TaxPercentage, + }), + ...(cartItem?.Offer > 0 && { + Offer: editedQty * cartItem.OrderRate, + }), + }; + } + return cartItem; + }); + dispatch(changeOrderCardDetails(updatedCart)); + const remainingQty = freeQtyNeeded - totalFreeQtyInCart; + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId && + product?.OfferId === + (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeFreeProduct?.OfferMessage?.[0] + ?.OfferId) && + product?.OfferMode === + (sameBookingTypeFreeProduct?.OfferMode || + otherBookingTypeFreeProduct?.OfferMode) + ) { + return { + ...product, + FreeQty: finalOrderQty - remainingQty, + OverAllFreeQty: finalOrderQty, + RemainingQty: remainingQty, + discount: + (finalOrderQty - remainingQty) * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + const updatedOfferAppliedProducts = OfferAppliedProducts?.map( + (offerProduct) => { + // Check if this offer product contains the edited product in its free products list + const hasMatchingFreeProduct = + offerProduct?.FreeProductsList?.some((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + // Also check main offer conditions + const isMatchingOffer = + offerProduct?.OfferId === + (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || + otherBookingTypeProduct?.OfferMessage?.[0] + ?.OfferId) && + offerProduct?.OfferMode === + (sameBookingTypeProduct?.OfferMode || + otherBookingTypeProduct?.OfferMode); + + if (hasMatchingFreeProduct && isMatchingOffer) { + // Get loyalty points from the matching free product + const matchingFreeProduct = + offerProduct?.FreeProductsList?.find((freeProduct) => + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ) + ); + + const prodLoyaltyPoint = + matchingFreeProduct?.ProdVariantDetails?.[0] + ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; + + // Update the specific free product in the list + const updatedFreeProductsList = + offerProduct?.FreeProductsList?.map((freeProduct) => { + const isTargetFreeProduct = + freeProduct?.ProdVariantDetails?.some((variant) => + variant?.StockDetails?.some( + (stock) => + stock?.FreeInwardDtlId === + (sameBookingTypeProduct?.InwardDtlId || + otherBookingTypeProduct?.InwardDtlId) + ) + ); + + if (isTargetFreeProduct) { + return { + ...freeProduct, + FreeQty: finalOrderQty - remainingQty, + }; + } + return freeProduct; + }); + + return { + ...offerProduct, + ActualFreeQty: finalOrderQty - remainingQty, + ActualOfferAmount: + (finalOrderQty - remainingQty) * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferAmount: + (finalOrderQty - remainingQty) * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + OfferValue: + (finalOrderQty - remainingQty) * + (sameBookingTypeProduct?.OrderRate || + otherBookingTypeProduct?.OrderRate), + FreeProductsList: updatedFreeProductsList, + UsedCount: + (finalOrderQty - remainingQty) * prodLoyaltyPoint, + }; + } + + return offerProduct; + } + ); + dispatch( + changeFullOfferAppliedProducts(updatedOfferAppliedProducts) + ); + } + } else { + // just update the free product list + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice + ); + const updatedFreeProdList = FreeProdList?.map((product) => { + if ( + product?.ProdId === editedProduct?.ProdId && + product?.InwardDtlId === editedProduct?.InwardDtlId + ) { + return { + ...product, + OverAllFreeQty: finalOrderQty, + RemainingQty: finalOrderQty - product?.FreeQty, + discount: finalOrderQty * editedProduct?.OrderRate, + }; + } + return product; + }); + dispatch(ChangeFullFreeProductList(updatedFreeProdList)); + } + } + } + } else { + await handleNormalEditQuantity( + editedProduct, + editedProductIndex, + editedQty, + newPrice + ); + } + } + }; + + const handleNormalEditQuantity = async ( + editedProduct, + index, + qty, + newPrice = 0, + offerApply = false + ) => { + const fixedQty = Number(qty.toFixed(3)); + const updatedProduct = { + ...editedProduct, + OrderQty: fixedQty, + OrderRate: newPrice > 0 ? newPrice : editedProduct?.OrderRate, + ...calculateTaxAmounts({ + qty: qty, + rate: newPrice > 0 ? newPrice : editedProduct?.OrderRate, + taxPercentage: editedProduct?.TaxPercentage, + type: editedProduct?.Type, + product: editedProduct, + }), + PackageDtl: PackageDtl, + // ✅ FIXED: Proper conditional property assignment + ...(offerApply && { + Offer: qty * (newPrice > 0 ? newPrice : editedProduct?.OrderRate), + }), + }; + + if (hasOffer) { + const offers = validateOffers( + updatedProduct, + OverAllproductBasedOfferDatas, + CartOrderDetails, + TakAwayId, + DineinId + ); + if (!offers?.length) { + if (updatedProduct?.OfferType && updatedProduct?.Offer > 0) { + dispatch( + RemoveOfferAppliedProduct({ + ProdId: updatedProduct?.ProdId, + InwardDtlId: updatedProduct?.InwardDtlId, + OfferType: updatedProduct?.OfferType, + }) + ); + } + dispatch( + changeOrderCardDetails( + CartOrderDetails?.map((i) => + i?.InwardDtlId == updatedProduct?.InwardDtlId && + i?.BookingTypeName == updatedProduct?.BookingTypeName && + i?.localId === updatedProduct?.localId + ? { + ...updatedProduct, + Offer: 0, + OfferType: + updatedProduct?.Type === 'C' + ? updatedProduct?.OfferType + : null, + OfferMessage: null, + } + : i + ) + ) + ); + return; + } + + let bestOffer = null; + for (const offer of offers) { + if (!bestOffer || offer.OfferAmount > bestOffer.OfferAmount) { + bestOffer = offer; + } + } + + const UpdatedCartItemWithOffer = { + ...updatedProduct, + Offer: + bestOffer?.OfferMode === 'I' || bestOffer?.OfferMode === 'Q' + ? bestOffer?.OfferAmount || updatedProduct.Offer + : updatedProduct.Offer || bestOffer?.OfferAmount, + OfferType: updatedProduct?.OfferType || bestOffer?.OfferType, + OfferMessage: updatedProduct?.OfferMessage || bestOffer?.OfferMessage, + }; + + console.log(updatedProduct, 'updatedProduct'); + + const shouldRemove = (c) => + c.ProdId === updatedProduct.ProdId && + c.InwardDtlId === updatedProduct.InwardDtlId && + c.OrderRate === updatedProduct.OrderRate && + c.BookingTypeName === updatedProduct.BookingTypeName && + !c.SalesId && + ((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 updatedCartData = [UpdatedCartItemWithOffer, ...filteredCart]; + + if (bestOffer) { + dispatch(ChangeOfferAppliedProducts(bestOffer)); + } + + dispatch(changeOrderCardDetails(updatedCartData)); + } else { + const updatedData = [...CartOrderDetails]; + updatedData[index] = updatedProduct; + dispatch(changeOrderCardDetails(updatedData)); + } + }; + + const calculateTaxAmounts = ({ + qty, + rate, + taxPercentage, + type = null, + product = {}, + isOfferApply = false, + }) => { + const { OfferType = null, OfferPrice = 0 } = product; + const totalAmount = qty * rate; + const taxAmount = ( + (totalAmount * taxPercentage) / + (100 + taxPercentage) + ).toFixed(2); + const withoutTaxRate = (totalAmount - taxAmount).toFixed(2); + const offerValue = + type === 'C' + ? OfferType === 'F' + ? qty * OfferPrice + : (qty * rate * OfferPrice) / 100 + : null; + + return { + TotalAmt: + type === 'C' && OfferPrice > 0 + ? totalAmount - (offerValue || 0) + : totalAmount, + TaxAmt: parseFloat(taxAmount), + WithoutTaxRate: parseFloat(withoutTaxRate), + OfferValue: offerValue, + }; + }; + const CloseModal = () => { + props.handleEditQuantityCancel(); + setClearQuantity(false); + }; + const onComplete = useCallback(() => { + setMessageData(null); + setMessageType(null); + }, []); + const onRadioBtnChange = (data) => { + setRadioBtnSelection(data); + }; + const onPercentageSelectionChange = (data) => { + setPercentageSelection(data); + setEditedPrice(0); + formRef.current?.resetFields(); + setDisableSubmitButton(false); + }; + const PriceChangefun = (data) => { + const enteredDiscount = parseFloat(data?.target.value); + if (enteredDiscount) { + const sellingPrice = parseFloat(props.Productdata?.SellingPrice || 0); + const limit = parseFloat(props.Productdata?.DiscountLimit || 0); + const limitType = props.Productdata?.DiscountLimitType; + + if (limit === null || limit === undefined || limit === 0) { + if (PercentageSelection == 'Fixed') { + if (parseFloat(enteredDiscount) < parseFloat(sellingPrice)) { + // setEditedPrice(enteredDiscount); + setEditedPrice( + parseFloat(sellingPrice) - parseFloat(enteredDiscount) + ); + setDisableSubmitButton(true); + } else { + setMessageType('error'); + setMessageData('Please Give less than value for sell price'); + setDisableSubmitButton(false); + setEditedPrice(0); + formRef.current?.resetFields(); + } + } else { + if (parseFloat(enteredDiscount) < 100) { + let temperc = + (parseFloat(enteredDiscount) * parseFloat(sellingPrice)) / 100; + setEditedPrice(parseFloat(sellingPrice) - parseFloat(temperc)); + setDisableSubmitButton(true); + } else { + setMessageType('error'); + setMessageData('Please Give less than 100% '); + setEditedPrice(0); + setDisableSubmitButton(false); + formRef.current?.resetFields(); + } + } + return; + } + + let maxDiscount = 0; + if (limitType === 'F') { + maxDiscount = sellingPrice - limit; + } else if (limitType === 'P') { + const afterdiscountfullamount = (sellingPrice * limit) / 100; + maxDiscount = sellingPrice - afterdiscountfullamount; + } + + if (PercentageSelection == 'Fixed') { + if (parseFloat(enteredDiscount) < parseFloat(sellingPrice)) { + if (sellingPrice - enteredDiscount === maxDiscount) { + setEditedPrice( + parseFloat(sellingPrice) - parseFloat(enteredDiscount) + ); + setDisableSubmitButton(true); + return; + } + + if (sellingPrice - enteredDiscount < sellingPrice - maxDiscount) { + setMessageType('error'); + setMessageData( + `Discount amount should not exeed ₹ ${(sellingPrice - maxDiscount).toFixed(2)}` + ); + setEditedPrice(0); + setDisableSubmitButton(true); + formRef.current?.resetFields(); + setDisableSubmitButton(false); + return; + } + + setEditedPrice( + parseFloat(sellingPrice) - parseFloat(enteredDiscount) + ); + setDisableSubmitButton(true); + } else { + setMessageType('error'); + setMessageData('Please Give less than value for sell price'); + setDisableSubmitButton(false); + setEditedPrice(0); + formRef.current?.resetFields(); + } + } else { + if (parseFloat(enteredDiscount) < 100) { + const discountAmount = (sellingPrice * enteredDiscount) / 100; + if (discountAmount > maxDiscount) { + setMessageType('error'); + setMessageData( + `Discount % should not exeed above ${(maxDiscount / sellingPrice) * 100} %` + ); + setEditedPrice(0); + setDisableSubmitButton(false); + formRef.current?.resetFields(); + return; + } + + let temperc = + (parseFloat(enteredDiscount) * parseFloat(sellingPrice)) / 100; + setEditedPrice(parseFloat(sellingPrice) - parseFloat(temperc)); + setDisableSubmitButton(true); + } else { + setMessageType('error'); + setMessageData('Please Give less than 100 '); + setEditedPrice(0); + setDisableSubmitButton(false); + formRef.current?.resetFields(); + } + } + } else { + setDisableSubmitButton(false); + setEditedPrice(0); + formRef.current?.resetFields(); + } + }; + const SellingPriceChange = (data) => { + if (data?.target.value) { + const sellingPrice = parseFloat(props.Productdata?.SellingPrice || 0); + const limit = parseFloat(props.Productdata?.DiscountLimit || 0); + const limitType = props.Productdata?.DiscountLimitType; + const enteredDiscount = parseFloat(data?.target.value); + + if (limit === null || limit === undefined || limit === 0) { + if ( + parseFloat(enteredDiscount) < parseFloat(sellingPrice) || + parseFloat(enteredDiscount) === parseFloat(sellingPrice) + ) { + setEditedPrice(enteredDiscount); + setDisableSubmitButton(true); + } else { + setMessageType('error'); + setMessageData('Please Give less than value for sell price'); + setDisableSubmitButton(false); + setEditedPrice(0); + formRef.current?.resetFields(); + } + return; + } + + let maxDiscount = 0; + if (limitType === 'F') { + maxDiscount = limit; + } else if (limitType === 'P') { + const afterdiscountfullamount = (sellingPrice * limit) / 100; + maxDiscount = afterdiscountfullamount; + } + + if (enteredDiscount === maxDiscount) { + setEditedPrice(data?.target.value); + setDisableSubmitButton(true); + return; + } + + if (enteredDiscount < maxDiscount) { + setMessageType('error'); + setMessageData(`You cannot sell below ₹${maxDiscount.toFixed(2)}`); + setEditedPrice(0); + setDisableSubmitButton(false); + return; + } + setDisableSubmitButton(true); + setEditedPrice(data?.target.value); + } else { + setDisableSubmitButton(false); + setEditedPrice(0); + } + }; + + const AddPacking = async (data) => { + console.log(data, 'Cartdata'); + setPackageDtl(data || []); + }; + + const handleWeightCalculation = async (data) => { + const { price, quantity } = data; + setQuantity(quantity); + setEditedPrice(price); + await handleWeightSubmit(quantity, price); + }; + + const handleWeightSubmit = async (qty, price) => { + await dispatch(changeHoldOrderDtl(false)); + await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); + let localId = props.Index; + let editedProductIndex = CartOrderDetails?.findIndex( + (e) => e?.localId == localId + ); + const editedProduct = { + ...CartOrderDetails[editedProductIndex], + OrderQty: qty + }; + + await handleEditQuantity(editedProduct, editedProductIndex, editedProduct.OrderRate, qty); + props.handleEditQuantityCancel(); + setClearQuantity(false); + }; + const isKg = + props?.Productdata?.Size == 1 && + ["KG", "KGS"].includes(props?.Productdata?.UomName?.toUpperCase()); + + return ( +
+ + + // + //
+ } + open={EditOpen} + width={600} + footer={null} + children={ +
+
+
{ + if (RadioBtnSelection === 'Price' && !disableSubmitButton) { + return; + } + AddProductQuantity(values); + }} + > +
+
+

Item Name:

+
+
+

+ {' '} + {ItemData?.ProdName} +

+
+
+
+ {/* onRadioBtnChange(e)} + /> */} + {ItemData?.ScaleType !== 'weight' && ( + + )} + {PriceChangeaccess && ( + + )} + + + + {isKg && ()} + +
+ + {RadioBtnSelection == 'Quantity' && ( + <> +
+ + setQuantity(e.target.value)} + className="EditQuantity-Quantitybox" + /> + +
+
+
AddQuantity(1)}> + 1 +
+
AddQuantity(2)}> + 2 +
+
AddQuantity(3)}> + 3 +
+ +
AddQuantity(4)}> + 4 +
+
AddQuantity(5)}> + 5 +
+
AddQuantity(6)}> + 6 +
+ +
AddQuantity(7)}> + 7 +
+
AddQuantity(8)}> + 8 +
+
AddQuantity(9)}> + 9 +
+
+
AddQuantity(0)}> + 0 +
+
+
+ + )} + {RadioBtnSelection == 'Price' && ( +
+ + + {!RadioDetails && ( + { + await validateSafeInput(value); + + if (value && value.length > 10) { + return Promise.reject( + 'Selling Price should not exceed 10 characters' + ); + } + + return Promise.resolve(); + }, + }, + ]} + > + { + const cleanedValue = e.target.value.replace( + /[^0-9.]/g, + '' + ); + const parts = cleanedValue.split('.'); + e.target.value = + parts.length > 2 + ? `${parts[0]}.${parts.slice(1).join('')}` + : cleanedValue; + }} + // isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.CustName ? true : false} + /> + + )} + +
+ More +
+ {RadioDetails && ( + <> +
+ { + onPercentageSelectionChange(e); + }} + /> +
+
+ + { + await validateSafeInput(value); // To block HTML tags & SQL keywords + return Promise.resolve(); + }, + }, + ]} + > + PriceChangefun(e)} + inputMode="decimal" + onInput={(e) => { + const cleanedValue = e.target.value.replace( + /[^0-9.]/g, + '' + ); + const parts = cleanedValue.split('.'); + e.target.value = + parts.length > 2 + ? `${parts[0]}.${parts.slice(1).join('')}` + : cleanedValue; + }} + // isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.CustName ? true : false} + /> + + {/* PriceChangefun(e)} + className="EditQuantity-Pricebox" + /> */} + +
+
+
+ {' '} + Price: {safeRound(editedPrice ? editedPrice : 0)} +
+
+ + )} +
+ )} + {RadioBtnSelection == 'Parcel' && ( + <> + AddPacking(data)} + PackageDtl={PackageDtl} + CurrentData={ItemData?.PackageDtl} + localId={ItemData?.localId} + /> + + )} + {RadioBtnSelection == 'AddWeight' && ( + <> + + + )} +
+ {((RadioBtnSelection == 'Price' && disableSubmitButton) || + RadioBtnSelection == 'Quantity') && ( + } + > + )} +
+ +
+ } + handleCancel={CloseModal} + /> +
+ ); +}; +export default BSBillingEditQuantity; From 990c60975bee20a2ab5e5cc4b24b86b7aae92b07 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:23:50 +0530 Subject: [PATCH 11/46] create new component amt and qnt calculation --- .../WeightCalculatePrice.jsx | 3883 +---------------- 1 file changed, 108 insertions(+), 3775 deletions(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx index f4b35e8..f9e0d20 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx @@ -1,3801 +1,134 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { shallowEqual, useDispatch, useSelector } from 'react-redux'; -import { DefaultModal } from '../../../../../Components/Modal/DefaultModal'; -import FormHeader from '../../../../PageComponents/FormHeader.jsx'; -import { Form } from 'antd'; -import { - GlobalOrderCardDetails, - changeOrderCardDetails, - changeHoldOrderDtl, - changePreviousOrderLength, - GlobalOrderType, - GlobalReorderProductDetails, - PreferenceData, - getConfigType, -} from '../../../../../Features/BookingScreen/BookingData/BookingData'; -import { ArrowRightOutlined } from '@ant-design/icons'; -import { Messages } from '../../../../../Components/Notifications/Messages'; -import '../../../../../Styles/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/BSBillingEditQuantity.scss'; -import { settingDataSelector } from '../../../../../Features/PreferenceMaster/PreferenceMaster.js'; -import { RadioGrpButton } from '../../../../../Components/Forms/RadioGroup.jsx'; -import Buttons from '../../../../../Components/Forms/Buttons.jsx'; +import { useState, useEffect, useRef } from 'react'; import { InputField } from '../../../../../Components/Forms/InputField.jsx'; -import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx'; -import { - getTemplateData, - StoredSessionData, -} from '../../../../../Features/ThemeChange/ThemeChange.js'; -import { validateSafeInput } from '../../../../../Services/Others.js'; -import { GlobalEmpAccessDetail } from '../../../../../Features/AppPage/CenterPage.js'; -import Packing from './BSPacking.jsx'; -// import { ApplicationPreferences } from '../../../../../Features/BrachLogin/BranchLogin.js'; -import { - ChangeFullFreeProductList, - changeFullOfferAppliedProducts, - ChangeOfferAppliedProducts, - changeOfferAppliedProductsForLoyalty, - GlobalFreeProdList, - GlobalOfferAppliedProducts, - RemoveOfferAppliedProduct, -} from '../../../../../Features/Offer/Offernew/BookingOffernew.js'; -import { validateOffers } from '../../BSItemCards/ValidateOffer.jsx'; -import { v4 as uuidv4 } from 'uuid'; -import WeightCalculatePrice from './WeightCalculatePrice.jsx'; +import { Form } from 'antd'; +import Buttons from '../../../../../Components/Forms/Buttons.jsx'; +import { ArrowRightOutlined } from '@ant-design/icons'; -const BSBillingEditQuantity = (props) => { - console.log(props?.Productdata.UomName, 'hfghfvbufvbfdviv', props?.Productdata.Size); +const WeightCalculatePrice = ({ itemData, CartOrderDetails, onSubmit }) => { + const [enteredPrice, setEnteredPrice] = useState(''); + const [calculatedQty, setCalculatedQty] = useState(0); + const priceInputRef = useRef(null); + const [form] = Form.useForm(); - const dispatch = useDispatch(); - const formRef = useRef(null); - const quantityInputRef = useRef(null); - const priceChangeInputRef = useRef(null); - const reductionInputRef = useRef(null); - - const { setIndex = () => { } } = props; - - - const [disableSubmitButton, setDisableSubmitButton] = useState(false); - const SessionData = useSelector(StoredSessionData); - // const AppId = SessionData?.AppId; - // const CompId = SessionData?.CompId; - // const BranchId = SessionData?.BranchId; - const UserType = SessionData?.UserType; - const applyOffer = useApplyOfferto_CardDetail(); - const preferenceDatas = useSelector(PreferenceData); - const EmpAccessDetail = useSelector(GlobalEmpAccessDetail); - const OverAllproductBasedOfferDatas = useSelector( - (state) => state?.BookingOFferNew?.OverAllProductBasedProducts, - shallowEqual - ); - const preferenceOffer = - preferenceDatas?.[0]?.['SettingDtlDetails']?.find( - (item) => item.SettingIdName === 'Offer' - )?.SettingValue === 'Y'; - const preferenceshortcutkey = preferenceDatas?.[0]?.[ - 'SettingDtlDetails' - ]?.some( - (item) => - item.SettingIdName.toLowerCase() === 'shortcutkeys' && - item.SettingValue === 'Y' - ); - console.log(preferenceshortcutkey, 'preferenceshortcutkey'); - const [PriceChangeaccess, setPriceChangeaccess] = useState(true); - - const [ConfigDataList, setConfigDataList] = useState([]); - const [messageType, setMessageType] = useState(null); - const [messageData, setMessageData] = useState(null); - const [EditOpen, setEditOpen] = useState(props?.BSBillingEditQuantity); - const [ItemData, setItemData] = useState(props?.Productdata); - const [Quantity, setQuantity] = useState( - props?.Productdata?.ScaleType !== 'weight' - ? parseInt(props.Productdata.OrderQty) - : props.Productdata.OrderQty - ); - const ReorderProductData = useSelector(GlobalReorderProductDetails); - const templateData = useSelector(getTemplateData); - const OfferCheckedInSetup = - templateData?.BookingNavbar?.[1].some( - (item) => item?.OptionName == 'Offer' - ) || - templateData?.BookingCombo1?.[1]?.some( - (item) => item?.OptionName == 'Offer' - ); - const [ClearQuantity, setClearQuantity] = useState(false); - const CartOrderDetails = useSelector(GlobalOrderCardDetails); - const SettingDataSelector = useSelector(PreferenceData); - const OrderType = useSelector(GlobalOrderType); - const [BillOrderPre, setBillOrderPre] = useState(null); - const [RadioBtnSelection, setRadioBtnSelection] = useState( - props?.shortKeyMethod == 'price' - ? 'Price' - : ItemData?.ScaleType !== 'weight' - ? 'Quantity' - : PriceChangeaccess - ? 'Price' - : 'Parcel' - ); - const [PercentageSelection, setPercentageSelection] = useState('Fixed'); - const [RadioDetails, setRadioDetails] = useState(false); - const [editedPrice, setEditedPrice] = useState(0); - const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find( - (setting) => - setting?.SettingIdName?.toLowerCase() === 'decimal' && - setting?.SettingValue === 'Y' - ); - const [PackageDtl, setPackageDtl] = useState([]); - // const appPreferences = useSelector(ApplicationPreferences); - // 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 OfferAppliedProducts = useSelector( - GlobalOfferAppliedProducts, - shallowEqual - ); - const FreeProdList = useSelector(GlobalFreeProdList); - console.log(CartOrderDetails, 'CartOrderDetails'); - - const TakAwayId = ConfigDataList?.find( - (a) => a?.ConfigName === 'TakeAway' - )?.ConfigId; - - const DineinId = ConfigDataList?.find( - (a) => a?.ConfigName === 'Dine In' - )?.ConfigId; - - const hasOffer = preferenceOffer && OfferCheckedInSetup; + const basePrice = parseFloat(itemData?.OrderRate || itemData?.SellingPrice || 0); useEffect(() => { - if (ConfigDataList?.length === 0) { - getBookingTypeId(); - } + setTimeout(() => { + const inputElement = priceInputRef.current?.querySelector('input'); + if (inputElement) { + inputElement.focus(); + } + }, 100); }, []); - useEffect( - () => { - setEditOpen(props.BSBillingEditQuantity); - setItemData(props.Productdata); - setQuantity( - props?.Productdata?.ScaleType !== 'weight' - ? parseInt(props.Productdata.OrderQty) - : props.Productdata.OrderQty - ); - }, - [props.BSBillingEditQuantity], - [props.Productdata] - ); + // Calculate quantity based on entered price + const handlePriceChange = (e) => { + const value = e.target.value; + setEnteredPrice(value); - useEffect(() => { - if (preferenceshortcutkey) { - if (props.BSBillingEditQuantity && RadioBtnSelection === 'Quantity') { - setTimeout(() => { - quantityInputRef.current?.focus(); - }, 100); - } - - if (props.BSBillingEditQuantity && RadioBtnSelection === 'Price') { - setTimeout(() => { - if (RadioDetails) { - const inputElement = - reductionInputRef.current?.querySelector('input'); - inputElement?.focus(); - } else { - const inputElement = - priceChangeInputRef.current?.querySelector('input'); - inputElement?.focus(); - } - }, 100); - } - } - }, [ - RadioBtnSelection, - props.BSBillingEditQuantity, - RadioDetails, - preferenceshortcutkey, - ]); - - useEffect(() => { - const handleKeyDown = (event) => { - if (preferenceshortcutkey && event.shiftKey && event.key === 'E') { - event.preventDefault(); - if (PriceChangeaccess && props.Productdata?.Offer <= 0) { - onRadioBtnChange('Price'); - } - } - }; - - if (EditOpen) { - document.addEventListener('keydown', handleKeyDown); - } - - return () => { - document.removeEventListener('keydown', handleKeyDown); - }; - }, [ - EditOpen, - preferenceshortcutkey, - PriceChangeaccess, - props.Productdata?.Offer, - ]); - - useEffect(() => { - const BillOrder = SettingDataSelector?.[0]?.SettingDtlDetails?.find( - (item) => item.SettingIdName === 'BillItemsOrder' - ); - setBillOrderPre(BillOrder?.SettingValue); - }, []); - - useEffect(() => { - if (UserType == 'Employee') { - const Pricechange = EmpAccessDetail?.filter( - (item) => item.ConfigName === 'Sales Discount' - ); - - setPriceChangeaccess(Pricechange?.[0]?.AddAccess != 'Y' ? false : true); - } - }, [EmpAccessDetail]); - - useEffect(() => { - if (PackageDtl.length > 0) { - AddProductQuantity(); - } - }, [PackageDtl]); - - const getBookingTypeId = async () => { - let tempconfigdata = await dispatch( - getConfigType({ TypeName: 'Booking Type' }) - ).unwrap(); - - if (tempconfigdata?.data?.statusCode == 1) { - setConfigDataList(tempconfigdata?.data?.data); - } - }; - - function safeRound(amountStr) { - if (amountStr == null) return allowDecimal ? '0.00' : '0'; - - const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ''); - const num = Number(cleaned); - - if (isNaN(num)) return allowDecimal ? '0.00' : '0'; - - return allowDecimal ? num.toFixed(2) : Math.round(num).toString(); - } - const AddQuantity = (value) => { - if (ClearQuantity === false) { - setQuantity(value); - setClearQuantity(true); + if (value && basePrice > 0) { + const price = parseFloat(value); + const qty = price / basePrice; + setCalculatedQty(qty); } else { - setQuantity(Quantity.toString() + value.toString()); - if (Quantity?.length > 10) { - setMessageType('error'); - setMessageData('Quantity is to long'); - setQuantity(''); - } + setCalculatedQty(0); } }; - const Removevalue = () => { - let tempremovedata = Quantity.toString().substring(0, Quantity?.length - 1); - setQuantity(tempremovedata); - }; - const openRadioDetails = () => { - setDisableSubmitButton(false); - setRadioDetails(!RadioDetails); - setEditedPrice(0); - }; - // const AddQuantityonly = () => { - // setMessageType('success'); - // setMessageData('Quantity Added'); - // }; - - const createUpdatedCartItem = (cartItem, quantity, newPrice) => { - const qty = parseInt(quantity); - const rate = parseFloat(newPrice); - const offerType = cartItem?.OfferType; - const offerPrice = cartItem?.OfferPrice || 0; - const taxPercent = cartItem?.TaxPercentage || 0; - - const baseAmount = qty * rate; - - const offerValue = - offerType === 'F' ? qty * offerPrice : (baseAmount * offerPrice) / 100; - - const totalAmt = - cartItem?.OfferPrice > 0 ? baseAmount - offerValue : baseAmount; - - const taxAmt = (baseAmount * taxPercent) / (100 + taxPercent); - const withoutTax = baseAmount - taxAmt; - - return { - ...cartItem, - OrderQty: qty, - OrderRate: rate, - TotalAmt: totalAmt, - OfferValue: offerValue, - TaxAmt: taxAmt.toFixed(2), - WithoutTaxRate: withoutTax.toFixed(2), - PackageDtl: PackageDtl, - }; - }; - - const calculateOverAllQty = (item, filterItems) => { - if (!item) return 0; - - const totalUsedQty = - filterItems?.reduce((acc, card) => { - if (card?.StockAvailable !== 'Y') return acc; - - const isSinglePcItem = item?.SinglePc === 'Y'; - const isSinglePcCard = card?.SinglePc === 'Y'; - - let qty = 0; - if (isSinglePcItem) { - qty = isSinglePcCard ? card.OrderQty : card.OrderQty * card.NoOfPcs; - } else { - if (isSinglePcCard) { - const remainder = card?.OverAllPcs % card?.NoOfPcs; - qty = - remainder >= card?.OrderQty - ? 0 - : Math.ceil(card?.OrderQty / card?.NoOfPcs); - } else { - qty = card.OrderQty; - } - } - return acc + qty; - }, 0) || 0; - - const availableQty = - item?.SinglePc === 'Y' ? item?.OverAllPcs : item?.BalanceQty; - return availableQty - totalUsedQty; - }; - - const MergecardItem = (cartItem, BillOrderPre, OtherorderDataforNormal) => { - const updatedCart = {}; - let updatedItemKey = null; - - // Add existing items to the map - OtherorderDataforNormal?.forEach((item) => { - const key = `${item?.ProdId}-${item?.InwardDtlId}-${item?.BookingTypeName}-${item?.OrderRate}`; - if (!updatedCart[key]) { - updatedCart[key] = { ...item }; - } - }); - - // Merge or add new item - const key = `${cartItem?.ProdId}-${cartItem?.InwardDtlId}-${cartItem?.BookingTypeName}-${cartItem?.OrderRate}`; - if (updatedCart[key]) { - updatedCart[key].OrderQty += cartItem?.OrderQty; - } else { - updatedCart[key] = { ...cartItem }; - } - updatedItemKey = key; - - // Recalculate total amounts - Object.values(updatedCart).forEach((item) => { - const orderQty = item.OrderQty; - const orderRate = item.OrderRate; - const taxPercentage = item?.TaxPercentage || 0; - item.TotalAmt = orderQty * orderRate; - item.TaxAmt = ( - (orderQty * orderRate * taxPercentage) / - (100 + taxPercentage) - ).toFixed(2); - item.WithoutTaxRate = orderQty * orderRate - parseFloat(item.TaxAmt); - }); - - let updatedArray = Object.values(updatedCart); - - // Ensure updated item appears first - if (BillOrderPre === 'Y' && updatedItemKey) { - const updatedItem = updatedCart[updatedItemKey]; - updatedArray = [ - updatedItem, - ...updatedArray?.filter((item) => item !== updatedItem), - ]; + const handleSubmit = (e) => { + if (e && e.preventDefault) { + e.preventDefault(); } - return updatedArray; - }; - - const AddProductQuantity = async () => { - let newPrice = editedPrice > 0 ? editedPrice : props.Productdata.OrderRate; - await dispatch(changeHoldOrderDtl(false)); - await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); - - if ( - (parseInt(Quantity) === 0 || Quantity === '') && - props?.Productdata?.ScaleType !== 'weight' - ) { - setMessageType('error'); - setMessageData('Please enter valid quantity'); - setQuantity(''); - } else { - let localId = props.Index; - const editedQty = - props?.Productdata?.ScaleType !== 'weight' - ? parseInt(Quantity) - : props.Productdata.OrderQty; - let editedProductIndex = CartOrderDetails?.findIndex( - (e) => e?.localId == localId - ); - const editedProduct = CartOrderDetails[editedProductIndex]; - const productBookingType = editedProduct?.BookingTypeName; - const isItemInCart = CartOrderDetails?.find( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - !cartItem?.SalesId - ); - // changing for one piece stock checking - const isItemInCartfilter = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate !== editedProduct?.OrderRate && - !cartItem?.SalesId - ); - - const isItemInCartHold = CartOrderDetails?.find( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ); // check if the item is already in the cart - const isItemInCartHoldfilter = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - !( - (cartItem?.OrderRate === editedProduct?.OrderRate) - // && cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ) - ); - - if ( - (isItemInCart && - productBookingType !== 'Dine In' && - OrderType != 'Hold') || - (isItemInCart && - productBookingType === 'Dine In' && - OrderType != 'Hold') - ) { - // let onePcsQtyOther = 0; - // if (editedProduct?.SinglePc === 'Y') { - // // check if there is same rate product in other booking type - // const sameRateProductInOtherBookingType = CartOrderDetails?.find( - // (cartItem) => - // cartItem?.ProdId === editedProduct?.ProdId && - // cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - // cartItem?.OrderRate === editedProduct?.OrderRate && - // cartItem?.BookingTypeName !== editedProduct?.BookingTypeName && - // !cartItem?.SalesId - // ) - // if (sameRateProductInOtherBookingType?.StockAvailable === 'Y') { - // onePcsQtyOther = sameRateProductInOtherBookingType?.OrderQty; - // } - // } - const overAllQuantity = calculateOverAllQty( - isItemInCart, - isItemInCartfilter - ); - let totalUsedQty = 0; - const sameProductInOtherBookingType = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName && - !cartItem?.SalesId - ); - if (editedProduct?.Offer > 0) { - // check same product available in paid product - const sameProductAsPaidInSameBookingType = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - !cartItem?.SalesId && - !cartItem?.OfferMode && - cartItem?.Offer === 0 - ); - - if (sameProductAsPaidInSameBookingType?.length > 0) { - const stockAvailable = sameProductAsPaidInSameBookingType?.some( - (item) => item?.StockAvailable === 'Y' - ); - if (stockAvailable) { - totalUsedQty = sameProductAsPaidInSameBookingType?.reduce( - (acc, item) => { - if (item?.StockAvailable === 'Y') { - return acc + parseInt(item?.OrderQty); - } - return acc; - }, - 0 - ); - } - } - } else if (!editedProduct?.Offer) { - const sameProductAsFree = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - !cartItem?.SalesId && - cartItem?.Offer > 0 && - cartItem?.OfferMode - ); - - if (sameProductAsFree?.length > 0) { - const stockAvailable = sameProductAsFree?.some( - (item) => item?.StockAvailable === 'Y' - ); - if (stockAvailable) { - totalUsedQty = sameProductAsFree?.reduce((acc, item) => { - if (item?.StockAvailable === 'Y') { - return acc + parseInt(item?.OrderQty); - } - return acc; - }, 0); - } - } - } - - if (sameProductInOtherBookingType?.length > 0) { - const stockAvailable = sameProductInOtherBookingType?.some( - (item) => item?.StockAvailable === 'Y' - ); - if (stockAvailable) { - totalUsedQty += sameProductInOtherBookingType?.reduce( - (acc, item) => { - if (item?.StockAvailable === 'Y') { - return acc + parseInt(item?.OrderQty); - } - return acc; - }, - 0 - ); - } - } - - if ( - overAllQuantity < editedQty + (totalUsedQty || 0) && - isItemInCart?.StockAvailable === 'Y' - ) { - setMessageType('error'); - setMessageData('Stock Not Available'); - return; - } - } else if (isItemInCartHold && OrderType === 'Hold') { - const holddataproduct = ReorderProductData?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId - ); - - let totalSelectedProductQty = holddataproduct?.reduce( - (accumulator, card) => { - return ( - accumulator + - parseInt( - card?.StockAvailable === 'Y' - ? editedProduct?.SinglePc === 'Y' - ? card.SinglePc !== 'Y' - ? card.OrderQty * card.NoOfPcs - : card.OrderQty - : 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 totalUsedQty = 0; - - const sameProductInOtherBookingType = CartOrderDetails?.filter( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - - if (editedProduct?.Offer > 0) { - // check same product available in paid product - const sameProductAsPaid = CartOrderDetails?.find( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - !cartItem?.OfferMode && - cartItem?.Offer === 0 - ); - - if (sameProductAsPaid?.StockAvailable === 'Y') { - totalUsedQty = sameProductAsPaid?.OrderQty; - } - } else if (!editedProduct?.Offer) { - const sameProductAsFree = CartOrderDetails?.find( - (cartItem) => - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - cartItem?.Offer > 0 && - cartItem?.OfferMode - ); - if (sameProductAsFree?.StockAvailable === 'Y') { - totalUsedQty = sameProductAsFree?.OrderQty; - } - } - - if (sameProductInOtherBookingType?.length > 0) { - const stockAvailable = sameProductInOtherBookingType?.some( - (item) => item?.StockAvailable === 'Y' - ); - if (stockAvailable) { - totalUsedQty += sameProductInOtherBookingType?.reduce( - (acc, item) => { - if (item?.StockAvailable === 'Y') { - return acc + parseInt(item?.OrderQty); - } - return acc; - }, - 0 - ); - } - } - - let overAllQuantityHold = - calculateOverAllQty(isItemInCartHold, isItemInCartHoldfilter) + - totalSelectedProductQty; - if ( - isItemInCartHold?.StockAvailable === 'Y' && - overAllQuantityHold < editedQty + (totalUsedQty || 0) - ) { - setMessageType('error'); - setMessageData('Stock Not Available'); - return; - } - } - await handleEditQuantity(editedProduct, editedProductIndex, newPrice); - props.handleEditQuantityCancel(); - setClearQuantity(false); - } - setIndex(null); - }; - - const handleEditQuantity = async ( - editedProduct, - editedProductIndex, - newPrice, - overrideQty = null - ) => { - const editedQty = overrideQty !== null - ? overrideQty - : props?.Productdata?.ScaleType !== 'weight' - ? parseInt(Quantity) - : props.Productdata.OrderQty; - const addFirst = BillOrderPre === 'Y'; - const isExistsInFreeProdList = FreeProdList?.find( - (product) => - product?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) && - editedProduct?.OfferMessage?.[0]?.OfferId === product?.OfferId && - editedProduct?.OfferMode === product?.OfferMode - ); - console.log(FreeProdList, 'FreeProdList'); - - if ( - isExistsInFreeProdList && - editedProduct?.Offer > 0 && - hasOffer && - editedProduct?.SinglePc !== 'Y' - ) { - const freeProductInOtherBooking = CartOrderDetails?.find((cartItem) => { - return ( - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OfferMessage?.[0]?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - cartItem?.OfferMode === editedProduct?.OfferMode && - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); + if (enteredPrice && calculatedQty > 0) { + console.log('Submitting weight calculation:', { + price: parseFloat(enteredPrice), + quantity: calculatedQty, }); - const finalOrderQty = - (freeProductInOtherBooking?.OrderQty || 0) + editedQty; - - if (isExistsInFreeProdList?.RemainingQty === 0) { - // need to split the free product and paid product - - if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) { - const paidQty = - finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty; - const isAlreadyExistsInCart = CartOrderDetails?.findIndex( - (cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - !cartItem?.OfferMode && - cartItem?.Offer === 0 && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - cartItem?.OrderRate === editedProduct?.OrderRate - ); - } - ); - - let updatedCart = [...CartOrderDetails]; - - if (isAlreadyExistsInCart !== -1) { - // update the existing paid product in cart - const existingItem = updatedCart[isAlreadyExistsInCart]; - const updatedItem = { - ...existingItem, - OrderQty: existingItem?.OrderQty + paidQty, - ...calculateTaxAmounts({ - qty: existingItem?.OrderQty + paidQty, - rate: existingItem?.OrderRate, - taxPercentage: existingItem?.TaxPercentage, - }), - }; - updatedCart?.splice(isAlreadyExistsInCart, 1); - updatedCart = addFirst - ? [updatedItem, ...updatedCart] - : [...updatedCart, updatedItem]; - } else { - // add new paid product in cart - const paidProduct = { - localId: uuidv4(), - ...editedProduct, - OrderQty: paidQty, - Offer: 0, - OfferMode: null, - OfferMessage: null, - OfferType: null, - ...calculateTaxAmounts({ - qty: paidQty, - rate: editedProduct.OrderRate, - taxPercentage: editedProduct.TaxPercentage, - }), - }; - updatedCart = addFirst - ? [paidProduct, ...updatedCart] - : [...updatedCart, paidProduct]; - } - dispatch(changeOrderCardDetails(updatedCart)); - } else { - // Check if there is any same product but No offer applied in OrderCardDtls in same BookingType - // In Same BookingType Have Enough Free Qty Just only Update Qty in Same Booking Type OtherWise need to update in Other Booking Type Qty also if exists in Other Booking Type - const isAlreadyExistsInCart = CartOrderDetails?.find((cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - !cartItem?.OfferMode && - cartItem?.Offer === 0 - ); - }); - - const freeQtyNeeded = - isExistsInFreeProdList?.OverAllFreeQty - finalOrderQty; - const paidQtySame = isAlreadyExistsInCart?.OrderQty || 0; - - if (paidQtySame >= freeQtyNeeded) { - const remainingPaidQty = (paidQtySame || 0) - freeQtyNeeded; - if (remainingPaidQty === 0) { - // Just need to update the Free Qty and Remove the Paid Product from Cart - const updatedCart = CartOrderDetails?.filter( - (cartItem) => cartItem !== isAlreadyExistsInCart - ); - dispatch( - changeOrderCardDetails( - updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - PackageDtl: PackageDtl, - }; - } - return cartItem; - }) - ) - ); - } else { - // need to update the Paid Qty to Remaining Qty - const updatedCart = CartOrderDetails?.map((cartItem) => { - if (cartItem === isAlreadyExistsInCart) { - return { - ...cartItem, - OrderQty: remainingPaidQty, - ...calculateTaxAmounts({ - qty: remainingPaidQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - dispatch(changeOrderCardDetails(updatedCart)); - } - } else { - // check if the same product exists in other booking type as paid product - // need to calculate how much qty going to be updated in other booking type and same booking type - - const diffBookingTypeProduct = CartOrderDetails?.find( - (cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName !== - editedProduct?.BookingTypeName && - !cartItem?.OfferMode && - cartItem?.Offer === 0 - ); - } - ); - - const diffBookingTypeFreeProduct = CartOrderDetails?.find( - (cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.OrderRate === editedProduct?.OrderRate && - cartItem?.BookingTypeName !== - editedProduct?.BookingTypeName && - cartItem?.OfferMode === editedProduct?.OfferMode && - cartItem?.Offer > 0 - ); - } - ); - - const paidQtyOther = diffBookingTypeProduct?.OrderQty || 0; - const sameBookTypeUpdateQty = freeQtyNeeded - paidQtySame; - const otherBookTypePaidUpdateQty = - paidQtyOther - sameBookTypeUpdateQty; - const totalPaidQty = paidQtySame + paidQtyOther; - - if (paidQtySame || paidQtyOther) { - let updatedCart = [...CartOrderDetails]; - - // Remove paid product in same booking type if needed - if (paidQtySame) { - updatedCart = updatedCart.filter( - (cartItem) => cartItem !== isAlreadyExistsInCart - ); - updatedCart = updatedCart.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty + paidQtySame, - ...calculateTaxAmounts({ - qty: editedQty + paidQtySame, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - ...(cartItem?.Offer > 0 && { - Offer: (editedQty + paidQtySame) * cartItem.OrderRate, - }), - }; - } - return cartItem; - }); - } - - // Remove/update paid product in other booking type if needed - if (paidQtyOther) { - if (otherBookTypePaidUpdateQty <= 0) { - // Remove paid product from other booking type - updatedCart = updatedCart.filter( - (cartItem) => cartItem !== diffBookingTypeProduct - ); - updatedCart = updatedCart.map((cartItem) => { - if (cartItem === diffBookingTypeFreeProduct) { - return { - ...cartItem, - OrderQty: paidQtyOther + cartItem?.OrderQty, - ...calculateTaxAmounts({ - qty: paidQtyOther + cartItem?.OrderQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: - (paidQtyOther + cartItem?.OrderQty) * - cartItem?.OrderRate, - }; - } else if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: editedQty * cartItem?.OrderRate, - }; - } - return cartItem; - }); - } else if (otherBookTypePaidUpdateQty > 0) { - updatedCart = updatedCart.map((cartItem) => { - if (cartItem === diffBookingTypeFreeProduct) { - return { - ...cartItem, - OrderQty: cartItem?.OrderQty + sameBookTypeUpdateQty, - ...calculateTaxAmounts({ - qty: cartItem?.OrderQty + sameBookTypeUpdateQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: - (cartItem?.OrderQty + sameBookTypeUpdateQty) * - cartItem?.OrderRate, - }; - } else if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: editedQty * cartItem?.OrderRate, - }; - } else if (cartItem === diffBookingTypeProduct) { - return { - ...cartItem, - OrderQty: otherBookTypePaidUpdateQty, - ...calculateTaxAmounts({ - qty: otherBookTypePaidUpdateQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - }; - } - return cartItem; - }); - } - } - - // Only one dispatch after all updates - dispatch(changeOrderCardDetails(updatedCart)); - - if (totalPaidQty < freeQtyNeeded) { - const additionalFreeQtyNeeded = freeQtyNeeded - totalPaidQty; - - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.FreeProdId === editedProduct?.ProdId && - product?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) && - product?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - product?.OfferMode === editedProduct?.OfferMode - ) { - const freeQty = - product?.OverAllFreeQty - additionalFreeQtyNeeded; - return { - ...product, - FreeQty: freeQty, - RemainingQty: additionalFreeQtyNeeded, - discount: freeQty * editedProduct?.OrderRate, - }; - } - return product; - }); - - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - offerProduct?.OfferMode === editedProduct?.OfferMode; - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - const freeQty = - matchingFreeProduct?.FreeQty - additionalFreeQtyNeeded; - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: freeQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: freeQty, - ActualOfferAmount: freeQty * editedProduct?.OrderRate, - OfferAmount: freeQty * editedProduct?.OrderRate, - OfferValue: freeQty * editedProduct?.OrderRate, - FreeProductsList: updatedFreeProductsList, - UsedCount: freeQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } - } else { - // no paid product exists in other booking type and same booking type - // Just need to update the Free Qty in FreeProductList - // Need to update the Qty in Edited Product - // Need to update the FreeQty in OfferAppliedProducts - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice, - true - ); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.FreeProdId === editedProduct?.ProdId && - product?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) && - product?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - product?.OfferMode === editedProduct?.OfferMode - ) { - return { - ...product, - FreeQty: finalOrderQty, - RemainingQty: product?.OverAllFreeQty - finalOrderQty, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - offerProduct?.OfferMode === editedProduct?.OfferMode; - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: - finalOrderQty * editedProduct?.OrderRate, - OfferAmount: finalOrderQty * editedProduct?.OrderRate, - OfferValue: finalOrderQty * editedProduct?.OrderRate, - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } - } - } - } else if (isExistsInFreeProdList?.RemainingQty > 0) { - // perform normal edit qty operation - // console.log(editedProduct?.OrderQty, "editedProduct") - // await handleNormalEditQuantity(editedProduct, editedProductIndex); - - if (finalOrderQty > isExistsInFreeProdList?.OverAllFreeQty) { - // split paid and free product - const paidProdQty = - finalOrderQty - isExistsInFreeProdList?.OverAllFreeQty; - const freeProdQty = editedQty - paidProdQty; - const isAlreadyExistsInCart = CartOrderDetails?.findIndex( - (cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - !cartItem?.OfferMode && - cartItem?.Offer === 0 && - cartItem?.BookingTypeName === editedProduct?.BookingTypeName && - cartItem?.OrderRate === editedProduct?.OrderRate - ); - } - ); - - let updatedCart = [...CartOrderDetails]; - - if (isAlreadyExistsInCart !== -1) { - // update the existing paid product in cart - updatedCart[isAlreadyExistsInCart] = { - ...updatedCart[isAlreadyExistsInCart], - OrderQty: - updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty, - ...calculateTaxAmounts({ - qty: updatedCart[isAlreadyExistsInCart]?.OrderQty + paidProdQty, - rate: updatedCart[isAlreadyExistsInCart]?.OrderRate, - taxPercentage: - updatedCart[isAlreadyExistsInCart]?.TaxPercentage, - }), - }; - } else { - // add new paid product in cart - const paidProduct = { - localId: uuidv4(), - ...editedProduct, - OrderQty: paidProdQty, - Offer: 0, - OfferMode: null, - OfferMessage: null, - OfferType: null, - ...calculateTaxAmounts({ - qty: paidProdQty, - rate: editedProduct?.OrderRate, - taxPercentage: editedProduct?.TaxPercentage, - }), - }; - updatedCart = [...updatedCart, paidProduct]; - } - - dispatch( - changeOrderCardDetails( - updatedCart?.map((prod) => { - if (prod === editedProduct) { - return { - ...prod, - OrderQty: freeProdQty, - ...calculateTaxAmounts({ - qty: freeProdQty, - rate: prod.OrderRate, - taxPercentage: prod.TaxPercentage, - }), - ...(prod?.Offer > 0 && { - Offer: freeProdQty * prod.OrderRate, - }), - }; - } - return prod; - }) - ) - ); - } else if (finalOrderQty === isExistsInFreeProdList?.OverAllFreeQty) { - // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice, - true - ); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.FreeProdId === editedProduct?.ProdId && - product?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) && - product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId && - product?.OfferMode === editedProduct?.OfferMode - ) { - return { - ...product, - FreeQty: finalOrderQty, - RemainingQty: 0, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - offerProduct?.OfferMode === editedProduct?.OfferMode; - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate, - OfferAmount: finalOrderQty * editedProduct?.OrderRate, - OfferValue: finalOrderQty * editedProduct?.OrderRate, - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts)); - } else if (finalOrderQty < isExistsInFreeProdList?.OverAllFreeQty) { - // Just need to update the Qty in Edited Product and FreeProductList and OfferAppliedProducts - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice, - true - ); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.FreeProdId === editedProduct?.ProdId && - product?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) && - product?.OfferId === editedProduct?.OfferMessage?.[0]?.OfferId && - product?.OfferMode === editedProduct?.OfferMode - ) { - return { - ...product, - FreeQty: finalOrderQty, - RemainingQty: product?.OverAllFreeQty - finalOrderQty, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - editedProduct?.OfferMessage?.[0]?.OfferId && - offerProduct?.OfferMode === editedProduct?.OfferMode; - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === editedProduct?.InwardDtlId - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - editedProduct?.InwardDtlId - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: finalOrderQty * editedProduct?.OrderRate, - OfferAmount: finalOrderQty * editedProduct?.OrderRate, - OfferValue: finalOrderQty * editedProduct?.OrderRate, - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch(changeFullOfferAppliedProducts(updatedOfferAppliedProducts)); - } - } - } else { - // check is there any free product applicable for the edited product - const isFreeProductApplicable = FreeProdList?.find((product) => { - return ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId - ); - }); - - const sameProductInOtherBooking = CartOrderDetails?.find((cartItem) => { - return ( - cartItem?.ProdId === editedProduct?.ProdId && - cartItem?.InwardDtlId === editedProduct?.InwardDtlId && - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - }); - - const finalOrderQty = - (sameProductInOtherBooking?.OrderQty || 0) + editedQty; - - if (isFreeProductApplicable && hasOffer) { - const applicableFreeProducts = - isFreeProductApplicable?.ProdVariantDetails; - - const freeProductVariants = applicableFreeProducts?.map((variant) => { - return { - ...variant, - FreeProdId: isFreeProductApplicable?.FreeProdId, - OfferId: isFreeProductApplicable?.OfferId, - OfferMode: isFreeProductApplicable?.OfferMode, - }; + // Pass the calculated values back to parent component + if (onSubmit) { + onSubmit({ + price: parseFloat(enteredPrice), + quantity: calculatedQty, }); - - if (isFreeProductApplicable?.OverAllFreeQty > finalOrderQty) { - if (isFreeProductApplicable?.FreeQty === 0) { - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice - ); - // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty) - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId - ) { - return { - ...product, - FreeQty: 0, - OverAllFreeQty: finalOrderQty, - RemainingQty: finalOrderQty, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - } else if (isFreeProductApplicable?.FreeQty <= finalOrderQty) { - // check if there is any applicable free product in cart - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice - ); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId - ) { - return { - ...product, - OverAllFreeQty: finalOrderQty, - RemainingQty: finalOrderQty - product?.FreeQty, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - } else if (isFreeProductApplicable?.FreeQty > finalOrderQty) { - // need to split free product and paid product - let remainingPaidQty = - isFreeProductApplicable?.FreeQty - finalOrderQty; - const applicableFreeInCart = CartOrderDetails?.filter( - (cartItem) => { - return ( - freeProductVariants?.some( - (variant) => - variant.FreeProdId === cartItem.ProdId && - variant?.StockDetails?.some( - (stock) => - stock.FreeInwardDtlId === cartItem.InwardDtlId - ) - ) && - cartItem?.Offer && - isFreeProductApplicable?.OfferId === - cartItem?.OfferMessage?.[0]?.OfferId - ); - } - ); - const applicableFreeInCartAsPaid = CartOrderDetails?.filter( - (cartItem) => { - return ( - freeProductVariants?.some( - (variant) => - variant.FreeProdId === cartItem.ProdId && - variant?.StockDetails?.some( - (stock) => - stock.FreeInwardDtlId === cartItem.InwardDtlId - ) - ) && !cartItem?.Offer - ); - } - ); - const sameBookingTypeProduct = applicableFreeInCart?.find( - (cartItem) => { - return ( - cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ); - } - ); - const otherBookingTypeProduct = applicableFreeInCart?.find( - (cartItem) => { - return ( - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - } - ); - const sameBookingTypeProductAsPaid = - applicableFreeInCartAsPaid?.find((cartItem) => { - return ( - cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ); - }); - const otherBookingTypeProductAsPaid = - applicableFreeInCartAsPaid?.find((cartItem) => { - return ( - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - }); - let updatedCart = [...CartOrderDetails]; - if (sameBookingTypeProduct) { - if (sameBookingTypeProductAsPaid) { - if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== sameBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProductAsPaid) { - const newItem = { - ...cartItem, - OrderQty: - cartItem.OrderQty + sameBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: 0, - }; - - delete newItem.OfferMode; - delete newItem.OfferMessage; - delete newItem.OfferType; - - return newItem; - } - return cartItem; - }); - } else if ( - sameBookingTypeProduct?.OrderQty > remainingPaidQty - ) { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty - remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty - remainingPaidQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem?.OrderQty - remainingPaidQty) * - cartItem?.OrderRate, - }; - } else if (cartItem === sameBookingTypeProductAsPaid) { - return { - ...cartItem, - OrderQty: cartItem?.OrderQty + remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem?.OrderQty + remainingPaidQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - }; - } - return cartItem; - }); - } - } else { - if (sameBookingTypeProduct?.OrderQty <= remainingPaidQty) { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - const newPaidProd = { - ...cartItem, - Offer: 0, - }; - - delete newPaidProd.OfferMode; - delete newPaidProd.OfferMessage; - delete newPaidProd.OfferType; - return newPaidProd; - } - return cartItem; - }); - } else if ( - sameBookingTypeProduct?.OrderQty > remainingPaidQty - ) { - const newPaidProduct = { - ...sameBookingTypeProduct, - OrderQty: remainingPaidQty, - Offer: 0, - }; - delete newPaidProduct.OfferMode; - delete newPaidProduct.OfferMessage; - delete newPaidProduct.OfferType; - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty - remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem?.OrderQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: - (cartItem?.OrderQty - remainingPaidQty) * - cartItem?.OrderRate, - }; - } - return cartItem; - }); - updatedCart = [...updatedCart, newPaidProduct]; - } - } - remainingPaidQty = - remainingPaidQty - sameBookingTypeProduct?.OrderQty; - } - - if (otherBookingTypeProduct && remainingPaidQty > 0) { - if (otherBookingTypeProductAsPaid) { - if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== otherBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProductAsPaid) { - const newItem = { - ...cartItem, - OrderQty: - cartItem.OrderQty + otherBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: 0, - }; - - delete newItem.OfferMode; - delete newItem.OfferMessage; - delete newItem.OfferType; - - return newItem; - } - return cartItem; - }); - } else if ( - otherBookingTypeProduct?.OrderQty > remainingPaidQty - ) { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty - remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty - remainingPaidQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem?.OrderQty - remainingPaidQty) * - cartItem?.OrderRate, - }; - } else if (cartItem === otherBookingTypeProductAsPaid) { - return { - ...cartItem, - OrderQty: cartItem?.OrderQty + remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem?.OrderQty + remainingPaidQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - }; - } - return cartItem; - }); - } - } else { - if (otherBookingTypeProduct?.OrderQty <= remainingPaidQty) { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - const newPaidProd = { - ...cartItem, - Offer: 0, - }; - delete newPaidProd.OfferMode; - delete newPaidProd.OfferMessage; - delete newPaidProd.OfferType; - return newPaidProd; - } - return cartItem; - }); - } else if ( - otherBookingTypeProduct?.OrderQty > remainingPaidQty - ) { - const newPaidProduct = { - ...otherBookingTypeProduct, - OrderQty: - otherBookingTypeProduct?.OrderQty - remainingPaidQty, - Offer: 0, - }; - delete newPaidProduct.OfferMode; - delete newPaidProduct.OfferMessage; - delete newPaidProduct.OfferType; - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty - remainingPaidQty, - ...calculateTaxAmounts({ - qty: cartItem?.OrderQty, - rate: cartItem?.OrderRate, - taxPercentage: cartItem?.TaxPercentage, - }), - Offer: - (cartItem?.OrderQty - remainingPaidQty) * - cartItem?.OrderRate, - }; - } - return cartItem; - }); - updatedCart = [...updatedCart, newPaidProduct]; - } - } - } - - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - - dispatch(changeOrderCardDetails(updatedCart)); - - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId && - product?.OfferId === - (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) && - product?.OfferMode === - (sameBookingTypeProduct?.OfferMode || - otherBookingTypeProduct?.OfferMode) - ) { - return { - ...product, - FreeQty: finalOrderQty, - OverAllFreeQty: finalOrderQty, - RemainingQty: 0, - discount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeProduct?.OfferMessage?.[0]?.OfferId) && - offerProduct?.OfferMode === - (sameBookingTypeProduct?.OfferMode || - otherBookingTypeProduct?.OfferMode); - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferValue: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } - } else { - if (isFreeProductApplicable?.FreeQty === 0) { - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice - ); - // update free product list (Set OverAllFreeQty = OrderQty and Remaining = OrderQty) - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId - ) { - return { - ...product, - FreeQty: 0, - OverAllFreeQty: finalOrderQty, - RemainingQty: finalOrderQty, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - } else if (isFreeProductApplicable?.FreeQty === finalOrderQty) { - dispatch( - changeOrderCardDetails( - updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - PackageDtl: PackageDtl, - }; - } - return cartItem; - }) - ) - ); - return; - } else if (isFreeProductApplicable?.FreeQty < finalOrderQty) { - // check if there is any applicable free product in cart - console.log(freeProductVariants, 'freeProductVariants'); - const applicableFreeInCart = CartOrderDetails?.filter( - (cartItem) => { - return ( - freeProductVariants?.some( - (variant) => - variant.FreeProdId === cartItem.ProdId && - variant?.StockDetails?.some( - (stock) => - stock.FreeInwardDtlId === cartItem.InwardDtlId - ) - ) && !cartItem?.Offer - ); - } - ); - - const applicableOfferAppliedFreeInCart = CartOrderDetails?.filter( - (cartItem) => { - return ( - freeProductVariants?.some( - (variant) => - variant.FreeProdId === cartItem.ProdId && - variant?.StockDetails?.some( - (stock) => - stock.FreeInwardDtlId === cartItem.InwardDtlId - ) - ) && - cartItem?.Offer > 0 && - isFreeProductApplicable?.OfferMode === cartItem?.OfferMode && - isFreeProductApplicable?.OfferId === - cartItem?.OfferMessage?.[0]?.OfferId - ); - } - ); - - if (applicableFreeInCart?.length > 0) { - console.log(applicableFreeInCart, 'applicableFreeInCart'); - const sameBookingTypeProduct = applicableFreeInCart?.find( - (cartItem) => { - return ( - cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ); - } - ); - const otherBookingTypeProduct = applicableFreeInCart?.find( - (cartItem) => { - return ( - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - } - ); - const sameBookingTypeFreeProduct = - applicableOfferAppliedFreeInCart?.find((cartItem) => { - return ( - cartItem?.BookingTypeName === editedProduct?.BookingTypeName - ); - }); - const otherBookingTypeFreeProduct = - applicableOfferAppliedFreeInCart?.find((cartItem) => { - return ( - cartItem?.BookingTypeName !== editedProduct?.BookingTypeName - ); - }); - // find how many qty need to be updated as free product - const totalFreeQtyInCart = applicableFreeInCart?.reduce( - (acc, item) => acc + item.OrderQty, - 0 - ); - const freeQtyNeeded = - finalOrderQty - isFreeProductApplicable?.OverAllFreeQty; - if (totalFreeQtyInCart === freeQtyNeeded) { - let updatedCart = [...CartOrderDetails]; - if (sameBookingTypeProduct) { - if (sameBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== sameBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeFreeProduct) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - Offer: - sameBookingTypeProduct?.OrderQty * - cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } - - if (otherBookingTypeProduct) { - if (otherBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== otherBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === otherBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - otherBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - otherBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - otherBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - Offer: - otherBookingTypeProduct?.OrderQty * - cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - ...(cartItem?.Offer > 0 && { - Offer: editedQty * cartItem.OrderRate, - }), - }; - } - return cartItem; - }); - dispatch(changeOrderCardDetails(updatedCart)); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId && - product?.OfferId === - (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeFreeProduct?.OfferMessage?.[0] - ?.OfferId) && - product?.OfferMode === - (sameBookingTypeFreeProduct?.OfferMode || - otherBookingTypeFreeProduct?.OfferMode) - ) { - return { - ...product, - FreeQty: finalOrderQty, - OverAllFreeQty: finalOrderQty, - RemainingQty: 0, - discount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeFreeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - (sameBookingTypeFreeProduct?.OfferMessage?.[0] - ?.OfferId || - otherBookingTypeFreeProduct?.OfferMessage?.[0] - ?.OfferId) && - offerProduct?.OfferMode === - (sameBookingTypeFreeProduct?.OfferMode || - otherBookingTypeFreeProduct?.OfferMode); - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferValue: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } else if (totalFreeQtyInCart > freeQtyNeeded) { - let updatedCart = [...CartOrderDetails]; - if (sameBookingTypeProduct) { - // if available same booking type product qty is more than or equal to freeQtyNeeded. - // if more than then we need to update both free and paid product= - if (sameBookingTypeProduct?.OrderQty === freeQtyNeeded) { - if (sameBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== sameBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === sameBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - sameBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - sameBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - sameBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - Offer: - sameBookingTypeProduct?.OrderQty * - cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } else if (sameBookingTypeProduct?.OrderQty > freeQtyNeeded) { - if (sameBookingTypeFreeProduct) { - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === sameBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - sameBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - sameBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - sameBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty + freeQtyNeeded, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty + freeQtyNeeded, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + freeQtyNeeded) * - cartItem.OrderRate, - }; - } else if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - OrderQty: cartItem.OrderQty - freeQtyNeeded, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty - freeQtyNeeded, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - } else { - const remainingPaidQty = - sameBookingTypeProduct?.OrderQty - freeQtyNeeded; - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - OrderQty: remainingPaidQty, - ...calculateTaxAmounts({ - qty: remainingPaidQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - const freeProduct = { - ...sameBookingTypeProduct, - OrderQty: freeQtyNeeded, - ...calculateTaxAmounts({ - qty: freeQtyNeeded, - rate: sameBookingTypeProduct.OrderRate, - taxPercentage: sameBookingTypeProduct.TaxPercentage, - }), - Offer: freeQtyNeeded * sameBookingTypeProduct.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - localId: uuidv4(), - }; - updatedCart = [...updatedCart, freeProduct]; - } - } - } - - if ( - otherBookingTypeProduct && - freeQtyNeeded > (sameBookingTypeProduct?.OrderQty || 0) - ) { - const remainingFreeQtyNeeded = - freeQtyNeeded - (sameBookingTypeProduct?.OrderQty || 0); - if ( - remainingFreeQtyNeeded === otherBookingTypeProduct?.OrderQty - ) { - if (otherBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== otherBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === otherBookingTypeProduct.ProdId && - cartItem?.InwardDtlId === - otherBookingTypeProduct.InwardDtlId && - cartItem?.BookingTypeName === - otherBookingTypeProduct.BookingTypeName && - cartItem?.OrderRate === - otherBookingTypeProduct.OrderRate && - cartItem?.OfferMode && - cartItem?.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === otherBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - otherBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - otherBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - otherBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - Offer: cartItem.OrderQty * cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } else if ( - otherBookingTypeProduct?.OrderQty > remainingFreeQtyNeeded - ) { - if (otherBookingTypeFreeProduct) { - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === otherBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - otherBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - otherBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - otherBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + remainingFreeQtyNeeded, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty + remainingFreeQtyNeeded, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + remainingFreeQtyNeeded) * - cartItem.OrderRate, - }; - } else if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty - remainingFreeQtyNeeded, - ...calculateTaxAmounts({ - qty: cartItem.OrderQty - remainingFreeQtyNeeded, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - } else { - const remainingPaidQty = - otherBookingTypeProduct?.OrderQty - - remainingFreeQtyNeeded; - const newFreeProduct = { - ...otherBookingTypeProduct, - OrderQty: remainingFreeQtyNeeded, - ...calculateTaxAmounts({ - qty: remainingFreeQtyNeeded, - rate: otherBookingTypeProduct.OrderRate, - taxPercentage: otherBookingTypeProduct.TaxPercentage, - }), - Offer: - remainingFreeQtyNeeded * - otherBookingTypeProduct.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - localId: uuidv4(), - }; - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - OrderQty: remainingPaidQty, - ...calculateTaxAmounts({ - qty: remainingPaidQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - }; - } - return cartItem; - }); - updatedCart = [...updatedCart, newFreeProduct]; - } - } - } - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - ...(cartItem?.Offer > 0 && { - Offer: editedQty * cartItem.OrderRate, - }), - }; - } - return cartItem; - }); - dispatch(changeOrderCardDetails(updatedCart)); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId && - product?.OfferId === - (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeFreeProduct?.OfferMessage?.[0] - ?.OfferId) && - product?.OfferMode === - (sameBookingTypeFreeProduct?.OfferMode || - otherBookingTypeFreeProduct?.OfferMode) - ) { - return { - ...product, - FreeQty: finalOrderQty, - OverAllFreeQty: finalOrderQty, - RemainingQty: 0, - discount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeProduct?.OfferMessage?.[0] - ?.OfferId) && - offerProduct?.OfferMode === - (sameBookingTypeProduct?.OfferMode || - otherBookingTypeProduct?.OfferMode); - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty, - ActualOfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferAmount: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferValue: - finalOrderQty * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - FreeProductsList: updatedFreeProductsList, - UsedCount: finalOrderQty * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } else if (totalFreeQtyInCart < freeQtyNeeded) { - let updatedCart = [...CartOrderDetails]; - if (sameBookingTypeProduct) { - if (sameBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== sameBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === sameBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - sameBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - sameBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - sameBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === sameBookingTypeProduct) { - return { - ...cartItem, - Offer: - (cartItem.OrderQty + - sameBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } - - if (otherBookingTypeProduct) { - if (otherBookingTypeFreeProduct) { - updatedCart = updatedCart?.filter( - (cartItem) => cartItem !== otherBookingTypeProduct - ); - updatedCart = updatedCart?.map((cartItem) => { - if ( - cartItem.ProdId === otherBookingTypeProduct.ProdId && - cartItem.InwardDtlId === - otherBookingTypeProduct.InwardDtlId && - cartItem.BookingTypeName === - otherBookingTypeProduct.BookingTypeName && - cartItem.OrderRate === - otherBookingTypeProduct.OrderRate && - cartItem.OfferMode && - cartItem.Offer > 0 - ) { - return { - ...cartItem, - OrderQty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - ...calculateTaxAmounts({ - qty: - cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - Offer: - (cartItem.OrderQty + - otherBookingTypeProduct?.OrderQty) * - cartItem.OrderRate, - }; - } - return cartItem; - }); - } else { - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === otherBookingTypeProduct) { - return { - ...cartItem, - Offer: - otherBookingTypeProduct?.OrderQty * - cartItem.OrderRate, - OfferMode: isFreeProductApplicable?.OfferMode, - OfferType: isFreeProductApplicable?.OfferType, - OfferMessage: [ - { - OfferId: isFreeProductApplicable?.OfferId, - OfferName: isFreeProductApplicable?.OfferName, - OfferDescription: - isFreeProductApplicable?.OfferDescription, - }, - ], - }; - } - return cartItem; - }); - } - } - updatedCart = updatedCart?.map((cartItem) => { - if (cartItem === editedProduct) { - return { - ...cartItem, - OrderQty: editedQty, - ...calculateTaxAmounts({ - qty: editedQty, - rate: cartItem.OrderRate, - taxPercentage: cartItem.TaxPercentage, - }), - ...(cartItem?.Offer > 0 && { - Offer: editedQty * cartItem.OrderRate, - }), - }; - } - return cartItem; - }); - dispatch(changeOrderCardDetails(updatedCart)); - const remainingQty = freeQtyNeeded - totalFreeQtyInCart; - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId && - product?.OfferId === - (sameBookingTypeFreeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeFreeProduct?.OfferMessage?.[0] - ?.OfferId) && - product?.OfferMode === - (sameBookingTypeFreeProduct?.OfferMode || - otherBookingTypeFreeProduct?.OfferMode) - ) { - return { - ...product, - FreeQty: finalOrderQty - remainingQty, - OverAllFreeQty: finalOrderQty, - RemainingQty: remainingQty, - discount: - (finalOrderQty - remainingQty) * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - const updatedOfferAppliedProducts = OfferAppliedProducts?.map( - (offerProduct) => { - // Check if this offer product contains the edited product in its free products list - const hasMatchingFreeProduct = - offerProduct?.FreeProductsList?.some((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - // Also check main offer conditions - const isMatchingOffer = - offerProduct?.OfferId === - (sameBookingTypeProduct?.OfferMessage?.[0]?.OfferId || - otherBookingTypeProduct?.OfferMessage?.[0] - ?.OfferId) && - offerProduct?.OfferMode === - (sameBookingTypeProduct?.OfferMode || - otherBookingTypeProduct?.OfferMode); - - if (hasMatchingFreeProduct && isMatchingOffer) { - // Get loyalty points from the matching free product - const matchingFreeProduct = - offerProduct?.FreeProductsList?.find((freeProduct) => - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ) - ); - - const prodLoyaltyPoint = - matchingFreeProduct?.ProdVariantDetails?.[0] - ?.StockDetails?.[0]?.ProdLoyaltyPoint || 0; - - // Update the specific free product in the list - const updatedFreeProductsList = - offerProduct?.FreeProductsList?.map((freeProduct) => { - const isTargetFreeProduct = - freeProduct?.ProdVariantDetails?.some((variant) => - variant?.StockDetails?.some( - (stock) => - stock?.FreeInwardDtlId === - (sameBookingTypeProduct?.InwardDtlId || - otherBookingTypeProduct?.InwardDtlId) - ) - ); - - if (isTargetFreeProduct) { - return { - ...freeProduct, - FreeQty: finalOrderQty - remainingQty, - }; - } - return freeProduct; - }); - - return { - ...offerProduct, - ActualFreeQty: finalOrderQty - remainingQty, - ActualOfferAmount: - (finalOrderQty - remainingQty) * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferAmount: - (finalOrderQty - remainingQty) * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - OfferValue: - (finalOrderQty - remainingQty) * - (sameBookingTypeProduct?.OrderRate || - otherBookingTypeProduct?.OrderRate), - FreeProductsList: updatedFreeProductsList, - UsedCount: - (finalOrderQty - remainingQty) * prodLoyaltyPoint, - }; - } - - return offerProduct; - } - ); - dispatch( - changeFullOfferAppliedProducts(updatedOfferAppliedProducts) - ); - } - } else { - // just update the free product list - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice - ); - const updatedFreeProdList = FreeProdList?.map((product) => { - if ( - product?.ProdId === editedProduct?.ProdId && - product?.InwardDtlId === editedProduct?.InwardDtlId - ) { - return { - ...product, - OverAllFreeQty: finalOrderQty, - RemainingQty: finalOrderQty - product?.FreeQty, - discount: finalOrderQty * editedProduct?.OrderRate, - }; - } - return product; - }); - dispatch(ChangeFullFreeProductList(updatedFreeProdList)); - } - } - } - } else { - await handleNormalEditQuantity( - editedProduct, - editedProductIndex, - editedQty, - newPrice - ); } } }; - const handleNormalEditQuantity = async ( - editedProduct, - index, - qty, - newPrice = 0, - offerApply = false - ) => { - const fixedQty = Number(qty.toFixed(3)); - const updatedProduct = { - ...editedProduct, - OrderQty: fixedQty, - OrderRate: newPrice > 0 ? newPrice : editedProduct?.OrderRate, - ...calculateTaxAmounts({ - qty: qty, - rate: newPrice > 0 ? newPrice : editedProduct?.OrderRate, - taxPercentage: editedProduct?.TaxPercentage, - type: editedProduct?.Type, - product: editedProduct, - }), - PackageDtl: PackageDtl, - // ✅ FIXED: Proper conditional property assignment - ...(offerApply && { - Offer: qty * (newPrice > 0 ? newPrice : editedProduct?.OrderRate), - }), - }; - - if (hasOffer) { - const offers = validateOffers( - updatedProduct, - OverAllproductBasedOfferDatas, - CartOrderDetails, - TakAwayId, - DineinId - ); - if (!offers?.length) { - if (updatedProduct?.OfferType && updatedProduct?.Offer > 0) { - dispatch( - RemoveOfferAppliedProduct({ - ProdId: updatedProduct?.ProdId, - InwardDtlId: updatedProduct?.InwardDtlId, - OfferType: updatedProduct?.OfferType, - }) - ); - } - dispatch( - changeOrderCardDetails( - CartOrderDetails?.map((i) => - i?.InwardDtlId == updatedProduct?.InwardDtlId && - i?.BookingTypeName == updatedProduct?.BookingTypeName && - i?.localId === updatedProduct?.localId - ? { - ...updatedProduct, - Offer: 0, - OfferType: - updatedProduct?.Type === 'C' - ? updatedProduct?.OfferType - : null, - OfferMessage: null, - } - : i - ) - ) - ); - return; - } - - let bestOffer = null; - for (const offer of offers) { - if (!bestOffer || offer.OfferAmount > bestOffer.OfferAmount) { - bestOffer = offer; - } - } - - const UpdatedCartItemWithOffer = { - ...updatedProduct, - Offer: - bestOffer?.OfferMode === 'I' || bestOffer?.OfferMode === 'Q' - ? bestOffer?.OfferAmount || updatedProduct.Offer - : updatedProduct.Offer || bestOffer?.OfferAmount, - OfferType: updatedProduct?.OfferType || bestOffer?.OfferType, - OfferMessage: updatedProduct?.OfferMessage || bestOffer?.OfferMessage, - }; - - console.log(updatedProduct, 'updatedProduct'); - - const shouldRemove = (c) => - c.ProdId === updatedProduct.ProdId && - c.InwardDtlId === updatedProduct.InwardDtlId && - c.OrderRate === updatedProduct.OrderRate && - c.BookingTypeName === updatedProduct.BookingTypeName && - !c.SalesId && - ((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 updatedCartData = [UpdatedCartItemWithOffer, ...filteredCart]; - - if (bestOffer) { - dispatch(ChangeOfferAppliedProducts(bestOffer)); - } - - dispatch(changeOrderCardDetails(updatedCartData)); - } else { - const updatedData = [...CartOrderDetails]; - updatedData[index] = updatedProduct; - dispatch(changeOrderCardDetails(updatedData)); - } - }; - - const calculateTaxAmounts = ({ - qty, - rate, - taxPercentage, - type = null, - product = {}, - isOfferApply = false, - }) => { - const { OfferType = null, OfferPrice = 0 } = product; - const totalAmount = qty * rate; - const taxAmount = ( - (totalAmount * taxPercentage) / - (100 + taxPercentage) - ).toFixed(2); - const withoutTaxRate = (totalAmount - taxAmount).toFixed(2); - const offerValue = - type === 'C' - ? OfferType === 'F' - ? qty * OfferPrice - : (qty * rate * OfferPrice) / 100 - : null; - - return { - TotalAmt: - type === 'C' && OfferPrice > 0 - ? totalAmount - (offerValue || 0) - : totalAmount, - TaxAmt: parseFloat(taxAmount), - WithoutTaxRate: parseFloat(withoutTaxRate), - OfferValue: offerValue, - }; - }; - const CloseModal = () => { - props.handleEditQuantityCancel(); - setClearQuantity(false); - }; - const onComplete = useCallback(() => { - setMessageData(null); - setMessageType(null); - }, []); - const onRadioBtnChange = (data) => { - setRadioBtnSelection(data); - }; - const onPercentageSelectionChange = (data) => { - setPercentageSelection(data); - setEditedPrice(0); - formRef.current?.resetFields(); - setDisableSubmitButton(false); - }; - const PriceChangefun = (data) => { - const enteredDiscount = parseFloat(data?.target.value); - if (enteredDiscount) { - const sellingPrice = parseFloat(props.Productdata?.SellingPrice || 0); - const limit = parseFloat(props.Productdata?.DiscountLimit || 0); - const limitType = props.Productdata?.DiscountLimitType; - - if (limit === null || limit === undefined || limit === 0) { - if (PercentageSelection == 'Fixed') { - if (parseFloat(enteredDiscount) < parseFloat(sellingPrice)) { - // setEditedPrice(enteredDiscount); - setEditedPrice( - parseFloat(sellingPrice) - parseFloat(enteredDiscount) - ); - setDisableSubmitButton(true); - } else { - setMessageType('error'); - setMessageData('Please Give less than value for sell price'); - setDisableSubmitButton(false); - setEditedPrice(0); - formRef.current?.resetFields(); - } - } else { - if (parseFloat(enteredDiscount) < 100) { - let temperc = - (parseFloat(enteredDiscount) * parseFloat(sellingPrice)) / 100; - setEditedPrice(parseFloat(sellingPrice) - parseFloat(temperc)); - setDisableSubmitButton(true); - } else { - setMessageType('error'); - setMessageData('Please Give less than 100% '); - setEditedPrice(0); - setDisableSubmitButton(false); - formRef.current?.resetFields(); - } - } - return; - } - - let maxDiscount = 0; - if (limitType === 'F') { - maxDiscount = sellingPrice - limit; - } else if (limitType === 'P') { - const afterdiscountfullamount = (sellingPrice * limit) / 100; - maxDiscount = sellingPrice - afterdiscountfullamount; - } - - if (PercentageSelection == 'Fixed') { - if (parseFloat(enteredDiscount) < parseFloat(sellingPrice)) { - if (sellingPrice - enteredDiscount === maxDiscount) { - setEditedPrice( - parseFloat(sellingPrice) - parseFloat(enteredDiscount) - ); - setDisableSubmitButton(true); - return; - } - - if (sellingPrice - enteredDiscount < sellingPrice - maxDiscount) { - setMessageType('error'); - setMessageData( - `Discount amount should not exeed ₹ ${(sellingPrice - maxDiscount).toFixed(2)}` - ); - setEditedPrice(0); - setDisableSubmitButton(true); - formRef.current?.resetFields(); - setDisableSubmitButton(false); - return; - } - - setEditedPrice( - parseFloat(sellingPrice) - parseFloat(enteredDiscount) - ); - setDisableSubmitButton(true); - } else { - setMessageType('error'); - setMessageData('Please Give less than value for sell price'); - setDisableSubmitButton(false); - setEditedPrice(0); - formRef.current?.resetFields(); - } - } else { - if (parseFloat(enteredDiscount) < 100) { - const discountAmount = (sellingPrice * enteredDiscount) / 100; - if (discountAmount > maxDiscount) { - setMessageType('error'); - setMessageData( - `Discount % should not exeed above ${(maxDiscount / sellingPrice) * 100} %` - ); - setEditedPrice(0); - setDisableSubmitButton(false); - formRef.current?.resetFields(); - return; - } - - let temperc = - (parseFloat(enteredDiscount) * parseFloat(sellingPrice)) / 100; - setEditedPrice(parseFloat(sellingPrice) - parseFloat(temperc)); - setDisableSubmitButton(true); - } else { - setMessageType('error'); - setMessageData('Please Give less than 100 '); - setEditedPrice(0); - setDisableSubmitButton(false); - formRef.current?.resetFields(); - } - } - } else { - setDisableSubmitButton(false); - setEditedPrice(0); - formRef.current?.resetFields(); - } - }; - const SellingPriceChange = (data) => { - if (data?.target.value) { - const sellingPrice = parseFloat(props.Productdata?.SellingPrice || 0); - const limit = parseFloat(props.Productdata?.DiscountLimit || 0); - const limitType = props.Productdata?.DiscountLimitType; - const enteredDiscount = parseFloat(data?.target.value); - - if (limit === null || limit === undefined || limit === 0) { - if ( - parseFloat(enteredDiscount) < parseFloat(sellingPrice) || - parseFloat(enteredDiscount) === parseFloat(sellingPrice) - ) { - setEditedPrice(enteredDiscount); - setDisableSubmitButton(true); - } else { - setMessageType('error'); - setMessageData('Please Give less than value for sell price'); - setDisableSubmitButton(false); - setEditedPrice(0); - formRef.current?.resetFields(); - } - return; - } - - let maxDiscount = 0; - if (limitType === 'F') { - maxDiscount = limit; - } else if (limitType === 'P') { - const afterdiscountfullamount = (sellingPrice * limit) / 100; - maxDiscount = afterdiscountfullamount; - } - - if (enteredDiscount === maxDiscount) { - setEditedPrice(data?.target.value); - setDisableSubmitButton(true); - return; - } - - if (enteredDiscount < maxDiscount) { - setMessageType('error'); - setMessageData(`You cannot sell below ₹${maxDiscount.toFixed(2)}`); - setEditedPrice(0); - setDisableSubmitButton(false); - return; - } - setDisableSubmitButton(true); - setEditedPrice(data?.target.value); - } else { - setDisableSubmitButton(false); - setEditedPrice(0); - } - }; - - const AddPacking = async (data) => { - console.log(data, 'Cartdata'); - setPackageDtl(data || []); - }; - - const handleWeightCalculation = async (data) => { - const { price, quantity } = data; - setQuantity(quantity); - setEditedPrice(price); - await handleWeightSubmit(quantity, price); - }; - - const handleWeightSubmit = async (qty, price) => { - await dispatch(changeHoldOrderDtl(false)); - await dispatch(changePreviousOrderLength(CartOrderDetails?.length)); - let localId = props.Index; - let editedProductIndex = CartOrderDetails?.findIndex( - (e) => e?.localId == localId - ); - const editedProduct = { - ...CartOrderDetails[editedProductIndex], - OrderQty: qty - }; - - await handleEditQuantity(editedProduct, editedProductIndex, editedProduct.OrderRate, qty); - props.handleEditQuantityCancel(); - setClearQuantity(false); - }; - const isKg = - props?.Productdata?.Size == 1 && - ["KG", "KGS"].includes(props?.Productdata?.UomName?.toUpperCase()); - return ( -
- - - // - //
- } - open={EditOpen} - width={600} - footer={null} - children={ -
-
-
{ - if (RadioBtnSelection === 'Price' && !disableSubmitButton) { - return; - } - AddProductQuantity(values); - }} - > -
-
-

Item Name:

-
-
-

- {' '} - {ItemData?.ProdName} -

-
-
-
- {/* onRadioBtnChange(e)} - /> */} - {ItemData?.ScaleType !== 'weight' && ( - - )} - {PriceChangeaccess && ( - - )} - - - - {isKg && ()} - -
- - {RadioBtnSelection == 'Quantity' && ( - <> -
- - setQuantity(e.target.value)} - className="EditQuantity-Quantitybox" - /> - -
-
-
AddQuantity(1)}> - 1 -
-
AddQuantity(2)}> - 2 -
-
AddQuantity(3)}> - 3 -
- -
AddQuantity(4)}> - 4 -
-
AddQuantity(5)}> - 5 -
-
AddQuantity(6)}> - 6 -
- -
AddQuantity(7)}> - 7 -
-
AddQuantity(8)}> - 8 -
-
AddQuantity(9)}> - 9 -
-
-
AddQuantity(0)}> - 0 -
-
-
- - )} - {RadioBtnSelection == 'Price' && ( -
- - - {!RadioDetails && ( - { - await validateSafeInput(value); - - if (value && value.length > 10) { - return Promise.reject( - 'Selling Price should not exceed 10 characters' - ); - } - - return Promise.resolve(); - }, - }, - ]} - > - { - const cleanedValue = e.target.value.replace( - /[^0-9.]/g, - '' - ); - const parts = cleanedValue.split('.'); - e.target.value = - parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join('')}` - : cleanedValue; - }} - // isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.CustName ? true : false} - /> - - )} - -
- More -
- {RadioDetails && ( - <> -
- { - onPercentageSelectionChange(e); - }} - /> -
-
- - { - await validateSafeInput(value); // To block HTML tags & SQL keywords - return Promise.resolve(); - }, - }, - ]} - > - PriceChangefun(e)} - inputMode="decimal" - onInput={(e) => { - const cleanedValue = e.target.value.replace( - /[^0-9.]/g, - '' - ); - const parts = cleanedValue.split('.'); - e.target.value = - parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join('')}` - : cleanedValue; - }} - // isOnChange={formType == "edit" || formRef.current?.getFieldsValue()?.CustName ? true : false} - /> - - {/* PriceChangefun(e)} - className="EditQuantity-Pricebox" - /> */} - -
-
-
- {' '} - Price: {safeRound(editedPrice ? editedPrice : 0)} -
-
- - )} -
- )} - {RadioBtnSelection == 'Parcel' && ( - <> - AddPacking(data)} - PackageDtl={PackageDtl} - CurrentData={ItemData?.PackageDtl} - localId={ItemData?.localId} - /> - - )} - {RadioBtnSelection == 'AddWeight' && ( - <> - - - )} -
- {((RadioBtnSelection == 'Price' && disableSubmitButton) || - RadioBtnSelection == 'Quantity') && ( - } - > - )} -
- +
+
e.preventDefault()} + > +
+
+

Product: {itemData?.ProdName}

+

Variant: {itemData?.ProdVariantName}

+

Base Price: ₹{basePrice.toFixed(2)} per {itemData?.UomName || 'unit'}

- } - handleCancel={CloseModal} - /> +
+ + + { + const cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + const parts = cleanedValue.split('.'); + e.target.value = + parts.length > 2 + ? `${parts[0]}.${parts.slice(1).join('')}` + : cleanedValue; + }} + /> + + +
+
+ + + {calculatedQty > 0 ? calculatedQty.toFixed(3) : '0.000'} {itemData?.UomName || 'units'} + +
+ {calculatedQty > 0 && ( +
+ + ₹{parseFloat(enteredPrice || 0).toFixed(2)} +
+ )} +
+
+ } + /> +
+
); }; -export default BSBillingEditQuantity; + +export default WeightCalculatePrice; \ No newline at end of file From 585872eb8fbef6e4443910294880c00079b64f00 Mon Sep 17 00:00:00 2001 From: Srinath Date: Fri, 6 Feb 2026 17:25:26 +0530 Subject: [PATCH 12/46] create new component amt and qnt calculation --- .../BSBillingEditQuantity/WeightCalculatePrice.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx index f9e0d20..7b80bf0 100644 --- a/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx +++ b/src/Pages/BookingScreen/Components/BSBillingTables/BSBillingEditQuantity/WeightCalculatePrice.jsx @@ -131,4 +131,4 @@ const WeightCalculatePrice = ({ itemData, CartOrderDetails, onSubmit }) => { ); }; -export default WeightCalculatePrice; \ No newline at end of file +export default WeightCalculatePrice; \ No newline at end of file From 480f34bdf54f3bbc5edbe9de7cb4eb47c4a080cf Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 9 Feb 2026 10:11:39 +0530 Subject: [PATCH 13/46] StokcForm --- src/Pages/StockMaster/StockForm.jsx | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/Pages/StockMaster/StockForm.jsx b/src/Pages/StockMaster/StockForm.jsx index 882b2a7..d7e533a 100644 --- a/src/Pages/StockMaster/StockForm.jsx +++ b/src/Pages/StockMaster/StockForm.jsx @@ -1715,7 +1715,7 @@ const StockForm = ({ formType }) => { title: 'Amount per piece', dataIndex: 'OnePcsPrice', key: 'OnePcsPrice', - width: 70, + width: 125, editable: true, render: (_, record, index) => { return ( @@ -1751,7 +1751,7 @@ const StockForm = ({ formType }) => { title: 'Number of piece', dataIndex: 'NoOfPcs', key: 'NoOfPcs', - width: 70, + width: 125, editable: true, render: (_, record, index) => { return ( @@ -1784,7 +1784,7 @@ const StockForm = ({ formType }) => { title: 'Wholesale price', dataIndex: 'WhSalePrice', key: 'WhSalePrice', - width: 70, + width: 125, editable: true, render: (_, record) => { return ( @@ -1821,6 +1821,7 @@ const StockForm = ({ formType }) => { dataIndex: 'ManufDate', key: 'ManufDate', editable: true, + width: 100, render: (text, record, index) => { return ( { dataIndex: 'ExpDate', key: 'ExpDate', editable: true, + width: 100, render: (text, record, index) => { return ( { dataIndex: 'Hsn', key: 'Hsn', editable: true, - // width: 130, + width: 100, + align: 'center', render: (text, record, index) => { return ( { dataIndex: 'Model', key: 'Model', editable: true, + width: 100, + align: 'center', render: (text, record, index) => { return ( { title: 'Batch', dataIndex: 'Batch', key: 'Batch', + width: 100, + align: 'center', editable: true, render: (text, record, index) => { return ( @@ -1976,6 +1983,8 @@ const StockForm = ({ formType }) => { dataIndex: 'RejectedQty', key: 'RejectedQty', editable: true, + width: 100, + align: 'center', render: (text, record, index) => { return ( { dataIndex: 'Freeqty', key: 'Freeqty', editable: true, + width: 100, + align: 'center', render: (text, record) => { return ( Date: Mon, 9 Feb 2026 10:32:03 +0530 Subject: [PATCH 14/46] optimized code --- src/Pages/Product/ExcelUpload.jsx | 2593 ++++++++++------- src/Pages/Product/ProductList.jsx | 277 +- .../StockPriceUpdate/StockPriceUpdate.jsx | 1185 ++++---- .../StockPriceUpdate/StockPriceUpdate.scss | 76 + src/Services/findrerender.js | 26 + src/Styles/Product/excel.scss | 35 +- 6 files changed, 2492 insertions(+), 1700 deletions(-) create mode 100644 src/Pages/StockPriceUpdate/StockPriceUpdate.scss create mode 100644 src/Services/findrerender.js diff --git a/src/Pages/Product/ExcelUpload.jsx b/src/Pages/Product/ExcelUpload.jsx index 3aa26e7..367bd07 100644 --- a/src/Pages/Product/ExcelUpload.jsx +++ b/src/Pages/Product/ExcelUpload.jsx @@ -1,8 +1,8 @@ -import React, { useState, useRef, useEffect, useContext, useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { read, utils } from "xlsx"; -import ExcelJS from "exceljs"; -import { Table, Form, Input, Button, Tooltip, Modal, Select } from "antd"; +import React, { useState, useRef, useEffect, useContext, useMemo } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { read, utils } from 'xlsx'; +import ExcelJS from 'exceljs'; +import { Table, Form, Input, Button, Tooltip, Modal, Select } from 'antd'; import { emptyExcelData, excelDataSelector, @@ -10,36 +10,46 @@ import { excelFileErrorSelector, fileInputRefSelector, uploadExcel, -} from "../../Features/ExcelUploadPage/ExcelUploadPage.js"; -import { getProductData, onlineimages, postFieldSetup, getFieldSetupData } from "../../Features/ProductPage/ProductPage.js"; -import Imageupload from "../../Components/Forms/Upload.jsx"; -import { BiSolidFileExport } from "react-icons/bi"; -import { CiExport } from "react-icons/ci"; +} from '../../Features/ExcelUploadPage/ExcelUploadPage.js'; +import { + getProductData, + onlineimages, + postFieldSetup, + getFieldSetupData, +} from '../../Features/ProductPage/ProductPage.js'; +import Imageupload from '../../Components/Forms/Upload.jsx'; +import { BiSolidFileExport } from 'react-icons/bi'; +import { CiExport } from 'react-icons/ci'; -import { uploadImage } from "../../Features/upload/upload.js"; -import { TbWorldSearch } from "react-icons/tb"; -import { DefaultModal } from "../../Components/Modal/DefaultModal.jsx"; -import "../../Styles/Product/excel.scss"; -import { AiFillDelete } from "react-icons/ai"; -import upldimg from "../../Images/upldimg.png"; -import Excelupldimg from "../../Images/Excel.png"; -import { FiDelete, FiDownload } from "react-icons/fi"; -import { getSession } from "../../Services/Others.js"; -import * as XLSX from "xlsx"; -import { CiBoxList } from "react-icons/ci"; -import { ArrowRightOutlined, CloseCircleOutlined } from '@ant-design/icons' -import stringSimilarity from "string-similarity"; -import { getCommonAppPreference, ApplicationPreferences, getApplicationDetails } from "../../Features/BrachLogin/BranchLogin.js"; -import { MdOutlineAppRegistration } from "react-icons/md"; -import FormHeader from "../PageComponents/FormHeader.jsx"; -import { DropDowns } from "../../Components/Forms/DropDown.jsx"; -import Buttons from "../../Components/Forms/Buttons.jsx"; -import { IoClose } from "react-icons/io5"; -import { Messages } from "../../Components/Notifications/Messages.jsx"; +import { uploadImage } from '../../Features/upload/upload.js'; +import { TbWorldSearch } from 'react-icons/tb'; +import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx'; +import '../../Styles/Product/excel.scss'; +import { AiFillDelete } from 'react-icons/ai'; +import upldimg from '../../Images/upldimg.png'; +import Excelupldimg from '../../Images/Excel.png'; +import { FiDelete, FiDownload } from 'react-icons/fi'; +import { getSession } from '../../Services/Others.js'; +import * as XLSX from 'xlsx'; +import { CiBoxList } from 'react-icons/ci'; +import { ArrowRightOutlined, CloseCircleOutlined } from '@ant-design/icons'; +import stringSimilarity from 'string-similarity'; +import { + getCommonAppPreference, + ApplicationPreferences, + getApplicationDetails, +} from '../../Features/BrachLogin/BranchLogin.js'; +import { MdOutlineAppRegistration } from 'react-icons/md'; +import FormHeader from '../PageComponents/FormHeader.jsx'; +import { DropDowns } from '../../Components/Forms/DropDown.jsx'; +import Buttons from '../../Components/Forms/Buttons.jsx'; +import { IoClose } from 'react-icons/io5'; +import { Messages } from '../../Components/Notifications/Messages.jsx'; +import useWhyDidYouUpdate from '../../Services/findrerender.js'; const getApplicationSampleData = (appName) => { const sampleDataMap = { - 'Restaurant': { + Restaurant: { productName: 'Chicken Biryani', quantity: 1, uom: 'PLT', @@ -58,7 +68,7 @@ const getApplicationSampleData = (appName) => { uom: 'PLT', salesPrice: 120, category: 'Vegetarian', - subCategory: 'South Indian' + subCategory: 'South Indian', }, { productName: 'Paneer Butter Masala', @@ -66,11 +76,11 @@ const getApplicationSampleData = (appName) => { uom: 'PLT', salesPrice: 200, category: 'Vegetarian', - subCategory: 'North Indian' - } - ] + subCategory: 'North Indian', + }, + ], }, - 'Bakery': { + Bakery: { productName: 'Chocolate Cake', quantity: 1, uom: 'PCS', @@ -89,7 +99,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 45, category: 'Pastries', - subCategory: 'French Pastries' + subCategory: 'French Pastries', }, { productName: 'Whole Wheat Bread', @@ -97,9 +107,9 @@ const getApplicationSampleData = (appName) => { uom: 'LOAF', salesPrice: 35, category: 'Breads', - subCategory: 'Wheat Breads' - } - ] + subCategory: 'Wheat Breads', + }, + ], }, 'Electrical, Electronics and Computers': { productName: 'LED Bulb 9W', @@ -120,7 +130,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 299, category: 'Mobile Accessories', - subCategory: 'Chargers' + subCategory: 'Chargers', }, { productName: 'Extension Board 4 Socket', @@ -128,9 +138,9 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 350, category: 'Electrical Accessories', - subCategory: 'Power Strips' - } - ] + subCategory: 'Power Strips', + }, + ], }, 'Mobile Phone and Accessories': { productName: 'Smartphone Screen Guard', @@ -151,7 +161,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 149, category: 'Protection', - subCategory: 'Back Covers' + subCategory: 'Back Covers', }, { productName: 'Wireless Earbuds', @@ -159,11 +169,11 @@ const getApplicationSampleData = (appName) => { uom: 'PAIR', salesPrice: 1599, category: 'Audio', - subCategory: 'Bluetooth Earphones' - } - ] + subCategory: 'Bluetooth Earphones', + }, + ], }, - 'Grocery': { + Grocery: { productName: 'Basmati Rice', quantity: 1, uom: 'KG', @@ -182,7 +192,7 @@ const getApplicationSampleData = (appName) => { uom: 'KG', salesPrice: 120, category: 'Pulses', - subCategory: 'Arhar Dal' + subCategory: 'Arhar Dal', }, { productName: 'Refined Oil', @@ -190,9 +200,9 @@ const getApplicationSampleData = (appName) => { uom: 'LITER', salesPrice: 110, category: 'Cooking Oil', - subCategory: 'Sunflower Oil' - } - ] + subCategory: 'Sunflower Oil', + }, + ], }, 'Departmental Stores': { productName: 'Shampoo', @@ -213,7 +223,7 @@ const getApplicationSampleData = (appName) => { uom: 'TUBE', salesPrice: 45, category: 'Oral Care', - subCategory: 'Toothpaste' + subCategory: 'Toothpaste', }, { productName: 'Laundry Detergent', @@ -221,11 +231,11 @@ const getApplicationSampleData = (appName) => { uom: 'KG', salesPrice: 85, category: 'Household', - subCategory: 'Washing Powder' - } - ] + subCategory: 'Washing Powder', + }, + ], }, - 'Jewellery': { + Jewellery: { productName: 'Gold Ring', quantity: 1, uom: 'PCS', @@ -244,7 +254,7 @@ const getApplicationSampleData = (appName) => { uom: 'PAIR', salesPrice: 1200, category: 'Silver Jewellery', - subCategory: 'Earrings' + subCategory: 'Earrings', }, { productName: 'Diamond Pendant', @@ -252,9 +262,9 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 15000, category: 'Diamond Jewellery', - subCategory: 'Pendants' - } - ] + subCategory: 'Pendants', + }, + ], }, 'Lifestyle and Fashion': { productName: 'Cotton T-Shirt', @@ -275,7 +285,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 1299, category: 'Bottoms', - subCategory: 'Denim' + subCategory: 'Denim', }, { productName: 'Sneakers', @@ -283,9 +293,9 @@ const getApplicationSampleData = (appName) => { uom: 'PAIR', salesPrice: 2499, category: 'Footwear', - subCategory: 'Casual Shoes' - } - ] + subCategory: 'Casual Shoes', + }, + ], }, 'Salon, Spa and Beauty Parlour': { productName: 'Hair Cut Service', @@ -306,7 +316,7 @@ const getApplicationSampleData = (appName) => { uom: 'SERVICE', salesPrice: 800, category: 'Skin Care', - subCategory: 'Facial' + subCategory: 'Facial', }, { productName: 'Hair Color', @@ -314,11 +324,11 @@ const getApplicationSampleData = (appName) => { uom: 'SERVICE', salesPrice: 1200, category: 'Hair Services', - subCategory: 'Coloring' - } - ] + subCategory: 'Coloring', + }, + ], }, - 'Stationery': { + Stationery: { productName: 'A4 Paper Pack', quantity: 1, uom: 'PACK', @@ -337,7 +347,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 15, category: 'Writing Instruments', - subCategory: 'Pens' + subCategory: 'Pens', }, { productName: 'Notebook', @@ -345,11 +355,11 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 45, category: 'Books & Notebooks', - subCategory: 'Exercise Books' - } - ] + subCategory: 'Exercise Books', + }, + ], }, - 'Pharmacy': { + Pharmacy: { productName: 'Paracetamol 500mg', quantity: 1, uom: 'STRIP', @@ -368,7 +378,7 @@ const getApplicationSampleData = (appName) => { uom: 'BTL', salesPrice: 65, category: 'Healthcare', - subCategory: 'Sanitizers' + subCategory: 'Sanitizers', }, { productName: 'Bandage Roll', @@ -376,11 +386,11 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 25, category: 'Medical Supplies', - subCategory: 'First Aid' - } - ] + subCategory: 'First Aid', + }, + ], }, - 'Furniture': { + Furniture: { productName: 'Wooden Dining Table', quantity: 1, uom: 'PCS', @@ -399,7 +409,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 5500, category: 'Office Furniture', - subCategory: 'Chairs' + subCategory: 'Chairs', }, { productName: 'Queen Size Bed', @@ -407,11 +417,11 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 12000, category: 'Bedroom Furniture', - subCategory: 'Beds' - } - ] + subCategory: 'Beds', + }, + ], }, - 'Fruits': { + Fruits: { productName: 'Fresh Apples', quantity: 1, uom: 'KG', @@ -430,7 +440,7 @@ const getApplicationSampleData = (appName) => { uom: 'DOZEN', salesPrice: 60, category: 'Fresh Fruits', - subCategory: 'Tropical Fruits' + subCategory: 'Tropical Fruits', }, { productName: 'Orange Juice', @@ -438,11 +448,11 @@ const getApplicationSampleData = (appName) => { uom: 'LITER', salesPrice: 120, category: 'Fruit Juices', - subCategory: 'Fresh Juice' - } - ] + subCategory: 'Fresh Juice', + }, + ], }, - 'Textiles': { + Textiles: { productName: 'Cotton Fabric', quantity: 1, uom: 'METER', @@ -461,7 +471,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 2500, category: 'Ready Made', - subCategory: 'Sarees' + subCategory: 'Sarees', }, { productName: 'Woolen Shawl', @@ -469,9 +479,9 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 800, category: 'Accessories', - subCategory: 'Shawls' - } - ] + subCategory: 'Shawls', + }, + ], }, 'Computer Sales Shop': { productName: 'Gaming Laptop', @@ -492,7 +502,7 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 1200, category: 'Computer Accessories', - subCategory: 'Mouse' + subCategory: 'Mouse', }, { productName: 'SSD 500GB', @@ -500,33 +510,34 @@ const getApplicationSampleData = (appName) => { uom: 'PCS', salesPrice: 4500, category: 'Storage', - subCategory: 'Solid State Drive' - } - ] - } + subCategory: 'Solid State Drive', + }, + ], + }, }; // Return sample data for the specified app, or generic data if not found - return sampleDataMap[appName] || { - productName: 'Sample Product Name', - quantity: 1, - uom: 'PCS', - salesPrice: 100, - mrp: 100, - category: 'Sample Category', - subCategory: 'Sample Sub Category', - brand: 'Sample Brand', - variantName: 'Sample Variant Name', - tax: 'NIL - 0%', - hsn: '12345678', - additionalSamples: [] - }; + return ( + sampleDataMap[appName] || { + productName: 'Sample Product Name', + quantity: 1, + uom: 'PCS', + salesPrice: 100, + mrp: 100, + category: 'Sample Category', + subCategory: 'Sample Sub Category', + brand: 'Sample Brand', + variantName: 'Sample Variant Name', + tax: 'NIL - 0%', + hsn: '12345678', + additionalSamples: [], + } + ); }; - const allowedExcelTypes = [ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx - 'application/vnd.ms-excel' // .xls + 'application/vnd.ms-excel', // .xls ]; const ProductExcel = ({ @@ -545,13 +556,28 @@ const ProductExcel = ({ CategoryName1, Catconfigid, }) => { - + useWhyDidYouUpdate('ProductExcel', { + handleSubmit, + CategoryId, + CategoryNames, + SubcatId, + SubCatData, + AllBrandId, + Allbranddata, + Allbranddatanumfid, + Subcatnumfid, + Unit, + TaxDatas, + SuplierNames, + CategoryName1, + Catconfigid, + }); const dispatch = useDispatch(); const formRef = useRef(null); - const CompId = getSession("CompId") - const BranchId = getSession("BranchId") - const AppId = getSession("AppId"); - const UserId = getSession("UserId"); + const CompId = getSession('CompId'); + const BranchId = getSession('BranchId'); + const AppId = getSession('AppId'); + const UserId = getSession('UserId'); const fileInputRef = useRef(fileInputRefSelector); const excelData = useSelector(excelDataSelector); @@ -559,7 +585,7 @@ const ProductExcel = ({ const excelFileError = useSelector(excelFileErrorSelector); const ApplicationPreferenceData = useSelector(ApplicationPreferences); const productBulkUploadCatId = ApplicationPreferenceData?.find( - p => p?.PreferredCatName?.toLowerCase() === "product bulk upload" + (p) => p?.PreferredCatName?.toLowerCase() === 'product bulk upload' )?.PreferredCatId; const [appName, setAppName] = useState(null); @@ -569,7 +595,7 @@ const ProductExcel = ({ const [tableFieldPreferences, setTableFieldPreferences] = useState([]); const [worksheet, setWorksheet] = useState(null); const [worksheet1, setWorksheet1] = useState(null); - const [editdelete, seteditdelete] = useState(""); + const [editdelete, seteditdelete] = useState(''); const [fieldSetup, setFieldSetup] = useState(false); const [selectedImageIndex, setSelectedImageIndex] = useState(null); const [selectedProductName, setSelectedProductName] = useState(null); @@ -588,54 +614,57 @@ const ProductExcel = ({ const [ExcelData, setExcelData] = useState([]); const [originalUploadedRawData, setOriginalUploadedRawData] = useState([]); const [FieldValues, setFieldValues] = useState([]); - + const [OrginalData, setOrginalData] = useState([]); const handleTableChange = (pagination, filters, sorter) => { setCurrentPage(pagination.current); }; + console.log(tableFieldPreferences, 'tableFieldPreferences'); useEffect(() => { if (excelData && excelData?.length > 0) { let ExecelToJsConvertion = []; let slicedData = excelData?.slice(1); - let filteredData = slicedData?.filter(item => item?.[item?.length - 1]?.trim() !== "sample row"); + let filteredData = slicedData?.filter( + (item) => item?.[item?.length - 1]?.trim() !== 'sample row' + ); filteredData?.map((item, index) => { ExecelToJsConvertion.push({ key: index, - ProductName: item?.["0"], - Quantity: item?.["1"], - UOM: item?.["2"], - SellPrice: item?.["3"], - Category: item?.["4"], - SubCategory: item?.["5"], - Brand: item?.["6"], - ProductVariantName: item?.["7"] ? item?.["7"] : "Variant 1", - MRP: item?.["8"], - WhSalePrice: item?.["9"], - StockAvailable: item?.["10"] ? item?.["10"] : "No", - TokenAvailable: item?.["11"] ? item?.["11"] : "No", - ProductType: item?.["12"], - Tax: item?.["13"], - AutoGenerateQrcode: item?.["14"], - AddQrCode: item?.["15"], - OnePeiceAvailable: item?.["16"] ? item?.["16"] : "No", - OnePeicePrice: item?.["17"], - AutoGenerateOnePieceQrcode: item?.["18"] ? item?.["18"] : "No", - AutoGenerateOnePieceQrcodeNumber: item?.["19"], - CESS: item?.["20"], - HSN: item?.["21"], - PartNumber: item?.["22"], - Rack: item?.["23"], - ManufactureDate: item?.["24"], - ExpireDate: item?.["25"], - AvailableFrom: item?.["26"] ? item?.["26"] : "", - AvailableTo: item?.["27"] ? item?.["27"] : "", - Productimage: "", + ProductName: item?.['0'], + Quantity: item?.['1'], + UOM: item?.['2'], + SellPrice: item?.['3'], + Category: item?.['4'], + SubCategory: item?.['5'], + Brand: item?.['6'], + ProductVariantName: item?.['7'] ? item?.['7'] : 'Variant 1', + MRP: item?.['8'], + WhSalePrice: item?.['9'], + StockAvailable: item?.['10'] ? item?.['10'] : 'No', + TokenAvailable: item?.['11'] ? item?.['11'] : 'No', + ProductType: item?.['12'], + Tax: item?.['13'], + AutoGenerateQrcode: item?.['14'], + AddQrCode: item?.['15'], + OnePeiceAvailable: item?.['16'] ? item?.['16'] : 'No', + OnePeicePrice: item?.['17'], + AutoGenerateOnePieceQrcode: item?.['18'] ? item?.['18'] : 'No', + AutoGenerateOnePieceQrcodeNumber: item?.['19'], + CESS: item?.['20'], + HSN: item?.['21'], + PartNumber: item?.['22'], + Rack: item?.['23'], + ManufactureDate: item?.['24'], + ExpireDate: item?.['25'], + AvailableFrom: item?.['26'] ? item?.['26'] : '', + AvailableTo: item?.['27'] ? item?.['27'] : '', + Productimage: '', }); }); setDatas(ExecelToJsConvertion); // setExcelData(ExecelToJsConvertion); - // setOriginalUploadedRawData(ExecelToJsConvertion); + // setOriginalUploadedRawData(ExecelToJsConvertion); const style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = ` @@ -648,19 +677,20 @@ const ProductExcel = ({ return () => { document.head.removeChild(style); }; - } }, [excelData]); useEffect(() => { const fetchData = async () => { if (AppId) { - const response = await dispatch(getApplicationDetails({ AppId }))?.unwrap(); - setAppName(response?.data?.data?.[0]?.AppName) + const response = await dispatch( + getApplicationDetails({ AppId }) + )?.unwrap(); + setAppName(response?.data?.data?.[0]?.AppName); } }; fetchData(); - }, [AppId]) + }, [AppId]); useEffect(() => { // Call handleSubmit when Datas is updated @@ -670,11 +700,18 @@ const ProductExcel = ({ }, [Datas, handleSubmit]); // Automatically update preview data on mapping change - const mandatoryFields = ["ProductName", "Quantity", "UOM", "SellPrice", "Category"]; + const mandatoryFields = [ + 'ProductName', + 'Quantity', + 'UOM', + 'SellPrice', + 'Category', + ]; useEffect(() => { if (UploadedRawData.length > 0) { const updatedMappedData = UploadedRawData.map((row, index) => { const newRow = { key: index }; + newRow['isModified'] = row?.isModified; // ✅ Process mandatory fields (retain value even if unmapped) mandatoryFields.forEach((field) => { @@ -699,11 +736,10 @@ const ProductExcel = ({ } }); - // ✅ Process non-mandatory mapped fields Object.entries(fieldMapping).forEach(([field, header]) => { if (!mandatoryFields.includes(field)) { - newRow[field] = headers.includes(header) ? row[header] ?? '' : ''; + newRow[field] = headers.includes(header) ? (row[header] ?? '') : ''; } }); @@ -716,7 +752,7 @@ const ProductExcel = ({ const isMandatory = mandatoryFields.includes(mappedField); if (!isMapped && !(header in newRow)) { - newRow[header] = isMandatory ? row[header] ?? '' : ''; + newRow[header] = isMandatory ? (row[header] ?? '') : ''; } }); return newRow; @@ -727,7 +763,11 @@ const ProductExcel = ({ } }, [fieldMapping, UploadedRawData, headers]); - + useEffect(() => { + if (AppId && BranchId && CompId) { + handleExportBulkdata(); + } + }, [AppId, BranchId, CompId]); // useEffect(() => { // if (UploadedRawData.length > 0) { // const updatedMappedData = UploadedRawData.map((row, index) => { @@ -765,30 +805,43 @@ const ProductExcel = ({ useEffect(() => { getFieldSetup(); - }, [productBulkUploadCatId]) + }, [productBulkUploadCatId]); const getFieldSetup = async () => { try { - const response = await dispatch(getFieldSetupData({ AppId, CompId, BranchId, categoryId: productBulkUploadCatId, Type: 'EB' })).unwrap(); + const response = await dispatch( + getFieldSetupData({ + AppId, + CompId, + BranchId, + categoryId: productBulkUploadCatId, + Type: 'EB', + }) + ).unwrap(); if (response?.data?.statusCode === 1) { - console.log(response?.data?.data?.[0]?.ConfigDtl, "Field Setup Data"); - setSelectedFields(response?.data?.data?.[0]?.ConfigDtl?.filter(c => c.ConfigId && c.Access === 'Y')?.map(c => c.ConfigId) || []); - setTableFieldPreferences(response?.data?.data?.[0]?.ConfigDtl?.map(c => ({ - value: c.ConfigId, - label: c.ConfigName, - access: c.Access - })) || []); + console.log(response?.data?.data?.[0]?.ConfigDtl, 'Field Setup Data'); + setSelectedFields( + response?.data?.data?.[0]?.ConfigDtl?.filter( + (c) => c.ConfigId && c.Access === 'Y' + )?.map((c) => c.ConfigId) || [] + ); + setTableFieldPreferences( + response?.data?.data?.[0]?.ConfigDtl?.map((c) => ({ + value: c.ConfigId, + label: c.ConfigName, + access: c.Access, + })) || [] + ); setFieldValues(response?.data?.data?.[0]?.ConfigDtl); } else { - setMessageType("error"); - setMessageData("Failed to fetch field setup"); + setMessageType('error'); + setMessageData('Failed to fetch field setup'); } } catch (error) { console.error('Error fetching field setup:', error); } }; - const handleFileUpload = (e) => { const file = e.target.files[0]; const reader = new FileReader(); @@ -800,7 +853,7 @@ const ProductExcel = ({ title: 'Invalid File Type', content: 'Only Excel files (.xls, .xlsx) are allowed.', }); - handleCancelData() + handleCancelData(); } else { reader.readAsDataURL(file); uploadAndProcessExcel(file); @@ -814,43 +867,107 @@ const ProductExcel = ({ // Programmatically trigger the file input click event fileInputRef.current.click(); }; + const getFieldValue = (product, field) => { + const aliasField = FIELD_ALIAS[field]; + return normalize(product[field] ?? product[aliasField]); + }; + const normalize = (value) => { + // Empty / invalid values + if ( + value === undefined || + value === null || + value === '' || + value === 'NaN-NaN-NaN' + ) { + return ''; + } + + // Y / N flags + if (value === 'Y') return true; + if (value === 'N') return false; + + // Numbers (handles "150", 150, "0") + if ( + typeof value === 'number' || + (typeof value === 'string' && + value.trim() !== '' && + !Number.isNaN(Number(value))) + ) { + return Number(value); + } + + // Default string + return String(value).trim(); + }; + const hashProduct = (product) => + COMPARE_FIELDS.map((field) => getFieldValue(product, field)).join('§'); + function findModifiedProducts(originalData, updatedData) { + + if (!originalData?.length || !updatedData?.length) return []; + + const originalHashMap = new Map(); + + for (const product of originalData) { + if (!product.ProdId) continue; + originalHashMap.set(product.ProdId, hashProduct(product)); + } + + // Step 2: Compare updated products + const modifiedProducts = []; + + for (const product of updatedData) { + if (!product.ProdId) continue; + + const originalHash = originalHashMap.get(product.ProdId); + if (!originalHash) continue; // new product, not modified + + const updatedHash = hashProduct(product); + + if (originalHash !== updatedHash) { + modifiedProducts.push(product); + } + } + + return modifiedProducts; + } + const FIELD_ALIAS = { + 'Product Variant Name': 'Product Varient Name', + }; const uploadAndProcessExcel = (file) => { - const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); - const workbook = read(data, { type: "array" }); + const workbook = read(data, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; - const jsonData = utils.sheet_to_json(worksheet, { header: 1, raw: false, - dateNF: "DD/MM/YY", + dateNF: 'DD/MM/YY', }); const nonEmptyRows = jsonData.filter((row) => - row.some((cell) => cell !== "") + row.some((cell) => cell !== '') ); const header = nonEmptyRows[0]; const rows = nonEmptyRows.slice(1); const dateFields = [ - "Available From", - "Available To", - "Manufacture Date", - "Expire Date", - "Stock Date", + 'Available From', + 'Available To', + 'Manufacture Date', + 'Expire Date', + 'Stock Date', ]; function convertToDisplayFormat(dateString) { const date = new Date(dateString); - const day = date.getDate().toString().padStart(2, "0"); - const month = (date.getMonth() + 1).toString().padStart(2, "0"); + const day = date.getDate().toString().padStart(2, '0'); + const month = (date.getMonth() + 1).toString().padStart(2, '0'); const year = date.getFullYear().toString(); return `${day}-${month}-${year}`; } @@ -871,22 +988,40 @@ const ProductExcel = ({ if (jsonData.length > 0) { const extractedHeaders = Object.keys(formattedData[0]); - const filteredData = formattedData.filter((item) => - !Object.values(item)?.includes("sample row") + const filteredData = formattedData.filter( + (item) => !Object.values(item)?.includes('sample row') ); // ✅ Add default variant name if missing const updatedData = filteredData.map((item) => ({ ...item, - "Product Varient Name": - item["Product Varient Name"] === undefined ? "Variant 1" : item["Product Varient Name"], - "Available To": - item["Available To"] == "NaN-NaN-NaN" ? "" : item["Available To"], + 'Product Varient Name': + item['Product Varient Name'] === undefined + ? 'Variant 1' + : item['Product Varient Name'], + 'Available To': + item['Available To'] == 'NaN-NaN-NaN' ? '' : item['Available To'], + ProdId: item['ProdId'] || null, })); + // Detect modified products + + const modifiedProducts = findModifiedProducts(OrginalData, updatedData); + const modifiedIds = new Set(modifiedProducts.map((p) => p.ProdId)); + const originalIds = new Set(OrginalData?.map((p) => p.ProdId) || []); + const markedData = updatedData + .map((item) => ({ + ...item, + isModified: + modifiedIds.has(item.ProdId) || !originalIds.has(item.ProdId), + })) + .sort((a, b) => b.isModified - a.isModified); + setUploadedRawData(markedData); + console.log(modifiedProducts, 'modifiedProducts'); + // ✅ Set only once with final data setHeaders(extractedHeaders); - setUploadedRawData(updatedData); // Final, cleaned and enriched data + autoMapFields(extractedHeaders); dispatch(uploadExcel({ file, jsonData: nonEmptyRows })); setWorksheet(worksheet); @@ -900,7 +1035,6 @@ const ProductExcel = ({ setWorksheet1(worksheet1); setDatas(formattedData); // Update Datas state here // setExcelData(formattedData); - }; reader.readAsArrayBuffer(file); @@ -932,7 +1066,6 @@ const ProductExcel = ({ setDatas(newData1); setExcelData(newData1); - }; const handleimage = () => { @@ -949,10 +1082,10 @@ const ProductExcel = ({ const response = await fetch(selectedImage.image); const datas = await response.blob(); const metadata = { - type: "image/jpeg", + type: 'image/jpeg', }; - const file = new File([datas], "image.jpg", metadata); + const file = new File([datas], 'image.jpg', metadata); const uploadImgData = await dispatch(uploadImage(file)).unwrap(); @@ -976,46 +1109,46 @@ const ProductExcel = ({ }; const fieldOrder = [ - "Product Name", - "Quantity", - "UOM", - "Sales Price", - "MRP", - "WholeSale Price", - "Category", - "Sub Category", - "Brand", - "Product Variant Name", - "Stock Available", - "Token Available", - "Product Type", - "Tax", - "Auto Generate QRCode", - "Add Qr Code", - "One Piece Available", - "OnePiece Price", - "Auto Generate One Piece Qrcode", - "Auto Generate One Piece Qrcode Number", - "CESS", - "HSN", - "Part Number", - "Rack", - "Manufacture Date", - "Expire Date", - "Available From", - "Available To" + 'Product Name', + 'Quantity', + 'UOM', + 'Sales Price', + 'MRP', + 'WholeSale Price', + 'Category', + 'Sub Category', + 'Brand', + 'Product Variant Name', + 'Stock Available', + 'Token Available', + 'Product Type', + 'Tax', + 'Auto Generate QRCode', + 'Add Qr Code', + 'One Piece Available', + 'OnePiece Price', + 'Auto Generate One Piece Qrcode', + 'Auto Generate One Piece Qrcode Number', + 'CESS', + 'HSN', + 'Part Number', + 'Rack', + 'Manufacture Date', + 'Expire Date', + 'Available From', + 'Available To', ]; const sortPreferredFields = (fields) => { const fieldMap = {}; - fields.forEach(field => { + fields.forEach((field) => { fieldMap[field.ConfigName] = field; }); const sorted = []; - fieldOrder.forEach(name => { - if (fieldMap[name] && fieldMap[name].Access === "Y") { + fieldOrder.forEach((name) => { + if (fieldMap[name] && fieldMap[name].Access === 'Y') { sorted.push(fieldMap[name]); } }); @@ -1025,14 +1158,22 @@ const ProductExcel = ({ // Usage inside your Fielddatas const Fielddatas = async () => { - const res = await dispatch(getCommonAppPreference(AppId)).unwrap(); - const productbulkUploadCatId = res?.data?.data?.[0]?.PreferenceDetails?.find( - p => p?.PreferredCatName?.toLowerCase() === "product bulk upload" - )?.PreferredCatId; + const productbulkUploadCatId = + res?.data?.data?.[0]?.PreferenceDetails?.find( + (p) => p?.PreferredCatName?.toLowerCase() === 'product bulk upload' + )?.PreferredCatId; - const response = await dispatch(getFieldSetupData({ AppId, CompId, BranchId, categoryId: productbulkUploadCatId, Type: 'EB' })).unwrap(); + const response = await dispatch( + getFieldSetupData({ + AppId, + CompId, + BranchId, + categoryId: productbulkUploadCatId, + Type: 'EB', + }) + ).unwrap(); const productBulkUploadFields = response?.data?.data?.[0]?.ConfigDtl || []; const sortedFields = sortPreferredFields(productBulkUploadFields); @@ -1041,357 +1182,471 @@ const ProductExcel = ({ }; const handleDownload = async () => { - const workbook = new ExcelJS.Workbook(); - const worksheet = workbook.addWorksheet("Sheet1"); - const worksheet1 = workbook.addWorksheet("Sheet2"); + const worksheet = workbook.addWorksheet('Sheet1'); + const worksheet1 = workbook.addWorksheet('Sheet2'); const headerStyle = { font: { bold: true }, border: { - top: { style: "thin" }, - left: { style: "thin" }, - bottom: { style: "thin" }, - right: { style: "thin" }, + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' }, }, - alignment: { horizontal: "center", vertical: "middle" }, + alignment: { horizontal: 'center', vertical: 'middle' }, }; // Define all possible field configurations const sampleData = getApplicationSampleData(appName); - console.log(sampleData, "sampleData") + console.log(sampleData, 'sampleData'); const fieldConfigs = { - 'ProdName': { - header: "Product Name", - key: "ProdName", + ProdId: { + header: 'ProdId', + key: 'ProdId', + width: 15, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, + validation: null, + sampleValue: '', + headerColor: 'D3D3D3', + locked: true, + }, + ProdName: { + header: 'Product Name', + key: 'ProdName', width: 20, Height: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: sampleData?.productName || "Sample Product Name", - headerColor: "FF2929" + sampleValue: sampleData?.productName || 'Sample Product Name', + headerColor: 'FF2929', }, - 'Size': { - header: "Quantity", - key: "Size", + Size: { + header: 'Quantity', + key: 'Size', width: 10, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "custom", + type: 'custom', allowBlank: true, - formulae: ["ISNUMBER({COLUMN}{ROW})"], + formulae: ['ISNUMBER({COLUMN}{ROW})'], showErrorMessage: true, - errorTitle: "Validation Error", - error: "Please enter a Number.", + errorTitle: 'Validation Error', + error: 'Please enter a Number.', }, sampleValue: sampleData?.quantity || 1, - headerColor: "FF2929" + headerColor: 'FF2929', }, - 'UOM': { - header: "UOM", - key: "UOM", + UOM: { + header: 'UOM', + key: 'UOM', width: 10, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, - validation: { - type: "list", - allowBlank: true, - formulae: ['"' + (typeof Unit !== 'undefined' ? Unit.join(",") : "KGS,PCS,LITER") + '"'], + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, }, - sampleValue: sampleData?.uom || "KGS", - headerColor: "FF2929" - }, - 'SellPrice': { - header: "Sales Price", - key: "SellPrice", - width: 15, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, validation: { - type: "custom", + type: 'list', allowBlank: true, - formulae: ["ISNUMBER({COLUMN}{ROW})"], + formulae: [ + '"' + + (typeof Unit !== 'undefined' ? Unit.join(',') : 'KGS,PCS,LITER') + + '"', + ], + }, + sampleValue: sampleData?.uom || 'KGS', + headerColor: 'FF2929', + }, + SellPrice: { + header: 'Sales Price', + key: 'SellPrice', + width: 15, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, + validation: { + type: 'custom', + allowBlank: true, + formulae: ['ISNUMBER({COLUMN}{ROW})'], showErrorMessage: true, - errorTitle: "Validation Error", - error: "Please enter a Number.", + errorTitle: 'Validation Error', + error: 'Please enter a Number.', }, sampleValue: sampleData?.salesPrice || 100, - headerColor: "FF2929" + headerColor: 'FF2929', }, - 'ProdCat': { - header: "Category", - key: "ProdCat", + ProdCat: { + header: 'Category', + key: 'ProdCat', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, - validation: { - type: "list", - allowBlank: true, - formulae: ['"' + (typeof CategoryNames !== 'undefined' ? CategoryNames.join(",") : "Sample Category") + '"'], + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, }, - sampleValue: sampleData?.category || "Sample Category", - headerColor: "FF2929" + validation: { + type: 'list', + allowBlank: true, + formulae: [ + '"' + + (typeof CategoryNames !== 'undefined' + ? CategoryNames.join(',') + : 'Sample Category') + + '"', + ], + }, + sampleValue: sampleData?.category || 'Sample Category', + headerColor: 'FF2929', }, - 'ProdSubCat': { - header: "Sub Category", - key: "ProdSubCat", + ProdSubCat: { + header: 'Sub Category', + key: 'ProdSubCat', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: sampleData?.subCategory || "Sample Sub Category", - headerColor: "52c41a" + sampleValue: sampleData?.subCategory || 'Sample Sub Category', + headerColor: '52c41a', }, - 'Brand': { - header: "Brand", - key: "Brand", + Brand: { + header: 'Brand', + key: 'Brand', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: sampleData?.brand || "Sample Brand", - headerColor: "52c41a" + sampleValue: sampleData?.brand || 'Sample Brand', + headerColor: '52c41a', }, - 'ProdVarientName': { - header: "Product Variant Name", - key: "ProdVarientName", + ProdVarientName: { + header: 'Product Variant Name', + key: 'ProdVarientName', width: 20, Height: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: sampleData?.variantName || "Sample Variant Name", - headerColor: "52c41a" + sampleValue: sampleData?.variantName || 'Sample Variant Name', + headerColor: '52c41a', }, - 'MRP': { - header: "MRP", - key: "MRP", + MRP: { + header: 'MRP', + key: 'MRP', width: 10, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "custom", + type: 'custom', allowBlank: true, - formulae: ["ISNUMBER({COLUMN}{ROW})"], + formulae: ['ISNUMBER({COLUMN}{ROW})'], showErrorMessage: true, - errorTitle: "Validation Error", - error: "Please enter a Number.", + errorTitle: 'Validation Error', + error: 'Please enter a Number.', }, sampleValue: sampleData?.mrp || 100, - headerColor: "52c41a" + headerColor: '52c41a', }, - 'WhSalePrice': { - header: "WholeSale Price", - key: "WhSalePrice", + WhSalePrice: { + header: 'WholeSale Price', + key: 'WhSalePrice', width: 15, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "custom", + type: 'custom', allowBlank: true, - formulae: ["ISNUMBER({COLUMN}{ROW})"], + formulae: ['ISNUMBER({COLUMN}{ROW})'], showErrorMessage: true, - errorTitle: "Validation Error", - error: "Please enter a Number.", + errorTitle: 'Validation Error', + error: 'Please enter a Number.', }, sampleValue: 100, - headerColor: "52c41a" + headerColor: '52c41a', }, - 'StockAvailable': { - header: "Stock Available", - key: "StockAvailable", + StockAvailable: { + header: 'Stock Available', + key: 'StockAvailable', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "list", + type: 'list', allowBlank: true, formulae: ['"Yes,No"'], }, - sampleValue: "Choose Yes or No", - headerColor: "52c41a" + sampleValue: 'Choose Yes or No', + headerColor: '52c41a', }, - 'OfferPrice': { - header: "Token Available", - key: "OfferPrice", + OfferPrice: { + header: 'Token Available', + key: 'OfferPrice', width: 15, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "list", + type: 'list', allowBlank: true, formulae: ['"Yes,No"'], }, - sampleValue: "Choose Yes or No", - headerColor: "52c41a" + sampleValue: 'Choose Yes or No', + headerColor: '52c41a', }, - 'Supplier': { - header: "Product Type", - key: "Supplier", + Supplier: { + header: 'Product Type', + key: 'Supplier', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "list", + type: 'list', allowBlank: true, formulae: ['"Product"'], }, - sampleValue: "Product", - headerColor: "52c41a" + sampleValue: 'Product', + headerColor: '52c41a', }, - 'TaxId': { - header: "Tax", - key: "TaxId", + TaxId: { + header: 'Tax', + key: 'TaxId', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, - validation: { - type: "list", - allowBlank: true, - formulae: ['"' + (typeof TaxDatas !== 'undefined' ? TaxDatas.map(item => item.replace(/,/g, "").replace("-", "-").trim()).join(",") : "NIL - 0%") + '"'], + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, }, - sampleValue: "NIL - 0%", - headerColor: "52c41a" - }, - 'AutoGenerateQr': { - header: "Auto Generate Qrcode", - key: "AutoGenerateQr", - width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, validation: { - type: "list", + type: 'list', + allowBlank: true, + formulae: [ + '"' + + (typeof TaxDatas !== 'undefined' + ? TaxDatas.map((item) => + item.replace(/,/g, '').replace('-', '-').trim() + ).join(',') + : 'NIL - 0%') + + '"', + ], + }, + sampleValue: 'NIL - 0%', + headerColor: '52c41a', + }, + AutoGenerateQr: { + header: 'Auto Generate Qrcode', + key: 'AutoGenerateQr', + width: 20, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, + validation: { + type: 'list', allowBlank: true, formulae: ['"Yes,No"'], }, - sampleValue: "Choose Yes or No", - headerColor: "52c41a" + sampleValue: 'Choose Yes or No', + headerColor: '52c41a', }, - 'AddQrCode': { - header: "Add Qr Code", - key: "AddQrCode", + AddQrCode: { + header: 'Add Qr Code', + key: 'AddQrCode', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Sample Qr eg:12345", - headerColor: "52c41a" + sampleValue: 'Sample Qr eg:12345', + headerColor: '52c41a', }, - 'SpecialPrice': { - header: "One Piece Available", - key: "SpecialPrice", + SpecialPrice: { + header: 'One Piece Available', + key: 'SpecialPrice', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "list", + type: 'list', allowBlank: true, formulae: ['"Yes,No"'], }, - sampleValue: "Choose Yes or No", - headerColor: "52c41a" + sampleValue: 'Choose Yes or No', + headerColor: '52c41a', }, - 'OnePiecePrice': { - header: "OnePiece Price", - key: "StockAvailable", + OnePiecePrice: { + header: 'OnePiece Price', + key: 'StockAvailable', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "custom", + type: 'custom', allowBlank: true, - formulae: ["ISNUMBER({COLUMN}{ROW})"], + formulae: ['ISNUMBER({COLUMN}{ROW})'], showErrorMessage: true, - errorTitle: "Validation Error", - error: "Please enter a Number.", + errorTitle: 'Validation Error', + error: 'Please enter a Number.', }, - sampleValue: "OnePiecePrice", - headerColor: "52c41a" + sampleValue: 'OnePiecePrice', + headerColor: '52c41a', }, - 'AutoGenOnePieceQr': { - header: "Auto Generate One Piece Qrcode", - key: "StockDate", + AutoGenOnePieceQr: { + header: 'Auto Generate One Piece Qrcode', + key: 'StockDate', width: 30, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: { - type: "list", + type: 'list', allowBlank: true, formulae: ['"Yes,No"'], }, - sampleValue: "Choose Yes or No", - headerColor: "52c41a" + sampleValue: 'Choose Yes or No', + headerColor: '52c41a', }, - 'AutoGenOnePieceQrNum': { - header: "Auto Generate One Piece Qrcode Number", - key: "StockDate", + AutoGenOnePieceQrNum: { + header: 'Auto Generate One Piece Qrcode Number', + key: 'StockDate', width: 40, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Qr Number eg:ABC123", - headerColor: "52c41a" + sampleValue: 'Qr Number eg:ABC123', + headerColor: '52c41a', }, - 'CESS': { - header: "CESS", - key: "CESS", + CESS: { + header: 'CESS', + key: 'CESS', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Cess eg:0.5", - headerColor: "52c41a" + sampleValue: 'Cess eg:0.5', + headerColor: '52c41a', }, - 'HSNCode': { - header: "HSN", - key: "HSNCode", + HSNCode: { + header: 'HSN', + key: 'HSNCode', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Hsn Number eg:100190", - headerColor: "52c41a" + sampleValue: 'Hsn Number eg:100190', + headerColor: '52c41a', }, - 'PartNumber': { - header: "Part Number", - key: "PartNumber", + PartNumber: { + header: 'Part Number', + key: 'PartNumber', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Part Number eg:1234-5678", - headerColor: "52c41a" + sampleValue: 'Part Number eg:1234-5678', + headerColor: '52c41a', }, - 'Rack': { - header: "Rack", - key: "Rack", + Rack: { + header: 'Rack', + key: 'Rack', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, - sampleValue: "Rack Number eg:2200302", - headerColor: "52c41a" + sampleValue: 'Rack Number eg:2200302', + headerColor: '52c41a', }, - 'ManufDate': { - header: "Manufacture Date", - key: "ManufDate DATETIME", + ManufDate: { + header: 'Manufacture Date', + key: 'ManufDate DATETIME', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, sampleValue: new Date(), - headerColor: "52c41a" + headerColor: '52c41a', }, - 'ExpDate': { - header: "Expire Date", - key: "ExpDate DATETIME", + ExpDate: { + header: 'Expire Date', + key: 'ExpDate DATETIME', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, sampleValue: new Date(), - headerColor: "52c41a" + headerColor: '52c41a', }, - 'AvailableFrom': { - header: "Available From", - key: "AvailableFrom TIME", + AvailableFrom: { + header: 'Available From', + key: 'AvailableFrom TIME', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, sampleValue: new Date(), - headerColor: "52c41a" + headerColor: '52c41a', }, - 'AvailableTo': { - header: "Available To", - key: "AvailableTo TIME", + AvailableTo: { + header: 'Available To', + key: 'AvailableTo TIME', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, validation: null, sampleValue: new Date(), - headerColor: "52c41a" - } + headerColor: '52c41a', + }, }; function getExcelColumnLetter(colIndex) { - let temp = ""; - let letter = ""; + let temp = ''; + let letter = ''; while (colIndex > 0) { temp = (colIndex - 1) % 26; letter = String.fromCharCode(temp + 65) + letter; @@ -1400,44 +1655,44 @@ const ProductExcel = ({ return letter; } - const mandatoryFields = ["ProdName", "Size", "UOM", "SellPrice", "ProdCat"]; + const mandatoryFields = ['ProdName', 'Size', 'UOM', 'SellPrice', 'ProdCat']; const apiToInternalFieldMap = { - "Product Name": "ProdName", - "Quantity": "Size", - "UOM": "UOM", - "Sales Price": "SellPrice", - "MRP": "MRP", - "WholeSale Price": "WhSalePrice", - "Category": "ProdCat", - "Sub Category": "ProdSubCat", - "Brand": "Brand", - "Product Variant Name": "ProdVarientName", - "Token Available": "OfferPrice", - "Stock Available": "StockAvailable", - "Tax": "TaxId", - "Auto Generate QRCode": "AutoGenerateQr", - "Add Qr Code": "AddQrCode", - "One Piece Available": "SpecialPrice", - "OnePiece Price": "OnePiecePrice", - "Auto Generate One Piece Qrcode": "AutoGenOnePieceQr", - "Auto Generate One Piece Qrcode Number": "AutoGenOnePieceQrNum", - "CESS": "CESS", - "HSN": "HSNCode", - "Part Number": "PartNumber", - "Rack": "Rack", - "Manufacture Date": "ManufDate", - "Expire Date": "ExpDate", - "Available From": "AvailableFrom", - "Available To": "AvailableTo", - "Product Type": "Supplier" + 'Product Name': 'ProdName', + Quantity: 'Size', + UOM: 'UOM', + 'Sales Price': 'SellPrice', + MRP: 'MRP', + 'WholeSale Price': 'WhSalePrice', + Category: 'ProdCat', + 'Sub Category': 'ProdSubCat', + Brand: 'Brand', + 'Product Variant Name': 'ProdVarientName', + 'Token Available': 'OfferPrice', + 'Stock Available': 'StockAvailable', + Tax: 'TaxId', + 'Auto Generate QRCode': 'AutoGenerateQr', + 'Add Qr Code': 'AddQrCode', + 'One Piece Available': 'SpecialPrice', + 'OnePiece Price': 'OnePiecePrice', + 'Auto Generate One Piece Qrcode': 'AutoGenOnePieceQr', + 'Auto Generate One Piece Qrcode Number': 'AutoGenOnePieceQrNum', + CESS: 'CESS', + HSN: 'HSNCode', + 'Part Number': 'PartNumber', + Rack: 'Rack', + 'Manufacture Date': 'ManufDate', + 'Expire Date': 'ExpDate', + 'Available From': 'AvailableFrom', + 'Available To': 'AvailableTo', + 'Product Type': 'Supplier', }; // Define dependent relationships const dependentFieldMap = { - "Auto Generate QRCode": "Add Qr Code", - "One Piece Available": "OnePiece Price", - "Auto Generate One Piece Qrcode": "Auto Generate One Piece Qrcode Number" + 'Auto Generate QRCode': 'Add Qr Code', + 'One Piece Available': 'OnePiece Price', + 'Auto Generate One Piece Qrcode': 'Auto Generate One Piece Qrcode Number', }; // Step 1: Sort preferred fields @@ -1447,14 +1702,14 @@ const ProductExcel = ({ const preferredFieldKeys = []; const preferredFieldSet = new Set(); - sortedPreferredFields.forEach(field => { + sortedPreferredFields.forEach((field) => { const fieldName = field.ConfigName; const status = field.Access; // Skip dependent fields for now if (Object.values(dependentFieldMap).includes(fieldName)) return; - if (status === "Y") { + if (status === 'Y') { const internalKey = apiToInternalFieldMap[fieldName]; if (internalKey) { preferredFieldKeys.push(internalKey); @@ -1464,7 +1719,8 @@ const ProductExcel = ({ // If this field has a dependent field, and it's enabled, add dependent too const dependentFieldName = dependentFieldMap[fieldName]; if (dependentFieldName) { - const dependentInternalKey = apiToInternalFieldMap[dependentFieldName]; + const dependentInternalKey = + apiToInternalFieldMap[dependentFieldName]; if (dependentInternalKey) { preferredFieldKeys.push(dependentInternalKey); } @@ -1473,25 +1729,30 @@ const ProductExcel = ({ }); // Step 3: Merge Mandatory + Preferred (no duplicates) - const finalFieldKeys = [...mandatoryFields, ...preferredFieldKeys.filter(key => !mandatoryFields.includes(key))]; + const finalFieldKeys = [ + ...mandatoryFields, + ...preferredFieldKeys.filter((key) => !mandatoryFields.includes(key)), + ]; // Step 4: Map to ExcelJS column configs - const selectedColumns = finalFieldKeys.map(fieldKey => { - const config = fieldConfigs[fieldKey]; - if (!config) { - console.warn(`Field configuration not found for: ${fieldKey}`); - return null; - } - return config; - }).filter(Boolean); + const selectedColumns = finalFieldKeys + .map((fieldKey) => { + const config = fieldConfigs[fieldKey]; + if (!config) { + console.warn(`Field configuration not found for: ${fieldKey}`); + return null; + } + return config; + }) + .filter(Boolean); selectedColumns.push({ - header: "__isSampleRow", - key: "__isSampleRow", + header: '__isSampleRow', + key: '__isSampleRow', width: 10, // width can be any value - style: { font: { size: 1 }, alignment: { horizontal: "left" } }, - sampleValue: "sample row", // Mark sample row - headerColor: "FFFFFF" + style: { font: { size: 1 }, alignment: { horizontal: 'left' } }, + sampleValue: 'sample row', // Mark sample row + headerColor: 'FFFFFF', }); worksheet.columns = selectedColumns; @@ -1504,10 +1765,10 @@ const ProductExcel = ({ headerCell.style = { ...config.style, fill: { - type: "pattern", - pattern: "solid", - fgColor: { argb: config.headerColor } - } + type: 'pattern', + pattern: 'solid', + fgColor: { argb: config.headerColor }, + }, }; }); @@ -1530,8 +1791,10 @@ const ProductExcel = ({ let validation = { ...config.validation }; if (validation.formulae) { - validation.formulae = validation.formulae.map(formula => - formula.replace('{COLUMN}', columnLetter).replace('{ROW}', rowNumber.toString()) + validation.formulae = validation.formulae.map((formula) => + formula + .replace('{COLUMN}', columnLetter) + .replace('{ROW}', rowNumber.toString()) ); } @@ -1540,7 +1803,6 @@ const ProductExcel = ({ } }); - // Add empty rows for data entry for (let i = 1; i <= 1000; i++) { worksheet.addRow({}); @@ -1550,8 +1812,9 @@ const ProductExcel = ({ // First, unlock ALL cells in the worksheet for (let rowNum = 1; rowNum <= worksheet.rowCount; rowNum++) { const row = worksheet.getRow(rowNum); - row.eachCell({ includeEmpty: true }, (cell) => { - cell.protection = { locked: false }; + row.eachCell({ includeEmpty: true }, (cell, colNumber) => { + const config = selectedColumns[colNumber - 1]; + cell.protection = { locked: config?.locked || false }; }); } @@ -1566,353 +1829,436 @@ const ProductExcel = ({ // Protect the worksheet await worksheet.protect('', { - selectLockedCells: true, // Allow selecting locked cells (header/sample) - selectUnlockedCells: true, // Allow selecting unlocked cells (data rows) + selectLockedCells: true, // Allow selecting locked cells (header/sample) + selectUnlockedCells: true, // Allow selecting unlocked cells (data rows) formatCells: false, formatColumns: false, formatRows: false, insertColumns: false, insertRows: false, deleteColumns: false, - deleteRows: false + deleteRows: false, }); // Configure Sheet2 with all original columns and functionality worksheet1.columns = [ { - header: "Category Id", - key: "CategoryId", + header: 'Category Id', + key: 'CategoryId', width: 15, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Category Name", - key: "Category", + header: 'Category Name', + key: 'Category', width: 30, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "SUBCAT DATAS OF PARTICULAR CATEGORY", - key: "SDPC", + header: 'SUBCAT DATAS OF PARTICULAR CATEGORY', + key: 'SDPC', width: 180, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "SUBCAT ID", - key: "SubcayID", + header: 'SUBCAT ID', + key: 'SubcayID', width: 10, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Sub Category name", - key: "SubCategory", + header: 'Sub Category name', + key: 'SubCategory', width: 25, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "", - key: "", + header: '', + key: '', width: 5, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "SUBCAT NUMFID", - key: "SubcatnumfId", + header: 'SUBCAT NUMFID', + key: 'SubcatnumfId', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "", - key: "smallIcon", + header: '', + key: 'smallIcon', width: 5, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Brand ID", - key: "BrandId", + header: 'Brand ID', + key: 'BrandId', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Brand Name", - key: "Brandname", + header: 'Brand Name', + key: 'Brandname', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Brand NumfId", - key: "BrandnumfId", + header: 'Brand NumfId', + key: 'BrandnumfId', width: 20, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "", - key: "smallIcon", + header: '', + key: 'smallIcon', width: 5, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, { - header: "Brand Details", - key: "Branddetails", + header: 'Brand Details', + key: 'Branddetails', width: 150, - style: { ...headerStyle, font: { bold: true, color: { argb: "#000000" } } }, + style: { + ...headerStyle, + font: { bold: true, color: { argb: '#000000' } }, + }, }, ]; // Add data to Sheet2 for (let i = 1; i <= 100; i++) { worksheet1.addRow({ - CategoryId: "", - Category: "", - SDPC: "", - SubcayID: "", - SubCategory: "", - SubcatnumfId: "", - BrandId: "", - Brandname: "", - BrandnumfId: "", - Branddetails: "", + CategoryId: '', + Category: '', + SDPC: '', + SubcayID: '', + SubCategory: '', + SubcatnumfId: '', + BrandId: '', + Brandname: '', + BrandnumfId: '', + Branddetails: '', }); } // All the original dropdown and validation logic for Sheet2 const dropdownOptions = { - Option1: ["Yes", "No"], - Option2: ["Product"], - Option3: ["ValueX", "ValueY", "ValueZ"], + Option1: ['Yes', 'No'], + Option2: ['Product'], + Option3: ['ValueX', 'ValueY', 'ValueZ'], }; - const selectedOptionA = "Option1"; - const selectedOptionB = "Option2"; + const selectedOptionA = 'Option1'; + const selectedOptionB = 'Option2'; // Create category and brand data maps (original logic) const categoryDataMap = {}; if (typeof CategoryId !== 'undefined') { CategoryId.forEach((categoryId, index) => { - categoryDataMap[categoryId] = typeof SubCatData !== 'undefined' ? SubCatData[index] : ''; + categoryDataMap[categoryId] = + typeof SubCatData !== 'undefined' ? SubCatData[index] : ''; }); } const BrandDataMap = {}; if (typeof AllBrandId !== 'undefined') { AllBrandId.forEach((AllBrandId, index) => { - BrandDataMap[AllBrandId] = typeof SubCatData !== 'undefined' ? SubCatData[index] : ''; + BrandDataMap[AllBrandId] = + typeof SubCatData !== 'undefined' ? SubCatData[index] : ''; }); } // Apply all original Sheet2 validations and logic if (typeof CategoryId !== 'undefined') { - worksheet1.getColumn("A").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + CategoryId.join(",") + '"'; - const defaultCategoryId = CategoryId[rowNumber - 2]; - cell.value = defaultCategoryId; + worksheet1 + .getColumn('A') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + CategoryId.join(',') + '"'; + const defaultCategoryId = CategoryId[rowNumber - 2]; + cell.value = defaultCategoryId; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof CategoryNames !== 'undefined') { - worksheet1.getColumn("B").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + CategoryNames.join(",") + '"'; - const defaultCategoryName = CategoryNames[rowNumber - 2]; - cell.value = defaultCategoryName; + worksheet1 + .getColumn('B') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + CategoryNames.join(',') + '"'; + const defaultCategoryName = CategoryNames[rowNumber - 2]; + cell.value = defaultCategoryName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof SubcatId !== 'undefined') { - worksheet1.getColumn("D").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + SubcatId.join(",") + '"'; - const defaultCategorysubName = SubcatId[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('D') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + SubcatId.join(',') + '"'; + const defaultCategorysubName = SubcatId[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof SubCatData !== 'undefined') { - worksheet1.getColumn("E").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + SubCatData.join(",") + '"'; - const defaultCategorysubName = SubCatData[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('E') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + SubCatData.join(',') + '"'; + const defaultCategorysubName = SubCatData[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof Subcatnumfid !== 'undefined') { - worksheet1.getColumn("G").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + Subcatnumfid.join(",") + '"'; - const defaultCategorysubName = Subcatnumfid[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('G') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + Subcatnumfid.join(',') + '"'; + const defaultCategorysubName = Subcatnumfid[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof AllBrandId !== 'undefined') { - worksheet1.getColumn("I").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + AllBrandId.join(",") + '"'; - const defaultCategorysubName = AllBrandId[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('I') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + AllBrandId.join(',') + '"'; + const defaultCategorysubName = AllBrandId[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof Allbranddata !== 'undefined') { - worksheet1.getColumn("J").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + Allbranddata.join(",") + '"'; - const defaultCategorysubName = Allbranddata[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('J') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + Allbranddata.join(',') + '"'; + const defaultCategorysubName = Allbranddata[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } if (typeof Allbranddatanumfid !== 'undefined') { - worksheet1.getColumn("K").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const dynamicValidValues = '"' + Allbranddatanumfid.join(",") + '"'; - const defaultCategorysubName = Allbranddatanumfid[rowNumber - 2]; - cell.value = defaultCategorysubName; + worksheet1 + .getColumn('K') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const dynamicValidValues = '"' + Allbranddatanumfid.join(',') + '"'; + const defaultCategorysubName = Allbranddatanumfid[rowNumber - 2]; + cell.value = defaultCategorysubName; - cell.dataValidation = { - type: "list", - allowBlank: true, - formulae: [dynamicValidValues], - }; - } - }); + cell.dataValidation = { + type: 'list', + allowBlank: true, + formulae: [dynamicValidValues], + }; + } + }); } // Original complex logic for column C (SUBCAT DATAS) - worksheet1.getColumn("C").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const categoryId = worksheet1.getCell(`A${rowNumber}`).value; - if (categoryId !== null) { - const uniqueSubCategoryData = new Set(); - const matchedData = []; + worksheet1 + .getColumn('C') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const categoryId = worksheet1.getCell(`A${rowNumber}`).value; + if (categoryId !== null) { + const uniqueSubCategoryData = new Set(); + const matchedData = []; - worksheet1.getColumn("G").eachCell({ includeEmpty: true }, function (subCatCell, subCatRowNumber) { - if (subCatRowNumber > 1 && subCatCell.value === categoryId) { - const subCategoryName = worksheet1.getCell(`E${subCatRowNumber}`).value; - const subCatId = worksheet1.getCell(`D${subCatRowNumber}`).value; + worksheet1 + .getColumn('G') + .eachCell( + { includeEmpty: true }, + function (subCatCell, subCatRowNumber) { + if (subCatRowNumber > 1 && subCatCell.value === categoryId) { + const subCategoryName = worksheet1.getCell( + `E${subCatRowNumber}` + ).value; + const subCatId = worksheet1.getCell( + `D${subCatRowNumber}` + ).value; - const fullSubCategoryName = `${subCatId} - ${subCategoryName}`; + const fullSubCategoryName = `${subCatId} - ${subCategoryName}`; - uniqueSubCategoryData.add({ - subCategoryId: subCatId, - subCategoryName: subCategoryName, - }); + uniqueSubCategoryData.add({ + subCategoryId: subCatId, + subCategoryName: subCategoryName, + }); - const subCatData = categoryDataMap[categoryId] ? categoryDataMap[categoryId].subCatData : null; + const subCatData = categoryDataMap[categoryId] + ? categoryDataMap[categoryId].subCatData + : null; - const data = { - subCategoryId: subCatId, - subCategoryName: subCategoryName, - subCatData: subCatData, - }; - matchedData.push(data); - } - }); + const data = { + subCategoryId: subCatId, + subCategoryName: subCategoryName, + subCatData: subCatData, + }; + matchedData.push(data); + } + } + ); - cell.value = JSON.stringify(Array.from(uniqueSubCategoryData)); + cell.value = JSON.stringify(Array.from(uniqueSubCategoryData)); + } } - } - }); + }); // Original complex logic for column M (Brand Details) - worksheet1.getColumn("M").eachCell({ includeEmpty: true }, function (cell, rowNumber) { - if (rowNumber > 1) { - const SubcatId = worksheet1.getCell(`D${rowNumber}`).value; - if (SubcatId !== null) { - const uniqueSubCategoryData = new Set(); - const matchedData = []; + worksheet1 + .getColumn('M') + .eachCell({ includeEmpty: true }, function (cell, rowNumber) { + if (rowNumber > 1) { + const SubcatId = worksheet1.getCell(`D${rowNumber}`).value; + if (SubcatId !== null) { + const uniqueSubCategoryData = new Set(); + const matchedData = []; - worksheet1.getColumn("K").eachCell({ includeEmpty: true }, function (BrandCell, BrandRowNumber) { - if (BrandRowNumber > 1 && BrandCell.value === SubcatId) { - const BrandName = worksheet1.getCell(`J${BrandRowNumber}`).value; - const BrandId = worksheet1.getCell(`I${BrandRowNumber}`).value; + worksheet1 + .getColumn('K') + .eachCell( + { includeEmpty: true }, + function (BrandCell, BrandRowNumber) { + if (BrandRowNumber > 1 && BrandCell.value === SubcatId) { + const BrandName = worksheet1.getCell( + `J${BrandRowNumber}` + ).value; + const BrandId = worksheet1.getCell( + `I${BrandRowNumber}` + ).value; - const fullSubCategoryName = `${BrandId} - ${BrandName}`; + const fullSubCategoryName = `${BrandId} - ${BrandName}`; - uniqueSubCategoryData.add({ - BrandId: BrandId, - BrandName: BrandName, - }); + uniqueSubCategoryData.add({ + BrandId: BrandId, + BrandName: BrandName, + }); - const BrandData = BrandDataMap[SubcatId] ? BrandDataMap[SubcatId].BrandData : null; + const BrandData = BrandDataMap[SubcatId] + ? BrandDataMap[SubcatId].BrandData + : null; - const data = { - BrandId: BrandId, - BrandName: BrandName, - BrandData: BrandData, - }; - matchedData.push(data); - } - }); + const data = { + BrandId: BrandId, + BrandName: BrandName, + BrandData: BrandData, + }; + matchedData.push(data); + } + } + ); - cell.value = JSON.stringify(Array.from(uniqueSubCategoryData)); + cell.value = JSON.stringify(Array.from(uniqueSubCategoryData)); + } } - } - }); + }); // Generate and download the file const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { - type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); - const filename = "Product Data.xlsx"; + const filename = 'Product Data.xlsx'; - if (typeof window !== "undefined") { + if (typeof window !== 'undefined') { if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, filename); } else { - const downloadLink = document.createElement("a"); + const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = filename; downloadLink.click(); @@ -1927,15 +2273,15 @@ const ProductExcel = ({ // handleDownload(['ProdName', 'Size', 'UOM', 'SellPrice', 'ProdCat', 'Brand']); // More fields // Available field names: - // 'ProdName', 'Size', 'UOM', 'SellPrice', 'ProdCat', 'ProdSubCat', 'Brand', - // 'ProdVarientName', 'MRP', 'StockAvailable', 'OfferPrice', 'Supplier', 'TaxId', - // 'AutoGenerateQr', 'AddQrCode', 'SpecialPrice', 'OnePiecePrice', 'AutoGenOnePieceQr', - // 'AutoGenOnePieceQrNum', 'CESS', 'HSNCode', 'PartNumber', 'Rack', 'ManufDate', + // 'ProdName', 'Size', 'UOM', 'SellPrice', 'ProdCat', 'ProdSubCat', 'Brand', + // 'ProdVarientName', 'MRP', 'StockAvailable', 'OfferPrice', 'Supplier', 'TaxId', + // 'AutoGenerateQr', 'AddQrCode', 'SpecialPrice', 'OnePiecePrice', 'AutoGenOnePieceQr', + // 'AutoGenOnePieceQrNum', 'CESS', 'HSNCode', 'PartNumber', 'Rack', 'ManufDate', // 'ExpDate', 'AvailableFrom', 'AvailableTo' const handleFileSubmit = (e) => { e.preventDefault(); if (excelFile === null) { - excelFileError("Please select an Excel file."); + excelFileError('Please select an Excel file.'); } else { handleSubmit(Datas); } @@ -1946,33 +2292,32 @@ const ProductExcel = ({ }; const handleFieldSetupSubmit = async () => { - const postData = { - "AppId": AppId, - "CompId": CompId, - "BranchId": BranchId, - "Type": "EB", - "FormType": "Product", - "TypeId": productBulkUploadCatId, - "ConfigDtl": selectedFields?.map((field) => ({ - "ConfigId": field, - "Access": 'Y', + AppId: AppId, + CompId: CompId, + BranchId: BranchId, + Type: 'EB', + FormType: 'Product', + TypeId: productBulkUploadCatId, + ConfigDtl: selectedFields?.map((field) => ({ + ConfigId: field, + Access: 'Y', })), - "CreatedBy": UserId - } + CreatedBy: UserId, + }; const response = await dispatch(postFieldSetup(postData))?.unwrap(); if (response?.data?.statusCode === 1) { - setMessageType("success"); + setMessageType('success'); setMessageData(response?.data?.response); setFieldSetup(false); await getFieldSetup(); } else { - setMessageType("error"); - setMessageData("Failed to set up fields"); + setMessageType('error'); + setMessageData('Failed to set up fields'); } - } + }; const handleFieldSelect = (value) => { setSelectedFields((prev) => { @@ -1987,187 +2332,186 @@ const ProductExcel = ({ setSelectedFields((prev) => prev.filter((field) => field !== id)); }; - const handleCancelData = () => { dispatch(emptyExcelData()); if (fileInputRef.current) { - fileInputRef.current.value = ""; + fileInputRef.current.value = ''; } }; const columns = [ { - title: "Product Name", - dataIndex: "ProductName", - key: "ProductName", + title: 'Product Name', + dataIndex: 'ProductName', + key: 'ProductName', editable: true, }, { - title: "Qty", - dataIndex: "Quantity", - key: "Quantity", + title: 'Qty', + dataIndex: 'Quantity', + key: 'Quantity', editable: true, }, { - title: "UOM", - dataIndex: "UOM", - key: "UOM", + title: 'UOM', + dataIndex: 'UOM', + key: 'UOM', editable: true, }, { - title: "Sales Price", - dataIndex: "SellPrice", - key: "SellPrice", + title: 'Sales Price', + dataIndex: 'SellPrice', + key: 'SellPrice', editable: true, }, { - title: "Category", - dataIndex: "Category", - key: "Category", + title: 'Category', + dataIndex: 'Category', + key: 'Category', editable: true, }, { - title: "Sub Category", - dataIndex: "SubCategory", - key: "SubCategory", + title: 'Sub Category', + dataIndex: 'SubCategory', + key: 'SubCategory', editable: true, }, { - title: "Brand", - dataIndex: "Brand", - key: "Brand", + title: 'Brand', + dataIndex: 'Brand', + key: 'Brand', editable: true, }, { - title: "Variant Name", - dataIndex: "ProductVariantName", - key: "ProductVariantName", + title: 'Variant Name', + dataIndex: 'ProductVariantName', + key: 'ProductVariantName', editable: true, }, { - title: "MRP", - dataIndex: "MRP", - key: "MRP", + title: 'MRP', + dataIndex: 'MRP', + key: 'MRP', editable: true, }, { - title: "WholeSale Price", - dataIndex: "WhSalePrice", - key: "WhSalePrice", + title: 'WholeSale Price', + dataIndex: 'WhSalePrice', + key: 'WhSalePrice', editable: true, }, { - title: "Auto Qrcode", - dataIndex: "AutoGenerateQrcode", - key: "AutoGenerateQrcode", + title: 'Auto Qrcode', + dataIndex: 'AutoGenerateQrcode', + key: 'AutoGenerateQrcode', editable: true, }, { - title: "Add QrCode", - dataIndex: "AddQrCode", - key: "AddQrCode", + title: 'Add QrCode', + dataIndex: 'AddQrCode', + key: 'AddQrCode', editable: true, }, { - title: "Stock Available", - dataIndex: "StockAvailable", - key: "StockAvailable", + title: 'Stock Available', + dataIndex: 'StockAvailable', + key: 'StockAvailable', editable: true, }, { - title: "Token Available", - dataIndex: "TokenAvailable", - key: "TokenAvailable", + title: 'Token Available', + dataIndex: 'TokenAvailable', + key: 'TokenAvailable', editable: true, }, { - title: "One Piece Available", - dataIndex: "OnePieceAvailable", - key: "OnePieceAvailable", + title: 'One Piece Available', + dataIndex: 'OnePieceAvailable', + key: 'OnePieceAvailable', editable: true, }, { - title: "One Piece Price", - dataIndex: "OnePiecePrice", - key: "OnePiecePrice", + title: 'One Piece Price', + dataIndex: 'OnePiecePrice', + key: 'OnePiecePrice', editable: true, }, { - title: "Auto Gen One Piece Qr", - dataIndex: "AutoGenerateOnePieceQrcode", - key: "AutoGenerateOnePieceQrcode", + title: 'Auto Gen One Piece Qr', + dataIndex: 'AutoGenerateOnePieceQrcode', + key: 'AutoGenerateOnePieceQrcode', editable: true, }, { - title: "Auto Gen One Piece Qr No", - dataIndex: "AutoGenerateOnePieceQrcodeNumber", - key: "AutoGenerateOnePieceQrcodeNumber", + title: 'Auto Gen One Piece Qr No', + dataIndex: 'AutoGenerateOnePieceQrcodeNumber', + key: 'AutoGenerateOnePieceQrcodeNumber', editable: true, }, { - title: "Product Type", - dataIndex: "ProductType", - key: "ProductType", + title: 'Product Type', + dataIndex: 'ProductType', + key: 'ProductType', editable: true, }, { - title: "Tax", - dataIndex: "Tax", - key: "Tax", + title: 'Tax', + dataIndex: 'Tax', + key: 'Tax', editable: true, }, { - title: "Cess", - dataIndex: "CESS", - key: "CESS", + title: 'Cess', + dataIndex: 'CESS', + key: 'CESS', editable: true, }, { - title: "HSN", - dataIndex: "HSN", - key: "HSN", + title: 'HSN', + dataIndex: 'HSN', + key: 'HSN', editable: true, }, { - title: "Part Number", - dataIndex: "PartNumber", - key: "PartNumber", + title: 'Part Number', + dataIndex: 'PartNumber', + key: 'PartNumber', editable: true, }, { - title: "Rack", - dataIndex: "Rack", - key: "Rack", + title: 'Rack', + dataIndex: 'Rack', + key: 'Rack', editable: true, }, { - title: "Mfg Date", - dataIndex: "ManufactureDate", - key: "ManufactureDate", + title: 'Mfg Date', + dataIndex: 'ManufactureDate', + key: 'ManufactureDate', editable: true, }, { - title: "Exp Date", - dataIndex: "ExpireDate", - key: "ExpireDate", + title: 'Exp Date', + dataIndex: 'ExpireDate', + key: 'ExpireDate', editable: true, }, { - title: "Avl From", - dataIndex: "AvailableFrom", - key: "AvailableFrom", + title: 'Avl From', + dataIndex: 'AvailableFrom', + key: 'AvailableFrom', editable: true, }, { - title: "Avl To", - dataIndex: "AvailableTo", - key: "AvailableTo", + title: 'Avl To', + dataIndex: 'AvailableTo', + key: 'AvailableTo', editable: true, }, { - title: "Image", - dataIndex: "Productimage", - key: "Productimage", + title: 'Image', + dataIndex: 'Productimage', + key: 'Productimage', render: (ProdImage, record, index) => { const Img = ProdImage; return ( @@ -2176,7 +2520,7 @@ const ProductExcel = ({ {record.Productimage} ) : ( <> @@ -2190,7 +2534,7 @@ const ProductExcel = ({ ? onlineImage : record.Productimage ? record.Productimage - : "" + : '' } listType="picture-card" // onlineImage={onlineImage?onlineImage:""} @@ -2202,7 +2546,7 @@ const ProductExcel = ({ addOnlineImage(record, index)} /> @@ -2215,7 +2559,6 @@ const ProductExcel = ({ }, ]; - const column = columns?.map((col) => { if (!col.editable) { return col; @@ -2223,7 +2566,7 @@ const ProductExcel = ({ let onClickHandler = null; - if (editdelete === "Delete") { + if (editdelete === 'Delete') { onClickHandler = (record) => removeFromTable(record); } @@ -2243,7 +2586,6 @@ const ProductExcel = ({ const EditableContext = React.createContext(null); const EditableRow = ({ index, dataIndex, ...props }) => { - const [form] = Form.useForm(); return (
@@ -2328,18 +2670,20 @@ const ProductExcel = ({ }; const handleSave = (row) => { - const newDatas = [...Datas]; - const item = newDatas.filter(item => item.key === row.key); + const item = newDatas.filter((item) => item.key === row.key); // const item = newDatas[index]; const UpdatedData = { ProductName: row?.ProductName, - ProductVariantName: row?.ProductVariantName ? row?.ProductVariantName : "Variant 1", + ProductVariantName: row?.ProductVariantName + ? row?.ProductVariantName + : 'Variant 1', Quantity: row?.Quantity, UOM: row?.UOM, MRP: row?.MRP, + isModified: true, WhSalePrice: row?.WhSalePrice, SellPrice: row?.SellPrice, Category: row?.Category, @@ -2366,7 +2710,6 @@ const ProductExcel = ({ AvailableTo: row?.AvailableTo, Productimage: row?.Productimage, key: row?.key, - }; newDatas.splice(item?.[0]?.key, 1, { ...item?.[0], @@ -2377,10 +2720,10 @@ const ProductExcel = ({ }; const handlechange22 = (index) => { - if (editdelete === "Delete") { - seteditdelete(""); + if (editdelete === 'Delete') { + seteditdelete(''); } else { - seteditdelete("Delete"); + seteditdelete('Delete'); } }; @@ -2396,91 +2739,175 @@ const ProductExcel = ({ }; const handleExportData = async () => { - setLoading(true) - let response = await dispatch(getProductData({ CompId: CompId, BranchId: BranchId, AppId: AppId })).unwrap(); + setLoading(true); + let response = await dispatch( + getProductData({ CompId: CompId, BranchId: BranchId, AppId: AppId }) + ).unwrap(); if (response?.data?.statusCode == 1 && response?.data?.data?.length > 0) { - const formattedData = response?.data?.data?.map(item => { + const formattedData = response?.data?.data?.map((item) => { return { - "Product Name": item.ProdName, - "Product Variant Name": item.ProdVarientName, - "Quantity": item.Size, - "UOM": item.UomName, - "MRP": item.MRP, - "WholeSale Price": item.WhSalePrice, - "Sales Price": item.SellPrice, - "Category": item.CategoryName, - "Sub Category": item.SubCategoryName, - "Brand": item.BrandName, - "Auto Generate Qrcode": item.AutoGenerateQr ? item.AutoGenerateQr : "N", - "Add Qr Code": item.QRCode, - "Stock Available": item.StockAvailable ? item.StockAvailable : "N", - "Token Available": item.TokenAvailable ? item.TokenAvailable : "N", - "One Piece Available": item.OnePcsAvailable ? item.OnePcsAvailable : "N", - "One Piece Price": item.OnePcsPrice, - "Auto Generate One Piece Qrcode": item.AutoGenerateSingleQr ? item.AutoGenerateSingleQr : "N", - "Auto Generate One Piece Qrcode Number": item.OnePcQR, - "Product Type": item.ProdTypeName ? item.ProdTypeName : "Product", - "Tax": `${item.TaxName || "NIL"} - ${item.TaxPercentage || 0}%`, // Ensures a valid tax format - "CESS": item.CESS, - "HSN": item.HSNCode, - "Part Number": item.PartNumber, - "Rack": item.Rack, - "Manufacture Date": null, - "Expire Date": null, - "Available From": item.AvailableFrom != "00:00:00" ? item.AvailableFrom : null, - "Available To": item.AvailableTo != "00:00:00" ? item.AvailableTo : null + ProdId: item.ProdId, + 'Product Name': item.ProdName, + 'Product Variant Name': item.ProdVarientName, + Quantity: item.Size, + UOM: item.UomName, + MRP: item.MRP, + 'WholeSale Price': item.WhSalePrice, + 'Sales Price': item.SellPrice, + Category: item.CategoryName, + 'Sub Category': item.SubCategoryName, + Brand: item.BrandName, + 'Auto Generate Qrcode': item.AutoGenerateQr + ? item.AutoGenerateQr + : 'N', + 'Add Qr Code': item.QRCode, + 'Stock Available': item.StockAvailable ? item.StockAvailable : 'N', + 'Token Available': item.TokenAvailable ? item.TokenAvailable : 'N', + 'One Piece Available': item.OnePcsAvailable + ? item.OnePcsAvailable + : 'N', + 'One Piece Price': item.OnePcsPrice, + 'Auto Generate One Piece Qrcode': item.AutoGenerateSingleQr + ? item.AutoGenerateSingleQr + : 'N', + 'Auto Generate One Piece Qrcode Number': item.OnePcQR, + 'Product Type': item.ProdTypeName ? item.ProdTypeName : 'Product', + Tax: `${item.TaxName || 'NIL'} - ${item.TaxPercentage || 0}%`, + CESS: item.CESS, + HSN: item.HSNCode, + 'Part Number': item.PartNumber, + Rack: item.Rack, + 'Manufacture Date': null, + 'Expire Date': null, + 'Available From': + item.AvailableFrom != '00:00:00' ? item.AvailableFrom : null, + 'Available To': + item.AvailableTo != '00:00:00' ? item.AvailableTo : null, }; }); - const ws = XLSX.utils.json_to_sheet(formattedData); + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('Products'); - // Create a new workbook and append the worksheet - const wb = XLSX.utils.book_new(); - XLSX.utils.book_append_sheet(wb, ws, "Products"); - setLoading(false) - // Trigger the file download - XLSX.writeFile(wb, "Product_Data.xlsx"); + worksheet.columns = Object.keys(formattedData[0]).map((key) => ({ + header: key, + key: key, + width: 20, + })); + formattedData.forEach((row) => worksheet.addRow(row)); + + worksheet.eachRow((row, rowNumber) => { + row.eachCell((cell, colNumber) => { + cell.protection = { locked: colNumber === 1 }; + }); + }); + + await worksheet.protect('', { + selectLockedCells: true, + selectUnlockedCells: true, + }); + + const buffer = await workbook.xlsx.writeBuffer(); + const blob = new Blob([buffer], { + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + const downloadLink = document.createElement('a'); + downloadLink.href = window.URL.createObjectURL(blob); + downloadLink.download = 'Product_Data.xlsx'; + downloadLink.click(); + + setLoading(false); + } else { + setLoading(false); + setMessage(true); } - else { - setLoading(false) - setMessage(true) + }; + + const handleExportBulkdata = async () => { + let response = await dispatch( + getProductData({ CompId: CompId, BranchId: BranchId, AppId: AppId }) + ).unwrap(); + if (response?.data?.statusCode == 1 && response?.data?.data?.length > 0) { + const formattedData = response?.data?.data?.map((item) => { + return { + ProdId: item.ProdId, + 'Product Name': item.ProdName, + 'Product Variant Name': item.ProdVarientName, + Quantity: item.Size, + UOM: item.UomName, + MRP: item.MRP, + 'WholeSale Price': item.WhSalePrice, + 'Sales Price': item.SellPrice, + Category: item.CategoryName, + 'Sub Category': item.SubCategoryName, + Brand: item.BrandName, + 'Auto Generate Qrcode': item.AutoGenerateQr + ? item.AutoGenerateQr + : 'N', + 'Add Qr Code': item.QRCode, + 'Stock Available': item.StockAvailable ? item.StockAvailable : 'N', + 'Token Available': item.TokenAvailable ? item.TokenAvailable : 'N', + 'One Piece Available': item.OnePcsAvailable + ? item.OnePcsAvailable + : 'N', + 'One Piece Price': item.OnePcsPrice, + 'Auto Generate One Piece Qrcode': item.AutoGenerateSingleQr + ? item.AutoGenerateSingleQr + : 'N', + 'Auto Generate One Piece Qrcode Number': item.OnePcQR, + 'Product Type': item.ProdTypeName ? item.ProdTypeName : 'Product', + Tax: `${item.TaxName || 'NIL'} - ${item.TaxPercentage || 0}%`, + CESS: item.CESS, + HSN: item.HSNCode, + 'Part Number': item.PartNumber, + Rack: item.Rack, + 'Manufacture Date': null, + 'Expire Date': null, + 'Available From': + item.AvailableFrom != '00:00:00' ? item.AvailableFrom : null, + 'Available To': + item.AvailableTo != '00:00:00' ? item.AvailableTo : null, + }; + }); + + setOrginalData(formattedData); } - } + }; const requiredFields = [ - "ProductName", - "ProductVariantName", - "Quantity", - "UOM", - "MRP", - "SellPrice", - "WhSalePrice", - "Category", - "SubCategory", - "Brand", - "StockAvailable", - "TokenAvailable", - "ProductType", - "Tax", - "AutoGenerateQrcode", - "AddQrCode", - "OnePieceAvailable", - "OnePiecePrice", - "AutoGenerateOnePieceQrcode", - "AutoGenerateOnePieceQrcodeNumber", - "CESS", - "HSN", - "PartNumber", - "Rack", - "ManufactureDate", - "ExpireDate", - "AvailableFrom", - "AvailableTo" + 'ProductName', + 'ProductVariantName', + 'Quantity', + 'UOM', + 'MRP', + 'SellPrice', + 'WhSalePrice', + 'Category', + 'SubCategory', + 'Brand', + 'StockAvailable', + 'TokenAvailable', + 'ProductType', + 'Tax', + 'AutoGenerateQrcode', + 'AddQrCode', + 'OnePieceAvailable', + 'OnePiecePrice', + 'AutoGenerateOnePieceQrcode', + 'AutoGenerateOnePieceQrcodeNumber', + 'CESS', + 'HSN', + 'PartNumber', + 'Rack', + 'ManufactureDate', + 'ExpireDate', + 'AvailableFrom', + 'AvailableTo', ]; - const enhancedColumns = columns.map((col) => { - if (col.dataIndex === "Productimage") return col; + const enhancedColumns = column.map((col) => { + if (col.dataIndex === 'Productimage') return col; // Get all used fields *except* the current column (to allow remap) const usedFields = Object.entries(fieldMapping) @@ -2488,24 +2915,31 @@ const ProductExcel = ({ .map(([, value]) => value); // Fields left for dropdown (excluding already selected ones) - const availableHeaders = headers?.filter(h => !usedFields?.includes(h) && h !== "__isSampleRow"); + const availableHeaders = headers?.filter( + (h) => !usedFields?.includes(h) && h !== '__isSampleRow' + ); const isMapped = !!fieldMapping[col.dataIndex]; return { ...col, title: ( -
+
{col.title} {!isMapped && ( - - Not mapped - + Not mapped )}
-
+
- Upload Sheet + + {' '} + Upload Sheet{' '} +
@@ -2759,14 +3274,16 @@ const ProductExcel = ({ )} {excelFileError && ( -
+
{excelFileError}
)}
-
- +
{excelData && excelData?.length > 0 ? ( + record.isModified ? 'modified-row' : 'old-row' + } >
- ) : - ( -

- )} + ) : ( +

+ )}
-
- +
{/*
@@ -2790,23 +3316,23 @@ const ProductExcel = ({
*/} - - - - - {excelData && excelData?.length > 0 && + {excelData && excelData?.length > 0 && (
- + Remove File - -
- } - + )}
- +
@@ -2824,11 +3352,16 @@ const ProductExcel = ({ label="Select fields" // valueData={selectedFields} onChangeFunction={handleFieldSelect} - options={tableFieldPreferences?.filter(p => !selectedFields?.some(s => s === p.value))} /> + options={tableFieldPreferences?.filter( + (p) => !selectedFields?.some((s) => s === p.value) + )} + />
{selectedFields - ?.map((id) => tableFieldPreferences?.find((p) => p.value === id)) + ?.map((id) => + tableFieldPreferences?.find((p) => p.value === id) + ) .filter(Boolean) .map((field) => (
@@ -2857,7 +3390,6 @@ const ProductExcel = ({ />
- {imagedata?.map((item, index) => (
setSelectedImage(item)} > - no image + no image
))}
@@ -2883,7 +3419,6 @@ const ProductExcel = ({ handleSubmit={submitimage} handleCancel={handleimage} > -
key !== field) .map(([, value]) => value); - const availableHeaders = headers?.filter(header => !usedHeaders?.includes(header)); + const availableHeaders = headers?.filter( + (header) => !usedHeaders?.includes(header) + ); return (
@@ -2907,7 +3444,9 @@ const ProductExcel = ({ style={{ width: '100%' }} placeholder="Select column" value={fieldMapping[field] || undefined} - clearIcon={} + clearIcon={ + + } onChange={(value) => { setFieldMapping((prev) => { const updated = { ...prev }; @@ -2931,9 +3470,7 @@ const ProductExcel = ({ })}
- ); - }; export default ProductExcel; diff --git a/src/Pages/Product/ProductList.jsx b/src/Pages/Product/ProductList.jsx index abd3608..37fc604 100644 --- a/src/Pages/Product/ProductList.jsx +++ b/src/Pages/Product/ProductList.jsx @@ -2029,125 +2029,190 @@ const ProductList = () => { formRef?.current?.resetFields(); }; - const handleCancel = () => { + + + + const handleResetExcelData = useCallback(() => { + dispatch(emptyExcelData()); + }, []); + + const handleCancel = useCallback(() => { setOpenExcel(false); handleResetExcelData(); - }; + }, [handleResetExcelData]); - const openModal = () => { + const openModal = useCallback(() => { setOpenExcel(true); - }; - - const handleResetExcelData = () => { - dispatch(emptyExcelData()); - }; - - const handleSubmitbulk = (excelData) => { + }, []); + const handleSubmitbulk = useCallback((excelData) => { setExceldatasubmit(excelData?.filter((e) => e?.isModified)); - }; + }, []); - const handleSubmit = async () => { + const handleSubmit = useCallback(async () => { setBulkpost(true); - let FilterData = Exceldatasubmit?.filter((a) => a['ProductName'] != ''); - if (FilterData && FilterData.length > 0) { - const formattedData = FilterData?.map((data) => ({ - AppId: getSession('AppId'), - CompId: getSession('CompId'), - BranchId: getSession('BranchId'), - CreatedBy: getSession('UserId'), + const FilterData = Exceldatasubmit?.filter( + a => a.ProductName !== '' + ); - ProdName: data?.ProductName, - ProdVariantName: data?.ProductVariantName, - Size: data?.Quantity, - UOM: data?.UOM, - MRP: data?.MRP, - WhSalePrice: data?.WhSalePrice, - SellPrice: data?.SellPrice, - ProdCat: data?.Category ? data?.Category : 'General', - ProdSubCat: data?.SubCategory, - Brand: data?.Brand ? data?.Brand : '', - AutoGenerateQr: data?.AutoGenerateQrcode - ? data?.AutoGenerateQrcode - : 'No', - QRCode: data?.AddQrCode, - StockAvailable: data?.StockAvailable ? data?.StockAvailable : 'No', - TaxId: data?.Tax ? data?.Tax : 'NIL - 0%', - Cess: data?.Cess, - HSNCode: data?.HSN, - PartNumber: data?.PartNumber, - Rack: data?.Rack, - ManufDate: moment(data?.ManufactureDate, ['M/D/YY']).format( - 'YYYY-MM-DDTHH:mm:ss' - ), - ExpDate: moment(data?.ExpireDate, ['M/D/YY']).format( - 'YYYY-MM-DDTHH:mm:ss' - ), - AvailableFrom: data?.AvailableFrom - ? moment(data?.AvailableFrom, ['M/D/YY']).format('HH:mm:ss') - : '', - AvailableTo: data?.AvailableTo - ? moment(data?.AvailableTo, ['M/D/YY']).format('HH:mm:ss') - : '', - OnePcsAvailable: data?.Amountperpiece ? data?.Amountperpiece : 'No', - OnePcsPrice: data?.AmountperpiecePrice, - // NoOfPcs:data?.NumberOfPieceInside, - AutoGenerateSingleQr: data?.AutoGenerateOnePieceQrcode - ? data?.AutoGenerateOnePieceQrcode - : 'No', - OnePcQR: data?.AutoGenerateOnePieceQrcodeNumber, - // ProductType:data?.ProductType, - TokenAvailable: data?.TokenAvailable ? data?.TokenAvailable : 'No', - ProdLogo: data?.Productimage, - })); - - let postDatas = { prodDetails: formattedData }; - - let response = await dispatch(bulkpostdata(postDatas)).unwrap(); - if (response?.data?.statusCode == 1) { - setMessageType('success'); - setMessageData(response?.data?.response); - setBulkpost(false); - setpage(1); - - var responseData = await dispatch( - getProductDataPageNo({ CompId, BranchId, AppId, PageNumber: 1 }) - ).unwrap(); - setCurrentPage(1); - - if (responseData?.data?.statusCode === 1) { - setCachedData({ [currentPage]: responseData?.data?.data }); - setproductData(responseData?.data?.data); - } - } else { - setMessageType('error'); - setMessageData(responseData?.data?.response); - } - - handleResetExcelData(); - handleCancel(); - } else { + if (!FilterData || FilterData.length === 0) { setBulkpost(false); setMessageType('error'); setMessageData('No data to submit. Please upload an Excel file.'); + return; } - }; - const Unit = UomPreference?.map((e) => e.ConfigName); - const CategoryId = ProdCatData?.map((e) => e.ConfigId); - const CategoryNames = ProdCatData?.map((e) => e.ConfigName); - const CatconfigId = ProdCatData?.map((e) => e.ConfigId); - const Subcatnames = subCatData?.map((e) => e.ConfigName); - const SubcatId = subCatData?.map((e) => e.ConfigId); - const SubcatNumFId = subCatData?.map((e) => e.NumFId); - const BrandNumFId = allBrandData?.map((e) => e.NumFId); - const BrandId = allBrandData?.map((e) => e.ConfigId); - const BrandName = allBrandData?.map((e) => e.ConfigName); - const SuplierNames = SupplierData?.map((e) => e.SuppName); - const TaxDatas = TaxData?.map((e) => e.TaxIdName); - const TaxData1 = TaxData?.map((e) => e.TaxPercentage); - const combinedTaxData = TaxDatas?.map( - (taxIdName, index) => `${taxIdName} - ${TaxData1[index]}%` + const formattedData = FilterData.map(data => ({ + AppId: getSession('AppId'), + CompId: getSession('CompId'), + BranchId: getSession('BranchId'), + CreatedBy: getSession('UserId'), + + ProdName: data.ProductName, + ProdVariantName: data.ProductVariantName, + Size: data.Quantity, + UOM: data.UOM, + MRP: data.MRP, + WhSalePrice: data.WhSalePrice, + SellPrice: data.SellPrice, + ProdCat: data.Category || 'General', + ProdSubCat: data.SubCategory, + Brand: data.Brand || '', + AutoGenerateQr: data.AutoGenerateQrcode || 'No', + QRCode: data.AddQrCode, + StockAvailable: data.StockAvailable || 'No', + TaxId: data.Tax || 'NIL - 0%', + Cess: data.Cess, + HSNCode: data.HSN, + PartNumber: data.PartNumber, + Rack: data.Rack, + ManufDate: moment(data.ManufactureDate, ['M/D/YY']).format( + 'YYYY-MM-DDTHH:mm:ss' + ), + ExpDate: moment(data.ExpireDate, ['M/D/YY']).format( + 'YYYY-MM-DDTHH:mm:ss' + ), + AvailableFrom: data.AvailableFrom + ? moment(data.AvailableFrom, ['M/D/YY']).format('HH:mm:ss') + : '', + AvailableTo: data.AvailableTo + ? moment(data.AvailableTo, ['M/D/YY']).format('HH:mm:ss') + : '', + OnePcsAvailable: data.Amountperpiece || 'No', + OnePcsPrice: data.AmountperpiecePrice, + AutoGenerateSingleQr: data.AutoGenerateOnePieceQrcode || 'No', + OnePcQR: data.AutoGenerateOnePieceQrcodeNumber, + TokenAvailable: data.TokenAvailable || 'No', + ProdLogo: data.Productimage, + })); + + const postDatas = { prodDetails: formattedData }; + + const response = await dispatch(bulkpostdata(postDatas)).unwrap(); + + if (response?.data?.statusCode === 1) { + setMessageType('success'); + setMessageData(response.data.response); + setpage(1); + + const responseData = await dispatch( + getProductDataPageNo({ CompId, BranchId, AppId, PageNumber: 1 }) + ).unwrap(); + + if (responseData?.data?.statusCode === 1) { + setCachedData({ 1: responseData.data.data }); + setproductData(responseData.data.data); + setCurrentPage(1); + } + } else { + setMessageType('error'); + setMessageData(response?.data?.response); + } + + setBulkpost(false); + handleResetExcelData(); + handleCancel(); + }, [ + Exceldatasubmit, + + CompId, + BranchId, + AppId, + handleResetExcelData, + handleCancel + ]); + + const Unit = useMemo( + () => UomPreference?.map((e) => e.ConfigName), + [UomPreference] + ); + + const CategoryId = useMemo( + () => ProdCatData?.map((e) => e.ConfigId), + [ProdCatData] + ); + + const CategoryNames = useMemo( + () => ProdCatData?.map((e) => e.ConfigName), + [ProdCatData] + ); + + const CatconfigId = useMemo( + () => ProdCatData?.map((e) => e.ConfigId), + [ProdCatData] + ); + + const Subcatnames = useMemo( + () => subCatData?.map((e) => e.ConfigName), + [subCatData] + ); + + const SubcatId = useMemo( + () => subCatData?.map((e) => e.ConfigId), + [subCatData] + ); + + const SubcatNumFId = useMemo( + () => subCatData?.map((e) => e.NumFId), + [subCatData] + ); + + const BrandNumFId = useMemo( + () => allBrandData?.map((e) => e.NumFId), + [allBrandData] + ); + + const BrandId = useMemo( + () => allBrandData?.map((e) => e.ConfigId), + [allBrandData] + ); + + const BrandName = useMemo( + () => allBrandData?.map((e) => e.ConfigName), + [allBrandData] + ); + + const SuplierNames = useMemo( + () => SupplierData?.map((e) => e.SuppName), + [SupplierData] + ); + + const TaxDatas = useMemo( + () => TaxData?.map((e) => e.TaxIdName), + [TaxData] + ); + + const TaxData1 = useMemo( + () => TaxData?.map((e) => e.TaxPercentage), + [TaxData] + ); + + const combinedTaxData = useMemo( + () => + TaxDatas?.map( + (taxIdName, index) => `${taxIdName} - ${TaxData1[index]}%` + ), + [TaxDatas, TaxData1] ); const Deletebulk = async () => { let data = { @@ -2641,7 +2706,7 @@ const ProductList = () => { generateQRCodeCopy={(code) => generateQRCodeCopy(QrandbarcodeDatas, code) } - generateCodeImage={(code, codeType = 'Q') => generateCodeImage(code, codeType, QrandbarcodeDatas) } + generateCodeImage={(code, codeType = 'Q') => generateCodeImage(code, codeType, QrandbarcodeDatas)} imageTagBarcodeAndQR={imageTagBarcodeAndQR} dropdownValue={dropdownValue} barcodeTemplateDetails={barcodeTemplateDetails} diff --git a/src/Pages/StockPriceUpdate/StockPriceUpdate.jsx b/src/Pages/StockPriceUpdate/StockPriceUpdate.jsx index 9e93125..0c919a8 100644 --- a/src/Pages/StockPriceUpdate/StockPriceUpdate.jsx +++ b/src/Pages/StockPriceUpdate/StockPriceUpdate.jsx @@ -4,76 +4,77 @@ import React, { useRef, useContext, useCallback, -} from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { Select, Tooltip } from "antd"; -import { Form, Input, Table } from "antd"; +} from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { Select, Tooltip } from 'antd'; +import { Form, Input, Table } from 'antd'; import { EditFilled, DeleteFilled, ArrowRightOutlined, -} from "@ant-design/icons"; +} from '@ant-design/icons'; import { PutStockPrice, bulkPriceUpdate, getStockNames, -} from "../../Features/StockPriceUpdate/StockPriceUpdateMaster"; +} from '../../Features/StockPriceUpdate/StockPriceUpdateMaster'; import { dateFormatChange, ExtractDateFormate, getSession, -} from "../../Services/Others"; -import { DefaultModal } from "../../Components/Modal/DefaultModal"; -import { Tables } from "../../Components/Tables/Table"; -import Buttons from "../../Components/Forms/Buttons"; -import { Messages } from "../../Components/Notifications/Messages"; +} from '../../Services/Others'; +import { DefaultModal } from '../../Components/Modal/DefaultModal'; +import { Tables } from '../../Components/Tables/Table'; +import Buttons from '../../Components/Forms/Buttons'; +import { Messages } from '../../Components/Notifications/Messages'; import { changeBreadCrumb, getEmpAccess, -} from "../../Features/AppPage/CenterPage.js"; -import FormHeader from "../PageComponents/FormHeader"; -import Search from "../../Components/Forms/Search"; -import { RadioGrpButton } from "../../Components/Forms/RadioGroup.jsx"; -import { useAuth } from "../../AuthContext.jsx"; -import "../../Styles/OverAllStyle/OverAllStyle.scss"; -import { getPreferenceData } from "../../Features/BookingScreen/BookingData/BookingData.js"; -import { DropDowns } from "../../Components/Forms/DropDown.jsx"; -import { FiDelete, FiUploadCloud } from "react-icons/fi"; -import { CiExport } from "react-icons/ci"; -import Excelupldimg from "../../Images/Excel.png"; +} from '../../Features/AppPage/CenterPage.js'; +import FormHeader from '../PageComponents/FormHeader'; +import Search from '../../Components/Forms/Search'; +import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx'; +import { useAuth } from '../../AuthContext.jsx'; +import '../../Styles/OverAllStyle/OverAllStyle.scss'; +import './StockPriceUpdate.scss'; +import { getPreferenceData } from '../../Features/BookingScreen/BookingData/BookingData.js'; +import { DropDowns } from '../../Components/Forms/DropDown.jsx'; +import { FiDelete, FiUploadCloud } from 'react-icons/fi'; +import { CiExport } from 'react-icons/ci'; +import Excelupldimg from '../../Images/Excel.png'; import { emptyExcelData, fileInputRefSelector, -} from "../../Features/ExcelUploadPage/ExcelUploadPage.js"; +} from '../../Features/ExcelUploadPage/ExcelUploadPage.js'; const subDirectory = import.meta.env.BASE_URL; -import ExcelJS from "exceljs"; -import { read, utils } from "xlsx"; -import { v4 as uuidv4 } from "uuid"; -import { InputField } from "../../Components/Forms/InputField.jsx"; -import { MdOutlineAppRegistration } from "react-icons/md"; +import ExcelJS from 'exceljs'; +import { read, utils } from 'xlsx'; +import { v4 as uuidv4 } from 'uuid'; +import { InputField } from '../../Components/Forms/InputField.jsx'; +import { MdOutlineAppRegistration } from 'react-icons/md'; import { getFieldSetupData, postFieldSetup, -} from "../../Features/ProductPage/ProductPage.js"; +} from '../../Features/ProductPage/ProductPage.js'; import { ApplicationPreferences, getCommonAppPreference, -} from "../../Features/BrachLogin/BranchLogin.js"; -import { IoClose } from "react-icons/io5"; +} from '../../Features/BrachLogin/BranchLogin.js'; +import { IoClose } from 'react-icons/io5'; const StockPriceUpdate = () => { const { SadminuserAccess } = useAuth(); let SAAccessCommonMaster = SadminuserAccess?.find( - (e) => e?.MenuName === "Price Change", + (e) => e?.MenuName === 'Price Change' ); const ApplicationPreferenceData = useSelector(ApplicationPreferences); const categoryId = ApplicationPreferenceData?.find( - (p) => p?.PreferredCatName?.toLowerCase() === "price change fields", + (p) => p?.PreferredCatName?.toLowerCase() === 'price change fields' )?.PreferredCatId; const excelCategoryId = ApplicationPreferenceData?.find( - (p) => p?.PreferredCatName?.toLowerCase() === "price change sheet fields", + (p) => p?.PreferredCatName?.toLowerCase() === 'price change sheet fields' )?.PreferredCatId; const fileInputRef = useRef(fileInputRefSelector); @@ -81,8 +82,8 @@ const StockPriceUpdate = () => { const formRef = useRef(null); const allowedExcelTypes = [ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx - "application/vnd.ms-excel", // .xls + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx + 'application/vnd.ms-excel', // .xls ]; const dispatch = useDispatch(); @@ -90,7 +91,7 @@ const StockPriceUpdate = () => { const [selectedExcelFields, setSelectedExcelFields] = useState([]); const [tableFieldPreferences, setTableFieldPreferences] = useState([]); const [tableExcelFieldPreferences, setTableExcelFieldPreferences] = useState( - [], + [] ); const [messageType, setMessageType] = useState(null); const [messageData, setMessageData] = useState(null); @@ -103,8 +104,8 @@ const StockPriceUpdate = () => { const [dataSource, setDataSource] = useState([]); const [sortedInfo, setSortedInfo] = useState({}); const [BulksortedInfo, setBulksortedInfo] = useState({}); - const [searchedText, setSearchedText] = useState(""); - const [BulksearchedText, setBulksearchedText] = useState(""); + const [searchedText, setSearchedText] = useState(''); + const [BulksearchedText, setBulksearchedText] = useState(''); const [filteredInfo, setFilteredInfo] = useState({}); const [page, setpage] = useState(1); const [Bulkchangepage, setBulkchangepage] = useState(1); @@ -114,35 +115,36 @@ const StockPriceUpdate = () => { const [open, setOpen] = useState(false); const [excelModalOpen, setExcelModalOpen] = useState(false); const [priceChangeModalOpen, setPriceChangeModalOpen] = useState(false); - const [stockVariantBased, setStockVariantBased] = useState("Yes"); + const [stockVariantBased, setStockVariantBased] = useState('Yes'); const [exportLoading, setExportLoading] = useState(false); const [fileLoading, setFileLoading] = useState(false); const [loading, setLoading] = useState(false); const [headers, setHeaders] = useState([]); + console.log(headers, 'headers'); const [uploadedData, setUploadedData] = useState([]); - const CompId = getSession("CompId"); - const BranchId = getSession("BranchId"); - const AppId = getSession("AppId"); - const UserId = getSession("UserId"); - const UserType = getSession("UserType"); + const CompId = getSession('CompId'); + const BranchId = getSession('BranchId'); + const AppId = getSession('AppId'); + const UserId = getSession('UserId'); + const UserType = getSession('UserType'); const [empData, setEmpData] = useState(); const [addnewAccess, setaddnewAccess] = useState(true); - const [RadioSelection, setRadioSelection] = useState("Single"); + const [RadioSelection, setRadioSelection] = useState('Single'); const [BulkProductData, setBulkProductData] = useState([]); const [allowDecimal, setAllowDecimal] = useState(false); const hasFieldExists = (label) => headers.some((h) => h.toLowerCase() === label.toLowerCase()); const hasField = (label) => - tableFieldPreferences?.some((f) => f.label === label && f.access === "Y"); + tableFieldPreferences?.some((f) => f.label === label && f.access === 'Y'); const hasExcelField = (label) => tableExcelFieldPreferences?.some( - (f) => f.label === label && f.access === "Y", + (f) => f.label === label && f.access === 'Y' ); const items = [ { - name: "Home", + name: 'Home', link: `${subDirectory}app-page/home`, }, ]; @@ -150,75 +152,78 @@ const StockPriceUpdate = () => { const handleRemoveRecord = (index) => { setUploadedData((prev) => prev.filter((_, i) => i !== index)); }; - + console.log(uploadedData, "uploadedData") const columns = [ { - title: "Product Name", - dataIndex: "ProductName", - key: "ProductName", + title: 'Product Name', + dataIndex: 'ProductName', + key: 'ProductName', width: 180, render: (value, record, index) => ( -

{`${value} (${record?.Size} ${record?.UOMName})`}

+

+ {value}{' '} + {record?.Size && `(${record?.Size || ''} ${record?.UOMName || ''})`} +

), }, { - title: "Variant Name", - dataIndex: "VariantName", - key: "VariantName", + title: 'Variant Name', + dataIndex: 'VariantName', + key: 'VariantName', width: 180, }, { - title: "Batch No", - dataIndex: "BatchRef", - key: "BatchRef", + title: 'Batch No', + dataIndex: 'BatchRef', + key: 'BatchRef', width: 180, }, - ...(hasFieldExists("Stock") + ...(hasFieldExists('Stock') ? [ { - title: "Stock", - dataIndex: "Stock", - key: "Stock", + title: 'Stock', + dataIndex: 'Stock', + key: 'Stock', width: 80, }, ] : []), - ...(hasFieldExists("Stock Date") + ...(hasFieldExists('Stock Date') ? [ { - title: "Stock Date", - dataIndex: "StockDate", - key: "StockDate", + title: 'Stock Date', + dataIndex: 'StockDate', + key: 'StockDate', width: 80, }, ] : []), - ...(hasFieldExists("Old MRP") + ...(hasFieldExists('Old MRP') ? [ { - title: "Old MRP", - dataIndex: "OldMRP", - key: "OldMRP", + title: 'Old MRP', + dataIndex: 'OldMRP', + key: 'OldMRP', width: 100, }, ] : []), - ...(hasFieldExists("Old SP") + ...(hasFieldExists('Old SP') ? [ { - title: "Old SP", - dataIndex: "OldSP", - key: "OldSP", + title: 'Old SP', + dataIndex: 'OldSP', + key: 'OldSP', width: 100, }, ] : []), - ...(hasFieldExists("Old Wholesale Price") + ...(hasFieldExists('Old Wholesale Price') ? [ { - title: "Old Wholesale Price", - dataIndex: "OldWholeSalePrice", - key: "OldWholeSalePrice", + title: 'Old Wholesale Price', + dataIndex: 'OldWholeSalePrice', + key: 'OldWholeSalePrice', width: 140, }, ] @@ -226,9 +231,9 @@ const StockPriceUpdate = () => { // ✅ EDITABLE { - title: "New MRP", - dataIndex: "NewMRP", - key: "NewMRP", + title: 'New MRP', + dataIndex: 'NewMRP', + key: 'NewMRP', width: 120, render: (_, record, index) => ( @@ -236,17 +241,17 @@ const StockPriceUpdate = () => { placeholder="New MRP" inputMode="decimal" onChange={(e) => - handlePriceChange(index, "NewMRP", e.target.value, record.localId) + handlePriceChange(index, 'NewMRP', e.target.value, record.localId) } onInput={(e) => { - let cleanedValue = e.target.value.replace(/[^0-9.]/g, ""); - if (cleanedValue.startsWith(".")) { - cleanedValue = "0" + cleanedValue; + let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + if (cleanedValue.startsWith('.')) { + cleanedValue = '0' + cleanedValue; } - const parts = cleanedValue.split("."); + const parts = cleanedValue.split('.'); e.target.value = parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join("")}` + ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} /> @@ -254,38 +259,38 @@ const StockPriceUpdate = () => { ), }, { - title: "New SP", - dataIndex: "NewSellPrice", - key: "NewSellPrice", + title: 'New SP', + dataIndex: 'NewSellPrice', + key: 'NewSellPrice', width: 120, render: (_, record, index) => ( ({ validator(_, value) { const mrp = getFieldValue(`NewMRP${record.localId}`); - if (mrp === undefined || mrp === null || mrp === "") { + if (mrp === undefined || mrp === null || mrp === '') { return Promise.resolve(); } const numMRP = Number(mrp); const numSP = - value === undefined || value === null || value === "" + value === undefined || value === null || value === '' ? null : Number(value); if (numSP === null) { return Promise.reject( - new Error("New SP is required when New MRP is provided"), + new Error('New SP is required when New MRP is provided') ); } if (numSP > numMRP) { return Promise.reject( - new Error("New SP cannot be greater than New MRP"), + new Error('New SP cannot be greater than New MRP') ); } @@ -298,23 +303,23 @@ const StockPriceUpdate = () => { placeholder="New SP" inputMode="decimal" onInput={(e) => { - let cleanedValue = e.target.value.replace(/[^0-9.]/g, ""); - const parts = cleanedValue.split("."); - if (cleanedValue.startsWith(".")) { - cleanedValue = "0" + cleanedValue; + let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + const parts = cleanedValue.split('.'); + if (cleanedValue.startsWith('.')) { + cleanedValue = '0' + cleanedValue; } e.target.value = parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join("")}` + ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} onChange={(e) => { { handlePriceChange( index, - "NewSellPrice", + 'NewSellPrice', e.target.value, - record.localId, + record.localId ); excelDataRef.current ?.validateFields([`NewSellPrice${record.localId}`]) @@ -325,12 +330,12 @@ const StockPriceUpdate = () => { ), }, - ...(hasFieldExists("New Wholesale Price") + ...(hasFieldExists('New Wholesale Price') ? [ { - title: "New Wholesale Price", - dataIndex: "NewWholeSalePrice", - key: "NewWholeSalePrice", + title: 'New Wholesale Price', + dataIndex: 'NewWholeSalePrice', + key: 'NewWholeSalePrice', width: 160, render: (value, record, index) => ( @@ -338,22 +343,22 @@ const StockPriceUpdate = () => { onChange={(e) => handlePriceChange( index, - "NewWholeSalePrice", + 'NewWholeSalePrice', e.target.value, - record.localId, + record.localId ) } placeholder="New Wholesale" inputMode="decimal" onInput={(e) => { - let cleanedValue = e.target.value.replace(/[^0-9.]/g, ""); - const parts = cleanedValue.split("."); - if (cleanedValue.startsWith(".")) { - cleanedValue = "0" + cleanedValue; + let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + const parts = cleanedValue.split('.'); + if (cleanedValue.startsWith('.')) { + cleanedValue = '0' + cleanedValue; } e.target.value = parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join("")}` + ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} /> @@ -363,15 +368,15 @@ const StockPriceUpdate = () => { ] : []), { - title: "Action", - key: "action", + title: 'Action', + key: 'action', width: 80, - align: "center", + align: 'center', render: (_, record, index) => ( handleRemoveRecord(index)} /> @@ -390,7 +395,7 @@ const StockPriceUpdate = () => { dispatch(getCommonAppPreference(AppId)); }, [AppId, dispatch]); useEffect(() => { - if (UserType === "Employee") { + if (UserType === 'Employee') { fetchApi(); } }, [UserType]); @@ -406,25 +411,25 @@ const StockPriceUpdate = () => { const getFieldSetup = async () => { try { const response = await dispatch( - getFieldSetupData({ AppId, CompId, BranchId, categoryId, Type: "GB" }), + getFieldSetupData({ AppId, CompId, BranchId, categoryId, Type: 'GB' }) ).unwrap(); if (response?.data?.statusCode === 1) { - console.log(response?.data?.data?.[0]?.ConfigDtl, "Field Setup Data"); + console.log(response?.data?.data?.[0]?.ConfigDtl, 'Field Setup Data'); setSelectedFields( response?.data?.data?.[0]?.ConfigDtl?.filter( - (c) => c.ConfigId && c.Access === "Y", - )?.map((c) => c.ConfigId) || [], + (c) => c.ConfigId && c.Access === 'Y' + )?.map((c) => c.ConfigId) || [] ); setTableFieldPreferences( response?.data?.data?.[0]?.ConfigDtl?.map((c) => ({ value: c.ConfigId, label: c.ConfigName, access: c.Access, - })) || [], + })) || [] ); } } catch (error) { - console.error("Error fetching field setup:", error); + console.error('Error fetching field setup:', error); } }; @@ -436,38 +441,38 @@ const StockPriceUpdate = () => { CompId, BranchId, categoryId: excelCategoryId, - Type: "GB", - }), + Type: 'GB', + }) ).unwrap(); if (response?.data?.statusCode === 1) { - console.log(response?.data?.data?.[0]?.ConfigDtl, "Field Setup Data"); + console.log(response?.data?.data?.[0]?.ConfigDtl, 'Field Setup Data'); setSelectedExcelFields( response?.data?.data?.[0]?.ConfigDtl?.filter( - (c) => c.ConfigId && c.Access === "Y", - )?.map((c) => c.ConfigId) || [], + (c) => c.ConfigId && c.Access === 'Y' + )?.map((c) => c.ConfigId) || [] ); setTableExcelFieldPreferences( response?.data?.data?.[0]?.ConfigDtl?.map((c) => ({ value: c.ConfigId, label: c.ConfigName, access: c.Access, - })) || [], + })) || [] ); } } catch (error) { - console.error("Error fetching field setup:", error); + console.error('Error fetching field setup:', error); } }; useEffect(() => { let hasAccess = false; - if (UserType === "Admin" || UserType === "Super Admin") { + 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"; + } else if (UserType === 'Employee') { + hasAccess = empData?.AddAccess === 'Y'; + } else if (UserType === 'Super Admin User') { + hasAccess = SAAccessCommonMaster?.AddAccess === 'Y'; } setaddnewAccess(!hasAccess); @@ -490,7 +495,7 @@ const StockPriceUpdate = () => { }; let response = await dispatch(getEmpAccess(data)).unwrap(); let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter( - (item) => item.ConfigName === "Price Change", + (item) => item.ConfigName === 'Price Change' ); setEmpData(datas?.[0]); }; @@ -553,7 +558,7 @@ const StockPriceUpdate = () => { ...values, }); } catch (errInfo) { - console.log("Save failed:", errInfo); + console.log('Save failed:', errInfo); } }; @@ -569,12 +574,12 @@ const StockPriceUpdate = () => { rules={[ { pattern: /^(?!0$)(\d+)(\.\d{1,2})?$/, - message: "Invalid format (Max 2 decimals, No zero)", + message: 'Invalid format (Max 2 decimals, No zero)', }, { validator: (_, value) => value?.length > 10 - ? Promise.reject("Max 10 characters allowed") + ? Promise.reject('Max 10 characters allowed') : Promise.resolve(), }, ]} @@ -590,11 +595,11 @@ const StockPriceUpdate = () => { } inputMode="decimal" onInput={(e) => { - const cleanedValue = e.target.value.replace(/[^0-9.]/g, ""); - const parts = cleanedValue.split("."); + const cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + const parts = cleanedValue.split('.'); e.target.value = parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join("")}` + ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} /> @@ -660,7 +665,7 @@ const StockPriceUpdate = () => { ...values, }); } catch (errInfo) { - console.log("Save failed:", errInfo); + console.log('Save failed:', errInfo); } }; @@ -676,12 +681,12 @@ const StockPriceUpdate = () => { rules={[ { pattern: /^(?!0$)(\d+)(\.\d{1,2})?$/, - message: "Invalid format (Max 2 decimals, No zero)", + message: 'Invalid format (Max 2 decimals, No zero)', }, { validator: (_, value) => value?.length > 10 - ? Promise.reject("Max 10 characters allowed") + ? Promise.reject('Max 10 characters allowed') : Promise.resolve(), }, ]} @@ -696,11 +701,11 @@ const StockPriceUpdate = () => { } inputMode="decimal" onInput={(e) => { - const cleanedValue = e.target.value.replace(/[^0-9.]/g, ""); - const parts = cleanedValue.split("."); + const cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); + const parts = cleanedValue.split('.'); e.target.value = parts.length > 2 - ? `${parts[0]}.${parts.slice(1).join("")}` + ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} /> @@ -736,8 +741,8 @@ const StockPriceUpdate = () => { const { data: res } = await dispatch(getPreferenceData(data)).unwrap(); const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find( (setting) => - setting?.SettingIdName?.toLowerCase() === "decimal" && - setting?.SettingValue === "Y", + setting?.SettingIdName?.toLowerCase() === 'decimal' && + setting?.SettingValue === 'Y' ); if (decimalSetting) { setAllowDecimal(true); @@ -781,7 +786,7 @@ const StockPriceUpdate = () => { ProdVariantName: detail?.ProdVariantName, BatchRef: detail?.BatchRef, key: `${product.ProdId}_${detail.InwardDtlId}`, - })), + })) ); setBulkProductData(flattenedArray); }; @@ -799,7 +804,7 @@ const StockPriceUpdate = () => { const currentRow = { ...updated[rowIndex] }; // If changing New MRP, clear New SP - if (field === "NewMRP") { + if (field === 'NewMRP') { currentRow.NewSellPrice = null; excelDataRef.current?.setFieldsValue({ [`NewSellPrice${localId}`]: null, @@ -807,18 +812,19 @@ const StockPriceUpdate = () => { } currentRow[field] = numValue; + currentRow.isModified = true; updated[rowIndex] = currentRow; return updated; }); // Validate New SP against New MRP - if (field === "NewSellPrice" && numValue) { + if (field === 'NewSellPrice' && numValue) { const currentRow = uploadedData[rowIndex]; const newMRP = currentRow?.NewMRP; if (newMRP && numValue > newMRP) { - setMessageType("error"); - setMessageData("New SP cannot be greater than New MRP"); + setMessageType('error'); + setMessageData('New SP cannot be greater than New MRP'); return; } } @@ -830,7 +836,7 @@ const StockPriceUpdate = () => { const statusFormatter = async (row) => { const updatedData = StockDetails?.filter( - (item) => item?.InwardDtlId !== row?.InwardDtlId, + (item) => item?.InwardDtlId !== row?.InwardDtlId ); setStockDetails(updatedData); }; @@ -838,7 +844,7 @@ const StockPriceUpdate = () => { let tableValue = StockNames?.[0]?.stockDetails; let DataSource = StockNames?.map((name, index) => ({ value: index + 1, - label: name?.ProdName + "(" + (name?.Size + " " + name?.UOMName) + ")", + label: name?.ProdName + '(' + (name?.Size + ' ' + name?.UOMName) + ')', ProdId: name?.ProdId, stockDetails: name?.stockDetails, Quantity: name?.Size, @@ -864,8 +870,8 @@ const StockPriceUpdate = () => { }); setStockDetails(newData); } else { - setMessageType("error"); - setMessageData("MRP is must be greater than or equal to selling price"); + setMessageType('error'); + setMessageData('MRP is must be greater than or equal to selling price'); } } else { const newData = StockDetails?.map((item) => { @@ -891,12 +897,13 @@ const StockPriceUpdate = () => { newData?.splice(index, 1, { ...item, ...row, + }); setBulkProductData(newData); } else { - setMessageType("error"); + setMessageType('error'); setMessageData( - "MRP is must be greater than or equal to selling price", + 'MRP is must be greater than or equal to selling price' ); } } else { @@ -926,31 +933,31 @@ const StockPriceUpdate = () => { }; function safeRound(amountStr) { - if (amountStr == null) return allowDecimal ? "0.00" : "0"; + if (amountStr == null) return allowDecimal ? '0.00' : '0'; - const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ""); + const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ''); const num = Number(cleaned); - if (isNaN(num)) return allowDecimal ? "0.00" : "0"; + if (isNaN(num)) return allowDecimal ? '0.00' : '0'; return allowDecimal ? num.toFixed(2) : Math.round(num).toString(); } const columns2 = [ { - title: "Sl.No", - align: "center", - key: "sno", - width: "60px", + title: 'Sl.No', + align: 'center', + key: 'sno', + width: '60px', render: (text, object, index) => ( - {index + 1} + {index + 1} ), }, { - title: "Product Name", - dataIndex: "ProdName", - key: "ProdName", - width: "20%", + title: 'Product Name', + dataIndex: 'ProdName', + key: 'ProdName', + width: '20%', filteredValue: [searchedText], onFilter: (value, record) => { return String(record.ProdName) @@ -958,7 +965,7 @@ const StockPriceUpdate = () => { .includes(value?.toLowerCase()); }, sorter: (a, b) => a?.ProdName?.localeCompare(b.ProdName), - sortOrder: sortedInfo.columnKey === "ProdName" ? sortedInfo.order : null, + sortOrder: sortedInfo.columnKey === 'ProdName' ? sortedInfo.order : null, ellipsis: true, render: (_, record) => ( @@ -968,65 +975,65 @@ const StockPriceUpdate = () => { ), }, { - title: "stock Date", - dataIndex: "InwardDate", - key: "InwardDate", - align: "right", - width: "150px", + title: 'stock Date', + dataIndex: 'InwardDate', + key: 'InwardDate', + align: 'right', + width: '150px', render: (InwardDate) => - InwardDate !== null ? ExtractDateFormate(InwardDate) : "-", + InwardDate !== null ? ExtractDateFormate(InwardDate) : '-', }, { - title: "Old MRP", - dataIndex: "MRP", - key: "MRP", - align: "right", - render: (MRP) => (safeRound(MRP) !== null ? safeRound(MRP) : "-"), + title: 'Old MRP', + dataIndex: 'MRP', + key: 'MRP', + align: 'right', + render: (MRP) => (safeRound(MRP) !== null ? safeRound(MRP) : '-'), }, { - title: "Old Price", - dataIndex: "SellPrice", - key: "SellPrice", - align: "right", + title: 'Old Price', + dataIndex: 'SellPrice', + key: 'SellPrice', + align: 'right', render: (SellPrice) => - safeRound(SellPrice) !== null ? safeRound(SellPrice) : "-", + safeRound(SellPrice) !== null ? safeRound(SellPrice) : '-', }, { - title: "New MRP", - dataIndex: "CurrentMRP", - key: "CurrentMRP", - align: "right", + title: 'New MRP', + dataIndex: 'CurrentMRP', + key: 'CurrentMRP', + align: 'right', editable: true, - render: (text, record) =>

{text ? text : "Enter MRP"}

, + render: (text, record) =>

{text ? text : 'Enter MRP'}

, width: 100, }, { - title: "New SP", - dataIndex: "CurrentAmt", - key: "CurrentAmt", - align: "right", + title: 'New SP', + dataIndex: 'CurrentAmt', + key: 'CurrentAmt', + align: 'right', editable: true, - render: (text, record) =>

{text ? text : "Enter Price"}

, + render: (text, record) =>

{text ? text : 'Enter Price'}

, width: 100, }, { - title: "Action", - dataIndex: "SellPrice", - key: "SellPrice", - align: "center", - width: "100px", + title: 'Action', + dataIndex: 'SellPrice', + key: 'SellPrice', + align: 'center', + width: '100px', render: (_, record, index) => (
statusFormatter(record, index)} />
@@ -1035,21 +1042,21 @@ const StockPriceUpdate = () => { ]; const BulkPricechangeColumns = [ { - title: "Sl.No", - align: "center", - key: "sno", - width: "50px", + title: 'Sl.No', + align: 'center', + key: 'sno', + width: '50px', render: (text, object, index) => ( - + {(Bulkchangepage - 1) * 10 + index + 1} ), }, { - title: "Name", - dataIndex: "ProdName", - key: "ProdName", - width: "20%", + title: 'Name', + dataIndex: 'ProdName', + key: 'ProdName', + width: '20%', filteredValue: [BulksearchedText], onFilter: (value, record) => { return String(record.ProdName) @@ -1058,7 +1065,7 @@ const StockPriceUpdate = () => { }, sorter: (a, b) => a?.ProdName?.localeCompare(b.ProdName), sortOrder: - BulksortedInfo.columnKey === "ProdName" ? BulksortedInfo.order : null, + BulksortedInfo.columnKey === 'ProdName' ? BulksortedInfo.order : null, ellipsis: true, render: (_, record) => ( @@ -1067,127 +1074,126 @@ const StockPriceUpdate = () => { ), }, { - title: "Variant Name", - dataIndex: "ProdVariantName", - key: "ProdVariantName", - align: "left", - width: "120px", + title: 'Variant Name', + dataIndex: 'ProdVariantName', + key: 'ProdVariantName', + align: 'left', + width: '120px', }, { - title: "Batch No", - dataIndex: "BatchRef", - key: "BatchRef", - align: "left", - width: "120px", + title: 'Batch No', + dataIndex: 'BatchRef', + key: 'BatchRef', + align: 'left', + width: '120px', }, - ...(hasField("Stock Date") + ...(hasField('Stock Date') ? [ { - title: "stock Date", - dataIndex: "InwardDate", - key: "InwardDate", - align: "center", - width: "100px", + title: 'stock Date', + dataIndex: 'InwardDate', + key: 'InwardDate', + align: 'center', + width: '100px', render: (InwardDate) => - InwardDate !== null ? ExtractDateFormate(InwardDate) : "-", + InwardDate !== null ? ExtractDateFormate(InwardDate) : '-', }, ] : []), - ...(hasField("Expiry Date") + ...(hasField('Expiry Date') ? [ { - title: "Exp date", - dataIndex: "ExpDate", - key: "ExpDate", - align: "center", - width: "100px", + title: 'Exp date', + dataIndex: 'ExpDate', + key: 'ExpDate', + align: 'center', + width: '100px', render: (ExpDate) => - ExpDate !== null ? ExtractDateFormate(ExpDate) : "-", + ExpDate !== null ? ExtractDateFormate(ExpDate) : '-', }, ] : []), - ...(hasField("Stock") + ...(hasField('Stock') ? [ - { - title: "stock", - dataIndex: "BalanceQty", - key: "BalanceQty", - align: "right", - width: "60px", - render: (BalanceQty) => (BalanceQty !== null ? BalanceQty : "-"), + title: 'stock', + dataIndex: 'BalanceQty', + key: 'BalanceQty', + align: 'right', + width: '60px', + render: (BalanceQty) => (BalanceQty !== null ? BalanceQty : '-'), }, ] : []), - ...(hasField("Old MRP") + ...(hasField('Old MRP') ? [ { - title: "Old MRP", - dataIndex: "MRP", - key: "MRP", - align: "right", - width: "70px", - render: (MRP) => (safeRound(MRP) !== null ? safeRound(MRP) : "-"), + title: 'Old MRP', + dataIndex: 'MRP', + key: 'MRP', + align: 'right', + width: '70px', + render: (MRP) => (safeRound(MRP) !== null ? safeRound(MRP) : '-'), }, ] : []), - ...(hasField("Old SP") + ...(hasField('Old SP') ? [ { - title: "Old SP", - dataIndex: "SellPrice", - key: "SellPrice", - align: "right", - width: "70px", + title: 'Old SP', + dataIndex: 'SellPrice', + key: 'SellPrice', + align: 'right', + width: '70px', render: (SellPrice) => - safeRound(SellPrice) !== null ? safeRound(SellPrice) : "-", + safeRound(SellPrice) !== null ? safeRound(SellPrice) : '-', }, ] : []), - ...(hasField("Old Wholesale Price") + ...(hasField('Old Wholesale Price') ? [ { - title: "Old Wholesale Price", - dataIndex: "WhSalePrice", - key: "WhSalePrice", - align: "right", - width: "120px", + title: 'Old Wholesale Price', + dataIndex: 'WhSalePrice', + key: 'WhSalePrice', + align: 'right', + width: '120px', render: (WhSalePrice) => - safeRound(WhSalePrice) !== null ? safeRound(WhSalePrice) : "-", + safeRound(WhSalePrice) !== null ? safeRound(WhSalePrice) : '-', }, ] : []), { - title: "New MRP", - dataIndex: "CurrentMRP", - key: "CurrentMRP", - align: "center", - with: "4rem", + title: 'New MRP', + dataIndex: 'CurrentMRP', + key: 'CurrentMRP', + align: 'center', + with: '4rem', editable: true, - render: (text, record) =>

{text ? text : "Enter MRP"}

, + render: (text, record) =>

{text ? text : 'Enter MRP'}

, width: 100, }, { - title: "New SP", - dataIndex: "CurrentAmt", - key: "CurrentAmt", - align: "center", - with: "4rem", + title: 'New SP', + dataIndex: 'CurrentAmt', + key: 'CurrentAmt', + align: 'center', + with: '4rem', editable: true, - render: (text, record) =>

{text ? text : "Enter Price"}

, + render: (text, record) =>

{text ? text : 'Enter Price'}

, width: 100, }, - ...(hasField("New Wholesale Price") + ...(hasField('New Wholesale Price') ? [ { - title: "New Wholesale Price", - dataIndex: "CurrentWhAmt", - key: "CurrentWhAmt", - align: "center", - with: "4rem", + title: 'New Wholesale Price', + dataIndex: 'CurrentWhAmt', + key: 'CurrentWhAmt', + align: 'center', + with: '4rem', editable: true, render: (text, record) => ( -

{text ? text : "Enter Wholesale Price"}

+

{text ? text : 'Enter Wholesale Price'}

), width: 120, }, @@ -1200,7 +1206,7 @@ const StockPriceUpdate = () => { // Check if any of the new products already exist in StockDetails setStockDetails((prevStockDetails) => { const existingInwardDtlIds = new Set( - prevStockDetails?.map((item) => item.InwardDtlId), + prevStockDetails?.map((item) => item.InwardDtlId) ); const uniqueNewStockDetails = newStockDetails @@ -1255,18 +1261,18 @@ const StockPriceUpdate = () => { // }; const HandlePutData = async () => { - if (RadioSelection == "Bulk") { + if (RadioSelection == 'Bulk') { const filteredCurrentAmtData = BulkProductData?.filter( (item) => (item.CurrentAmt !== undefined && item.CurrentAmt !== null && - item.CurrentAmt !== "" && + item.CurrentAmt !== '' && item.CurrentMRP !== undefined && item.CurrentMRP !== null && - item.CurrentMRP !== "") || + item.CurrentMRP !== '') || (item.CurrentWhAmt !== undefined && item.CurrentWhAmt !== null && - item.CurrentWhAmt !== ""), + item.CurrentWhAmt !== '') ); const hasInvalidData = BulkProductData.every((item) => { const isAbsent = item.CurrentAmt == null && item.CurrentMRP == null; @@ -1280,12 +1286,12 @@ const StockPriceUpdate = () => { let Postdata = { CompId: CompId, BranchId: BranchId, - Type: "Variant", + Type: 'Variant', ProductDetails: filteredCurrentAmtData?.map((item) => ({ ProdId: item?.ProdId, NewMRP: item?.CurrentMRP, NewSellPrice: item?.CurrentAmt, - AdjComment: "string", + AdjComment: 'string', InwardDtlId: item?.InwardDtlId, NewWholeSalePrice: item.CurrentWhAmt, })), @@ -1295,32 +1301,32 @@ const StockPriceUpdate = () => { if (response?.data?.statusCode == 1) { setProductName(); - setMessageType("success"); + setMessageType('success'); setMessageData(response?.data?.response); fetchData(); - setBulksearchedText(""); + setBulksearchedText(''); setStockDetails([]); setBulkProductData([]); } else { - setMessageType("error"); + setMessageType('error'); setMessageData(response?.data?.response); } } else { - setMessageType("error"); - setMessageData("Please give all details"); + setMessageType('error'); + setMessageData('Please give all details'); } } else { const filteredStockDetails = StockDetails?.filter( (item) => item?.CurrentMRP && - item?.CurrentMRP !== "" && + item?.CurrentMRP !== '' && item?.CurrentAmt && - item?.CurrentAmt !== "", + item?.CurrentAmt !== '' ); if (filteredStockDetails?.length === 0) { - setMessageType("error"); - setMessageData("Please enter price details for at least one product"); + setMessageType('error'); + setMessageData('Please enter price details for at least one product'); return; } @@ -1331,7 +1337,7 @@ const StockPriceUpdate = () => { ProdId: item?.ProdId, MRP: item?.CurrentMRP, SellPrice: item?.CurrentAmt, - AdjComment: "string", + AdjComment: 'string', InwardDtlId: item?.InwardDtlId, })), UpdatedBy: 1, @@ -1343,11 +1349,11 @@ const StockPriceUpdate = () => { setStockNames(res?.data?.data); if (response?.data?.statusCode == 1) { setProductName(); - setMessageType("success"); + setMessageType('success'); setMessageData(response?.data?.response); fetchData(); } else { - setMessageType("error"); + setMessageType('error'); setMessageData(response?.data?.response); } setStockDetails([]); @@ -1464,94 +1470,94 @@ const StockPriceUpdate = () => { setPriceChangeModalOpen(true); }; - const handleExport = async (isStockVariantBased = "Yes") => { + const handleExport = async (isStockVariantBased = 'Yes') => { setExportLoading(true); setPriceChangeModalOpen(false); const uniqueBulkProductData = - isStockVariantBased === "Yes" + isStockVariantBased === 'Yes' ? BulkProductData || [] : (BulkProductData || [])?.filter( (item, index, self) => - index === self.findIndex((p) => p.ProdId === item.ProdId), + index === self.findIndex((p) => p.ProdId === item.ProdId) ); if (!uniqueBulkProductData?.length) { - setMessageType("error"); - setMessageData("No data available to export"); + setMessageType('error'); + setMessageData('No data available to export'); setExportLoading(false); return; } const workbook = new ExcelJS.Workbook(); - const worksheet = workbook.addWorksheet("Products"); + const worksheet = workbook.addWorksheet('Products'); /* ---------------- COLUMN DEFINITIONS ---------------- */ const columns = [ - { header: "Product Name", key: "ProdName", width: 20 }, - ...(isStockVariantBased === "Yes" - ? [{ header: "Variant Name", key: "ProdVariantName", width: 20 }] + { header: 'Product Name', key: 'ProdName', width: 20 }, + ...(isStockVariantBased === 'Yes' + ? [{ header: 'Variant Name', key: 'ProdVariantName', width: 20 }] : []), - ...(isStockVariantBased === "Yes" - ? [{ header: "Batch No", key: "BatchRef", width: 20 }] + ...(isStockVariantBased === 'Yes' + ? [{ header: 'Batch No', key: 'BatchRef', width: 20 }] : []), - ...(hasExcelField("Stock Date") - ? [{ header: "Stock Date", key: "StockDate", width: 15 }] + ...(hasExcelField('Stock Date') + ? [{ header: 'Stock Date', key: 'StockDate', width: 15 }] : []), - ...(hasExcelField("Expiry Date") - ? [{ header: "Exp Date", key: "ExpDate", width: 15 }] + ...(hasExcelField('Expiry Date') + ? [{ header: 'Exp Date', key: 'ExpDate', width: 15 }] : []), - ...(hasExcelField("Stock") - ? [{ header: "Stock", key: "Stock", width: 10 }] + ...(hasExcelField('Stock') + ? [{ header: 'Stock', key: 'Stock', width: 10 }] : []), - ...(hasExcelField("Old MRP") - ? [{ header: "Old MRP", key: "OldMRP", width: 10 }] + ...(hasExcelField('Old MRP') + ? [{ header: 'Old MRP', key: 'OldMRP', width: 10 }] : []), - ...(hasExcelField("Old SP") - ? [{ header: "Old SP", key: "OldSP", width: 10 }] + ...(hasExcelField('Old SP') + ? [{ header: 'Old SP', key: 'OldSP', width: 10 }] : []), - ...(hasExcelField("Old Wholesale Price") - ? [{ header: "Old Wholesale Price", key: "WhSalePrice", width: 14 }] + ...(hasExcelField('Old Wholesale Price') + ? [{ header: 'Old Wholesale Price', key: 'WhSalePrice', width: 14 }] : []), - ...(hasExcelField("Size") - ? [{ header: "Size", key: "Size", width: 10 }] + ...(hasExcelField('Size') + ? [{ header: 'Size', key: 'Size', width: 10 }] : []), - ...(hasExcelField("Stock Maintainence") - ? [{ header: "Stock Maintainence", key: "StockAvailable", width: 18 }] + ...(hasExcelField('Stock Maintainence') + ? [{ header: 'Stock Maintainence', key: 'StockAvailable', width: 18 }] : []), - ...(hasExcelField("UOM Name") - ? [{ header: "UOMName", key: "UOMName", width: 15 }] + ...(hasExcelField('UOM Name') + ? [{ header: 'UOMName', key: 'UOMName', width: 15 }] : []), // ...(hasExcelField("New MRP & New SP") // ? [ - { header: "New MRP", key: "NewMRP", width: 12 }, - { header: "New SP", key: "NewSP", width: 12 }, + { header: 'New MRP', key: 'NewMRP', width: 12 }, + { header: 'New SP', key: 'NewSP', width: 12 }, // ] // : []), - ...(hasExcelField("New Wholesale Price") - ? [{ header: "New Wholesale Price", key: "NewWhSalePrice", width: 14 }] + ...(hasExcelField('New Wholesale Price') + ? [{ header: 'New Wholesale Price', key: 'NewWhSalePrice', width: 14 }] : []), // --- Hidden system columns (always included) --- - { header: "ProdId", key: "ProdId", width: 1 }, + { header: 'ProdId', key: 'ProdId', width: 1 }, - ...(isStockVariantBased === "Yes" - ? [{ header: "InwardDtlId", key: "InwardDtlId", width: 1 }] + ...(isStockVariantBased === 'Yes' + ? [{ header: 'InwardDtlId', key: 'InwardDtlId', width: 1 }] : []), - { header: "key", key: "key", width: 1 }, - { header: "downloadType", key: "downloadType", width: 1 }, + { header: 'key', key: 'key', width: 1 }, + { header: 'downloadType', key: 'downloadType', width: 1 }, ]; worksheet.columns = columns; - worksheet.views = [{ state: "frozen", xSplit: 1, ySplit: 1 }]; + worksheet.views = [{ state: 'frozen', xSplit: 1, ySplit: 1 }]; const headerRow = worksheet.getRow(1); - const newMRPCol = headerRow.values.indexOf("New MRP"); - const newSPCol = headerRow.values.indexOf("New SP"); + const newMRPCol = headerRow.values.indexOf('New MRP'); + const newSPCol = headerRow.values.indexOf('New SP'); const hasNewMRPAndSP = newMRPCol > 0 && newSPCol > 0; /* ---------------- HEADER STYLE ---------------- */ @@ -1559,36 +1565,36 @@ const StockPriceUpdate = () => { const header = cell.value; const isHiddenCol = - header === "key" || - header === "ProdId" || - header === "InwardDtlId" || - header === "downloadType"; + header === 'key' || + header === 'ProdId' || + header === 'InwardDtlId' || + header === 'downloadType'; cell.font = { bold: true, size: isHiddenCol ? 1 : 11, - color: { argb: isHiddenCol ? "FFFFFFFF" : "FF000000" }, + color: { argb: isHiddenCol ? 'FFFFFFFF' : 'FF000000' }, }; cell.alignment = { - horizontal: "center", - vertical: "middle", + horizontal: 'center', + vertical: 'middle', wrapText: true, // ✅ prevents overflow in header }; cell.fill = { - type: "pattern", - pattern: "solid", + type: 'pattern', + pattern: 'solid', fgColor: { - argb: isHiddenCol ? "FFFFFFFF" : "FF52C41A", + argb: isHiddenCol ? 'FFFFFFFF' : 'FF52C41A', }, }; cell.border = isHiddenCol ? undefined : { - right: { style: "thin", color: { argb: "FF000000" } }, - bottom: { style: "thin", color: { argb: "FF000000" } }, + right: { style: 'thin', color: { argb: 'FF000000' } }, + bottom: { style: 'thin', color: { argb: 'FF000000' } }, }; }); @@ -1599,7 +1605,7 @@ const StockPriceUpdate = () => { ProdVariantName: product?.ProdVariantName, BatchRef: product?.BatchRef, StockDate: product?.InwardDate, - ExpDate: product?.ExpDate || "-", + ExpDate: product?.ExpDate || '-', Stock: product?.BalanceQty, OldMRP: product?.MRP, OldSP: product?.SellPrice, @@ -1608,13 +1614,13 @@ const StockPriceUpdate = () => { StockAvailable: product?.StockAvailable, UOMName: product?.UOMName, key: product?.key, - downloadType: isStockVariantBased === "Yes" ? "Variant" : "Product", - NewMRP: "", - NewSP: "", - NewWhSalePrice: "", + downloadType: isStockVariantBased === 'Yes' ? 'Variant' : 'Product', + NewMRP: '', + NewSP: '', + NewWhSalePrice: '', ProdId: product?.ProdId, InwardDtlId: - isStockVariantBased === "Yes" ? product?.InwardDtlId : undefined, + isStockVariantBased === 'Yes' ? product?.InwardDtlId : undefined, }); }); @@ -1627,15 +1633,15 @@ const StockPriceUpdate = () => { const newSPCell = row.getCell(newSPCol); newSPCell.dataValidation = { - type: "custom", + type: 'custom', allowBlank: true, formulae: [ `IFERROR(VALUE(${newSPCell.address}),0) <= IFERROR(VALUE(${newMRPCell.address}),0)`, ], showErrorMessage: true, - errorStyle: "stop", - errorTitle: "Invalid Selling Price", - error: "New SP cannot be greater than New MRP", + errorStyle: 'stop', + errorTitle: 'Invalid Selling Price', + error: 'New SP cannot be greater than New MRP', }; }); } @@ -1662,38 +1668,38 @@ const StockPriceUpdate = () => { const header = worksheet.getRow(1).getCell(colNumber).value; const isHiddenCol = - header === "key" || - header === "ProdId" || - header === "InwardDtlId" || - header === "downloadType"; + header === 'key' || + header === 'ProdId' || + header === 'InwardDtlId' || + header === 'downloadType'; const isEditable = - header === "New MRP" || - header === "New SP" || - header === "New Wholesale Price"; + header === 'New MRP' || + header === 'New SP' || + header === 'New Wholesale Price'; cell.protection = { locked: !isEditable }; cell.alignment = { - vertical: "middle", + vertical: 'middle', wrapText: true, }; if (isHiddenCol) { cell.font = { size: 1, - color: { argb: "FFFFFFFF" }, + color: { argb: 'FFFFFFFF' }, }; cell.fill = { - type: "pattern", - pattern: "solid", - fgColor: { argb: "FFFFFFFF" }, + type: 'pattern', + pattern: 'solid', + fgColor: { argb: 'FFFFFFFF' }, }; } }); }); /* ---------------- PROTECT SHEET ---------------- */ - await worksheet.protect("", { + await worksheet.protect('', { selectLockedCells: false, selectUnlockedCells: true, formatCells: false, @@ -1705,12 +1711,12 @@ const StockPriceUpdate = () => { /* ---------------- DOWNLOAD ---------------- */ const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { - type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); - const link = document.createElement("a"); + const link = document.createElement('a'); link.href = URL.createObjectURL(blob); - link.download = "PriceChange_Data.xlsx"; + link.download = 'PriceChange_Data.xlsx'; link.click(); setExportLoading(false); @@ -1733,8 +1739,8 @@ const StockPriceUpdate = () => { const isAllowed = allowedExcelTypes?.includes(file.type); if (!isAllowed) { Modal.error({ - title: "Invalid File Type", - content: "Only Excel files (.xls, .xlsx) are allowed.", + title: 'Invalid File Type', + content: 'Only Excel files (.xls, .xlsx) are allowed.', }); handleCancelData(); setFileLoading(false); @@ -1748,15 +1754,42 @@ const StockPriceUpdate = () => { const extractedData = extractPriceChangeDataFromExcel(arrayBuffer); - console.log(extractedData, "extractedData"); + console.log(extractedData, 'extractedData'); if ((extractedData || [])?.length === 0) { - setMessageData("No Data Found in Uploaded Sheet"); - setMessageType("error"); + setMessageData('No Data Found in Uploaded Sheet'); + setMessageType('error'); handleCancelData(); setFileLoading(false); return; } - setUploadedData(extractedData); + + // Compare and mark as Old/Modified + const comparedData = extractedData + .map((uploaded) => { + const current = BulkProductData.find( + (p) => + p.ProdId === uploaded.ProdId && + (!uploaded.InwardDtlId || p.InwardDtlId === uploaded.InwardDtlId) + ); + + if (current) { + const isModified = + Number(current.MRP) !== Number(uploaded.NewMRP) || + Number(current.SellPrice) !== Number(uploaded.NewSellPrice) || + Number(current.WhSalePrice || 0) !== + Number(uploaded.NewWholeSalePrice || 0); + + return { + ...uploaded, + isModified, + status: isModified ? 'Modified' : 'Old', + }; + } + + return { ...uploaded, isModified: false, status: 'Old' }; + }) + .sort((a, b) => Number(b.isModified) - Number(a.isModified)); + setUploadedData(comparedData); setFileLoading(false); // setFormValuesFromExtractedData(extractedData); }; @@ -1790,13 +1823,13 @@ const StockPriceUpdate = () => { }; const extractPriceChangeDataFromExcel = (arrayBuffer) => { - const workbook = read(arrayBuffer, { type: "array" }); + const workbook = read(arrayBuffer, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const rows = utils.sheet_to_json(worksheet, { header: 1, raw: false, - defval: "", + defval: '', }); if (!rows.length) return []; @@ -1808,23 +1841,23 @@ const StockPriceUpdate = () => { // Helper to safely get column value const getVal = (row, colName) => { const idx = header.indexOf(colName); - return idx !== -1 ? row[idx] : ""; + return idx !== -1 ? row[idx] : ''; }; const result = dataRows .map((row) => { - const prodId = getVal(row, "ProdId")?.toString().trim(); + const prodId = getVal(row, 'ProdId')?.toString().trim(); if (!prodId) return null; const newMRP = - getVal(row, "New MRP") !== "" ? Number(getVal(row, "New MRP")) : null; + getVal(row, 'New MRP') !== '' ? Number(getVal(row, 'New MRP')) : null; const newSP = - getVal(row, "New SP") !== "" ? Number(getVal(row, "New SP")) : null; + getVal(row, 'New SP') !== '' ? Number(getVal(row, 'New SP')) : null; const newWholesale = - getVal(row, "New Wholesale Price") !== "" - ? Number(getVal(row, "New Wholesale Price")) + getVal(row, 'New Wholesale Price') !== '' + ? Number(getVal(row, 'New Wholesale Price')) : null; // ❌ Must have at least one change @@ -1836,37 +1869,37 @@ const StockPriceUpdate = () => { // 🔹 Product identity localId: uuidv4(), ProdId: prodId, - InwardDtlId: getVal(row, "InwardDtlId") - ? getVal(row, "InwardDtlId").toString() + InwardDtlId: getVal(row, 'InwardDtlId') + ? getVal(row, 'InwardDtlId').toString() : null, // 🔹 Product info - VariantName: getVal(row, "Variant Name") || null, - BatchRef: getVal(row, "Batch No") || null, - ProductName: getVal(row, "Product Name") || null, - Size: getVal(row, "Size") || null, - UOMName: getVal(row, "UOMName") || null, - StockMaintainence: getVal(row, "Stock Maintainence") || null, + VariantName: getVal(row, 'Variant Name') || null, + BatchRef: getVal(row, 'Batch No') || null, + ProductName: getVal(row, 'Product Name') || null, + Size: getVal(row, 'Size') || null, + UOMName: getVal(row, 'UOMName') || null, + StockMaintainence: getVal(row, 'Stock Maintainence') || null, // 🔹 Stock / dates - StockDate: getVal(row, "Stock Date") || null, - ExpDate: getVal(row, "Exp Date") || null, - downloadType: getVal(row, "downloadType") || null, + StockDate: getVal(row, 'Stock Date') || null, + ExpDate: getVal(row, 'Exp Date') || null, + downloadType: getVal(row, 'downloadType') || null, Stock: - getVal(row, "Stock") !== "" ? Number(getVal(row, "Stock")) : null, + getVal(row, 'Stock') !== '' ? Number(getVal(row, 'Stock')) : null, // 🔹 Old prices OldMRP: - getVal(row, "Old MRP") !== "" - ? Number(getVal(row, "Old MRP")) + getVal(row, 'Old MRP') !== '' + ? Number(getVal(row, 'Old MRP')) : null, OldSP: - getVal(row, "Old SP") !== "" ? Number(getVal(row, "Old SP")) : null, + getVal(row, 'Old SP') !== '' ? Number(getVal(row, 'Old SP')) : null, OldWholeSalePrice: - getVal(row, "Old Wholesale Price") !== "" - ? Number(getVal(row, "Old Wholesale Price")) + getVal(row, 'Old Wholesale Price') !== '' + ? Number(getVal(row, 'Old Wholesale Price')) : null, // 🔹 New prices (normalized) @@ -1883,7 +1916,7 @@ const StockPriceUpdate = () => { const handleCancelData = () => { dispatch(emptyExcelData()); if (fileInputRef.current) { - fileInputRef.current.value = ""; + fileInputRef.current.value = ''; } setUploadedData([]); }; @@ -1901,26 +1934,26 @@ const StockPriceUpdate = () => { // If MRP is present, SP must also be present if (newMRP && !newSP) { - setMessageType("error"); + setMessageType('error'); setMessageData( - "If New MRP is provided, New SP must also be provided", + 'If New MRP is provided, New SP must also be provided' ); return; } // If SP is present, MRP must also be present if (newSP && !newMRP) { - setMessageType("error"); + setMessageType('error'); setMessageData( - "If New SP is provided, New MRP must also be provided", + 'If New SP is provided, New MRP must also be provided' ); return; } // New SP cannot be greater than New MRP if (newMRP && newSP && parseFloat(newSP) > parseFloat(newMRP)) { - setMessageType("error"); - setMessageData("New SP cannot be greater than New MRP"); + setMessageType('error'); + setMessageData('New SP cannot be greater than New MRP'); return; } } @@ -1930,10 +1963,15 @@ const StockPriceUpdate = () => { const hasMRP = !!data?.NewMRP; const hasSell = !!data?.NewSellPrice; const hasWholesale = !!data?.NewWholeSalePrice; + const isModified = data?.isModified === true; + // valid cases - if (hasMRP && hasSell) return true; - if (!hasMRP && !hasSell && hasWholesale) return true; + if (hasMRP && hasSell && isModified) return true; + + // ✅ Case 2: Only Wholesale changed + if (!hasMRP && !hasSell && hasWholesale && isModified) return true;; + return false; }) @@ -1943,7 +1981,7 @@ const StockPriceUpdate = () => { NewSellPrice: data?.NewSellPrice, NewMRP: data?.NewMRP, NewWholeSalePrice: data?.NewWholeSalePrice, - AdjComment: "string", + AdjComment: 'string', })); const putData = { @@ -1955,25 +1993,32 @@ const StockPriceUpdate = () => { CreatedBy: UserId, }; + if (!updatedData || updatedData.length === 0) { + setMessageData('Minimum 1 product needs to be changed or added'); + setMessageType('error'); + return; + } + + const res = await dispatch(bulkPriceUpdate(putData))?.unwrap(); if (res?.data?.statusCode === 1) { - setMessageData(res?.data?.response || "Price Updated Successfully"); - setMessageType("success"); + setMessageData(res?.data?.response || 'Price Updated Successfully'); + setMessageType('success'); setUploadedData([]); handleCancelData(); setExcelModalOpen(false); await fetchData(); } else { setMessageData(res?.data?.response); - setMessageType("error"); + setMessageType('error'); } // If validation passes, proceed with submission - console.log("Form validation passed", updatedData); + console.log('Form validation passed', updatedData); } catch (error) { - setMessageType("error"); - setMessageData("Please check all fields and try again"); + setMessageType('error'); + setMessageData('Please check all fields and try again'); } finally { setLoading(false); } @@ -1984,14 +2029,14 @@ const StockPriceUpdate = () => { AppId: AppId, CompId: CompId, BranchId: BranchId, - Type: "GB", - FormType: fieldSetup ? "Price Change" : "Price Change Sheet", + Type: 'GB', + FormType: fieldSetup ? 'Price Change' : 'Price Change Sheet', TypeId: fieldSetup ? categoryId : excelCategoryId, ConfigDtl: (fieldSetup ? selectedFields : selectedExcelFields)?.map( (field) => ({ ConfigId: field, - Access: "Y", - }), + Access: 'Y', + }) ), CreatedBy: UserId, }; @@ -1999,7 +2044,7 @@ const StockPriceUpdate = () => { const response = await dispatch(postFieldSetup(postData))?.unwrap(); if (response?.data?.statusCode === 1) { - setMessageType("success"); + setMessageType('success'); setMessageData(response?.data?.response); if (fieldSetup) { await getFieldSetup(); @@ -2007,8 +2052,8 @@ const StockPriceUpdate = () => { await getExcelFieldSetup(); } } else { - setMessageType("error"); - setMessageData("Failed to set up fields"); + setMessageType('error'); + setMessageData('Failed to set up fields'); } }; @@ -2049,24 +2094,24 @@ const StockPriceUpdate = () => {
- +
- {RadioSelection == "Bulk" && ( + {RadioSelection == 'Bulk' && (
@@ -2094,21 +2139,21 @@ const StockPriceUpdate = () => {
)}
- {RadioSelection == "Single" && ( + {RadioSelection == 'Single' && (
-
+
@@ -2119,7 +2164,7 @@ const StockPriceUpdate = () => { onChangeFunction={(value, option) => HandleStockNames(value, option) } - style={{ width: "240px" }} + style={{ width: '240px' }} options={DataSource} isOnchanges={ProductName ? true : false} /> @@ -2148,17 +2193,17 @@ const StockPriceUpdate = () => {
{
- {(RadioSelection == "Bulk" || - (RadioSelection == "Single" && StockDetails.length > 0)) && ( + {(RadioSelection == 'Bulk' || + (RadioSelection == 'Single' && StockDetails.length > 0)) && (
} disabled={addnewAccess} @@ -2182,10 +2227,10 @@ const StockPriceUpdate = () => { )}
- {RadioSelection == "Single" && ( + {RadioSelection == 'Single' && (
{ >
)} - {RadioSelection == "Bulk" && ( + {RadioSelection == 'Bulk' && (
{ pagination={{ current: Bulkchangepage, pageSize: pageSize, - pageSizeOptions: ["10", "20", "30"], + pageSizeOptions: ['10', '20', '30'], onChange: handlePageChangeBulk, showSizeChanger: false, }} @@ -2232,7 +2277,7 @@ const StockPriceUpdate = () => { open={excelModalOpen} title="Bulk Upload" footer={false} - className={"bulkuploadmodal padding-less-modal"} + className={'bulkuploadmodal padding-less-modal'} handleCancel={() => { setExcelModalOpen(false); handleCancelData(); @@ -2243,24 +2288,24 @@ const StockPriceUpdate = () => { {uploadedData?.length === 0 && (
@@ -2268,7 +2313,7 @@ const StockPriceUpdate = () => {
{ } : () => showPriceChangeModal() } @@ -2276,7 +2321,7 @@ const StockPriceUpdate = () => {
-
+
Export Excel
@@ -2287,29 +2332,29 @@ const StockPriceUpdate = () => { {!fileLoading && (
{/* */}
{ onChange={handleFileUpload} ref={fileInputRef} style={{ - position: "absolute", + position: 'absolute', top: 0, left: 0, - width: "100%", - height: "100%", + width: '100%', + height: '100%', opacity: 0, - cursor: "pointer", + cursor: 'pointer', }} /> - - {" "} - Upload Sheet{" "} + + {' '} + Upload Sheet{' '}
)} {fileLoading && ( -
+
-

+

Processing file...