This commit is contained in:
Mohit kalshan 2025-03-03 17:33:26 +05:30
commit 13ac338091
37 changed files with 19494 additions and 1428 deletions

16095
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,7 @@
"@emotion/styled": "^11.14.0",
"@mui/icons-material": "^6.4.5",
"@mui/material": "^6.4.5",
"@mui/x-charts": "^7.27.0",
"@mui/x-charts": "^7.27.1",
"@mui/x-data-grid": "^7.27.0",
"@mui/x-date-pickers": "^7.27.0",
"@react-spring/web": "^9.7.5",
@ -27,9 +27,11 @@
"react-dom": "^18.0.0",
"react-dropzone": "^14.3.5",
"react-hook-form": "^7.54.2",
"react-minimal-pie-chart": "^9.1.0",
"react-redux": "^9.2.0",
"react-router-dom": "^7.1.1",
"react-scripts": "5.0.1",
"recharts": "^2.15.1",
"sonner": "^1.7.4",
"web-vitals": "^4.2.4"
},

BIN
public/mainPageLogo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 566 KiB

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 {
@ -21,7 +23,8 @@ interface AddEditCategoryModalProps {
name: string,
email: string,
phone: string,
registeredAddress: string
registeredAddress: string,
password: string
) => void;
editRow: any;
}
@ -31,6 +34,7 @@ interface FormData {
email: string;
phone: string;
registeredAddress: string;
password: string;
}
const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
@ -52,6 +56,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
email: "",
phone: "",
registeredAddress: "",
password: "",
},
});
@ -62,7 +67,8 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
data.name,
data.email,
data.phone,
data.registeredAddress
data.registeredAddress,
data.password
);
} else {
handleCreate(data);
@ -82,6 +88,8 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
}
}, [editRow, setValue, reset]);
const [showPassword, setShowPassword] = React.useState(false);
return (
<Dialog
open={open}
@ -168,7 +176,58 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
/>
)}
/>
{!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

@ -0,0 +1,212 @@
import React, { useEffect } from "react";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
//By Jaanvi : Edit Model :: 11-feb-25
interface AddUserModalProps {
open: boolean;
handleClose: () => void;
handleCreate: (data: FormData) => void;
handleUpdate: (
id: string,
name: string,
email: string,
phone: string,
password: string
) => void;
editRow: any;
}
interface FormData {
name: string;
email: string;
phone: string;
password: string;
}
const AddUserModal: React.FC<AddUserModalProps> = ({
open,
handleClose,
handleCreate,
editRow,
}) => {
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
} = useForm<FormData>({
defaultValues: {
name: "",
email: "",
phone: "",
password: "",
},
});
const onSubmit = (data: FormData) => {
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 Admin" : "Add Admin"}
<Box
onClick={handleClose}
sx={{
cursor: "pointer",
display: "flex",
alignItems: "center",
}}
>
<CloseIcon />
</Box>
</DialogTitle>
<DialogContent>
<Controller
name="name"
control={control}
rules={{
required: "Admin 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="User Name"
type="text"
fullWidth
variant="standard"
error={!!errors.name}
helperText={errors.name?.message}
/>
)}
/>
<Controller
name="email"
control={control}
rules={{
required: "Email is required",
pattern: {
value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
message: "Invalid email address",
},
}}
render={({ field }) => (
<TextField
{...field}
required
margin="dense"
label="Email"
type="email"
fullWidth
variant="standard"
error={!!errors.email}
helperText={errors.email?.message}
/>
)}
/>
<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}
/>
)}
/>
<Controller
name="phone"
control={control}
rules={{
required: "Phone number is required",
pattern: {
value: /^[0-9]*$/,
message: "Only numbers are allowed",
},
minLength: {
value: 6,
message: "Phone number must be exactly 6 digits",
},
maxLength: {
value: 14,
message: "Phone number must be exactly 14 digits",
},
}}
render={({ field }) => (
<TextField
{...field}
required
margin="dense"
label="Phone Number"
type="tel"
fullWidth
variant="standard"
error={!!errors.phone}
helperText={errors.phone?.message}
/>
)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button type="submit">Create</Button>
</DialogActions>
</Dialog>
);
};
export default AddUserModal;

View file

@ -68,12 +68,12 @@ export default function AppNavbar() {
<Typography
variant="h4"
component="h1"
sx={{ color: "text.primary" }}
sx={{ color: "#202020" }}
>
Dashboard
</Typography>
</Stack>
<ColorModeIconDropdown />
{/* <ColorModeIconDropdown /> */}
<MenuButton aria-label="menu" onClick={toggleDrawer(true)}>
<MenuRoundedIcon />
</MenuButton>
@ -81,7 +81,6 @@ export default function AppNavbar() {
<SideMenuMobile open={open} toggleDrawer={toggleDrawer} />
</Stack>
</Toolbar>
</AppBar>
);
}

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

@ -8,6 +8,8 @@ import SearchIcon from "@mui/icons-material/Search";
import Divider from "@mui/material/Divider";
import MenuButton from "../MenuButton";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import ColorModeIconDropdown from "../../shared-theme/ColorModeIconDropdown";
import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
export default function Header() {
const [showNotifications, setShowNotifications] = React.useState(false);
@ -20,11 +22,12 @@ export default function Header() {
sx={{
width: "100%",
height: "84px",
backgroundColor: "#202020",
// backgroundColor: "#202020",
padding: "20px 24px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexDirection: { xs: "column", sm: "row" },
}}
>
<Box sx={{ flexGrow: 1 }} />
@ -33,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",
@ -47,42 +55,75 @@ 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
onClick={toggleNotifications}
showBadge
aria-label="Open notifications"
onClick={toggleNotifications}
>
{/* Custom Bell Icon */}
<Box
component="img"
src="/Bell.jpg"
alt="Notification Icon"
sx={{ width: 24, height: 24 }}
/>
<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 /> */}
</Stack>
{showNotifications && (
<Box
sx={{
p: 2,
position: "absolute",
top: "55px",
right: { xs: "10px", sm: "280px" },
bgcolor: "#FFFFFF",
boxShadow: 1,
borderRadius: 1,
zIndex: 1300,
cursor: "pointer",
width: "250px",
}}
>
{/* <Typography variant="h6" color="text.primary">
Notifications
</Typography> */}
<Typography variant="body2" color="text.secondary">
No notifications yet
</Typography>
</Box>
)}
</Stack>
</Box>
);

View file

