Api integeration for Role

This commit is contained in:
jaanvi 2025-02-28 14:53:24 +05:30
commit 1c233360c4
14 changed files with 523 additions and 405 deletions

View file

@ -7,22 +7,10 @@ import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper, { paperClasses } from "@mui/material/Paper";
import { adminList, deleteAdmin } from "../../redux/slices/adminSlice";
import { useDispatch } from "react-redux";
import {
Box,
Button,
dividerClasses,
IconButton,
listClasses,
Menu,
} from "@mui/material";
import { Box, Button, IconButton, Menu } from "@mui/material";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import DeleteModal from "../Modals/DeleteModal";
import { useDispatch } from "react-redux"; // Correct the import for dispatch
import { AppDispatch } from "../../redux/store/store";
import ViewModal from "../Modals/ViewModal";
// Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: " #1565c0",
@ -50,17 +38,22 @@ export interface Column {
interface Row {
[key: string]: any;
status: number;
statusValue: any;
}
interface CustomTableProps {
columns: Column[];
rows: Row[];
setDeleteModal: Function;
setRowData: Function;
setModalOpen: Function;
// setRowData: Function;
// setModalOpen: Function;
viewModal: boolean;
setViewModal: Function;
deleteModal: boolean;
setRowData: React.Dispatch<React.SetStateAction<any>>; // Adjust this type if needed
setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
handleStatusToggle: (id: string, currentStatus: number) => void;
}
const CustomTable: React.FC<CustomTableProps> = ({
@ -72,43 +65,28 @@ const CustomTable: React.FC<CustomTableProps> = ({
setRowData,
setViewModal,
setModalOpen,
handleStatusToggle,
}) => {
const dispatch = useDispatch<AppDispatch>();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [selectedRow, setSelectedRow] = React.useState<Row | null>(null);
const open = Boolean(anchorEl);
///const dispatch = useDispatch(); // Initialize dispatch
// Handle menu actions
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
setAnchorEl(event.currentTarget);
setSelectedRow(row); // Ensure the row data is set
setSelectedRow(row);
};
const handleClose = () => {
setAnchorEl(null);
};
const isImage = (value: any) => {
if (typeof value === "string") {
return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image
}
return false;
};
const handleDeleteButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id);
dispatch(deleteAdmin(id || ""));
setDeleteModal(false); // Close the modal only after deletion
handleClose();
};
const handleViewButton = (id: string | undefined) => {
if (!id) console.error("ID not found", id);
dispatch(adminList());
setViewModal(false);
};
const dispatch = useDispatch<AppDispatch>();
// Handle status toggle logic
// const handleStatusToggle = (id: string, status: number) => {
// dispatch(toggleStatus({ id, status })); // Dispatch the action to update status
// };
return (
<Box sx={{ overflowX: "auto", width: "100%" }}>
@ -119,11 +97,7 @@ const CustomTable: React.FC<CustomTableProps> = ({
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
fontSize: { xs: "12px", sm: "14px" }, // Responsively adjust font size
}}
align={column.align}
>
{column.label}
</StyledTableCell>
@ -136,33 +110,15 @@ const CustomTable: React.FC<CustomTableProps> = ({
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
fontSize: {
xs: "12px",
sm: "14px",
}, // Responsively adjust font size
}}
align={column.align}
>
{isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: "50px",
height: "50px",
objectFit: "cover",
}}
/>
) : column.id !== "action" ? (
{column.id !== "action" ? (
row[column.id]
) : (
<IconButton
onClick={(e) => {
handleClick(e, row);
setRowData(row); // Store the selected row
}}
onClick={(e) =>
handleClick(e, row)
}
>
<MoreVertRoundedIcon />
</IconButton>
@ -176,98 +132,46 @@ const CustomTable: React.FC<CustomTableProps> = ({
</TableContainer>
{/* Menu Actions */}
{open && (
{open && selectedRow && (
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{
[`& .${listClasses.root}`]: {
padding: "4px",
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: "4px -4px",
},
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "flex-start",
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
setViewModal(true);
}}
>
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
setViewModal(true);
}}
color="primary"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
View
</Button>
{viewModal && (
<ViewModal
handleView={() =>
handleViewButton(selectedRow?.id)
}
open={viewModal}
setViewModal={setViewModal}
id={selectedRow?.id}
/>
)}
<Button
variant="text"
onClick={() => setModalOpen(true)}
color="primary"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
Edit
</Button>
View
</Button>
<Button variant="text" onClick={() => setModalOpen(true)}>
Edit
</Button>
{/* This button now toggles the status based on the current status */}
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
const newStatus = selectedRow?.status === 0 ? 0 : 1;
handleStatusToggle(selectedRow?.id, newStatus);
}}
>
{selectedRow?.status === 1 ? "Deactivate" : "Activate"}
</Button>
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
setDeleteModal(true);
}}
color="error"
sx={{
justifyContent: "flex-start",
py: 0,
textTransform: "capitalize",
}}
>
Delete
</Button>
{deleteModal && (
<DeleteModal
handleDelete={() =>
handleDeleteButton(selectedRow?.id)
}
open={deleteModal}
setDeleteModal={setDeleteModal}
id={selectedRow?.id}
/>
)}
</Box>
<Button
variant="text"
onClick={(e) => {
e.stopPropagation();
setDeleteModal(true);
}}
>
Delete
</Button>
</Menu>
)}
</Box>

