import React, {
useState,
useRef,
useEffect,
useCallback,
useContext,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
Button,
Form,
Input,
Table,
Space,
Select,
Checkbox,
AutoComplete,
Switch,
Tooltip,
Popconfirm,
} from 'antd';
import { TiDelete } from 'react-icons/ti';
import { CiCalculator1 } from 'react-icons/ci';
import { Tables } from '../../../../Components/Tables/Table';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
import { DeleteFilled } from '@ant-design/icons';
import { Radio } from 'antd';
import moment from 'moment';
import FormHeader from '../../../PageComponents/FormHeader';
import {
changeCustomerDelete,
changeCustomerID,
changeReorderHoldDetails,
ChangeWSProduct,
getSelectedFavItems,
GlobalProductCategorie,
getLayoutproductCard,
GlobalProductSubCategorie,
getAllCustomer,
getCardDataWithoutSub,
getCardDataWithoutSubmodule,
changeSelectedCustId,
changeSelectedOption,
changeHoldOrderDtl,
changeCombofocus,
ChangeSelectedCustDisable,
GlobalReorderHoldDetails,
GlobalBookingType,
GlobalEstimateBooking,
GlobalSelProdWiseEst,
changeSelProdWiseEst,
changeEstimateBooking,
changeOrderType,
GlobalBookingTypeBoth,
changeReorderProductDetails,
ChangeOverAllDiscEstimate,
ChangeOverAllDiscSales,
PreferenceData,
ChangeComboCarddata,
getPreferenceData,
getCustomerForHold,
PostBlockSlots,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { getTemplateData } from '../../../../Features/ThemeChange/ThemeChange';
import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
import { ArrowRightOutlined, CloseSquareFilled } from '@ant-design/icons';
import { InputField } from '../../../../Components/Forms/InputField';
import { Messages } from '../../../../Components/Notifications/Messages';
import Buttons from '../../../../Components/Forms/Buttons';
import ProductForm from '../../../../Pages/BookingScreen/Forms/QuickAdd/QuickAdd.jsx';
import {
GlobalAddCustomerDetails,
getAddCustomerDetails,
postAddCustomerDetails,
triggerCustomerRefresh,
} from '../../../../Features/BookingScreen/Customer/addCustomer';
import {
extractLastNumberOrderId,
getSession,
validateSafeInput,
} from '../../../../Services/Others';
import { getExtTabledata } from '../../../../Features/ExteraCharges/ExtraCharges';
import {
globalExtraChargesType,
ChangeTotalAmount,
globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
import WeightScaleComp from '../../../../Components/WeightScale/weightScale.jsx';
import {
gettinghold,
puttinghold,
changeholddata,
} from '../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import {
changeOrderCardDetails,
GlobalOrderCardDetails,
getProductsearch,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { AiOutlineDownCircle, AiOutlineUpCircle } from 'react-icons/ai';
import '../../../../Styles/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.scss';
import {
IoCloseSharp,
IoPersonAddSharp,
IoSearchOutline,
} from 'react-icons/io5';
import { GrCheckboxSelected } from 'react-icons/gr';
import { BiCustomize } from 'react-icons/bi';
import { DatePicProd } from '../../../../Components/Forms/DatePickerProduct.jsx';
import {
GlobalPreOrderList,
GlobalpreOrderOpen,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import Imageupload from '../../../../Components/Forms/Upload.jsx';
import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { getCombolist } from '../../../../Features/ComboMaster/ComboMaster.js';
import {
ChangeFullFreeProductList,
changeFullOfferAppliedProducts,
changeLoyaltyConsumedQuantities,
} from '../../../../Features/Offer/Offernew/BookingOffernew.js';
import { v4 as uuidv4 } from 'uuid';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';
import { FaEdit, FaMapMarkedAlt, FaTrash } from 'react-icons/fa';
import { MdHome, MdLocationOn } from 'react-icons/md';
import { RadioGrpButton } from '../../../../Components/Forms/RadioGroup.jsx';
const FeaturesFunctionalities = (props) => {
const { closeModal = () => {} } = props;
const applyOffer = useApplyOfferto_CardDetail();
const EditableContext = React.createContext(null);
const EditableContext1 = React.createContext(null);
const CompId = getSession('CompId');
const BranchId = getSession('BranchId');
const AppId = getSession('AppId');
const UserId = getSession('UserId');
const dispatch = useDispatch();
const formRef = useRef();
const formWsRef = useRef();
const formRefExtraCharges = useRef();
const ExtraChargesType = useSelector(globalExtraChargesType);
const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
const ReorderHoldDetails = useSelector(GlobalReorderHoldDetails);
const BookingType = useSelector(GlobalBookingType);
const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
const [dataSource, setDataSource] = useState(
ExtraChargesType.filter((item) => item.ActiveStatus == 'A')
);
const [dataSource1, setDataSource1] = useState(
ExtraChargesType.filter((item) => item.ActiveStatus == 'A')
);
const [ImageUrl, setImageUrl] = useState(null);
const preOrder = useSelector(GlobalpreOrderOpen);
const PreOrderList = useSelector(GlobalPreOrderList);
const withoutPreOrderList = useSelector(GlobalOrderCardDetails);
const PreferenceDatas = useSelector(PreferenceData);
console.log(PreferenceDatas, 'PreferenceDatas');
const CartOrderDetails = preOrder ? PreOrderList : withoutPreOrderList;
const [InitialOutStandingType, setInitialOutStandingType] = useState(null);
const [amountType, setAmountType] = useState('C');
const templateData = useSelector(getTemplateData);
const prodCat = useSelector(GlobalProductCategorie);
const ProdSubCat = useSelector(GlobalProductSubCategorie);
const GlobalAddCustomerDetails1 = useSelector(GlobalAddCustomerDetails);
const GlobEstBooking = useSelector(GlobalEstimateBooking);
const GlobProdwisedata = useSelector(GlobalSelProdWiseEst);
const [hold, setHold] = useState(props.modalOpen);
const [WeightScale, setWeightScale] = useState(props.WeightScale);
const [WeightScale2, setWeightScale2] = useState(true);
const [CusDetails, setCusDetails] = useState(false);
const [zipCodeData, setZipCodeData] = useState(false);
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
const [totalAmount, setTotalAmount] = useState(0);
const [Tabledata, setTabledata] = useState();
const [extdata, setExtdata] = useState([]);
const [extdata1, setExtdata1] = useState([]);
const [SelectData, setSelectData] = useState([]);
const [SelectData2, setSelectData2] = useState([]);
const [oldUserId, setoldUserId] = useState(null);
const [CalcProductRate, setCalcProductRate] = useState();
const [CalcProductWeight, setCalcProductWeight] = useState();
const [WSProductList, setWSProductList] = useState([]);
const [ProductValue, setProductValue] = useState();
const [WSProductDataSource, setWSProductDataSource] = useState([]);
const [WSProductRate, setWSProductRate] = useState(0);
const [WSProductWeight, setWSProductWeight] = useState(0);
const [WSTotalPrice, setWSTotalPrice] = useState(0);
const [WSSelectedStockDetail, setWSSelectedStockDetail] = useState([]);
const [WSSelectedOnekgProd, setWSSelectedOnekgProd] = useState([]);
const [CalcPriceWeightOpen, setCalcPriceWeightOpen] = useState(false);
const [wsport, setwsport] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const [Searchopen, setSearchopen] = useState(false);
const [gender, setGender] = useState('M');
const [isSearching, setIsSearching] = useState(false);
const [suggestionClicked, setSuggestionClicked] = useState(false);
const [selectSearchDefaultValue, setselectSearchDefaultValue] = useState('');
const [TableName, setTableName] = useState([]);
const [Checkbox1, setCheckbox1] = useState(true);
const [selectedProduct, setselectedProduct] = useState();
const [inputValue, setInputValue] = useState('');
const [suggestions, setSuggestions] = useState(['prematix', 'pr']);
const [searchResults, setSearchResults] = useState([]);
const [selectedSearchValue, setselectedSearchValue] = useState('CustMobile');
const [selectedValue, setSelectedValue] = useState(null);
const [offerType, setofferType] = useState('P');
const [OfferValue, setOfferValue] = useState(null);
const [Maritalstatus, setMaritalstatus] = useState('N');
const [allowDecimal, setAllowDecimal] = useState(false);
const [DobDate, setDobDate] = useState();
const [SpouseDobDate, setSpouseDobDate] = useState();
const [anniversaryDate, setanniversaryDate] = useState();
const [customerAddress, setCustomerAddress] = useState();
const appPreferences = useSelector(ApplicationPreferences);
const { selectedDate } = useDateStore();
const salespagefields = appPreferences?.find(
(pref) => pref?.PreferredCatName === 'Sales Page Fields'
)?.PreferenceCatDetails;
const AvailableDate = salespagefields?.find(
(type) =>
type?.PreferredSubCatName?.toLowerCase() === 'available date' &&
type?.PreferredStatus === 'Y'
);
const commonModulePreference = appPreferences?.find(
(preference) => preference?.PreferredCatName === 'Common Module'
)?.PreferenceCatDetails;
const sportsAppPreference = commonModulePreference?.find(
(preference) =>
preference?.PreferredSubCatName === 'SportsApp' &&
preference?.PreferredStatus === 'Y'
);
const [addressPreview, setAddressPreview] = useState([]);
const [addressesList, setAddressesList] = useState([]);
const [addressTypes, setAddressTypes] = useState({});
const [editingIndex, setEditingIndex] = useState(null);
const yesNoOptions = [
{ value: 'A', label: 'Active' },
{ value: 'D', label: 'Deactive' },
];
useEffect(() => {
fetchdata();
getPreference();
}, []);
useEffect(() => {
getPreference();
}, [PreferenceDatas]);
useEffect(() => {
hold ? dispatch(changeCombofocus(true)) : dispatch(changeCombofocus(false));
}, [hold]);
useEffect(() => {
WeightScale
? dispatch(changeCombofocus(true))
: dispatch(changeCombofocus(false));
}, [WeightScale]);
useEffect(() => {
WeightScale2
? dispatch(changeCombofocus(true))
: dispatch(changeCombofocus(false));
}, [WeightScale2]);
useEffect(() => {
if (preOrder) {
if (GlobalExtraCharge?.length > 0) {
if (
GlobalExtraCharge?.[0]?.ProdId === null ||
(GlobalExtraCharge?.[0]?.ProdId === '' &&
GlobalExtraCharge?.[0]?.InwardDtlId === '')
) {
setCheckbox1(true);
} else {
setCheckbox1(false);
}
} else {
setCheckbox1(true);
}
}
}, [preOrder]);
useEffect(() => {
if (props?.mobileNo && String(props?.mobileNo)?.length === 10) {
handleSelectSuggestion(String(props?.mobileNo));
}
}, [props?.mobileNo]);
useEffect(() => {
const { addcustomer, ExtraCharges, QuickAdd, reprint } = props;
if (addcustomer || ExtraCharges || QuickAdd || reprint) {
dispatch(changeCombofocus(true));
} else {
dispatch(changeCombofocus(false));
}
}, [props.addcustomer, props.ExtraCharges, props.QuickAdd, props.reprint]);
useEffect(() => {
formRef.current?.getFieldsValue()?.Zip === undefined &&
setZipCodeData(false);
}, [inputValue]);
let CustIdForDynamicChange = ` ${' '}${suggestions?.[0]?.CustId?.match(/(.+)-\d+$/)?.[1]}-`;
const statusFormatters = (index) => {
const rows = [...TableName];
const remove = rows?.filter(
(e) => !(e.ProdName === index?.ProdName && e.UniqueId === index?.UniqueId)
);
setTableName(remove);
};
const fetchdata = async () => {
let res = await dispatch(
getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId })
).unwrap();
if (res?.data?.statusCode == 1) {
setSuggestions(res?.data?.data);
}
};
const handleSelectSuggestion = (suggestion) => {
checkExistingCustomer(
suggestions.filter((a) => a[selectedSearchValue] === suggestion)?.[0]
?.CustMobile || suggestion
);
setInputValue(
suggestions.filter((a) => a[selectedSearchValue] === suggestion)?.[0]
?.CustMobile || suggestion
);
};
const getPreference = async () => {
// const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
// const { data: res } = await dispatch(getPreferenceData(data)).unwrap() // comment for karthiga
const decimalSetting = PreferenceDatas?.[0]?.SettingDtlDetails?.find(
(setting) =>
setting?.SettingIdName?.toLowerCase() === 'decimal' &&
setting?.SettingValue === 'Y'
);
if (decimalSetting) {
setAllowDecimal(true);
}
};
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 options = suggestions
? suggestions
?.filter((item) =>
selectedSearchValue === 'CustName' ? item.CustName !== null : item
)
.map((item) => ({
value: item?.CustMobile,
label:
selectedSearchValue === 'CustMobile'
? `${item?.CustMobile} - ${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`
: selectedSearchValue === 'CustId'
? `${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}${item?.CustName ? ' - ' : ''} ${item?.CustName ? item?.CustName : ''} - ${item?.CustMobile}`
: selectedSearchValue === 'CustName' &&
item?.CustName !== null &&
`${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${item?.CustMobile} - ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`,
CustMobile: item?.CustMobile,
CustId: item?.CustId?.match(/-(\d+)$/)?.[1],
CustName: item?.CustName,
}))
: GlobalAddCustomerDetails1?.map((item) => ({
value: item.CustMobile,
label: `${item?.CustName} ${item?.CustMobile}`,
CustMobile: item?.CustMobile,
CustId: item?.CustId,
CustName: item?.CustName,
}));
const handleYesOrNoChange = (value) => {
setSelectedValue(value);
formRef.current?.setFieldsValue({ OfferActiveStatus: value });
};
const columnshold = [
{
title: 'Order.Id',
key: 'productDetails',
dataIndex: 'productDetails',
align: 'center',
width: '150px',
onCell: (record) => {
const productDetails = record?.productDetails;
const Combodtl =
record?.productDetails?.[0]?.comboDtl?.[0]?.ComboInwardDetails?.[0]
?.ComboDetails;
return {
onClick: () => {
HoldPutfun(productDetails, record, Combodtl);
},
};
},
render: (productDetails, record) => (
HoldPutfun(productDetails, record)}
>
{record?.OrderId &&
extractLastNumberOrderId(record?.OrderId, record?.FYStatus)}
),
},
{
title: 'Order Type',
key: 'productDetails',
dataIndex: 'productDetails',
align: 'center',
width: '150px',
onCell: (record) => {
const productDetails = record?.productDetails;
const Combodtl =
record?.productDetails?.[0]?.comboDtl?.[0]?.ComboInwardDetails?.[0]
?.ComboDetails;
return {
onClick: () => {
HoldPutfun(productDetails, record, Combodtl);
},
};
},
render: (productDetails, record) => (
HoldPutfun(productDetails, record)}
>
{record?.OrderType == 'E' ? 'Estimate' : 'Sales'}
),
},
...(sportsAppPreference
? [
{
title: 'Subcategory',
key: 'productDetails',
dataIndex: 'productDetails',
align: 'center',
width: '150px',
onCell: (record) => {
const productDetails = record?.productDetails;
const Combodtl =
record?.productDetails?.[0]?.comboDtl?.[0]
?.ComboInwardDetails?.[0]?.ComboDetails;
return {
onClick: () => {
HoldPutfun(productDetails, record, Combodtl);
},
};
},
render: (productDetails, record) => (
HoldPutfun(productDetails, record)}
>
{record?.productDetails?.[0]?.ProdSubCatName}
),
},
]
: []),
{
title: 'Orders',
key: 'productDetails',
dataIndex: 'productDetails',
width: '150px',
onCell: (record) => {
const productDetails = record?.productDetails;
return {
onClick: () => {
HoldPutfun(productDetails, record);
},
};
},
render: (productDetails, record) => (
HoldPutfun(productDetails, record)}
>
{productDetails?.length > 0 &&
productDetails
?.map(
(item) =>
item.ProdName +
('(' + item.Size + '' + ' ' + item.UomName) +
')'
)
.join(',')}
),
},
{
title: 'Customer Name/Mobile.No/Cust.Id',
key: 'sno',
dataIndex: 'CustSuppName',
width: '150px',
onCell: (record) => {
const productDetails = record?.productDetails;
return {
onClick: () => {
HoldPutfun(productDetails, record);
},
style: { cursor: 'pointer' },
};
},
render: (text, record) =>
record?.CustSuppName || record?.CustSuppMobileNo || '-',
},
{
title: 'Delete',
key: 'sno',
width: '150px',
render: (record) => (
statusFormatter(record)}
/>
),
},
];
const WSStockColumns = [
{
title: 'Stock Quantity',
dataIndex: 'BalanceQty',
key: 'BalanceQty',
align: 'right',
onCell: (record) => {
return {
onClick: () => {
GetProductRate(record);
},
};
},
render: (text, row) => (
{row.BalanceQty ? row.BalanceQty : 'Stock Not Maintained'}
),
},
{
title: 'Amount',
dataIndex: 'SellPrice',
key: 'SellPrice',
align: 'right',
onCell: (record) => {
return {
onClick: () => {
GetProductRate(record);
},
};
},
},
];
useEffect(() => {
setWeightScale(props.WeightScale);
}, [props.WeightScale]);
// useEffect(() => {
// if (!props.addcustomer) {
// formRef.current?.resetFields();
// setZipCodeData(false);
// }
// }, [props.addcustomer]);
const ExtTabledata = async () => {
const data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
};
await dispatch(getExtTabledata(data)).unwrap();
};
useEffect(() => {
setDataSource(
ExtraChargesType.filter(
(item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
)
);
setDataSource1(
ExtraChargesType.filter(
(item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
)
);
}, [ExtraChargesType]);
useEffect(() => {
if (props.ExtraCharges == true) {
if (ExtraChargesType?.length === 0) {
ExtTabledata();
}
}
}, [props.ExtraCharges]);
useEffect(() => {
setTotalAmount(
extdata.reduce((sum, item) => sum + item.QTY * item.Price, 0)
);
}, [extdata]);
useEffect(() => {
setselectedProduct();
if (GlobalExtraCharge?.length === 0) {
setTableName([]);
setExtdata([]);
setSelectData([]);
}
}, [Checkbox1]);
useEffect(() => {
if (GlobalExtraCharge?.length > 0) {
if (
GlobalExtraCharge?.[0]?.ProdId === null ||
(GlobalExtraCharge?.[0]?.ProdId === '' &&
GlobalExtraCharge?.[0]?.InwardDtlId === '')
) {
let globalexdata = GlobalExtraCharge?.map((item) => {
let mappedItem = {
UniqueId: item?.ExtraChargeId,
QTY: item?.OrderQty,
Price: item?.OrderRate,
ProdId: null,
InwardDtlId: null,
ExtraChargeType: item?.ExtraChargeType,
TotalAmt: item?.TotalAmt,
TaxAmt: item?.TaxAmt,
ProdName: item?.ProdName,
TaxId: item?.TaxId,
TaxPercentage: item?.TaxPercentage,
SinglePc: null,
};
// Add SalesId only if it exists
if (item?.SalesId) {
mappedItem['SalesId'] = item?.SalesId;
}
return mappedItem;
});
setExtdata(globalexdata);
setSelectData(globalexdata?.map((item) => item.UniqueId));
let mergedArray = mergearrays(dataSource, globalexdata);
setDataSource(mergedArray);
} else {
let globalexdata = GlobalExtraCharge?.map((item) => {
let mappedItem = {
UniqueId: item?.ExtraChargeId,
QTY: item?.OrderQty,
Price: item?.OrderRate * item?.OrderQty,
ProdId: item?.ProdId,
InwardDtlId: item?.InwardDtlId,
ProdName: item?.ProdName,
ExtraChargeType: item?.ExtraChargeType,
TotalAmt: item?.TotalAmt,
TaxAmt: item?.TaxAmt,
BookingTypeName: item?.BookingTypeName,
BookingType: item?.BookingType,
TaxId: item?.TaxId,
TaxPercentage: item?.TaxPercentage,
SinglePc: item?.SinglePc,
};
// Add SalesId only if it exists
if (item?.SalesId) {
mappedItem['SalesId'] = item?.SalesId;
}
return mappedItem;
});
setCheckbox1(false);
setTableName(globalexdata);
setSelectData([]);
}
} else {
setTableName([]);
setExtdata([]);
setSelectData([]);
}
}, [GlobalExtraCharge]);
function mergearrays(array1, array2) {
let mergedArray = [];
// Merge array1 into mergedArray
mergedArray = array1.slice();
// Merge array2 into mergedArray, ensuring unique objects based on UniqueId
for (let item2 of array2) {
let existingItemIndex = mergedArray.findIndex(
(item) => item.UniqueId === item2.UniqueId
);
if (existingItemIndex !== -1) {
// If item2 exists in mergedArray, update its properties
mergedArray[existingItemIndex] = {
...mergedArray[existingItemIndex],
...item2,
};
} else {
// If item2 doesn't exist in mergedArray, add it
mergedArray.push(item2);
}
}
return mergedArray;
}
useEffect(
() => {
if (WSProductWeight > 0 && WSProductRate > 0) {
WSTotalCalculation();
}
},
[WSProductWeight],
[WSProductRate]
);
const addeddata = (record) => {
if (SelectData.includes(record.UniqueId)) {
if (totalAmount > 0) {
setTotalAmount(totalAmount - record.Price * parseInt(record.QTY));
const remove = extdata?.filter(
(item) => item.UniqueId !== record.UniqueId
);
setExtdata(remove);
setSelectData(SelectData?.filter((a) => a != record.UniqueId));
}
} else {
setSelectData([...SelectData, record.UniqueId]);
setTotalAmount(totalAmount + record.Price * parseInt(record.QTY));
let data = {
ExtraChargeType: record.ExtraChargeType,
Price: record.Price,
QTY: parseInt(record.QTY),
UniqueId: record.UniqueId,
TotalAmt: parseFloat(
formatAmount(parseInt(record.Price) * parseInt(record.QTY))
),
TaxAmt: formatAmount(
((record.Price * record.TaxPercentage) /
(100 + record.TaxPercentage)) *
record.QTY
),
TaxId: record.TaxId,
TaxPercentage: record.TaxPercentage,
};
setExtdata([data, ...extdata]);
}
};
const formatAmount = (value) => {
return allowDecimal
? parseFloat(value || 0).toFixed(2)
: Math.round(value || 0);
};
const addeddata1 = (record) => {
// Check if the UniqueId of the record is included in SelectData2
if (SelectData2.includes(record.UniqueId)) {
// If included, remove the record from extdata1 and update SelectData2
const remove = extdata1?.filter(
(item) => item.UniqueId !== record.UniqueId
);
setExtdata1(remove);
setSelectData2(SelectData2?.filter((a) => a !== record.UniqueId));
} else {
// If not included, check for duplicates in extdata1 based on ExtraChargeType and UniqueId
const isDuplicate = TableName?.some(
(item) =>
item.InwardDtlId +
' ' +
item.BookingTypeName +
' ' +
item.SinglePc ===
selectedProduct && item.UniqueId === record.UniqueId
);
if (!isDuplicate) {
// If not a duplicate, add the UniqueId to SelectData2 and construct data object
setSelectData2([...SelectData2, record.UniqueId]);
let data = {
ExtraChargeType: record.ExtraChargeType,
Price: record.Price,
QTY: parseInt(record.QTY),
UniqueId: record.UniqueId,
TotalAmt: parseFloat(
formatAmount(parseInt(record.Price) * parseInt(record.QTY))
),
TaxAmt: formatAmount(
((record.Price * record.TaxPercentage) /
(100 + record.TaxPercentage)) *
record.QTY
),
TaxId: record?.TaxId,
TaxPercentage: record.TaxPercentage,
SinglePc: record?.SinglePc,
};
// Add the constructed data object to extdata1
setExtdata1([data, ...extdata1]);
}
// If it's a duplicate, you can handle it accordingly (e.g., show a message)
else {
setMessageType('error');
setMessageData('Data Already Exists');
}
}
};
const ProfuctName = CartOrderDetails?.find(
(e) =>
e.InwardDtlId + ' ' + e.BookingTypeName + ' ' + e.SinglePc ==
selectedProduct
);
const producttName = ProfuctName?.ProdName;
const globalamount1 = () => {
if (selectedProduct) {
setSelectData2([]);
setExtdata1([]);
const newArray = extdata1?.map((obj) => ({
...obj,
ProdName:
ProfuctName?.ProdVariantName !== 'Variant 1'
? `${ProfuctName?.ProdName} (${ProfuctName.Size} ${ProfuctName.UomName}) (${ProfuctName.ProdVariantName}${BookingTypeBoth ? ` (${ProfuctName?.BookingTypeName})` : ''})`
: `${ProfuctName?.ProdName} (${ProfuctName.Size} ${ProfuctName.UomName}) ${BookingTypeBoth ? ` (${ProfuctName?.BookingTypeName})` : ''}`,
InwardDtlId: ProfuctName?.InwardDtlId,
ProdId: ProfuctName?.ProdId,
BookingTypeName: ProfuctName?.BookingTypeName,
BookingType: ProfuctName?.BookingType,
// booking type no came from global booking
SinglePc: ProfuctName?.SinglePc,
}));
setTableName([...TableName, ...newArray]);
}
};
const globalamount = async (data) => {
setSelectData2([]);
setTableName([]);
props.ExtraChargesCancle();
const modifiedData = data?.map(
({ UniqueId, ExtraChargeType, Price, QTY, ...rest }) => ({
...rest,
ExtraChargeId: UniqueId,
ExtraChargeType: ExtraChargeType,
ProdId: null,
InwardDtlId: '',
OrderRate: Price,
OrderQty: QTY,
OrderType:
GlobEstBooking === 'OvrAllEst' ? 'E' : preOrder ? 'PRE' : 'S',
SinglePc: null,
BookingTypeName: rest?.BookingTypeName,
BookingType: rest?.BookingType,
})
);
await dispatch(ChangeTotalAmount(modifiedData));
};
const globalamount2 = async (data) => {
setTotalAmount(0);
props.ExtraChargesCancle();
setDataSource(
ExtraChargesType.filter(
(item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
)
);
const modifiedData = data?.map(
({ UniqueId, ExtraChargeType, QTY, Price, ProdName, ...item }) => ({
...item,
SinglePc: item?.SinglePc ? item?.SinglePc : 'N',
ExtraChargeId: UniqueId,
ExtraChargeType: ExtraChargeType,
OrderQty: QTY,
OrderRate: Price / QTY,
ProdName: ProdName,
OrderType:
GlobEstBooking === 'OvrAllEst'
? 'E'
: GlobEstBooking === 'ParEst'
? GlobProdwisedata?.includes(item?.InwardDtlId)
? 'E'
: 'S'
: preOrder
? 'PRE'
: 'S',
Size: item?.Size,
UomName: item?.UomName,
ProdVariantName: item?.ProdVariantName,
BookingTypeName: item?.BookingTypeName,
BookingType: item?.BookingType,
})
);
await dispatch(ChangeTotalAmount(modifiedData));
};
const EditableRow = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
);
};
const EditableRow1 = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
);
};
const onChangeProduct = (e) => {
formRefExtraCharges.current.setFieldsValue({
Extracharges: e,
});
setselectedProduct(e);
};
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
const form = useContext(EditableContext);
useEffect(() => {
if (editing) {
inputRef?.current?.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({
[dataIndex]: record[dataIndex],
});
};
const save = async () => {
try {
const values = await form.validateFields();
toggleEdit();
handleSave({
...record,
...values,
});
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
};
let childNode = children;
if (editable) {
childNode = editing ? (
) : (
{children}
);
}
return {childNode} | ;
};
const EditableCell1 = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing1, setEditing1] = useState(false);
const inputRef1 = useRef(null);
const form1 = useContext(EditableContext1);
useEffect(() => {
if (editing1) {
inputRef1?.current?.focus();
}
}, [editing1]);
const toggleEdit1 = () => {
setEditing1(!editing1);
form1.setFieldsValue({
[dataIndex]: record[dataIndex],
});
};
const save1 = async () => {
try {
const values = await form1.validateFields();
toggleEdit1();
handleSave1({
...record,
...values,
});
} catch (errInfo) {}
};
let childNode = children;
if (editable) {
childNode = editing1 ? (
) : (
{children}
);
}
return {childNode} | ;
};
const calculateTaxAmount = (record) => {
return (
((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
record.QTY
);
};
const WithoutTaxAmountTaxAmount = (record) => {
return (
record.Price * record.QTY -
((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
record.QTY
);
};
const WithTaxAmountTaxAmount = (record) => {
return record.Price * record.QTY;
};
const WithoutTaxAmountTaxAmount2 = (record) => {
return record.Price - record.TaxAmt;
};
const defaultColumns = [
{
title: 'ExtraCharge Type',
key: 'ExtraChargeType',
dataIndex: 'ExtraChargeType',
width: '200px',
},
{
title: 'QTY',
key: 'QTY',
dataIndex: 'QTY',
align: 'right',
width: '100px',
editable: Checkbox1 ? true : false,
},
{
title: 'Price',
key: 'Price',
dataIndex: 'Price',
align: 'right',
width: '100px',
render: (text, record) => (
{formatAmount(WithoutTaxAmountTaxAmount(record))}
),
},
{
title: 'Tax Amt',
key: 'TotalTaxAmt',
dataIndex: 'TotalTaxAmt',
align: 'right',
width: '100px',
render: (text, record) => (
{formatAmount(calculateTaxAmount(record))}
),
},
{
title: 'Amt',
key: 'Price',
dataIndex: 'Price',
align: 'right',
width: '100px',
render: (text, record) => (
{formatAmount(WithTaxAmountTaxAmount(record))}
),
},
{
title: 'Action',
key: 'Action',
dataIndex: 'Action',
width: '80px',
render: (text, record) => (
addeddata(record)}
disabled={
Object.keys(ReorderHoldDetails).length !== 0 &&
BookingType === 'Dine In' &&
GlobalExtraCharge.some(
(item) => item.ExtraChargeId === record.UniqueId
)
? true
: false
}
/>
),
},
];
const defaultColumns1 = [
{
title: 'ExtraCharge Type',
key: 'ExtraChargeType',
dataIndex: 'ExtraChargeType',
width: '200px',
},
{
title: 'QTY',
key: 'QTY',
dataIndex: 'QTY',
align: 'right',
width: '100px',
// editable: Checkbox1 ? true : false,
},
{
title: 'Price1',
key: 'Price',
dataIndex: 'Price',
align: 'right',
width: '100px',
render: (text, record) => {
return (
{formatAmount(WithoutTaxAmountTaxAmount(record))}
);
},
},
{
title: 'Tax Amt',
key: 'TotalTaxAmt',
dataIndex: 'TotalTaxAmt',
align: 'right',
width: '100px',
render: (text, record) => (
{formatAmount(calculateTaxAmount(record))}
),
},
{
title: 'Amt',
key: 'Price',
dataIndex: 'Price',
align: 'right',
width: '100px',
render: (text, record) => (
{formatAmount(WithTaxAmountTaxAmount(record))}
),
},
{
title: 'Action',
key: 'Action',
dataIndex: 'Action',
width: '80px',
render: (text, record) => (
addeddata1(record)}
/>
),
},
];
const handleSave = (row) => {
const newData = [...dataSource];
const index = newData.findIndex((item) => row.UniqueId === item.UniqueId);
const item = newData[index];
if (SelectData?.includes(row.UniqueId)) {
const isDuplicate = extdata?.some(
(item) => item.UniqueId === row.UniqueId
);
const remove = extdata?.filter((item) => item.UniqueId !== row.UniqueId);
let data = {
ExtraChargeType: row.ExtraChargeType,
Price: row.Price,
QTY: parseInt(row.QTY),
TaxAmt: formatAmount(
((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage)) *
row.QTY
),
TotalAmt: row.Price * row.QTY,
// ((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage) *row.QTY ).toFixed(2),
TaxId: row.TaxId,
TaxPercentage: row.TaxPercentage,
UniqueId: row.UniqueId,
};
setExtdata([...remove, data]);
}
newData.splice(index, 1, {
...item,
...row,
});
// let vv={...newData,
// TotalTaxAmt:(row.Price * row.TaxPercentage) / (100 + row.TaxPercentage) * parseInt(row.QTY)
// }
const newArray = newData.map((obj) => ({
...obj,
// TotalTaxAmt: parseFloat((obj.Price * obj.TaxPercentage) / (100 + obj.TaxPercentage) * parseInt(obj.QTY)).toFixed(2)
}));
setDataSource(newArray);
};
const handleSave1 = (row) => {
const newData = [...TableName];
const index = newData.findIndex(
(item) => row.UniqueId === item.UniqueId && row.ProdName === item.ProdName
);
const item = newData[index];
const tax = dataSource?.find((e) => e.UniqueId == item.UniqueId);
let Taxx = tax?.TaxPercentage;
let Price2 = tax?.Price;
const hasUniqueId = TableName.some(
(item) => item.UniqueId === row.UniqueId
);
if (hasUniqueId) {
let updateQty = [...TableName];
updateQty[index] = {
ProdName: row.ProdName,
ExtraChargeType: row.ExtraChargeType,
Price: Price2 * row.QTY,
QTY: parseInt(row.QTY),
ProdId: row.ProdId,
InwardDtlId: row.InwardDtlId,
UniqueId: row.UniqueId,
//((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
TaxAmt: formatAmount(
((Price2 * Taxx) / (100 + Taxx)) * parseInt(row.QTY)
),
TotalAmt: formatAmount(parseInt(Price2) * parseInt(row.QTY)),
BookingTypeName: row.BookingTypeName,
};
setTableName(updateQty);
}
newData.splice(index, 1, {
...item,
...row,
});
};
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
const components1 = {
body: {
row: EditableRow1,
cell: EditableCell1,
},
};
const ExtraChargescolumns = [
{
title: 'Sl.No',
key: 'sno',
render: (text, object, index) => (
{index + 1}
),
align: 'center',
width: '150px',
},
{
title: 'Product Name',
dataIndex: 'ProdName',
key: 'ProdName',
width: '150px',
render: (text, record) => (
{record?.ProdName + '(' + record?.BookingTypeName + ')'}
),
},
{
title: 'EXTRACHARGE TYPE',
dataIndex: 'ExtraChargeType',
key: 'ExtraChargeType',
align: 'right',
width: '150px',
},
{
title: 'Price',
dataIndex: 'Price',
key: 'Price',
align: 'right',
width: '150px',
render: (text, record) => (
{formatAmount(WithoutTaxAmountTaxAmount2(record))}
),
},
{
title: 'QTY',
dataIndex: 'QTY',
key: 'QTY',
align: 'center',
width: '200px',
editable: true,
},
{
title: ' Tax AMT',
dataIndex: 'TaxAmt',
key: 'ProdId',
align: 'right',
width: '150px',
render: (text) => {safeRound(text)},
},
{
title: 'AMT',
dataIndex: 'TotalAmt',
key: 'ProdId',
align: 'right',
width: '150px',
render: (amt) => {safeRound(amt)},
},
{
title: 'Action',
dataIndex: 'Action',
key: 'Action',
align: 'center',
render: (_, record, index) => (
{Object.keys(ReorderHoldDetails).length !== 0 &&
BookingType === 'Dine In' &&
GlobalExtraCharge?.some(
(item) =>
item.ExtraChargeId === record.UniqueId &&
item.InwardDtlId === record.InwardDtlId
) ? (
) : (
statusFormatters(record, index)}
/>
)}
),
},
];
const columns = defaultColumns?.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
};
});
const columns1 = ExtraChargescolumns?.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave1,
}),
};
});
const handleToggle = () => {
setIsOpen(!isOpen);
};
useEffect(() => {
setHold(props.modalOpen);
}, [props.modalOpen]);
useEffect(() => {
if (hold == true) {
holding();
dispatch(changeCustomerDelete('Deleted'));
}
}, [hold]);
useEffect(() => {
if (customerAddress && customerAddress[0]?.CustomerAddressDtl) {
const addressList = customerAddress[0].CustomerAddressDtl.map((addr) => ({
ActiveStatus: addr.ActiveStatus,
Address1: addr.Address1 || '',
Address2: addr.Address2 || '',
Zip: addr.Zip || '',
AddId: addr.AddId || '',
City: addr.City || '',
Dist: addr.Dist || '',
State: addr.State || '',
Latitude: addr.Latitude || '',
Longitude: addr.Longitude || '',
AddressType: addr.AddressType || '',
}));
console.log(addressList, 'ddddddddddddd');
const prefilled = {};
addressList.forEach((addr, idx) => {
switch (addr.AddressType) {
case 'Both Address':
prefilled[idx] = [
'Delivery Address',
'Billing Address',
'Both Address',
];
break;
case 'Delivery Address':
prefilled[idx] = ['Delivery Address'];
break;
case 'Billing Address':
prefilled[idx] = ['Billing Address'];
break;
default:
prefilled[idx] = [];
break;
}
});
setAddressTypes(prefilled);
setAddressesList(addressList);
setAddressPreview(addressList);
// setZipCodeData(true);
}
}, [customerAddress]);
const pinCodeChange = (e) => {
const value = e.target.value;
if (value.length === 6) {
getPincodeValues(value);
} else {
setZipCodeData(false);
}
};
const getPincodeValues = async (pinCode) => {
try {
const res = await fetch(
`https://api.postalpincode.in/pincode/${pinCode}`
);
const response = await res.json();
if (response[0]?.Status === 'Success') {
const postOffice = response[0].PostOffice?.[0];
setZipCodeData(true);
formRef.current?.setFieldsValue({
City: postOffice?.Block || postOffice?.Name || '',
Dist: postOffice?.District || '',
State: postOffice?.State || '',
});
} else {
setZipCodeData(false);
formRef.current?.setFieldsValue({
City: '',
Dist: '',
State: '',
});
}
} catch (error) {
console.error('Error fetching pincode info:', error);
setZipCodeData(false);
}
};
// const getPincodeValues = async (pinCode) => {
// let response = '';
// await fetch(`https://api.postalpincode.in/pincode/${pinCode}`)
// .then((res) => res.text())
// .then((text) => (response = JSON.parse(text)));
// if (response[0]['Status'] === 'Success') {
// setZipCodeData(true);
// formRef.current?.setFieldsValue({
// City: response[0]['PostOffice'][0]['Block'],
// Dist: response[0]['PostOffice'][0]['District'],
// State: response[0]['PostOffice'][0]['State'],
// });
// } else {
// setZipCodeData(false);
// }
// };
const onComplete = useCallback(() => {
setMessageData(null);
setMessageType(null);
}, []);
const customerData = async (e) => {
let data = {
MobileNo: e,
CompId: getSession('CompId'),
BranchId: getSession('BranchId'),
AppId: getSession('AppId'),
};
let response = await dispatch(getAddCustomerDetails(data)).unwrap();
if (response?.data?.statusCode === 1) {
setoldUserId(response?.data?.data?.[0]?.UserId);
setCustomerAddress(response?.data?.data);
if (response?.data?.data?.[0]?.Zip) {
getPincodeValues(response?.data?.data?.[0].Zip);
}
if (response?.data?.data?.[0]?.OfferActiveStatus) {
setSelectedValue(response?.data?.data?.[0]?.OfferActiveStatus);
}
if (response?.data?.data?.[0]?.OfferType) {
setofferType(response?.data?.data?.[0]?.OfferType);
}
if (response?.data?.data?.[0]?.MarriedStatus) {
setMaritalstatus(response?.data?.data?.[0]?.MarriedStatus);
}
if (response?.data?.data?.[0]?.SpouseDOB) {
setSpouseDobDate(response?.data?.data?.[0]?.SpouseDOB);
}
if (response?.data?.data?.[0]?.AnniversaryDate) {
setanniversaryDate(response?.data?.data?.[0]?.AnniversaryDate);
}
if (response?.data?.data?.[0]?.CustDOB) {
setDobDate(response?.data?.data?.[0]?.CustDOB);
}
if (
response?.data?.data?.[0]?.OfferValue == 0 ||
response?.data?.data?.[0]?.OfferValue
) {
setOfferValue(
response?.data?.data?.[0]?.OfferValue
? response?.data?.data?.[0]?.OfferValue
: 0
);
}
formRef.current?.setFieldsValue(response?.data?.data?.[0]);
if (response?.data?.data?.[0]?.InitialOutStanding) {
setInitialOutStandingType(
response?.data?.data?.[0]?.InitialOutStanding
);
}
} else if (response?.data?.statusCode === 0) {
setoldUserId(null);
!Searchopen && formRef.current?.resetFields();
!Searchopen && formRef.current?.setFieldsValue({ CustMobile: e });
Searchopen && setCusDetails(false);
}
};
const handleSubmit = async (value) => {
let PostData = value;
PostData['CompId'] = getSession('CompId');
PostData['BranchId'] = getSession('BranchId');
PostData['AppId'] = getSession('AppId');
PostData['CreatedBy'] = getSession('UserId');
// PostData['Document'] = ImageUrl ? ImageUrl : null;
PostData['CustomerProfile'] = ImageUrl ? ImageUrl : null;
PostData['InitialOutStanding'] = parseInt(value?.OutStandingAmount);
if (oldUserId) {
PostData['UserId'] = oldUserId;
}
if (offerType) {
PostData['OfferType'] = offerType;
}
if (Maritalstatus == 'N') {
PostData['MarriedStatus'] = 'N';
PostData['CustDOB'] = DobDate;
}
if (Maritalstatus == 'Y') {
PostData['MarriedStatus'] = 'Y';
PostData['CustDOB'] = DobDate;
PostData['SpouseDOB'] = SpouseDobDate;
PostData['AnniversaryDate'] = anniversaryDate;
}
const addedAddresses = addressesList || [];
const validAddresses = addedAddresses?.filter(
(addr) => addr?.Address1 && addr?.Zip
);
PostData['CustomerAddressDtl'] = validAddresses;
let response = await dispatch(postAddCustomerDetails(PostData)).unwrap();
if (response?.data?.statusCode == 1) {
fetchdata();
dispatch(changeSelectedOption(null));
dispatch(
changeCustomerID(
response?.data?.CustomerDetails?.[
response?.data?.CustomerDetails.length - 1
]
)
);
dispatch(
changeSelectedCustId(response?.data?.CustomerDetails?.[0]?.CustId)
);
setMessageType('success');
setMessageData('Customer Added Successfully');
setInputValue('');
setoldUserId(null);
dispatch(triggerCustomerRefresh());
formRef.current?.resetFields();
props.handleAddCustomerCancel();
} else {
setMessageType('error');
setMessageData(response?.data?.response);
}
setIsOpen(false);
setSearchopen(false);
setCusDetails(false);
setselectedSearchValue('CustMobile');
};
const checkExistingCustomer = (value) => {
if (!isNaN(value)) {
if (value?.length == 10) {
customerData(value);
setCusDetails(true);
} else {
setCusDetails(false);
}
} else {
if (value?.length == 50) {
customerData(value);
setCusDetails(true);
} else {
setCusDetails(false);
}
}
};
const holding = async () => {
const data = { CompId: CompId, BranchId: BranchId, AppId: AppId };
let response = await dispatch(gettinghold(data)).unwrap();
if (response?.data?.statusCode == 1) {
let modifiedData = response?.data?.data?.map((item) => {
return {
...item,
productDetails: item.productDetails.map((product) => {
// Clone the product to avoid modifying the original object
let newProduct = { ...product };
if (product.Type === 'P') {
if (product.SinglePc === 'Y') {
newProduct.UomName = 'PCS';
newProduct.MRP = newProduct.OrderRate;
}
} else {
newProduct.ProdName = newProduct.ProdName;
newProduct.Size = 1;
newProduct.UomName = 'Combo';
newProduct.MRP = newProduct.OrderRate;
}
return newProduct; // Return the modified product
}),
};
});
setTabledata(modifiedData);
}
};
const statusFormatter = async (row) => {
let orderListIds = [];
orderListIds.push(row.OrderId);
let putData = { OrderId: orderListIds };
let response = await dispatch(puttinghold(putData)).unwrap();
const extractedData = row?.productDetails?.map((prod) => ({
ProdId: prod.ProdId,
InwardDtlId: prod.InwardDtlId,
SinglePc: prod.SinglePc,
Qty: prod.OrderQty,
Date: prod?.BookingDate,
}));
let BlockPostdata = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
Status: 'UnBlock',
CreatedBy: UserId,
ProductList: extractedData,
};
await dispatch(PostBlockSlots(BlockPostdata)).unwrap();
if (response?.data?.statusCode == 1) {
setMessageType('success');
setMessageData(response?.data?.response);
let holdingData = await dispatch(
gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
).unwrap();
if (holdingData?.data?.statusCode === 1) {
setTabledata(holdingData?.data?.data);
dispatch(changeholddata(holdingData?.data?.data));
} else {
// props.handleHoldCancel();
props?.closeModal();
setHold(false);
const dataValue = { CompId: CompId, BranchId: BranchId, AppId: AppId };
let responseValue = await dispatch(gettinghold(dataValue)).unwrap();
if (responseValue?.data?.statusCode == 1) {
dispatch(changeholddata(responseValue?.data?.data));
getstockbadge();
Combocarddata();
} else {
dispatch(changeholddata([]));
}
}
getstockbadge();
Combocarddata();
}
};
const HoldPutfun = async (a, b) => {
const updated = a?.map((item) => ({
...item,
Offer: item?.OfferAmt,
localId: uuidv4(),
OfferMode: item?.OfferMode ? item?.OfferMode?.trim() : null,
VariantAvailableFrom: item?.AvailableFrom || null,
VariantAvailableTo: item?.AvailableTo || null,
// TotalAmt: formatAmount((item.TotalAmt - item.OfferValue)),
}));
b?.RefDetails?.[0]?.FreeProdList &&
dispatch(ChangeFullFreeProductList(b?.RefDetails[0]?.FreeProdList));
b?.RefDetails?.[0]?.OfferAppliedProductList &&
dispatch(
changeFullOfferAppliedProducts(
b?.RefDetails[0]?.OfferAppliedProductList
)
);
const loyaltyFreeProductOfferApplied =
b?.RefDetails?.[0]?.OfferAppliedProductList?.filter(
(off) =>
off?.FreeProductsList?.OfferMode === 'L' &&
off?.TableUniqueName === 'FreeProduct'
);
let res = await dispatch(
getCustomerForHold({
CompId: CompId,
AppId: AppId,
branchId: BranchId,
OrderId: b?.OrderId,
})
).unwrap();
if (res?.data?.statusCode == 1) {
let custdetail = res?.data?.data?.find(
(item) => item.CustId === b.CustSuppId
);
if (custdetail !== undefined) {
let data = {
CustId: custdetail?.CustId,
CustName: custdetail?.CustName,
label: custdetail?.CustName
? custdetail?.CustName
: custdetail?.CustMobile,
value: custdetail?.CustMobile,
LoyaltyPointsDetail: custdetail?.LoyaltyPointsDetail,
TotalLoyaltyPoints: custdetail?.TotalLoyaltyPoints,
};
await dispatch(changeSelectedOption(data));
await dispatch(ChangeSelectedCustDisable(true));
if (loyaltyFreeProductOfferApplied?.length > 0) {
const loyaltyProdQuantities = {};
loyaltyFreeProductOfferApplied.forEach((off) => {
const freeProdDtls = off?.FreeProductsList;
const freeProdOfferId =
freeProdDtls?.ProdVariantDetails?.[0]?.StockDetails?.[0]
?.ProdOfferId;
const key = [
freeProdDtls?.OfferId,
freeProdDtls?.FreeProdId,
freeProdDtls?.FreeProdVariantName,
freeProdOfferId,
].join('|');
loyaltyProdQuantities[key] = freeProdDtls?.FreeQty || 0;
});
if (Object.keys(loyaltyProdQuantities).length > 0) {
dispatch(changeLoyaltyConsumedQuantities(loyaltyProdQuantities));
}
console.log(loyaltyProdQuantities, 'loyaltyProdQuantities');
}
}
}
let temp = a
?.filter((item) => item.OrderType === 'E')
.map((item) => item.InwardDtlId + ' ' + item.BookingTypeName);
await dispatch(changeSelProdWiseEst(temp));
if (b.OrderType == 'E') {
await dispatch(changeEstimateBooking('OvrAllEst'));
await dispatch(ChangeOverAllDiscEstimate(parseFloat(b.OverallDisc)));
await dispatch(changeOrderCardDetails(updated));
} else {
await dispatch(changeEstimateBooking('Sales'));
await dispatch(ChangeOverAllDiscSales(parseFloat(b.OverallDisc)));
const salesOffer = templateData?.BookingNavbar?.[1]?.some(
(item) => item?.OptionName === 'Offer'
);
const preferenceOffer =
PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
(item) => item.SettingIdName === 'Offer'
)?.SettingValue === 'Y';
// if (salesOffer && preferenceOffer) {
// await applyOffer(a, b.OrderOfferDetails);
// }
// else
// {
await dispatch(changeOrderCardDetails(updated));
// }
}
await dispatch(changeOrderType('Hold'));
await dispatch(changeHoldOrderDtl(true));
await dispatch(changeReorderHoldDetails(b));
await dispatch(changeReorderProductDetails(b?.productDetails));
await dispatch(changeSelectedCustId(b?.CustSuppId));
await dispatch(ChangeTotalAmount(b?.ExtraChargeDetails));
setHold(false);
// props.handleHoldCancel();
props?.closeModal();
};
const removeAll = async () => {
let data = [];
Tabledata?.map((item) => {
data?.push(item.OrderId);
});
let putData = { OrderId: data };
clearall(putData);
};
const clearall = async (data) => {
let response = await dispatch(puttinghold(data)).unwrap();
const allProducts = Tabledata.flatMap((row) =>
row?.productDetails?.map((prod) => ({
ProdId: prod.ProdId,
InwardDtlId: prod.InwardDtlId,
SinglePc: prod.SinglePc,
Qty: prod.OrderQty,
Date: row?.SalesDate,
}))
);
const BlockPostdata = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
Status: 'UnBlock',
CreatedBy: UserId,
ProductList: allProducts,
};
await dispatch(PostBlockSlots(BlockPostdata)).unwrap();
if (response?.data?.statusCode == 1) {
setMessageType('success');
setMessageData(response?.data?.response);
// props.handleHoldCancel();
props?.closeModal();
setHold(false);
const dataValue = { CompId: CompId, BranchId: BranchId, AppId: AppId };
let responseValue = await dispatch(gettinghold(dataValue)).unwrap();
if (responseValue?.data?.statusCode == 1) {
dispatch(changeholddata(responseValue?.data?.data));
getstockbadge();
Combocarddata();
} else {
dispatch(changeholddata([]));
getstockbadge();
Combocarddata();
}
dispatch(triggerCustomerRefresh());
dispatch(changeSelectedOption(null));
}
};
const setWsport = async (e) => {
setwsport(e);
};
const myfun = async (e) => {
setWSProductWeight(e);
formWsRef.current?.setFieldsValue({ WSProductWeight: e });
};
const WSProductSelect = (data) => {
formWsRef.current.resetFields(['CalcProductRate']);
setCalcProductWeight();
setCalcProductRate();
formWsRef.current.resetFields(['CalcProductWeight', 'CalcProductRate']);
setProductValue(data);
let ProdNamedata = WSProductList?.find((item) => item.ProdName === data);
let OneKgProd = ProdNamedata?.ProductDetail?.find(
(item) =>
(item?.UomName?.toLowerCase() === 'KGS'?.toLowerCase() ||
item?.UomName?.toLowerCase() === 'KG'?.toLowerCase()) &&
item?.Size === 1
);
setWSSelectedOnekgProd(OneKgProd);
setWSProductDataSource(OneKgProd?.ProdVariantDetails?.[0]?.StockDetails);
if (OneKgProd?.ProdVariantDetails?.[0]?.StockDetails?.length === 1) {
GetProductRate(OneKgProd?.ProdVariantDetails?.[0]?.StockDetails?.[0]);
}
};
const WSProductChange = async (data) => {
formWsRef.current.resetFields([
'WSProductWeight',
'WSProductRate',
'WSTotalPrice',
]);
setWSProductRate(0);
setWSProductWeight(0);
setWSTotalPrice(0);
setWSProductDataSource([]);
setProductValue(data);
if (data?.length > 2) {
let ProductList = await dispatch(
getProductsearch({
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
ProdName: data,
})
).unwrap();
if (ProductList?.data?.statusCode == 1) {
setWSProductList(ProductList?.data?.data);
}
}
};
const GetProductRate = (data) => {
setWSSelectedStockDetail(data);
setWSProductRate(data?.SellPrice);
formWsRef.current?.setFieldsValue({ WSProductRate: data?.SellPrice });
};
const WSTotalCalculation = () => {
let pricepergram = WSProductRate / 1000;
let total = formatAmount(parseFloat(WSProductWeight) * 1000 * pricepergram);
setWSTotalPrice(total);
formWsRef.current?.setFieldsValue({ WSTotalPrice: total });
};
const onFinish = async () => {
let data = {
Type: WSProductList?.[0]?.Type,
OverallQuantity: WSProductList?.[0]?.OverAllQty,
ActiveStatus: WSSelectedOnekgProd?.ActiveStatus,
AvailableFrom: WSSelectedOnekgProd?.AvailableFrom,
AvailableTo: WSSelectedOnekgProd?.AvailableTo,
Cess: WSSelectedOnekgProd?.Cess,
ExpDate: WSSelectedStockDetail?.ExpDate,
HSNCode: WSSelectedOnekgProd?.HSNCode,
ManufDate: WSSelectedStockDetail?.ManufDate,
OpeningQty: WSSelectedOnekgProd?.OpeningQty,
ProdType: WSProductList?.[0]?.ProdType,
PartNumber: WSSelectedOnekgProd?.PartNumber,
ProdId: WSSelectedOnekgProd?.ProdId,
ProdLogo: WSSelectedOnekgProd?.ProdLogo,
ProdName: WSSelectedOnekgProd?.ProdName,
QRCode: WSSelectedOnekgProd?.QRCode,
QtyBasedPrice: WSSelectedOnekgProd?.QtyBasedPrice,
Rack: WSSelectedOnekgProd?.Rack,
Size: parseFloat(WSProductWeight).toFixed(3),
StockAvailable: WSSelectedOnekgProd?.StockAvailable,
TaxId: WSSelectedOnekgProd?.TaxId,
TaxPercentage: WSSelectedOnekgProd?.TaxPercentage,
TaxName: WSSelectedOnekgProd?.TaxIdName,
UniqueId: WSSelectedOnekgProd?.UniqueId,
UomName: WSSelectedOnekgProd?.UomName,
BalanceQty: WSSelectedStockDetail?.BalanceQty,
BatchRef: WSSelectedStockDetail?.BatchRef,
InwardDate: WSSelectedStockDetail?.InwardDate,
InwardDtlId: WSSelectedStockDetail?.InwardDtlId,
InwardId: WSSelectedStockDetail?.InwardId,
MRP: WSSelectedStockDetail?.MRP,
Offer: WSSelectedStockDetail?.OfferPrice,
SellPrice: WSSelectedStockDetail?.SellPrice,
ProdVariantName: 'Variant1',
OrderRate: Math.round(WSTotalPrice),
SuppId: WSSelectedStockDetail?.SuppId,
SuppName: WSSelectedStockDetail?.SuppName,
OrderQty: WSProductWeight,
};
if (WSTotalPrice > 0) {
await dispatch(ChangeWSProduct(data));
WSModalPortclose();
} else {
WSModalPortclose();
setMessageType('error');
setMessageData('Total is not calculated');
}
};
const WSModalPortclose = () => {
setWeightScale2(false);
setWSProductWeight(0);
formWsRef.current?.resetFields();
setTimeout(() => {
WSModalClose();
// setwsport(null)
}, 20);
};
const WSModalClose = () => {
setWeightScale2(true);
setWSProductList([]);
setProductValue();
setWSProductDataSource([]);
setWSProductRate(0);
setWSProductWeight(0);
setWSTotalPrice(0);
setWSSelectedStockDetail([]);
setWSSelectedOnekgProd([]);
setCalcProductWeight();
setCalcProductRate();
formWsRef.current?.resetFields();
setWeightScale(false);
if (props.handleWeightScaleCancel) {
props.handleWeightScaleCancel();
}
};
const CalculateWeight = async (e) => {
if (WSSelectedOnekgProd && ProductValue) {
setCalcProductRate(e?.target?.value);
let tempCalcProductWeight = (e.target.value / WSProductRate).toFixed(3);
setCalcProductWeight(parseFloat(tempCalcProductWeight));
formWsRef.current?.setFieldsValue({
CalcProductWeight: tempCalcProductWeight,
});
}
};
const CalculateWeightOpen = () => {
setCalcPriceWeightOpen(!CalcPriceWeightOpen);
setCalcProductWeight();
setCalcProductRate();
formWsRef.current.resetFields(['CalcProductWeight', 'CalcProductRate']);
};
const HandleProductName = (_, value) => {
return new Promise((resolve, reject) => {
if (WSSelectedOnekgProd && ProductValue) {
resolve();
} else {
reject('Please Select Product');
}
});
};
const HandleCloseModal = () => {
props.handleAddCustomerCancel();
setInputValue('');
setCusDetails(false);
setselectedSearchValue('CustMobile');
setSearchopen(false);
setIsOpen(false);
};
const getstockbadge = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
...(AvailableDate && selectedDate
? {
fromDate: selectedDate?.[0],
toDate: selectedDate?.[1],
}
: {}),
};
await dispatch(getSelectedFavItems(data)).unwrap();
let data1 = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
ProdSubCat: ProdSubCat,
...(AvailableDate && selectedDate
? {
fromDate: selectedDate?.[0],
toDate: selectedDate?.[1],
}
: {}),
};
let data2 = {
compId: CompId,
branchId: BranchId,
appId: AppId,
prodCat: prodCat,
...(AvailableDate && selectedDate
? {
fromDate: selectedDate?.[0],
toDate: selectedDate?.[1],
}
: {}),
};
if (
templateData?.BookingLayout?.[1]?.some(
(item) => item?.OptionName === 'SubCategory'
) &&
ProdSubCat
) {
await dispatch(getLayoutproductCard(data1)).unwrap();
} else if (
!templateData?.BookingLayout?.[1]?.some(
(item) => item?.OptionName === 'SubCategory'
)
) {
await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
} else {
await dispatch(getCardDataWithoutSub(data2)).unwrap();
}
};
const Combocarddata = async () => {
let data = {
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
ActiveStatus: 'A',
};
let response = await dispatch(getCombolist(data)).unwrap();
let datas = response?.data?.data;
await dispatch(ChangeComboCarddata(datas));
};
const HandleSearch = () => {
setSearchopen(!Searchopen);
setselectedSearchValue('CustMobile');
setInputValue('');
setCusDetails(false);
setIsOpen(false);
setselectSearchDefaultValue();
formRef.current?.resetFields();
Searchopen == true && setCusDetails(false);
};
const handleRadioChange = (event) => {
setselectedSearchValue(event.target.value);
event.target.value === 'CustName' ? setInputValue('') : setInputValue('');
setIsOpen(false);
setCusDetails(false);
event.target.value === 'CustId' && setInputValue(CustIdForDynamicChange);
setselectSearchDefaultValue();
formRef.current?.resetFields();
};
const validateEmail = (_, value) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!value || emailRegex.test(value)) {
return Promise.resolve();
}
return Promise.reject('Invalid email address');
};
const ClearMobileInput = () => {
setInputValue('');
setIsOpen(false);
setCusDetails(false);
formRef.current?.resetFields();
};
const handleCustomerSelectChange = (value, option) => {
handleSelectSuggestion(value);
setZipCodeData(false);
setIsOpen(false);
setselectSearchDefaultValue(
option[selectedSearchValue] !== null
? option[selectedSearchValue]
: option?.CustMobile
);
};
const handleSearchInputChange = (inputValue) => {
handleSelectSuggestion(inputValue);
};
const Onchangeoffertype = (a) => {
setofferType(a);
// dispatch(changeSetup_OfferType(a))
};
const Handleoffervalue = (e) => {
formRef.current?.setFieldsValue({ OfferValue: e?.target?.value });
setOfferValue(e?.target?.value);
// dispatch(changeSetup_OfferValue(e?.target?.value))
};
const onchangeStatus = (e) => {
setMaritalstatus(e?.target?.value);
};
// const dobchange=(e)
const dobchange = async (date, dateString) => {
if (dateString) {
const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
'YYYY-MM-DDTHH:mm:ss'
);
// formRef.current?.setFieldsValue({ ManufDate: Date1 })
await setDobDate(Date1);
}
};
const spousedobchange = async (date, dateString) => {
if (dateString) {
const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
'YYYY-MM-DDTHH:mm:ss'
);
// formRef.current?.setFieldsValue({ ManufDate: Date1 })
await setSpouseDobDate(Date1);
}
};
const anniversaryDatechange = async (date, dateString) => {
if (dateString) {
const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
'YYYY-MM-DDTHH:mm:ss'
);
// formRef.current?.setFieldsValue({ ManufDate: Date1 })
await setanniversaryDate(Date1);
}
};
const updateImageUrl = (url) => {
setImageUrl(url);
};
const deliveryOptions = [
'Delivery Address',
'Billing Address',
'Both Address',
];
const handleAddOrUpdateAddress = () => {
const currentFormValues = formRef.current?.getFieldsValue() || {};
if (!currentFormValues?.Address1 || !currentFormValues?.Zip) {
setMessageType('error');
setMessageData('Please enter Address Line1 and Zipcode before adding');
return;
}
const selectedAddressType =
editingIndex !== null
? addressTypes[editingIndex] || []
: addressTypes[Object.keys(addressTypes).length - 1] || [];
let addressType = '';
if (selectedAddressType.includes('Both Address')) {
addressType = 'Both Address';
} else if (
selectedAddressType.includes('Delivery Address') &&
selectedAddressType.includes('Billing Address')
) {
addressType = 'Both Address';
} else if (selectedAddressType.includes('Delivery Address')) {
addressType = 'Delivery Address';
} else if (selectedAddressType.includes('Billing Address')) {
addressType = 'Billing Address';
}
const newAddress = {
AddressType: addressType,
Address1: currentFormValues?.Address1,
Address2: currentFormValues?.Address2 || '',
Zip: currentFormValues?.Zip,
City: currentFormValues?.City || '',
Dist: currentFormValues?.Dist || '',
State: currentFormValues?.State || '',
Latitude: currentFormValues?.Latitude || '',
Longitude: currentFormValues?.Longitude || '',
};
if (editingIndex !== null) {
// 🛠️ Update existing address
setAddressesList((prev) => {
const updated = [...prev];
updated[editingIndex] = newAddress;
setAddressPreview(updated);
return updated;
});
setEditingIndex(null);
setMessageType('success');
setMessageData('Address updated successfully!');
} else {
// ➕ Add new address
setAddressesList((prev) => {
const updated = [...prev, newAddress];
setAddressPreview(updated);
return updated;
});
setMessageType('success');
setMessageData('Address added successfully!');
}
// 🧹 Clear form
formRef.current?.setFieldsValue({
Address1: '',
AddressType: '',
Address2: '',
Zip: '',
City: '',
Dist: '',
State: '',
Latitude: '',
Longitude: '',
});
setZipCodeData(false);
};
const handleAddressTypeChange = (index, type, checked) => {
setAddressTypes((prev) => {
const updated = { ...prev };
let currentTypes = [...(updated[index] || [])];
if (type === 'Both Address') {
if (checked) {
currentTypes = [
'Delivery Address',
'Billing Address',
'Both Address',
];
// Clear other addresses when Both Address is selected
Object.keys(updated).forEach((i) => {
if (parseInt(i) !== index) {
updated[i] = [];
}
});
} else {
currentTypes = [];
}
} else {
if (checked) {
if (!currentTypes.includes(type)) {
currentTypes.push(type);
}
// If both Delivery and Billing are selected, add Both Address
if (
currentTypes.includes('Delivery Address') &&
currentTypes.includes('Billing Address')
) {
currentTypes.push('Both Address');
}
// Clear same type from other addresses
Object.keys(updated).forEach((i) => {
if (parseInt(i) !== index) {
updated[i] = (updated[i] || []).filter(
(opt) => opt !== type && opt !== 'Both Address'
);
}
});
} else {
currentTypes = currentTypes.filter(
(t) => t !== type && t !== 'Both Address'
);
}
}
updated[index] = currentTypes;
// Update addresses list
setAddressesList((prev) => {
const newList = prev.map((addr, i) => {
const opts = updated[i] || [];
let addressType = '';
if (opts.includes('Both Address')) addressType = 'Both Address';
else if (opts.includes('Delivery Address'))
addressType = 'Delivery Address';
else if (opts.includes('Billing Address'))
addressType = 'Billing Address';
return { ...addr, AddressType: addressType };
});
setAddressPreview(newList);
return newList;
});
return updated;
});
};
const handleEditAddress = (index) => {
const addrToEdit = addressPreview[index];
formRef.current.setFieldsValue({
AddId: addrToEdit.AddId,
AddressType: addrToEdit.AddressType,
Address1: addrToEdit.Address1,
Address2: addrToEdit.Address2,
Zip: addrToEdit.Zip,
City: addrToEdit.City,
Dist: addrToEdit.Dist,
State: addrToEdit.State,
Latitude: addrToEdit.Latitude,
Longitude: addrToEdit.Longitude,
});
if (addrToEdit.Zip) {
setZipCodeData(true);
}
setEditingIndex(index);
// Scroll to and focus Address1 input
setTimeout(() => {
const addressForm = document.querySelector('.subinputForm');
const address1Input = document.querySelector('input[id*="Address1"]');
if (addressForm) {
addressForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
if (address1Input) {
address1Input.focus();
}
}, 100);
};
// const handleRemoveAddress = (index) => {
// setAddressPreview((prev) => prev.filter((_, i) => i !== index));
// setAddressesList((prev) => prev.filter((_, i) => i !== index));
// setNewAddress((prev) => prev.filter((_, i) => i !== index));
// setAddressTypes((prev) => {
// const updated = { ...prev };
// delete updated[index];
// return updated;
// });
// };
const handleRemoveAddress = (index) => {
setAddressPreview((prev) =>
prev.map((item, i) =>
i === index ? { ...item, ActiveStatus: 'D' } : item
)
);
setAddressesList((prev) =>
prev.map((item, i) =>
i === index ? { ...item, ActiveStatus: 'D' } : item
)
);
setNewAddress((prev) =>
prev.map((item, i) =>
i === index ? { ...item, ActiveStatus: 'D' } : item
)
);
};
return (
}
open={hold}
width={900}
footer={null}
children={
}
handleCancel={props.handleHoldCancel}
/>
}
open={props.addcustomer}
// width={900}
footer={null}
children={
}
handleCancel={
// props.handleAddCustomerCancel
HandleCloseModal
}
/>
{/*
}
open={props.reprint}
width={1000}
footer={null}
children={}
handleCancel={props.handleReprintCancel}
/>
*/}
}
handleCancel={props.handleQuickAddCancel}
/>
{
setCheckbox1(!Checkbox1);
}}
>{' '}
Overall orders
{' '}
{
setCheckbox1(!Checkbox1);
}}
>{' '}
{/* {!Checkbox1 ? ( */}
Individual orders
({
value:
option?.InwardDtlId +
' ' +
option?.BookingTypeName +
' ' +
option?.SinglePc,
// label: option.Type === 'P' ? option.ProdVariantName !== 'Variant 1'
// ? `${option?.ProdName} (${option.Size} ${option.UomName}) (${option.ProdVariantName}${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''})`
// : `${option?.ProdName} (${option.Size} ${option.UomName}) ${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''}`
// : `${option?.ProdName} (1 Combo)`
label:
option.Type === 'P'
? option.ProdVariantName !== 'Variant 1'
? `${option?.ProdName} (${option.Size} ${option?.SinglePc === 'PCS' ? 'PCS' : option.UomName}) (${option.ProdVariantName}${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''})`
: `${option?.ProdName} (${option.Size}${option?.SinglePc === 'PCS' ? 'PCS' : option.UomName}) ${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''}`
: `${option?.ProdName} (1 Combo)`,
}))}
label={}
className="field-DropDown"
onChangeFunction={(e) => onChangeProduct(e)}
valueData={selectedProduct}
/>
)}
{Checkbox1 ? (
'editable-row'}
bordered
dataSource={dataSource}
columns={columns}
/>
) : (
{/* JSX specific to false branch */}
)}
{!Checkbox1 && (
}
// handleSubmit={() => { globalamount1() }}
/>
)}
{!Checkbox1 && (
'editable-row'}
components={components1}
bordered
dataSource={TableName}
width={'120px'}
//pagination={column2?.length < "11" ? false : true}
>
)}
{Checkbox1 && (
Total Amount:
{safeRound(totalAmount)}
)}{' '}
{Checkbox1 && (
}
handleSubmit={() => {
globalamount(extdata);
}}
/>
)}
{!Checkbox1 && (
}
handleSubmit={() => {
globalamount2(TableName);
}}
/>
)}
>
}
handleCancel={props.ExtraChargesCancle}
/>
{WSProductDataSource?.length > 0 ? (
) : (
ProductValue && (
)
)}
>
}
handleCancel={WSModalPortclose}
/>
);
};
export default FeaturesFunctionalities;