@ -0,0 +1,152 @@
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Chip from "@mui/material/Chip";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import { LineChart } from "@mui/x-charts/LineChart";
import { Box } from "@mui/material";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
function AreaGradient({ color, id }: { color: string; id: string }) {
return (
<defs>
<linearGradient id={id} x1="50%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" stopColor={color} stopOpacity={0.5} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
);
}
function getDaysInMonth(month: number, year: number) {
const date = new Date(year, month, 0);
const monthName = date.toLocaleDateString("en-US", {
month: "short",
});
const daysInMonth = date.getDate();
const days = [];
let i = 1;
while (days.length < daysInMonth) {
days.push(`${monthName} ${i}`);
i += 1;
}
return days;
}
export default function LineChartCard() {
const theme = useTheme();
const data = getDaysInMonth(4, 2024);
const colorPalette = [theme.palette.primary.light];
return (
<Card
variant="outlined"
sx={{ width: "100%", height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<div
style={{
display: "flex",
alignItems: "center",
color: "#202020",
}}
>
<Typography
variant="h6"
align="left"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
Sales Stats
</Typography>
<Box
sx={{
mt: 2,
mb: 2,
backgroundColor: "#FFFFFF",
marginLeft: "auto",
marginRight: "16px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
p: 1.5,
borderRadius: "8px",
border: "1px solid #454545",
padding: "4px 8px",
color: "#FFFFFF",
}}
>
<Typography
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#202020",
p: "4px",
}}
>
Weekly
</Typography>
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
</div>
<LineChart
colors={colorPalette}
xAxis={[
{
scaleType: "point",
data,
tickInterval: (index, i) => (i + 1) % 5 === 0,
},
]}
series={[
{
id: "direct",
label: "Direct",
showMark: false,
curve: "linear",
stack: "total",
area: true,
stackOrder: "ascending",
data: [
300, 900, 500, 1200, 1500, 1800, 2400, 2100,
2700, 3000, 1800, 3300, 3600, 3900, 4200, 4500,
3900, 4800, 5100, 5400, 4500, 5700, 6000, 6300,
6600, 6900, 7200, 7500, 7800, 8100,
],
color: "#FFFFFF",
},
]}
height={250}
margin={{ left: 50, right: 20, top: 20, bottom: 20 }}
grid={{ horizontal: true }}
sx={{
"& .MuiAreaElement-series-direct": {
fill: "url('#direct')",
},
}}
slotProps={{
legend: {
hidden: true,
},
}}
>
<AreaGradient
color={theme.palette.primary.light}
id="direct"
/>
</LineChart>
</CardContent>
</Card>
);
}

View file

