Merge pull request 'frontend/apiIntegration' (#14) from frontend/apiIntegration into develop

Reviewed-on: DigiMantra/digiev_frontend#14
This commit is contained in:
Mohit kalshan 2025-03-03 11:51:12 +00:00
commit 1d9c5bccf9
21 changed files with 876 additions and 981 deletions

View file

@ -6,10 +6,12 @@ import {
DialogActions,
DialogContent,
DialogTitle,
IconButton,
TextField,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import { Visibility, VisibilityOff } from "@mui/icons-material";
//By Jaanvi : Edit Model :: 11-feb-25
interface AddEditCategoryModalProps {
@ -86,6 +88,8 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
}
}, [editRow, setValue, reset]);
const [showPassword, setShowPassword] = React.useState(false);
return (
<Dialog
open={open}
@ -172,26 +176,58 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
/>
)}
/>
<Controller
name="password"
control={control}
rules={{
required: "password is required",
}}
render={({ field }) => (
<TextField
{...field}
required
margin="dense"
label="Password"
type="password"
fullWidth
variant="standard"
error={!!errors.password}
helperText={errors.password?.message}
/>
)}
/>
{!editRow && (
<Controller
name="password"
control={control}
rules={{
required: "password is required",
}}
render={({ field }) => (
<>
<Box sx={{position:"relative" }}>
<TextField
{...field}
required
margin="dense"
label="Password"
type={showPassword ? "text" : "password"}
id="password"
autoComplete="current-password"
autoFocus
fullWidth
variant="standard"
error={!!errors.password}
helperText={errors.password?.message}
/>
<IconButton
sx={{
position: "absolute",
top: "60%",
right: "10px",
background: "none",
borderColor: "transparent",
transform: "translateY(-50%)",
"&:hover": {
backgroundColor: "transparent",
borderColor: "transparent",
},
}}
onClick={() =>
setShowPassword((prev) => !prev)
}
>
{showPassword ? (
<VisibilityOff />
) : (
<Visibility />
)}
</IconButton>
</Box>
</>
)}
/>
)}
<Controller
name="phone"
control={control}

View file

@ -1,300 +0,0 @@
import React, { useEffect } from "react";
import {
Box,
Button,
Checkbox,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
FormControlLabel,
FormHelperText,
FormLabel,
InputLabel,
MenuItem,
Select,
TextField,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
interface AddRoleModalProps {
open: boolean;
handleClose: () => void;
handleCreate: (data: FormData) => void;
handleUpdate: (
id: string,
name: string,
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[]
) => void;
editRow: any;
data: {
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
}; // Assuming `data` is passed as a prop
}
interface FormData {
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
}
const AddRoleModal: React.FC<AddRoleModalProps> = ({
open,
handleClose,
handleCreate,
handleUpdate,
editRow,
data,
}) => {
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
getValues, // Access getValues from the form methods here
} = useForm<FormData>({
defaultValues: {
name: "",
resource: [], // Ensure resource is initialized as an empty array
},
});
useEffect(() => {
if (editRow) {
setValue("name", editRow.name);
setValue("resource", editRow.resource);
}
}, [editRow, setValue]);
// Handles permissions checkbox change for a specific resource
const handlePermissionChange = (
resourceIndex: number,
permission: string,
checked: boolean
) => {
const updatedResources = [...getValues().resource]; // Use getValues to get the current form values
const resource = updatedResources[resourceIndex];
if (checked) {
// Add permission if checked
resource.permissions = [
...new Set([...resource.permissions, permission]),
];
} else {
// Remove permission if unchecked
resource.permissions = resource.permissions.filter(
(p) => p !== permission
);
}
setValue("resource", updatedResources); // Update the resource field in form state
};
const onSubmit = (data: FormData) => {
if (editRow) {
handleUpdate(editRow.id, data.name, data.resource);
} else {
handleCreate(data);
}
handleClose();
reset();
};
return (
<Dialog
open={open}
onClose={handleClose}
maxWidth="md"
fullWidth
PaperProps={{
component: "form",
onSubmit: handleSubmit(onSubmit),
}}
>
<DialogTitle
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
{editRow ? "Edit Role" : "Add Role"}
<Box
onClick={handleClose}
sx={{
cursor: "pointer",
display: "flex",
alignItems: "center",
}}
>
<CloseIcon />
</Box>
</DialogTitle>
<DialogContent>
{/* Role Name Field */}
<Controller
name="name"
control={control}
rules={{
required: "Role Name is required",
minLength: {
value: 3,
message: "Minimum 3 characters required",
},
maxLength: {
value: 30,
message: "Maximum 30 characters allowed",
},
}}
render={({ field }) => (
<TextField
{...field}
autoFocus
required
margin="dense"
label="Role Name"
type="text"
fullWidth
variant="standard"
error={!!errors.name}
helperText={errors.name?.message}
/>
)}
/>
{/* Resource Field */}
<Controller
name="resource"
control={control}
rules={{ required: "Resource is required" }}
render={({ field }) => (
<FormControl
fullWidth
margin="dense"
error={!!errors.resource}
>
<InputLabel>Resource</InputLabel>
<Select
{...field}
label="Resource"
required
fullWidth
variant="standard"
>
{/* Mapping over the resource array to display the options */}
{data.resource?.map((resourceItem, index) => (
<MenuItem
key={index}
value={resourceItem.moduleId}
>
{resourceItem.moduleName}
</MenuItem>
))}
</Select>
<FormHelperText>
{errors.resource?.message}
</FormHelperText>
</FormControl>
)}
/>
{/* Permissions Checkbox Fields for each resource */}
{getValues().resource &&
getValues().resource.length > 0 &&
getValues().resource.map((resource, resourceIndex) => (
<React.Fragment key={resourceIndex}>
<FormControl fullWidth margin="dense">
<FormLabel>
{resource.moduleName} Permissions
</FormLabel>
<FormControlLabel
control={
<Checkbox
value="view"
checked={resource.permissions.includes(
"view"
)}
onChange={(e) =>
handlePermissionChange(
resourceIndex,
"view",
e.target.checked
)
}
/>
}
label="View"
/>
<FormControlLabel
control={
<Checkbox
value="edit"
checked={resource.permissions.includes(
"edit"
)}
onChange={(e) =>
handlePermissionChange(
resourceIndex,
"edit",
e.target.checked
)
}
/>
}
label="Edit"
/>
<FormControlLabel
control={
<Checkbox
value="delete"
checked={resource.permissions.includes(
"delete"
)}
onChange={(e) =>
handlePermissionChange(
resourceIndex,
"delete",
e.target.checked
)
}
/>
}
label="Delete"
/>
<FormHelperText>
{
errors.resource?.[resourceIndex]
?.permissions?.message
}
</FormHelperText>
</FormControl>
</React.Fragment>
))}
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">{editRow ? "Update" : "Create"}</Button>
</DialogActions>
</Dialog>
);
};
export default AddRoleModal;

