Skip to content

developer-tag/zezt-developer-coding-test

Repository files navigation

🍽️ Restaurant Booking API

A comprehensive REST API for restaurant deal booking and management system built with Node.js, Express, and MongoDB.

📋 Table of Contents

✨ Features

Core Requirements ✅

  • Restaurant Deal Creation - POST /deals
  • Nearby Deals Search - GET /deals/nearby?lat=x&lng=y (geolocation-based)
  • Deal Booking - POST /book/:dealId
  • ML Discount Suggestions - Hardcoded logic with future ML integration plan

Additional Features

  • User Authentication & Authorization - JWT-based with role management
  • Admin Dashboard - User management and analytics
  • Real-time Deal Availability - Automatic capacity management
  • Booking Lifecycle Management - Status tracking (pending → confirmed → completed)
  • Geolocation Services - Radius-based deal discovery
  • Advanced Analytics - Business insights and user statistics
  • Rate Limiting - API abuse prevention
  • Data Validation - Comprehensive input validation

🛠️ Tech Stack

  • Backend: Node.js, Express.js
  • Database: MongoDB with Mongoose ODM
  • Authentication: JWT (JSON Web Tokens)
  • Security: Helmet, CORS, Rate Limiting, Data Sanitization
  • Validation: Custom middleware with comprehensive error handling
  • Documentation: Swagger/OpenAPI (planned)
  • Testing: Jest (planned)

🚀 Quick Start

Prerequisites

  • Node.js (v16+)
  • MongoDB (v4.4+)
  • npm or yarn

Installation

# Clone the repository
git clone <repository-url>
cd restaurant-booking-api

# Install dependencies
npm install

# Setup environment variables
cp .env.example .env
# Edit .env with your configuration

# Start MongoDB (if local)
mongod

# Seed the database with sample data
npm run seed

# Start the development server
npm run dev

Environment Variables

# Server Configuration
NODE_ENV=development
PORT=5000

# Database
MONGODB_URI=mongodb://localhost:27017/restaurant-booking

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d

# Security
BCRYPT_SALT_ROUNDS=12
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=900000

# CORS
CORS_ORIGIN=*

🔐 Authentication

The API uses JWT (JSON Web Tokens) for authentication with role-based access control.

User Roles

  • User - Regular customers (can book deals, manage own bookings)
  • Admin - System administrators (user management, analytics, all operations)

Test Credentials

Admin Account:
Email: admin@restaurant.com
Password: Admin@123

Regular Users:
Email: john.doe@example.com
Password: Test@123
Email: jane.smith@example.com
Password: Test@123

📡 API Endpoints

Authentication

POST   /api/v1/auth/register      # Register new user
POST   /api/v1/auth/login         # User login
POST   /api/v1/auth/logout        # User logout
GET    /api/v1/auth/me            # Get current user
PUT    /api/v1/auth/me            # Update profile
PUT    /api/v1/auth/change-password # Change password

Deals Management

GET    /api/v1/deals              # Get all deals
GET    /api/v1/deals/nearby       # Get nearby deals ⭐ CORE
POST   /api/v1/deals              # Create deal ⭐ CORE
GET    /api/v1/deals/:id          # Get single deal
PUT    /api/v1/deals/:id          # Update deal
DELETE /api/v1/deals/:id          # Delete deal
GET    /api/v1/deals/:id/ml-suggestion # ML discount suggestion ⭐ CORE
GET    /api/v1/deals/stats/overview # Deal statistics

Booking Management

POST   /api/v1/bookings/:dealId  # Book a deal ⭐ CORE
GET    /api/v1/bookings/my-bookings # User's bookings
GET    /api/v1/bookings          # All bookings (admin)
GET    /api/v1/bookings/:id      # Get booking details
PUT    /api/v1/bookings/:id      # Update booking
DELETE /api/v1/bookings/:id      # Cancel booking
PUT    /api/v1/bookings/:id/confirm # Confirm booking
PUT    /api/v1/bookings/:id/complete # Complete booking
GET    /api/v1/bookings/stats    # Booking statistics

User Management