@ -14,7 +14,7 @@ const Logout: React.FC<LogoutProps> = ({ setLogoutModal, logoutModal }) => {
const handlelogout = () => {
localStorage.clear();
navigate("/auth/login");
navigate("/login");
toast.success("Logged out successfully");
setLogoutModal(false);
};

View file

@ -14,7 +14,7 @@ const Logout: React.FC<LogoutProps> = ({ setLogoutModal, logoutModal }) => {
const handlelogout = () => {
localStorage.clear();
navigate("/auth/login");
navigate("/login");
toast.success("Logged out successfully");
setLogoutModal(false);
};

View file

@ -1,79 +1,74 @@
import * as React from 'react';
import Grid from '@mui/material/Grid2';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Copyright from '../../pages/Dashboard/internals/components/Copyright';
import ChartUserByCountry from '../ChartUserByCountry';
import CustomizedTreeView from '../CustomizedTreeView';
import CustomizedDataGrid from '../CustomizedDataGrid';
import HighlightedCard from '../HighlightedCard';
import PageViewsBarChart from '../PageViewsBarChart';
import SessionsChart from '../SessionsChart';
import StatCard, { StatCardProps } from '../StatCard';
import * as React from "react";
import Grid from "@mui/material/Grid2";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import Copyright from "../../pages/Dashboard/internals/components/Copyright";
import ChartUserByCountry from "../ChartUserByCountry";
import CustomizedTreeView from "../CustomizedTreeView";
import CustomizedDataGrid from "../CustomizedDataGrid";
import HighlightedCard from "../HighlightedCard";
import PageViewsBarChart from "../PageViewsBarChart";
import SessionsChart from "../SessionsChart";
import StatCard, { StatCardProps } from "../StatCard";
import ResourcesPieChart from "../ResourcePieChart";
import { BarChart } from "@mui/icons-material";
import RoundedBarChart from "../barChartCard";
import { LineHighlightPlot } from "@mui/x-charts";
import LineChartCard from "../LineChartCard";
const data: StatCardProps[] = [
{
title: 'Users',
value: '14k',
interval: 'Last 30 days',
trend: 'up',
data: [
200, 24, 220, 260, 240, 380, 100, 240, 280, 240, 300, 340, 320, 360, 340,
380, 360, 400, 380, 420, 400, 640, 340, 460, 440, 480, 460, 600, 880, 920,
],
},
{
title: 'Conversions',
value: '325',
interval: 'Last 30 days',
trend: 'down',
data: [
1640, 1250, 970, 1130, 1050, 900, 720, 1080, 900, 450, 920, 820, 840, 600,
820, 780, 800, 760, 380, 740, 660, 620, 840, 500, 520, 480, 400, 360, 300,
220,
],
},
{
title: 'Event count',
value: '200k',
interval: 'Last 30 days',
trend: 'neutral',
data: [
500, 400, 510, 530, 520, 600, 530, 520, 510, 730, 520, 510, 530, 620, 510,
530, 520, 410, 530, 520, 610, 530, 520, 610, 530, 420, 510, 430, 520, 510,
],
},
{
title: "Total Charge Stations",
value: "86",
},
{
title: "Charging Completed",
value: "12",
},
{
title: "Active Users",
value: "24",
},
{
title: "Total Energy Consumed",
value: "08",
},
];
export default function MainGrid() {
return (
<Box sx={{ width: '100%', maxWidth: { sm: '100%', md: '1700px' } }}>
{/* cards */}
<Typography component="h2" variant="h6" sx={{ mb: 2 }}>
Overview
</Typography>
<Grid
container
spacing={2}
columns={12}
sx={{ mb: (theme) => theme.spacing(2) }}
>
{data.map((card, index) => (
<Grid key={index} size={{ xs: 12, sm: 6, lg: 3 }}>
<StatCard {...card} />
</Grid>
))}
<Grid size={{ xs: 12, sm: 6, lg: 3 }}>
<HighlightedCard />
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<SessionsChart />
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<PageViewsBarChart />
</Grid>
</Grid>
</Box>
);
return (
<Box sx={{ width: "100%", maxWidth: { sm: "100%", md: "1700px" } }}>
{/* cards */}
<Typography component="h2" variant="h6" sx={{ mb: 2 }}>
Dashboard
</Typography>
<Grid
container
spacing={2}
columns={12}
sx={{ mb: (theme) => theme.spacing(2) }}
>
{data.map((card, index) => (
<Grid key={index} size={{ xs: 12, sm: 6, lg: 3 }}>
<StatCard {...card} />
</Grid>
))}
<Grid size={{ xs: 12, md: 6 }}>
<SessionsChart />
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<ResourcesPieChart />
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<RoundedBarChart />
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<LineChartCard />
</Grid>
</Grid>
</Box>
);
}

View file

@ -10,37 +10,13 @@ import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
import { Link, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store/store";
const baseMenuItems = [
{
text: "Home",
icon: <HomeRoundedIcon />,
url: "/panel/dashboard",
},
{
text: "Admins",
icon: <AnalyticsRoundedIcon />,
url: "/panel/admin-list",
},
{
text: "Users",
icon: <AnalyticsRoundedIcon />,
url: "/panel/user-list",
},
];
import DashboardOutlinedIcon from "@mui/icons-material/DashboardOutlined";
import ManageAccountsOutlinedIcon from "@mui/icons-material/ManageAccountsOutlined";
//Eknoor singh and Jaanvi
//date:- 12-Feb-2025
//Made a different variable for super admin to access all the details.
const superAdminOnlyItems = [
{
text: "Admin List",
icon: <FormatListBulletedIcon />,
url: "/panel/adminlist",
},
];
type PropType = {
hidden: boolean;
};
@ -48,18 +24,36 @@ type PropType = {
export default function MenuContent({ hidden }: PropType) {
const location = useLocation();
const userRole = useSelector(
(state: RootState) => state.profileReducer.user?.role
(state: RootState) => state.profileReducer.user?.userType
);
const mainListItems = [
...baseMenuItems,
...(userRole === "superadmin" ? superAdminOnlyItems : []),
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 filteredMenuItems = baseMenuItems.filter(Boolean);
return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
<List dense>
{mainListItems.map((item, index) => (
{filteredMenuItems.map((item, index) => (
<ListItem
key={index}
disablePadding

View file

@ -13,108 +13,107 @@ import MenuButton from "../MenuButton";
import { Avatar } from "@mui/material";
import { useNavigate } from "react-router-dom";
import Logout from "../LogOutFunction/LogOutFunction";
const MenuItem = styled(MuiMenuItem)({
margin: "2px 0",
margin: "2px 0",
});
export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [logoutModal, setLogoutModal] = React.useState<boolean>(false);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event?.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//Made a navigation page for the profile page
const navigate = useNavigate();
const handleProfile = () => {
navigate("/panel/profile");
};
//jaanvi
//date:- 13-Feb-2025
return (
<React.Fragment>
<MenuButton
aria-label="Open menu"
onClick={handleClick}
sx={{ borderColor: "transparent" }}
>
{avatar ? (
<MoreVertRoundedIcon />
) : (
<Avatar
sizes="small"
alt="Riley Carter"
src="/static/images/avatar/7.jpg"
sx={{ width: 36, height: 36 }}
/>
)}
</MenuButton>
<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",
},
}}
>
<MenuItem onClick={handleProfile}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem>
<MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider />
<MenuItem
onClick={handleClose}
sx={{
[`& .${listItemIconClasses.root}`]: {
ml: "auto",
minWidth: 0,
},
}}
>
{/* //Eknoor singh and jaanvi
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [logoutModal, setLogoutModal] = React.useState<boolean>(false);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event?.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//Made a navigation page for the profile page
const navigate = useNavigate();
const handleProfile = () => {
navigate("/panel/profile");
};
//jaanvi
//date:- 13-Feb-2025
return (
<React.Fragment>
<MenuButton
aria-label="Open menu"
onClick={handleClick}
sx={{ borderColor: "transparent" }}
>
{avatar ? (
<MoreVertRoundedIcon />
) : (
<Avatar
sizes="small"
alt="Super Admin"
src="/static/images/avatar/7.jpg"
sx={{ width: 36, height: 36 }}
/>
)}
</MenuButton>
<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",
},
}}
>
<MenuItem onClick={handleProfile}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem>
<MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider />
<MenuItem
onClick={handleClose}
sx={{
[`& .${listItemIconClasses.root}`]: {
ml: "auto",
minWidth: 0,
},
}}
>
{/* //Eknoor singh and jaanvi
//date:- 13-Feb-2025
//Implemented logout functionality which was static previously */}
<ListItemText
onClick={(e) => {
e.stopPropagation();
setLogoutModal(true);
}}
>
Logout
</ListItemText>
<Logout
setLogoutModal={setLogoutModal}
logoutModal={logoutModal}
/>
<ListItemIcon>
<LogoutRoundedIcon fontSize="small" />
</ListItemIcon>
</MenuItem>
</Menu>
</React.Fragment>
);
<ListItemText
onClick={(e) => {
e.stopPropagation();
setLogoutModal(true);
}}
>
Logout
</ListItemText>
<Logout
setLogoutModal={setLogoutModal}
logoutModal={logoutModal}
/>
<ListItemIcon>
<LogoutRoundedIcon fontSize="small" />
</ListItemIcon>
</MenuItem>
</Menu>
</React.Fragment>
);
}

View file

@ -0,0 +1,106 @@
import * as React from "react";
import { PieChart } from "@mui/x-charts/PieChart";
import { useDrawingArea } from "@mui/x-charts/hooks";
import { styled } from "@mui/material/styles";
import Typography from "@mui/material/Typography";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
const colorPalette = [
"hsla(202, 69%, 60%, 1)",
"hsl(204, 48.60%, 72.50%)",
"hsl(214, 56.40%, 30.60%)",
"hsl(222, 6.80%, 50.80%)",
];
const data = [
{ title: "Total Resources", value: 50, color: colorPalette[0] },
{ title: "Total Stations", value: 20, color: colorPalette[1] },
{ title: "Station Manager", value: 15, color: colorPalette[2] },
{ title: "Total Booth", value: 15, color: colorPalette[3] },
];
export default function ResourcePieChart() {
return (
<Card
variant="outlined"
sx={{
display: "flex",
flexDirection: "column",
gap: "8px",
flexGrow: 1,
width: "100%",
height: "100%",
backgroundColor: "#F2F2F2",
}}
>
<CardContent>
<Typography
component="h2"
variant="subtitle2"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
Resources
</Typography>
<Box sx={{ display: "flex", alignItems: "center" }}>
<PieChart
colors={colorPalette}
margin={{
left: 60,
right: 80,
top: 80,
bottom: 80,
}}
series={[
{
data,
innerRadius: 50,
outerRadius: 100,
paddingAngle: 0,
highlightScope: {
faded: "global",
highlighted: "item",
},
},
]}
height={300}
width={300}
slotProps={{
legend: { hidden: true },
}}
></PieChart>
<Stack spacing={1}>
{data.map((entry, index) => (
<Stack
key={index}
direction="row"
spacing={1}
alignItems="center"
>
<Box
sx={{
width: 16,
height: 16,
backgroundColor: entry.color,
borderRadius: "50%",
}}
/>
<Typography variant="body2" color="#202020">
{entry.title}
</Typography>
</Stack>
))}
</Stack>
</Box>
</CardContent>
</Card>
);
}

View file

@ -1,150 +1,113 @@
import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Chip from '@mui/material/Chip';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import { LineChart } from '@mui/x-charts/LineChart';
function AreaGradient({ color, id }: { color: string; id: string }) {
return (
<defs>
<linearGradient id={id} x1="50%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" stopColor={color} stopOpacity={0.5} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
);
}
function getDaysInMonth(month: number, year: number) {
const date = new Date(year, month, 0);
const monthName = date.toLocaleDateString('en-US', {
month: 'short',
});
const daysInMonth = date.getDate();
const days = [];
let i = 1;
while (days.length < daysInMonth) {
days.push(`${monthName} ${i}`);
i += 1;
}
return days;
}
import * as React from "react";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
export default function SessionsChart() {
const theme = useTheme();
const data = getDaysInMonth(4, 2024);
return (
<Card
variant="outlined"
sx={{
width: "100%",
height: "100%",
backgroundColor: "#F2F2F2",
p: 2,
}}
>
<CardContent>
<Typography
variant="h6"
align="left"
color="#202020"
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "18px",
lineHeight: "24px",
}}
>
Charging prices
</Typography>
const colorPalette = [
theme.palette.primary.light,
theme.palette.primary.main,
theme.palette.primary.dark,
];
{/* Responsive dropdown box */}
<Box
sx={{
mt: 2,
mb: 2,
backgroundColor: "#FFFFFF",
fontSize: "14px",
lineHeight: "20px",
width: { xs: "100%" },
height: "48px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
p: 1.5,
borderRadius: "8px",
border: "1px solid #454545",
}}
>
<Typography
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#202020",
p: "4px",
}}
>
Delhi NCR EV Station
</Typography>
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
return (
<Card variant="outlined" sx={{ width: '100%' }}>
<CardContent>
<Typography component="h2" variant="subtitle2" gutterBottom>
Sessions
</Typography>
<Stack sx={{ justifyContent: 'space-between' }}>
<Stack
direction="row"
sx={{
alignContent: { xs: 'center', sm: 'flex-start' },
alignItems: 'center',
gap: 1,
}}
>
<Typography variant="h4" component="p">
13,277
</Typography>
<Chip size="small" color="success" label="+35%" />
</Stack>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
Sessions per day for the last 30 days
</Typography>
</Stack>
<LineChart
colors={colorPalette}
xAxis={[
{
scaleType: 'point',
data,
tickInterval: (index, i) => (i + 1) % 5 === 0,
},
]}
series={[
{
id: 'direct',
label: 'Direct',
showMark: false,
curve: 'linear',
stack: 'total',
area: true,
stackOrder: 'ascending',
data: [
300, 900, 600, 1200, 1500, 1800, 2400, 2100, 2700, 3000, 1800, 3300,
3600, 3900, 4200, 4500, 3900, 4800, 5100, 5400, 4800, 5700, 6000,
6300, 6600, 6900, 7200, 7500, 7800, 8100,
],
},
{
id: 'referral',
label: 'Referral',
showMark: false,
curve: 'linear',
stack: 'total',
area: true,
stackOrder: 'ascending',
data: [
500, 900, 700, 1400, 1100, 1700, 2300, 2000, 2600, 2900, 2300, 3200,
3500, 3800, 4100, 4400, 2900, 4700, 5000, 5300, 5600, 5900, 6200,
6500, 5600, 6800, 7100, 7400, 7700, 8000,
],
},
{
id: 'organic',
label: 'Organic',
showMark: false,
curve: 'linear',
stack: 'total',
stackOrder: 'ascending',
data: [
1000, 1500, 1200, 1700, 1300, 2000, 2400, 2200, 2600, 2800, 2500,
3000, 3400, 3700, 3200, 3900, 4100, 3500, 4300, 4500, 4000, 4700,
5000, 5200, 4800, 5400, 5600, 5900, 6100, 6300,
],
area: true,
},
]}
height={250}
margin={{ left: 50, right: 20, top: 20, bottom: 20 }}
grid={{ horizontal: true }}
sx={{
'& .MuiAreaElement-series-organic': {
fill: "url('#organic')",
},
'& .MuiAreaElement-series-referral': {
fill: "url('#referral')",
},
'& .MuiAreaElement-series-direct': {
fill: "url('#direct')",
},
}}
slotProps={{
legend: {
hidden: true,
},
}}
>
<AreaGradient color={theme.palette.primary.dark} id="organic" />
<AreaGradient color={theme.palette.primary.main} id="referral" />
<AreaGradient color={theme.palette.primary.light} id="direct" />
</LineChart>
</CardContent>
</Card>
);
{/* Grid container for the four boxes */}
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
},
gap: { xs: 1, sm: 2 },
maxWidth: "750px",
width: "100%",
mx: "auto",
}}
>
{/* You can map over your data here; for simplicity, were using static boxes */}
{[1, 2, 3, 4].map((item) => (
<Box
key={item}
sx={{
height: "84px",
borderRadius: "8px",
p: "12px 16px",
backgroundColor: "#FFFFFF",
color: "#202020",
}}
>
<Typography
component="h1"
variant="body2"
gutterBottom
>
Basic Charging
</Typography>
<Typography
component="h1"
variant="subtitle2"
gutterBottom
>
16.83 cents/kWh
</Typography>
</Box>
))}
</Box>
</CardContent>
</Card>
);
}

