import React, { useCallback, useEffect, useRef, useState } from 'react'; import { AiFillPrinter, AiOutlineCheckSquare } from 'react-icons/ai'; import { useDispatch, useSelector } from 'react-redux'; import { DefaultModal } from '../../../../../Components/Modal/DefaultModal'; import { Button, Checkbox, Input, Modal, Pagination, Switch, Tooltip, } from 'antd'; import { getSession, printDiv, extractLastNumberOrderId, ExtractDateFormate, dateTimeFormatChange, } from '../../../../../Services/Others'; import { Tables } from '../../../../../Components/Tables/Table'; import { getRePrintDefault, postDefaultReprintReason, postRePrintReason, ReprintDetails, } from '../../../../../Features/BookingScreen/Customer/addCustomer'; import { GlobalprintDatas, SelectedPrintTemplate, GlobalPrinterMappingDtls, getPrinterMappingDetails, getPrintSelectionComponentData, } from '../../../../../Features/ThemeChange/ThemeChange'; import FormHeader from '../../../../../Pages/PageComponents/FormHeader'; import { ArrowRightOutlined } from '@ant-design/icons'; import { PrintStyleFunction } from '../../../../paymentpdfPage/PrintStyleFunction.js'; import moment from 'moment'; import { isMobile } from 'react-device-detect'; import MobilePrint from '../../BookingFunctionality/MobilePrint.jsx'; import '../../../../../Styles/BookingScreen/Components/OtherConponents/Reprint/BSReprint.scss'; import PaymentPdfBooking from '../../../../paymentpdfPage/PaymentPdfBooking.jsx'; import { changeBillEditingMode, changeEstimateBooking, changeHoldOrderDtl, changeOrderCardDetails, changeOrderType, ChangeOverAllDiscEstimate, ChangeOverAllDiscSales, changePreviousOrderOfferDetail, changePreviousOrderPayment, changeReorderHoldDetails, changeReorderProductDetails, ChangeSelectedCustDisable, changeSelectedCustId, changeSelectedOption, changeSelProdWiseEst, getAllCustomer, getConfigType, getCustomerForHold, GlobalSalesBillEdit, GlobalSelectedCustDisable, PreferenceData, } from '../../../../../Features/BookingScreen/BookingData/BookingData.js'; import { DatePicker, Form } from 'antd'; import { DropDowns } from '../../../../../Components/Forms/DropDown.jsx'; import TextAreaInput from '../../../../../Components/Forms/TextArea.jsx'; import Buttons from '../../../../../Components/Forms/Buttons.jsx'; import { Messages } from '../../../../../Components/Notifications/Messages.jsx'; import { ApplicationPreferences } from '../../../../../Features/BrachLogin/BranchLogin.js'; import { IoEye } from 'react-icons/io5'; const { RangePicker } = DatePicker; import { MobilePdfPrint } from '../../BookingFunctionality/MobilePdfPrint.js'; import { FaDownload } from 'react-icons/fa'; import { MdEmail } from 'react-icons/md'; import { FaWhatsapp } from 'react-icons/fa'; import { MobileMultiPdfPrint, PdfProcessingProgress, } from '../../BookingFunctionality/MobileMultiPdfPrint.jsx'; import { TbSettingsCog } from 'react-icons/tb'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { axiosRetailInstanceData } from '../../../../../Features/AuthenicationToken/AuthenticationToken.js'; import { MdEdit } from "react-icons/md"; import { v4 as uuidv4 } from 'uuid'; import { changeOrderOfferDetail } from '../../../../../Features/Offer/Offer.js'; import { ChangeFullFreeProductList, changeFullOfferAppliedProducts, changeLoyaltyConsumedQuantities } from '../../../../../Features/Offer/Offernew/BookingOffernew.js'; import { ChangeTotalAmount } from '../../../../../Features/ExteraCharges/ExtraCharges.js'; const RetailApiurl = import.meta.env.ENV_API_URL; function BSReprint({ setOpenModel = () => { } }) { const dispatch = useDispatch(); const queryClient = useQueryClient(); const appPreferences = useSelector(ApplicationPreferences); const bookingTypePreference = appPreferences?.find( (preference) => preference?.PreferredCatName === 'Booking Type' )?.PreferenceCatDetails; const printerTemplateStyle = useSelector(SelectedPrintTemplate); const [message, setMessage] = useState({ type: null, data: null }); const reprintReasonRef = useRef(); const [reprint, setReprint] = useState(false); const [reprintDetaile, setReprintDetaile] = useState(); const [table2Data, settable2Data] = useState([]); const [reprintReasonModel, setReprintReasonModel] = useState({ modal: false, action: 'without', default: true, }); const [SearchText, setSearchText] = useState(null); const [selectedRows, setSelectedRows] = useState([]); const [selectAll, setSelectAll] = useState(false); const [bulkMode, setBulkMode] = useState(false); const [loading, setLoading] = useState(false); const [reprintData, setReprintData] = useState([]); console.log(reprintData, 'reprintData'); const [reprintReasonList, setReprintReasonList] = useState([]); const [isDuplicate, setIsDuplicate] = useState('Original'); const [BillSearch, setBillSearch] = useState(''); const [EmailId, setEmailId] = useState(''); const [emailModalOpen, setEmailModalOpen] = useState(false); const [page, setpage] = useState(1); const [itemsPerPage] = useState(10); const [DefReason, setDefReason] = useState({}); const SettingDataSelector = useSelector(PreferenceData); const salesBillEdit = useSelector(GlobalSalesBillEdit); const custDisable = useSelector(GlobalSelectedCustDisable); console.log(SettingDataSelector, 'SettingDataSelector'); const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find( (setting) => setting?.SettingIdName?.toLowerCase() === 'mobilea4' && setting?.SettingValue === 'Y' ); const editBill = SettingDataSelector?.[0]?.SettingDtlDetails?.find( (setting) => setting?.SettingIdName?.toLowerCase() === 'editbill' && setting?.SettingValue === 'Y' ); const TokenOnly = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName === 'TokenOnly' )?.[0]; const IndividualToken = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName === 'AllProductindividualToken' )?.[0]; const Weightasquantity = SettingDataSelector?.[0]?.SettingDtlDetails?.some( (setting) => setting?.SettingIdName?.toLowerCase() === 'weightasquantity' && setting?.SettingValue === 'Y' ); const printDatas = useSelector(GlobalprintDatas); console.log(printDatas, 'GlobalprintDatas'); const PrinterDetails = useSelector(GlobalPrinterMappingDtls); const CompId = getSession('CompId'); const BranchId = getSession('BranchId'); const AppId = getSession('AppId'); const UserId = getSession('UserId'); const UserType = getSession('UserType'); const AuthToken = sessionStorage.getItem('auth'); const SessionMobileNo = getSession('MobileNo'); const [dateStrings, setDateStrings] = useState([]); // ---- 1. Fetch Function ---- const fetchData = async ({ queryKey }) => { const [_, dates, page] = queryKey; const Response = await dispatch( ReprintDetails({ CompId, BranchId, AppId, OrderFromDate: dates?.[0] ?? '', OrderToDate: dates?.[1] ?? '', PageNumber: page, }) ).unwrap(); if (Response?.data?.statusCode === 1) { return Response?.data?.data; } else { return []; } }; const { data, isLoading, error } = useQuery({ queryKey: ['reprint', dateStrings, page], queryFn: fetchData, enabled: true, staleTime: 1000 * 60 * 5, cacheTime: 1000 * 60 * 30, keepPreviousData: true, refetchOnMount: 'always', refetchOnWindowFocus: true, refetchOnReconnect: true, }); const { data: countData } = useQuery({ queryKey: ['searchReprint', SearchText], queryFn: searchData, enabled: !!SearchText, staleTime: 1000 * 60 * 5, cacheTime: 1000 * 60 * 30, keepPreviousData: true, refetchOnMount: 'always', refetchOnWindowFocus: true, refetchOnReconnect: true, }); async function searchData({ queryKey }) { const [_, SearchText] = queryKey; const res = await axiosRetailInstanceData.get( `/rePrint?compId=${CompId}&appId=${AppId}&branchId=${BranchId}&type=B&orderId=${SearchText}` ); if (res?.data?.statusCode == 1) { setpage(1); return res?.data?.data; } else { return []; } } const countOfProduct = SearchText ? countData?.length ? countData?.length : 0 : data?.[0]?.TotalCount; console.log(countOfProduct, 'countOfProduct'); useEffect(() => { const commonMasterApiCall = async () => { try { // queryClient.invalidateQueries(['reprint']); const response = await dispatch( getConfigType({ TypeName: 'Reprint Reason' }) ).unwrap(); if (response.data.statusCode === 1) { setReprintReasonList(response?.data?.data); } else { setMessage({ type: 'error', data: response?.data?.response }); } } catch (error) { setMessage({ type: 'error', data: error.message }); } }; commonMasterApiCall(); DefaultReprintReason(); }, []); useEffect(() => { let data = { CompId: CompId, BranchId: BranchId, AppId: AppId, // UserId: UserId, }; dispatch(getPrinterMappingDetails(data)).unwrap(); const Data1 = { AppId, CompId, BranchId }; dispatch(getPrintSelectionComponentData(Data1)).unwrap(); }, []); const handleDateChange = (dates, dateStrings) => { // setDateRange(dateStrings); if (dateStrings[0] && dateStrings[1]) { setDateStrings(dateStrings); setpage(1); } }; const DefaultReprintReason = async () => { let data = { AppId: AppId, CompId: CompId, BranchId: BranchId, Status: 'Y', }; let defaultget = await dispatch(getRePrintDefault(data)).unwrap(); if (defaultget.data.statusCode === 1) { let apiData = defaultget?.data?.data?.[0]; setDefReason(apiData); } else { setDefReason({}); reprintReasonRef?.current?.resetFields(); setIsDuplicate('Original'); } }; const reprintReasonDropDownChange = (event) => { reprintReasonRef?.current?.setFieldsValue({ Reason: event }); }; const HandleReprint = async (reprintData, type) => { console.log(type, reprintReasonModel, 'type-reprintReasonModel'); const PrintLogo = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName?.toLowerCase() === 'printlogo' )?.[0]; const PrintGreeting = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName?.toLowerCase() === 'printgreetings' )?.[0]; const EstimateHeader = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName?.toLowerCase() === 'estimateprintheader' )?.[0]; const SalesMode = SettingDataSelector?.[0]?.SettingDtlDetails?.filter( (i) => i.SettingIdName?.toLowerCase() === 'sales mode' )?.[0]; const WithorWithoutToken = type == 'with' ? true : false; if (isMobile) { if (MobileA4Print) { const Tokenthere = TokenOnly?.SettingValue === 'Y'; const Individual = IndividualToken?.SettingValue === 'Y'; const PrintGrettingthere = PrintGreeting?.SettingValue === 'Y'; const Printlogothere = PrintLogo?.SettingValue === 'Y'; const EstimateHeaderthere = EstimateHeader?.SettingValue === 'Y'; const SalesModethere = SalesMode?.SettingValue === 'Y'; const takeAwayPreference = bookingTypePreference?.some( (type) => type?.PreferredSubCatName?.toLowerCase() === 'take away' && type?.PreferredStatus === 'Y' ); const orderidlist = reprintData?.map((item) => ({ OrderId: item.OrderId, })); const filesJson = JSON.stringify(PrinterDetails); const Stylename = printDatas?.StyleName; const PrintSize = printDatas?.PageSize ? printDatas?.PageSize : '3inch'; const isCreditDetailsAvailable = printDatas?.FieldDetails?.some( (item) => String(item?.ConfigName || '').toLowerCase() === 'credit details' ); console.log(printDatas, printDatas?.StyleName, 'printDatas'); var receiptText = ''; var textEncoded = encodeURI(receiptText); var scheme = 'pozoprinter'; var packageName = 'com.example.pozoprinter'; window.location.href = scheme + '://' + textEncoded + '#Intent;scheme=' + scheme + ';package=' + packageName + 'AppIdS' + AppId + 'AppIdE' + 'CompIdS' + CompId + 'CompIdE' + 'BranchIdS' + BranchId + 'BranchIdE' + 'UserIdS' + UserId + 'UserIdE' + 'ApiClientS' + RetailApiurl + 'ApiClientE' + 'InvoiceOrderIdS' + JSON.stringify(orderidlist) + 'InvoiceOrderIdE' + 'MobileNoS' + SessionMobileNo + 'MobileNoE' + 'AuthTokenS' + AuthToken + 'AuthTokenE' + 'PrintSizeS' + PrintSize + 'PrintSizeE' + 'PrintTypeS' + Stylename + 'PrintTypeE' + 'TokenOnlyS' + Tokenthere + 'TokenOnlyE' + 'AllProductindividualTokenS' + Individual + 'AllProductindividualTokenE' + 'PrintGreetingsS' + PrintGrettingthere + 'PrintGreetingsE' + 'PrintLogoS' + Printlogothere + 'PrintLogoE' + 'ReprintS' + true + 'ReprintE' + 'WithTokenS' + WithorWithoutToken + 'WithTokenE' + 'ReprintTextS' + isDuplicate + 'ReprintTextE' + 'CustomerCreditPrintS' + isCreditDetailsAvailable + 'CustomerCreditPrintE' + 'EstimatePrintHeaderS' + EstimateHeaderthere + 'EstimatePrintHeaderE' + 'SalesModeS' + SalesModethere + 'SalesModeE' + 'TakeAwayPreferenceS' + takeAwayPreference + 'TakeAwayPreferenceE' + 'IpS' + filesJson + 'IpE' + 'ConfigurationS' + true + 'ConfigurationE' + ';end;'; // var receiptText = ''; // var textEncoded = encodeURI(receiptText); // var scheme = 'pozoprinter'; // var packageName = 'com.example.pozoprinter'; // window.location.href = // scheme + // '://' + // textEncoded + // '#Intent;scheme=' + // scheme + // ';package=' + // packageName + // 'AppIdS' + // AppId + // 'AppIdE' + // 'CompIdS' + // CompId + // 'CompIdE' + // 'BranchIdS' + // BranchId + // 'BranchIdE' + // 'UserIdS' + // UserId + // 'UserIdE' + // 'ApiClientS' + // RetailApiurl + // 'ApiClientE' + // 'InvoiceOrderIdS' + // reprintData?.[0]?.OrderId + // 'InvoiceOrderIdE' + // 'MobileNoS' + // SessionMobileNo + // 'MobileNoE' + // 'AuthTokenS' + // AuthToken + // 'AuthTokenE' + // 'PrintTypeS' + // printDatas?.PageSize + // 'PrintTypeE' // ';end;'; // // MobilePdfPrint() // await MobilePdfPrint({ // printerTemplateStyle, // printDatas, // PrintOrderDetails: reprintData, // map table2Data → PrintOrderDetails // PrintComing: 'Reprint' // }); } else { MobilePrint( appPreferences, reprintData, '', 'Reprint', SettingDataSelector, type ? type : reprintReasonModel.action === 'with' ? 'WithToken' : 'WithOutToken' ); } } else { Print(reprintData, type ? type : reprintReasonModel.action); } reprintReasonRef?.current?.resetFields(); setReprintReasonModel({ modal: false, action: 'without', default: true }); }; const handleReprintReasonSubmission = async (printdata, type) => { console.log( reprintReasonRef?.current?.getFieldsValue(), 'reprintReasonRef?.current?.getFieldsValue(),' ); if (reprintReasonModel.action === 'NoPrint') { const checked = reprintReasonRef?.current?.getFieldValue('SetAsDefault'); const payload = { ...reprintReasonRef?.current?.getFieldsValue(), SetAsDefault: checked ? 'Y' : 'N', }; const postData = { UserId, CompId, BranchId, AppId, CreatedBy: UserId, SetAsDefault: payload?.SetAsDefault, DefaultType: 'Reprint', DefaultDetails: [ { Description: payload?.Description, Reason: payload?.Reason, ReprintType: isDuplicate, }, ], }; const response = await dispatch( postDefaultReprintReason(postData) ).unwrap(); if (response.data.statusCode === 1) { setReprintReasonModel({ modal: false, action: 'without', default: true, }); DefaultReprintReason(); } console.log(postData, 'postDataNoPrint'); } else { let postData; if (Object.keys(DefReason)?.length > 0) { postData = { UserId, CompId, BranchId, AppId, BookingId: printdata?.[0]?.SalesId, CreatedBy: UserId, OrderId: printdata?.[0]?.OrderId, Reason: DefReason?.DefaultDetails?.[0]?.Reason, Description: DefReason?.DefaultDetails?.[0]?.Description || '', }; } else { postData = { UserId, CompId, BranchId, AppId, BookingId: reprintData?.[0]?.SalesId, CreatedBy: UserId, OrderId: reprintData?.[0]?.OrderId, Reason: reprintReasonRef?.current?.getFieldsValue()?.Reason, Description: reprintReasonRef?.current?.getFieldsValue()?.Description, }; } console.log( postData, reprintReasonModel, DefReason, printdata, 'postDatapostData' ); try { const response = await dispatch(postRePrintReason(postData)).unwrap(); if (response.data.statusCode === 1) { let data = Object.keys(DefReason)?.length > 0 ? printdata : reprintData; HandleReprint(data, type); // setReprintData([]); } else { setMessage({ type: 'error', data: response?.data?.response }); } } catch (error) { setMessage({ type: 'error', data: error.message }); } } }; const Print = async (reprintData, data) => { console.log(reprintData, 'reprintDatareprintData'); const style = await PrintStyleFunction( printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle, 'Reprint' ); const stylesMap = { 'Style 1': 'PrintStyle1', 'Style 2': 'PrintStyle2', 'Style 3': 'PrintStyle3', 'Style 4': 'PrintStyle4', 'Style 5': 'PrintStyle5', 'Style 6': 'PrintStyle6', 'Style 7': 'PrintStyle7', 'Style 8': 'PrintStyle8', 'Style 9': 'PrintStyle9', 'Style 10': 'PrintStyle10', 'Style 11': 'PrintStyle11', 'Style 12': 'PrintStyle12', 'Style 13': 'RePrint', A4: 'PrintStyleA4', A5: 'PrintStyleA5', A4Standard: 'A4Standard', TaxInvoice: 'TaxInvoice', }; const selectedStyle = stylesMap[ printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle ]; if (selectedStyle) { if (data === 'without') { await Promise.all( reprintData?.map(async (orderDetail, index) => { await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print }) ); } else { await Promise.all( reprintData?.map(async (orderDetail, index) => { await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print if (orderDetail?.BookingTypeName !== 'Dine In') { const groupedTokens = orderDetail?.productDetails?.reduce( (acc, item, idx) => { if (item.TokenAvailable === 'Y') { if (!item.CounterName) { // If CounterName is null or empty acc[`individual-${idx}-${item.ProdId}`] = [item]; // Unique entry for each null/empty CounterName item } else { if (!acc[item.CounterName]) { acc[item.CounterName] = []; } acc[item.CounterName].push(item); // Group by CounterName } } return acc; }, {} ); // Iterate over grouped tokens and print them const tokensToPrint = Object.entries(groupedTokens).map( async ([counterName, items], idx) => { // Use the counterName (or unique identifier for individual items) as part of the tokenId const tokenId = `${idx}-${items?.[0]?.ProdId}-${counterName}`; await TokenPrint(tokenId, items); // Pass all grouped items to the print function } ); if (tokensToPrint?.length > 0) { await Promise.all(tokensToPrint); } } }) ); } // setReprintData([]); } ReprintCancel(); }; const TokenPrint = async (index) => { try { console.log(`Starting token print for index ${index}`); const stylePrint = ``; await printDiv(`TakeawayToken${index}`, stylePrint); } catch (error) { console.error(`Error printing token for index ${index}:`, error); } }; const ReprintCancel = () => { setReprint(false); }; const dataSource = data; const filteredData = SearchText ? countData?.length ? countData : [] : dataSource; const handlePageChange = (current) => { setpage(current); }; function safeRound(amountStr) { if (amountStr == null) return '0.00'; const cleaned = String(amountStr).replace(/[^0-9.-]+/g, ''); const num = Number(cleaned); return isNaN(num) ? '0.00' : num.toFixed(2); // return as string with 2 decimals } const Reprintformdata = () => { if (Object.keys(DefReason)?.length > 0) { reprintReasonRef?.current?.setFieldsValue({ ReprintType: DefReason?.DefaultDetails?.[0]?.ReprintType || 'Original', Reason: DefReason?.DefaultDetails?.[0]?.Reason, // must match your DropDown option value (ConfigId) Description: DefReason?.DefaultDetails?.[0]?.Description, SetAsDefault: DefReason?.SetAsDefault === 'Y', // convert "Y"/"N" to boolean }); setIsDuplicate(DefReason?.DefaultDetails?.[0]?.ReprintType || 'Original'); } }; const columns = [ { title: 'SL NO', dataIndex: 'SINO', key: 'SINO', align: 'center', width: '50px', render: (text, object, index) => ( {(page - 1) * 10 + index + 1} ), }, { title: 'Bill No', dataIndex: 'BillNo', key: 'BillNo', width: '75px', render: (text, row) => ( {row?.OrderPaymentDtl?.[0]?.OrderId?.split('-')?.pop()} ), }, { title: 'Order No', dataIndex: 'OrderNo', key: 'OrderNo', width: '75px', render: (text, row) => ( {row?.SalesId?.split('-')?.pop()} ), }, { title: 'Customer', dataIndex: 'CustSuppName', key: 'CustSuppName', width: '100px', render: (text, row) => ( {row?.CustSuppName || row?.CustomerDetails?.[0]?.MobileNo || '-'} ), }, // { // title: 'Item Name', // dataIndex: 'ItemName', // key: 'ItemName', // render: (text, row) => ( // // {row?.productDetails?.map( // (item, index) => // (index > 0 ? ',' : '') + // item.ProdName + // ' ' + // item.Size + // ' ' + // item.UomName // )} // // ), // }, { title: 'Date', dataIndex: 'Date', key: 'Date', width: '100px', align: 'right', render: (text, row) => ( {ExtractDateFormate(row.SalesDate)} ), }, { title: 'Products', dataIndex: 'productDetails', render: (text, row) => { const items = row?.productDetails || []; const visible = items .slice(0, 2) .map((item) => `${item.ProdName} ${item.Size} ${item.UomName}`); const hidden = items .slice(2) .map((item) => `${item.ProdName} ${item.Size} ${item.UomName}`); return ( <> {visible.join(', ')} {hidden.length > 0 && ( {' '} +{hidden.length} more )} ); }, }, { title: 'View', key: 'OrderDetails', dataIndex: 'OrderDetails', align: 'center', render: (text, row) => ( { settable2Data([row]); setReprintData([row]); setReprint(true); }} /> ), }, // ...(editBill ? [ { title: 'Edit Bill', key: 'EditBill', dataIndex: 'EditBill', align: 'center', render: (text, row) => ( await handleEditBill(e, row)} /> ), } // ] : []) , { title: () => (
PRINT RECEIPT {UserType !== 'Employee' && ( { setBulkMode(!bulkMode); setSelectedRows([]); // reset when toggling setReprintData([]); setSelectAll(false); }} /> )} {bulkMode && ( { const checked = e.target.checked; setSelectAll(checked); if (checked) { setSelectedRows(dataSource); // ✅ all rows selected setReprintData(dataSource); } else { setSelectedRows([]); setReprintData([]); } }} /> )}
), dataIndex: 'PRINTRECEIPT', key: 'PRINTRECEIPT', align: 'center', width: '100px', render: (text, row) => { if (bulkMode) { const isChecked = selectedRows.some((r) => r.SalesId === row.SalesId); return ( { if (e.target.checked) { setSelectedRows((prev) => [...prev, row]); // ✅ store full row object setReprintData((prev) => [...prev, row]); } else { setSelectedRows((prev) => prev.filter((r) => r.SalesId !== row.SalesId) ); setReprintData((prev) => prev.filter((r) => r.SalesId !== row.SalesId) ); setSelectAll(false); } }} /> ); } // 👇 normal behavior (your print buttons) return (
{/* ✅ Always visible icon */} {/* Conditional buttons/icons */} {row?.productDetails?.some( (item) => item.TokenAvailable === 'Y' ) ? (
) : ( { setReprintData([row]); if (Object.keys(DefReason)?.length > 0) { handleReprintReasonSubmission([row], 'without'); } else { setReprintReasonModel({ modal: true, action: 'without', default: false, }); } }} /> )}
); }, }, ]; const columns2 = [ { title: 'SI NO', dataIndex: 'SINO', key: 'SINO', align: 'center', render: (text, object, index) => ( {index + 1} ), }, { title: 'Item', dataIndex: 'ProdName', key: 'Item', }, { title: 'Qty', dataIndex: 'SalesQty', key: 'Qty', align: 'right', }, { title: 'Rate', dataIndex: 'Rate', key: 'Rate', align: 'right', render: (rate) => {safeRound(rate)}, }, { title: 'Price', dataIndex: 'TotalAmt', key: 'Price', align: 'right', render: (Price) => {safeRound(Price)}, }, ]; const handleToggle = (checked) => { setIsDuplicate(checked ? 'Duplicate' : 'Original'); console.log('Reprint type:', checked ? 'Duplicate' : 'Original'); }; console.log(reprintData, 'aaaaaaaaaaaaaaaaaaaa'); const handleDownload = async () => { await MobilePdfPrint({ printerTemplateStyle, printDatas, PrintOrderDetails: reprintData, // map table2Data → PrintOrderDetails PrintComing: 'download', }); }; const handleEmail = () => { setEmailModalOpen(true); }; const handleSendEmail = async () => { try { if (selectedRows.length === 0) { setLoading(true); const result = await MobilePdfPrint({ printerTemplateStyle, printDatas, PrintOrderDetails: reprintData, PrintComing: 'email', emailId: EmailId, dispatch, }); if (result?.data?.status === 1) { setEmailModalOpen(false); // ✅ Close modal setEmailId(''); // ✅ Reset email input (optional) setLoading(false); } } else { mutiplePrint('email'); } } catch (err) { console.error('❌ Email error:', err); } }; const handleWhatsApp = async () => { await MobilePdfPrint({ printerTemplateStyle, printDatas, PrintOrderDetails: reprintData, // map table2Data → PrintOrderDetails PrintComing: 'whatsapp', UserId: UserId, dispatch, }); }; const [processingProgress, setProcessingProgress] = useState(0); const [isProcessing, setIsProcessing] = useState(false); const mutiplePrint = async (printType) => { setIsProcessing(true); setProcessingProgress(0); const result = await MobileMultiPdfPrint({ printerTemplateStyle, printDatas, PrintOrderDetails: selectedRows, setPrintOrderDetails: setReprintData, PrintComing: printType, emailId: EmailId, UserId: UserId, dispatch, onProgress: (progress) => setProcessingProgress(progress), }); setIsProcessing(false); if (printType === 'email') { if (result?.data?.status === 1) { setEmailModalOpen(false); setEmailId(''); setSelectedRows([]); setSelectAll(false); setBulkMode(false); } else { setSelectedRows([]); setSelectAll(false); setBulkMode(false); } } else { setSelectedRows([]); setSelectAll(false); setBulkMode(false); } }; const onComplete = useCallback(() => { setMessage({ type: null, data: null }); }, []); function Debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn(...args); }, delay); }; } const searchOrderIDFn = (value) => { setSearchText(value); }; const debouncedSearch = useCallback(Debounce(searchOrderIDFn, 500), []); console.log(table2Data, 'table2Datadfnfjd'); const totalSalesQty = table2Data?.[0]?.productDetails?.reduce((acc, item) => { const isWeightScale = item?.ScaleType === 'weight'; if (isWeightScale) { return acc + ( Weightasquantity ? Math.round(Number(item?.SalesQty || item?.OrderQty || 0)) : 1 ); } return acc + Math.round(Number(item?.SalesQty || item?.OrderQty || 0)); }, 0) const widthOutTexAmt = table2Data?.[0]?.TaxDetails?.reduce( (sum, item) => sum + (item?.WithOutTaxAmount || 0), 0 ); const handleEditBill = async (e, orderDtls) => { setOpenModel(e); dispatch(changeBillEditingMode(true)); const { productDetails, ExtraChargeDetails, CustSuppId, OrderOfferDetails, RefDetails, OrderId, OrderType, OverallDisc, OrderPaymentDtl, } = orderDtls; const updated = productDetails?.map((item) => ({ ...item, Offer: item?.OfferAmt, localId: uuidv4(), OfferMode: item?.OfferMode ? item?.OfferMode?.trim() : null, VariantAvailableFrom: item?.AvailableFrom || null, VariantAvailableTo: item?.AvailableTo || null, OrderQty: item?.SalesQty, OrderRate: item?.Rate, SellingPrice: item?.Rate, // TotalAmt: formatAmount((item.TotalAmt - item.OfferValue)), })); if (RefDetails?.[0]?.FreeProdList) { dispatch(ChangeFullFreeProductList(RefDetails[0]?.FreeProdList)); } if (RefDetails?.[0]?.OfferAppliedProductList) { dispatch( changeFullOfferAppliedProducts( RefDetails[0]?.OfferAppliedProductList ) ); } if (CustSuppId) { let res = await dispatch( getCustomerForHold({ CompId: CompId, AppId: AppId, branchId: BranchId, OrderId: OrderId, }) ).unwrap(); if (res?.data?.statusCode !== 1) { res = await dispatch( getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId, }) ).unwrap(); } if (res?.data?.statusCode === 1) { const loyaltyFreeProductOfferApplied = (RefDetails?.[0]?.OfferAppliedProductList || [])?.filter( (off) => off?.FreeProductsList?.OfferMode === 'L' && off?.TableUniqueName === 'FreeProduct' ); const customerDetails = res?.data?.data?.find( (item) => item.CustId === CustSuppId ); if (customerDetails) { const { CustId, CustName, CustMobile, LoyaltyPointsDetail, TotalLoyaltyPoints } = customerDetails; const data = { CustId: CustId, CustName: CustName, label: CustName ? CustName : CustMobile, value: CustMobile, LoyaltyPointsDetail: LoyaltyPointsDetail, TotalLoyaltyPoints: TotalLoyaltyPoints }; dispatch(changeOrderOfferDetail([...OrderOfferDetails])); dispatch(changeSelectedOption(data)); await dispatch(ChangeSelectedCustDisable(true)); if (loyaltyFreeProductOfferApplied?.length > 0) { const loyaltyProdQuantities = {}; loyaltyFreeProductOfferApplied.forEach((off) => { const freeProdDtls = off?.FreeProductsList; const freeProdOfferId = freeProdDtls?.ProdVariantDetails?.[0]?.StockDetails?.[0] ?.ProdOfferId; const key = [ freeProdDtls?.OfferId, freeProdDtls?.FreeProdId, freeProdDtls?.FreeProdVariantName, freeProdOfferId, ].join('|'); loyaltyProdQuantities[key] = freeProdDtls?.FreeQty || 0; }); if (Object.keys(loyaltyProdQuantities).length > 0) { dispatch(changeLoyaltyConsumedQuantities(loyaltyProdQuantities)); } console.log(loyaltyProdQuantities, 'loyaltyProdQuantities'); } } } } await dispatch(changeOrderType('Hold')); await dispatch(changeHoldOrderDtl(true)); await dispatch(changeReorderHoldDetails(orderDtls)); await dispatch(changeReorderProductDetails(updated)); await dispatch(changeSelectedCustId(CustSuppId)); await dispatch(ChangeTotalAmount(ExtraChargeDetails)); await dispatch(changePreviousOrderPayment(OrderPaymentDtl)); await dispatch(changePreviousOrderOfferDetail(OrderOfferDetails)); dispatch(changeOrderCardDetails(updated)); let temp = updated?.filter((item) => item.OrderType === 'E') .map((item) => item.InwardDtlId + ' ' + item.BookingTypeName); await dispatch(changeSelProdWiseEst(temp)); if (OrderType === 'E') { await dispatch(changeEstimateBooking('OvrAllEst')); await dispatch(ChangeOverAllDiscEstimate(parseFloat(OverallDisc))); } else { await dispatch(changeEstimateBooking('Sales')); await dispatch(ChangeOverAllDiscSales(parseFloat(OverallDisc))); } } return ( <>
{/* Your existing JSX */} {/* Add the progress component */}
{reprintData?.length > 0 && selectedRows.length > 0 && reprintData?.map((orderDetail, index) => (
))}
{selectedRows.length > 0 && (
mutiplePrint('download')} className="icon-download" /> handleEmail()} className="icon-email" /> mutiplePrint('whatsapp')} className="icon-whatsapp" />
)}
{ debouncedSearch(e.target.value); }} />
{ setReprintReasonModel({ modal: true, action: 'NoPrint', default: true, }); Reprintformdata(); }} />
{/*
*/}
{countOfProduct > 10 && ( `Total ${countOfProduct ? countOfProduct : 0} items` } /> )}{' '}
} open={reprintReasonModel.modal} footer={false} children={ <>
({ value: option.ConfigId, label: option.ConfigName, }))} label={ } className="field-DropDown-Emp" onChangeFunction={(e) => reprintReasonDropDownChange(e)} valueData={ DefReason?.DefaultDetails?.[0]?.Reason || reprintReasonRef.current?.getFieldValue('Reason') } /> Description..} defaultValue={ DefReason?.DefaultDetails?.[0]?.Description || reprintReasonRef.current?.getFieldValue('Description') } isOnChange={ reprintReasonRef.current?.getFieldValue('Description') ? true : false } /> {reprintReasonModel.default == true && ( <> {/* ✅ Checkbox for Set as Default */} Set as Default )}
} />
} handleCancel={() => { setReprintData([]); setReprintReasonModel({ modal: false, action: 'without' }); }} />
} open={reprint} footer={null} children={ <>
{dateTimeFormatChange(table2Data?.[0]?.SalesDate)}
Total Qty {totalSalesQty}
{widthOutTexAmt > 0 && (
WithOut Tax Amt ₹ {Number(widthOutTexAmt).toFixed(2)}
)} {table2Data?.[0]?.TaxAmount > 0 && (
Tax Amt ₹ {table2Data?.[0]?.TaxAmount}
)}
Total Net Amt ₹ {table2Data?.[0]?.NetAmount}
{reprintData?.length > 0 && reprintData?.map((orderDetail, index) => (
))}
} handleCancel={ReprintCancel} /> setEmailModalOpen(false)} footer={null} > {loading &&
} setEmailId(e.target.value)} style={{ marginBottom: '16px' }} />
{!emailModalOpen && ( )} {reprintData?.length > 0 && reprintData?.map((orderDetail, index) => (
))} ); } export default BSReprint;