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, Checkbox, } 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 { getAllCustomerAndBranch, PendingOrdersDC } 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'; import { DCPDFMobilePrint } from './DCPDFMobilePrint.js'; import { isMobile } from 'react-device-detect'; import EmailModel from '../BookingScreen/Components/UtillComponents/EmailModel.jsx'; 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 [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); const [SelProduct, setSelProduct] = useState(null); const [selectedProductName, setSelectedProductName] = useState(null); const [productSearchText, setProductSearchText] = useState(""); const [scanner, setScanner] = useState(false); const [Variants, setVariants] = useState([]); const [TableData, setTableData] = useState([]); const [editingKey, setEditingKey] = useState(''); const [ordersCustomer, setOrdersCustomer] = 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 [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); const [segmentValue, setSegmentValue] = useState("N") const [selectedOrder, setSelectedOrder] = useState(); const [orderTableData, setOrderTableData] = useState([]); const [emailSending, setEmailSending] = useState(false); const [selectedCustomertype, setSelectedCustomertype] = useState('N'); const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, { name: 'Delivery Challan', link: `${subDirectory}setting/delivery-challan`, }, ]; useEffect(() => { dispatch(changeBreadCrumb({ items: items })); getProduct(); getPrintData(); }, []); useEffect(() => { fetchdata(); }, [selectedCustomertype]); 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 === 'Delivery Challan' ); 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([]); } }; console.log(AllCustomer, "AllCustomerAllCustomer") const fetchdata = async () => { try { const resCustomer = await dispatch(getAllCustomerAndBranch({ CompId, AppId, BranchId, selectedCustomertype })).unwrap(); if (resCustomer?.data?.statusCode === 1) { setAllCustomer(resCustomer?.data?.data); } else { setAllCustomer([]); // setMessageType("error"); // setMessageData(resCustomer?.data?.response); } const resOrders = await dispatch(PendingOrdersDC({ CompId, AppId, BranchId })).unwrap(); if (resOrders?.data?.statusCode === 1) { setOrdersCustomer(resOrders?.data?.data?.PurchaseOrder); } else { setOrdersCustomer([]); // setMessageType("error"); // setMessageData(resOrders?.data?.response); } } catch (err) { // setAllCustomer([]); setOrdersCustomer([]); setMessageType("error"); setMessageData("Something went wrong"); } }; const handleOrderChange = (params) => { const [suppId, purOrderId] = params.split("||"); formRef?.current?.setFieldsValue({ Order: suppId }) setSelectedOrder(suppId) const { OrderDetails } = ordersCustomer?.find(find => find.SuppId === suppId && find.PurOrderId === purOrderId); setOrderTableData(OrderDetails?.map(item => { const { InwardDtlId, OnePcsAvailable, SellPrice, TaxId, TaxName } = ProductData?.find((e) => e.ProdId === item.ProdId); return { ...item, InwardDtlId, TaxId, TaxName, SinglePc: OnePcsAvailable, ProductRate: SellPrice, TotalAmount: item.OrderQty * SellPrice, TaxAmount: 0, GrossTotal: item.OrderQty * SellPrice } })) setSelectedProductName(null) setVariants([]) setTableData([]) formRef?.current?.setFieldsValue({ ProdId: undefined, }) } 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); setVariants(null) formRef?.current?.setFieldsValue({ ProdId: null, VarProdId: null }); } const handleProductSearch = (value) => { if (scanner) { debouncedScannerSearch(value); } setSelectedProductName(value); setProductSearchText(value) setVariants([]) }; const ProductDropDownChange = async (ProdId, option) => { formRef?.current?.resetFields(['VarProdId']); setProductSearchText("") setSelectedProductName(option?.label ? option?.label : '') 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 (segmentValue === "O") { if (cc?.[0]?.ProdVariantDetails?.length < 2) { if (orderTableData?.some((e) => e.ProdId === ProdId)) { setMessageType('error'); setMessageData('Already Product Exists'); } else { const { ProdName, UomName, OnePcsAvailable, SellPrice, InwardDtlId, TaxId, TaxName } = ProductData?.find(item => item.ProdId === ProdId); setOrderTableData(prev => [...prev, { OrderQty: 1, ProdId, ProdName: ProdName, ProdVariantName: "Variant 1", PurOrderId: "", UOM: UomName, InwardDtlId, TaxId, TaxName, SinglePc: OnePcsAvailable, ProductRate: SellPrice, TotalAmount: 1 * SellPrice, TaxAmount: 0, GrossTotal: 1 * SellPrice }]) } } } else { 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); 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, TaxId: ProductData1?.TaxId, TaxPercentage: ProductData1?.TaxPercentage, SinglePc: ProductData1?.OnePcsAvailable, }; let tempPurData = { ...ProduData2, Qty: 0, ProdVariantName: 'Variant 1', }; setTableData([...TableData, tempPurData]); } } } }; const ProductVariantDropDownChange = (value) => { if (segmentValue === "O") { const selectedVarientName = Variants?.filter(({ ProdIdProdName }) => ProdIdProdName === value)?.[0]?.ProdVariantName; const isVarientDublicate = orderTableData?.some(({ ProdId, ProdVariantName }) => ProdId === SelProduct && ProdVariantName === selectedVarientName); if (isVarientDublicate) { setMessageType('error'); setMessageData('Already variant Exists'); } else { formRef?.current?.setFieldsValue({ VarProdId: value }); setOrderTableData(prev => prev.map(item => { if (item.ProdId === SelProduct) { return { ...item, ProdVariantName: selectedVarientName } } return item })) const { ProdName, UomName, OnePcsAvailable, SellPrice, InwardDtlId, TaxId, TaxName } = ProductData?.find(item => item.ProdId === SelProduct); setOrderTableData(prev => [...prev, { OrderQty: 1, ProdId: SelProduct, ProdName: ProdName, ProdVariantName: "Variant 1", PurOrderId: "", UOM: UomName, InwardDtlId, TaxId, TaxName, SinglePc: OnePcsAvailable, ProductRate: SellPrice, TotalAmount: 1 * SellPrice, TaxAmount: 0, GrossTotal: 1 * SellPrice }]) } } else { 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; formRef?.current?.setFieldsValue({ VarProdId: value }); let ProductData1 = ProductData?.find((e) => e.ProdId === SelProduct); 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, ProdName: ProductData1?.ProdName, UomName: ProductData1?.UomName, Price: sellprice, TaxName: ProductData1?.TaxName, HSNCode: ProductData1?.HSNCode, InwardDtlId: InwardDtlId, Size: ProductData1?.Size, TaxId: ProductData1?.TaxId, TaxPercentage: ProductData1?.TaxPercentage, }; let tempPurData = { ...ProduData2, Qty: 0, ProdVariantName: ProdName, }; 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 ordersColumns = [ { title: "SL.NO", key: "ProdId", dataIndex: 'ProdId', align: "center", render: (text, object, index) => ( {index + 1} ), }, { title: "Product Name", key: "ProdName", dataIndex: 'ProdName', align: "center", render: (text, record, index) => ( {text + " " + record?.UOM} ), }, { title: "Product Variant Name", key: "ProdVariantName", dataIndex: 'ProdVariantName', align: "center", }, { title: "Product Rate", key: "ProductRate", dataIndex: 'ProductRate', align: "center", render: (value) => ( {Number(value).toFixed(2)} ), }, { title: "Order Qty", key: "OrderQty", dataIndex: 'OrderQty', align: "center", render: (text, object, index) => ( value && Number(value) >= 1 ? Promise.resolve() : Promise.reject('Order Qty must be at least 1'), }, ]} > { const value = e.target.value; if (Number(value) < 1) { setMessageType('error'); setMessageData('Order Qty must be at least 1'); return; } handlePendingOrdersQtyOnChange(value, object, index); }} /> ), }, { title: "Total Amount", key: "TotalAmount", dataIndex: 'TotalAmount', align: "center", render: (value) => ( {Number(value).toFixed(2)} ), }, { title: 'Action', key: 'Action', dataIndex: 'Action', render: (_, record, index) => handlePendingOrderDelete(record)} /> }, ] const handlePendingOrdersQtyOnChange = (value, object, index) => { const { ProdId } = object; setOrderTableData(prev => prev.map(item => { if (item.ProdId === ProdId) { return { ...item, OrderQty: value, TotalAmount: value * item.ProductRate, GrossTotal: value * item.ProductRate } } return item })) } const handlePendingOrderDelete = (object) => { const { ProdId } = object; setOrderTableData(prev => prev.filter(item => item.ProdId !== ProdId)) } const edit = (record, index) => { form.setFieldsValue({ ...record }); setEditingKey(index); form.setFieldsValue({ [`Qty${index}`]: record?.Qty }); }; 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, GrossTotal: Amount + taxamt, ProductRate: item.Price, }; } return item; }); setTableData(newData); form.setFieldsValue({ ...form.getFieldsValue(), [`Qty${index}`]: qty }); }; const PrintQuotation = async () => { if (segmentValue === "N") { if (TableData.some((item) => !item.Qty || parseFloat(item.Qty) < 1)) { setMessageType('error'); setMessageData('Every product must have a quantity of at least 1.'); return; } } else { if (orderTableData.some((item) => !item.OrderQty || parseFloat(item.OrderQty) < 1)) { setMessageType('error'); setMessageData('Every product must have a quantity of at least 1.'); return; } } setIsSubmitted(true); const total = orderTableData?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TotalAmount; }, 0); const totalgst = (orderTableData?.filter( (item) => item.TaxName?.toLowerCase() === 'cgst,sgst' )?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TaxAmt; }, 0) || 0) / 2; const totaligst = orderTableData?.filter( (item) => item.TaxName?.toLowerCase() === 'igst' )?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TaxAmt; }, 0); const totalAmount = orderTableData?.reduce((accumulator, currentValue) => { return accumulator + currentValue.TotalAmount; }, 0); const Type = segmentValue === "N" ? AllCustomer?.find(item => item.CustId === SelecAdminUser)?.Type : ordersCustomer?.find(item => item.SuppId === selectedOrder)?.LocationType; let data1 = transportFormRef.current?.getFieldsValue(); let data = { AppId: AppId, CompId: CompId, BranchId: BranchId, CustId: segmentValue === "N" ? SelecAdminUser : selectedOrder, TotalAmount: segmentValue === "N" ? TotalBillAmount : totalAmount, TaxAmount: segmentValue === "N" ? (TotalCgst + TotalSgst + TotalIgst || 0) : (totalgst + totalgst + totaligst || 0), GrandTotal: segmentValue === "N" ? TotalAmount : total, VehicleNo: data1?.vehicleNo ? data1?.vehicleNo : null, Remarks: '', Type, ModeOfTransport: selectedMode, TransporterId: data1?.transporter ? data1?.transporter : null, TransporterName: data1?.transporterName ? data1?.transporterName : null, ProductDetails: (segmentValue === "N" ? TableData : orderTableData)?.map((item) => { return { ProdId: item?.ProdId, InwardDtlId: item?.InwardDtlId, SinglePc: item?.SinglePc, Qty: segmentValue === "N" ? item?.Qty : item?.OrderQty, ProductRate: item?.ProductRate, TotalAmount: item?.TotalAmount, TaxAmount: item?.TaxAmt, TaxId: item?.TaxId, GrossTotal: item?.TotalAmount, }; }), CreatedBy: UserId, }; let response = await dispatch(PostChallan(data)).unwrap(); if (response?.data?.statusCode == 1) { setMessageType('success'); setMessageData(response?.data?.response); transportFormRef?.current?.resetFields(); formRef?.current?.resetFields(); setSelecAdminUser(); setSelTaxType(); setSelProduct(); setSelTaxTypeName(); setTotalBillAmount(); setTableData([]); setTotalCgst(); setTotalSgst(); setTotalIgst(); fetchdata() 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]); setSelectedProductName(null) setVariants([]) setOrderTableData([]) formRef?.current?.setFieldsValue({ Order: undefined, CustId: undefined, ProdId: undefined, }) } // 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 () => { setIsSubmitted(false); 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(() => { if (isMobile) { DCPDFMobilePrint({ PrintTempData: DCPrintTemplateDtl, UserId: UserId, dispatch }) } else { printDiv(`${selectedStyle}`, DCstyle); } }, 100); }; 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) { setEmailSending(true); setTimeout(async () => { try { const blob = await pdfDiv('DC-Default-Print', PurchaseOrderStyle); const payload = { fileBlob: blob, toEmail: orderData?.CustMail, type: 'DeliveryChallan', 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'); } finally { setEmailSending(false); } }, 300); } else { setPendingOrderDetails(ProductDetails); setPendingRecord(record); setiSEmail(true); setIsSubmitted(false); } }; 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); }; const handleOnChangeSegment = (params) => { setSegmentValue(params) setSelectedProductName(null) setVariants([]) setTableData([]) setOrderTableData([]) formRef?.current?.setFieldsValue({ Order: undefined, CustId: undefined, ProdId: undefined, }) } return (
navigate(`${subDirectory}setting/delivery-challan/list`)} > View Challans
{segmentValue === "N" ?
({ value: option.CustId, label: (option.CustShortName || option.CustName || option.CustMobile) + `(${option.Type})`, }))} label={} className="field-DropDown" onChangeFunction={handleAdminUserDropDownChange} /> {/* */} { setSelectedCustomertype(e.target.checked ? 'Y' : 'N'); }} > {selectedCustomertype === 'Y' ? 'All Branch' : 'My Branch'} {/* */}
:
({ label: option.SuppName + (option.SuppMobile === null ? "" : ` - ${option.SuppMobile}`) + (option.LocationType === null ? "" : ` (${option.LocationType})`) + " " + option.PurOrderId.split("-").slice(4).join("-"), value: option.SuppId + "||" + option.PurOrderId }))} label={} className="field-DropDown" onChangeFunction={handleOrderChange} />
}
{ 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(); } }} >
{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 } ) } maxLength={10} /> {/* 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); }} />
} />
{segmentValue === "N" ?
({ onClick: () => { edit(record, index); }, })} pagination={false} /> :
}
} htmlType={true} /> {isSubmitted && ( <>
)}
{/* setiSEmail(false)} footer={false} children={
} /> */} {(iSEmail || emailSending) && ( setiSEmail(false)} form={form} handleSendEmailWithEnteredEmail={handleSendEmailWithEnteredEmail} />)} {PrintingData?.length > 0 &&
} ); }; export default DeliveryChellanForm;