import React, { useState, useEffect } from "react"; import { Button, Dropdown, Modal, Form, Row, Col, InputGroup, FormControl, } from "react-bootstrap"; import { Table, Pagination, PaginationItem, PaginationLink } from "reactstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faEdit, faTrashAlt, faPlus, faBars, faTimes, faFileExcel, faUpload, faDownload, } from "@fortawesome/free-solid-svg-icons"; import "bootstrap/dist/css/bootstrap.min.css"; import "../Dashboard/CSS/CSS/CommonStyle.css"; import { FaSearch } from "react-icons/fa"; import { BsJournals } from "react-icons/bs"; import { toast } from "react-toastify"; import Spinner from "../../UIComponants/Spinner"; import { Tooltip, OverlayTrigger } from "react-bootstrap"; import * as XLSX from "xlsx"; import { fetchUserGroups } from "../../APIServices/UserGroupMaintenanceApi"; import ExcelControlAPI from "../../APIServices/ExcelControlApi"; import { createUserGroup, deleteUserGroup, updateUserGroup} from "../../APIServices/UserGroupMaintenanceApi"; export function UserGroupMaintenance() { const [userGroups, setUserGroups] = useState([]); const [showAddItemPopup, setShowAddItemPopup] = useState(false); const [currentPage, setCurrentPage] = useState(1); const [searchQuery, setSearchQuery] = useState(""); const [loading, setLoading] = useState(true); const [showModal, setShowModal] = useState(false); const [excelData, setExcelData] = useState([]); const [newGroupData, setNewGroupData] = useState({ usrGrp: "", groupName: "", groupDesc: "", status: "", groupLevel: "", }); const [recordsPerPage, setRecordsPerPage] = useState(10); const [visibleColumns, setVisibleColumns] = useState({ usrGrp: true, groupName: true, groupDesc: true, status: true, groupLevel: true, }); const [isEditing, setIsEditing] = useState(false); // useEffect(() => { // const apiUrl = `${process.env.REACT_APP_API_URL}/api/getAllUsrGrp`; // const token = localStorage.getItem("authToken"); // const fetchUserGroups = async () => { // try { // const response = await fetch(apiUrl, { // method: "GET", // headers: { // "Content-Type": "application/json", // Authorization: `Bearer ${token}`, // }, // }); // if (!response.ok) { // throw new Error(`HTTP error! status: ${response.status}`); // } // const data = await response.json(); // setUserGroups(data); // } catch (error) { // console.error("Fetching error:", error); // } // }; // fetchUserGroups(); // }, []); useEffect(() => { const loadUserGroups = async () => { try { const data = await fetchUserGroups(); setUserGroups(data); console.log("all user group data ", data); } catch (error) { toast.error("Failed to load user groups."); } finally { setLoading(false); } }; loadUserGroups(); }, []); useEffect(() => { // Simulate loading data setTimeout(() => { setLoading(false); }, 3000); // Simulated 3 seconds loading }, []); const handleOpenModal = () => setShowModal(true); const handleCloseModal = () => setShowModal(false); const handleFileChange = (event) => { const file = event.target.files[0]; if (file) { console.log("Selected file:", file.name); // For debugging or processing } }; const handleUpload = () => { // Simulate file upload success setTimeout(() => { toast.success("File uploaded successfully!"); // Show toaster notification setShowModal(false); // Close modal }, 1000); }; const exportToExcel = async (fileType) => { try { // Fetch binary Excel data const response = await ExcelControlAPI.demoDownload(fileType); // Log the response size for debugging const dataSize = response.data?.byteLength || response.data?.length; console.log("Response Data Size:", dataSize); // If file is too large, show error and exit const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB if (dataSize > MAX_FILE_SIZE) { console.error("File is too large to process"); return; } // Convert binary data to a Blob const blob = new Blob([response.data], { type: "application/vnd.ms-excel", }); // Use FileReader to convert Blob to ArrayBuffer const arrayBuffer = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsArrayBuffer(blob); }); console.log("ArrayBuffer Size:", arrayBuffer.byteLength); // Parse Excel data const workbook = XLSX.read(arrayBuffer, { type: "array" }); console.log("workbook", workbook); const firstSheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[firstSheetName]; // Convert worksheet to JSON const jsonData = XLSX.utils.sheet_to_json(worksheet); console.log("Parsed JSON Data:", jsonData); // Create a new workbook and trigger download const newWorksheet = XLSX.utils.json_to_sheet(jsonData); const newWorkbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(newWorkbook, newWorksheet, fileType); XLSX.writeFile(newWorkbook, `${fileType}_processed.xlsx`); console.log("Excel file generated successfully!"); } catch (error) { console.error("Error exporting to Excel:", error); } }; const toggleColumn = (column) => { setVisibleColumns((prev) => ({ ...prev, [column]: !prev[column], })); }; const handleAddItem = () => { setIsEditing(false); setNewGroupData({ usrGrp: "", groupName: "", groupDesc: "", status: "", groupLevel: "", }); setShowAddItemPopup(true); }; const handleInputChange = (event) => { const { name, value } = event.target; setNewGroupData({ ...newGroupData, [name]: value }); }; const handleSubmit = async (event) => { event.preventDefault(); try { // Validate input fields if ( !newGroupData.usrGrp || !newGroupData.groupName || !newGroupData.groupDesc || !newGroupData.status || !newGroupData.groupLevel ) { toast.error("Please make sure all fields are filled out."); return; } if (isEditing) { // Update existing group data setUserGroups( userGroups.map((group) => group.usrGrp === newGroupData.usrGrp ? newGroupData : group ) ); toast.success("Menu access updated successfully!"); } else { // Make an API call to create a new user group const newGroup = { ...newGroupData }; // Prepare data for API const response = await createUserGroup(newGroup); // Call API function if (response && response.data) { // Update userGroups state with the newly created group setUserGroups([...userGroups, response.data]); toast.success("Menu access added successfully!"); } else { toast.error("Failed to add menu access."); } } // Close the modal and reset the form setShowAddItemPopup(false); setNewGroupData({ usrGrp: "", groupName: "", groupDesc: "", status: "", groupLevel: "", }); } catch (error) { toast.error("There was an error processing your request."); console.error("Error in handleSubmit:", error); // Log the error for debugging } }; const handleSearch = (query) => { setSearchQuery(query); }; const handleClose = () => { setShowAddItemPopup(false); // Close the modal by setting the state to false }; const handleEdit = (usrGrp) => { const groupToEdit = userGroups.find((group) => group.usrGrp === usrGrp); setIsEditing(true); setNewGroupData(groupToEdit); setShowAddItemPopup(true); }; // const handleDelete = (usrGrp) => { // setUserGroups(userGroups.filter((group) => group.usrGrp !== usrGrp)); // toast.success("Menu Access delet successfully!"); // }; const handleDelete = async (usrGrp) => { try { // Call API to delete the user group const response = await deleteUserGroup(usrGrp); if (response && response.data) { // Update state after successful API call setUserGroups(userGroups.filter((group) => group.usrGrp !== usrGrp)); toast.success("User group deleted successfully!"); } } catch (error) { toast.error("Error deleting Menu Access!"); } }; const handleRecordsPerPageChange = (number) => { setRecordsPerPage(number); setCurrentPage(1); }; const totalPages = Math.ceil(userGroups.length / recordsPerPage); const handlePageChange = (pageNumber) => { setCurrentPage(pageNumber); }; const slicedUserGroup = userGroups .filter( (item) => item.groupName && item.groupName.toLowerCase().includes(searchQuery.toLowerCase()) ) .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage); return (
{loading ? ( ) : (

User Group Maintenance

{/* Left: Search Bar */} handleSearch(e.target.value)} style={{ padding: "10px", border: "none", paddingRight: "5px", // More space on the right side of input field }} /> {/*Add Icons */} <> Add Group} > handleAddItem(true)} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} /> Download template} > Import} > XLSX} > exportToExcel("customer")} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} /> Menu} > {/* Add Icon */} Import File
Select a file to import:
{Object.keys(visibleColumns).map((key) => ( ))} {slicedUserGroup.length === 0 ? ( ) : ( slicedUserGroup.map((group, index) => ( {Object.keys(visibleColumns).map((key) => visibleColumns[key] ? ( ) : null )} )) )}
{key.charAt(0).toUpperCase() + key.slice(1).toLowerCase()} Actions
visibleColumns[key] ).length + 1 // +1 for Actions column } className="text-center" > No data available
{key === "status" ? ( // Render status dynamically based on isActive or status key {group.status === "Enabled" ? "Active" : "Inactive"} ) : ( group[key] )} {/* Adding Action icons */} handleEdit(group.usrGrp)} style={{ cursor: "pointer", fontSize: "1rem", color: "green", marginRight: "15px", }} /> handleDelete(group.usrGrp)} style={{ cursor: "pointer", fontSize: "1rem", color: "#dc3545", }} />
{/* Manage Columns & Records Per Page */} Manage Columns {Object.keys(visibleColumns).map((column) => ( toggleColumn(column)} > ))} {[1, 5, 10, 20, 50].map((number) => ( handleRecordsPerPageChange(number)} className="text-dark d-flex justify-content-between align-items-center" > {number} ))} handlePageChange(currentPage - 1)} /> {[...Array(totalPages)].map((_, index) => ( handlePageChange(index + 1)} style={{ color: "#0b6592" }} > {index + 1} ))} handlePageChange(currentPage + 1)} /> {/* Add/Edit model */} setShowAddItemPopup(false)} > {isEditing ? "Edit Group" : "Add New Group"}
User Group Group Name Description Status Group Level
)}
); } export default UserGroupMaintenance;