import React, { useEffect, useRef, useState } from "react"; import Box from "@app-emos/layout/Box"; import zipcelx from "zipcelx"; import ContentWrapper from "@app-emos/layout/ContentWrapper"; import { TableView, FormField } from "@amxchange/grid-view-web-client"; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap"; import TableViewFinance from "./TableViewFinance"; import { PETTY_VOUCHER_FLOAT_ALLOCATION_VIEW_NAME, FLOAT_BRANCH_DATA, PETTY_VOUCHER_FLOAT_ALLOCATION_VIEW_NAME_WOT_FILTER } from "./constant"; import { USER_STAGES } from "../constants"; import ExcelJS from "exceljs"; import { saveAs } from "file-saver"; // For saving the file import DataService from "@common-services/DataService"; import ToastUtil from "@common-utils/ToastUtil"; import downloadIcon from "@app-emos/assets/utils/svgs/circle-arrow-up-solid.svg"; import thumbsIcon from "@app-emos/assets/utils/svgs/thumbs-icon.svg"; import { usePettyCashContext } from "../Context/PettyCashContext"; import { connect } from "react-redux"; import { AuthService } from "@common-services/AuthService"; import moment from "moment"; function Index({ employeeDetails }) { const tableRef = useRef(null); const tableRefTwo = useRef(null); const [modal, setModal] = useState(false); const [branchData, setBranchData] = useState([]); const [allocationAmt, setAllocationAmt] = useState(""); const [floatCountryBranchId, setFloatCountryBranchId] = useState(""); const [employeeNumber, setEmployeeNumber] = useState(null); const [refreshData, setRefreshData] = useState(false); // Add this state const [existingLimit, setExistingLimit] = useState(null); const [xlsxViewData, setXlsxViewData] = useState({ viewDataOne: [], viewDataTwo: [] }); const toggleModal = () => setModal(!modal); const { currentStage, changeCurrentStage } = usePettyCashContext(); //get current stage here useEffect(() => { // Set BU or FU here if (AuthService.isAllowed("PETTY_CASH.FINANCE_APPROVAL")) changeCurrentStage("PETTY_CASH.FINANCE_APPROVAL"); else if (AuthService.isAllowed("PETTY_CASH.BRANCH_APPROVAL")) changeCurrentStage("PETTY_CASH.BRANCH_APPROVAL"); }, []); // useEffect(() => { // console.log("tableRef.current.fetchResults(); ", tableRef.current?.state?.results); // setXlsxViewData(prevVal => ({ // ...prevVal, // viewDataOne: tableRef.current?.state?.results || [] // })); // }, [tableRef.current?.state?.results]); useEffect(() => { const timeout = setTimeout(() => { if (tableRef.current?.state) { const { results } = tableRef?.current?.state; if (results) { setXlsxViewData(prevVal => ({ ...prevVal, viewDataOne: results })); } } }, 1000); // Delay to ensure data is loaded return () => clearTimeout(timeout); }, [refreshData, tableRef]); useEffect(() => { const timeout = setTimeout(() => { if (tableRefTwo.current?.state) { const { results } = tableRefTwo?.current?.state; if (results) { setXlsxViewData(prevVal => ({ ...prevVal, viewDataTwo: results })); } } }, 1000); // Delay to ensure data is loaded return () => clearTimeout(timeout); }, [refreshData, tableRefTwo]); useEffect(() => { // Replace with your actual API endpoint fetch("https://jemsd-kwt.amxremit.com/emos/pub/meta") .then(response => response.json()) .then(data => { // Assuming data.results[0].employeeDetailsDTO.employeeNumber is the correct path const empNumber = data.results[0].employeeDetailsDTO.employeeNumber; setEmployeeNumber(empNumber); }) .catch(error => console.error("Error fetching data:", error)); }, []); useEffect(() => { const fetchBranchData = async () => { try { const response = await DataService.get(FLOAT_BRANCH_DATA); setBranchData(response.data.results); setFloatCountryBranchId(response.data.results?.countryBranchId || ""); // Initialize with the first countryBranchId or empty console.log(response.data.results, "Branch Data"); } catch (error) { console.error("Error while fetching branch data ", error); } }; fetchBranchData(); }, [refreshData]); const onSubmit = async () => { try { const response = await DataService.post("/api/pettycash/save-float-allocation", { countryBranchId: floatCountryBranchId, allocationAmt: allocationAmt }); if (response.data.results[0].success === true) { ToastUtil.success("Data saved successfully"); setModal(!modal); setRefreshData(prev => !prev); } } catch (err) { console.error("Error submitting form: ", err); } }; const handleFloatAcknowledgement = headerId => { console.log("header id :: ", headerId); try { DataService.post(`/api/pettycash/update-float-allocation?headerId=${headerId}`) .then(resp => { const message = resp.data.results[0]; if (message === "successfully updated the acknowledgement status") { ToastUtil.success(message); setRefreshData(prev => !prev); // Toggle refreshData state } else { ToastUtil.error("Error: " + message); } }) .catch(err => { ToastUtil.error("Error submitting"); console.log(err); }); } catch (err) { console.error(err); } }; useEffect(() => { if (floatCountryBranchId) DataService.get(`/api/pettycash/get-existing-limit?branchId=${floatCountryBranchId}`) .then(resp => { console.log(resp, "Limit existing data"); setExistingLimit(resp.data.results[0]); }) .catch(err => { console.log(err); }); }, [floatCountryBranchId]); console.log(currentStage, "currentStage"); const fetchAndGenerateExcel = async () => { try { // Fetch data from the API const response = xlsxViewData?.viewDataOne; const data = response; // Create a new workbook and add a worksheet const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet("PettyCashAllocation"); // Define the header row const headerRow = [ { header: "Area", key: "area", width: 20 }, { header: "Branch", key: "branch", width: 25 }, { header: "Allocation Amount", key: "allocationAmt", width: 20 }, { header: "Float Amount", key: "floatAmt", width: 20 }, { header: "Float Date", key: "floatDate", width: 20 }, { header: "Acknowledgment Status", key: "ackStatus", width: 25 }, { header: "Acknowledgment Document Reference", key: "ackDocRef", width: 50 }, { header: "Acknowledged By", key: "acknowledgeBy", width: 25 }, { header: "Created By", key: "createdBy", width: 25 }, { header: "Pettycash Float ID", key: "pettycashFloatId", width: 20 }, { header: "Created Date", key: "createdDate", width: 25 }, { header: "Status Description", key: "statusDescription", width: 30 }, { header: "Acknowledge Date", key: "acknowledgeDate", width: 25 }, { header: "Country Branch ID", key: "countryBranchId", width: 20 } ]; // Add the header row to the worksheet worksheet.columns = headerRow; // Apply styling to header row worksheet.getRow(1).eachCell(cell => { cell.font = { bold: true, color: { argb: "FFFFFF" } }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "0070C0" }, bgColor: { argb: "0070C0" } }; cell.alignment = { vertical: "middle", horizontal: "center" }; }); // Helper function to format dates using moment.js const formatDate = dateString => { if (!dateString) return ""; return moment(dateString).format("DD-MMM-YYYY"); // Format example: 28-AUG-2024 }; // Add data rows to the worksheet data.forEach(item => { worksheet.addRow({ area: item.AREA || "", branch: item.BRANCH || "", allocationAmt: item.ALLOCATION_AMOUNT || 0, floatAmt: item.FLOAT_AMOUNT || 0, floatDate: formatDate(item.FLOAT_DATE) || "", ackStatus: item.ACKNOW_STATUS || "", ackDocRef: item.ACKNOW_DOC_REF || "", acknowledgeBy: item.ACKNOWLEDGE_BY || "", createdBy: item.CREATED_BY || "", pettycashFloatId: item.PETTYCASH_FLOAT_ID || "", createdDate: formatDate(item.CREATED_DATE) || "", statusDescription: item.STATUS_DESCRIPTION || "", acknowledgeDate: formatDate(item.ACKNOWLEDGE_DATE) || "", countryBranchId: item.COUNTRY_BRANCH_ID || "" }); }); // Apply styling to the data rows if needed worksheet.eachRow({ includeEmpty: false }, row => { row.eachCell(cell => { cell.alignment = { vertical: "middle", horizontal: "center" }; }); }); // Save the workbook to a buffer and then to a file const buffer = await workbook.xlsx.writeBuffer(); saveAs(new Blob([buffer]), "PettyCashAllocation.xlsx"); } catch (error) { console.error("Error fetching data:", error); } }; const fetchAndGenerateExcelV2 = async () => { try { // Fetch data from the API const response = xlsxViewData?.viewDataTwo; const data = response; // Create a new workbook and add a worksheet const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet("PettyCashAllocationV2"); // Define the header row const headerRow = [ { header: "Area", key: "area", width: 20 }, { header: "Branch", key: "branch", width: 25 }, { header: "Allocation Amount", key: "allocationAmt", width: 20 }, { header: "Float Date", key: "floatDate", width: 20 }, { header: "Acknowledgment Status", key: "ackStatus", width: 25 }, { header: "Acknowledgment Document Reference", key: "ackDocRef", width: 50 }, { header: "Acknowledged By", key: "acknowledgeBy", width: 25 }, { header: "Created By", key: "createdBy", width: 25 }, { header: "Pettycash Branch Float ID", key: "pettycashBranchFloatId", width: 20 }, { header: "Created Date", key: "createdDate", width: 25 }, { header: "Status Description", key: "statusDescription", width: 30 }, { header: "Acknowledge Date", key: "acknowledgeDate", width: 25 }, { header: "Country Branch ID", key: "countryBranchId", width: 20 }, { header: "System Date", key: "sysDate", width: 25 } ]; // Add the header row to the worksheet worksheet.columns = headerRow; // Apply styling to header row worksheet.getRow(1).eachCell(cell => { cell.font = { bold: true, color: { argb: "FFFFFF" } }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "0070C0" }, bgColor: { argb: "0070C0" } }; cell.alignment = { vertical: "middle", horizontal: "center" }; }); // Helper function to format dates using moment.js const formatDate = dateString => { if (!dateString) return ""; return moment(dateString).format("DD-MMM-YYYY"); // Format example: 28-AUG-2024 }; // Add data rows to the worksheet data.forEach(item => { worksheet.addRow({ area: item.AREA || "", branch: item.BRANCH || "", allocationAmt: item.ALLOCATION_AMOUNT || 0, floatDate: formatDate(item.FLOAT_DATE) || "", ackStatus: item.ACKNOW_STATUS || "", ackDocRef: item.ACKNOW_DOC_REF || "", acknowledgeBy: item.ACKNOWLEDGE_BY || "", createdBy: item.CREATED_BY || "", pettycashBranchFloatId: item.PETTYCASH_BRANCH_FLOAT_ID || "", createdDate: formatDate(item.CREATED_DATE) || "", statusDescription: item.STATUS_DESCRIPTION || "", acknowledgeDate: formatDate(item.ACKNOWLEDGE_DATE) || "", countryBranchId: item.COUNTRY_BRANCH_ID || "", sysDate: formatDate(item.SYSDATE) || "" }); }); // Apply styling to the data rows if needed worksheet.eachRow({ includeEmpty: false }, row => { row.eachCell(cell => { cell.alignment = { vertical: "middle", horizontal: "center" }; }); }); // Save the workbook to a buffer and then to a file const buffer = await workbook.xlsx.writeBuffer(); saveAs(new Blob([buffer]), "PettyCashAllocationV2.xlsx"); } catch (error) { console.error("Error fetching data:", error); } }; // const viewName = employeeNumber === "406138" // ? PETTY_VOUCHER_FLOAT_ALLOCATION_VIEW_NAME // : PETTY_VOUCHER_FLOAT_ALLOCATION_VIEW_NAME_WOT_FILTER; useEffect(() => { const branchDetails = async () => { try { const resp = await DataService.get("/emos/pub/meta"); // console.log(resp.data.results, "branch details"); } catch (error) { console.log("error", error); } }; branchDetails(); }); console.log({ COUNTRY_BRANCH_ID: employeeDetails.countryBranchId }, "Country Branch Id"); return (
{currentStage === USER_STAGES.BM ? ( Petty Cash ) : currentStage === USER_STAGES.FU ? ( Petty Cash ) : null}
{currentStage === USER_STAGES.FU ? ( ) : null}
{currentStage === USER_STAGES.BM && ( (tableRefTwo.current = ref)} view={PETTY_VOUCHER_FLOAT_ALLOCATION_VIEW_NAME_WOT_FILTER} additionalColumns={[ { accessor: "noKey", Header: "ACTION", width: 150, Cell: row => { const { PETTYCASH_BRANCH_FLOAT_ID } = row.original; return (
handleFloatAcknowledgement(PETTYCASH_BRANCH_FLOAT_ID) } onMouseEnter={e => { e.target.style.opacity = 1; e.target.style.backgroundColor = "none"; }} onMouseLeave={e => { e.target.style.opacity = 1; e.target.style.backgroundColor = "white"; }} defaultPageSize={5} />
); } } ]} overrideColumns={[ { accessor: "ALLOCATION_AMOUNT", width: 250 }, { accessor: "AREA", Header: "AREA", width: 200 }, { accessor: "BRANCH", Header: "BRANCH", width: 200 }, { accessor: "FLOAT_DATE", Header: "FLOAT DATE", width: 200 }, { accessor: "ACKNOW_STATUS", Header: "ACKNOW STATUS", width: 200 } ]} customFilters={{ COUNTRY_BRANCH_ID: employeeDetails.countryBranchId }} extraConfig={{ sortColumn: "FLOAT_DATE", sortOrder: "DESC" }} /> )} {currentStage === USER_STAGES.FU && ( { console.log("tableRef.current.fetchResults(); ", tableRef.current?.state?.results); setXlsxViewData(prevVal => ({ ...prevVal, viewDataOne: tableRef.current?.state?.results || [] })); }} /> )}
ADD
setFloatCountryBranchId(e.value)} // Update state on change options={branchData.map(data => { return { label: `${data.branchId} - ${data.branchName}`, value: data.countryBranchId }; })} /> setAllocationAmt(e)} // Correct onChange handler />
); } const mapStateToProps = state => ({ employeeDetails: state.Auth.user }); export default connect(mapStateToProps)(Index);