Changes after Pull and resolved conflicts

This commit is contained in:
jaanvi 2025-02-17 09:43:48 +05:30
commit be5de3ac9e
16 changed files with 19252 additions and 19222 deletions

37832
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -73,4 +73,4 @@
"@types/react-dom": "^19.0.2",
"typescript": "^5.7.3"
}
}
}

View file

@ -7,7 +7,7 @@ import TableContainer from "@mui/material/TableContainer"
import TableHead from "@mui/material/TableHead"
import TableRow from "@mui/material/TableRow"
import Paper, { paperClasses } from "@mui/material/Paper"
import { deleteAdmin } from "../../redux/slices/authSlice"
import { deleteAdmin } from "../../redux/slices/adminSlice"
import { useDispatch } from "react-redux"
import {
Box,

View file

@ -43,7 +43,9 @@ type PropType = {
export default function MenuContent({ hidden }: PropType) {
const location = useLocation();
const userRole = useSelector((state: RootState) => state.auth.user?.role);
const userRole = useSelector(
(state: RootState) => state.profile.user?.role
);
const mainListItems = [
...baseMenuItems,

View file

@ -11,7 +11,7 @@ import React, { useEffect } from "react";
import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
import { AppDispatch, RootState } from "../../redux/store/store";
import { Button } from "@mui/material";
import { fetchAdminProfile } from "../../redux/slices/authSlice";
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
const drawerWidth = 240;
@ -34,7 +34,7 @@ export default function SideMenu() {
//Dispatch is called with user from Authstate Interface
const dispatch = useDispatch<AppDispatch>();
const { user } = useSelector((state: RootState) => state?.auth);
const { user } = useSelector((state: RootState) => state?.profile);
useEffect(() => {
dispatch(fetchAdminProfile());

View file

@ -1,47 +1,15 @@
// import axios from 'axios';
import axios from "axios";
// const http = axios.create({
// baseURL: process.env.REACT_APP_BACKEND_URL,
// });
// console.log(process.env.REACT_APP_BACKEND_URL);
// http.interceptors.request.use((config) => {
// const authToken = localStorage.getItem('authToken');
// if (authToken) {
// config.headers.Authorization = authToken;
// }
// return config;
// });
// export default http;
//Eknoor singh
//date:- 10-Feb-2025
//Made different functions for calling different backends and sent them in a function for clarity
import axios, { AxiosInstance } from "axios";
const backendHttp = axios.create({
const http = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL,
});
http.interceptors.request.use((config) => {
const authToken = localStorage.getItem("authToken");
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`;
}
// Axios instance for the local API
const apiHttp = axios.create({
baseURL: "http://localhost:5000/api",
return config;
});
// Add interceptors to both instances
const addAuthInterceptor = (instance: AxiosInstance) => {
instance.interceptors.request.use((config) => {
const authToken = localStorage.getItem("authToken");
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`; // <-- Add "Bearer "
}
return config;
});
};
addAuthInterceptor(backendHttp);
addAuthInterceptor(apiHttp);
export { backendHttp, apiHttp };
export default http;

View file

@ -4,7 +4,7 @@ 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, updateAdmin } from "../../redux/slices/authSlice";
import { adminList, updateAdmin } from "../../redux/slices/adminSlice";
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
export default function AdminList() {
@ -17,7 +17,7 @@ export default function AdminList() {
const dispatch = useDispatch<AppDispatch>();
// Fetching admin data from the Redux store
const admins = useSelector((state: RootState) => state.auth.admins);
const admins = useSelector((state: RootState) => state.admin.admins);
// Dispatching the API call when the component mounts
useEffect(() => {

View file

@ -96,6 +96,10 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
const navigate = useNavigate();
const [phone, setPhone] = React.useState("");
const roleOptions = [
{ value: "admin", label: "Admin" },
{ value: "user", label: "User" }
];
// Enhanced email validation regex
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
@ -266,11 +270,14 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
}
error={!!errors.role}
>
<MenuItem value="superadmin">
SuperAdmin
</MenuItem>
<MenuItem value="admin">Admin</MenuItem>
<MenuItem value="user">User</MenuItem>
{roleOptions.map((option) => (
<MenuItem
key={option.value}
value={option.value}
>
{option.label}
</MenuItem>
))}
</Select>
)}
/>

View file

@ -16,7 +16,7 @@ import {
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../../redux/store/store";
import { fetchAdminProfile } from "../../redux/slices/authSlice";
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
const ProfilePage = () => {
//Eknoor singh
@ -24,7 +24,7 @@ const ProfilePage = () => {
//Dispatch is called and user, isLoading, and error from Authstate Interface
const dispatch = useDispatch<AppDispatch>();
const { user, isLoading, error } = useSelector(
(state: RootState) => state?.auth
(state: RootState) => state?.profile
);
useEffect(() => {
@ -56,10 +56,6 @@ const ProfilePage = () => {
);
}
console.log(user?.name);
console.log(user?.email);
console.log(user?.role);
return (
<Container sx={{ py: 4 }}>
<Typography variant="h4" gutterBottom>

View file

@ -1,9 +1,13 @@
import { combineReducers } from "@reduxjs/toolkit";
import authReducer from "./slices/authSlice";
import adminReducer from "./slices/adminSlice";
import profileReducer from "./slices/profileSlice";
const rootReducer = combineReducers({
auth: authReducer,
authReducer,
adminReducer,
profileReducer
});
export type RootState = ReturnType<typeof rootReducer>;

View file

@ -0,0 +1,155 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https";
import { toast } from "react-toastify";
// Interfaces
interface User {
token: string | null;
id: string;
name: string;
email: string;
role: string;
phone: string;
}
interface Admin {
id: string;
name: string;
role: string;
email: string;
phone: string;
}
interface AuthState {
user: User | null;
admins: Admin[];
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
token: string | null;
}
// Fetch Admin List
export const adminList = createAsyncThunk<
Admin[],
void,
{ rejectValue: string }
>("FetchAdminList", async (_, { rejectWithValue }) => {
try {
const response = await http.get("auth/admin-list");
return response?.data?.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
// Delete Admin
export const deleteAdmin = createAsyncThunk<
string,
string,
{ rejectValue: string }
>("deleteAdmin", async (id, { rejectWithValue }) => {
try {
const response = await http.delete(`auth/${id}/delete-admin`);
toast.success(response.data?.message);
return id;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
// Update Admin
export const updateAdmin = createAsyncThunk(
"UpdateAdmin",
async (
{ id, name, role }: { id: any; name: string; role: string },
{ rejectWithValue }
) => {
try {
const response = await http.put(`auth/${id}/update-admin`, {
name,
role,
});
toast.success("Admin updated successfully");
return response?.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
}
);
const initialState: AuthState = {
user: null,
admins: [],
isAuthenticated: false,
isLoading: false,
error: null,
token: null,
};
const adminSlice = createSlice({
name: "admin",
initialState,
reducers: {
},
extraReducers: (builder) => {
builder
.addCase(adminList.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(
adminList.fulfilled,
(state, action: PayloadAction<Admin[]>) => {
state.isLoading = false;
state.admins = action.payload;
}
)
.addCase(
adminList.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.isLoading = false;
state.error = action.payload || "An error occurred";
}
)
.addCase(deleteAdmin.pending, (state) => {
state.isLoading = true;
})
.addCase(deleteAdmin.fulfilled, (state, action) => {
state.isLoading = false;
state.admins = state.admins.filter(
(admin) => String(admin.id) !== String(action.payload)
);
})
.addCase(deleteAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to delete admin";
})
.addCase(updateAdmin.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(updateAdmin.fulfilled, (state, action) => {
const updatedAdmin = action.payload;
state.admins = state?.admins?.map((admin) =>
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
);
state.isLoading = false;
})
.addCase(updateAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error =
typeof action.payload === "string"
? action.payload
: "Something went wrong while updating Admin!";
});
},
});
export default adminSlice.reducer;

View file

@ -1,6 +1,5 @@
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
import { backendHttp, apiHttp } from "../../lib/https";
import http from "../../lib/https";
import { toast } from "react-toastify";
// Define types for state
@ -8,6 +7,7 @@ import { toast } from "react-toastify";
//date:- 12-Feb-2025
//Token for the user has been declared
interface User {
data: any;
token: string | null;
map(
arg0: (
@ -44,9 +44,10 @@ export const loginUser = createAsyncThunk<
User,
{ email: string; password: string },
{ rejectValue: string }
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
>("LoginUser", async ({ email, password }, { rejectWithValue }) => {
try {
const response = await apiHttp.post("auth/login", {
// this is endpoint not action name
const response = await http.post("auth/login", {
email,
password,
});
@ -73,7 +74,7 @@ export const registerUser = createAsyncThunk<
{ rejectValue: string }
>("auth/signup", async (data, { rejectWithValue }) => {
try {
const response = await apiHttp.post("auth/signup", data);
const response = await http.post("auth/signup", data);
return response.data;
} catch (error: any) {
return rejectWithValue(
@ -82,111 +83,6 @@ export const registerUser = createAsyncThunk<
}
});
//created by Eknoor and jaanvi
//date: 10-Feb-2025
//Fetching list of admins
export const adminList = createAsyncThunk<
Admin[],
void,
{ rejectValue: string }
>("/auth", async (_, { rejectWithValue }) => {
try {
const response = await apiHttp.get("/auth");
console.log(response?.data?.data);
return response?.data?.data?.map(
(admin: {
id: string;
name: string;
role: string;
email: string;
}) => ({
id: admin?.id,
name: admin?.name,
role: admin?.role || "N/A",
email: admin?.email,
})
);
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
//created by Eknoor
//date: 11-Feb-2025
//function for deleting admin
export const deleteAdmin = createAsyncThunk<
string,
string,
{ rejectValue: string }
>("deleteAdmin", async (id, { rejectWithValue }) => {
try {
const response = await apiHttp.delete(`/auth/${id}`);
toast.success(response.data?.message);
return id;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
});
export const updateAdmin = createAsyncThunk(
"/auth/id",
async (
{ id, name, role }: { id: any; name: string; role: string },
{ rejectWithValue }
) => {
try {
const response = await apiHttp.put(`/auth/${id}`, { name, role });
toast.success("Admin updated successfully");
console.log(response?.data);
return response?.data;
} catch (error: any) {
return rejectWithValue(
error.response?.data?.message || "An error occurred"
);
}
}
);
//Eknoor singh
//date:- 12-Feb-2025
//Function for fetching profile of a particular user has been implemented with Redux.
export const fetchAdminProfile = createAsyncThunk<
User,
void,
{ rejectValue: string }
>("auth/fetchAdminProfile", async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await apiHttp?.get("/auth/profile", {
headers: { Authorization: `Bearer ${token}` }, // Ensure 'Bearer' prefix
});
console.log("API Response:", response?.data); // Debugging
if (!response.data?.data) {
throw new Error("Invalid API response");
}
return response?.data?.data; // Fix: Return only `data`, assuming it contains user info.
} catch (error: any) {
console.error(
"Profile Fetch Error:",
error?.response?.data || error?.message
);
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
}
});
const initialState: AuthState = {
user: null,
admins: [],
@ -202,17 +98,7 @@ const initialState: AuthState = {
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
logout: (state) => {
state.user = null;
state.isAuthenticated = false;
//Eknoor singh
//date:- 12-Feb-2025
//Token is removed from local storage and set to null
state.token = null;
localStorage.removeItem("authToken");
},
},
reducers: {},
extraReducers: (builder) => {
builder
// Login
@ -223,9 +109,10 @@ const authSlice = createSlice({
.addCase(loginUser.fulfilled, (state, action) => {
state.isLoading = false;
state.isAuthenticated = true;
state.user = action.payload; // Fix: Extract correct payload
state.token = action.payload.token; // Store token in Redux
state.user = action.payload.data;
state.token = action.payload.data.token;
})
.addCase(
loginUser.rejected,
(state, action: PayloadAction<string | undefined>) => {
@ -252,83 +139,16 @@ const authSlice = createSlice({
state.isLoading = false;
state.error = action.payload || "An error occurred";
}
)
);
// created by Jaanvi and Eknoor
//AdminList
.addCase(adminList.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(
adminList.fulfilled,
(state, action: PayloadAction<Admin[]>) => {
state.isLoading = false;
state.admins = action.payload;
}
)
// created by Jaanvi and Eknoor
//AdminList
.addCase(
adminList.rejected,
(state, action: PayloadAction<string | undefined>) => {
state.isLoading = false;
state.error = action.payload || "An error occurred";
}
)
//created by Eknoor
//date: 11-Feb-2025
//cases for deleting admin
.addCase(deleteAdmin.pending, (state) => {
state.isLoading = true;
})
.addCase(deleteAdmin.fulfilled, (state, action) => {
state.isLoading = false;
state.admins = state.admins.filter(
(admin) => String(admin.id) !== String(action.payload)
);
})
.addCase(deleteAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to delete admin";
})
.addCase(updateAdmin.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(updateAdmin.fulfilled, (state, action) => {
const updatedAdmin = action.payload;
state.admins = state?.admins?.map((admin) =>
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
);
state.isLoading = false;
})
.addCase(updateAdmin.rejected, (state, action) => {
state.isLoading = false;
state.error =
action.payload ||
"Something went wrong while updating Admin!!";
})
//Eknoor singh
//date:- 12-Feb-2025
//Reducers for fetching profiles has been implemented
.addCase(fetchAdminProfile.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(fetchAdminProfile.fulfilled, (state, action) => {
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(fetchAdminProfile.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to fetch admin profile";
});
//Eknoor singh
//date:- 12-Feb-2025
//Reducers for fetching profiles has been implemente
},
});
export const { logout } = authSlice.actions;
// export const { logout } = authSlice.actions;
export default authSlice.reducer;

View file

@ -0,0 +1,72 @@
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import http from "../../lib/https";
interface User {
token: string | null;
id: string;
name: string;
email: string;
role: string;
phone: string;
}
interface AuthState {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
}
export const fetchAdminProfile = createAsyncThunk<
User,
void,
{ rejectValue: string }
>("GetAdminProfile", async (_, { rejectWithValue }) => {
try {
const token = localStorage?.getItem("authToken");
if (!token) throw new Error("No token found");
const response = await http.get("/auth/profile", {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.data?.data) throw new Error("Invalid API response");
return response.data.data;
} catch (error: any) {
return rejectWithValue(
error?.response?.data?.message || "An error occurred"
);
}
});
const initialState: AuthState = {
user: null,
isAuthenticated: false,
isLoading: false,
error: null,
};
const profileSlice = createSlice({
name: "profile",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchAdminProfile.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(fetchAdminProfile.fulfilled, (state, action) => {
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(fetchAdminProfile.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload || "Failed to fetch admin profile";
});
},
});
export default profileSlice.reducer;

View file

@ -1,8 +1,12 @@
import { configureStore } from '@reduxjs/toolkit';
import authReducer from '../slices/authSlice.ts'
import adminReducer from "../slices/adminSlice.ts"
import profileReducer from "../slices/profileSlice.ts"
const store = configureStore({
reducer: {
auth: authReducer,
admin: adminReducer,
profile: profileReducer
},
});

View file

@ -1,7 +1,16 @@
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
import {
Routes as BaseRoutes,
Navigate,
Route,
RouteProps,
} from "react-router-dom";
import React, { Suspense } from "react";
import { useSelector } from "react-redux";
import { RootState } from "./redux/store/store";
import LoadingComponent from "./components/Loading";
import DashboardLayout from "./layouts/DashboardLayout";
// Page imports
import Login from "./pages/Auth/Login";
import SignUp from "./pages/Auth/SignUp";
import Dashboard from "./pages/Dashboard";
@ -9,27 +18,44 @@ import Vehicles from "./pages/Vehicles";
import AdminList from "./pages/AdminList";
import ProfilePage from "./pages/ProfilePage";
import SuperAdminRouter from "./superAdminRouter";
function ProtectedRoute({
caps,
component,
}: {
interface ProtectedRouteProps {
caps: string[];
component: React.ReactNode;
}) {
if (!localStorage.getItem("authToken"))
return <Navigate to={`/auth/login`} replace />;
return component;
}
interface SuperAdminRouteProps {
children: React.ReactNode;
}
// Protected Route Component
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ caps, component }) => {
if (!localStorage.getItem("authToken")) {
return <Navigate to="/auth/login" replace />;
}
return <>{component}</>;
};
// Super Admin Route Component
const SuperAdminRoute: React.FC<SuperAdminRouteProps> = ({ children }) => {
const userRole = useSelector(
(state: RootState) => state.profile.user?.role
);
if (userRole !== "superadmin") {
return <Navigate to="/panel/dashboard" replace />;
}
return <>{children}</>;
};
// Combined Router Component
export default function AppRouter() {
return (
<Suspense fallback={<LoadingComponent />}>
<BaseRoutes>
{/* Default Route */}
<Route element={<Navigate to="/auth/login" replace />} index />
{/* Auth Routes */}
<Route path="/auth">
<Route
path=""
@ -38,8 +64,18 @@ export default function AppRouter() {
/>
<Route path="login" element={<Login />} />
<Route path="signup" element={<SignUp />} />
<Route
path="profile"
element={
<ProtectedRoute
caps={[]}
component={<ProfilePage />}
/>
}
/>
</Route>
{/* Dashboard Routes */}
<Route path="/panel" element={<DashboardLayout />}>
<Route
path="dashboard"
@ -65,26 +101,17 @@ export default function AppRouter() {
<ProtectedRoute
caps={[]}
component={
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//Admin list put under protected route for specific use
<SuperAdminRouter>
<SuperAdminRoute>
<AdminList />
</SuperAdminRouter>
</SuperAdminRoute>
}
/>
}
/>
<Route path="*" element={<>404</>} />
</Route>
<Route
path="/auth/profile"
element={
<ProtectedRoute caps={[]} component={<ProfilePage />} />
}
/>
{/* Catch-all Route */}
<Route path="*" element={<>404</>} />
</BaseRoutes>
</Suspense>

View file

@ -1,25 +0,0 @@
//Eknoor singh and jaanvi
//date:- 12-Feb-2025
//seperate route for super admin implemented
import React from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import { RootState } from "./redux/store/store";
interface SuperAdminRouteProps {
children: React.ReactNode;
}
const SuperAdminRouter: React.FC<SuperAdminRouteProps> = ({ children }) => {
const userRole = useSelector((state: RootState) => state.auth.user?.role);
if (userRole !== "superadmin") {
// Redirect to dashboard if user is not a superadmin
return <Navigate to="/panel/dashboard" replace />;
}
return <>{children}</>;
};
export default SuperAdminRouter;