import React, { useState, useEffect, useRef, useCallback } from 'react'; import { useNavigate } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import { Form, Table, Input, Select, AutoComplete, Radio, DatePicker, Button, Tooltip, Space, Segmented, } from 'antd'; import { BsUpcScan } from "react-icons/bs"; import { ArrowRightOutlined, DeleteFilled, SearchOutlined, } from '@ant-design/icons'; import { IoMdAddCircleOutline } from 'react-icons/io'; import { FaEye, FaPrint, FaTruck } from 'react-icons/fa'; import { Messages } from '../../Components/Notifications/Messages.jsx'; import { InputField } from '../../Components/Forms/InputField.jsx'; import Buttons from '../../Components/Forms/Buttons.jsx'; import { getSession, pdfDiv, printDiv, validateSafeInput, } from '../../Services/Others.js'; import FormHeader from '../PageComponents/FormHeader.jsx'; import { DropDowns } from '../../Components/Forms/DropDown.jsx'; import { CiBarcode } from 'react-icons/ci'; import { AdminUserData, getProdQuoaVariantdata, getPurProductData, } from '../../Features/PurchaseQuotation/PurchaseQuotation.js'; import './DeliveryChallan.scss'; import { getPurchaseTaxTypeData } from '../../Features/StockMaster/StockMaster.js'; import { changeBreadCrumb, getEmpAccess, } from '../../Features/AppPage/CenterPage.js'; import { useAuth } from '../../AuthContext.jsx'; import { getAllCustomer } from '../../Features/BookingScreen/BookingData/BookingData.js'; const subDirectory = import.meta.env.BASE_URL; import TooltipWrapper from '../../Components/Tooltip/Tooltip.jsx'; import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx'; import { PostChallan } from '../../Features/DeliveryChallan/DeliveryChallan.js'; import { MdOutlineMail } from 'react-icons/md'; import DeliveryPrint from './DeliveryPrint.jsx'; import { Emailsend } from '../../Features/PurchaseOrder/PurchaseOrder.js'; import FloatLabel from '../../Components/Forms/FloatLabel/index.jsx'; import { debounce } from 'lodash'; import { DCPrintStyleFunction } from './DCPrintStyleFunction.js'; import { useSelector } from 'react-redux'; import { getPrintSelectionComponentData } from '../../Features/ThemeChange/ThemeChange.js'; const DeliveryChellanForm = () => { const { SadminuserAccess } = useAuth(); let SAAccessCommonMaster = SadminuserAccess?.find( (e) => e?.MenuName === 'Delivery challan' ); const formRef = useRef(null); const transportFormRef = useRef(null); const [form] = Form.useForm(); const dispatch = useDispatch(); const navigate = useNavigate(); const CompId = getSession('CompId'); const BranchId = getSession('BranchId'); const AppId = getSession('AppId'); const UserId = getSession('UserId'); const UserType = getSession('UserType'); const [DCPrintTemplateStyle, setDCPrintTemplateStyle] = useState(null); const [DCPrintTemplateDtl, setDCPrintTemplateDtl] = useState(null); const [messageType, setMessageType] = useState(null); const [messageData, setMessageData] = useState(null); // const [AdminUser, setAdminUser] = useState([]); const [SelecAdminUser, setSelecAdminUser] = useState(null); const [SelTaxType, setSelTaxType] = useState(null); const [SelTaxTypeName, setSelTaxTypeName] = useState(null); const [ProductData, setProductData] = useState([]); const [AllCustomer, setAllCustomer] = useState(null); const [Modal, setModal] = useState(false); console.log(AllCustomer, 'AllCustomer'); const [SelProduct, setSelProduct] = useState(null); const [selectedProductName, setSelectedProductName] = useState(null); const [productSearchText, setProductSearchText] = useState(""); const [scanner, setScanner] = useState(false); console.log(ProductData, 'ProductData'); const [selectedProductVariantData, setselectedProductVariantData] = useState(null); const [Variants, setVariants] = useState(); const [TableData, setTableData] = useState([]); const [editingKey, setEditingKey] = useState(''); const [TotalBillAmount, setTotalBillAmount] = useState(null); const [TotalCgst, setTotalCgst] = useState(null); const [TotalSgst, setTotalSgst] = useState(null); const [TotalIgst, setTotalIgst] = useState(null); const [TotalAmount, setTotalAmount] = useState(null); const isEditing = (record, index) => index === editingKey; const [empData, setEmpData] = useState(); const [addnewAccess, setaddnewAccess] = useState(true); const [isbarcode, setisbarcode] = useState(false); const [selectedMode, setSelectedMode] = useState(''); const [isSubmitted, setIsSubmitted] = useState(false); const [PrintingData, setPrintingData] = useState([]); const [iSEmail, setiSEmail] = useState(false); const [pendingOrderDetails, setPendingOrderDetails] = useState(null); const [pendingRecord, setPendingRecord] = useState(null); console.log(PrintingData, 'PrintingDataPrintingData'); console.log(TableData, 'TableData'); const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, { name: 'Delivery Challan', link: `${subDirectory}setting/delivery-challan`, }, ]; useEffect(() => { dispatch(changeBreadCrumb({ items: items })); // getAdminUserdata(); getProduct(); fetchdata(); getPrintData(); }, []); const changebarcode = useCallback(() => { setisbarcode((prev) => !prev); }, []); useEffect(() => { if (UserType === 'Employee') { fetchApi(); } }, [UserType]); useEffect(() => { let hasAccess = false; if (UserType === 'Admin' || UserType === 'Super Admin') { hasAccess = true; } else if (UserType === 'Employee') { hasAccess = empData?.AddAccess === 'Y'; } else if (UserType === 'Super Admin User') { hasAccess = SAAccessCommonMaster?.AddAccess === 'Y'; } setaddnewAccess(!hasAccess); }, [empData, SAAccessCommonMaster, UserType]); const debouncedScannerSearch = useCallback( debounce((value) => { const qr = value?.trim(); const matchedProduct = ProductData.find( (p) => p.QRCode?.toLowerCase() === qr.toLowerCase() ); if (matchedProduct) { let productName = {}; productName.label = `${matchedProduct?.ProdName} (${matchedProduct.Size} ${matchedProduct.UomName})${matchedProduct?.BrandName ? ` - ${matchedProduct?.BrandName}` : ''}` ProductDropDownChange(matchedProduct.ProdId, productName); if (matchedProduct?.ProdVariantPriceDetails?.length < 2) { setSelectedProductName(""); setSelProduct(null) } } else { setMessageType("error"); setMessageData("The Scanned Product not Available in Product List") } }, 300), [ProductData] ); const fetchApi = async () => { let data = { CompId: CompId, BranchId: BranchId, AppId: AppId, EmpId: UserId, }; let response = await dispatch(getEmpAccess(data)).unwrap(); let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter( (item) => item.ConfigName === 'Purchase Quotation' ); setEmpData(datas?.[0]); }; const getPrintData = async () => { let data = { CompId: CompId, BranchId: BranchId, AppId: AppId, }; let response = await dispatch(getPrintSelectionComponentData(data)).unwrap(); if(response?.data?.statusCode === 1) { let DCPrintTemplate = response?.data?.data?.[0]?.ComponentDetails?.find( (item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan' ); console.log(DCPrintTemplate,response?.data?.data?.[0]?.ComponentDetails?.find( (item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan' ), 'DCPrintTemplate'); setDCPrintTemplateStyle(DCPrintTemplate?.StyleName); setDCPrintTemplateDtl(DCPrintTemplate); } }; // useEffect(() => { // Print(); // }, [PrintData]); useEffect(() => { let total = TableData?.reduce((accumulator, currentValue) => { return accumulator + currentValue.NetAmt; }, 0); setTotalAmount(total); let cgst = TableData?.filter( (item) => item.TaxName?.toLowerCase() === 'cgst,sgst' ); let totalgst = cgst?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TaxAmt; }, 0); setTotalCgst(totalgst / 2); setTotalSgst(totalgst / 2); let igst = TableData?.filter( (item) => item.TaxName?.toLowerCase() === 'igst' ); let totaligst = igst?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TaxAmt; }, 0); setTotalIgst(totaligst); let billtotal = TableData?.reduce((accumulator, currentValue) => { return accumulator + currentValue.NetAmt; }, 0); console.log(billtotal, total, TableData, 'billtotal'); setTotalBillAmount(billtotal); }, [TableData]); const getProduct = async () => { let Product = await dispatch( getPurProductData({ CompId: CompId, AppId: AppId, BranchId: BranchId, ActiveStatus: 'A', }) ).unwrap(); if (Product?.data?.statusCode === 1) { let Productonlydata = Product?.data?.data?.filter( (item) => item?.ProdTypeName === 'Product' ); setProductData(Productonlydata); } else { setProductData([]); } }; const fetchdata = async () => { let res = await dispatch( getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId }) ).unwrap(); await setAllCustomer(res?.data?.data); }; const handleAdminUserDropDownChange = (UserId) => { setSelecAdminUser(UserId); formRef.current?.setFieldsValue({ CustId: UserId }); setIsSubmitted(false); }; const handleScanSearch = () => { if (scanner === false) { setMessageType("success"); setMessageData("Search by QrCode/BarCode Enabled") } else { setMessageType("success"); setMessageData("Search by QrCode/BarCode Disabled") } setScanner(prev => !prev) setSelectedProductName(null); setselectedProductVariantData(null); setVariants(null) formRef?.current?.setFieldsValue({ ProdId: null, VarProdId: null }); } const handleProductSearch = (value) => { if (scanner) { debouncedScannerSearch(value); } setProductSearchText(value) setSelectedProductName(value); setselectedProductVariantData([]); setVariants([]) }; const ProductDropDownChange = async (ProdId, option) => { formRef?.current?.resetFields(['VarProdId']); setProductSearchText("") setSelectedProductName(option?.label ? option?.label : '') console.log(ProdId, 'ProdIdProdId'); setSelProduct(ProdId); formRef.current?.setFieldsValue({ ProdId: ProdId }); let x = ProductData?.find((e) => e.ProdId === ProdId)?.ProdName; let variantValues1 = await dispatch( getProdQuoaVariantdata({ CompId: CompId, AppId: AppId, BranchId: BranchId, prodName: x, }) ).unwrap(); let variants1 = variantValues1?.data?.data; // let cc = variants1?.[0]?.ProductDetail; let cc = variants1?.filter((item) => item?.ProdName == x)?.[0]?.ProductDetail; setVariants( cc?.[0]?.ProdVariantDetails?.map((detail) => ({ ...detail, ProdIdProdName: `${detail.ProdVariantName} ${detail.ProdId}`, })) ); if (cc?.[0]?.ProdVariantDetails?.length < 2) { if (TableData?.some((e) => e.ProdId === ProdId) ) { setMessageType('error'); setMessageData('Already Product Exists'); } else { let ProductData1 = ProductData?.find((e) => e.ProdId === ProdId); console.log(ProductData1, 'ProductData1ProductData1'); let ProduData2 = { ProdId: ProductData1?.ProdId, ProdName: ProductData1?.ProdName, UomName: ProductData1?.UomName, Price: ProductData1?.SellPrice, TaxName: ProductData1?.TaxName, HSNCode: ProductData1?.HSNCode, Size: ProductData1?.Size, InwardDtlId: ProductData1?.InwardDtlId, // OnePcsAvailable:ProductData1?.OnePcsAvailable, // NumberofPieceinside: ProductData1?.NoOfPcs, // AmountPerPiece: ProductData1?.OnePcsPrice, TaxId: ProductData1?.TaxId, TaxPercentage: ProductData1?.TaxPercentage, SinglePc: ProductData1?.OnePcsAvailable, }; let tempPurData = { ...ProduData2, Qty: 0, // 'InwardPrice': 0, // PurcDisc: 0, // NetAmt: 0, // BillAmount: 0, // DiscType: 'P', // 'WhSalePrice': 0, // 'ReceivedQty': 0, // 'AcceptedQty': 0, // 'RejectedQty': 0, // "OfferPrice": 0, // "SpecialPrice": 0, ProdVariantName: 'Variant 1', // "FreeItem": 0, // 'TaxPerc': PurcselectedTax ? PurcselectedTax : 0, // TaxAmt: 0, // 'TaxType': SelectedPurcTaxType ? SelectedPurcTaxType : 0, }; form.setFieldsValue({ // [`BalanceQty${TableData.length + 1}`]: undefined, // [`ReceivedQty${index}`]: undefined, // [`AcceptedQty${index}`]: undefined, // [`RejectedQty${index}`]: undefined, // [`Amount${TableData.length + 1}`]: ProductData1?.SellPrice, // [`FreeQty${index}`]: undefined, // [`InwardPrice${index}`]: undefined, // [`MRP${index}`]: undefined, // [`PurcDisc${TableData.length + 1}`]: 0, // [`SellPrice${TableData.length + 1}`]: ProductData1?.SellPrice, // [`WhSalePrice${index}`]: undefined, // [`offerSalePrice${index}`]: undefined, // [`splSalePrice${index}`]: undefined }); setTableData([...TableData, tempPurData]); } } }; const ProductVariantDropDownChange = (value) => { const ProdName2 = Variants?.filter( (item) => item.ProdIdProdName === value )?.[0]?.ProdVariantName; const ProdName1 = TableData?.some( (e) => e.ProdId === SelProduct && e.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 x = VariantData1?.filter((e) => e.InwardDtlId == value); // let u = ProductData?.find((e) => e.ProdId == selectedProductData); // console.log(first) let ProductData1 = ProductData?.find((e) => e.ProdId === SelProduct); console.log(ProductData1, 'ProductData1ProductData1'); let mrp; let sellprice; let InwardDtlId; if (ProdName == 'Variant 1') { mrp = ProductData1?.MRP; sellprice = ProductData1?.SellPrice; InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find( (item) => item.ProdVariantName == ProdName )?.InwardDtlId; } else { mrp = ProductData1?.ProdVariantPriceDetails?.find( (item) => item.ProdVariantName == ProdName )?.MRP; sellprice = ProductData1?.ProdVariantPriceDetails?.find( (item) => item.ProdVariantName == ProdName )?.SellPrice; InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find( (item) => item.ProdVariantName == ProdName )?.InwardDtlId; } let ProduData2 = { ProdId: ProductData1?.ProdId, // MRP: mrp, ProdName: ProductData1?.ProdName, UomName: ProductData1?.UomName, Price: sellprice, TaxName: ProductData1?.TaxName, HSNCode: ProductData1?.HSNCode, // StockAvailable: ProductData1?.StockAvailable, // OnePcsAvailable:ProductData1?.OnePcsAvailable, // NumberofPieceinside: ProductData1?.NoOfPcs, // AmountPerPiece: ProductData1?.OnePcsPrice, InwardDtlId: InwardDtlId, Size: ProductData1?.Size, TaxId: ProductData1?.TaxId, TaxPercentage: ProductData1?.TaxPercentage, }; // ProduData2["StockAvailable"]="Y" let tempPurData = { ...ProduData2, Qty: 0, // PurcDisc: 0, // NetAmt: 0, // BillAmount: 0, // DiscType: 'P', ProdVariantName: ProdName, // TaxAmt: 0, }; setTableData([...TableData, tempPurData]); } }; const onComplete = useCallback(() => { setMessageData(null); setMessageType(null); }, []); const save = async (index) => { try { 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]; } const newData = [...TableData]; // const index = newData.findIndex((item) => recordKey === item.InwardDtlId); if (index > -1) { const item = newData[index]; newData.splice(index, 1, { ...item, ...modifiedObject }); setTableData(newData); setEditingKey(''); } } catch (err) { console.error('Save failed:', err); } }; const handleKeyPress = async (e, record, index) => { if (e.key === 'Enter') { try { await form.validateFields(); save(index); } catch (error) { console.error('Save failed:', error); } } }; const statusFormatter = (record)=>{ let filterData=TableData?.filter((e)=> e?.InwardDtlId !=record.InwardDtlId); setTableData(filterData) } const getColumns = (data, seltax) => { const hasDiscount = data?.some((record) => record.PurcDisc > 0); const baseColumns = [ { title: 'Sl.No', align: 'center', key: 'sno', width: '50px', render: (text, object, index) => ( {index + 1} ), }, { title: 'Product Name', dataIndex: 'ProdName', key: 'ProdName', align: 'right', width: '300px', render: (text, record, index) => ( { record?.ProdName + '(' + record?.Size + '-' + record?.UomName + ')' // + // '(' + // record?.ProdVariantName + // ')' } ), }, { title: 'Variant Name', dataIndex: 'ProdVariantName', key: 'ProdVariantName', }, { title: 'Qty', dataIndex: 'Qty', key: 'Qty', editable: true, with: '100px', render: (text, record, index) => { return isEditing(record, index) ? ( handleKeyPress(e, record, index)} onBlur={(e) => handleQtyChange(e, record)} onChange={(e) => handleQtyChange(e, record, index)} autoComplete="off" inputMode="decimal" onInput={(e) => { let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters const parts = cleanedValue.split('.'); if (cleanedValue.startsWith('.')) { cleanedValue = '0' + cleanedValue; } e.target.value = parts.length > 2 ? `${parts[0]}.${parts.slice(1).join('')}` : cleanedValue; }} /> ) : ( text ); }, }, { title: 'Action', key: 'Action', dataIndex: 'Action', render: (_, record, index) => TableData.length >= 1 ? ( { ( statusFormatter(record) } /> ) } ) : null, }, ]; return baseColumns; }; const columns = getColumns(TableData, SelTaxType); const edit = (record, index) => { form.setFieldsValue({ ...record }); setEditingKey(index); // setindex(index); form.setFieldsValue({ [`Qty${index}`]: record?.Qty, // [`NetAmt${index}`]: !isNaN(record?.NetAmt) ? record?.NetAmt : 0, // [`PurcDisc${index}`]: record?.PurcDisc, // [`Price${index}`]: record?.Price, }); }; // }; // const statusFormatters = (record, index) => { // // Remove the row from table data // const newData = TableData.filter((_, i) => i !== index); // setTableData(newData); // setDelete(true); // setEditingKey(''); // // Get all current form values // const currentFormValues = form.getFieldsValue(); // // Clear all form fields first // const allFieldsToClear = []; // for (let i = 0; i < TableData.length; i++) { // allFieldsToClear.push( // `BalanceQty${i}`, // `Amount${i}`, // `PurcDisc${i}`, // `SellPrice${i}`, // `Qty${i}`, // `NetAmt${i}`, // `Price${i}`, // `DiscType${i}` // ); // } // const clearAllValues = {}; // allFieldsToClear.forEach((field) => { // clearAllValues[field] = undefined; // }); // // Set new form values with correct indices // const newFormValues = {}; // newData.forEach((item, newIndex) => { // newFormValues[`Qty${newIndex}`] = item.Qty; // newFormValues[`NetAmt${newIndex}`] = item.NetAmt; // newFormValues[`PurcDisc${newIndex}`] = item.PurcDisc; // newFormValues[`Price${newIndex}`] = item.Price; // newFormValues[`DiscType${newIndex}`] = item.DiscType; // }); // // Apply the new form values // form.setFieldsValue({ ...clearAllValues, ...newFormValues }); // console.log(form.getFieldsValue(), 'jjij'); // }; const handleQtyChange = (e, record, index) => { const qty = e.target.value; if (!/^\d*\.?\d*$/.test(qty)) { setMessageType('error'); setMessageData('Only numeric values are allowed'); return; } const sellprice = parseInt(record.Price); const Amount = !isNaN(sellprice * parseInt(qty)) ? sellprice * parseInt(qty) : 0; const taxamt = SelTaxTypeName?.toLowerCase() === 'withtax' ? (Amount * parseInt(record?.TaxPercentage)) / (100 + parseInt(record?.TaxPercentage)) : 0; const newData = TableData.map((item, index1) => { if (index1 === index) { return { ...item, Qty: qty, NetAmt: Amount, TaxAmt: taxamt, // BillAmount: Amount - taxamt, TotalAmount: Amount * qty, GrossTotal: Amount + taxamt, ProductRate: item.Price, }; } return item; }); setTableData(newData); form.setFieldsValue({ ...form.getFieldsValue(), [`Qty${index}`]: qty, // [`NetAmt${index}`]: Amount, // [`ReceivedQty${index}`]: qty, // [`AcceptedQty${index}`]: acceptedQty, // [`RejectedQty${index}`]: qty - acceptedQty, // ReceivedQty: qty, // AcceptedQty: acceptedQty, // RejectedQty: qty - acceptedQty, // [`PurcDisc${index}`]: 0, // [`DiscType${index}`]: 'P', }); }; const PrintQuotation = async () => { if (TableData.some((item) => !item.Qty || parseFloat(item.Qty) < 1)) { setMessageType('error'); setMessageData('Every product must have a quantity of at least 1.'); return; } setIsSubmitted(true); // await printDiv(`Pur-Quot-Print`, QuotationStyle) let data1 = transportFormRef.current?.getFieldsValue(); console.log(data1, 'data1'); let data = { AppId: AppId, CompId: CompId, BranchId: BranchId, CustId: SelecAdminUser, TotalAmount: TotalBillAmount, TaxAmount: TotalCgst + TotalSgst + TotalIgst || 0, GrandTotal: TotalAmount, VehicleNo: data1?.vehicleNo ? data1?.vehicleNo : null, Remarks: '', ModeOfTransport: selectedMode, TransporterId: data1?.transporter ? data1?.transporter : null, TransporterName: data1?.transporterName ? data1?.transporterName : null, ProductDetails: TableData?.map((item) => { return { ProdId: item?.ProdId, InwardDtlId: item?.InwardDtlId, SinglePc: item?.SinglePc, Qty: item?.Qty, ProductRate: item?.ProductRate, TotalAmount: item?.TotalAmount, TaxAmount: item?.TaxAmt, TaxId: item?.TaxId, GrossTotal: item?.TotalAmount, }; }), CreatedBy: UserId, }; let response = await dispatch(PostChallan(data)).unwrap(); console.log(response, 'responseresponse'); if (response?.data?.statusCode == 1) { setMessageType('success'); setMessageData(response?.data?.response); transportFormRef?.current?.resetFields(); formRef?.current?.resetFields(); setSelecAdminUser(); setSelTaxType(); setSelProduct(); setSelTaxTypeName(); setVariants(); setTotalBillAmount(); setTableData([]); setTotalCgst(); setTotalSgst(); setTotalIgst(); const challanDetail = response?.data?.DeliveryChallanDetails?.[0]; const orderData = { Remarks: challanDetail?.Remarks, DCNo: challanDetail?.DCNo, DCDate: challanDetail?.DCDate, CustMobile: challanDetail?.CustMobile, CustName: challanDetail?.CustName, TransporterName: challanDetail?.TransporterName, ModeOfTransport: challanDetail?.ModeOfTransport, TransporterId: challanDetail?.TransporterId, ProductDetails: challanDetail?.ProductDetails, TotalAmount: challanDetail?.TotalAmount, VehicleNo: challanDetail?.VehicleNo }; setPrintingData([orderData]); navigate(`${subDirectory}setting/delivery-challan`, { state: { Notiffy: { messageType: 'success', messageData: response?.data?.response, }, }, }); } // if (response?.data?.statusCode == 1) { // navigate(`${subDirectory}setting/customer-master/`, { // state: { // Notiffy: { // messageType: 'success', // messageData: response?.data?.response, // }, // }, // }); // } else { setMessageType('error'); setMessageData(response?.data?.response); } }; const PurchaseOrderStyle = ``; const handleSendEmailWithEnteredEmail = async (values) => { const record = { ...pendingRecord, CustEmail: values.email }; await handleEmailClick(pendingOrderDetails, record); setiSEmail(false); setPendingOrderDetails(null); setPendingRecord(null); form.resetFields(); }; const handlePrint = async() => { const DCstyle = await DCPrintStyleFunction( DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle); const stylesMap = { 'Style 1': 'DCPrintStyle1', 'Style 2': 'DCPrintStyle2', 'Style 3': 'DCPrintStyle3', 'Style 4': 'DCPrintStyle4', 'Style 5': 'DCPrintStyle5', 'Style 6': 'DCPrintStyle6', 'Style 7': 'DCPrintStyle7', 'Style 8': 'DCPrintStyle8', 'Style 9': 'DCPrintStyle9', 'Style 10': 'DCPrintStyle10', 'Style 11': 'DCPrintStyle11', 'Style 12': 'DCPrintStyle12', 'Style 13': 'DC-Default-Print', A4: 'DCPrintStyleA4', A5: 'DCPrintStyleA5', A4Standard: 'DCPrintStyleA4Standard', }; const selectedStyle = stylesMap[ DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle ]; console.log(selectedStyle,DCstyle, 'selectedStyle'); setTimeout(() => { printDiv(`${selectedStyle}`, DCstyle); }, 100); }; const onChangeprodFunction = (e) => { if (isbarcode) { // When in barcode mode, search by QRCode const productByQR = ProductData.find( (p) => p.QRCode && p.QRCode.toLowerCase() === e.toLowerCase() ); if (productByQR) { const productValue = productByQR.ProdName + ' ' + '(' + productByQR.Size + productByQR.UomName + ')'; form.setFieldsValue({ ProdId: productValue }); setSelProduct(productValue); ProductDropDownChange({ value: productValue }); } } else { // Normal mode - search by product name form.setFieldsValue({ ProdId: e }); setSelProduct(e); } }; const transporterFn = () => { setModal(true); }; const handleEmailClick = async (ProductDetails, record) => { // alert("This feature is not available yet. Please contact support for assistance."); const orderData = { 0: { ...record }, customerName: record?.CustName || '', CustName: record?.CustName || '', customerAddress: record?.AddressDetails || '', Address1: record?.AddressDetails || '', customerMobile: record?.CustMobile || '', MobileNo: record?.CustMobile || '', CustMail: record?.CustEmail, }; // setPrintData(record); if (orderData?.CustMail) { setTimeout(async () => { try { const blob = await pdfDiv('Pur-Order-Print', PurchaseOrderStyle); console.log(blob, 'blobblob'); const payload = { fileBlob: blob, toEmail: orderData?.CustMail, type: 'PurchaseOrder', messageTemplatesList: [], }; const res = await dispatch(Emailsend(payload))?.unwrap(); console.log('✅ API Response:', res?.data || res); setMessageData('Email sent successfully'); setMessageType('success'); } catch (error) { console.error('❌ Email send failed:', error); setMessageData('Email failed to send'); setMessageType('error'); } }, 300); } else { setPendingOrderDetails(ProductDetails); setPendingRecord(record); setiSEmail(true); } }; const handleTransportModeChange = (e) => { setSelectedMode(e.target.value); // Set the value in the transport form using ref transportFormRef.current?.setFieldsValue({ transportationMode: e.target.value, }); }; const closeDeliveryChallanModel = (e) => { let data = transportFormRef.current?.getFieldsValue(); if (data.lrDate && data.lrDate.format) { data.lrDate = data.lrDate.format('YYYY-MM-DD'); } if (data.dateOfSupply && data.dateOfSupply.format) { data.dateOfSupply = data.dateOfSupply.format('YYYY-MM-DD'); } console.log(data, 'datadata'); e.stopPropagation(); setModal(false); }; return (
navigate(`${subDirectory}setting/delivery-challan/list`)} > View Chellans
({ value: option.CustId, label: option.CustShortName || option.CustName || option.CustMobile, }))} label={} className="field-DropDown" onChangeFunction={handleAdminUserDropDownChange} />
{ const product = ProductData.find(p => p.ProdId === option.value); const nameMatch = option.label.toLowerCase().includes(productSearchText.toLowerCase()); const qrMatch = product?.QRCode?.toLowerCase() == productSearchText.toLowerCase(); return nameMatch || qrMatch; }} options={!scanner ? ProductData?.map ((option) => ({ value: option.ProdId, label: `${option.ProdName} (${option.Size} ${option.UomName})${option?.BrandName ? ` - ${option?.BrandName}` : ''}` })) : []} onSelect={ProductDropDownChange} onChange={handleProductSearch} onKeyDown={(e) => { if (scanner && e.key === "Enter") { e.preventDefault(); } }} >
{/* ({ value: option.ProdName + ' ' + '(' + option.Size + option.UomName + ')', label: option.ProdName + ' ' + '(' + option.Size + option.UomName + ')', qrCode: option.QRCode, }))} style={{ width: '250px', height: '48px' }} onSelect={(value, option) => { if (isbarcode && option.qrCode) { const productByQR = ProductData.find( (p) => p.QRCode === option.qrCode ); if (productByQR) { ProductDropDownChange({ value: productByQR.ProdName + ' ' + '(' + productByQR.Size + productByQR.UomName + ')', }); } } else { ProductDropDownChange(option); } }} filterOption={(input, option) => { if (isbarcode) { return ( option.qrCode && option.qrCode .toLowerCase() .includes(input.toLowerCase()) ); } else { return option.label .toLowerCase() .includes(input.toLowerCase()); } }} value={SelProduct} > onChangeprodFunction(e?.target?.value) } onPressEnter={(e) => onChangeprodFunction(e?.target?.value) } isOnChange={SelProduct ? true : false} suffix={ } /> */} {Variants?.length > 1 && ( ({ value: option.ProdIdProdName, label: option.ProdVariantName, }))} label={'Variant Name'} className="field-DropDown" onChangeFunction={(e) => ProductVariantDropDownChange(e) } /> )}
Add Transport Details{' '}
} handleCancel={(e) => { closeDeliveryChallanModel(e); }} open={Modal} width={700} footer={null} children={
Road Rail Air Not Applicable
{/* transportFormRef.current?.setFieldsValue( { lrNumber: e.target.value } ) } /> transportFormRef.current?.setFieldsValue( { lrDate: date } ) } /> */} transportFormRef.current?.setFieldsValue( { vehicleNo: e.target.value } ) } /> {/* transportFormRef.current?.setFieldsValue( { dateOfSupply: date } ) } /> */} {/* transportFormRef.current?.setFieldsValue( { placeOfSupply: e.target.value } ) } /> */} transportFormRef.current?.setFieldsValue( { transporterName: e.target.value } ) } /> {/* transportFormRef.current?.setFieldsValue({ transporter: value })} /> */} transportFormRef.current?.setFieldsValue( { transporter: e.target.value } ) } />
} handleSubmit={(e) => { closeDeliveryChallanModel(e); }} />
} />
({ onClick: () => { edit(record, index); }, })} pagination={false} />
} htmlType={true} /> {isSubmitted && ( <>
)}
setiSEmail(false)} footer={false} children={
} /> {PrintingData?.length > 0 &&
} ); }; export default DeliveryChellanForm;