View file

@ -11,6 +11,9 @@ import NotificationsRoundedIcon from "@mui/icons-material/NotificationsRounded";
import MenuButton from "../MenuButton";
import MenuContent from "../MenuContent";
import CardAlert from "../CardAlert/CardAlert";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useDispatch, useSelector } from "react-redux";
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
interface SideMenuMobileProps {
open: boolean | undefined;
@ -21,6 +24,12 @@ export default function SideMenuMobile({
open,
toggleDrawer,
}: SideMenuMobileProps) {
const dispatch = useDispatch<AppDispatch>();
const { user } = useSelector((state: RootState) => state?.profileReducer);
React.useEffect(() => {
dispatch(fetchAdminProfile());
}, [dispatch]);
return (
<Drawer
anchor="right"
@ -47,12 +56,12 @@ export default function SideMenuMobile({
>
<Avatar
sizes="small"
alt="Riley Carter"
alt={user?.name || "User Avatar"}
src="/static/images/avatar/7.jpg"
sx={{ width: 24, height: 24 }}
/>
<Typography component="p" variant="h6">
Riley Carter
Super Admin
</Typography>
</Stack>
<MenuButton showBadge>
@ -61,7 +70,7 @@ export default function SideMenuMobile({
</Stack>
<Divider />
<Stack sx={{ flexGrow: 1 }}>
<MenuContent />
<MenuContent hidden={false} />
<Divider />
</Stack>
<CardAlert />

View file

@ -1,129 +1,45 @@
import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';
import { areaElementClasses } from '@mui/x-charts/LineChart';
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { SparkLineChart } from "@mui/x-charts/SparkLineChart";
import { areaElementClasses } from "@mui/x-charts/LineChart";
export type StatCardProps = {
title: string;
value: string;
interval: string;
trend: 'up' | 'down' | 'neutral';
data: number[];
title: string;
value: string;
};
function getDaysInMonth(month: number, year: number) {
const date = new Date(year, month, 0);
const monthName = date.toLocaleDateString('en-US', {
month: 'short',
});
const daysInMonth = date.getDate();
const days = [];
let i = 1;
while (days.length < daysInMonth) {
days.push(`${monthName} ${i}`);
i += 1;
}
return days;
}
function AreaGradient({ color, id }: { color: string; id: string }) {
return (
<defs>
<linearGradient id={id} x1="50%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" stopColor={color} stopOpacity={0.3} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
);
}
export default function StatCard({
title,
value,
interval,
trend,
data,
}: StatCardProps) {
const theme = useTheme();
const daysInWeek = getDaysInMonth(4, 2024);
const trendColors = {
up:
theme.palette.mode === 'light'
? theme.palette.success.main
: theme.palette.success.dark,
down:
theme.palette.mode === 'light'
? theme.palette.error.main
: theme.palette.error.dark,
neutral:
theme.palette.mode === 'light'
? theme.palette.grey[400]
: theme.palette.grey[700],
};
const labelColors = {
up: 'success' as const,
down: 'error' as const,
neutral: 'default' as const,
};
const color = labelColors[trend];
const chartColor = trendColors[trend];
const trendValues = { up: '+25%', down: '-25%', neutral: '+5%' };
return (
<Card variant="outlined" sx={{ height: '100%', flexGrow: 1 }}>
<CardContent>
<Typography component="h2" variant="subtitle2" gutterBottom>
{title}
</Typography>
<Stack
direction="column"
sx={{ justifyContent: 'space-between', flexGrow: '1', gap: 1 }}
>
<Stack sx={{ justifyContent: 'space-between' }}>
<Stack
direction="row"
sx={{ justifyContent: 'space-between', alignItems: 'center' }}
>
<Typography variant="h4" component="p">
{value}
</Typography>
<Chip size="small" color={color} label={trendValues[trend]} />
</Stack>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
{interval}
</Typography>
</Stack>
<Box sx={{ width: '100%', height: 50 }}>
<SparkLineChart
colors={[chartColor]}
data={data}
area
showHighlight
showTooltip
xAxis={{
scaleType: 'band',
data: daysInWeek, // Use the correct property 'data' for xAxis
}}
sx={{
[`& .${areaElementClasses.root}`]: {
fill: `url(#area-gradient-${value})`,
},
}}
>
<AreaGradient color={chartColor} id={`area-gradient-${value}`} />
</SparkLineChart>
</Box>
</Stack>
</CardContent>
</Card>
);
export default function StatCard({ title, value }: StatCardProps) {
return (
<Card
variant="outlined"
sx={{ height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<Typography
component="h2"
variant="subtitle2"
color="#202020"
gutterBottom
>
{title}
</Typography>
<Typography
component="h1"
variant="body1"
color="#202020"
fontSize={30}
fontWeight={700}
gutterBottom
>
{value}
</Typography>
</CardContent>
</Card>
);
}

View file

@ -0,0 +1,106 @@
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
} from "recharts";
import {
Card,
CardContent,
Typography,
Box,
} from "@mui/material";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
const data = [
{ name: "Jan", v1: 40 },
{ name: "Feb", v1: 50 },
{ name: "Mar", v1: 80 },
{ name: "Apr", v1: 20 },
{ name: "May", v1: 60 },
{ name: "Jun", v1: 30 },
];
export default function RoundedBarChart() {
const theme = useTheme();
return (
<Card
variant="outlined"
sx={{ width: "100%", height: "100%", backgroundColor: "#F2F2F2" }}
>
<CardContent>
<div
style={{
display: "flex",
alignItems: "center",
color: "#202020",
}}
>
<Typography
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: "#FFFFFF",
marginLeft: "auto",
marginRight: "16px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
p: 1.5,
borderRadius: "8px",
border: "1px solid #454545",
padding: "4px 8px",
color: "#202020",
}}
>
<Typography
sx={{
fontFamily: "Gilroy",
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
color: "#202020",
p: "4px",
}}
>
Monthly
</Typography>
<ArrowDropDownIcon sx={{ color: "#202020" }} />
</Box>
</div>
<BarChart
width={600}
height={300}
data={data}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
style={{ width: "100%", height: "auto" }}
>
<CartesianGrid vertical={false} />
<XAxis />
<YAxis tickFormatter={(value) => `${value}`} />
<Bar dataKey="v1" fill="skyblue" radius={[10, 10, 0, 0]} />
<Bar dataKey="v2" fill="skyblue" radius={[10, 10, 0, 0]} />
</BarChart>
</CardContent>
</Card>
);
}

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,355 +1,196 @@
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 React, { useEffect, useState } from "react";
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";
import { useDispatch, useSelector } from "react-redux";
import { adminList } from "../../redux/slices/adminSlice";
import {
adminList,
updateAdmin,
createAdmin,
} from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import SearchIcon from "@mui/icons-material/Search";
export default function AdminList() {
const [searchQuery, setSearchQuery] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const adminsPerPage = 10;
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 dispatch = useDispatch<AppDispatch>();
const admins = useSelector((state: RootState) => state.adminReducer.admins);
const admins = useSelector((state: RootState) => state.adminReducer.admins);
const [searchTerm, setSearchTerm] = useState("");
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);
const handleClickOpen = () => {
setRowData(null); // Reset row data when opening for new admin
setModalOpen(true);
};
const handleCloseModal = () => {
setModalOpen(false);
setRowData(null);
reset();
};
const handleCreate = async (data: {
name: string;
email: string;
phone: string;
registeredAddress: string;
}) => {
try {
await dispatch(createAdmin(data));
await dispatch(adminList()); // Refresh the list after creation
handleCloseModal();
} catch (error) {
console.error("Creation failed", error);
}
};
const handleUpdate = async (
id: string,
name: string,
email: string,
phone: string,
registeredAddress: string
) => {
try {
await dispatch(
updateAdmin({
id,
name,
email,
phone,
registeredAddress,
})
);
await dispatch(adminList());
} catch (error) {
console.error("Update failed", error);
}
};
const categoryColumns: Column[] = [
{ id: "srno", label: "Sr No" },
{ id: "name", label: "Name" },
{ id: "email", label: "Email" },
{ id: "phone", label: "Phone" },
{ 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 = filteredAdmins?.length
? filteredAdmins?.map(
(
admin: {
id: string;
name: string;
email: string;
phone: string;
registeredAddress: string;
},
index: number
) => ({
id: admin?.id,
srno: index + 1,
name: admin?.name,
email: admin?.email,
phone: admin?.phone,
registeredAddress: admin?.registeredAddress,
})
)
: [];
return (
<Box
sx={{
width: "calc(100% - 48px)",
margin: "0 auto",
padding: "24px",
backgroundColor: "#1C1C1C",
borderRadius: "12px",
}}
>
<>
<Typography
component="h2"
variant="h6"
sx={{
color: "#FFFFFF",
fontWeight: 500,
fontSize: "18px",
fontFamily: "Gilroy",
fontWeight: 600,
mb: { xs: 2, sm: 0 },
width: "100%",
display: "flex",
}}
>
Charge stations
Admins
</Typography>
{/* Search & Buttons Section */}
<Box
sx={{
width: "100%",
display: "flex",
gap: "16px",
marginTop: "16px",
flexDirection: { xs: "column", sm: "row" },
justifyContent: "space-between",
alignItems: "center",
fontFamily: "Gilroy",
mb: 2, // Add margin bottom for spacing
}}
>
<TextField
variant="outlined"
placeholder="Search Charge stations"
size="small"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
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",
},
},
width: { xs: "100%", sm: "30%" },
marginBottom: { xs: 2, sm: 0 },
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon sx={{ color: "#FFFFFF" }} />
</InputAdornment>
<SearchIcon
sx={{ color: "#202020", marginRight: 1 }}
/>
),
}}
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
<Button
variant="contained"
size="medium"
sx={{
width: "44px",
height: "44px",
borderRadius: "8px",
backgroundColor: "#272727",
color: "#52ACDF",
"&:hover": { backgroundColor: "#333333" },
textAlign: "center",
width: { xs: "100%", sm: "auto" },
}}
onClick={handleClickOpen}
>
<TuneIcon />
</IconButton>
Add Admin
</Button>
</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>
<CustomTable
columns={categoryColumns}
rows={categoryRows}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setViewModal={setViewModal}
viewModal={viewModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
/>
<AddEditCategoryModal
open={modalOpen}
handleClose={handleCloseModal}
handleCreate={handleCreate}
handleUpdate={handleUpdate}
editRow={rowData}
/>
</>
);
}

View file

@ -1,82 +1,43 @@
import * as React from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import CssBaseline from "@mui/material/CssBaseline";
import FormControlLabel from "@mui/material/FormControlLabel";
import Divider from "@mui/material/Divider";
import FormLabel from "@mui/material/FormLabel";
import FormControl from "@mui/material/FormControl";
import Link from "@mui/material/Link";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import MuiCard from "@mui/material/Card";
import { styled } from "@mui/material/styles";
import {
Box,
Button,
Checkbox,
FormControlLabel,
FormLabel,
FormControl,
TextField,
Typography,
Grid,
IconButton,
Link,
} from "@mui/material";
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";
import { useNavigate } from "react-router-dom";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Card, SignInContainer } from "./styled.css.tsx";
const Card = styled(MuiCard)(({ theme }) => ({
display: "flex",
flexDirection: "column",
alignSelf: "center",
width: "100%",
padding: theme.spacing(4),
gap: theme.spacing(2),
margin: "auto",
[theme.breakpoints.up("sm")]: {
maxWidth: "450px",
},
boxShadow:
"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
...theme.applyStyles("dark", {
boxShadow:
"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
}),
}));
const SignInContainer = styled(Stack)(({ theme }) => ({
height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
minHeight: "100%",
padding: theme.spacing(2),
[theme.breakpoints.up("sm")]: {
padding: theme.spacing(4),
},
"&::before": {
content: '""',
display: "block",
position: "absolute",
zIndex: -1,
inset: 0,
backgroundImage:
"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
backgroundRepeat: "no-repeat",
...theme.applyStyles("dark", {
backgroundImage:
"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
}),
},
}));
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);
};
@ -99,148 +60,287 @@ 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" }}
/>
<Card variant="outlined">
{/* <SitemarkIcon /> */}
Digi-EV
<Typography
component="h1"
variant="h4"
<Grid container sx={{ height: "100vh" }}>
{/* Image Section */}
<Grid
item
xs={0}
sm={0}
md={7}
sx={{
width: "100%",
fontSize: "clamp(2rem, 10vw, 2.15rem)",
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
}}
>
Sign in
</Typography>
<Box
component="form"
onSubmit={handleSubmit(onSubmit)}
noValidate
/>
{/* Form Section */}
<Grid
item
xs={12}
md={5}
sx={{
backgroundColor: "black",
display: "flex",
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
width: "100%",
gap: 2,
padding: { xs: "2rem", md: "3rem", lg: "3rem" },
height: "100%",
}}
>
<FormControl>
<FormLabel htmlFor="email">Email</FormLabel>
<Controller
name="email"
control={control}
defaultValue=""
rules={{
required: "Email is required",
pattern: {
value: /\S+@\S+\.\S+/,
message:
"Please enter a valid email address.",
},
}}
render={({ field }) => (
<TextField
{...field}
error={!!errors.email}
helperText={errors.email?.message}
id="email"
type="email"
placeholder="your@email.com"
autoComplete="email"
autoFocus
required
fullWidth
variant="outlined"
color={
errors.email ? "error" : "primary"
}
/>
)}
/>
</FormControl>
<FormControl>
<FormLabel htmlFor="password">Password</FormLabel>
<Controller
name="password"
control={control}
defaultValue=""
rules={{
required: "Password is required",
minLength: {
value: 6,
message:
"Password must be at least 6 characters long.",
},
}}
render={({ field }) => (
<TextField
{...field}
error={!!errors.password}
helperText={errors.password?.message}
name="password"
placeholder="••••••"
type="password"
id="password"
autoComplete="current-password"
autoFocus
required
fullWidth
variant="outlined"
color={
errors.password
? "error"
: "primary"
}
/>
)}
/>
</FormControl>
<FormControlLabel
control={
<Checkbox value="remember" color="primary" />
}
label="Remember me"
/>
<ForgotPassword open={open} handleClose={handleClose} />
<Button type="submit" fullWidth variant="contained">
Sign in
</Button>
{/* <Link
component="button"
type="button"
onClick={handleClickOpen}
variant="body2"
sx={{ alignSelf: "center" }}
<Typography
variant="h3"
sx={{
color: "white",
textAlign: "center",
fontSize: {
xs: "2rem",
sm: "2.2rem",
md: "36px",
},
}}
>
Forgot your password?
</Link> */}
</Box>
{/* <Divider>or</Divider>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 2,
}}
>
<Typography sx={{ textAlign: "center" }}>
Don&apos;t have an account?{" "}
<Link
href="/auth/signup"
variant="body2"
sx={{ alignSelf: "center" }}
>
Sign up
</Link>
Welcome Back!
</Typography>
</Box> */}
</Card>
<Card
variant="outlined"
sx={{
maxWidth: "400px",
width: { xs: "80%", sm: "80%", md: "100%" },
}}
>
<Box
component="form"
onSubmit={handleSubmit(onSubmit)}
noValidate
sx={{
display: "flex",
flexDirection: "column",
gap: 2,
}}
>
<Typography
component="h1"
variant="h4"
sx={{
textAlign: "center",
color: "white",
fontSize: { xs: "1.5rem", sm: "2rem" },
}}
>
Login
</Typography>
<Typography
component="h6"
variant="subtitle2"
sx={{
textAlign: "center",
color: "white",
fontSize: { xs: "0.9rem", sm: "1rem" },
}}
>
Log in with your email and password
</Typography>
<FormControl sx={{ width: "100%" }}>
<FormLabel
htmlFor="email"
sx={{
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
color: "white",
}}
>
Email
</FormLabel>
<Controller
name="email"
control={control}
defaultValue=""
rules={{
required: "Email is required",
pattern: {
value: /\S+@\S+\.\S+/,
message:
"Please enter a valid email address.",
},
}}
render={({ field }) => (
<TextField
{...field}
error={!!errors.email}
helperText={
errors.email?.message
}
id="email"
type="email"
placeholder="Email"
autoComplete="email"
autoFocus
required
fullWidth
variant="outlined"
color={
errors.email
? "error"
: "primary"
}
sx={{
input: {
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
},
}}
/>
)}
/>
</FormControl>
<FormControl sx={{ width: "100%" }}>
<FormLabel
htmlFor="password"
sx={{
fontSize: {
xs: "0.9rem",
sm: "1rem",
},
color: "white",
}}
>
Password
</FormLabel>
<Controller
name="password"
control={control}
defaultValue=""
rules={{
required: "Password is required",
minLength: {
value: 6,
message:
"Password must be at least 6 characters long.",
},
}}
render={({ field }) => (
<Box sx={{ position: "relative" }}>
<TextField
{...field}
error={!!errors.password}
helperText={
errors.password?.message
}
name="password"
placeholder="Password"
type={
showPassword
? "text"
: "password"
}
id="password"
autoComplete="current-password"
autoFocus
required
fullWidth
variant="outlined"
color={
errors.password
? "error"
: "primary"
}
/>
<IconButton
sx={{
position: "absolute",
top: "50%",
right: "10px",
background: "none",
borderColor:
"transparent",
transform:
"translateY(-50%)",
"&:hover": {
backgroundColor:
"transparent",
borderColor:
"transparent",
},
}}
onClick={() =>
setShowPassword(
(prev) => !prev
)
}
>
{showPassword ? (
<VisibilityOff />
) : (
<Visibility />
)}
</IconButton>
</Box>
)}
/>
</FormControl>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
color: "white",
}}
>
<FormControlLabel
control={
<Checkbox
value="remember"
color="primary"
/>
}
label="Remember me"
/>
<Link
component="button"
type="button"
onClick={handleClickOpen}
variant="body2"
sx={{
alignSelf: "center",
color: "#01579b",
}}
>
Forgot password?
</Link>
</Box>
<ForgotPassword
open={open}
handleClose={handleClose}
/>
<Button
type="submit"
fullWidth
sx={{
color: "white",
backgroundColor: "#52ACDF",
"&:hover": {
backgroundColor: "#52ACDF",
opacity: 0.9,
},
}}
>
Login
</Button>
</Box>
</Card>
</Grid>
</Grid>
</SignInContainer>
</AppTheme>
);

