Add create-admin script to package.json and set up /api/users route in server.js for user management functionality.

This commit is contained in:
Alvin committed 2025-06-10 09:47:17 +02:00
1 parent ef07016a14
commit d44338aa95
39 files changed
+22271 -1

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
+113
View File
@@ -0,0 +1,113 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import Login from './components/Login';
import Dashboard from './components/Dashboard';
import CustomerList from './components/CustomerList';
import CustomerDetail from './components/CustomerDetail';
import CarModifications from './components/CarModifications';
import ContactHistory from './components/ContactHistory';
import PrivateRoute from './components/PrivateRoute';
import UserManagement from './components/UserManagement';
// Create a theme that matches the "stoer en snel" (tough and fast) requirement
const theme = createTheme({
palette: {
mode: 'dark',
primary: {
main: '#ff3d00', // Bright orange for speed and energy
},
secondary: {
main: '#212121', // Dark gray for toughness
},
background: {
default: '#121212',
paper: '#1e1e1e',
},
},
typography: {
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
h1: {
fontWeight: 700,
},
h2: {
fontWeight: 700,
},
},
components: {
MuiButton: {
styleOverrides: {
root: {
borderRadius: 0,
textTransform: 'none',
fontWeight: 600,
},
},
},
},
});
function App() {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/"
element={
<PrivateRoute>
<Dashboard />
</PrivateRoute>
}
/>
<Route
path="/customers"
element={
<PrivateRoute>
<CustomerList />
</PrivateRoute>
}
/>
<Route
path="/customers/:id"
element={
<PrivateRoute>
<CustomerDetail />
</PrivateRoute>
}
/>
<Route
path="/modifications"
element={
<PrivateRoute>
<CarModifications />
</PrivateRoute>
}
/>
<Route
path="/contacts"
element={
<PrivateRoute>
<ContactHistory />
</PrivateRoute>
}
/>
<Route
path="/users"
element={
<PrivateRoute>
<UserManagement />
</PrivateRoute>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Router>
</ThemeProvider>
);
}
export default App;
+8
View File
@@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
+164
View File
@@ -0,0 +1,164 @@
import React, { useState } from 'react';
import {
Container,
Typography,
Grid,
Paper,
Card,
CardContent,
CardMedia,
Button,
Box,
TextField,
InputAdornment,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
const CarModifications = () => {
const [searchTerm, setSearchTerm] = useState('');
// Sample modifications data - in a real app, this would come from an API
const modifications = [
{
id: 1,
name: 'Performance Chip',
description: 'Increase engine power and torque with our custom ECU tuning',
price: '€299',
image: 'https://via.placeholder.com/300x200?text=Performance+Chip',
category: 'Engine',
},
{
id: 2,
name: 'Sport Exhaust System',
description: 'High-flow exhaust system for better sound and performance',
price: '€599',
image: 'https://via.placeholder.com/300x200?text=Exhaust+System',
category: 'Exhaust',
},
{
id: 3,
name: 'Lowering Springs',
description: 'Sport suspension lowering springs for improved handling',
price: '€399',
image: 'https://via.placeholder.com/300x200?text=Lowering+Springs',
category: 'Suspension',
},
{
id: 4,
name: 'Cold Air Intake',
description: 'Improved air flow for better engine performance',
price: '€199',
image: 'https://via.placeholder.com/300x200?text=Cold+Air+Intake',
category: 'Engine',
},
{
id: 5,
name: 'Sport Brake Kit',
description: 'Upgraded brake system for better stopping power',
price: '€899',
image: 'https://via.placeholder.com/300x200?text=Brake+Kit',
category: 'Brakes',
},
{
id: 6,
name: 'Wheel Spacers',
description: 'Improve stance and handling with wheel spacers',
price: '€149',
image: 'https://via.placeholder.com/300x200?text=Wheel+Spacers',
category: 'Wheels',
},
];
const filteredModifications = modifications.filter((mod) =>
mod.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
mod.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
mod.category.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
Car Modifications
</Typography>
<Box sx={{ mb: 4 }}>
<TextField
fullWidth
variant="outlined"
placeholder="Search modifications..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</Box>
<Grid container spacing={3}>
{filteredModifications.map((mod) => (
<Grid item xs={12} sm={6} md={4} key={mod.id}>
<Card
sx={{
height: '100%',
display: 'flex',
flexDirection: 'column',
transition: 'transform 0.2s',
'&:hover': {
transform: 'scale(1.02)',
},
}}
>
<CardMedia
component="img"
height="200"
image={mod.image}
alt={mod.name}
/>
<CardContent sx={{ flexGrow: 1 }}>
<Typography gutterBottom variant="h5" component="h2">
{mod.name}
</Typography>
<Typography
variant="body2"
color="text.secondary"
sx={{ mb: 2 }}
>
{mod.description}
</Typography>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography variant="h6" color="primary">
{mod.price}
</Typography>
<Typography
variant="body2"
sx={{
backgroundColor: 'primary.main',
color: 'white',
px: 1,
py: 0.5,
borderRadius: 1,
}}
>
{mod.category}
</Typography>
</Box>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Container>
);
};
export default CarModifications;
+194
View File
@@ -0,0 +1,194 @@
import React, { useState, useEffect } from 'react';
import {
Container,
Typography,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Box,
Chip,
IconButton,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import axios from 'axios';
const ContactHistory = () => {
const [contacts, setContacts] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
const [selectedContact, setSelectedContact] = useState(null);
const [openDialog, setOpenDialog] = useState(false);
useEffect(() => {
const fetchContacts = async () => {
try {
const response = await axios.get('http://localhost:5000/api/contacts', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
setContacts(response.data);
} catch (error) {
console.error('Error fetching contacts:', error);
}
};
fetchContacts();
}, []);
const filteredContacts = contacts.filter((contact) =>
contact.customer?.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
contact.notes.toLowerCase().includes(searchTerm.toLowerCase()) ||
contact.type.toLowerCase().includes(searchTerm.toLowerCase())
);
const handleViewContact = (contact) => {
setSelectedContact(contact);
setOpenDialog(true);
};
const getContactTypeColor = (type) => {
switch (type) {
case 'phone':
return 'primary';
case 'email':
return 'success';
case 'in-person':
return 'warning';
default:
return 'default';
}
};
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
Contact History
</Typography>
<Box sx={{ mb: 3 }}>
<TextField
fullWidth
variant="outlined"
placeholder="Search contacts..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
InputProps={{
startAdornment: (
<SearchIcon sx={{ mr: 1, color: 'text.secondary' }} />
),
}}
/>
</Box>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Customer</TableCell>
<TableCell>Type</TableCell>
<TableCell>Date</TableCell>
<TableCell>Notes</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{filteredContacts.map((contact) => (
<TableRow key={contact._id}>
<TableCell>{contact.customer?.name}</TableCell>
<TableCell>
<Chip
label={contact.type}
color={getContactTypeColor(contact.type)}
size="small"
/>
</TableCell>
<TableCell>
{new Date(contact.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
{contact.notes.length > 50
? `${contact.notes.substring(0, 50)}...`
: contact.notes}
</TableCell>
<TableCell>
<IconButton
onClick={() => handleViewContact(contact)}
color="primary"
>
<VisibilityIcon />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Dialog
open={openDialog}
onClose={() => setOpenDialog(false)}
maxWidth="md"
fullWidth
>
{selectedContact && (
<>
<DialogTitle>
Contact Details - {selectedContact.customer?.name}
</DialogTitle>
<DialogContent>
<Box sx={{ mt: 2 }}>
<Typography variant="subtitle1" gutterBottom>
<strong>Type:</strong>{' '}
<Chip
label={selectedContact.type}
color={getContactTypeColor(selectedContact.type)}
size="small"
/>
</Typography>
<Typography variant="subtitle1" gutterBottom>
<strong>Date:</strong>{' '}
{new Date(selectedContact.createdAt).toLocaleString()}
</Typography>
<Typography variant="subtitle1" gutterBottom>
<strong>Notes:</strong>
</Typography>
<Typography variant="body1" sx={{ mt: 1 }}>
{selectedContact.notes}
</Typography>
{selectedContact.followUp?.required && (
<Box sx={{ mt: 2 }}>
<Typography variant="subtitle1" gutterBottom>
<strong>Follow-up Required:</strong>
</Typography>
<Typography variant="body1">
Date: {new Date(selectedContact.followUp.date).toLocaleDateString()}
</Typography>
<Typography variant="body1">
Notes: {selectedContact.followUp.notes}
</Typography>
</Box>
)}
</Box>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpenDialog(false)}>Close</Button>
</DialogActions>
</>
)}
</Dialog>
</Container>
);
};
export default ContactHistory;
+222
View File
@@ -0,0 +1,222 @@
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import {
Container,
Paper,
Typography,
Box,
Grid,
TextField,
Button,
List,
ListItem,
ListItemText,
Divider,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
} from '@mui/material';
import axios from 'axios';
const CustomerDetail = () => {
const { id } = useParams();
const [customer, setCustomer] = useState(null);
const [contacts, setContacts] = useState([]);
const [newContact, setNewContact] = useState({
type: 'phone',
notes: '',
followUp: {
required: false,
date: '',
notes: '',
},
});
const [openDialog, setOpenDialog] = useState(false);
useEffect(() => {
const fetchCustomerData = async () => {
try {
const [customerResponse, contactsResponse] = await Promise.all([
axios.get(`http://localhost:5000/api/customers/${id}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
}),
axios.get(`http://localhost:5000/api/contacts/customer/${id}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
}),
]);
setCustomer(customerResponse.data);
setContacts(contactsResponse.data);
} catch (error) {
console.error('Error fetching customer data:', error);
}
};
fetchCustomerData();
}, [id]);
const handleAddContact = async () => {
try {
const response = await axios.post(
'http://localhost:5000/api/contacts',
{
...newContact,
customer: id,
},
{
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
}
);
setContacts([...contacts, response.data]);
setOpenDialog(false);
setNewContact({
type: 'phone',
notes: '',
followUp: {
required: false,
date: '',
notes: '',
},
});
} catch (error) {
console.error('Error adding contact:', error);
}
};
if (!customer) return null;
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
Customer Details
</Typography>
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Personal Information
</Typography>
<Box sx={{ mt: 2 }}>
<Typography variant="subtitle1">Name: {customer.name}</Typography>
<Typography variant="subtitle1">Email: {customer.email}</Typography>
<Typography variant="subtitle1">Phone: {customer.phone}</Typography>
</Box>
</Paper>
</Grid>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Car Information
</Typography>
<Box sx={{ mt: 2 }}>
<Typography variant="subtitle1">
Make: {customer.carDetails?.make}
</Typography>
<Typography variant="subtitle1">
Model: {customer.carDetails?.model}
</Typography>
<Typography variant="subtitle1">
Year: {customer.carDetails?.year}
</Typography>
<Typography variant="subtitle1">
Modifications: {customer.carDetails?.modifications?.join(', ')}
</Typography>
</Box>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
<Typography variant="h6">Contact History</Typography>
<Button
variant="contained"
color="primary"
onClick={() => setOpenDialog(true)}
>
Add Contact
</Button>
</Box>
<List>
{contacts.map((contact, index) => (
<React.Fragment key={contact._id}>
<ListItem>
<ListItemText
primary={`${contact.type} - ${new Date(
contact.createdAt
).toLocaleDateString()}`}
secondary={contact.notes}
/>
</ListItem>
{index < contacts.length - 1 && <Divider />}
</React.Fragment>
))}
</List>
</Paper>
</Grid>
</Grid>
<Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
<DialogTitle>Add New Contact</DialogTitle>
<DialogContent>
<Box sx={{ mt: 2 }}>
<TextField
select
fullWidth
label="Contact Type"
value={newContact.type}
onChange={(e) =>
setNewContact({ ...newContact, type: e.target.value })
}
SelectProps={{
native: true,
}}
sx={{ mb: 2 }}
>
<option value="phone">Phone</option>
<option value="email">Email</option>
<option value="in-person">In Person</option>
<option value="other">Other</option>
</TextField>
<TextField
fullWidth
multiline
rows={4}
label="Notes"
value={newContact.notes}
onChange={(e) =>
setNewContact({ ...newContact, notes: e.target.value })
}
sx={{ mb: 2 }}
/>
<TextField
fullWidth
type="date"
label="Follow-up Date"
value={newContact.followUp.date}
onChange={(e) =>
setNewContact({
...newContact,
followUp: { ...newContact.followUp, date: e.target.value },
})
}
InputLabelProps={{
shrink: true,
}}
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpenDialog(false)}>Cancel</Button>
<Button onClick={handleAddContact} variant="contained" color="primary">
Add Contact
</Button>
</DialogActions>
</Dialog>
</Container>
);
};
export default CustomerDetail;
+109
View File
@@ -0,0 +1,109 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Container,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Typography,
Box,
IconButton,
InputAdornment,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import axios from 'axios';
const CustomerList = () => {
const navigate = useNavigate();
const [customers, setCustomers] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
const fetchCustomers = async () => {
try {
const response = await axios.get('http://localhost:5000/api/customers', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
setCustomers(response.data);
} catch (error) {
console.error('Error fetching customers:', error);
}
};
fetchCustomers();
}, []);
const filteredCustomers = customers.filter((customer) =>
customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
customer.email.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
Customers
</Typography>
<Box sx={{ mb: 3 }}>
<TextField
fullWidth
variant="outlined"
placeholder="Search customers..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</Box>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Email</TableCell>
<TableCell>Phone</TableCell>
<TableCell>Car</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{filteredCustomers.map((customer) => (
<TableRow key={customer._id}>
<TableCell>{customer.name}</TableCell>
<TableCell>{customer.email}</TableCell>
<TableCell>{customer.phone}</TableCell>
<TableCell>
{customer.carDetails?.make} {customer.carDetails?.model}
</TableCell>
<TableCell>
<IconButton
onClick={() => navigate(`/customers/${customer._id}`)}
color="primary"
>
<VisibilityIcon />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Container>
);
};
export default CustomerList;
+111
View File
@@ -0,0 +1,111 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Container,
Grid,
Paper,
Typography,
Box,
} from '@mui/material';
import DirectionsCarIcon from '@mui/icons-material/DirectionsCar';
import PeopleIcon from '@mui/icons-material/People';
import ChatIcon from '@mui/icons-material/Chat';
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
import axios from 'axios';
const Dashboard = () => {
const navigate = useNavigate();
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
const checkAdminStatus = async () => {
try {
const response = await axios.get('http://localhost:5000/api/users/me', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
setIsAdmin(response.data.role === 'admin');
} catch (error) {
console.error('Error checking admin status:', error);
}
};
checkAdminStatus();
}, []);
const menuItems = [
{
title: 'Customers',
icon: <PeopleIcon sx={{ fontSize: 40 }} />,
description: 'View and manage customer information',
path: '/customers',
},
{
title: 'Car Modifications',
icon: <DirectionsCarIcon sx={{ fontSize: 40 }} />,
description: 'Browse available car modifications',
path: '/modifications',
},
{
title: 'Contact History',
icon: <ChatIcon sx={{ fontSize: 40 }} />,
description: 'View customer interaction history',
path: '/contacts',
},
...(isAdmin ? [{
title: 'User Management',
icon: <AdminPanelSettingsIcon sx={{ fontSize: 40 }} />,
description: 'Manage system users and permissions',
path: '/users',
}] : []),
];
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold' }}>
Dashboard
</Typography>
<Grid container spacing={3}>
{menuItems.map((item) => (
<Grid item xs={12} md={4} key={item.title}>
<Paper
sx={{
p: 3,
display: 'flex',
flexDirection: 'column',
height: 240,
cursor: 'pointer',
transition: 'transform 0.2s',
'&:hover': {
transform: 'scale(1.02)',
},
}}
onClick={() => navigate(item.path)}
>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
flexGrow: 1,
}}
>
{item.icon}
<Typography variant="h6" component="h2" sx={{ mt: 2, fontWeight: 'bold' }}>
{item.title}
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1, textAlign: 'center' }}>
{item.description}
</Typography>
</Box>
</Paper>
</Grid>
))}
</Grid>
</Container>
);
};
export default Dashboard;
+107
View File
@@ -0,0 +1,107 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Container,
Box,
TextField,
Button,
Typography,
Paper,
} from '@mui/material';
import axios from 'axios';
const Login = () => {
const navigate = useNavigate();
const [formData, setFormData] = useState({
username: '',
password: '',
});
const [error, setError] = useState('');
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('http://localhost:5000/api/auth/login', formData);
localStorage.setItem('token', response.data.token);
navigate('/');
} catch (err) {
setError('Invalid username or password');
}
};
return (
<Container component="main" maxWidth="xs">
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Paper
elevation={3}
sx={{
padding: 4,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
width: '100%',
}}
>
<Typography component="h1" variant="h5" sx={{ mb: 3 }}>
Car Tuning CRM
</Typography>
<Box component="form" onSubmit={handleSubmit} sx={{ mt: 1, width: '100%' }}>
<TextField
margin="normal"
required
fullWidth
id="username"
label="Username"
name="username"
autoComplete="username"
autoFocus
value={formData.username}
onChange={handleChange}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={formData.password}
onChange={handleChange}
/>
{error && (
<Typography color="error" sx={{ mt: 2 }}>
{error}
</Typography>
)}
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign In
</Button>
</Box>
</Paper>
</Box>
</Container>
);
};
export default Login;
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import { Navigate } from 'react-router-dom';
const PrivateRoute = ({ children }) => {
const isAuthenticated = localStorage.getItem('token') !== null;
return isAuthenticated ? children : <Navigate to="/login" />;
};
export default PrivateRoute;
+265
View File
@@ -0,0 +1,265 @@
import React, { useState, useEffect } from 'react';
import {
Container,
Typography,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Button,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
IconButton,
Box,
Alert,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import axios from 'axios';
const UserManagement = () => {
const [users, setUsers] = useState([]);
const [openDialog, setOpenDialog] = useState(false);
const [selectedUser, setSelectedUser] = useState(null);
const [formData, setFormData] = useState({
username: '',
password: '',
role: 'staff',
});
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
useEffect(() => {
fetchUsers();
}, []);
const fetchUsers = async () => {
try {
const response = await axios.get('http://localhost:5000/api/users', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
setUsers(response.data);
} catch (error) {
console.error('Error fetching users:', error);
setError('Failed to fetch users');
}
};
const handleOpenDialog = (user = null) => {
if (user) {
setSelectedUser(user);
setFormData({
username: user.username,
password: '',
role: user.role,
});
} else {
setSelectedUser(null);
setFormData({
username: '',
password: '',
role: 'staff',
});
}
setOpenDialog(true);
};
const handleCloseDialog = () => {
setOpenDialog(false);
setSelectedUser(null);
setFormData({
username: '',
password: '',
role: 'staff',
});
setError('');
};
const handleSubmit = async (e) => {
e.preventDefault();
setError('');
setSuccess('');
try {
if (selectedUser) {
// Update existing user
await axios.put(
`http://localhost:5000/api/users/${selectedUser._id}`,
formData,
{
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}
);
setSuccess('User updated successfully');
} else {
// Create new user
await axios.post(
'http://localhost:5000/api/users',
formData,
{
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}
);
setSuccess('User created successfully');
}
handleCloseDialog();
fetchUsers();
} catch (error) {
setError(error.response?.data?.message || 'An error occurred');
}
};
const handleDelete = async (userId) => {
if (window.confirm('Are you sure you want to delete this user?')) {
try {
await axios.delete(`http://localhost:5000/api/users/${userId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
setSuccess('User deleted successfully');
fetchUsers();
} catch (error) {
setError('Failed to delete user');
}
}
};
return (
<Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
<Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
User Management
</Typography>
<Button
variant="contained"
color="primary"
onClick={() => handleOpenDialog()}
>
Add New User
</Button>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 2 }}>
{error}
</Alert>
)}
{success && (
<Alert severity="success" sx={{ mb: 2 }}>
{success}
</Alert>
)}
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Username</TableCell>
<TableCell>Role</TableCell>
<TableCell>Created At</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user) => (
<TableRow key={user._id}>
<TableCell>{user.username}</TableCell>
<TableCell>{user.role}</TableCell>
<TableCell>
{new Date(user.createdAt).toLocaleDateString()}
</TableCell>
<TableCell>
<IconButton
onClick={() => handleOpenDialog(user)}
color="primary"
>
<EditIcon />
</IconButton>
<IconButton
onClick={() => handleDelete(user._id)}
color="error"
>
<DeleteIcon />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
<DialogTitle>
{selectedUser ? 'Edit User' : 'Add New User'}
</DialogTitle>
<DialogContent>
<Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}>
<TextField
fullWidth
label="Username"
value={formData.username}
onChange={(e) =>
setFormData({ ...formData, username: e.target.value })
}
margin="normal"
required
/>
<TextField
fullWidth
label="Password"
type="password"
value={formData.password}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
margin="normal"
required={!selectedUser}
helperText={
selectedUser
? 'Leave blank to keep current password'
: 'Required for new users'
}
/>
<TextField
fullWidth
select
label="Role"
value={formData.role}
onChange={(e) =>
setFormData({ ...formData, role: e.target.value })
}
margin="normal"
SelectProps={{
native: true,
}}
>
<option value="staff">Staff</option>
<option value="admin">Admin</option>
</TextField>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDialog}>Cancel</Button>
<Button onClick={handleSubmit} variant="contained" color="primary">
{selectedUser ? 'Update' : 'Create'}
</Button>
</DialogActions>
</Dialog>
</Container>
);
};
export default UserManagement;
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+13
View File
@@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';