GET    /api/v1/users/profile     # Own profile
PUT    /api/v1/users/profile     # Update own profile
GET    /api/v1/users/booking-history # Own booking history
GET    /api/v1/users/booking-stats # Own statistics
GET    /api/v1/users/preferences # User preferences
PUT    /api/v1/users/preferences # Update preferences

# Admin Only Routes
GET    /api/v1/users             # All users (admin)
GET    /api/v1/users/:id         # User details (admin)
PUT    /api/v1/users/:id         # Update user (admin)
DELETE /api/v1/users/:id         # Delete user (admin)
PUT    /api/v1/users/:id/activate # Activate user (admin)
PUT    /api/v1/users/:id/deactivate # Deactivate user (admin)
GET    /api/v1/users/analytics   # User analytics (admin)

🎯 Core Features

1. Nearby Deals Search

Endpoint: GET /api/v1/deals/nearby?lat=31.5204&lng=74.3587&radius=10

// Example Response
{
  "status": "success",
  "message": "Nearby deals retrieved successfully",
  "data": [
    {
      "_id": "...",
      "restaurantName": "Pizza Palace",
      "description": "20% off on all pizzas",
      "discountPercentage": 20,
      "originalPrice": 25,
      "discountedPrice": 20,
      "location": {
        "type": "Point",
        "coordinates": [74.3587, 31.5204]
      },
      "address": "123 Main Street, Lahore",
      "validFrom": "2025-06-13T00:00:00.000Z",
      "validUntil": "2025-06-20T23:59:59.000Z",
      "maxBookings": 50,
      "currentBookings": 15,
      "isActive": true
    }
  ],
  "meta": {
    "total": 5,
    "page": 1,
    "limit": 10,
    "pages": 1
  }
}

2. Deal Creation

Endpoint: POST /api/v1/deals

// Example Request
{
  "restaurantName": "Burger House",
  "description": "Buy 1 Get 1 Free on all burgers",
  "discountPercentage": 50,
  "originalPrice": 15,
  "location": {
    "type": "Point",
    "coordinates": [74.3587, 31.5204]
  },
  "address": "456 Food Street, Lahore",
  "validFrom": "2025-06-13T00:00:00.000Z",
  "validUntil": "2025-06-20T23:59:59.000Z",
  "maxBookings": 100
}

3. Deal Booking

Endpoint: POST /api/v1/bookings/:dealId

// Example Request
{
  "bookingDate": "2025-06-15T19:00:00.000Z",
  "numberOfPeople": 4,
  "specialRequests": "Window seat preferred"
}

// Example Response
{
  "status": "success",
  "message": "Booking created successfully",
  "data": {
    "booking": {
      "_id": "...",
      "userId": "...",
      "dealId": {
        "restaurantName": "Burger House",
        "discountPercentage": 50,
        "address": "456 Food Street, Lahore"
      },
      "bookingDate": "2025-06-15T19:00:00.000Z",
      "numberOfPeople": 4,
      "priceAtBooking": 15,
      "discountApplied": 50,
      "finalAmount": 30,
      "status": "pending",
      "specialRequests": "Window seat preferred"
    }
  }
}

🤖 ML Integration

Current Implementation (Hardcoded Logic)

The API includes hardcoded ML logic that analyzes:

  • Time of day (off-peak vs peak hours)
  • Day of week (weekend vs weekday)
  • Current booking count (demand level)
  • Utilization rate (capacity percentage)

ML Suggestion Rules

  1. Off-peak hours (2-4pm) + low bookings → 20% discount
  2. Weekend evenings + high demand → 5% discount
  3. Weekday lunch + moderate bookings → 15% discount
  4. Low utilization (<30%) → 25% discount
  5. Near capacity (>80%) → No additional discount

Future ML Integration Plan

// Planned External ML Service Integration
POST /ml-service/predict
{
  "features": {
    "time": "14:30",
    "day_of_week": "Tuesday", 
    "current_bookings": 8,
    "max_bookings": 50,
    "weather": "sunny",
    "local_events": ["concert_nearby"]
  }
}

// Response
{
  "suggested_discount": 22,
  "confidence": 0.87,
  "reasoning": "Low afternoon demand with good weather"
}