View file

@ -0,0 +1,31 @@
import { styled} from "@mui/material/styles";
import {
Stack,
Card as MuiCard
} from "@mui/material";
// eslint-disable-next-line @typescript-eslint/no-redeclare, @typescript-eslint/no-unused-vars
export const Card = styled(MuiCard)(({ theme }) => ({
display: "flex",
flexDirection: "column",
alignSelf: "center",
width: "100%",
padding: theme.spacing(4),
gap: theme.spacing(2),
margin: "16px",
backgroundColor: "#1E1F1F",
[theme.breakpoints.up("sm")]: {
maxWidth: "450px",
},
}));
export const SignInContainer = styled(Stack)(() => ({
height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
minHeight: "100%",
"&::before": {
content: '""',
display: "block",
position: "absolute",
zIndex: -1,
inset: 0,
},
}));

View file

@ -133,7 +133,7 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
};
await dispatch(registerUser(payload)).unwrap();
navigate("/auth/login");
navigate("/login");
toast.success("Registration successful!");
} catch (error: any) {
toast.error(error?.message || "Registration failed");
@ -347,7 +347,7 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
<Typography sx={{ textAlign: "center" }}>
Already have an account? &nbsp;
<Link
href="/auth/login"
href="/login"
variant="body2"
sx={{ alignSelf: "center" }}
>

View file

@ -12,6 +12,7 @@ import {
import DashboardLayout from '../../layouts/DashboardLayout';
import AppTheme from '../../shared-theme/AppTheme';
import MainGrid from '../../components/MainGrid';
import AdminList from '../AdminList';
const xThemeComponents = {
...chartsCustomizations,
@ -29,26 +30,20 @@ const Dashboard: React.FC<DashboardProps> = ({ disableCustomTheme = false }) =>
<AppTheme {...{ disableCustomTheme }} themeComponents={xThemeComponents}>
<CssBaseline enableColorScheme />
{!disableCustomTheme ? (
<MainGrid />
<><MainGrid /></>
) : (
<Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor:'#202020',
height: '100vh',
textAlign: 'center',
padding: 2,
}}
>
<Box>
<Typography variant="h6" component="h1" gutterBottom>
Dashboard
</Typography>
<Typography variant="body1" sx={{ marginTop: 2 }}>
No content available on the Dashboard yet.
</Typography>
</Box>
</Box>
)}
</AppTheme>
@ -56,3 +51,10 @@ const Dashboard: React.FC<DashboardProps> = ({ disableCustomTheme = false }) =>
};
export default Dashboard;

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

