import { useCallback, useEffect, useRef, useState } from "react" import { Messages } from "../../Components/Notifications/Messages" import FormHeader from "../PageComponents/FormHeader"; import { useLocation, useNavigate } from "react-router-dom"; import { Button, Checkbox, Form, Input, Tooltip } from "antd"; import { ArrowRightOutlined } from '@ant-design/icons'; import { useDispatch } from "react-redux"; import { changeBreadCrumb } from "../../Features/AppPage/CenterPage"; import { DropDowns } from "../../Components/Forms/DropDown"; import { ExtractDateFormate, getSession, pdfDiv } from "../../Services/Others"; import { getNonConvertedDeliveryChallans, postDeliveryToInvoice } from '../../Features/DeliveryChallan/DeliveryChallan.js'; import { Tables } from "../../Components/Tables/Table.jsx"; import Buttons from "../../Components/Forms/Buttons.jsx"; import { getPaymentOptionsData } from "../../Features/Payment/Paymentoptions/Paymentoptions.js"; import { RadioGrpButton } from "../../Components/Forms/RadioGroup.jsx"; import { FaEye, FaPrint } from "react-icons/fa"; import { DefaultModal } from "../../Components/Modal/DefaultModal.jsx"; import { MdOutlineMail } from "react-icons/md"; import { printDiv } from "../../Services/WSOthers.js"; import DeliveryChallanToInvoicePrint from "./DeliveryChallanToInvoicePrint.jsx"; import { Emailsend } from "../../Features/PurchaseOrder/PurchaseOrder.js"; import './DeliveryChallanToInvoice.scss' import { getPrintSelectionComponentData, GlobalprintDatas } from "../../Features/ThemeChange/ThemeChange.js"; import { useSelector } from "react-redux"; import { settingDataSelector } from "../../Features/PreferenceMaster/PreferenceMaster.js"; import { printDCToInvoiceStyles } from "./PrintTemplates/printDCToInvoiceStyles.js"; import { getBranchDetail } from "../../Features/BrachLogin/BranchLogin.js"; import { PreferenceData } from "../../Features/BookingScreen/BookingData/BookingData.js"; import EmailModel from "../BookingScreen/Components/UtillComponents/EmailModel.jsx"; const subDirectory = import.meta.env.BASE_URL; const DeliveryChallanToInvoiceForm = () => { const [form] = Form.useForm(); const formRef = useRef(null); const location = useLocation(); const navigate = useNavigate(); const dispatch = useDispatch(); const state = location?.state; const editstate = state?.editstate; const SettingDataSelector = useSelector(PreferenceData); const printDatas = useSelector(GlobalprintDatas); const AppId = getSession("AppId"); const BranchId = getSession("BranchId"); const CompId = getSession("CompId"); const UserId = getSession("UserId"); const [page, setPage] = useState(1); const [messageType, setMessageType] = useState(null); const [messageData, setMessageData] = useState(null); const [deliveryChallanData, setDeliveryChallanData] = useState([]) const [selectedDeliveryChallan, setSelectedDeliveryChallan] = useState(null); const [selectedDeliveryChallanData, setSelectedDeliveryChallanData] = useState(); const [paymentOptions, setPaymentOptions] = useState([]); const [selectedPayment, setSelectedPayment] = useState(null); const [emailModal, setEmailModal] = useState(false); const [printingData, setPrintingData] = useState([]); const [showShare, setShowShare] = useState(false); const [defaultPrintStyle, setDefaultPrintStyle] = useState(null); const [printTrue, setPrintTrue] = useState(false); const [emailSending, setEmailSending] = useState(false); console.log(paymentOptions, "paymentOptions") const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, { name: 'Delivery Challan to Invoice', link: `${subDirectory}setting/delivery-challan-to-invoice/list`, }, ]; const columns = [ { title: 'Sl.No', key: 'sno', align: 'center', render: (text, object, index) => ( {(page - 1) * 10 + index + 1} ), }, { title: 'Product Name', key: 'ProdName', dataIndex: 'ProdName', width: '150px', }, { title: 'Product Variant Name', key: 'ProdVariantName', dataIndex: 'ProdVariantName', width: '200px', }, { title: 'Qty', key: 'Qty', dataIndex: 'Qty', align: 'center', width: '80px', }, { title: 'Product Rate', key: 'ProductRate', dataIndex: 'ProductRate', align: 'center' }, { title: 'Convert To Invoice', key: 'ConvertToInvoice', align: 'center', render: (text, record, index) => ( handleCheckboxChange(e.target.checked, ((page - 1) * 10) + index)} /> ), }, ]; useEffect(() => { dispatch(changeBreadCrumb({ items: items })); getDeliveryChallanData(); getPaymentOptions(); getDefaultPrintStyle(); }, []) const onComplete = useCallback(() => { setMessageData(null); setMessageType(null); }, []); const getDefaultPrintStyle = async () => { const { data: res } = await dispatch(getPrintSelectionComponentData({ AppId, CompId, BranchId }))?.unwrap(); const styleName = res?.data[0]?.ComponentDetails?.find((component) => component?.PrintTypeName === "DC to Invoice" && component?.SetasDefault === 'Y')?.StyleName; setDefaultPrintStyle(styleName) } const getPrintStyle = () => { const style = printDCToInvoiceStyles((defaultPrintStyle === undefined || defaultPrintStyle === null) ? 'Style 13' : defaultPrintStyle); return style; } const getPaymentOptions = async () => { const { data: res } = await dispatch(getPaymentOptionsData({ AppId, CompId, BranchId }))?.unwrap(); const paymentData = res?.data[0]; const filterSalesPayment = paymentData?.PaymentDetails?.filter( (item) => item.FlowName?.toLowerCase() === 'sales' ); const filterpaycounter = filterSalesPayment?.[0]?.OptionDetails?.filter( (item) => item?.OptionName?.toLowerCase() === 'pay at the counter' ); setPaymentOptions(filterpaycounter?.[0]?.ModeDetails); const selectedPaymentOption = filterpaycounter?.[0]?.ModeDetails?.find((payment) => payment?.ModeName === "Cash")?.ModeId setSelectedPayment(selectedPaymentOption); formRef?.current?.setFieldValue('PaymentOption', selectedPaymentOption); } const getDeliveryChallanData = async () => { const { data: response } = await dispatch(getNonConvertedDeliveryChallans({ AppId, CompId, BranchId })).unwrap(); setDeliveryChallanData(response?.data) } const handleDeliveryChallanChange = (value) => { formRef?.current?.setFieldValue('DeliveryChallanNo', value); setSelectedDeliveryChallan(value) if (value !== null && value !== undefined) { const data = deliveryChallanData?.find((data) => data?.DCNo === value); setSelectedDeliveryChallanData(JSON.parse(JSON.stringify(data))) } else { setSelectedDeliveryChallanData() } } const handlePageChange = (current) => { setPage(current); }; const handleCheckboxChange = (checked, rowIndex) => { const updatedData = { ...selectedDeliveryChallanData }; updatedData.ProductDetails[rowIndex].ConvertToInvoice = checked; setSelectedDeliveryChallanData({ ...updatedData }); }; const handleChange = (pagination, filters, sorter) => { setFilteredInfo(filters); setSortedInfo(sorter); }; const handlePrint = async () => { setPrintTrue(true); const style = getPrintStyle(); setTimeout(() => { printDiv(`delivery-challan-to-invoice-print`, style); setPrintTrue(false); }, 100); } const handleEmailShare = async (record) => { console.log("record", printingData) // alert("This feature is not available yet. Please contact support for assistance.") if (record?.CustEmail) { setEmailSending(true) setPrintTrue(true); setTimeout(async () => { try { const style = getPrintStyle(); const blob = await pdfDiv('delivery-challan-to-invoice-print', style); console.log(blob, 'blobblob'); const payload = { fileBlob: blob, toEmail: record?.CustEmail, type: 'DeliveryChallantoInvoice', 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 { setPrintTrue(false); setEmailSending(false) } }, 300); } else { setEmailModal(true); } }; const handleSendEmailWithEnteredEmail = async (values) => { const record = { ...printingData[0], CustEmail: values.email }; await handleEmailShare(record); setEmailModal(false); form.resetFields(); }; const onFinish = async (values) => { const productDtls = selectedDeliveryChallanData?.ProductDetails?.filter((data) => data?.ConvertToInvoice === true)?.map((product) => ({ ProdId: product?.ProdId, InwardDtlId: product?.InwardDtlId, Qty: product?.Qty, ProductRate: product?.ProductRate, TotalAmount: product?.TotalAmount, TaxAmount: product?.TaxAmount, TaxId: product?.TaxId, GrossTotal: product?.GrossTotal, DCDtlId: product?.DCDtlId })); if (productDtls?.length < 1) { setMessageType('error') setMessageData('No Product Selected') return } const totalAmountOfProduct = productDtls?.reduce((acc, product) => (acc + product?.TotalAmount), 0); const totalTaxAmount = productDtls?.reduce((acc, product) => (acc + product?.TaxAmount), 0); const totalGrossTotal = productDtls?.reduce((acc, product) => (acc + product?.GrossTotal), 0); const postData = { AppId: selectedDeliveryChallanData?.AppId, CompId: selectedDeliveryChallanData?.CompId, BranchId: selectedDeliveryChallanData?.BranchId, DCNo: selectedDeliveryChallanData?.DCNo, CustId: selectedDeliveryChallanData?.CustId, CustMobile: selectedDeliveryChallanData?.CustMobile, TotalAmount: totalAmountOfProduct, TaxAmount: totalTaxAmount, GrandTotal: totalGrossTotal, VehicleNo: selectedDeliveryChallanData?.VehicleNo, PaymentMode: selectedPayment, CreatedBy: UserId, ProductDetails: productDtls } const { data: res } = await dispatch(postDeliveryToInvoice(postData))?.unwrap(); const { data: branchData } = await dispatch(getBranchDetail({ BrId: BranchId }))?.unwrap(); res.InvoiceDetails[0].AddressDetails = branchData?.data; if (res?.statusCode === 1) { setPrintingData(res?.InvoiceDetails) setShowShare(true) setMessageType('success') setMessageData(res?.response); await getDeliveryChallanData(); } else { setMessageType('error') setMessageData(res?.response); } setSelectedDeliveryChallanData(); setSelectedDeliveryChallan(null) formRef?.current?.setFieldValue('DeliveryChallanNo', null); console.log(res?.statusCode === 1, "valuesvalues") } return (
navigate(`${subDirectory}setting/delivery-challan-to-invoice/list`)} >

View DC to Invoice List

({ label: option?.DCNo, value: option?.DCNo }))} label={} onChangeFunction={handleDeliveryChallanChange} isOnChange={selectedDeliveryChallan} defaultValue={selectedDeliveryChallan} valueData={selectedDeliveryChallan} /> {selectedDeliveryChallanData && <>
Customer Mobile No:
{selectedDeliveryChallanData?.CustMobile}
{selectedDeliveryChallanData?.CustName &&
Customer Name:
{selectedDeliveryChallanData?.CustName}
}
Delivery Challan Date:
{ExtractDateFormate(selectedDeliveryChallanData?.DCDate)}
({ value: payment?.ModeId, label: payment?.ModeName }))} defaultSelect={selectedPayment} Header={} onSelectFuntion={(e) => { formRef?.current?.setFieldValue('PaymentOption', e); setSelectedPayment(e) }} /> } } /> {showShare && (
handleEmailShare(printingData[0])} />
)}
{(emailModal || emailSending) && ( setEmailModal(false)} form={form} handleSendEmailWithEnteredEmail={handleSendEmailWithEnteredEmail} />)} {(printingData?.length > 0 && printTrue) &&
}
) } export default DeliveryChallanToInvoiceForm