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
2025-06-10 09:47:17 +02:00
parent ef07016a14
commit d44338aa95
39 changed files with 22271 additions and 1 deletions

3
.env Normal file
View File

@@ -0,0 +1,3 @@
MONGODB_URI=mongodb://localhost:27017/car-tuning-crm
JWT_SECRET=your-secret-key
PORT=5000

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules

94
README.md Normal file
View File

@@ -0,0 +1,94 @@
# Car Tuning CRM System
A modern CRM system for car tuning businesses, built with React and Node.js.
## Features
- User authentication and authorization
- Customer management
- Contact history tracking
- Car modification details
- Modern, responsive UI
- Search and filter capabilities
## Prerequisites
- Node.js (v14 or higher)
- MongoDB
- npm or yarn
## Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd car-tuning-crm
```
2. Install backend dependencies:
```bash
npm install
```
3. Install frontend dependencies:
```bash
cd client
npm install
```
4. Create a `.env` file in the root directory with the following variables:
```
MONGODB_URI=mongodb://localhost:27017/car-tuning-crm
JWT_SECRET=your-secret-key
PORT=5000
```
## Running the Application
1. Start the backend server:
```bash
npm run dev
```
2. In a new terminal, start the frontend development server:
```bash
cd client
npm start
```
The application will be available at:
- Frontend: http://localhost:3000
- Backend API: http://localhost:5000
## API Endpoints
### Authentication
- POST /api/auth/login - User login
- POST /api/auth/register - Register new user (admin only)
### Customers
- GET /api/customers - Get all customers
- GET /api/customers/:id - Get single customer
- POST /api/customers - Create new customer
- PUT /api/customers/:id - Update customer
- DELETE /api/customers/:id - Delete customer
### Contacts
- GET /api/contacts/customer/:customerId - Get all contacts for a customer
- POST /api/contacts - Create new contact
- PUT /api/contacts/:id - Update contact
- DELETE /api/contacts/:id - Delete contact
## Security
- All routes except login are protected with JWT authentication
- Passwords are hashed using bcrypt
- CORS is enabled for the frontend domain
## Contributing
1. Fork the repository
2. Create your feature branch
3. Commit your changes
4. Push to the branch
5. Create a new Pull Request

23
client/.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
client/README.md Normal file
View File

@@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

18156
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

45
client/package.json Normal file
View File

@@ -0,0 +1,45 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@mui/icons-material": "^7.1.1",
"@mui/material": "^7.1.1",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.9.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
client/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
client/public/index.html Normal file
View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
client/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
client/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
client/public/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
client/src/App.css Normal file
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
client/src/App.js Normal file
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
client/src/App.test.js Normal file
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();
});

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;

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;

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;

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;

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;

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;

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;

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
client/src/index.css Normal file
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
client/src/index.js Normal file
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
client/src/logo.svg Normal file
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

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
client/src/setupTests.js Normal file
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';

14
docker-compose.yml Normal file
View File

@@ -0,0 +1,14 @@
services:
mongodb:
image: mongo:latest
container_name: car-tuning-crm-mongodb
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
environment:
- MONGO_INITDB_DATABASE=car-tuning-crm
volumes:
mongodb_data:

20
middleware/auth.js Normal file
View File

@@ -0,0 +1,20 @@
const jwt = require('jsonwebtoken');
module.exports = function (req, res, next) {
// Get token from header
const token = req.header('Authorization')?.replace('Bearer ', '');
// Check if no token
if (!token) {
return res.status(401).json({ message: 'No token, authorization denied' });
}
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ message: 'Token is not valid' });
}
};

2013
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,8 @@
"start": "node server.js", "start": "node server.js",
"dev": "nodemon server.js", "dev": "nodemon server.js",
"client": "cd client && npm start", "client": "cd client && npm start",
"dev:full": "concurrently \"npm run dev\" \"npm run client\"" "dev:full": "concurrently \"npm run dev\" \"npm run client\"",
"create-admin": "node scripts/createAdmin.js"
}, },
"dependencies": { "dependencies": {
"express": "^4.18.2", "express": "^4.18.2",

69
routes/auth.js Normal file
View File

@@ -0,0 +1,69 @@
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
// Login route
router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
// Find user
const user = await User.findOne({ username });
if (!user) {
return res.status(400).json({ message: 'Invalid credentials' });
}
// Check password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ message: 'Invalid credentials' });
}
// Create token
const token = jwt.sign(
{ id: user._id, role: user.role },
process.env.JWT_SECRET || 'your-secret-key',
{ expiresIn: '1d' }
);
res.json({ token });
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Register route (for admin use only)
router.post('/register', async (req, res) => {
try {
const { username, password, role } = req.body;
// Check if user exists
let user = await User.findOne({ username });
if (user) {
return res.status(400).json({ message: 'User already exists' });
}
// Create new user
user = new User({
username,
password,
role: role || 'staff',
});
// Hash password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
res.status(201).json({ message: 'User created successfully' });
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

65
routes/contacts.js Normal file
View File

@@ -0,0 +1,65 @@
const express = require('express');
const router = express.Router();
const Contact = require('../models/Contact');
// Get all contacts for a customer
router.get('/customer/:customerId', async (req, res) => {
try {
const contacts = await Contact.find({ customer: req.params.customerId })
.sort({ createdAt: -1 })
.populate('user', 'username');
res.json(contacts);
} catch (error) {
console.error('Error fetching contacts:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Create new contact
router.post('/', async (req, res) => {
try {
const contact = new Contact({
...req.body,
user: req.user.id, // This will be set by the auth middleware
});
await contact.save();
res.status(201).json(contact);
} catch (error) {
console.error('Error creating contact:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Update contact
router.put('/:id', async (req, res) => {
try {
const contact = await Contact.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!contact) {
return res.status(404).json({ message: 'Contact not found' });
}
res.json(contact);
} catch (error) {
console.error('Error updating contact:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Delete contact
router.delete('/:id', async (req, res) => {
try {
const contact = await Contact.findByIdAndDelete(req.params.id);
if (!contact) {
return res.status(404).json({ message: 'Contact not found' });
}
res.json({ message: 'Contact deleted successfully' });
} catch (error) {
console.error('Error deleting contact:', error);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

74
routes/customers.js Normal file
View File

@@ -0,0 +1,74 @@
const express = require('express');
const router = express.Router();
const Customer = require('../models/Customer');
// Get all customers
router.get('/', async (req, res) => {
try {
const customers = await Customer.find().sort({ name: 1 });
res.json(customers);
} catch (error) {
console.error('Error fetching customers:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Get single customer
router.get('/:id', async (req, res) => {
try {
const customer = await Customer.findById(req.params.id);
if (!customer) {
return res.status(404).json({ message: 'Customer not found' });
}
res.json(customer);
} catch (error) {
console.error('Error fetching customer:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Create customer
router.post('/', async (req, res) => {
try {
const customer = new Customer(req.body);
await customer.save();
res.status(201).json(customer);
} catch (error) {
console.error('Error creating customer:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Update customer
router.put('/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndUpdate(
req.params.id,
{ ...req.body, updatedAt: Date.now() },
{ new: true }
);
if (!customer) {
return res.status(404).json({ message: 'Customer not found' });
}
res.json(customer);
} catch (error) {
console.error('Error updating customer:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Delete customer
router.delete('/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndDelete(req.params.id);
if (!customer) {
return res.status(404).json({ message: 'Customer not found' });
}
res.json({ message: 'Customer deleted successfully' });
} catch (error) {
console.error('Error deleting customer:', error);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

118
routes/users.js Normal file
View File

@@ -0,0 +1,118 @@
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const auth = require('../middleware/auth');
// Get all users (admin only)
router.get('/', auth, async (req, res) => {
try {
// Check if user is admin
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Not authorized' });
}
const users = await User.find().select('-password');
res.json(users);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Create new user (admin only)
router.post('/', auth, async (req, res) => {
try {
// Check if user is admin
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Not authorized' });
}
const { username, password, role } = req.body;
// Check if user exists
let user = await User.findOne({ username });
if (user) {
return res.status(400).json({ message: 'User already exists' });
}
// Create new user
user = new User({
username,
password,
role: role || 'staff',
});
// Hash password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// Return user without password
const userResponse = user.toObject();
delete userResponse.password;
res.status(201).json(userResponse);
} catch (error) {
console.error('Error creating user:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Update user (admin only)
router.put('/:id', auth, async (req, res) => {
try {
// Check if user is admin
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Not authorized' });
}
const { username, password, role } = req.body;
const updateData = {};
if (username) updateData.username = username;
if (role) updateData.role = role;
if (password) {
const salt = await bcrypt.genSalt(10);
updateData.password = await bcrypt.hash(password, salt);
}
const user = await User.findByIdAndUpdate(
req.params.id,
updateData,
{ new: true }
).select('-password');
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (error) {
console.error('Error updating user:', error);
res.status(500).json({ message: 'Server error' });
}
});
// Delete user (admin only)
router.delete('/:id', auth, async (req, res) => {
try {
// Check if user is admin
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Not authorized' });
}
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
} catch (error) {
console.error('Error deleting user:', error);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;

42
scripts/createAdmin.js Normal file
View File

@@ -0,0 +1,42 @@
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
require('dotenv').config();
async function createAdminUser() {
try {
// Connect to MongoDB
await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/car-tuning-crm');
console.log('Connected to MongoDB');
// Check if admin user already exists
const existingAdmin = await User.findOne({ username: 'admin' });
if (existingAdmin) {
console.log('Admin user already exists');
process.exit(0);
}
// Create admin user
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash('admin123', salt);
const adminUser = new User({
username: 'admin',
password: hashedPassword,
role: 'admin'
});
await adminUser.save();
console.log('Admin user created successfully');
console.log('Username: admin');
console.log('Password: admin123');
} catch (error) {
console.error('Error creating admin user:', error);
} finally {
await mongoose.disconnect();
process.exit(0);
}
}
createAdminUser();

View File

@@ -21,6 +21,7 @@ mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/car-tunin
// Routes // Routes
app.use('/api/auth', require('./routes/auth')); app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/users'));
app.use('/api/customers', require('./routes/customers')); app.use('/api/customers', require('./routes/customers'));
app.use('/api/contacts', require('./routes/contacts')); app.use('/api/contacts', require('./routes/contacts'));