@ -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

@ -0,0 +1,162 @@
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";
import SearchIcon from "@mui/icons-material/Search";
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 handleStatusToggle = (id: string, newStatus: number) => {
dispatch(toggleStatus({ id, status: newStatus }));
};
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 filterRoles = roles?.filter((role) =>
role.name.toLocaleLowerCase().includes(searchTerm.toLowerCase())
);
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 (
<>
<Box
sx={{
width: "100%",
display: "flex",
flexDirection: { xs: "column", sm: "row" },
justifyContent: "space-between",
alignItems: "center",
mb: 2,
}}
>
<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="small"
onClick={handleClickOpen}
sx={{
textAlign: "center",
width: { xs: "100%", sm: "auto" },
}}
>
Add Role
</Button>
</Box>
{showPermissions ? (
<AddEditRolePage />
) : (
<CustomTable
columns={categoryColumns}
rows={categoryRows || []}
setDeleteModal={setDeleteModal}
deleteModal={deleteModal}
setViewModal={setViewModal}
viewModal={viewModal}
setRowData={setRowData}
setModalOpen={setModalOpen}
handleStatusToggle={handleStatusToggle}
tableType="roleList"
/>
)}
</>
);
}

File diff suppressed because it is too large Load diff

View file

@ -4,12 +4,14 @@ import authReducer from "./slices/authSlice";
import adminReducer from "./slices/adminSlice";
import profileReducer from "./slices/profileSlice";
import userReducer from "./slices/userSlice.ts";
import roleReducer from "./slices/roleSlice.ts";
const rootReducer = combineReducers({
authReducer,
adminReducer,
profileReducer,
userReducer,
authReducer,
adminReducer,
profileReducer,
userReducer,
roleReducer,
});
export type RootState = ReturnType<typeof rootReducer>;

