import { RadioGrpButton } from '../../../Components/Forms/RadioGroup'; import { DatePicker, Space, Tooltip } from 'antd'; import React, { useEffect, useRef, useState } from 'react'; import { useDispatch } from 'react-redux'; import moment from 'moment'; import { DropDowns } from '../../../Components/Forms/DropDown.jsx'; import { Tables } from '../../../Components/Tables/Table'; import { BiSolidPrinter } from 'react-icons/bi'; import { getAllCustomerWithoutActive, PreferenceData, } from '../../../Features/BookingScreen/BookingData/BookingData'; import { getSession, extractLastNumber, printDiv, ExtractDateFormate, } from '../../../Services/Others'; import { changeBreadCrumb } from '../../../Features/AppPage/CenterPage'; import dayjs from 'dayjs'; import customParseFormat from 'dayjs/plugin/customParseFormat'; import Buttons from '../../../Components/Forms/Buttons'; import { Form } from 'antd'; import { ArrowRightOutlined } from '@ant-design/icons'; import LedgerReportPdf from '../../paymentpdfPage/LedgerReportPdf.jsx'; import { LedgergetReport, getFirstOrderLedgerDate, } from '../../../Features/Reports/Reports'; import '../../../Styles/Reports/LedgerReport/LedgerReport.scss'; import { isMobile } from 'react-device-detect'; import { ReportMobilePDFPrint } from '../../paymentpdfPage/ReportMobilePDFPrint.js'; import { useSelector } from 'react-redux'; import excelExport from '../../../Images/xls-export.png'; import ExcelJS from 'exceljs'; import { saveAs } from 'file-saver'; import { downloadFile } from '../../../utils/downloadFile.js'; dayjs.extend(customParseFormat); const { RangePicker } = DatePicker; const dateFormat = 'DD-MM-YYYY'; const LedgerReport = () => { const dispatch = useDispatch(); const [AllCustomer1, setAllCustomer1] = useState([]); const [SelectedCusId, setSelectedCusId] = useState(null); const [LedgerData, setLedgerData] = useState([]); const [SelectType, setSelectType] = useState('ALL'); const [Type, setType] = useState('Y'); const [Fromdate, setFromdate] = useState(null); const [Todate, setTodate] = useState(null); const [selectedMonth, setSelectedMonth] = useState(null); const [Year, setYear] = useState(null); const [filteredInfo, setFilteredInfo] = useState({}); const [sortedInfo, setSortedInfo] = useState({}); const [page, setpage] = useState(1); const [FirstOrderLedgerDate, setFirstOrderLedgerDate] = useState(''); const formRef = useRef(null); const CompId = getSession('CompId'); const BranchId = getSession('BranchId'); const AppId = getSession('AppId'); const SettingDataSelector = useSelector(PreferenceData); const subDirectory = import.meta.env.BASE_URL; const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find( (setting) => setting?.SettingIdName?.toLowerCase() === 'mobilea4' && setting?.SettingValue === 'Y' ); const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, // { // name: "Ledger", // link: `${subDirectory}report/ledgerreport`, // }, ]; const style = ``; useEffect(() => { dispatch(changeBreadCrumb({ items: items })); fetchdata2(); }, []); useEffect(() => { setLedgerData(); setSelectedCusId(null); setFromdate(null); setTodate(null); setSelectedMonth(null); setYear(null); setSelectedCusId(null); fetchdata(); formRef.current?.resetFields(); // Assuming formRef is a ref assigned to your Form component }, [Type, SelectType]); const fetchdata = async () => { let res = await dispatch( getAllCustomerWithoutActive({ CompId: CompId, AppId: AppId, branchId: BranchId, }) ).unwrap(); setAllCustomer1(res?.data?.data); }; const fetchdata2 = async () => { let response = await dispatch( getFirstOrderLedgerDate({ CompId: CompId, AppId: AppId, BranchId: BranchId, }) ).unwrap(); if (response?.data?.statusCode == 1) { setFirstOrderLedgerDate(response?.data?.data?.[0]?.OrderDate); } }; const ledger = (e) => { formRef.current?.resetFields(); setSelectType(e); }; const ledgerDatePicker = (e) => { setType(e); formRef.current?.resetFields(); }; const CusSelect = (e) => { formRef.current?.setFieldsValue({ CustomerName: e }); setSelectedCusId(e); }; const onChange = (date, dateString) => { setYear(dateString); // setFromdate(null); // setTodate(null); // selectedMonth(null); }; const handleCalendarChange = (dates, dateStrings) => { if (dates && dates[1]) { setFromdate(dateStrings[0]); setTodate(dateStrings[1]); } }; const Datetrimmer = (data) => { let dateVal = moment(data, ['YYYY-MM-DDTHH:mm:ss']).format('DD-MM-YYYY'); return dateVal; // const dateObject = new Date(data); // // Get day, month, and year components // const day = dateObject.toLocaleDateString("en-US", { day: "2-digit" }); // const month = dateObject.toLocaleDateString("en-US", { month: "2-digit" }); // const year = dateObject.getFullYear(); // return `${day}/ ${month}/ ${year}`; }; const columns = [ { title: 'SI no', dataIndex: 'sno', key: 'sno', align: 'center', width: 10, render: (text, object, index) => ( {index + 1} ), }, { title: 'Type', dataIndex: 'TypeName', key: 'TypeName', align: 'left', width: 10, render: (text, object, index) => ( {text == 'OB' ? 'OB' : text} ), }, { title: ' Cus-Id', dataIndex: 'CustId', key: 'CustId', align: 'left', width: 100, render: (text, object, index) => ( {text == null ? 'GEN' : extractLastNumber(text)} ), }, { title: 'Cus-Name', dataIndex: 'CustName', key: 'CustName', align: 'left', width: 150, }, { title: 'RC.NO', dataIndex: 'ReceiptNo', key: 'ReceiptNo', align: 'left', width: 10, }, { title: 'Mob.No', dataIndex: 'MobileNo', key: 'MobileNo', align: 'left', width: 100, }, { title: 'Address', dataIndex: 'Address1', key: 'Address1', align: 'left', render: (text, object, index) => (

{text}

), }, { title: 'Payment Mode', dataIndex: 'PaymentTypeName', key: 'PaymentTypeName', align: 'left', width: 150, // ellipsis: true, }, { title: 'Date', dataIndex: 'Date', key: 'Date', align: 'center', width: 250, render: (text, object, index) => ( {ExtractDateFormate(text)} ), }, { title: 'Debit', dataIndex: 'Debit', key: 'Debit', align: 'right', width: 10, render: (text, object, index) => ( {text > 0 ? text : ' '} ), }, { title: 'Credit', dataIndex: 'Credit', key: 'Credit', align: 'right', width: 10, render: (text, object, index) => ( {text > 0 ? text : ' '} ), }, { title: 'Balance', // dataIndex: "company", key: 'company', align: 'center', width: 100, children: [ { title: 'Credit', key: 'BalCredit', dataIndex: 'BalCredit', // width: 30, render: (text, object, index) => ( {text > 0 ? text : ' '} ), }, { title: 'Debit', dataIndex: 'BalDebit', key: 'BalDebit', render: (text, object, index) => ( {text > 0 ? text : ' '} ), }, ], }, ]; const handleOk = (date) => { // Handle the "OK" button click event setSelectedMonth(date.format('YYYY-MM')); setYear(null); setFromdate(null); setTodate(null); }; const getReport = async (value) => { let data1 = { CompId: CompId, BranchId: BranchId, AppId: AppId, Year: Year, Month: selectedMonth, Fromdate: Fromdate, Todate: Todate, CustId: SelectedCusId, }; let response = await dispatch(LedgergetReport(data1)).unwrap(); if (response?.data?.statusCode == 1) { setLedgerData(response?.data?.data); } else { setLedgerData(); } }; const handleChange = (pagination, filters, sorter) => { setFilteredInfo(filters); setSortedInfo(sorter); }; const handlePageChange = (current) => { setpage(current); }; const Print = async () => { if (isMobile) { if (MobileA4Print) { ReportMobilePDFPrint({ printId: 'RePrint', printStyle: style, }); } } else { await printDiv('RePrint', style); } }; const exportToExcel = async () => { if (!LedgerData || LedgerData.length === 0) return; const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Ledger Report'); worksheet.views = [ { state: 'frozen', ySplit: 2, }, ]; // HEADER ROW 1 worksheet.addRow([ 'SI No', 'Type', 'Cus-Id', 'Cus-Name', 'RC.NO', 'Mob.No', 'Address', 'Payment Mode', 'Date', 'Debit', 'Credit', 'Balance in', '', ]); // HEADER ROW 2 worksheet.addRow([ '', '', '', '', '', '', '', '', '', '', '', 'Credit', 'Debit', ]); // MERGE CELLS worksheet.mergeCells('A1:A2'); worksheet.mergeCells('B1:B2'); worksheet.mergeCells('C1:C2'); worksheet.mergeCells('D1:D2'); worksheet.mergeCells('E1:E2'); worksheet.mergeCells('F1:F2'); worksheet.mergeCells('G1:G2'); worksheet.mergeCells('H1:H2'); worksheet.mergeCells('I1:I2'); worksheet.mergeCells('J1:J2'); worksheet.mergeCells('K1:K2'); worksheet.mergeCells('L1:M1'); // worksheet.eachRow((row) => { // row.eachCell((cell) => { // cell.protection = { // locked: true // }; // }); // }); // Lock header rows [1, 2].forEach((rowNumber) => { const row = worksheet.getRow(rowNumber); row.eachCell((cell) => { cell.protection = { locked: true }; }); }); // HEADER STYLE const headerRows = [1, 2]; headerRows.forEach((rowNumber) => { const row = worksheet.getRow(rowNumber); row.eachCell((cell) => { cell.font = { bold: true, color: { argb: 'FFFFFFFF' }, // white text }; cell.alignment = { vertical: 'middle', horizontal: 'center', }; cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2E7D32' }, // green header }; cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' }, }; }); }); // specifically ensure Balance in header center worksheet.getCell('L1').alignment = { horizontal: 'center', vertical: 'middle', }; // COLUMN WIDTH worksheet.columns = [ { width: 8 }, { width: 10 }, { width: 12 }, { width: 20 }, { width: 12 }, { width: 15 }, { width: 25 }, { width: 15 }, { width: 15 }, { width: 12 }, { width: 12 }, { width: 12 }, { width: 12 }, ]; // DATA ROWS LedgerData.forEach((row, index) => { const r = worksheet.addRow([ index + 1, row.TypeName === 'OB' ? 'OB' : row.TypeName, row.CustId ? extractLastNumber(row.CustId) : 'GEN', row.CustName || '', row.ReceiptNo || '', row.MobileNo || '', row.Address1 || '', row.PaymentTypeName || '', ExtractDateFormate(row.Date) || '', row.Debit > 0 ? row.Debit : '', row.Credit > 0 ? row.Credit : '', row.BalCredit > 0 ? row.BalCredit : '', row.BalDebit > 0 ? row.BalDebit : '', ]); // 🔓 Unlock every cell in this row r.eachCell({ includeEmpty: true }, (cell) => { cell.protection = { locked: false }; }); // Credit red if (row.BalCredit > 0) { r.getCell(12).font = { color: { argb: 'FFFF0000' } }; } // Debit green if (row.BalDebit > 0) { r.getCell(13).font = { color: { argb: 'FF008000' } }; } }); // Unlock all data rows worksheet.eachRow((row, rowNumber) => { if (rowNumber > 2) { row.eachCell((cell) => { cell.protection = { locked: false }; }); } }); await worksheet.protect('ledger123', { selectLockedCells: true, selectUnlockedCells: true, formatColumns: true, // allow column resize formatRows: false, insertColumns: false, insertRows: false, deleteColumns: false, deleteRows: false, }); const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-of ficedocument.spreadsheetml.sheet', }); const now = new Date(); const day = String(now.getDate()).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0'); const year = now.getFullYear(); let hours = now.getHours(); const minutes = String(now.getMinutes()).padStart(2, '0'); const ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; hours = String(hours).padStart(2, '0'); const fileName = `Ledger Report_${day}-${month}-${year}_${hours}-${minutes}-${ampm}.xlsx`; downloadFile( buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", (success) => { if (success) { console.log("File downloaded and opened successfully!"); } else { console.log("Failed to download/open file."); } } ); // saveAs(blob, fileName); }; const FirstOrderLedgerDateRaw = dayjs(FirstOrderLedgerDate); const disabledDate = (current) => { return ( current && (current < FirstOrderLedgerDateRaw.startOf('day') || current > dayjs().endOf('day')) ); }; return ( <>
{/* */}
{' '}

Ledger

ledger(e)} />
{' '}
ledgerDatePicker(e)} />
{/* datepicer */}
{Type == 'Y' && ( current && (current.year() < FirstOrderLedgerDateRaw.year() || current.year() > moment().year()) } onChange={(date, dateString) => onChange(date, dateString) } /> )} {Type == 'M' && ( current && (current < FirstOrderLedgerDateRaw.startOf('month') || current > moment().endOf('month')) } onChange={(date, dateString) => handleOk(date)} /> )} {Type == 'D' && ( )}
{SelectType === 'CUS' && ( {/* ({ value: option.CustId, label: option.CustName, }))} placeholder="Customer Name" // label={} label="Config Type" onChangeFunction={(e) => CusSelect(e)} isOnchanges={true} className="field-DropDown" valueData={SelectedCusId} width={20} /> */} ({ value: option.CustId, label: option.CustName || option?.MobileNo, }))} // defaultValue="Select" // Set "Select" as the default value // placeholder="Name" label={ } // onChangeFunction={(e)=>ConfigSelect(e)} // isOnchanges={} className="field-DropDown" valueData={SelectedCusId} onChangeFunction={(e) => CusSelect(e)} // onFilter={(value, record) => // String(record.TypeName) // .toLowerCase() // .includes(value.toLowerCase()) // } /> )}
{/* datepicer */}
} // handleSubmit={() => { getReport() }} />
0 ? () => Print() : () => {}} className={ LedgerData?.length > 0 ? 'ItemWiseReport-printerIcon' : 'ItemWiseReport-printerIcon-disabled' } /> 0 ? 'Export as Excel' : 'No data to Export' } placement="top" >
0 ? 'pointer' : 'not-allowed', opacity: LedgerData?.length > 0 ? 1 : 0.5, }} > Excel Export 0 ? () => exportToExcel() : () => {} } />
{/* */} {LedgerData && LedgerData.length > 0 ? ( LedgerData.map((row, idx) => ( )) ) : ( )}
SI no Type Cus-Id Cus-Name RC.NO Mob.No Address Payment Mode Date Debit Credit Balance in
Credit Debit
{idx + 1} {row.TypeName === 'OB' ? 'OB' : row.TypeName} {row.CustId == null ? 'GEN' : typeof extractLastNumber === 'function' ? extractLastNumber(row.CustId) : row.CustId} {row.CustName} {row.ReceiptNo} {row.MobileNo} {row.Address1} {row.PaymentTypeName} {ExtractDateFormate(row.Date)} {row.Debit > 0 ? row.Debit : ''} {row.Credit > 0 ? row.Credit : ''} {row.BalCredit > 0 ? row.BalCredit : ''} {row.BalDebit > 0 ? row.BalDebit : ''}
Data not found
{' '} ); }; export default LedgerReport;