Endpoint: GET /api/v1/deals/:id/ml-suggestion

🗄️ Database Schema

User Model

{
  name: String,
  email: String (unique),
  phone: String,
  password: String (hashed),
  role: ['user', 'admin'],
  status: ['active', 'inactive'],
  timestamps: true
}

Deal Model

{
  restaurantName: String,
  description: String,
  discountPercentage: Number,
  originalPrice: Number,
  location: GeoJSON Point,
  address: String,
  validFrom: Date,
  validUntil: Date,
  maxBookings: Number,
  currentBookings: Number,
  isActive: Boolean,
  suggestedDiscount: Number,
  lastMLUpdate: Date,
  timestamps: true
}

Booking Model

{
  userId: ObjectId (ref: User),
  dealId: ObjectId (ref: Deal),
  bookingDate: Date,
  numberOfPeople: Number,
  priceAtBooking: Number,
  discountApplied: Number,
  finalAmount: Number,
  status: ['pending', 'confirmed', 'completed', 'cancelled'],
  specialRequests: String,
  cancellationReason: String,
  timestamps: true
}

🔧 Advanced Features

Query Parameters

# Pagination
?page=1&limit=10

# Filtering
?status=active&discountPercentage[gte]=20

# Searching
?search=pizza

# Sorting
?sort=-createdAt,discountPercentage

# Field Selection
?fields=restaurantName,discountPercentage,address

# Geolocation
?lat=31.5204&lng=74.3587&radius=15

Rate Limiting

  • General API: 100 requests per 15 minutes
  • Auth Operations: 20 requests per hour
  • Booking Operations: 50 requests per hour

Security Features

  • JWT Authentication with secure token handling
  • Password Hashing using bcrypt
  • Data Sanitization against NoSQL injection
  • XSS Protection using xss-clean
  • Helmet for security headers
  • CORS configuration
  • Rate Limiting per IP and per user

📊 API Response Format

Success Response

{
  "status": "success",
  "message": "Operation completed successfully",
  "data": { /* response data */ },
  "meta": { /* pagination info */ }
}

Error Response

{
  "status": "error", 
  "message": "Error description",
  "error": {
    "statusCode": 400,
    "details": "Detailed error information"
  }
}

🧪 Testing

Manual Testing

Use the provided test credentials to test different user roles:

# Test user registration
curl -X POST http://localhost:5000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"Test User","email":"test@example.com","password":"Test@123"}'

# Test nearby deals
curl "http://localhost:5000/api/v1/deals/nearby?lat=31.5204&lng=74.3587&radius=10"

# Test booking creation (requires authentication)
curl -X POST http://localhost:5000/api/v1/bookings/DEAL_ID \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"bookingDate":"2025-06-15T19:00:00.000Z","numberOfPeople":2}'

Database Seeding

# Seed database with sample data
npm run seed

# Clear database
npm run seed:clear

🚀 Deployment

Environment Setup

  1. Set NODE_ENV=production
  2. Configure production MongoDB URI
  3. Set secure JWT secret
  4. Configure CORS for your frontend domain
  5. Set up SSL/TLS certificates
  6. Configure reverse proxy (nginx)

Production Checklist

  • Environment variables configured
  • Database indexes created
  • SSL certificates installed
  • Rate limiting configured
  • Monitoring setup
  • Backup strategy implemented
  • Error logging configured

🤝 Contributing

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

📝 API Documentation

Interactive API documentation will be available at:

  • Development: http://localhost:5000/api/docs
  • Production: https://your-domain.com/api/docs

📞 Support

For technical support or questions:

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


🎯 Project Status

Core Requirements Completed

  • Restaurant deal creation
  • Nearby deals with geolocation
  • Deal booking system
  • ML discount suggestions (hardcoded)

Additional Features

  • User authentication & authorization
  • Admin dashboard
  • Real-time availability
  • Comprehensive analytics
  • Rate limiting & security

🔄 Future Enhancements

  • External ML service integration
  • Real-time notifications
  • Payment gateway integration
  • Mobile app API extensions
  • Advanced analytics dashboard

Built with ❤️ for the restaurant industry

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors