// import React, { useState, useEffect } from "react"; // import { Button, Dropdown, Table, Modal, Form ,Row,Col} from "react-bootstrap"; // import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; // import { faEdit, faTrashAlt, faPlus ,faBars} from "@fortawesome/free-solid-svg-icons"; // import "bootstrap/dist/css/bootstrap.min.css"; // import "../Dashboard/UserMaintainanceView.css"; // function UserMaintenanceView() { // const [appUsers, setAppUsers] = useState([]); // const [isSubMenu, setIsSubMenu] = useState(false); // const [showAddItemPopup, setShowAddItemPopup] = useState(false); // const [newItemData, setNewItemData] = useState({ // userId: "", // username: "", // fullName: "", // email: "", // mobileNumber: "", // isActive: true, // userGroupId: "", // }); // const [recordsPerPage, setRecordsPerPage] = useState(10); // const [visibleColumns, setVisibleColumns] = useState({ // userId: true, // username: true, // fullName: true, // email: true, // mobileNumber: true, // isActive: true, // userGroupId: true, // actions: true, // }); // const [isEditing, setIsEditing] = useState(false); // useEffect(() => { // const apiUrl = `${process.env.REACT_APP_API_URL}/api/getAllAppUser`; // const token = localStorage.getItem("authToken"); // const fetchAppUsers = 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(); // setAppUsers(data); // } catch (error) { // console.error("Fetching error:", error ); // } // }; // fetchAppUsers(); // }, []); // const toggleColumn = (column) => { // setVisibleColumns(prevColumns => ({ // ...prevColumns, // [column]: !prevColumns[column] // })); // }; // const handleAddItem = () => { // setIsEditing(false); // setNewItemData({ // userId: "", // username: "", // fullName: "", // email: "", // mobileNumber: "", // isActive: true, // userGroupId: "", // }); // setShowAddItemPopup(true); // }; // const handleInputChange = (event) => { // const { name, value, type, checked } = event.target; // setNewItemData((prev) => ({ // ...prev, // [name]: type === "checkbox" ? checked : value, // })); // }; // const handleSubmit = (event) => { // event.preventDefault(); // if (isEditing) { // setAppUsers( // appUsers.map((user) => // user.userId === newItemData.userId ? newItemData : user // ) // ); // } else { // const newUserId = `ID${appUsers.length + 1}`; // setAppUsers([...appUsers, { ...newItemData, userId: newUserId }]); // } // setShowAddItemPopup(false); // }; // const handleEdit = (userId) => { // const userToEdit = appUsers.find((user) => user.userId === userId); // setNewItemData(userToEdit); // setIsEditing(true); // setShowAddItemPopup(true); // }; // const handleDelete = (userId) => { // setAppUsers(appUsers.filter((user) => user.userId !== userId)); // }; // return( //
//
//

User Maintenance