View file

@ -73,7 +73,7 @@ export default function AppNavbar() {
Dashboard
</Typography>
</Stack>
<ColorModeIconDropdown />
{/* <ColorModeIconDropdown /> */}
<MenuButton aria-label="menu" onClick={toggleDrawer(true)}>
<MenuRoundedIcon />
</MenuButton>

View file

@ -61,6 +61,8 @@ interface CustomTableProps {
viewModal: boolean;
setViewModal: Function;
deleteModal: boolean;
handleStatusToggle: (id: string, currentStatus: number) => void;
tableType?: string;
}
const CustomTable: React.FC<CustomTableProps> = ({
@ -72,8 +74,9 @@ const CustomTable: React.FC<CustomTableProps> = ({
setRowData,
setViewModal,
setModalOpen,
handleStatusToggle,
tableType,
}) => {
// console.log("columnsss", columns, rows)
const dispatch = useDispatch<AppDispatch>();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [selectedRow, setSelectedRow] = React.useState<Row | null>(null);
@ -83,6 +86,7 @@ const CustomTable: React.FC<CustomTableProps> = ({
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
setAnchorEl(event.currentTarget);
setSelectedRow(row); // Ensure the row data is set
setRowData(row);
};
const handleClose = () => {
@ -111,57 +115,96 @@ const CustomTable: React.FC<CustomTableProps> = ({
setViewModal(false);
};
const handleToggleStatus = () => {
if (selectedRow) {
// Toggle the opposite of current status
const newStatus = selectedRow.statusValue === 1 ? 0 : 1;
handleStatusToggle(selectedRow.id, newStatus);
}
handleClose();
};
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
>
{column.label}
</StyledTableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, rowIndex) => (
<StyledTableRow key={rowIndex}>
<Box sx={{ overflowX: "auto", width: "100%" }}>
<TableContainer component={Paper}>
<Table
sx={{
minWidth: 700,
width: "100%",
tableLayout: "auto",
}}
aria-label="customized table"
>
<TableHead>
<TableRow>
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
// fontSize: { xs: "12px", sm: "14px" },
fontSize: {
xs: "10px",
sm: "12px",
md: "14px",
}, // Adjust font size responsively
padding: { xs: "8px", sm: "12px" },
}}
>
{isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: "50px",
height: "50px",
objectFit: "cover",
}}
/>
) : column.id !== "action" ? (
row[column.id]
) : (
<IconButton
onClick={(e) => {
handleClick(e, row);
setRowData(row); // Store the selected row
}}
>
<MoreVertRoundedIcon />
</IconButton>
)}
{column.label}
</StyledTableCell>
))}
</StyledTableRow>
))}
</TableBody>
</Table>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, rowIndex) => (
<StyledTableRow key={rowIndex}>
{columns.map((column) => (
<StyledTableCell
key={column.id}
align={column.align || "left"}
sx={{
whiteSpace: "nowrap", // Prevent wrapping
fontSize: {
xs: "10px",
sm: "12px",
md: "14px",
}, // Adjust font size responsively
padding: { xs: "8px", sm: "12px" },
}}
>
{isImage(row[column.id]) ? (
<img
src={row[column.id]}
alt="Row "
style={{
width: "50px",
height: "50px",
objectFit: "cover",
}}
/>
) : column.id !== "action" ? (
row[column.id]
) : (
<IconButton
onClick={(e) => {
handleClick(e, row);
setRowData(row); // Store the selected row
}}
>
<MoreVertRoundedIcon />
</IconButton>
)}
</StyledTableCell>
))}
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
{/* Menu Actions */}
{open && (
<Menu
anchorEl={anchorEl}
@ -228,6 +271,14 @@ const CustomTable: React.FC<CustomTableProps> = ({
Edit
</Button>
{tableType === "roleList" && (
<Button variant="text" onClick={handleToggleStatus}>
{selectedRow.statusValue === 1
? "Deactivate"
: "Activate"}
</Button>
)}
<Button
variant="text"
onClick={(e) => {
@ -256,7 +307,7 @@ const CustomTable: React.FC<CustomTableProps> = ({
</Box>
</Menu>
)}
</TableContainer>
</Box>
);
};

View file

@ -12,10 +12,10 @@ import ColorModeIconDropdown from "../../shared-theme/ColorModeIconDropdown";
import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
export default function Header() {
const [showNotifications, setShowNotifications] = React.useState(false);
const toggleNotifications = () => {
setShowNotifications((prev) => !prev);
};
const [showNotifications, setShowNotifications] = React.useState(false);
const toggleNotifications = () => {
setShowNotifications((prev) => !prev);
};
return (
<Box
@ -27,6 +27,7 @@ export default function Header() {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexDirection: { xs: "column", sm: "row" },
}}
>
<Box sx={{ flexGrow: 1 }} />
@ -35,13 +36,18 @@ export default function Header() {
spacing={3}
alignItems="center"
justifyContent="flex-end"
sx={{
width: "100%",
justifyContent: { xs: "center", sm: "flex-end" },
marginTop: { xs: 2, sm: 0 },
}}
>
{/* Search Bar */}
<Box
sx={{
width: "360px",
width: { xs: "100%", sm: "360px" },
height: "44px",
backgroundColor: "#303030",
backgroundColor: "#FFFFFF",
borderRadius: "8px",
border: "1px solid #424242",
display: "flex",
@ -49,14 +55,26 @@ 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",
fontSize: { xs: "12px", sm: "14px" },
}}
/>
</Box>
{/* Notification and Profile Section */}
<Stack direction="row" spacing={2} alignItems="center">
<Stack
direction="row"
spacing={2}
alignItems="center"
sx={{
display: { xs: "none", sm: "flex" }, // Hide on mobile, show on larger screens
}}
>
{/* Custom Bell Icon */}
<MenuButton
showBadge
@ -66,22 +84,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
@ -89,12 +107,13 @@ export default function Header() {
p: 2,
position: "absolute",
top: "55px",
right: "280px",
right: { xs: "10px", sm: "280px" },
bgcolor: "#FFFFFF",
boxShadow: 1,
borderRadius: 1,
zIndex: 1300,
cursor: "pointer",
width: "250px",
}}
>
{/* <Typography variant="h6" color="text.primary">

View file

@ -43,20 +43,20 @@ export default function LineChartCard() {
return (
<Card
variant="outlined"
sx={{ width: "100%", height: 400, 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

@ -47,6 +47,7 @@ export default function MainGrid() {
container
spacing={2}
columns={12}
sx={{ mb: (theme) => theme.spacing(2) }}
>
{data.map((card, index) => (

View file

@ -13,35 +13,10 @@ import { RootState } from "../../redux/store/store";
import DashboardOutlinedIcon from "@mui/icons-material/DashboardOutlined";
import ManageAccountsOutlinedIcon from "@mui/icons-material/ManageAccountsOutlined";
const baseMenuItems = [
{
text: "Dashboard",
icon: <DashboardOutlinedIcon />,
url: "/panel/dashboard",
},
{
text: "Admins",
icon: <AnalyticsRoundedIcon />,
url: "/panel/admin-list",
},
{
text: "Users",
icon: <AnalyticsRoundedIcon />,
url: "/panel/user-list",
},
{
text: "Roles",
icon: <AnalyticsRoundedIcon />,
url: "/panel/role-list",
},
];
//Eknoor singh and Jaanvi
//date:- 12-Feb-2025
//Made a different variable for super admin to access all the details.
type PropType = {
hidden: boolean;
};
@ -51,24 +26,34 @@ export default function MenuContent({ hidden }: PropType) {
const userRole = useSelector(
(state: RootState) => state.profileReducer.user?.userType
);
const baseMenuItems = [
{
text: "Dashboard",
icon: <DashboardOutlinedIcon />,
url: "/panel/dashboard",
},
userRole === "superadmin" && {
text: "Admins",
icon: <AnalyticsRoundedIcon />,
url: "/panel/admin-list",
},
userRole === "admin" && {
text: "Users",
icon: <AnalyticsRoundedIcon />,
url: "/panel/user-list",
},
userRole === "superadmin" && {
text: "Roles",
icon: <AnalyticsRoundedIcon />,
url: "/panel/role-list",
},
];
// const mainListItems = [
// ...baseMenuItems,
// // ...(userRole === "superadmin"
// // ? [
// // // {
// // // text: "Admin List",
// // // icon: <ManageAccountsOutlinedIcon />,
// // // url: "/panel/admin-list",
// // // },
// // ]
// // : []),
// ];
const filteredMenuItems = baseMenuItems.filter(Boolean);
return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
<List dense>
{baseMenuItems.map((item, index) => (
{filteredMenuItems.map((item, index) => (
<ListItem
key={index}
disablePadding

View file

@ -31,12 +31,22 @@ export default function ResourcePieChart() {
gap: "8px",
flexGrow: 1,
width: "100%",
height: "90%",
backgroundColor: "#202020",
height: "100%",
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" }}>
@ -83,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

@ -11,16 +11,16 @@ export default function SessionsChart() {
variant="outlined"
sx={{
width: "100%",
height: "90%",
backgroundColor: "#202020",
p: 2,
height: "100%",
backgroundColor: "#F2F2F2",
p: 2,
}}
>
<CardContent>
<Typography
variant="h6"
align="left"
color="#FFFFFF"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
@ -36,7 +36,7 @@ export default function SessionsChart() {
sx={{
mt: 2,
mb: 2,
backgroundColor: "#3B3B3B",
backgroundColor: "#FFFFFF",
fontSize: "14px",
lineHeight: "20px",
width: { xs: "100%" },
@ -55,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 */}
@ -86,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,34 +30,34 @@ export default function RoundedBarChart() {
return (
<Card
variant="outlined"
sx={{ width: "100%", height: 400, 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"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
variant="h6"
align="left"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
Charge Stats
</Typography>
<Box
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
@ -91,6 +91,7 @@ export default function RoundedBarChart() {
height={300}
data={data}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
style={{ width: "100%", height: "auto" }}
>
<CartesianGrid vertical={false} />
<XAxis />

View file

@ -1,56 +1,72 @@
// src/common/components/Layout
import * as React from 'react';
import { Box, Stack } from '@mui/material';
import { Outlet } from 'react-router-dom';
import SideMenu from '../../components/SideMenu';
import AppNavbar from '../../components/AppNavbar';
import Header from '../../components/Header';
import AppTheme from '../../shared-theme/AppTheme';
import * as React from "react";
import { Box, Stack } from "@mui/material";
import { Outlet } from "react-router-dom";
import SideMenu from "../../components/SideMenu";
import AppNavbar from "../../components/AppNavbar";
import Header from "../../components/Header";
import AppTheme from "../../shared-theme/AppTheme";
interface LayoutProps {
customStyles?: React.CSSProperties;
customStyles?: React.CSSProperties;
}
const DashboardLayout: React.FC<LayoutProps> = ({ customStyles }) => {
return (
<AppTheme>
<Box sx={{ display: 'flex' }}>
<SideMenu />
<AppNavbar />
<Box
component="main"
sx={(theme) => ({
display: "flex",
height: '100vh',
flexGrow: 1,
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.background.defaultChannel} / 1)`
: theme.palette.background.default,
overflow: 'auto',
...customStyles,
})}
>
<Stack
spacing={2}
sx={{
display: "flex",
flex: 1,
justifyItems: "center",
return (
<AppTheme>
<Box
sx={{
display: "flex",
height: "100vh",
flexDirection: { xs: "column", md: "row" },
}}
>
{/* SideMenu - Responsive, shown only on large screens */}
<Box
sx={{
display: { xs: "none", md: "block" },
width: 250,
}}
>
<SideMenu />
</Box>
alignItems: 'center',
mx: 3,
pb: 5,
mt: { xs: 8, md: 0 },
}}
>
<Header />
<Outlet />
</Stack>
</Box>
</Box>
</AppTheme>
);
{/* Navbar - Always visible */}
<AppNavbar />
<Box
component="main"
sx={(theme) => ({
display: "flex",
flexDirection: "column",
height: "100vh",
flexGrow: 1,
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.background.defaultChannel} / 1)`
: theme.palette.background.default,
overflow: "auto",
...customStyles,
mt: { xs: 8, md: 0 },
})}
>
<Stack
spacing={2}
sx={{
display: "flex",
flex: 1,
justifyItems: "center",
alignItems: "center",
mx: 3,
pb: 5,
mt: { xs: 3, md: 0 },
}}
>
<Header />
<Outlet />
</Stack>
</Box>
</Box>
</AppTheme>
);
};
export default DashboardLayout;

View file

@ -0,0 +1,281 @@
import React, { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Checkbox,
Typography,
Box,
Grid,
FormControlLabel,
Button,
TextField,
Snackbar,
} from "@mui/material";
import { useNavigate } from "react-router-dom"; // Import useNavigate
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;
add: boolean;
edit: boolean;
view: boolean;
delete: boolean;
}
// Initial sample data
const initialPermissions: Permission[] = [
{
module: "User Management",
list: false,
add: false,
edit: false,
view: false,
delete: false,
},
{
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) => {
setPermissions((prevPermissions) =>
prevPermissions.map((perm) =>
perm.module === module
? { ...perm, [action]: !perm[action] }
: perm
)
);
};
// 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 }}
>
{/* 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>
{/* Role Name Input */}
<Box sx={{ mb: 2}}>
<label >Role Name</label>
<TextField
placeholder="Enter role name"
value={roleName}
onChange={handleRoleNameChange}
fullWidth
required
variant="outlined"
sx={{ mb: 2 ,mt:2}}
/>
</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",
},
}}
>
<TableCell sx={{ fontWeight: 500 }}>
{row.module}
</TableCell>
<TableCell>
<Grid
container
spacing={1}
justifyContent="space-between"
>
{[
"list",
"add",
"edit",
"view",
"delete",
].map((action) => (
<Grid item key={action}>
<FormControlLabel
control={
<Checkbox
checked={
row[action]
}
onChange={() =>
handleCheckboxChange(
row.module,
action as keyof Permission
)
}
sx={{
color: "#1976D2",
}}
/>
}
label={
action
.charAt(0)
.toUpperCase() +
action.slice(1)
}
/>
</Grid>
))}
</Grid>
</TableCell>
</TableRow>
))}
</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>
);
};
export default AddEditRolePage;

View file

@ -1,360 +1,5 @@
// import { useEffect, useState } from "react";
// import {
// Box,
// Button,
// Typography,
// TextField,
// InputAdornment,
// Paper,
// Table,
// TableBody,
// TableCell,
// TableContainer,
// TableHead,
// TableRow,
// Pagination,
// IconButton,
// } from "@mui/material";
// import SearchIcon from "@mui/icons-material/Search";
// import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
// import TuneIcon from "@mui/icons-material/Tune";
// import { useDispatch, useSelector } from "react-redux";
// import { adminList } from "../../redux/slices/adminSlice";
// import { AppDispatch, RootState } from "../../redux/store/store";
// export default function AdminList() {
// const [searchQuery, setSearchQuery] = useState("");
// const [currentPage, setCurrentPage] = useState(1);
// const adminsPerPage = 10;
// const dispatch = useDispatch<AppDispatch>();
// const admins = useSelector((state: RootState) => state.adminReducer.admins);
// useEffect(() => {
// dispatch(adminList());
// }, [dispatch]);
// const staticAdmins = [
// {
// name: "John Doe",
// location: "New York",
// managerAssigned: "Alice Johnson",
// vehicle: "Tesla Model S",
// phone: "+1 234 567 8901",
// },
// {
// name: "Jane Smith",
// location: "Los Angeles",
// managerAssigned: "Bob Brown",
// vehicle: "Ford F-150",
// phone: "+1 987 654 3210",
// },
// {
// name: "Michael Brown",
// location: "Chicago",
// managerAssigned: "Sarah Lee",
// vehicle: "Chevrolet Bolt",
// phone: "+1 312 555 7890",
// },
// {
// name: "Emily Davis",
// location: "Houston",
// managerAssigned: "Tom Wilson",
// vehicle: "Nissan Leaf",
// phone: "+1 713 444 5678",
// },
// {
// name: "Daniel Martinez",
// location: "Phoenix",
// managerAssigned: "Jessica White",
// vehicle: "BMW i3",
// phone: "+1 602 999 4321",
// },
// {
// name: "Sophia Miller",
// location: "Philadelphia",
// managerAssigned: "Mark Adams",
// vehicle: "Audi e-tron",
// phone: "+1 215 777 6543",
// },
// {
// name: "James Anderson",
// location: "San Antonio",
// managerAssigned: "Emma Thomas",
// vehicle: "Hyundai Kona EV",
// phone: "+1 210 321 8765",
// },
// {
// name: "James Anderson",
// location: "San Antonio",
// managerAssigned: "Emma Thomas",
// vehicle: "Hyundai Kona EV",
// phone: "+1 210 321 8765",
// },
// ];
// const adminData = admins.length ? admins : staticAdmins;
// const filteredAdmins = adminData.filter((admin) =>
// admin.name.toLowerCase().includes(searchQuery.toLowerCase())
// );
// const indexOfLastAdmin = currentPage * adminsPerPage;
// const indexOfFirstAdmin = indexOfLastAdmin - adminsPerPage;
// const currentAdmins = filteredAdmins.slice(
// indexOfFirstAdmin,
// indexOfLastAdmin
// );
// const handlePageChange = (event, value) => {
// setCurrentPage(value);
// };
// return (
// <Box
// sx={{
// width: "calc(100% - 48px)",
// margin: "0 auto",
// padding: "24px",
// backgroundColor: "#1C1C1C",
// borderRadius: "12px",
// }}
// >
// <Typography
// sx={{
// color: "#FFFFFF",
// fontWeight: 500,
// fontSize: "18px",
// fontFamily: "Gilroy",
// }}
// >
// Charge stations
// </Typography>
// {/* Search & Buttons Section */}
// <Box
// sx={{
// display: "flex",
// gap: "16px",
// marginTop: "16px",
// alignItems: "center",
// fontFamily: "Gilroy",
// }}
// >
// <TextField
// variant="outlined"
// placeholder="Search Charge stations"
// sx={{
// width: "422px",
// backgroundColor: "#272727",
// borderRadius: "12px",
// input: { color: "#FFFFFF" },
// "& .MuiOutlinedInput-root": {
// borderRadius: "12px",
// "& fieldset": { borderColor: "#FFFFFF" },
// "&:hover fieldset": { borderColor: "#FFFFFF" },
// "&.Mui-focused fieldset": {
// borderColor: "#52ACDF",
// },
// },
// }}
// InputProps={{
// startAdornment: (
// <InputAdornment position="start">
// <SearchIcon sx={{ color: "#FFFFFF" }} />
// </InputAdornment>
// ),
// }}
// value={searchQuery}
// onChange={(e) => setSearchQuery(e.target.value)}
// />
// <Box
// sx={{
// display: "flex",
// justifyContent: "flex-end",
// width: "100%",
// }}
// >
// <Button
// sx={{
// backgroundColor: "#52ACDF",
// color: "white",
// borderRadius: "8px",
// width: "184px",
// "&:hover": {
// backgroundColor: "#439BC1",
// },
// }}
// >
// Add Charge Stations
// </Button>
// </Box>
// <IconButton
// sx={{
// width: "44px",
// height: "44px",
// borderRadius: "8px",
// backgroundColor: "#272727",
// color: "#52ACDF",
// "&:hover": { backgroundColor: "#333333" },
// }}
// >
// <TuneIcon />
// </IconButton>
// </Box>
// {/* Table Section */}
// <TableContainer
// component={Paper}
// sx={{
// marginTop: "24px",
// backgroundColor: "#1C1C1C",
// borderRadius: "12px",
// overflow: "hidden",
// }}
// >
// <Table>
// <TableHead sx={{ backgroundColor: "#272727" }}>
// <TableRow>
// {[
// "Name",
// "Location",
// "Manager Assigned",
// "Vehicle",
// "Phone Number",
// "Action",
// ].map((header) => (
// <TableCell
// key={header}
// sx={{
// color: "#FFFFFF",
// fontWeight: "bold",
// }}
// >
// {header}
// </TableCell>
// ))}
// </TableRow>
// </TableHead>
// <TableBody>
// {currentAdmins.map((admin, index) => (
// <TableRow
// key={index}
// sx={{ backgroundColor: "#1C1C1C" }}
// >
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// {admin.name}
// </TableCell>
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// {admin.location || "N/A"}
// </TableCell>
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// {admin.managerAssigned || "N/A"}
// </TableCell>
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// {admin.vehicle || "N/A"}{" "}
// <Typography
// component="span"
// sx={{
// color: "#52ACDF",
// cursor: "pointer",
// textDecoration: "none",
// "&:hover": {
// textDecoration: "underline",
// },
// }}
// >
// +6 more
// </Typography>
// </TableCell>
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// {admin.phone}
// </TableCell>
// <TableCell
// sx={{
// color: "#FFFFFF",
// borderBottom: "1px solid #2A2A2A",
// }}
// >
// <IconButton size="small">
// <MoreHorizIcon
// sx={{ color: "#FFFFFF" }}
// />
// </IconButton>
// </TableCell>
// </TableRow>
// ))}
// </TableBody>
// </Table>
// </TableContainer>
// {/* Pagination */}
// <Box
// sx={{
// display: "flex",
// justifyContent: "flex-end",
// alignItems: "center",
// marginTop: "16px",
// width: "100%",
// gap: "8px",
// }}
// >
// <Typography
// sx={{ color: "white", fontSize: "16px", fontWeight: 500 }}
// >
// Page Number :
// </Typography>
// <Pagination
// count={Math.ceil(filteredAdmins.length / adminsPerPage)}
// page={currentPage}
// onChange={handlePageChange}
// siblingCount={0}
// boundaryCount={0}
// sx={{
// "& .MuiPaginationItem-root": {
// color: "white",
// borderRadius: "0px",
// },
// "& .MuiPaginationItem-page.Mui-selected": {
// backgroundColor: "transparent",
// fontWeight: "bold",
// color: "#FFFFFF",
// },
// }}
// />
// </Box>
// </Box>
// );
// }
import React, { useEffect, useState } from "react";
import { Box, Button, Typography } from "@mui/material";
import { Box, Button, TextField, Typography } from "@mui/material";
import AddEditCategoryModal from "../../components/AddEditCategoryModal";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
@ -365,6 +10,7 @@ import {
createAdmin,
} from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import SearchIcon from "@mui/icons-material/Search";
export default function AdminList() {
const [modalOpen, setModalOpen] = useState(false);
@ -377,7 +23,7 @@ export default function AdminList() {
const dispatch = useDispatch<AppDispatch>();
const admins = useSelector((state: RootState) => state.adminReducer.admins);
const [searchTerm, setSearchTerm] = useState("");
useEffect(() => {
dispatch(adminList());
}, [dispatch]);
@ -439,9 +85,18 @@ export default function AdminList() {
{ id: "registeredAddress", label: "Address" },
{ id: "action", label: "Action", align: "center" },
];
const filteredAdmins = admins?.filter(
(admin) =>
admin.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
admin.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
admin.phone.toLowerCase().includes(searchTerm.toLowerCase()) ||
admin.registeredAddress
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
const categoryRows = admins?.length
? admins?.map(
const categoryRows = filteredAdmins?.length
? filteredAdmins?.map(
(
admin: {
id: string;
@ -464,28 +119,55 @@ export default function AdminList() {
return (
<>
<Typography
component="h2"
variant="h6"
sx={{
fontWeight: 600,
mb: { xs: 2, sm: 0 },
width: "100%",
display: "flex",
}}
>
Admins
</Typography>
<Box
sx={{
width: "100%",
maxWidth: {
sm: "100%",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
},
display: "flex",
flexDirection: { xs: "column", sm: "row" },
justifyContent: "space-between",
alignItems: "center",
mb: 2, // Add margin bottom for spacing
}}
>
<Typography
component="h2"
variant="h6"
sx={{ mt: 2, fontWeight: 600 }}
>
Admins
</Typography>
<TextField
variant="outlined"
size="small"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
sx={{
width: { xs: "100%", sm: "30%" },
marginBottom: { xs: 2, sm: 0 },
}}
InputProps={{
startAdornment: (
<SearchIcon
sx={{ color: "#202020", marginRight: 1 }}
/>
),
}}
/>
<Button
variant="contained"
size="medium"
sx={{ textAlign: "right" }}
sx={{
textAlign: "center",
width: { xs: "100%", sm: "auto" },
}}
onClick={handleClickOpen}
>
Add Admin

View file

@ -12,11 +12,9 @@ import {
IconButton,
Link,
} from "@mui/material";
import { styled, useTheme } from "@mui/material/styles";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import { useDispatch } from "react-redux";
import { loginUser } from "../../../redux/slices/authSlice.ts";
import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
import AppTheme from "../../../shared-theme/AppTheme.tsx";
import ForgotPassword from "./ForgotPassword.tsx";
import { toast } from "sonner";
@ -24,24 +22,22 @@ import { useNavigate } from "react-router-dom";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Card, SignInContainer } from "./styled.css.tsx";
interface ILoginForm {
email: string;
password: string;
}
export default function Login(props: { disableCustomTheme?: boolean }) {
const [open, setOpen] = React.useState(false);
const [showPassword, setShowPassword] = React.useState(false);
const {
control,
handleSubmit,
formState: { errors },
setError,
} = useForm<ILoginForm>();
const dispatch = useDispatch();
const router = useNavigate();
const handleClickOpen = () => {
setOpen(true);
};
@ -64,45 +60,59 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
return (
<AppTheme {...props}>
{/* <CssBaseline enableColorScheme /> */}
<SignInContainer direction="column" justifyContent="space-between">
{/* <ColorModeSelect
sx={{ position: "fixed", top: "1rem", right: "1rem" }}
/> */}
<Grid container sx={{ height: "100vh" }}>
{/* Image Section */}
<Grid
item
xs={7}
xs={0}
sm={0}
md={7}
sx={{
background: `url('/mainPageLogo.png') center/cover no-repeat`,
height: { xs: "0%", sm: "0%", md: "100%" },
backgroundSize: "cover",
display: { xs: "none", md: "block" }, // Hide the image on xs and sm screens
}}
/>
{/* Form Section */}
<Grid
item
xs={5}
xs={12}
md={5}
sx={{
backgroundColor: "black",
display: "flex",
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
padding: { xs: "2rem", md: "3rem", lg: "3rem" },
height: "100%",
}}
>
<Typography
variant="h3"
sx={{
color: "white",
textAlign: "center",
fontSize: {
xs: "2rem",
sm: "2.2rem",
md: "36px",
},
}}
>
Welcome Back!
</Typography>
<Card variant="outlined">
{/* <SitemarkIcon /> */}
<Card
variant="outlined"
sx={{
maxWidth: "400px",
width: { xs: "80%", sm: "80%", md: "100%" },
}}
>
<Box
component="form"
onSubmit={handleSubmit(onSubmit)}
@ -110,7 +120,6 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
sx={{
display: "flex",
flexDirection: "column",
width: "100%",
gap: 2,
}}
>
@ -118,9 +127,9 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
component="h1"
variant="h4"
sx={{
width: "100%",
textAlign: "center",
color: "white",
fontSize: { xs: "1.5rem", sm: "2rem" },
}}
>
Login
@ -129,18 +138,22 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
component="h6"
variant="subtitle2"
sx={{
width: "100%",
textAlign: "center",
color: "white",
fontSize: { xs: "0.9rem", sm: "1rem" },
}}
>
Log in with your email and password
</Typography>
<FormControl>
<FormControl sx={{ width: "100%" }}>
<FormLabel
htmlFor="email"
sx={{
fontSize: "1rem",
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
color: "white",
}}
>
@ -173,22 +186,32 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
required
fullWidth
variant="outlined"
color={
errors.email
? "error"
: "primary"
}
sx={{
input: {
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
},
}}
/>
)}
/>
</FormControl>
<FormControl>
<FormControl sx={{ width: "100%" }}>
<FormLabel
htmlFor="password"
sx={{
fontSize: "1rem",
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
color: "white",
}}
>
@ -207,11 +230,7 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
},
}}
render={({ field }) => (
<Box
sx={{
position: "relative",
}}
>
<Box sx={{ position: "relative" }}>
<TextField
{...field}
error={!!errors.password}
@ -220,7 +239,11 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
}
name="password"
placeholder="Password"
type="password"
type={
showPassword
? "text"
: "password"
}
id="password"
autoComplete="current-password"
autoFocus
@ -266,6 +289,7 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
)}
/>
</FormControl>
<Box
sx={{
display: "flex",
@ -282,7 +306,6 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
}
label="Remember me"
/>
<Link
component="button"
type="button"
@ -303,8 +326,6 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
<Button
type="submit"
fullWidth
// variant="contained"
// color="primary"
sx={{
color: "white",
backgroundColor: "#52ACDF",
@ -316,26 +337,6 @@ export default function Login(props: { disableCustomTheme?: boolean }) {
>
Login
</Button>
{/* <Divider>or</Divider>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 2,
}}
>
<Typography sx={{ textAlign: "center" }}>
Don&apos;t have an account?{" "}
<Link
href="/signup"
variant="body2"
sx={{ alignSelf: "center" }}
>
Sign up
</Link>
</Typography>
</Box> */}
</Box>
</Card>
</Grid>

View file

@ -56,9 +56,7 @@ const ProfilePage = () => {
<Grid container spacing={2} alignItems="center">
<Grid item>
<Avatar
//Eknoor singh
//date:- 12-Feb-2025
//user is called for name and email
alt={user?.name || "User Avatar"}
src={"/static/images/avatar/7.jpg"}
sx={{ width: 80, height: 80 }}
@ -75,7 +73,7 @@ const ProfilePage = () => {
Phone: {user?.phone || "N/A"}
</Typography>
<Typography variant="body2" color="text.secondary">
Role: <b>{user?.role || "N/A"}</b>
Role: <b>{user?.userType || "N/A"}</b>
</Typography>
</Grid>
</Grid>

View file

@ -5,9 +5,15 @@ 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 {
createRole,
roleList,
toggleStatus,
} from "../../redux/slices/roleSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useNavigate } from "react-router-dom";
import AddEditRolePage from "../AddEditRolePage";
import SearchIcon from "@mui/icons-material/Search";
export default function RoleList() {
const [modalOpen, setModalOpen] = useState(false);
@ -38,6 +44,10 @@ export default function RoleList() {
reset();
};
const handleStatusToggle = (id: string, newStatus: number) => {
dispatch(toggleStatus({ id, status: newStatus }));
};
const handleCreate = async (data: {
name: string;
resource: {
@ -62,23 +72,31 @@ export default function RoleList() {
{ 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" }}
/>
),
}));
const filterRoles = roles?.filter((role) =>
role.name.toLocaleLowerCase().includes(searchTerm.toLowerCase())
);
console.log("Category Rows:", categoryRows);
const categoryRows = filterRoles?.length
? filterRoles?.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 (
<>
@ -86,9 +104,10 @@ export default function RoleList() {
sx={{
width: "100%",
display: "flex",
flexDirection: { xs: "column", sm: "row" },
justifyContent: "space-between",
alignItems: "center",
mb: 2,
mb: 2,
}}
>
<TextField
@ -97,34 +116,47 @@ export default function RoleList() {
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
sx={{ width: "30%" }}
sx={{
width: { xs: "100%", sm: "30%" },
marginBottom: { xs: 2, sm: 0 },
}}
InputProps={{
startAdornment: (
<SearchIcon
sx={{ color: "#202020", marginRight: 1 }}
/>
),
}}
/>
<Button variant="contained" size="small" onClick={handleClickOpen}>
<Button
variant="contained"
size="small"
onClick={handleClickOpen}
sx={{
textAlign: "center",
width: { xs: "100%", sm: "auto" },
}}
>
Add Role
</Button>
</Box>
{showPermissions ? (
<PermissionsTable />
<AddEditRolePage />
) : (
<CustomTable
columns={categoryColumns}
rows={categoryRows}
rows={categoryRows || []}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setViewModal={setViewModal}
viewModal={viewModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
handleStatusToggle={handleStatusToggle}
tableType="roleList"
/>
)}
<AddEditRoleModal
open={modalOpen}
handleClose={handleCloseModal}
handleCreate={handleCreate}
editRow={rowData}
/>
</>
);
}

View file

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

View file

@ -5,13 +5,14 @@ import { toast } from "sonner";
// Define TypeScript types
interface Role {
id: any;
id: string;
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
status: number;
}
interface RoleState {
@ -27,7 +28,7 @@ const initialState: RoleState = {
error: null,
};
export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
export const roleList = createAsyncThunk<any, void, { rejectValue: string }>(
"fetchRoles",
async (_, { rejectWithValue }) => {
try {
@ -36,11 +37,12 @@ export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
const response = await http.get("get");
if (!response.data?.data) throw new Error("Invalid API response");
if (!response.data) throw new Error("Invalid API response");
return response.data.data;
// Return the full response to handle in the reducer
return response.data;
} catch (error: any) {
toast.error("Error Fetching Roles" + error);
toast.error("Error Fetching Roles: " + error.message);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
@ -50,7 +52,7 @@ export const roleList = createAsyncThunk<Role[], void, { rejectValue: string }>(
// Create Role
export const createRole = createAsyncThunk<
Role,
any,
{
name: string;
resource: {
@ -60,19 +62,57 @@ export const createRole = createAsyncThunk<
}[];
},
{ rejectValue: string }
>("/CreateRole", async (data, { rejectWithValue }) => {
>("role/createRole", async (data, { rejectWithValue }) => {
try {
const response = await http.post("create", data);
toast.success("Role created successfully");
return response.data;
} catch (error: any) {
toast.error(
"Failed to create role: " +
(error.response?.data?.message || "Unknown error")
);
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
export const toggleStatus = createAsyncThunk<
any,
{ id: string; status: number },
{ rejectValue: string }
>("role/toggleStatus", async ({ id, status }, { rejectWithValue }) => {
try {
const response = await http.patch(`${id}`, { status });
if (response.data.statusCode === 200) {
toast.success(
response.data.message || "Status updated successfully"
);
// Return both the response data and the requested status for reliable state updates
return {
responseData: response.data,
id,
status,
};
} else {
throw new Error(response.data.message || "Failed to update status");
}
} catch (error: any) {
toast.error(
"Error updating status: " + (error.message || "Unknown error")
);
return rejectWithValue(
error.response?.data?.message ||
error.message ||
"An error occurred"
);
}
});
const roleSlice = createSlice({
name: "fetchRoles",
name: "roles",
initialState,
reducers: {},
extraReducers: (builder) => {
@ -85,7 +125,11 @@ const roleSlice = createSlice({
roleList.fulfilled,
(state, action: PayloadAction<any>) => {
state.loading = false;
state.roles = action.payload.results; // Extract results from response
// Properly extract roles from the response data structure
state.roles =
action.payload.data?.results ||
action.payload.data ||
[];
}
)
.addCase(roleList.rejected, (state, action) => {
@ -97,9 +141,12 @@ const roleSlice = createSlice({
})
.addCase(
createRole.fulfilled,
(state, action: PayloadAction<Role>) => {
(state, action: PayloadAction<any>) => {
state.loading = false;
state.roles.push(action.payload);
// Add the newly created role to the state if it exists in the response
if (action.payload.data) {
state.roles.push(action.payload.data);
}
}
)
.addCase(
@ -108,6 +155,37 @@ const roleSlice = createSlice({
state.loading = false;
state.error = action.payload || "Failed to create role";
}
)
.addCase(toggleStatus.pending, (state) => {
state.loading = true;
})
.addCase(
toggleStatus.fulfilled,
(state, action: PayloadAction<any>) => {
state.loading = false;
// Get the id and updated status from the action payload
const { id, status } = action.payload;
// Find and update the role with the new status
const roleIndex = state.roles.findIndex(
(role) => role.id === id
);
if (roleIndex !== -1) {
state.roles[roleIndex] = {
...state.roles[roleIndex],
status: status,
};
}
}
)
.addCase(
toggleStatus.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.loading = false;
state.error =
action.payload || "Failed to toggle role status";
}
);
},
});

View file

@ -3,6 +3,7 @@ import React, { lazy, Suspense } from "react";
import LoadingComponent from "./components/Loading";
import DashboardLayout from "./layouts/DashboardLayout";
import RoleList from "./pages/RoleList";
import AddEditRolePage from "./pages/AddEditRolePage";
// Page imports
const Login = lazy(() => import("./pages/Auth/Login"));
@ -94,12 +95,15 @@ export default function AppRouter() {
/>
}
/>
<Route
path="permissions"
element={<ProtectedRoute caps={[]} component={<PermissionsTable />} />}
/>
<Route
path="permissions"
element={
<ProtectedRoute
caps={[]}
component={<AddEditRolePage />}
/>
}
/>
<Route
path="profile"
element={