diff --git a/src/Pages/StockMaster/StockForm.jsx b/src/Pages/StockMaster/StockForm.jsx index 8d2481b..e4b86f9 100644 --- a/src/Pages/StockMaster/StockForm.jsx +++ b/src/Pages/StockMaster/StockForm.jsx @@ -12,6 +12,7 @@ import { ArrowRightOutlined, PlusCircleOutlined, InfoCircleOutlined, + SearchOutlined, } from '@ant-design/icons'; import { Form, @@ -22,10 +23,11 @@ import { AutoComplete, Switch, } from 'antd'; -import { IoAddCircleSharp } from 'react-icons/io5'; +import { IoAddCircleSharp, IoSettingsOutline } from 'react-icons/io5'; import { ScannerInputField } from '../../Components/Forms/ScannerInputField.jsx'; import { InputField } from '../../Components/Forms/InputField.jsx'; import Buttons from '../../Components/Forms/Buttons.jsx'; +import { Modal } from 'antd'; import { Messages } from '../../Components/Notifications/Messages.jsx'; import { DeleteFilled } from '@ant-design/icons'; import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js'; @@ -74,6 +76,8 @@ import { productTypeDataSelector, getProductTypeData, bulkpostdata, + postFieldSetup, + getFieldSetupData, } from '../../Features/ProductPage/ProductPage.js'; import { postConfiguration } from '../../Features/ConfigMasterPage/ConfigMasterPage.js'; import SupplierProductMappingForm from '../SupplierProductMapping/SuplierProductMappingForm.jsx'; @@ -85,7 +89,7 @@ import { getSupplaierIdwithTypeBasedProducts, postSupplaierProducts, } from '../../Features/SupplierProductMapping/SupplierProductMapping.js'; -import { getCommonAppPreference } from '../../Features/BrachLogin/BranchLogin.js'; +import { ApplicationPreferences, getCommonAppPreference } from '../../Features/BrachLogin/BranchLogin.js'; import { getConfigType, getPaymentOptionFeatureApi, @@ -157,12 +161,12 @@ const EditableCell = ({ margin: 0, }} name={dataIndex} - // rules={[ - // (dataIndex == "imei1" || dataIndex == "imei2") && { - // pattern: /^[0-9]{15}$/, - // message: 'IMEI must be a 15-digit number' - // } - // ]} + // rules={[ + // (dataIndex == "imei1" || dataIndex == "imei2") && { + // pattern: /^[0-9]{15}$/, + // message: 'IMEI must be a 15-digit number' + // } + // ]} > - {/* {dataIndex === "CurrentAmt" && Array.isArray(record[dataIndex]) - ? record[dataIndex]?.map((item, index) => ( - - {item.CurrentAmt + "-" + item.CurrentAmt} - - )) - : children} */} + { const BrandData = useSelector(brandDataSelector); const UomData = useSelector(uomDataSelector); const ProductTypeData = useSelector(productTypeDataSelector); + const appPreferences = useSelector(ApplicationPreferences) const [applicationRestrictedFields, setApplicationRestrictedFields] = useState({ DatesAndExpiry: false, BatchAndModelDetails: false, AmountPerPieceDetail: false, }); + const [selectedAdditionalColumn, setSelectedAdditionalColumn] = useState([]); + console.log(selectedAdditionalColumn, "selectedAdditionalColumn") + const [showColumnModal, setShowColumnModal] = useState(false); + const [tempSelectedColumns, setTempSelectedColumns] = useState([]); + const [tableFieldPreferences, setTableFieldPreferences] = useState([]); + const [selectedFields, setSelectedFields] = useState([]); const [SupplierData, setSupplierData] = useState([]); const [StockOpen, setStockOpen] = useState('N'); const [SupplierOpen, setSupplierOpen] = useState('own'); @@ -275,6 +282,7 @@ const StockForm = ({ formType }) => { const [imageSubCategoryUrl, setSubCategoryImageUrl] = useState(''); const [imageBrandUrl, setBrandImageUrl] = useState(''); const [PurchaseData, setPurchaseData] = useState([]); + console.log(PurchaseData, "PurchaseData") const [additionalInfoModal, setAdditionalInfoModal] = useState(false); const [selectedRowIndex, setSelectedRowIndex] = useState(null); const [selectedRowRecord, setSelectedRowRecord] = useState({}); @@ -342,6 +350,24 @@ const StockForm = ({ formType }) => { const [extractorData, setExtractorData] = useState(null); const [isLoading, setIsLoading] = useState(false); const [loadingText, setLoadingText] = useState(''); + const [filteredPurchaseData, setFilteredPurchaseData] = useState([]); + const [searchValue, setSearchValue] = useState(''); + const isSearching = Boolean(searchValue?.trim()); + useEffect(() => { + if (searchValue?.trim()) { + const search = searchValue.toLowerCase(); + + const filtered = PurchaseData.filter(item => + item?.ProdName?.toLowerCase().includes(search) + ); + + setFilteredPurchaseData(filtered); + } else { + setFilteredPurchaseData([]); + } + }, [PurchaseData, searchValue]); + + const items = [ { name: 'Home', @@ -357,6 +383,9 @@ const StockForm = ({ formType }) => { link: null, }, ]; + const categoryId = appPreferences?.find( + p => p?.PreferredCatName?.toLowerCase() === "purchase entry" + )?.PreferredCatId; useEffect(() => { dispatch(changeBreadCrumb({ items: items })); dispatch( @@ -519,20 +548,27 @@ const StockForm = ({ formType }) => { }; useEffect(() => { - let total = PurchaseData?.reduce((accumulator, currentValue) => { - return accumulator + currentValue.Amount; + const total = PurchaseData?.reduce((acc, item) => { + return acc + Number(item?.Amount || 0); }, 0); - setSelInvoiceAmount(!isNaN(total) && total !== 0 ? total : null); + const invoiceAmount = + !isNaN(total) && total !== 0 ? total : null; + + setSelInvoiceAmount(invoiceAmount); + formRef.current?.setFieldsValue({ - InvoiceAmount: !isNaN(total) && total !== 0 ? total : null, + InvoiceAmount: invoiceAmount, }); - let totaltax = PurchaseData?.reduce((accumulator, currentValue) => { - return accumulator + currentValue.TaxAmt; + + const totalTax = PurchaseData?.reduce((acc, item) => { + return acc + Number(item?.TaxAmt || 0); }, 0); - setTotalTaxAmount(totaltax); + + setTotalTaxAmount(totalTax); }, [PurchaseData]); + const getPurchaseOrders = async () => { const { data: res } = await dispatch( PendingOrdersPE({ CompId, AppId, BranchId }) @@ -576,7 +612,26 @@ const StockForm = ({ formType }) => { ); return { mappedSupplierProducts, SuppId: finalList?.[0]?.SuppId }; }; - + useEffect(() => { + getFieldSetup(); + }, [categoryId]) + const getFieldSetup = async () => { + try { + const response = await dispatch(getFieldSetupData({ AppId, CompId, BranchId, categoryId, Type: "PE" })).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) || []); + setSelectedAdditionalColumn(response?.data?.data?.[0]?.ConfigDtl?.filter(c => c.ConfigId && c.Access === 'Y')?.map(c => c.ConfigName) || []) + 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); + } + }; const AddSupplierimg = async (subSupplierData) => { const addSupplierData = { CompId: getSession('CompId'), @@ -688,8 +743,8 @@ const StockForm = ({ formType }) => { const allSupplierProducts = response?.data?.data || []; const matchingProdIds = []; - const NewImageProducts=[] - console.log(unmatchedProducts,"unmatchedProductsunmatchedProducts") + const NewImageProducts = [] + console.log(unmatchedProducts, "unmatchedProductsunmatchedProducts") // check if the unmatched products exists in our products list unmatchedProducts.forEach((item) => { const match = allSupplierProducts?.[0]?.ProductDetails.find( @@ -700,89 +755,89 @@ const StockForm = ({ formType }) => { if (match) { matchingProdIds.push(match.ProdId); } - else{ + else { NewImageProducts.push(item?.parsedData); } }); - console.log(NewImageProducts,"NewImageProductsNewImageProducts") + console.log(NewImageProducts, "NewImageProductsNewImageProducts") // Bulk upload new image products if (NewImageProducts.length > 0) { - const newProductsData = NewImageProducts.map(product => ({ - AppId: AppId || 0, - CompId: CompId || "", - BranchId: BranchId || "", - CreatedBy: UserId || 0, - ProdName: product.description?.trim() || "", - ProdVariantName: "", - Size: 1 || "", - UOM: product.unit || "", - MRP: parseFloat(product.rate) || 0, - WhSalePrice: 0, - SellPrice: parseFloat(product.rate) || 0, - ProdCat: "General", - ProdSubCat: "", - Brand: "", - AutoGenerateQr: "", - QRCode: "", - StockAvailable: 'No', - TaxId: "", - HSNCode: "", - PartNumber: "", - Rack: 0, - ManufDate: "", - ExpDate: "", - AvailableFrom: "", - AvailableTo: "", - ProdLogo: "", - OnePcsAvailable: "No", - AutoGenerateSingleQr:'No', - TaxId: 'NIL - 0%', - OnePcQR: "", - TokenAvailable: 'No', - OpeningQty: 0, - QtyBasedPrice: "", - InwardDate: "", - SuppId: suppId || "", - Reference: "", - ReceivedQty: 0, - AcceptedQty: 0, - RejectedQty: 0, - RejectionReason: "", - IssuedQty: 0, - BalanceQty: 0, - InwardPrice: 0, - OfferPrice: 0, - SpecialPrice: 0, - Cess: 0, - })); + const newProductsData = NewImageProducts.map(product => ({ + AppId: AppId || 0, + CompId: CompId || "", + BranchId: BranchId || "", + CreatedBy: UserId || 0, + ProdName: product.description?.trim() || "", + ProdVariantName: "", + Size: 1 || "", + UOM: product.unit || "", + MRP: parseFloat(product.rate) || 0, + WhSalePrice: 0, + SellPrice: parseFloat(product.rate) || 0, + ProdCat: "General", + ProdSubCat: "", + Brand: "", + AutoGenerateQr: "", + QRCode: "", + StockAvailable: 'No', + TaxId: "", + HSNCode: "", + PartNumber: "", + Rack: 0, + ManufDate: "", + ExpDate: "", + AvailableFrom: "", + AvailableTo: "", + ProdLogo: "", + OnePcsAvailable: "No", + AutoGenerateSingleQr: 'No', + TaxId: 'NIL - 0%', + OnePcQR: "", + TokenAvailable: 'No', + OpeningQty: 0, + QtyBasedPrice: "", + InwardDate: "", + SuppId: suppId || "", + Reference: "", + ReceivedQty: 0, + AcceptedQty: 0, + RejectedQty: 0, + RejectionReason: "", + IssuedQty: 0, + BalanceQty: 0, + InwardPrice: 0, + OfferPrice: 0, + SpecialPrice: 0, + Cess: 0, + })); - const bulkResponse = await dispatch(bulkpostdata({ ProdDetails: newProductsData })).unwrap(); - - if (bulkResponse?.data?.statusCode === 1) { - // After successful bulk upload, check the condition again - const updatedResponse = await dispatch( - getSupplaierIdBasedProducts({ CompId, AppId, BranchId, SuppId: suppId }) - ).unwrap(); - if (updatedResponse?.data?.statusCode === 1) { - const updatedAllSupplierProducts = updatedResponse?.data?.data || []; - const updatedMatchingProdIds = []; - - unmatchedProducts.forEach((item) => { - const match = updatedAllSupplierProducts?.[0]?.ProductDetails.find( - (supp) => - supp?.ProdName?.toLowerCase() === - item?.parsedData?.description?.toLowerCase() - ); - if (match) { - updatedMatchingProdIds.push(match.ProdId); - } - }); - - if (updatedMatchingProdIds.length > 0) { - matchingProdIds.push(...updatedMatchingProdIds); - } + const bulkResponse = await dispatch(bulkpostdata({ ProdDetails: newProductsData })).unwrap(); + + if (bulkResponse?.data?.statusCode === 1) { + // After successful bulk upload, check the condition again + const updatedResponse = await dispatch( + getSupplaierIdBasedProducts({ CompId, AppId, BranchId, SuppId: suppId }) + ).unwrap(); + if (updatedResponse?.data?.statusCode === 1) { + const updatedAllSupplierProducts = updatedResponse?.data?.data || []; + const updatedMatchingProdIds = []; + + unmatchedProducts.forEach((item) => { + const match = updatedAllSupplierProducts?.[0]?.ProductDetails.find( + (supp) => + supp?.ProdName?.toLowerCase() === + item?.parsedData?.description?.toLowerCase() + ); + if (match) { + updatedMatchingProdIds.push(match.ProdId); } + }); + + if (updatedMatchingProdIds.length > 0) { + matchingProdIds.push(...updatedMatchingProdIds); } + } + } } // if there is matching products, map them to the supplier if (matchingProdIds.length > 0) { @@ -828,6 +883,7 @@ const StockForm = ({ formType }) => { for (const item of matchedProducts) { if (item.matchFound) { const newProduct = await ProductDropDownChange( + item?.selectedProduct.ProdVariantName, item.selectedProdId, { label: item.selectedProduct.ProdName }, mappedSupplierProducts, @@ -914,6 +970,8 @@ const StockForm = ({ formType }) => { for (const item of matchedProducts) { if (item.matchFound) { const newProduct = await ProductDropDownChange( + + item?.selectedProduct?.ProdVariantName, item.selectedProdId, { label: item.selectedProduct.ProdName }, supplierProducts, @@ -1118,12 +1176,12 @@ const StockForm = ({ formType }) => { formRef?.current?.getFieldsValue(), 'formRefformRefformRefformRef' ); - if(extractorData?.invoiceNo !== null && extractorData?.invoiceNo !== ""){ - formRef?.current?.setFieldsValue({ - SuppInvoiceNo: extractorData?.invoiceNo, - }); + if (extractorData?.invoiceNo !== null && extractorData?.invoiceNo !== "") { + formRef?.current?.setFieldsValue({ + SuppInvoiceNo: extractorData?.invoiceNo, + }); } - + formRef?.current?.setFieldsValue({ PaymentAmount: extractorData?.TotalAmtData, }); @@ -1206,6 +1264,7 @@ const StockForm = ({ formType }) => { }; const ProductDropDownChange = async ( + VariantName, ProdId, option, productsList, @@ -1213,55 +1272,58 @@ const StockForm = ({ formType }) => { extractedItem, existingProducts ) => { + setProductSearchText(''); setSelectedProductName(option?.label ? option?.label : ''); formRef?.current?.resetFields(['VarProdId']); setselectedProductVariantData(null); setSelectedProductData(ProdId); - let x = (productsList || productData)?.find( - (e) => e.ProdId == ProdId - )?.ProdName; - let OnePcsAvailable = - (productsList || productData)?.find((e) => e.ProdId == ProdId) - ?.OnePcsAvailable == 'Y'; - let variantValues1 = await dispatch( - getProdvaraiantdata({ - CompId: SupplierCompId, - AppId: SupplierAppId, - BranchId: SupplierBranchId, - prodName: x, - }) - ).unwrap(); - let variants = variantValues1?.data?.data; - let cc = variants?.filter((variant) => - variant?.ProductDetail?.some((e) => e.ProdId == ProdId) - )?.[0]?.ProductDetail; + // let x = (productsList || productData)?.find( + // (e) => e.ProdId == ProdId + // )?.ProdName; + let OnePcsAvailable = (productsList || productData)?.find((e) => e.ProdId == ProdId && e?.ProdVariantName == VariantName)?.OnePcsAvailable == 'Y'; + // let variantValues1 = await dispatch( + // getProdvaraiantdata({ + // CompId: SupplierCompId, + // AppId: SupplierAppId, + // BranchId: SupplierBranchId, + // prodName: x, + // }) + // ).unwrap(); + // let variants = variantValues1?.data?.data; - setVariants( - cc?.[0]?.ProdVariantDetails?.map((detail) => ({ - ...detail, - ProdIdProdName: `${detail.ProdVariantName} ${detail.ProdId}`, - OnePcsAvailable, - })) - ); + // let cc = variants?.filter((variant) => + // variant?.ProductDetail?.some((e) => e.ProdId == ProdId) + // )?.[0]?.ProductDetail; - if ( - cc?.[0]?.ProdVariantDetails?.length < 2 || - (extractedProduct ? cc?.[0]?.ProdVariantDetails?.length > 0 : false) + // setVariants( + // cc?.[0]?.ProdVariantDetails?.map((detail) => ({ + // ...detail, + // ProdIdProdName: `${detail.ProdVariantName} ${detail.ProdId}`, + // OnePcsAvailable, + // })) + // ); + + if (true + // cc?.[0]?.ProdVariantDetails?.length < 2 || + // (extractedProduct ? cc?.[0]?.ProdVariantDetails?.length > 0 : false) ) { // let getSuppId = (productsList || productData)?.filter((item) => item.ProdId == ProdId); formRef.current?.setFieldsValue({ ProdId: ProdId }); await setSelectedProductData(ProdId); // await setSelectedSupplierData(getSuppId?.[0]?.["SuppId"]) ,CustSuppId:getSuppId?.[0]?.["SuppId"] - if ((existingProducts || PurchaseData)?.some((e) => e.ProdId == ProdId)) { + if ((existingProducts || PurchaseData)?.some((e) => e.ProdId == ProdId && e?.ProdVariantName == VariantName)) { + const existingProduct = (existingProducts || PurchaseData)?.find((e) => e.ProdId == ProdId && e?.ProdVariantName == VariantName); setMessageType('error'); - setMessageData('Already Product Exists'); + setMessageData(`Product "${existingProduct?.ProdName} - ${existingProduct?.ProdVariantName}" already exists`); return null; - } else { + } + else { + let ProductData1 = (productsList || productData)?.find( - (e) => e.ProdId == ProdId + (e) => e.ProdId == ProdId && e?.ProdVariantName == VariantName ); let DefaultVariant = ProductData1?.ProdVariantPriceDetails?.find( (item) => item?.DefaultVariant === 'Y' && item?.ReceivedQty === 0 @@ -1275,10 +1337,13 @@ const StockForm = ({ formType }) => { SellPrice: ProductData1?.SellPrice, StockAvailable: ProductData1?.StockAvailable, OnePcsAvailable: ProductData1?.OnePcsAvailable, - NumberofPieceinside: ProductData1?.NoOfPcs, - AmountPerPiece: ProductData1?.OnePcsPrice, + // NumberofPieceinside: ProductData1?.NoOfPcs, + // AmountPerPiece: ProductData1?.OnePcsPrice, + OnePcsPrice: ProductData1?.OnePcsPrice, + NoOfPcs: ProductData1?.NoOfPcs, TaxId: ProductData1?.TaxId, TaxPercentage: ProductData1?.TaxPercentage, + ProdVariantName: ProductData1?.ProdVariantName, }; const qty = extractedProduct @@ -1304,7 +1369,7 @@ const StockForm = ({ formType }) => { RejectedQty: qty - acceptedQty, OfferPrice: 0, SpecialPrice: 0, - ProdVariantName: 'Variant 1', + // ProdVariantName: 'Variant 1', FreeItem: 0, TaxAmt: 0, TaxType: SelectedPurcTaxType ? SelectedPurcTaxType : 0, @@ -1330,6 +1395,7 @@ const StockForm = ({ formType }) => { let productName = {}; productName.label = `${matchedProduct?.ProdName} (${matchedProduct.Size} ${matchedProduct.UomName})${matchedProduct?.BrandName ? ` - ${matchedProduct?.BrandName}` : ''}`; const newProduct = await ProductDropDownChange( + matchedProduct?.ProdVariantName, matchedProduct.ProdId, productName ); @@ -1380,115 +1446,6 @@ const StockForm = ({ formType }) => { VarProdId: null, }); }; - const ProductVariantDropDownChange = (value) => { - const ProdName2 = Variants?.filter( - (item) => item.ProdIdProdName === value - )?.[0]?.ProdVariantName; - - const ProdName1 = PurchaseData?.some( - (item) => - item.ProdId === selectedProductData && - item.ProdVariantName === ProdName2 - ); - if (ProdName1) { - setMessageType('error'); - setMessageData('Already variant Exists'); - } else { - const ProdName = Variants?.filter( - (item) => item.ProdIdProdName === value - )?.[0]?.ProdVariantName; - const OnePcsAvailable = Variants?.filter( - (item) => item.ProdIdProdName === value - )?.[0]?.OnePcsAvailable; - formRef?.current?.setFieldsValue({ VarProdId: value }); - setselectedProductVariantData(ProdName); - - let ProductData1 = productData?.find( - (e) => e.ProdId == selectedProductData - ); - let mrp; - let sellprice; - if (ProdName == 'Variant 1') { - mrp = ProductData1?.MRP; - sellprice = ProductData1?.SellPrice; - } else { - mrp = ProductData1?.ProdVariantPriceDetails?.find( - (item) => item.ProdVariantName == ProdName - )?.MRP; - sellprice = ProductData1?.ProdVariantPriceDetails?.find( - (item) => item.ProdVariantName == ProdName - )?.SellPrice; - } - let DefaultVariant = ProductData1?.ProdVariantPriceDetails?.find( - (item) => item?.ProdVariantName === ProdName && item?.ReceivedQty === 0 - )?.DefaultVariant; - let ProduData2 = { - DefaultVariant: DefaultVariant, - ProdId: ProductData1?.ProdId, - MRP: mrp, - ProdName: ProductData1?.ProdName, - UomName: ProductData1?.UomName, - SellPrice: sellprice, - StockAvailable: ProductData1?.StockAvailable, - OnePcsAvailable: ProductData1?.OnePcsAvailable, - NumberofPieceinside: ProductData1?.NoOfPcs, - AmountPerPiece: ProductData1?.OnePcsPrice, - TaxId: ProductData1?.TaxId, - TaxPercentage: ProductData1?.TaxPercentage, - }; - // ProduData2["StockAvailable"]="Y" - - const localId = uuidv4(); - let tempPurData = { - ...ProduData2, - BalanceQty: 0, - InwardPrice: 0, - PurcDisc: 0, - Amount: 0, - WhSalePrice: 0, - ReceivedQty: 0, - AcceptedQty: 0, - FreeItem: 0, - RejectedQty: 0, - OfferPrice: 0, - SpecialPrice: 0, - ProdVariantName: ProdName, - // 'TaxId': PurcselectedTax ? PurcselectedTax : 0, - TaxAmt: 0, - TaxType: SelectedPurcTaxType ? SelectedPurcTaxType : 0, - PurcDiscType: 'P', - localId: localId, - PurchaseTax: 0, - }; - form?.setFieldsValue({ - [`SellPrice${localId}`]: tempPurData?.SellPrice, - [`PurchaseTax${localId}`]: tempPurData?.PurchaseTax, - }); - - setPurchaseData([tempPurData, ...PurchaseData]); - - Delete - ? (form.setFieldsValue({ - [`BalanceQty${index}`]: undefined, - [`ReceivedQty${index}`]: undefined, - [`AcceptedQty${index}`]: undefined, - [`RejectedQty${index}`]: undefined, - [`Amount${index}`]: undefined, - [`FreeQty${index}`]: undefined, - [`InwardPrice${index}`]: undefined, - [`MRP${index}`]: undefined, - [`PurcDisc${index}`]: undefined, - [`SellPrice${index}`]: undefined, - [`WhSalePrice${index}`]: undefined, - [`offerSalePrice${index}`]: undefined, - [`splSalePrice${index}`]: undefined, - [`NumberofPieceinside${index}`]: undefined, - [`AmountPerPiece${index}`]: undefined, - }), - setDelete(false)) - : ' '; - } - }; const handleTaxDropDownChange = async (TaxId) => { formProductRef.current?.setFieldsValue({ TaxId: TaxId }); @@ -1789,98 +1746,134 @@ const StockForm = ({ formType }) => { if (Delete) { form.setFieldsValue({ - BalanceQty: { [localId]: undefined }, - ReceivedQty: { [localId]: undefined }, - AcceptedQty: { [localId]: undefined }, - RejectedQty: { [localId]: undefined }, - Amount: { [localId]: undefined }, - FreeQty: { [localId]: undefined }, - InwardPrice: { [localId]: undefined }, - MRP: { [localId]: undefined }, - PurcDisc: { [localId]: undefined }, - SellPrice: { [localId]: undefined }, - WhSalePrice: { [localId]: undefined }, - offerSalePrice: { [localId]: undefined }, - splSalePrice: { [localId]: undefined }, - NumberofPieceinside: { [localId]: undefined }, - AmountPerPiece: { [localId]: undefined }, - PurcDiscType: { [localId]: undefined }, + [`BalanceQty${localId}`]: undefined, + [`ReceivedQty${localId}`]: undefined, + [`AcceptedQty${localId}`]: undefined, + [`RejectedQty${localId}`]: undefined, + [`Amount${localId}`]: undefined, + [`Freeqty${localId}`]: undefined, + [`InwardPrice${localId}`]: undefined, + [`MRP${localId}`]: undefined, + [`PurcDisc${localId}`]: undefined, + [`SellPrice${localId}`]: undefined, + [`WhSalePrice${localId}`]: undefined, + [`offerSalePrice${localId}`]: undefined, + [`splSalePrice${localId}`]: undefined, + [`NumberofPieceinside${localId}`]: undefined, + [`AmountPerPiece${localId}`]: undefined, + [`PurcDiscType${localId}`]: undefined, + [`ManufDate${localId}`]: undefined, + [`ExpDate${localId}`]: undefined, + [`OnePcsPrice${localId}`]: undefined, + [`NoOfPcs${localId}`]: undefined, }); setDelete(false); } else { form.setFieldsValue({ - BalanceQty: { [localId]: record?.BalanceQty }, - ReceivedQty: { [localId]: record?.ReceivedQty }, - AcceptedQty: { [localId]: record?.AcceptedQty }, - RejectedQty: { [localId]: record?.RejectedQty }, - PurcDiscType: { [localId]: record?.PurcDiscType }, - Amount: { [localId]: record?.Amount }, - FreeQty: { [localId]: record?.FreeItem }, - InwardPrice: { [localId]: record?.InwardPrice }, - MRP: { [localId]: record?.MRP }, - PurcDisc: { [localId]: record?.PurcDisc }, - SellPrice: { [localId]: record?.SellPrice }, - WhSalePrice: { [localId]: record?.WhSalePrice }, - offerSalePrice: { [localId]: record?.OfferPrice }, - splSalePrice: { [localId]: record?.SpecialPrice }, - NumberofPieceinside: { [localId]: record?.NumberofPieceinside }, - AmountPerPiece: { [localId]: record?.AmountPerPiece }, + [`BalanceQty${localId}`]: record?.BalanceQty, + [`ReceivedQty${localId}`]: record?.ReceivedQty, + [`AcceptedQty${localId}`]: record?.AcceptedQty, + [`RejectedQty${localId}`]: record?.RejectedQty, + [`Freeqty${localId}`]: record?.FreeItem, + [`MRP${localId}`]: record?.MRP, + [`ManufDate${localId}`]: record?.ManufDate, + [`ExpDate${localId}`]: record?.ExpDate, + [`SellPrice${localId}`]: record?.SellPrice, + [`WhSalePrice${localId}`]: record?.WhSalePrice, + [`PurcDiscType${localId}`]: record?.PurcDiscType, + [`Amount${localId}`]: record?.Amount, + [`InwardPrice${localId}`]: record?.InwardPrice, + [`PurcDisc${localId}`]: record?.PurcDisc, + [`offerSalePrice${localId}`]: record?.OfferPrice, + [`splSalePrice${localId}`]: record?.SpecialPrice, + [`OnePcsPrice${localId}`]: record?.OnePcsPrice, + [`NoOfPcs${localId}`]: record?.NoOfPcs, + + }); + if (applicationRestrictedFields.BatchAndModelDetails) { form.setFieldsValue({ - BatchRef: { [localId]: record?.BatchRef }, + [`BatchRef${localId}`]: record?.BatchRef, }); } } }; - const save = async (index) => { + const save = async (localId) => { try { - const row = await form?.validateFields(); + const row = await form.validateFields(); const modifiedObject = {}; + for (const key in row) { - const newKey = key.slice(0, -1); // Remove the last character ("0") from the key - modifiedObject[newKey] = row[key]; + // remove localId suffix from field names + if (key.endsWith(localId)) { + const newKey = key.replace(localId, ''); + modifiedObject[newKey] = row[key]; + } } - const newData = [...PurchaseData]; - // const index = newData.findIndex((item) => recordKey === item.InwardDtlId); - if (index > -1) { - const item = newData[index]; - newData.splice(index, 1, { ...item, ...modifiedObject }); - setPurchaseData(newData); - setEditingKey(''); - } + setPurchaseData((prev) => + prev.map((item) => + item.localId === localId + ? { ...item, ...modifiedObject } + : item + ) + ); + + setEditingKey(''); } catch (err) { console.error('Save failed:', err); } }; - const handleKeyPress = async (e, record, index) => { + + const handleKeyPress = async (e, record) => { if (e.key === 'Enter') { try { await form.validateFields(); - save(index); + save(record.localId); } catch (error) { console.error('Save failed:', error); } } }; - const openAdditionalInfoModal = (record, index) => { - console.log(record, 'recordrecord'); - if (record?.ReceivedQty === 0 || record?.ReceivedQty === '') { - setMessageType('error'); - setMessageData('Please Enter Qty'); - return; - } - setSelectedRowIndex(index); - setSelectedRowRecord(record); - setAdditionalInfoModal(true); + + const formatDateForDisplay = (dateString) => { + if (!dateString) return ''; + return moment(dateString).format('DD-MMM-YY'); }; + + const updateRowValues = (localId, updates) => { + setPurchaseData((prev) => + prev.map((item) => + item.localId === localId ? { ...item, ...updates } : item + ) + ); + + const formUpdates = {}; + Object.keys(updates).forEach((key) => { + formUpdates[`${key}${localId}`] = updates[key]; + }); + + form.setFieldsValue(formUpdates); + }; + const updateRowValue = (localId, key, value) => { + setPurchaseData((prev) => + prev.map((item) => + item.localId === localId ? { ...item, [key]: value } : item + ) + ); + + form.setFieldsValue({ + [`${key}${localId}`]: value, + }); + } + const columns = [ { title: 'SL.NO', @@ -1891,13 +1884,24 @@ const StockForm = ({ formType }) => { ), }, { - title: 'Product Name', + title: 'Name', dataIndex: 'ProdName', key: 'ProdName', align: 'left', render: (text, record, index) => ( - {record?.ProdName + '(' + record?.ProdVariantName + ')'} + {record?.ProdName} + + ), + }, + { + title: 'Variant', + dataIndex: 'ProdVariantName', + key: 'ProdVariantName', + align: 'left', + render: (text, record, index) => ( + + {record?.ProdVariantName} ), }, @@ -1934,9 +1938,9 @@ const StockForm = ({ formType }) => { ]} > handleKeyPress(e, record, index)} + onPressEnter={(e) => handleKeyPress(e, record)} onBlur={(e) => handleQtyChange(e, record)} - onChange={(e) => handleQtyChange(e, record, index)} + onChange={(e) => handleQtyChange(e, record)} inputMode="decimal" onInput={(e) => { let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters @@ -1961,7 +1965,7 @@ const StockForm = ({ formType }) => { { title: ( - Purchase Rate / Unit + Purchase Rate/unit ), dataIndex: 'InwardPrice', @@ -1991,9 +1995,9 @@ const StockForm = ({ formType }) => { ]} > handleKeyPress(e, record, index)} - onChange={(e) => handlePurrateChange(e, record, index)} - onBlur={(e) => handlePurrateChange(e, record, index)} + onPressEnter={(e) => handleKeyPress(e, record)} + onChange={(e) => handlePurrateChange(e, record)} + onBlur={(e) => handlePurrateChange(e, record)} inputMode="decimal" onInput={(e) => { let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters @@ -2024,7 +2028,7 @@ const StockForm = ({ formType }) => { ), dataIndex: 'PurchaseTax', key: 'PurchaseTax', - width: 120, + // width: 120, editable: true, render: (text, record, index) => { return isEditing(record, index) ? ( @@ -2075,9 +2079,9 @@ const StockForm = ({ formType }) => { ]} > handleKeyPress(e, record, index)} - onChange={(e) => handleTaxChange(e, record, index)} - onBlur={(e) => handleTaxChange(e, record, index)} + onPressEnter={(e) => handleKeyPress(e, record)} + onChange={(e) => handleTaxChange(e, record)} + onBlur={(e) => handleTaxChange(e, record)} inputMode="decimal" onInput={(e) => { let value = e.target.value.replace(/[^0-9.]/g, ''); @@ -2104,15 +2108,52 @@ const StockForm = ({ formType }) => { key: 'Amount', editable: true, }, + ...(selectedAdditionalColumn.includes("Mrp") ? [ + { + title: 'MRP', + dataIndex: 'MRP', + key: 'MRP', + editable: true, + // width: 150, + render: (text, record) => { + const localId = record.localId; + + return isEditing(record) ? ( + + { + const value = e.target.value; + + if (!/^\d*\.?\d*$/.test(value)) { + setMessageType('error'); + setMessageData('Only numeric values are allowed'); + return; + } + + updateRowValues(record.localId, { + MRP: value, + SellPrice: value, + }); + }} + onPressEnter={(e) => handleKeyPress(e, record)} + /> + + + ) : ( + text + ) + } + }] : []), { title: ( - Selling Price / Unit + Selling Price ), dataIndex: 'SellPrice', key: 'SellPrice', - width: 120, + width: 70, editable: true, render: (text, record, index) => { return isEditing(record, index) ? ( @@ -2125,9 +2166,9 @@ const StockForm = ({ formType }) => { ]} > handleKeyPress(e, record, index)} - onChange={(e) => handleSellPriceChange(e, record, index)} - onBlur={(e) => handleSellPriceChange(e, record, index)} + onPressEnter={(e) => handleKeyPress(e, record)} + onChange={(e) => handleSellPriceChange(e, record)} + onBlur={(e) => handleSellPriceChange(e, record)} inputMode="decimal" onInput={(e) => { let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters @@ -2147,25 +2188,425 @@ const StockForm = ({ formType }) => { ); }, }, - { - title: 'Additional Info', - dataIndex: 'AdditionalInfo', - key: 'AdditionalInfo', - width: 120, - align: 'center', - render: (text, record, index) => { - return ( - <> - {' '} - openAdditionalInfoModal(record, index)} - className="shape-preview" - /> - - ); + + ...(selectedAdditionalColumn.includes("Amount Per Piece") ? [ + { + title: "Amount per piece", + dataIndex: 'OnePcsPrice', + key: 'OnePcsPrice', + width: 70, + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record)} + onChange={(e) => { + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, OnePcsPrice: e.target.value } : item + ); + setPurchaseData(newData); + }} + placeholder="OnePcsPrice" + /> + + ) : ( + text + ); + }, + }] : []), + ...(selectedAdditionalColumn.includes("Amount Per Piece") ? [ + { + title: "Number of piece", + dataIndex: 'NoOfPcs', + key: 'NoOfPcs', + width: 70, + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record)} + onChange={(e) => { + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, NoOfPcs: e.target.value } : item + ); + setPurchaseData(newData); + }} + placeholder="NoOfPcs" + /> + + ) : ( + text + ); + }, + }] : []), + ...(selectedAdditionalColumn.includes("Wholesale Price") ? [ + { + title: "Wholesale price", + dataIndex: 'WhSalePrice', + key: 'WhSalePrice', + width: 70, + editable: true, + render: (text, record) => { + return isEditing(record) ? ( + + handleKeyPress(e, record)} + onChange={(e) => { + const value = e.target.value; + + // 🚫 block non-numeric + if (!/^\d*\.?\d*$/.test(value)) return; + + updateRowValue(record.localId, 'WhSalePrice', value); + }} + /> + + ) : ( + text + ); + }, + } + ] : []), + + ...(selectedAdditionalColumn.includes("Manufacture Date") ? [ + { + title: 'Manuf.Date', + dataIndex: 'ManufDate', + key: 'ManufDate', + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + { + const formattedDate = dateString === '' ? undefined : moment(dateString, ['DD-MM-YYYY']).format('YYYY-MM-DDTHH:mm:ss'); + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, ManufDate: formattedDate } : item + ); + setPurchaseData(newData); + form.setFieldsValue({ + [`ManufDate${record?.localId}`]: formattedDate + }); + }} + valueData={record?.ManufDate} + cancelFuture={true} + /> + + ) : ( + formatDateForDisplay(text) + ); + }, + }] : []), + ...(selectedAdditionalColumn.includes("Expiry Date") ? [ + { + title: 'Exp.Date', + dataIndex: 'ExpDate', + key: 'ExpDate', + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + { + const formattedDate = dateString === '' ? undefined : moment(dateString, ['DD-MM-YYYY']).format('YYYY-MM-DDTHH:mm:ss'); + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, ExpDate: formattedDate } : item + ); + setPurchaseData(newData); + form.setFieldsValue({ + [`ExpDate${record?.localId}`]: formattedDate + }); + }} + valueData={record?.ExpDate} + cancelFuture={false} + /> + + ) : ( + formatDateForDisplay(text) + ); + }, + }] : []), + + ...(selectedAdditionalColumn.includes("Hsn") ? [ + { + title: 'Hsn', + dataIndex: 'Hsn', + key: 'Hsn', + editable: true, + // width: 130, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record)} + onChange={(e) => { + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, PurchaseHSNCode: e.target.value } : item + ); + setPurchaseData(newData); + }} + placeholder="HSN code" + /> + + ) : ( + text + ); + }, + }] : []), + ...(selectedAdditionalColumn.includes("Model No") ? [ + { + title: 'Model', + dataIndex: 'Model', + key: 'Model', + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record, index)} + onChange={(e) => { + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, ModelNumber: e.target.value } : item + ); + setPurchaseData(newData); + }} + placeholder="Model No" + /> + + ) : ( + text + ); + }, + }] : []), + ...(selectedAdditionalColumn.includes("Batch No") ? [ + { + title: 'Batch', + dataIndex: 'Batch', + key: 'Batch', + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record, index)} + onChange={(e) => { + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { ...item, BatchRef: e.target.value } : item + ); + setPurchaseData(newData); + }} + placeholder="Batch No" + /> + + ) : ( + text + ); + }, + }] : []), + + ...(selectedAdditionalColumn.includes("Rejected Qty") ? + [ + { + title: 'Rejected Qty', + dataIndex: 'RejectedQty', + key: 'RejectedQty', + editable: true, + render: (text, record, index) => { + return isEditing(record, index) ? ( + + handleKeyPress(e, record, index)} + onChange={(e) => { + const inputValue = e.target.value; + const rejectedQty = parseFloat(inputValue) || 0; + const receivedQty = parseFloat(record.ReceivedQty) || 0; + + if (inputValue !== '' && rejectedQty >= receivedQty) { + setMessageType('error'); + setMessageData('Rejected Qty cannot be greater than or Equal to Received Qty'); + form.setFieldsValue({ + [`RejectedQty${record?.localId}`]: record.RejectedQty || 0 + }); + return; + } + + const acceptedQty = receivedQty - rejectedQty; + const totalAmount = acceptedQty * (parseFloat(record.InwardPrice) || 0); + + const newData = PurchaseData.map((item) => + item.localId === record?.localId ? { + ...item, + RejectedQty: parseFloat(inputValue) || 0, + AcceptedQty: acceptedQty, + Amount: totalAmount + } : item + ); + setPurchaseData(newData); + }} + placeholder="Rejected Qty" + /> + + ) : ( + text + ); + }, + }] : []), + + + + + ...(selectedAdditionalColumn.includes("Free Qty") ? [ + { + title: 'Free Qty', + dataIndex: 'Freeqty', + key: 'Freeqty', + editable: true, + render: (text, record) => { + return isEditing(record) ? ( + + handleKeyPress(e, record)} + onChange={(e) => { + const value = e.target.value; + + // 🚫 block non-numeric + if (!/^\d*$/.test(value)) return; + + updateRowValue(record.localId, 'Freeqty', value); + }} + /> + + ) : ( + text + ); + }, }, - }, + ] : []), + + ...(selectedAdditionalColumn.includes("IMEI") ? [ + { + title: 'IMEI', + dataIndex: 'AdditionalInfo', + key: 'AdditionalInfo', + width: 120, + align: 'center', + render: (text, record, index) => { + const hasQty = record?.ReceivedQty && parseFloat(record.ReceivedQty) > 0; + return ( + <> + {' '} + { + if (hasQty) { + + setSelectedRowIndex(index); + handleModelDataOpen(record); + + } else { + setMessageType('error'); + setMessageData('Please Enter Qty'); + } + }} + className="shape-preview" + /> + + ); + }, + }] : []), { title: 'Action', dataIndex: 'Action', @@ -2181,176 +2622,258 @@ const StockForm = ({ formType }) => { style={{ color: '#FF4D4F', }} - onClick={() => statusFormatters(record, index)} + onClick={() => statusFormatters(record)} /> ), }, ]; - const statusFormatters = (record, index) => { + + const statusFormatters = (record) => { const localId = record?.localId; - const Data = PurchaseData.filter((_, i) => i !== index); + + // Remove row using localId (not index) + const data = PurchaseData.filter( + (item) => item?.localId !== localId + ); + setDelete(true); + + // Clear form fields for this row + form.setFieldsValue({ [`BalanceQty${localId}`]: undefined, [`ReceivedQty${localId}`]: undefined, [`AcceptedQty${localId}`]: undefined, [`RejectedQty${localId}`]: undefined, - [`Amount${localId}`]: undefined, - [`FreeQty${localId}`]: undefined, - [`InwardPrice${localId}`]: undefined, + [`Freeqty${localId}`]: undefined, [`MRP${localId}`]: undefined, - [`PurcDisc${localId}`]: undefined, + [`ManufDate${localId}`]: undefined, + [`ExpDate${localId}`]: undefined, [`SellPrice${localId}`]: undefined, [`WhSalePrice${localId}`]: undefined, + [`PurcDiscType${localId}`]: undefined, + [`Amount${localId}`]: undefined, + [`InwardPrice${localId}`]: undefined, + [`PurcDisc${localId}`]: undefined, [`offerSalePrice${localId}`]: undefined, [`splSalePrice${localId}`]: undefined, + [`OnePcsPrice${localId}`]: undefined, + [`NoOfPcs${localId}`]: undefined, }); - setVariants(); - setPurchaseData(Data); + setVariants(undefined); + setPurchaseData(data); setSelectedProductData(null); - formRef?.current?.setFieldsValue({ ProdId: null }); + + formRef?.current?.setFieldsValue({ + ProdId: null, + }); }; - const handleQtyChange = (e, record, index) => { + + + + const handleQtyChange = (e, record) => { const { localId } = record; + + const sourceData = PurchaseData; + + const findIndex = sourceData.findIndex( + (item) => item?.localId === localId + ); + + if (findIndex === -1) return; + const inputValue = e.target.value; - setDataSource([]); - setDataSourceBackup([]); - // Validate if inputValue is numeric + + // ✅ Numeric validation if (!/^\d*\.?\d*$/.test(inputValue)) { setMessageType('error'); setMessageData('Only numeric values are allowed'); return; } - const qty = inputValue; - const acceptedQty = parseFloat(qty); + const qty = Number(inputValue) || 0; + const acceptedQty = qty; - const newData = PurchaseData.map((item, index1) => { - if (index1 === index) { - return { - ...item, - Amount: - isNaN(parseFloat(item?.InwardPrice)) || isNaN(acceptedQty) - ? 0 - : parseFloat(item?.InwardPrice) * acceptedQty, - PurcDisc: 0, - BalanceQty: qty, - ReceivedQty: qty, - AcceptedQty: !isNaN(acceptedQty) ? acceptedQty : 0, - RejectedQty: !isNaN(qty - acceptedQty) ? qty - acceptedQty : 0, - ProductIdentifierDtls: [], - }; - } - return item; - }); + const newData = [...PurchaseData]; + + const item = newData[findIndex]; + + newData[findIndex] = { + ...item, + Amount: + isNaN(Number(item?.InwardPrice)) || isNaN(acceptedQty) + ? 0 + : Number(item?.InwardPrice) * acceptedQty, + PurcDisc: 0, + BalanceQty: qty, + ReceivedQty: qty, + AcceptedQty: acceptedQty, + RejectedQty: 0, + ProductIdentifierDtls: [], + }; setPurchaseData(newData); + + // ✅ Sync form values form.setFieldsValue({ - ...form.getFieldsValue(), [`PurcDisc${localId}`]: 0, [`BalanceQty${localId}`]: qty, [`ReceivedQty${localId}`]: qty, - [`AcceptedQty${localId}`]: !isNaN(acceptedQty) ? acceptedQty : 0, - [`RejectedQty${localId}`]: !isNaN(qty - acceptedQty) - ? qty - acceptedQty - : 0, - // ReceivedQty: qty, - // AcceptedQty: acceptedQty, - // RejectedQty: qty - acceptedQty, + [`AcceptedQty${localId}`]: acceptedQty, + [`RejectedQty${localId}`]: 0, }); }; - const handlePurrateChange = (e, record, index) => { - const { localId, PurcDisc, PurcDiscType, PurchaseTax } = record; + + + const handlePurrateChange = (e, record) => { + const { localId, PurcDisc, PurcDiscType } = record; const PurcRate = e.target.value; + + // ✅ Numeric validation if (!/^\d*\.?\d*$/.test(PurcRate)) { setMessageType('error'); setMessageData('Only numeric values are allowed'); return; } - const Amount = parseFloat(PurcRate) * record?.AcceptedQty; + + const acceptedQty = Number(record?.AcceptedQty) || 0; + const rate = Number(PurcRate) || 0; + const amount = rate * acceptedQty; + + // 🔍 Find correct index using localId + const findIndex = PurchaseData.findIndex( + (item) => item?.localId === localId + ); + + if (findIndex === -1) return; + + const item = PurchaseData[findIndex]; + + // 🧮 Discount calculation let discountAmt = 0; if (PurcDiscType === 'P') { - discountAmt = (Amount * Number(PurcDisc)) / 100; + discountAmt = (amount * Number(PurcDisc || 0)) / 100; } else { - discountAmt = Number(PurcDisc); + discountAmt = Number(PurcDisc || 0); } - // You can calculate acceptedQty based on your requirement - const newData = PurchaseData.map((item, index1) => { - if (index1 === index) { - return { - ...item, - PurcDisc: 0, - InwardPrice: Delete ? 0 : PurcRate, - Amount: !isNaN(Amount) ? Amount : 0, - TaxAmt: - (parseInt(Amount) * parseInt(item?.TaxPercentage)) / - (100 + parseInt(item?.TaxPercentage))?.toFixed(2), - }; - } - return item; - }); - formRef?.current?.setFieldsValue({ - PaymentAmount: newData?.reduce((acc, data) => acc + data?.Amount, 0), - }); - setPaymentAmount(newData?.reduce((acc, data) => acc + data?.Amount, 0)); + + // 🧮 Tax calculation + const taxPercent = Number(item?.TaxPercentage || 0); + const taxAmt = + taxPercent > 0 + ? ((amount - discountAmt) * taxPercent) / (100 + taxPercent) + : 0; + + // ✅ Update data immutably + const newData = [...PurchaseData]; + + newData[findIndex] = { + ...item, + PurcDisc: 0, + InwardPrice: Delete ? 0 : rate, + Amount: !isNaN(amount) ? amount : 0, + TaxAmt: taxAmt.toFixed(2), + }; + setPurchaseData(newData); + + // 🔄 Update payment amount + const totalAmount = newData.reduce( + (acc, data) => acc + Number(data?.Amount || 0), + 0 + ); + + setPaymentAmount(totalAmount); + + formRef?.current?.setFieldsValue({ + PaymentAmount: totalAmount, + }); + + // 🔄 Sync row form fields form.setFieldsValue({ [`PurcDisc${localId}`]: 0, - InwardPrice: { [localId]: Delete ? 0 : PurcRate }, - Amount: { [localId]: !isNaN(Amount) ? Amount : 0 }, + [`InwardPrice${localId}`]: Delete ? 0 : rate, + [`Amount${localId}`]: !isNaN(amount) ? amount : 0, }); }; - const handleSellPriceChange = (e, record, index) => { + + const handleSellPriceChange = (e, record) => { const { localId } = record; const value = e?.target?.value; + + // ✅ Numeric validation if (!/^\d*\.?\d*$/.test(value)) { setMessageType('error'); setMessageData('Only numeric values are allowed'); return; } - const newData = PurchaseData?.map((item, index1) => { - if (index1 === index) { - return { - ...item, - SellPrice: value, - }; - } - return item; - }); + + // 🔍 Find correct row using localId + const findIndex = PurchaseData.findIndex( + (item) => item?.localId === localId + ); + + if (findIndex === -1) return; + + // ✅ Immutable update + const newData = [...PurchaseData]; + + newData[findIndex] = { + ...newData[findIndex], + SellPrice: value, + }; + + setPurchaseData(newData); + + // 🔄 Sync form field form.setFieldsValue({ [`SellPrice${localId}`]: value, }); - setPurchaseData(newData); }; - const handleTaxChange = (e, record, index) => { + const handleTaxChange = (e, record) => { const { localId } = record; const value = e?.target?.value; + + // ✅ Numeric validation if (!/^\d*\.?\d*$/.test(value)) { setMessageType('error'); setMessageData('Only numeric values are allowed'); return; } - const newData = PurchaseData?.map((item, index1) => { - if (index1 === index) { - return { - ...item, - PurchaseTax: parseFloat(value) || 0, - }; - } - return item; - }); - form.setFieldsValue({ - [`PurchaseTax${localId}`]: parseFloat(value) || 0, - }); + + const taxValue = Number(value) || 0; + + // 🔍 Find correct row + const findIndex = PurchaseData.findIndex( + (item) => item?.localId === localId + ); + + if (findIndex === -1) return; + + // ✅ Immutable update + const newData = [...PurchaseData]; + + newData[findIndex] = { + ...newData[findIndex], + PurchaseTax: taxValue, + }; + setPurchaseData(newData); + + // 🔄 Sync form value + form.setFieldsValue({ + [`PurchaseTax${localId}`]: taxValue, + }); }; + + const purchaseStatusChange = (value) => { setPurchaseStatus(value); }; @@ -2477,41 +3000,35 @@ const StockForm = ({ formType }) => { }, []); }; + + const onFinish = async ({ PaymentType, PaymentAmount = 0, ...values }) => { try { + // =============================== + // 1️⃣ TAX VALIDATION + // =============================== const invalidTaxItems = PurchaseData?.filter((item) => { const tax = item.PurchaseTax; - - if (tax === undefined || tax === '' || tax === null) { - return false; - } - + if (tax === undefined || tax === '' || tax === null) return false; const num = Number(tax); - - if (isNaN(num)) { - return true; - } - - if (num < 0 || num > 99) { - return true; - } - - return false; + return isNaN(num) || num < 0 || num > 99; }); - if (invalidTaxItems && invalidTaxItems.length > 0) { + if (invalidTaxItems.length > 0) { setMessageType('error'); - setMessageData( - 'Please enter valid tax percentage (0-99%) for all items' - ); + setMessageData('Please enter valid tax percentage (0–99%) for all items'); return; } + + // =============================== + // 2️⃣ SELL PRICE > MRP CHECK + // =============================== if ( PurchaseData?.some( (item) => item.SellPrice && item.MRP && - parseFloat(item.SellPrice) > parseFloat(item.MRP) + Number(item.SellPrice) > Number(item.MRP) ) ) { setMessageType('error'); @@ -2519,160 +3036,185 @@ const StockForm = ({ formType }) => { return; } - if (PurchaseData.length === 0) { + // =============================== + // 3️⃣ NO PRODUCT CHECK + // =============================== + if (!PurchaseData || PurchaseData.length === 0) { setMessageType('error'); setMessageData('No Product Selected'); return; } - if ( - !PurchaseData?.every( - (item) => - (parseFloat(item.BalanceQty) ? parseFloat(item.BalanceQty) : 0) !== - 0 && item.Amount !== 0 - ) - ) { - setMessageType('error'); - setMessageData('Please Enter Qty And Amount'); - return; - } + // =============================== + // 4️⃣ FILTER VALID / INVALID ROWS + // =============================== + const validRows = []; + const invalidRowNumbers = []; - if (!PurchaseData?.every((item) => item.AcceptedQty !== 0)) { - setMessageType('error'); - setMessageData('Qty & Rejected Qty Should not be same'); - return; - } - if (SupplierOpen === 'paid') { - const { SuppInvoiceNo, SuppInvoiceDate } = - (await formRef?.current?.getFieldsValue()) || {}; - if (!SuppInvoiceNo && !SuppInvoiceDate) { - setMessageType('error'); - setMessageData( - `Enter The ${invoiceType === 'I' ? 'Invoice ' : 'Delivery Challan'} No and Date` - ); - return; - } else if (!SuppInvoiceNo) { - setMessageType('error'); - setMessageData( - `Enter The ${invoiceType === 'I' ? 'Invoice ' : 'Delivery Challan'} No` - ); - return; - } else if (!SuppInvoiceDate) { - setMessageType('error'); - setMessageData( - `Enter The ${invoiceType === 'I' ? 'Invoice ' : 'Delivery Challan'} Date` - ); - return; + PurchaseData.forEach((item, index) => { + const qty = Number(item.BalanceQty) || 0; + const amount = Number(item.Amount) || 0; + + if (qty > 0 && amount > 0) { + validRows.push(item); + } else { + invalidRowNumbers.push(index + 1); } - } - - const images = getUniqueImageArray(PurchaseData); - - const postData = { - ...values, - InvoiceAmount: PurchaseData?.reduce( - (acc, data) => acc + data?.Amount, - 0 - ), - CompId, - BranchId, - AppId, - CreatedBy: UserId, - PurOrderStatus: purchaseStatus, - TaxAmount: TotalTaxAmount?.toFixed(2), - BillAmount: (SelInvoiceAmount - TotalTaxAmount)?.toFixed(2), - TotalAmount: SelInvoiceAmount, - PurOrderInvoiceNo: purchaseOrderId, - PaymentStatus: 'S', - LocationType: SupplierData?.find( - (item) => item?.SuppId === selectedSupplierData - )?.Type, - ImageDetails: images || [], - }; - - const fieldsToRemove = [ - 'InwardDtlId', - 'InwardId', - 'UomName', - 'ProdName', - 'UOMName', - ]; - - const processedData = PurchaseData?.map((item) => { - const cleanItem = { ...item }; - fieldsToRemove.forEach((field) => delete cleanItem[field]); - return { - ...cleanItem, - TaxType: SelectedPurcTaxType || 0, - BalanceQty: cleanItem.AcceptedQty, - OnePcsPrice: cleanItem.AmountPerPiece, - NoOfPcs: cleanItem.NumberofPieceinside, - }; }); - const isPaidSelected = PurchaseTypeData?.some( - (item) => - item.ConfigId === SelectedPurchaseType && item.ConfigName === 'Cash' - ); - if ( - (SupplierOpen !== 'own' || selectedSupplierName) && - selectedSupplierData && - isPaidSelected - ) { - postData.PaymentAmount = PaymentAmount; - postData.PaymentType = selectedPaymentMode; - } else { - postData.PaymentType = PaymentType; - } - - postData['ProdDetails'] = processedData; - - if (formType === 'edit') { - postData['ProdId'] = editstate?.ProdId; - postData['InwardId'] = editstate?.InwardId; - postData['InwardDtlId'] = editstate?.InwardDtlId; - postData['UpdatedBy'] = UserId; - } - - let response; - try { - if (formType === 'add') { - response = await dispatch(postPurchaseData(postData)).unwrap(); - } else { - response = await dispatch(putStockData(postData)).unwrap(); - } - } catch (err) { - if (err?.message === 'Request failed with status code 422') { - response = { - data: { - statusCode: 0, - response: 'Please Give Required Fields', - data: [], - }, - }; - } - } - - if (response?.data?.statusCode === 1) { - navigate(`${subDirectory}setting/purchase-entry/`, { - state: { - Notiffy: { - messageType: 'success', - messageData: response?.data?.response, - }, - }, - }); - } else { + if (validRows.length === 0) { setMessageType('error'); - setMessageData(response?.data?.response); + setMessageData('Please enter Qty and Amount for at least one product'); + return; } - } catch (errorInfo) { - console.log('Validation Failed:', errorInfo); + + // =============================== + // 5️⃣ CONFIRMATION FOR INVALID ROWS + // =============================== + if (invalidRowNumbers.length > 0) { + Modal.confirm({ + title: '⚠️ Incomplete Product Rows', + width: 520, + centered: true, + content: ( +
+

+ Some products are missing Qty or Amount. +

+ +

+ Affected row(s): {invalidRowNumbers.join(', ')} +

+ +

+ Are you sure you want to continue without these products? +

+
+ ), + okText: 'Continue Anyway', + cancelText: 'Go Back', + okButtonProps: { danger: true }, + onOk: () => + proceedSubmit(validRows, values, PaymentType, PaymentAmount), + }); + + return; + } + + // If all rows valid + await proceedSubmit(validRows, values, PaymentType, PaymentAmount); + } catch (error) { + console.error(error); setMessageType('error'); - setMessageData('Please correct the highlighted fields'); - return; + setMessageData('Something went wrong'); } }; + const proceedSubmit = async ( + filteredPurchaseData, + values, + PaymentType, + PaymentAmount + ) => { + const images = getUniqueImageArray(filteredPurchaseData); + const postData = { + ...values, + InvoiceAmount: filteredPurchaseData.reduce( + (acc, item) => acc + Number(item.Amount || 0), + 0 + ), + CompId, + BranchId, + AppId, + CreatedBy: UserId, + PurOrderStatus: purchaseStatus, + TaxAmount: TotalTaxAmount?.toFixed(2), + BillAmount: (SelInvoiceAmount - TotalTaxAmount)?.toFixed(2), + TotalAmount: SelInvoiceAmount, + PurOrderInvoiceNo: purchaseOrderId, + PaymentStatus: 'S', + LocationType: SupplierData?.find( + (item) => item?.SuppId === selectedSupplierData + )?.Type, + ImageDetails: images || [], + }; + + const fieldsToRemove = [ + 'InwardDtlId', + 'InwardId', + 'UomName', + 'ProdName', + 'UOMName', + ]; + + const processedData = filteredPurchaseData.map((item) => { + const cleanItem = { ...item }; + fieldsToRemove.forEach((field) => delete cleanItem[field]); + + return { + ...cleanItem, + TaxType: SelectedPurcTaxType || 0, + BalanceQty: cleanItem.AcceptedQty, + OnePcsPrice: cleanItem.OnePcsPrice, + NoOfPcs: cleanItem.NoOfPcs, + }; + }); + + const isPaidSelected = PurchaseTypeData?.some( + (item) => + item.ConfigId === SelectedPurchaseType && item.ConfigName === 'Cash' + ); + + if ( + (SupplierOpen !== 'own' || selectedSupplierName) && + selectedSupplierData && + isPaidSelected + ) { + postData.PaymentAmount = PaymentAmount; + postData.PaymentType = selectedPaymentMode; + } else { + postData.PaymentType = PaymentType; + } + + postData.ProdDetails = processedData; + + if (formType === 'edit') { + postData.ProdId = editstate?.ProdId; + postData.InwardId = editstate?.InwardId; + postData.InwardDtlId = editstate?.InwardDtlId; + postData.UpdatedBy = UserId; + } + + let response; + try { + response = + formType === 'add' + ? await dispatch(postPurchaseData(postData)).unwrap() + : await dispatch(putStockData(postData)).unwrap(); + } catch (err) { + response = { + data: { + statusCode: 0, + response: 'Please Give Required Fields', + }, + }; + } + + if (response?.data?.statusCode === 1) { + navigate(`${subDirectory}setting/purchase-entry/`, { + state: { + Notiffy: { + messageType: 'success', + messageData: response?.data?.response, + }, + }, + }); + } else { + setMessageType('error'); + setMessageData(response?.data?.response); + } + }; + + const onComplete = useCallback(() => { setMessageData(null); @@ -3003,73 +3545,12 @@ const StockForm = ({ formType }) => { // command - const handleRejectedQty = () => { - const formData = productAddInfoRef?.current?.getFieldsValue(); - const rejectedQty = - formData?.RejectedQty === '' ? 0 : parseFloat(formData?.RejectedQty); - const receivedQty = parseFloat(formData.ReceivedQty) - ? parseFloat(formData.ReceivedQty) - : 0; - let acceptedQty = receivedQty; - let newRejectedQty = 0; - if (isNaN(rejectedQty)) { - newRejectedQty = ''; - } else if (rejectedQty >= receivedQty) { - setMessageType('error'); - setMessageData( - 'Rejected Qty cannot be greater than or Equal to Received Qty' - ); - } else { - newRejectedQty = rejectedQty; - acceptedQty = receivedQty - rejectedQty; - } - let totalAmount = - acceptedQty * (parseFloat(selectedRowRecord?.InwardPrice) || 0); - setSelectedRowRecord((prev) => ({ - ...prev, - AcceptedQty: acceptedQty, - RejectedQty: newRejectedQty === '' ? 0 : newRejectedQty, - ProductIdentifierDtls: [], - Amount: totalAmount, - })); + ; - productAddInfoRef?.current?.setFieldsValue({ - RejectedQty: newRejectedQty === '' ? 0 : newRejectedQty, - AcceptedQty: acceptedQty, - }); - }; - const handleFreeQtyChange = (e) => { - const inputValue = e?.target?.value; - if (!/^\d*\.?\d*$/.test(inputValue)) { - setMessageType('error'); - setMessageData('Only numeric values are allowed'); - return; - } - - const freeQty = inputValue === '' ? '' : parseFloat(inputValue); - - setSelectedRowRecord((prev) => ({ - ...prev, - FreeItem: freeQty, - })); - }; - - const handleMRPChange = (e) => { - let value = e?.target?.value === '' ? 0 : parseFloat(e?.target?.value); - productAddInfoRef?.current?.setFieldsValue({ SellPrice: null, MRP: value }); - setSelectedRowRecord((prev) => ({ ...prev, SellPrice: null, MRP: value })); - productAddInfoRef?.current?.validateFields(); - }; - - const handleHSNChange = (e) => { - const value = e?.target?.value; - productAddInfoRef?.current?.setFieldsValue({ PurchaseHSNCode: value }); - setSelectedRowRecord((prev) => ({ ...prev, PurchaseHSNCode: value })); - }; const validateSellPrice = (record) => (_, value) => { if (!value) { @@ -3091,103 +3572,7 @@ const StockForm = ({ formType }) => { return Promise.resolve(); }; - const handleAmountPerPiecechange = (e) => { - const inputValue = e?.target?.value; - - const amountPerPiece = inputValue === '' ? '' : parseFloat(inputValue); - - if (selectedRowRecord?.OnePcsAvailable === 'Y') { - setSelectedRowRecord((prev) => ({ - ...prev, - AmountPerPiece: amountPerPiece, - })); - } - }; - - const handleNumberofPieceinsidechange = (e) => { - const inputValue = e?.target?.value; - - const numberOfPieceInside = inputValue === '' ? '' : parseFloat(inputValue); - - if (selectedRowRecord?.OnePcsAvailable === 'Y') { - setSelectedRowRecord((prev) => ({ - ...prev, - NumberofPieceinside: numberOfPieceInside, - })); - } - }; - - const handleManufactureDate = (date, dateString) => { - const formattedDate = - dateString === '' - ? undefined - : moment(dateString, ['DD-MM-YYYY']).format('YYYY-MM-DDTHH:mm:ss'); - productAddInfoRef?.current?.setFieldsValue({ - ManufDate: date, - }); - setSelectedRowRecord((prev) => ({ ...prev, ManufDate: formattedDate })); - }; - - const handleExpireDate = (date, dateString) => { - const formattedDate = - dateString === '' - ? undefined - : moment(dateString, ['DD-MM-YYYY']).format('YYYY-MM-DDTHH:mm:ss'); - productAddInfoRef?.current?.setFieldsValue({ - ExpDate: date, - }); - setSelectedRowRecord((prev) => ({ ...prev, ExpDate: formattedDate })); - }; - - const handleBatchRefChange = (e) => { - const value = parseInt(e?.target?.value); - if (!/^\d*\.?\d*$/.test(value)) { - return; - } - productAddInfoRef?.current?.setFieldsValue({ - BatchRef: value, - }); - setSelectedRowRecord((prev) => ({ ...prev, BatchRef: value })); - }; - - const handleModelNoChange = (e) => { - const value = parseInt(e?.target?.value); - if (!/^\d*\.?\d*$/.test(value)) { - return; - } - productAddInfoRef?.current?.setFieldsValue({ - ModelNumber: value, - }); - setSelectedRowRecord((prev) => ({ ...prev, ModelNumber: value })); - }; - - const handleAddtnlDtlsSubmit = async (values) => { - if ( - selectedRowIndex == null || - !Array.isArray(PurchaseData) || - selectedRowIndex >= PurchaseData.length - ) { - return; - } - - const newData = { ...selectedRowRecord, ...values }; - - const updatedData = PurchaseData.map((item, index) => - index === selectedRowIndex ? newData : item - ); - console.log(updatedData, 'updatedData'); - setPurchaseData(updatedData); - await handleAdditionalInfoClose(); - }; - - const handleAdditionalInfoClose = async () => { - setAdditionalInfoModal(false); - setSelectedRowIndex(null); - setSelectedRowRecord({}); - await productAddInfoRef?.current?.resetFields(); - }; - - const handleModelDataOpen = () => { + const handleModelDataOpen = (selectedRowRecord) => { const acceptedQty = parseInt(selectedRowRecord?.AcceptedQty) || 0; const productIdentifiers = selectedRowRecord?.ProductIdentifierDtls || []; @@ -3238,6 +3623,7 @@ const StockForm = ({ formType }) => { }; const handleModelDataSumbitOrClose = () => { + setimeiSerialOpen(false); const productIdentifierDtls = dataSource ?.filter( @@ -3249,12 +3635,42 @@ const StockForm = ({ formType }) => { IMEI2: item.imei2 || '', MacId: item.Macid || '', })); - setSelectedRowRecord((prev) => ({ - ...prev, - ProductIdentifierDtls: productIdentifierDtls, - })); - }; + const newData = PurchaseData.map((item, index) => + index === selectedRowIndex ? { ...item, ProductIdentifierDtls: productIdentifierDtls } : item + ); + setPurchaseData(newData); + }; + const handleFieldSetupSubmit = async () => { + + const postData = { + "AppId": AppId, + "CompId": CompId, + "BranchId": BranchId, + "Type": "PE", + "FormType": "Purchase Entry", + "TypeId": categoryId, + "ConfigDtl": selectedFields?.map((field) => ({ + "ConfigId": field, + "Access": 'Y', + })), + "CreatedBy": UserId + } + + const response = await dispatch(postFieldSetup(postData))?.unwrap(); + + if (response?.data?.statusCode === 1) { + setSelectedAdditionalColumn([...tempSelectedColumns]); + setShowColumnModal(false); + setTempSelectedColumns([]) + setMessageType("success"); + setMessageData(response?.data?.response); + await getFieldSetup(); + } else { + setMessageType("error"); + setMessageData("Failed to set up fields"); + } + } const handleModalSubmited = () => { setIsModalOpen(false); }; @@ -3362,7 +3778,7 @@ const StockForm = ({ formType }) => { )}
-
+
{
-
+

Supplier Details

@@ -3511,19 +3927,19 @@ const StockForm = ({ formType }) => { options={ SupplierData ? SupplierData.filter( - (obj, index, self) => - index === - self.findIndex( - (t) => t.SuppId === obj.SuppId - ) // remove dup SuppId - ).map((option) => ({ - key: `${option.SuppId}-${option.Type}`, // 👈 unique key - value: option.SuppId, - label: - option.Type === 'Branch' - ? `${option.SuppName} (${option.Type}) [${option.SuppId}]` - : `${option.SuppName} (${option.Type})`, - })) + (obj, index, self) => + index === + self.findIndex( + (t) => t.SuppId === obj.SuppId + ) // remove dup SuppId + ).map((option) => ({ + key: `${option.SuppId}-${option.Type}`, // 👈 unique key + value: option.SuppId, + label: + option.Type === 'Branch' + ? `${option.SuppName} (${option.Type}) [${option.SuppId}]` + : `${option.SuppName} (${option.Type})`, + })) : [] } label={} @@ -3682,88 +4098,88 @@ const StockForm = ({ formType }) => { item.ConfigId === SelectedPurchaseType && item.ConfigName === 'Cash' ) && ( - <> - - ({ - value: mode.ModeId, - label: mode.ModeName, - }))} - label={ - - } - className="field-DropDown" - onChangeFunction={handlePaymentModeChange} - valueData={selectedPaymentMode} - /> - - { - if ( - value === undefined || - value === null || - value === '' - ) { - return Promise.resolve(); - } - if (Number(value) === 0) { - return Promise.reject( - 'Payment Amount cannot be 0' - ); - } - if ( - isNaN(value) || - Number(value) < 0 - ) { - return Promise.reject( - 'Payment Amount cannot be less than 0' - ); - } - return Promise.resolve(); + <> + - - Payment Amount - - } - inputMode="decimal" - disable={!payAmountDisable} - isOnChange={paymentAmount ? true : false} - min={0} - type="number" - value={paymentAmount} - onChange={(e) => { - formRef?.current?.setFieldsValue({ - PaymentAmount: e?.target?.value, - }); - setPaymentAmount(e?.target?.value); - }} - /> - - - )} + ]} + > + ({ + value: mode.ModeId, + label: mode.ModeName, + }))} + label={ + + } + className="field-DropDown" + onChangeFunction={handlePaymentModeChange} + valueData={selectedPaymentMode} + /> + + { + if ( + value === undefined || + value === null || + value === '' + ) { + return Promise.resolve(); + } + if (Number(value) === 0) { + return Promise.reject( + 'Payment Amount cannot be 0' + ); + } + if ( + isNaN(value) || + Number(value) < 0 + ) { + return Promise.reject( + 'Payment Amount cannot be less than 0' + ); + } + return Promise.resolve(); + }, + }, + ]} + > + + Payment Amount + + } + inputMode="decimal" + disable={!payAmountDisable} + isOnChange={paymentAmount ? true : false} + min={0} + type="number" + value={paymentAmount} + onChange={(e) => { + formRef?.current?.setFieldsValue({ + PaymentAmount: e?.target?.value, + }); + setPaymentAmount(e?.target?.value); + }} + /> + + + )}
@@ -3791,8 +4207,9 @@ const StockForm = ({ formType }) => { className="field-DropDown" value={selectedProductName} filterOption={(input, option) => { + const [prodId, variantName] = option.value.split('_'); const product = productData.find( - (p) => p.ProdId === option.value + (p) => p.ProdId === prodId && (p.ProdVariantName || 'Variant1') === variantName ); const nameMatch = option.label ?.toLowerCase() @@ -3805,14 +4222,19 @@ const StockForm = ({ formType }) => { options={ !scanner ? productData?.map((option) => ({ - value: option.ProdId, - label: `${option.ProdName} (${option.Size} ${option.UomName})${option?.BrandName ? ` - ${option?.BrandName}` : ''}`, - })) + + value: `${option.ProdId}_${option.ProdVariantName}`, + label: `${option.ProdName} (${option.Size} ${option.UomName})${option?.BrandName ? ` - ${option?.BrandName}` : ''} - ${option.ProdVariantName}`, + + })) : [] } onSelect={async (value, option) => { + const [prodId, variantName] = value.split('_'); + const product = productData.find(p => p.ProdId === prodId && (p.ProdVariantName) === variantName); const newProduct = await ProductDropDownChange( - value, + product?.ProdVariantName, + prodId, option ); if (newProduct) { @@ -3851,22 +4273,59 @@ const StockForm = ({ formType }) => { />
- {/* - - */} + - setIsModalOpen(true)} /> + setIsModalOpen(true)} size={18} /> + + + + + {isModalOpen && ( { onMappingAdded={handleModalSubmited} /> )} - {Variants?.length > 1 && ( - - ({ - value: option.ProdIdProdName, - label: option.ProdVariantName, - }))} - label={'Variant Name'} - className="field-DropDown" - onChangeFunction={(e) => - ProductVariantDropDownChange(e) - } - valueData={selectedProductVariantData} - disabled={editstate?.ProdId ? true : false} - /> - {/* - + +
{ + setTempSelectedColumns([...selectedAdditionalColumn]); + setShowColumnModal(true); + }}> + + - */} - - )} + +
+
+ } + onChange={(e) => { + const value = e.target.value.toLowerCase(); + setSearchValue(value); + }} + style={{ width: '300px' }} + /> +
+
+ +
{ maxwidth: '500px', overflowX: 'auto', scrollbarWidth: 'thin', + maxHeight: "50vh" }} > -
+ {/* 0 ? filteredPurchaseData : PurchaseData} columns={columns} rowClassName="editable-row" onRow={(record, index) => ({ @@ -3932,48 +4398,75 @@ const StockForm = ({ formType }) => { }, })} pagination={false} + /> */} + +
({ + onClick: () => { + edit(record); + }, + })} + pagination={false} + locale={{ + emptyText: isSearching ? 'No matching products found' : 'No data', + }} /> + - {PurchaseData?.length > 0 && ( -
-
- -
- {PurchaseData.reduce( - (acc, data) => acc + data?.Amount, - 0 - )?.toFixed(2)} -
-
- {!orderType && ( -
- -
- )} -
- )} + -
- } - /> -
+ + + {PurchaseData?.length > 0 && ( +
+
+ +
+ {PurchaseData.reduce( + (acc, data) => acc + data?.Amount, + 0 + )?.toFixed(2)} +
+
+ {!orderType && ( +
+ +
+ )} +
+ )} + + } + /> + + { autoComplete="off" label="GST No" autocapitalize="on" - // isOnChange={formType == 'edit' ? true : false} + // isOnChange={formType == 'edit' ? true : false} /> @@ -4101,10 +4594,10 @@ const StockForm = ({ formType }) => { // isOnChange={formType == 'edit' ? true : false} inputMode="numeric" onInput={(e) => - (e.target.value = e.target.value.replace( - /[^0-9]/g, - '' - )) + (e.target.value = e.target.value.replace( + /[^0-9]/g, + '' + )) } /> @@ -4116,7 +4609,7 @@ const StockForm = ({ formType }) => { MailId} autocomplete="off" - // isOnChange={formType == 'edit' ? true : false} + // isOnChange={formType == 'edit' ? true : false} /> @@ -4143,7 +4636,7 @@ const StockForm = ({ formType }) => { Point of Contact} autocomplete="off" - // isOnChange={formType == 'edit' ? true : false} + // isOnChange={formType == 'edit' ? true : false} /> @@ -4165,7 +4658,7 @@ const StockForm = ({ formType }) => { label={} autocomplete="off" maxLength="10" - // isOnChange={formType == 'edit' ? true : false} + // isOnChange={formType == 'edit' ? true : false} /> @@ -4176,7 +4669,7 @@ const StockForm = ({ formType }) => { POC MailId} autocomplete="off" - // isOnChange={formType == 'edit' ? true : false} + // isOnChange={formType == 'edit' ? true : false} /> @@ -4459,18 +4952,18 @@ const StockForm = ({ formType }) => { Sales Price} - // isOnChange={(editstate?.SellPrice || QrcodeExistsData?.[0]?.SellPrice)? true : false} + // isOnChange={(editstate?.SellPrice || QrcodeExistsData?.[0]?.SellPrice)? true : false} /> ({ @@ -4530,7 +5023,7 @@ const StockForm = ({ formType }) => { // isOnchanges={(editstate?.Brand || SelectedBrand)?true:false} onChangeFunction={handleBrandDropDownChange} valueData={SelectedBrand} - // disabled={editstate?.Brand ? true : false} + // disabled={editstate?.Brand ? true : false} /> { onSelectFuntion={(e) => openAmountPerPieceAvailable(e) } - // disabled={editstate?.QRCode ? true : false} + // disabled={editstate?.QRCode ? true : false} /> {(QrcodeAuto == 'N' || editstate?.QRCode) && ( @@ -4669,38 +5162,38 @@ const StockForm = ({ formType }) => { {(QrcodeAutoSingle == 'N' || editstate?.OnePcQR) && ( -
- - { - await validateSafeInput(value); // To block HTML tags & SQL keywords - return Promise.resolve(); +
+ + { + await validateSafeInput(value); // To block HTML tags & SQL keywords + return Promise.resolve(); + }, }, - }, - ]} - > - + - {QrcodeSingleExistsVal && - QrcodeSingleExistsVal} - -
- )} + /> + {QrcodeSingleExistsVal && + QrcodeSingleExistsVal} +
+
+ )} )} @@ -4725,7 +5218,7 @@ const StockForm = ({ formType }) => {
)} @@ -5185,9 +5678,10 @@ const StockForm = ({ formType }) => { title="IMEI /Serial Number / Mac Id" open={imeiSerialOpen} footer={true} + width={600} buttonText="Submit" children={ -
+
'editable-row'} @@ -5201,365 +5695,51 @@ const StockForm = ({ formType }) => { handleSubmit={handleModelDataSumbitOrClose} handleCancel={handleModelDataSumbitOrClose} > + -

{`${selectedRowRecord?.ProdName} (${selectedRowRecord?.ProdVariantName})`}

-
-
- - - - - { - 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('')}` - : cleanedValue; - }} - /> - - - - - { - if ( - value === undefined || - value === null || - value === '' - ) { - return Promise.resolve(); - } - - if (!/^[0-9]\d*(\.\d+)?$/.test(value)) { - return Promise.reject( - 'Please enter a valid FreeQty' - ); - } - - if (value.toString().length > 10) { - return Promise.reject( - 'FreeQty cannot exceed more than 10 characters' - ); - } - - return Promise.resolve(); - }, - }, - ]} - > - - -
- { - if (value === undefined || value === '') - return Promise.resolve(); - - if (value.length > 30) { - return Promise.reject( - 'HSN cannot exceed 30 characters' - ); - } - - return Promise.resolve(); - }, - }, - ]} - > - { + setShowColumnModal(false); + setSelectedFields([...selectedAdditionalColumn.map(col => + tableFieldPreferences?.find(pref => pref.label === col)?.value + ).filter(Boolean)]); + setTempSelectedColumns([...selectedAdditionalColumn]); + }} + > +
+ {tableFieldPreferences?.map((option) => ( +
+ +
+ ))} +
+
+ setExtractorModalVisible(false)}