# Cab Booking Backend

A comprehensive Node.js backend service for a cab booking application featuring role-based access control, real-time communication via Socket.io, and secure email-based authentication with OTP verification.

## 📋 Table of Contents

- [Overview](#overview)
- [Tech Stack](#tech-stack)
- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [Environment Variables](#environment-variables)
- [Database Models](#database-models)
- [Authentication & Authorization](#authentication--authorization)
- [API Endpoints](#api-endpoints)
- [Socket.io](#socketio)
- [Development Workflow](#development-workflow)
- [Docker Support](#docker-support)
- [Troubleshooting](#troubleshooting)

---

## 🎯 Overview

This backend application powers a cab booking system with multi-role user management (users, drivers, vendors, zone admins, and super admins). It includes:

- **JWT-based authentication** with refresh tokens
- **Email OTP verification** for secure user registration
- **Password reset** functionality with time-limited tokens
- **Role-based access control** (RBAC)
- **Zone management** for geographical service areas
- **Real-time communication** using Socket.io
- **Swagger API documentation** for easy testing and integration
- **Rate limiting** on sensitive endpoints
- **Comprehensive error handling**

---

## 🛠 Tech Stack

| Technology | Purpose |
|------------|---------|
| **Node.js** | Runtime environment |
| **Express.js** | Web framework |
| **MongoDB** | NoSQL database |
| **Mongoose** | ODM for MongoDB |
| **Socket.io** | Real-time bidirectional communication |
| **JWT** | Token-based authentication |
| **Bcrypt.js** | Password hashing |
| **Nodemailer** | Email sending (OTP, password reset) |
| **Joi** | Request validation |
| **Swagger** | API documentation |
| **Morgan** | HTTP request logger |
| **Docker** | Containerization |

---

## 🚀 Getting Started

### Prerequisites

- Node.js v14 or higher
- npm or yarn
- MongoDB (local installation or cloud instance)
- SMTP credentials for email (Gmail recommended)

### Installation

1. **Clone the repository**
   ```bash
   git clone https://github.com/hltechbhopal/Cab-Booking-Backend.git
   cd cab-booking
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Configure environment variables**
   
   Copy `.env.sample` to `.env` and fill in your values:
   ```bash
   cp .env.sample .env
   ```

4. **Start the development server**
   ```bash
   npm run dev
   ```
   
   The server will start on `http://localhost:5000` by default.

5. **Generate Swagger documentation** (optional)
   ```bash
   npm run gen
   ```

6. **Access API documentation**
   
   Navigate to `http://localhost:5000/api-docs` in your browser.

---

## 📁 Project Structure

```
cab-booking/
├── src/
│   ├── app.js                      # Express app configuration
│   ├── server.js                   # Server entry point
│   ├── socket.js                   # Socket.io initialization
│   ├── swagger.js                  # Swagger configuration
│   ├── config/
│   │   └── db.config.js           # MongoDB connection
│   ├── controllers/
│   │   ├── auth.controller.js     # Authentication logic
│   │   └── zone.controller.js     # Zone management logic
│   ├── middlewares/
│   │   ├── authenticate.js        # JWT verification & RBAC
│   │   ├── catchAsyncErrors.js    # Async error wrapper
│   │   └── error.js               # Centralized error handler
│   ├── models/
│   │   ├── user.model.js          # User schema
│   │   ├── zone.model.js          # Zone schema
│   │   └── emailVerification.model.js  # OTP storage schema
│   ├── routes/
│   │   ├── router.js              # Main router (combines all routes)
│   │   ├── auth.routes.js         # Auth endpoints
│   │   ├── user.routes.js         # User-specific routes
│   │   ├── driver.routes.js       # Driver-specific routes
│   │   ├── vendor.routes.js       # Vendor-specific routes
│   │   ├── zone-admin.routes.js   # Zone admin routes
│   │   ├── super-admin.routes.js  # Super admin routes
│   │   └── super-admin/
│   │       └── zone.routes.js     # Zone management routes
│   ├── services/
│   │   └── email.service.js       # Email sending logic
│   ├── utils/
│   │   ├── ErrorHandler.js        # Custom error class
│   │   ├── SendJwtToken.js        # JWT token helper
│   │   ├── sendOtp.js             # OTP generation & sending
│   │   └── cleanObject.js         # Object sanitization
│   └── validation/
│       └── validatino.js          # Joi validation schemas
├── .env.sample                     # Environment variables template
├── .dockerignore                   # Docker ignore file
├── Dockerfile                      # Docker configuration
├── package.json                    # Dependencies & scripts
└── README.md                       # This file
| `FRONTEND_URL` | Frontend application URL | - |
**CORS Settings:**
- Allowed origins: `http://localhost:5173` (frontend dev server)
import { io } from 'socket.io-client';

const socket = io('http://localhost:5000', {
  withCredentials: true
});

socket.on('connect', () => {
  console.log('Connected:', socket.id);
});


**Response:**
```json
{
  "success": true,
  "stats": {
    "total": 150,
    "active": 45,
    "inactive": 5,
    "onTrip": 80,
    "maintenance": 10,
    "expired": 10
  }
}
```

#### 2. List Vehicles (with Filters)
Get a paginated list of vehicles with optional filters.

- **Endpoint**: `GET /api/v1/super-admin/vehicle`
- **Auth**: Required (Super Admin)

**Query Parameters:**

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `page` | Number | Page number (default: 1) | `1` |
| `limit` | Number | Items per page (default: 10) | `20` |
| `search` | String | Search by Vehicle Name, Reg Number, or Model | `Swift` |
| `status` | String | Filter by status | `Active`, `Maintenance` |
| `zone` | ID | Filter by Zone ID | `65f2...` |
| `vendor` | ID | Filter by Vendor ID | `65f2...` |
| `category` | String/ID | Filter by Category Name or ID | `Sedan` |

**Example URL:**
`http://localhost:5000/api/v1/super-admin/vehicle?page=1&limit=10&status=Active&category=Sedan`

#### 3. Add New Vehicle
Register a new vehicle in the system.

- **Endpoint**: `POST /api/v1/super-admin/vehicle/addVehicle`
- **Auth**: Required (Super Admin)

**Body:**
```json
{
  "vehicleName": "White Swift Dzire",
  "registrationNumber": "MP 04 AB 1234",
  "vendor": "65f2...",
  "zone": "65f2...",
  "model": "65f2...",
  "mileage": 18,
  "description": "New condition, AC working",
  "status": "Active"
}
```

#### 4. Update Vehicle (Status Change)
Update vehicle details or toggle status.

- **Endpoint**: `PATCH /api/v1/super-admin/vehicle/updateVehicle/:id`
- **Auth**: Required (Super Admin)

**Body (Status Update):**
```json
{
  "status": "Maintenance"
}
```

#### 5. User Insights
Get user registration insights with flexible filtering options.

- **Endpoint**: `GET /api/v1/super-admin/user/insights`
- **Auth**: Required (Super Admin)

**Query Parameters:**

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `filter` | String | Grouping criteria: `year`, `month`, or `day` | `month` |
| `year` | Number | Filter by specific year | `2024` |
| `month` | Number | Filter by specific month (1-12) | `5` |

**Usage Scenarios:**

1. **Yearly Overview**: `?filter=year` - Returns registration counts for last 5 years.
2. **Monthly Breakdown**: `?filter=month&year=2024` - Returns counts for each month in 2024.
3. **Daily Breakdown**: `?filter=day&year=2024&month=5` - Returns counts for each day in May 2024.

**Response Example:**
```json
{
  "success": true,
  "data": [
    {
      "_id": 5,
      "count": 120,
      "label": "May"
    },
    {
      "_id": 6,
      "count": 150,
      "label": "June"
    }
  ]
}
  ]
}
```

#### 6. Order Management & Booking
Complete flow for booking rides, managing orders, and tracking.

**User Booking:**
- **Endpoint**: `POST /api/v1/user/booking/book-ride`
- **Auth**: Required (User)
- **Features**:
    - **Vehicle-based Zone Assignment**: Automatically assigns the operating zone based on the selected `vehicleId`.
    - **Unique Order ID**: Generates a unique ID (e.g., `ORD-2024-000001`).
    - **Goibibo-style Options**: Supports `OneWay`, `RoundTrip`, `Rental`, `Airport` trips.

**Super Admin Management:**
- **List Bookings**: `GET /api/v1/super/booking` (Filter by status, date, zone, search).
- **Get Details**: `GET /api/v1/super/booking/:id`
- **Assign Driver**: `PUT /api/v1/super/booking/:id/assign`
- **Update Status**: `PUT /api/v1/super/booking/:id/status`
- **Generate Invoice**: `GET /api/v1/super/booking/:id/invoice`

#### 7. Zone Admin Management
Dedicated endpoints for Zone Admins to manage their specific geographical zone.

- **Unified Dashboard**: `GET /api/v1/zone/dashboard`
  - Get overview stats, vendors, drivers, vehicles, and orders.
  - Supports filtering by section (`?section=vehicles`), status, and more.

**Vehicle Management (Shared Endpoints):**
All vehicle operations are now handled via the shared super-admin endpoints. Zone Admins are restricted to their zone.
- **List Vehicles**: `GET /api/v1/super/vehicle` (Includes pending approvals)
- **Create Vehicle**: `POST /api/v1/super/vehicle/addVehicle`
  - Creates a vehicle with `Pending` status.
  - Supports image uploads.
- **Update Vehicle**: `PATCH /api/v1/super/vehicle/updateVehicle/:id`
- **Change Status**: `PATCH /api/v1/super/vehicle/updateVehicle/:id` (Status in body)
- **Approve/Reject**: `POST /api/v1/super/vehicle/vehicle/:id/approval`
- **Delete Vehicle**: `DELETE /api/v1/super/vehicle/deleteVehicle/:id`

**Vendor Management (Shared Endpoints):**
- **Create Vendor**: `POST /api/v1/super/vendor/create-vendor`
- **Update**: `PATCH /api/v1/super/vendor/:id`
- **List**: `GET /api/v1/super/vendor`
- **Delete**: `DELETE /api/v1/super/vendor/:id`

**Driver Management (Zone Specific):**
- **Create Driver**: `POST /api/v1/zone/drivers` (With document uploads)
- **Approve Document**: `PATCH /api/v1/zone/drivers/:id/documents/:docId`
- **Background Check**: `PATCH /api/v1/zone/drivers/:id/background-check`

*Note: All Zone Admin operations are strictly scoped to the admin's assigned zone.*

---

## 💻 Development Workflow

### Available Scripts

```bash
# Start production server
npm start

# Start development server with auto-reload
npm run dev

# Generate Swagger documentation
npm run gen
```

### Development Best Practices

1. **Code Organization**
   - Controllers: Business logic
   - Services: Reusable logic (email, external APIs)
   - Middlewares: Request processing (auth, validation, error handling)
   - Utils: Helper functions

2. **Error Handling**
   - Use `catchAsyncErrors` wrapper for async route handlers
   - Throw `ErrorHandler` instances with appropriate status codes
   - Centralized error handling in `error.js` middleware

3. **API Documentation**
   - Add Swagger comments to routes
   - Run `npm run gen` after route changes
   - Test endpoints in `/api-docs`

4. **Database**
   - Use Mongoose models for all DB operations
   - Validate data with Joi schemas before saving
   - Enable indexes on frequently queried fields

5. **Security**
   - Never commit `.env` file
   - Use `bcrypt` for password hashing
   - Implement rate limiting on sensitive endpoints
   - Validate and sanitize all user inputs

### Testing the API

1. **Using Swagger UI**
   - Navigate to `http://localhost:5000/api-docs`
   - Authorize with Bearer token (after login)
   - Test endpoints interactively

2. **Using Postman/Insomnia**
   - Import Swagger JSON from `src/swagger-output.json`
   - Set `Authorization: Bearer <token>` header

3. **Using cURL**
   - See request examples in [API Endpoints](#api-endpoints)

---

## 🐳 Docker Support

### Build Docker Image

```bash
docker build -t cab-booking-backend .
```

### Run Container

```bash
docker run -p 5000:5000 \
  -e MONGODB_URI="mongodb://host.docker.internal:27017/cab-booking" \
  -e JWT_SECRET="your-jwt-secret" \
  -e REFRESHTOKEN_SECRET="your-refresh-secret" \
  -e EXPRESS_SESSION_SECRET="your-session-secret" \
  -e NODEMAILER_USER="your-email@gmail.com" \
  -e NODEMAILER_PASS="your-app-password" \
  cab-booking-backend
```





### Common Issues

#### 1. **MongoDB Connection Failed**

**Error:** `MongooseServerSelectionError: connect ECONNREFUSED`

**Solutions:**
- Ensure MongoDB is running: `sudo systemctl start mongod` (Linux) or start MongoDB service (Windows)
- Check `MONGODB_URI` in `.env`
- For Docker: Use `mongodb://host.docker.internal:27017/cab-booking`

#### 2. **Email OTP Not Sending**

**Error:** `Error sending email`

**Solutions:**
- Verify `NODEMAILER_USER` and `NODEMAILER_PASS` in `.env`
- For Gmail: Use [App Password](https://support.google.com/accounts/answer/185833), not regular password
- Enable "Less secure app access" or use OAuth2

#### 3. **JWT Token Errors**

**Error:** `JsonWebTokenError: invalid signature`

**Solutions:**
- Ensure `JWT_SECRET` and `REFRESHTOKEN_SECRET` are set in `.env`
- Use the same secret across server restarts
- Clear cookies and login again

#### 4. **CORS Errors**

**Error:** `Access to fetch blocked by CORS policy`

**Solutions:**
- Add your frontend URL to `cors` origins in `src/app.js`
- Ensure `credentials: true` in both server and client
- For Socket.io, update origins in `src/socket.js`

#### 5. **Port Already in Use**

**Error:** `EADDRINUSE: address already in use :::5000`

**Solutions:**
- Change `PORT` in `.env`
- Kill process using port: 
  ```bash
  # Linux/Mac
  lsof -ti:5000 | xargs kill -9
  
  # Windows
  netstat -ano | findstr :5000
  taskkill /PID <PID> /F
  ```

#### 6. **Swagger Not Loading**

**Solutions:**
- Run `npm run gen` to regenerate `swagger-output.json`
- Check if `swagger-ui-express` is installed
- Ensure `src/swagger-output.json` exists

### Debugging Tips

1. **Enable Detailed Logging**
   - Morgan is configured for `tiny` logs
   - Change to `dev` or `combined` in `src/app.js` for more details

2. **Database Queries**
   - Enable Mongoose debug mode:
     ```javascript
     mongoose.set('debug', true);
     ```

3. **Inspect JWT Tokens**
   - Use [jwt.io](https://jwt.io) to decode tokens
   - Check expiration and payload

4. **Email Debugging**
   - Use [Mailtrap](https://mailtrap.io) for testing without real emails
   - Check spam folder for sent emails

---

## 📝 Additional Notes

### OTP Rate Limiting

- **Cooldown:** 60 seconds between OTP requests
- **Max Attempts:** 3 OTP sends per 10 minutes
- **Verification Attempts:** 5 failed attempts before lockout
- **OTP Expiry:** 5 minutes

### Password Reset Security

- Reset tokens are valid for **10 minutes**
- Tokens are single-use (deleted after successful reset)
- Tokens are cryptographically secure

### Refresh Token Strategy

- Access tokens expire in 15 minutes
- Refresh tokens expire in 7 days
- Refresh tokens are stored in the database
- Multiple refresh tokens allowed (multi-device support)

### Role Assignment

- Default role: `user`
- Role changes require `super-admin` access
- Roles cannot be self-assigned during registration

---

## 🤝 Contributing

Contributions are welcome! Please follow these steps:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

### Code Style

- Use ES6+ syntax
- Follow existing code formatting
- Add comments for complex logic
- Update Swagger documentation for new endpoints

---

## 📄 License

This project does not currently include a license. Please contact the repository owner for licensing information.

---

## 📧 Contact & Support

For questions, issues, or feature requests:

- **Repository:** [hltechbhopal/Cab-Booking-Backend](https://github.com/hltechbhopal/Cab-Booking-Backend)
- **Issues:** [GitHub Issues](https://github.com/hltechbhopal/Cab-Booking-Backend/issues)

---

## 🎉 Quick Start Checklist for New Developers

- [ ] Clone repository
- [ ] Install Node.js and MongoDB
- [ ] Run `npm install`
- [ ] Copy `.env.sample` to `.env` and configure
- [ ] Setup Gmail App Password for OTP emails
- [ ] Start MongoDB service
- [ ] Run `npm run dev`
- [ ] Access Swagger docs at `http://localhost:5000/api-docs`
- [ ] Test registration → OTP verification → login flow
- [ ] Explore Socket.io connection (if working with real-time features)

**Happy Coding! 🚀**