//
// // {isSubMenu && ( // // )} //
//
//
// // // // {Object.keys(visibleColumns).filter((key) => visibleColumns[key]).map((key) => ( // // ))} // // // // {appUsers.length > 0 ? ( // appUsers.slice(0, recordsPerPage).map((user, index) => ( // // {Object.keys(visibleColumns).filter((key) => visibleColumns[key]).map((key) => ( // // ))} // {!isSubMenu && ( // // )} // // )) // ) : ( // // // // ) // } // //
// {key.charAt(0).toUpperCase() + key.slice(1).toLowerCase()} //
// {key === "actions" ? ( //
// // //
// ) : ( // user[key] // )} //
// //
// No users found. Please add new users. //
//
// {/* Manage Columns & Records Per Page */} // // // // // Manage Columns // // // {Object.keys(visibleColumns).map((column) => ( // toggleColumn(column)}> // // // ))} // // // // // // // Records Per Page // // // {[5, 10, 20, 50].map((number) => ( // handleRecordsPerPageChange(number)}> // {number} // // ))} // // // // // setShowAddItemPopup(false)}> // // {isEditing ? "Edit User" : "Add New User"} // // //
// // Username // // // // Full Name // // // // Email // // // // Mobile Number // // // // // // // User Group ID // // // // // // //
//
//
//
// ); // } // export default UserMaintenanceView; import React, { useState, useEffect } from "react"; import { Button, Dropdown, Modal, Form, Row, Col, InputGroup, FormControl, ModalFooter, } from "react-bootstrap"; import { Table ,Pagination, PaginationItem, PaginationLink,} from 'reactstrap'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faEdit, faTrashAlt, faPlus, faBars, faTimes, faDownload, faUpload, faFileExcel } from "@fortawesome/free-solid-svg-icons"; import { FaSearch, FaTimes } from "react-icons/fa"; import "bootstrap/dist/css/bootstrap.min.css"; import "../Dashboard/CSS/CSS/UserMaintainanceView.css"; 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 { getAllUsers ,createUser,updateUser,deleteUser} from "../../APIServices/UserMaintenanceAPI.js"; function UserMaintenanceView() { const [currentPage, setCurrentPage] = useState(1); const [appUsers, setAppUsers] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [showAddItemPopup, setShowAddItemPopup] = useState(false); const [showModal, setShowModal] = useState(false); const [newItemData, setNewItemData] = useState({ userId: "", username: "", fullName: "", email: "", mob_no: "", active: true, usrGrpId: "", }); const [recordsPerPage, setRecordsPerPage] = useState(10); const [visibleColumns, setVisibleColumns] = useState({ userId: true, username: true, fullName: true, email: true, mob_no: true, acitve : true, usrGroupId: true, actions: true, }); const [isEditing, setIsEditing] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { const apiUrl = `${process.env.REACT_APP_API_URL}/api/getAllAppUser`; const token = localStorage.getItem("authToken"); const fetchAppUsers = 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(); setAppUsers(data); } catch (error) { console.error("Fetching error:", error); } }; fetchAppUsers(); }, []); useEffect(() => { // Simulate loading data setTimeout(() => { setLoading(false); }, 3000); // Simulated 3 seconds loading }, []); const toggleColumn = (column) => { setVisibleColumns((prevColumns) => ({ ...prevColumns, [column]: !prevColumns[column], })); }; const handleSearch = (query) => { setSearchQuery(query); }; // const handleBack = () => { // setViewMode("cards"); // }; const handleClose = () => { setShowAddItemPopup(false); // Close the modal by setting the state to false }; const handleAddItem = () => { setIsEditing(false); setNewItemData({ userId: "", username: "", fullName: "", email: "", mob_no : "", active : true, usrGrpId: "", }); setShowAddItemPopup(true); }; // const handleInputChange = (event) => { // const { name, value, type, checked } = event.target; // setNewItemData((prev) => ({ // ...prev, // [name]: type === "checkbox" ? checked : value, // })); // }; const handleOpenModal = () => setShowModal(true); const handleCloseModal = () => setShowModal(false); const handleInputChange = (event) => { const { name, type, checked, value } = event.target; setNewItemData({ ...newItemData, [name]: type === "checkbox" ? checked : value, }); }; // const handleSubmit = async (event) => { // try { // event.preventDefault(); // if (isEditing) { // setAppUsers( // appUsers.map((user) => // user.userId === newItemData.userId ? newItemData : user // ) // ); // toast.success("User Updated Successfully..."); // } else { // const newUserId = `ID${appUsers.length + 1}`; // setAppUsers([...appUsers, { ...newItemData, userId: newUserId }]); // toast.success("User added successfully!"); // } // setShowAddItemPopup(false); // } catch (error) { // toast.error("There was an error while submitting the USER."); // console.error("Error in handleSubmit:", error); // Log the error for debugging // } // }; const handleSubmit = async (event) => { event.preventDefault(); try { if (isEditing) { // If editing, update the user locally console.log("update api is applying..."); const data = await updateUser(newItemData); console.log("update user data",data); setAppUsers( appUsers.map((user) => user.userId === newItemData.userId ? newItemData : user ) ); toast.success("User Updated Successfully..."); } else { console.log("post api is applying...") // If not editing, call the createUser API to add the new user const response = await createUser(newItemData); if (response && response.data) { // On success, add the new user to the local state const newUserId = `ID${appUsers.length + 1}`; setAppUsers([...appUsers, { ...newItemData, userId: newUserId }]); toast.success("User added successfully!"); console.log("User added successfully:", response.data); } } // Close the popup after submit setShowAddItemPopup(false); } catch (error) { // Handle any errors that occur during submission toast.error("There was an error while submitting the USER."); console.error("Error in handleSubmit:", error); // Log the error for debugging } }; const handleEdit = (userId) => { try { const userToEdit = appUsers.find((user) => user.userId === userId); setNewItemData(userToEdit); setIsEditing(true); setShowAddItemPopup(true); } catch (error) { } }; const handleDelete = async (userId) => { const data = await deleteUser(userId); console.log("deleted data",data); setAppUsers(appUsers.filter((user) => user.userId !== userId)); toast.success("User deleted ....") }; const handleRecordsPerPageChange = (number) => { setRecordsPerPage(number); setCurrentPage(1); }; const totalPages = Math.ceil(appUsers.length / recordsPerPage); const handlePageChange = (pageNumber) => { setCurrentPage(pageNumber); }; 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 = () => { const worksheet = XLSX.utils.json_to_sheet([]); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "UserDetails"); XLSX.writeFile(workbook, "UserMaintenance.xlsx"); }; const slicedUsers = appUsers .filter((user) => user.username.toLowerCase().includes(searchQuery.toLowerCase()) ) .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage); return (
{loading ? ( ):(
{/* Header */}

User 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 Icon */} Add Items}> handleAddItem(true)} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} data-bs-toggle="tooltip" data-bs-placement="bottom" title="Add Item" /> Download template}> handleAddItem(true)} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} /> Import}> handleOpenModal(true)} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} /> XLSX}> exportToExcel(true)} style={{ cursor: "pointer", fontSize: "1.5rem", color: "#747264", marginRight: "20px", }} /> Menu Items}> Import File
Select a file to import:
{/* Table */}
{Object.keys(visibleColumns).map( (key) => visibleColumns[key] && ( ) )} {slicedUsers.length === 0 ? ( ) : ( slicedUsers.map((user, index) => ( {Object.keys(visibleColumns).map((key) => visibleColumns[key] ? ( ) : null )} )))} {appUsers.length === 0 && ( )}
{key.charAt(0).toUpperCase() + key.slice(1).toLowerCase()}
visibleColumns[key]) .length } className="text-center" >
{key === "actions" ? (
handleEdit(user.userId)} style={{ cursor: "pointer", fontSize: "1rem", color: "green", // edit icon color marginRight: "15px", // space between icons }} /> handleDelete(user.userId)} style={{ cursor: "pointer", fontSize: "1rem", color: "#dc3545", // delete icon color }} />
) : key === "isActive" ? ( {user.isActive ? "Active" : "Inactive"} ) : ( user[key] )}
visibleColumns[key] ).length } className="text-center" > No users found. Please add new users.
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)} /> {isEditing ? "Edit User" : "Add New User"}
{/* Form Content */} Username Full Name Email Mobile Number User Group
)}
); } export default UserMaintenanceView;