View file

@ -41,7 +41,7 @@ export default function Header() {
sx={{
width: "360px",
height: "44px",
backgroundColor: "#303030",
backgroundColor: "#FFFFFF",
borderRadius: "8px",
border: "1px solid #424242",
display: "flex",
@ -49,9 +49,9 @@ export default function Header() {
padding: "0 12px",
}}
>
<SearchIcon sx={{ color: "#FFFFFF" }} />
<SearchIcon sx={{ color: "#202020" }} />
<InputBase
sx={{ marginLeft: 1, flex: 1, color: "#FFFFFF" }}
sx={{ marginLeft: 1, flex: 1, color: "#202020" }}
/>
</Box>
@ -66,22 +66,22 @@ export default function Header() {
<NotificationsRoundedIcon />
</MenuButton>
<Divider flexItem sx={{ backgroundColor: "#424242" }} />
<Divider flexItem sx={{ backgroundColor: "#202020" }} />
<Stack direction="row" spacing={1.5} alignItems="center">
<Avatar
alt="User Avatar"
src="/avatar.png"
sx={{ width: 36, height: 36 }}
/>
<Typography variant="body1" sx={{ color: "#FFFFFF" }}>
<Typography variant="body1" sx={{ color: "#202020" }}>
Momah
</Typography>
{/* Dropdown Icon */}
<ArrowDropDownIcon
sx={{ color: "#FFFFFF", width: 16, height: 16 }}
sx={{ color: "#202020", width: 16, height: 16 }}
/>
</Stack>
<ColorModeIconDropdown />
{/* <ColorModeIconDropdown /> */}
</Stack>
{showNotifications && (
<Box

View file

@ -43,20 +43,20 @@ export default function LineChartCard() {
return (
<Card
variant="outlined"
sx={{ width: "100%", height: "100%", backgroundColor: "#202020" }}
sx={{ width: "100%", height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<div
style={{
display: "flex",
alignItems: "center",
color: "#FFFFFF",
color: "#202020",
}}
>
<Typography
variant="h6"
align="left"
color="#FFFFFF"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
@ -70,7 +70,7 @@ export default function LineChartCard() {
sx={{
mt: 2,
mb: 2,
backgroundColor: "#3B3B3B",
backgroundColor: "#FFFFFF",
marginLeft: "auto",
marginRight: "16px",
display: "flex",
@ -90,13 +90,13 @@ export default function LineChartCard() {
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#F2F2F2",
color: "#202020",
p: "4px",
}}
>
Weekly
</Typography>
<ArrowDropDownIcon sx={{ color: "#F2F2F2" }} />
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
</div>

View file

@ -32,12 +32,21 @@ export default function ResourcePieChart() {
flexGrow: 1,
width: "100%",
height: "100%",
backgroundColor: "#202020",
backgroundColor: "#F2F2F2",
}}
>
<CardContent>
<Typography component="h2" variant="subtitle2" color="#F2F2F2">
<Typography
component="h2"
variant="subtitle2"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
Resources
</Typography>
<Box sx={{ display: "flex", alignItems: "center" }}>
@ -84,7 +93,7 @@ export default function ResourcePieChart() {
borderRadius: "50%",
}}
/>
<Typography variant="body2" color="#F2F2F2">
<Typography variant="body2" color="#202020">
{entry.title}
</Typography>
</Stack>

View file

@ -12,16 +12,15 @@ export default function SessionsChart() {
sx={{
width: "100%",
height: "100%",
backgroundColor: "#202020",
p: 2,
backgroundColor: "#F2F2F2",
p: 2,
}}
>
<CardContent>
<Typography
variant="h6"
align="left"
color="#FFFFFF"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
@ -37,7 +36,7 @@ export default function SessionsChart() {
sx={{
mt: 2,
mb: 2,
backgroundColor: "#3B3B3B",
backgroundColor: "#FFFFFF",
fontSize: "14px",
lineHeight: "20px",
width: { xs: "100%" },
@ -56,13 +55,13 @@ export default function SessionsChart() {
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#F2F2F2",
color: "#202020",
p: "4px",
}}
>
Delhi NCR EV Station
</Typography>
<ArrowDropDownIcon sx={{ color: "#F2F2F2" }} />
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
{/* Grid container for the four boxes */}
@ -87,8 +86,8 @@ export default function SessionsChart() {
height: "84px",
borderRadius: "8px",
p: "12px 16px",
backgroundColor: "#3B3B3B",
color: "#F2F2F2",
backgroundColor: "#FFFFFF",
color: "#202020",
}}
>
<Typography

View file

@ -18,13 +18,13 @@ export default function StatCard({ title, value }: StatCardProps) {
return (
<Card
variant="outlined"
sx={{ height: "100%", backgroundColor: "#2C2C2C" }}
sx={{ height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<Typography
component="h2"
variant="subtitle2"
color="#F2F2F2"
color="#202020"
gutterBottom
>
{title}
@ -32,7 +32,7 @@ export default function StatCard({ title, value }: StatCardProps) {
<Typography
component="h1"
variant="body1"
color="#F2F2F2"
color="#202020"
fontSize={30}
fontWeight={700}
gutterBottom

View file

@ -30,20 +30,20 @@ export default function RoundedBarChart() {
return (
<Card
variant="outlined"
sx={{ width: "100%", height: "100%", backgroundColor: "#202020" }}
sx={{ width: "100%", height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<div
style={{
display: "flex",
alignItems: "center",
color: "#FFFFFF",
color: "#202020",
}}
>
<Typography
variant="h6"
align="left"
color="#FFFFFF"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
@ -57,7 +57,7 @@ export default function RoundedBarChart() {
sx={{
mt: 2,
mb: 2,
backgroundColor: "#3B3B3B",
backgroundColor: "#FFFFFF",
marginLeft: "auto",
marginRight: "16px",
display: "flex",
@ -68,7 +68,7 @@ export default function RoundedBarChart() {
border: "1px solid #454545",
padding: "4px 8px",
color: "#FFFFFF",
color: "#202020",
}}
>
<Typography
@ -77,13 +77,13 @@ export default function RoundedBarChart() {
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#F2F2F2",
color: "#202020",
p: "4px",
}}
>
Monthly
</Typography>
<ArrowDropDownIcon sx={{ color: "#F2F2F2" }} />
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
</div>
<BarChart

View file

@ -13,10 +13,15 @@ import {
Grid,
FormControlLabel,
Button,
TextField,
Snackbar,
} from "@mui/material";
import { useNavigate } from "react-router-dom"; // Import useNavigate
// Define the data structure
import { useDispatch, useSelector } from "react-redux";
import { createRole } from "../../redux/slices/roleSlice"; // Import the createRole action
import { AppDispatch, RootState } from "../../redux/store/store"; // Assuming this is the path to your store file
import { toast } from "sonner";
// Define the data structure for permission
interface Permission {
module: string;
list: boolean;
@ -26,10 +31,10 @@ interface Permission {
delete: boolean;
}
// Sample data
// Initial sample data
const initialPermissions: Permission[] = [
{
module: "Role & Permission",
module: "User Management",
list: false,
add: false,
edit: false,
@ -37,84 +42,28 @@ const initialPermissions: Permission[] = [
delete: false,
},
{
module: "Staff",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Manage Users",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Business Type",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Category",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Orders",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Discounts",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Transaction History",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Commission",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
module: "Email Templates",
module: "Role Management",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
// Add other modules as needed
];
// Table component
const AddEditRolePage: React.FC = () => {
const [permissions, setPermissions] =
useState<Permission[]>(initialPermissions);
const [roleName, setRoleName] = useState<string>("");
const [openSnackbar, setOpenSnackbar] = useState(false); // For snackbar (success message)
const navigate = useNavigate(); // Initialize useNavigate
const dispatch = useDispatch<AppDispatch>(); // Type the dispatch function with AppDispatch
const { loading } = useSelector(
(state: RootState) => state.roleReducer.roles
);
// Handle checkbox change
const handleCheckboxChange = (module: string, action: keyof Permission) => {
@ -127,11 +76,57 @@ const AddEditRolePage: React.FC = () => {
);
};
// Handle role name input change
const handleRoleNameChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setRoleName(event.target.value);
};
// Handle Back Navigation
const handleBack = () => {
navigate("/panel/role-list"); // Navigate back to Role List
};
// Handle form submission (adding role)
const handleSubmit = async () => {
if (!roleName.trim()) {
alert("Role name is required");
return;
}
const newRole = {
name: roleName,
resource: permissions.map((perm) => ({
moduleName: perm.module,
permissions: [
perm.list ? "list" : "",
perm.add ? "add" : "",
perm.edit ? "edit" : "",
perm.view ? "view" : "",
perm.delete ? "delete" : "",
].filter(Boolean),
moduleId: perm.module, // Assuming the module name can serve as the moduleId or use a unique id
})),
};
try {
// Dispatch the createRole action to create the new role
await dispatch(createRole(newRole));
// Show success message
toast.success("Role created successfully!");
setOpenSnackbar(true);
// Reset the form
setRoleName("");
setPermissions(initialPermissions);
navigate("/panel/role-list");
} catch (error) {
console.error("Error creating role:", error);
toast.error("Error creating role. Please try again.");
}
};
return (
<Box
sx={{ width: "100%", maxWidth: 1200, margin: "auto", mt: 4, px: 2 }}
@ -161,6 +156,18 @@ const AddEditRolePage: React.FC = () => {
</Button>
</Box>
{/* Role Name Input */}
<Box sx={{ mb: 2 }}>
<TextField
label="Role Name"
value={roleName}
onChange={handleRoleNameChange}
fullWidth
variant="outlined"
sx={{ mb: 2 }}
/>
</Box>
{/* Table Container */}
<TableContainer
component={Paper}
@ -194,27 +201,22 @@ const AddEditRolePage: React.FC = () => {
},
}}
>
{/* Module Name */}
<TableCell sx={{ fontWeight: 500 }}>
{row.module}
</TableCell>
{/* Action Checkboxes */}
<TableCell>
<Grid
container
spacing={1}
justifyContent="space-between"
>
{(
[
"list",
"add",
"edit",
"view",
"delete",
] as (keyof Permission)[]
).map((action) => (
{[
"list",
"add",
"edit",
"view",
"delete",
].map((action) => (
<Grid item key={action}>
<FormControlLabel
control={
@ -225,7 +227,7 @@ const AddEditRolePage: React.FC = () => {
onChange={() =>
handleCheckboxChange(
row.module,
action
action as keyof Permission
)
}
sx={{
@ -249,6 +251,27 @@ const AddEditRolePage: React.FC = () => {
</TableBody>
</Table>
</TableContainer>
{/* Submit Button */}
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
<Button
variant="contained"
color="primary"
onClick={handleSubmit}
disabled={loading}
>
{loading ? "Saving..." : "Save Role"}
</Button>
</Box>
{/* Snackbar for success message */}
<Snackbar
open={openSnackbar}
autoHideDuration={3000}
onClose={() => setOpenSnackbar(false)}
message="Role added successfully!"
/>
</Box>
);
};

View file

@ -113,7 +113,7 @@ export default function AdminList() {
sx={{
width: "100%",
display: "flex",
flexDirection: { xs: "column", sm: "row" },
flexDirection: { xs: "column", sm: "row" },
justifyContent: "space-between",
alignItems: "center",
mb: 2, // Add margin bottom for spacing
@ -122,7 +122,7 @@ export default function AdminList() {
<Typography
component="h2"
variant="h6"
sx={{ fontWeight: 600, mb: { xs: 2, sm: 0 } }}
sx={{ fontWeight: 600, mb: { xs: 2, sm: 0 } }}
>
Admins
</Typography>
@ -131,7 +131,7 @@ export default function AdminList() {
size="medium"
sx={{
textAlign: "center",
width: { xs: "100%", sm: "auto" },
width: { xs: "100%", sm: "auto" },
}}
onClick={handleClickOpen}
>

View file

@ -0,0 +1,135 @@
import React, { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Checkbox,
Typography,
Box,
Grid,
FormControlLabel,
Button,
} from "@mui/material";
import { useNavigate } from "react-router-dom"; // Import useNavigate
// Define the data structure
interface Permission {
module: string;
list: boolean;
add: boolean;
edit: boolean;
view: boolean;
delete: boolean;
}
// Sample data
const initialPermissions: Permission[] = [
{ module: "Role & Permission", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Staff", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Manage Users", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Business Type", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Category", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Orders", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Discounts", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Transaction History", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Commission", list: false, add: false, edit: false, view: false, delete: false },
{ module: "Email Templates", list: false, add: false, edit: false, view: false, delete: false },
];
// Table component
const PermissionsTable: React.FC = () => {
const [permissions, setPermissions] = useState<Permission[]>(initialPermissions);
const navigate = useNavigate(); // Initialize useNavigate
// Handle checkbox change
const handleCheckboxChange = (module: string, action: keyof Permission) => {
setPermissions((prevPermissions) =>
prevPermissions.map((perm) =>
perm.module === module ? { ...perm, [action]: !perm[action] } : perm
)
);
};
// Handle Back Navigation
const handleBack = () => {
navigate("/panel/role-list"); // Navigate back to Role List
};
return (
<Box sx={{ width: "100%", maxWidth: 1200, margin: "auto", mt: 4, px: 2 }}>
{/* Title & Back Button Section */}
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
backgroundColor: "#1976D2",
color: "#fff",
p: 2,
borderRadius: "8px",
mb: 2,
}}
>
<Typography variant="h6" fontWeight={600}>
Role Permissions
</Typography>
<Button variant="contained" color="secondary" onClick={handleBack}>
Back
</Button>
</Box>
{/* Table Container */}
<TableContainer component={Paper} sx={{ borderRadius: "8px", overflow: "hidden" }}>
<Table>
{/* Table Head */}
<TableHead>
<TableRow sx={{ backgroundColor: "#f5f5f5" }}>
<TableCell sx={{ fontWeight: "bold", width: "30%" }}>Module Name</TableCell>
<TableCell sx={{ fontWeight: "bold", width: "70%" }}>
<Typography>Actions</Typography>
</TableCell>
</TableRow>
</TableHead>
{/* Table Body */}
<TableBody>
{permissions.map((row, index) => (
<TableRow key={index} sx={{ "&:nth-of-type(odd)": { backgroundColor: "#FAFAFA" } }}>
{/* Module Name */}
<TableCell sx={{ fontWeight: 500 }}>{row.module}</TableCell>
{/* Action Checkboxes */}
<TableCell>
<Grid container spacing={1} justifyContent="space-between">
{(["list", "add", "edit", "view", "delete"] as (keyof Permission)[]).map(
(action) => (
<Grid item key={action}>
<FormControlLabel
control={
<Checkbox
checked={row[action]}
onChange={() => handleCheckboxChange(row.module, action)}
sx={{ color: "#1976D2" }}
/>
}
label={action.charAt(0).toUpperCase() + action.slice(1)}
/>
</Grid>
)
)}
</Grid>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Box>
);
};
export default PermissionsTable;

View file

@ -1,3 +1,143 @@
import React, { useEffect, useState } from "react";
import { Box, Button, Typography, TextField, Chip } from "@mui/material";
import AddEditRoleModal from "../../components/AddEditRoleModal";
import PermissionsTable from "../../pages/PermissionTable";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import {
createRole,
roleList,
toggleStatus,
} from "../../redux/slices/roleSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useNavigate } from "react-router-dom";
import AddEditRolePage from "../AddEditRolePage";
export default function RoleList() {
const [modalOpen, setModalOpen] = useState(false);
const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
const [viewModal, setViewModal] = React.useState<boolean>(false);
const [rowData, setRowData] = React.useState<any | null>(null);
const [searchTerm, setSearchTerm] = useState("");
const [showPermissions, setShowPermissions] = useState(false);
const dispatch = useDispatch<AppDispatch>();
const navigate = useNavigate();
const roles = useSelector((state: RootState) => state.roleReducer.roles);
useEffect(() => {
dispatch(roleList());
}, [dispatch]);
const handleClickOpen = () => {
navigate("/panel/permissions"); // Navigate to the correct route
};
const handleCloseModal = () => {
setModalOpen(false);
setRowData(null);
reset();
};
const handleCreate = async (data: {
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
}) => {
try {
await dispatch(createRole(data));
await dispatch(roleList()); // Refresh the list after creation
handleCloseModal();
} catch (error) {
console.error("Creation failed", error);
}
};
const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" },
{ id: "name", label: "Name" },
{ id: "status", label: "Status" },
{ id: "action", label: "Action", align: "center" },
];
const categoryRows = roles?.map((role: Role, index: number) => ({
id: role.id,
srno: index + 1,
name: role.name,
status: (
<Chip
label={role.status === 1 ? "Active" : "Inactive"}
color={role.status === 1 ? "primary" : "default"}
variant="outlined"
sx={{
fontWeight: 600,
width: "80px",
textAlign: "center",
borderRadius: "4px",
}}
/>
),
statusValue: role.status,
}));
return (
<>
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
mb: 2,
}}
>
<TextField
variant="outlined"
size="small"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
sx={{ width: "30%" }}
/>
<Button
variant="contained"
size="small"
onClick={handleClickOpen}
>
Add Role
</Button>
</Box>
{showPermissions ? (
<AddEditRolePage />
) : (
<CustomTable
columns={categoryColumns}
rows={categoryRows}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setViewModal={setViewModal}
viewModal={viewModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
handleStatusToggle={(id, currentStatus) => {
// Correct logic to toggle between active and inactive
const updatedStatus = currentStatus === 1 ? 0 : 1;
dispatch(toggleStatus({ id, status: updatedStatus }));
}}
/>
)}
</>
);
}
// import React, { useEffect, useState } from "react";
// import { Box, Button, Typography } from "@mui/material";
// import AddEditRoleModal from "../../components/AddEditRoleModal";
@ -135,134 +275,3 @@
// </>
// );
// }
import React, { useEffect, useState } from "react";
import { Box, Button, Typography, TextField, Chip } from "@mui/material";
import AddEditRoleModal from "../../components/AddEditRoleModal";
import PermissionsTable from "../../pages/PermissionTable";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import { createRole, roleList } from "../../redux/slices/roleSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useNavigate } from "react-router-dom";
import AddEditRolePage from "../AddEditRolePage";
export default function RoleList() {
const [modalOpen, setModalOpen] = useState(false);
const { reset } = useForm();
const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
const [viewModal, setViewModal] = React.useState<boolean>(false);
const [rowData, setRowData] = React.useState<any | null>(null);
const [searchTerm, setSearchTerm] = useState("");
const [showPermissions, setShowPermissions] = useState(false);
const dispatch = useDispatch<AppDispatch>();
const navigate = useNavigate();
const roles = useSelector((state: RootState) => state.roleReducer.roles);
useEffect(() => {
dispatch(roleList());
}, [dispatch]);
const handleClickOpen = () => {
navigate("/panel/permissions"); // Navigate to the correct route
};
const handleCloseModal = () => {
setModalOpen(false);
setRowData(null);
reset();
};
const handleCreate = async (data: {
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
}) => {
try {
await dispatch(createRole(data));
await dispatch(roleList()); // Refresh the list after creation
handleCloseModal();
} catch (error) {
console.error("Creation failed", error);
}
};
const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" },
{ id: "name", label: "Name" },
{ id: "status", label: "Status" },
{ id: "action", label: "Action", align: "center" },
];
const categoryRows = roles?.map((role: Role, index: number) => ({
id: role.id,
srno: index + 1,
name: role.name,
status: (
<Chip
label={role.status === 1 ? "Active" : "Inactive"} // ✅ Convert number to text
color={role.status === 1 ? "primary" : "default"}
variant="outlined"
sx={{
fontWeight: 600,
width: "80px",
textAlign: "center",
borderRadius: "4px",
}}
/>
),
}));
console.log("Category Rows:", categoryRows);
return (
<>
<Box
sx={{
width: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
mb: 2,
}}
>
<TextField
variant="outlined"
size="small"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
sx={{ width: "30%" }}
/>
<Button
variant="contained"
size="small"
onClick={handleClickOpen}
>
Add Role
</Button>
</Box>
{showPermissions ? (
<AddEditRolePage />
) : (
<CustomTable
columns={categoryColumns}
rows={categoryRows}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setViewModal={setViewModal}
viewModal={viewModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
/>
)}
</>
);
}

View file

@ -761,7 +761,7 @@ export default function UserList() {
id: string;
name: string;
email: string;
phone: string;
// location?: string;
// managerAssigned?: string;

View file

@ -12,6 +12,7 @@ interface Role {
moduleId: string;
permissions: string[];
}[];
status: number;
}
interface RoleState {
@ -71,6 +72,22 @@ export const createRole = createAsyncThunk<
}
});
export const toggleStatus = createAsyncThunk<
Role,
{ id: string; status: number }, // status now expects a number (0 or 1)
{ rejectValue: string }
>("/toggleRoleStatus", async ({ id, status }, { rejectWithValue }) => {
try {
const response = await http.patch(`${id}`, { status });
console.log("API Response:", response.data);
return response.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
const roleSlice = createSlice({
name: "fetchRoles",
initialState,
@ -108,7 +125,28 @@ const roleSlice = createSlice({
state.loading = false;
state.error = action.payload || "Failed to create role";
}
);
)
.addCase(
toggleStatus.fulfilled,
(state, action: PayloadAction<Role>) => {
state.loading = false;
const updatedRole = action.payload;
const index = state.roles.findIndex(
(role) => role.id === updatedRole.id
);
if (index >= 0) {
state.roles[index] = {
...state.roles[index],
status: updatedRole.status,
};
}
}
)
.addCase(toggleStatus.rejected, (state, action) => {
state.loading = false;
state.error = action.payload || "Failed to toggle role status";
});
},
});

View file

@ -14,6 +14,7 @@ const AdminList = lazy(() => import("./pages/AdminList"));
const ProfilePage = lazy(() => import("./pages/ProfilePage"));
const NotFoundPage = lazy(() => import("./pages/NotFound"));
const UserList = lazy(() => import("./pages/UserList"));
const PermissionsTable = lazy(() => import("./pages/PermissionTable"));
interface ProtectedRouteProps {
caps: string[];