View file

@ -37,7 +37,7 @@ export const adminList = createAsyncThunk<
{ rejectValue: string }
>("FetchAdminList", async (_, { rejectWithValue }) => {
try {
const response = await http.get("auth/admin-list");
const response = await http.get("/admin-list");
return response?.data?.data;
} catch (error: any) {
toast.error("Error fetching users list" + error);
@ -55,7 +55,7 @@ export const deleteAdmin = createAsyncThunk<
{ rejectValue: string }
>("deleteAdmin", async (id, { rejectWithValue }) => {
try {
const response = await http.delete(`auth/${id}/delete-admin`);
const response = await http.delete(`/${id}/delete-admin`);
toast.success(response.data?.message);
return id;
} catch (error: any) {
@ -76,9 +76,9 @@ export const createAdmin = createAsyncThunk<
registeredAddress: string;
},
{ rejectValue: string }
>("auth/signup", async (data, { rejectWithValue }) => {
>("/create-admin", async (data, { rejectWithValue }) => {
try {
const response = await http.post("auth/create-admin", data);
const response = await http.post("/create-admin", data);
return response.data;
} catch (error: any) {
return rejectWithValue(
@ -92,10 +92,7 @@ export const updateAdmin = createAsyncThunk(
"updateAdmin",
async ({ id, ...userData }: User, { rejectWithValue }) => {
try {
const response = await http.put(
`auth/${id}/update-admin`,
userData
);
const response = await http.put(`/${id}/update-admin`, userData);
toast.success("Admin updated successfully");
return response?.data;
} catch (error: any) {

View file

@ -75,7 +75,7 @@ export const registerUser = createAsyncThunk<
{ rejectValue: string }
>("SignUpUser", async (data, { rejectWithValue }) => {
try {
const response = await http.post("auth/signup", data);
const response = await http.post("/signup", data);
return response.data;
} catch (error: any) {
return rejectWithValue(

View file

@ -7,7 +7,7 @@ interface User {
id: string;
name: string;
email: string;
role: string;
userType: string;
phone: string;
}

View file

@ -0,0 +1,193 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
import http from "../../lib/https";
import { toast } from "sonner";
// Define TypeScript types
interface Role {
id: string;
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
status: number;
}
interface RoleState {
roles: Role[];
loading: boolean;
error: string | null;
}
// Initial state
const initialState: RoleState = {
roles: [],
loading: false,
error: null,
};
export const roleList = createAsyncThunk<any, void, { rejectValue: string }>(
"fetchRoles",
async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await http.get("get");
if (!response.data) throw new Error("Invalid API response");
// Return the full response to handle in the reducer
return response.data;
} catch (error: any) {
toast.error("Error Fetching Roles: " + error.message);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
}
}
);
// Create Role
export const createRole = createAsyncThunk<
any,
{
name: string;
resource: {
moduleName: string;
moduleId: string;
permissions: string[];
}[];
},
{ rejectValue: string }
>("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: "roles",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(roleList.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(
roleList.fulfilled,
(state, action: PayloadAction<any>) => {
state.loading = false;
// Properly extract roles from the response data structure
state.roles =
action.payload.data?.results ||
action.payload.data ||
[];
}
)
.addCase(roleList.rejected, (state, action) => {
state.loading = false;
state.error = action.payload || "Failed to fetch roles";
})
.addCase(createRole.pending, (state) => {
state.loading = true;
})
.addCase(
createRole.fulfilled,
(state, action: PayloadAction<any>) => {
state.loading = false;
// 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(
createRole.rejected,
(state, action: PayloadAction<string | undefined>) => {
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";
}
);
},
});
export default roleSlice.reducer;

View file

@ -1,5 +1,7 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
import http from "../../lib/https";
import { toast } from "sonner";
// Define TypeScript types
interface User {
@ -7,9 +9,10 @@ interface User {
name: string;
email: string;
phone?: string;
location?: string;
managerAssigned?: string;
vehicle?: string;
// location?: string;
// managerAssigned?: string;
// vehicle?: string;
password:string;
}
interface UserState {
@ -26,17 +29,62 @@ const initialState: UserState = {
};
// Async thunk to fetch user list
export const userList = createAsyncThunk<User[]>("users/fetchUsers", async () => {
// export const userList = createAsyncThunk<User[]>("users/fetchUsers", async () => {
// try {
// const response = await axios.get<User[]>("/api/users"); // Adjust the API endpoint as needed
// return response.data;
// } catch (error: any) {
// throw new Error(error.response?.data?.message || "Failed to fetch users");
// }
// });
export const userList = createAsyncThunk<User, void, { rejectValue: string }>(
"fetchUsers",
async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await http.get("users-list");
if (!response.data?.data) throw new Error("Invalid API response");
return response.data.data;
} catch (error: any) {
toast.error("Error Fetching Profile" + error);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
}
}
);
//Create User
export const createUser = createAsyncThunk<
User,
{
name: string;
email: string;
password: string;
phone: string;
// location?: string;
// managerAssigned?: string;
// vehicle?: string;
},
{ rejectValue: string }
>("/CreateUser", async (data, { rejectWithValue }) => {
try {
const response = await axios.get<User[]>("/api/users"); // Adjust the API endpoint as needed
const response = await http.post("create-user", data);
return response.data;
} catch (error: any) {
throw new Error(error.response?.data?.message || "Failed to fetch users");
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
const userSlice = createSlice({
name: "users",
name: "fetchUsers",
initialState,
reducers: {},
extraReducers: (builder) => {
@ -45,14 +93,34 @@ const userSlice = createSlice({
state.loading = true;
state.error = null;
})
.addCase(userList.fulfilled, (state, action: PayloadAction<User[]>) => {
state.loading = false;
state.users = action.payload;
})
.addCase(
userList.fulfilled,
(state, action: PayloadAction<User[]>) => {
state.loading = false;
state.users = action.payload;
}
)
.addCase(userList.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || "Failed to fetch users";
});
})
.addCase(createUser.pending, (state) => {
state.loading = true;
// state.error = null;
})
.addCase(
createUser.fulfilled,
(state, action: PayloadAction<User>) => {
state.loading = false;
state.users.push(action.payload);
}
)
.addCase(
createUser.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.loading = false;
}
);
},
});

View file

@ -2,6 +2,8 @@ import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
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"));
@ -12,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[];
@ -21,7 +24,7 @@ interface ProtectedRouteProps {
// Protected Route Component
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ caps, component }) => {
if (!localStorage.getItem("authToken")) {
return <Navigate to="/auth/login" replace />;
return <Navigate to="/login" replace />;
}
return component;
};
@ -32,13 +35,13 @@ export default function AppRouter() {
<Suspense fallback={<LoadingComponent />}>
<BaseRoutes>
{/* Default Route */}
<Route element={<Navigate to="/auth/login" replace />} index />
<Route element={<Navigate to="/login" replace />} index />
{/* Auth Routes */}
<Route path="/auth">
<Route path="">
<Route
path=""
element={<Navigate to="/auth/login" replace />}
element={<Navigate to="/login" replace />}
index
/>
<Route path="login" element={<Login />} />
@ -83,7 +86,24 @@ export default function AppRouter() {
/>
}
/>
<Route
path="role-list"
element={
<ProtectedRoute
caps={[]}
component={<RoleList />}
/>
}
/>
<Route
path="permissions"
element={
<ProtectedRoute
caps={[]}
component={<AddEditRolePage />}
/>
}
/>
<Route
path="profile"
element={