Skip to content

Repository files navigation

πŸš€ NextJS Dispatch Components - Fleet Management Dashboard

A comprehensive, modern fleet management and analytics dashboard built with Next.js 15, React 19, MongoDB, and TypeScript. This application provides real-time fleet monitoring, data visualization, comparison tools, and interactive maps for dispatch management.

Next.js React TypeScript MongoDB Tailwind CSS


πŸ“‹ Table of Contents


🎯 Overview

NextJS Dispatch Components is a full-stack web application designed for fleet management operations. It enables users to:

  • Monitor Fleet Performance - Real-time analytics and metrics visualization
  • Compare Simulations - Side-by-side comparison of different fleet scenarios
  • Interactive Maps - Visualize fleet locations with Leaflet maps
  • User Management - Role-based access control (HQ Manager & Fleet Manager)
  • Data Analytics - Comprehensive charts for revenue, orders, delivery times, and more

The application uses JWT-based authentication, MongoDB for data persistence, and provides a responsive, modern UI built with Tailwind CSS and Radix UI components.


✨ Features

πŸ” Authentication & Authorization

  • JWT-based Authentication - Secure token-based login system
  • Role-Based Access Control - Two authority levels:
    • HQM (Headquarters Manager) - Full access to all fleets
    • FM (Fleet Manager) - Access limited to assigned fleets/locations
  • Cookie-based Session Management - HTTP-only cookies for security

πŸ“Š Dashboard & Analytics

  • Interactive Charts - Multiple chart types (Area, Bar, Line) powered by Recharts
  • Real-time Data Visualization - Live updates from MongoDB
  • Fleet Metrics Dashboard - Comprehensive KPIs and performance indicators
  • Chart Categories:
    • Revenue Growth
    • Order Volume
    • Average Delivery Time
    • Customer Satisfaction
    • Fleet Utilization
    • Driver Retention

πŸ”„ Comparison Tools

  • Side-by-Side Fleet Comparison - Compare two fleets simultaneously
  • Multi-Chart Comparison - View all metrics across both fleets
  • Search & Filter - Quick search across chart categories

πŸ—ΊοΈ Map Integration

  • Interactive Leaflet Maps - Real-time fleet location visualization
  • Map Navigation - Smooth fly-to animations
  • Location Tracking - GPS coordinates for each fleet

🎨 User Interface

  • Modern Design - Clean, responsive UI with Tailwind CSS
  • Component Library - Radix UI primitives for accessible components
  • Dark Mode Support - Theme-aware components
  • Mobile Responsive - Works seamlessly on all devices

πŸ› οΈ Tech Stack

Frontend

  • Next.js 15.3.2 - React framework with App Router
  • React 19.0.0 - UI library
  • TypeScript 5.0 - Type-safe development
  • Tailwind CSS 4.0 - Utility-first CSS framework
  • Radix UI - Accessible component primitives
  • Recharts - Chart library
  • React Leaflet - Map integration
  • Lucide React - Icon library

Backend

  • Next.js API Routes - Serverless API endpoints
  • MongoDB - NoSQL database with Mongoose ODM
  • JWT (jsonwebtoken) - Authentication tokens
  • Node.js - Runtime environment

Development Tools

  • pnpm - Fast, disk-efficient package manager
  • ESLint - Code linting
  • Turbopack - Next-generation bundler
  • TypeScript - Static type checking

πŸ“ Project Structure

NextJS-DispatchComponents/
β”œβ”€β”€ app/                          # Next.js App Router
β”‚   β”œβ”€β”€ api/                      # API routes
β”‚   β”‚   β”œβ”€β”€ auth/                 # Authentication endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ login/           # POST /api/auth/login
β”‚   β”‚   β”‚   β”œβ”€β”€ logout/          # POST /api/auth/logout
β”‚   β”‚   β”‚   β”œβ”€β”€ me/              # GET /api/auth/me
β”‚   β”‚   β”‚   └── user/[id]/       # GET /api/auth/user/:id
β”‚   β”‚   └── charts/              # Chart data endpoints
β”‚   β”‚       β”œβ”€β”€ fleets/         # GET /api/charts/fleets
β”‚   β”‚       β”œβ”€β”€ fleet/[name]/   # GET /api/charts/fleet/:name
β”‚   β”‚       └── compare/        # POST /api/charts/compare
β”‚   β”œβ”€β”€ map/                     # Map page
β”‚   β”œβ”€β”€ layout.tsx              # Root layout
β”‚   β”œβ”€β”€ page.tsx                # Home page
β”‚   └── globals.css             # Global styles
β”‚
β”œβ”€β”€ components/                  # React components
β”‚   β”œβ”€β”€ charts/                 # Chart components
β”‚   β”‚   β”œβ”€β”€ AreaChartCard.tsx
β”‚   β”‚   β”œβ”€β”€ BarChartCard.tsx
β”‚   β”‚   └── LineChartCard.tsx
β”‚   β”œβ”€β”€ map/                    # Map components
β”‚   β”‚   β”œβ”€β”€ MapComponent.tsx
β”‚   β”‚   β”œβ”€β”€ LegendDropdown.tsx
β”‚   β”‚   └── TimelineScrubber.tsx
β”‚   β”œβ”€β”€ ui/                     # UI components
β”‚   β”‚   β”œβ”€β”€ DashboardCharts.tsx
β”‚   β”‚   β”œβ”€β”€ CompareSimulations.tsx
β”‚   β”‚   β”œβ”€β”€ ControlPanel.tsx
β”‚   β”‚   β”œβ”€β”€ Header.tsx
β”‚   β”‚   β”œβ”€β”€ Sidebar.tsx
β”‚   β”‚   └── [shadcn components]
β”‚   β”œβ”€β”€ DashboardClient.tsx     # Main dashboard client
β”‚   └── mvpblocks/              # MVP-specific components
β”‚
β”œβ”€β”€ lib/                         # Utility libraries
β”‚   β”œβ”€β”€ auth.ts                 # Authentication helpers
β”‚   β”œβ”€β”€ mongo.ts                # MongoDB connection
β”‚   β”œβ”€β”€ api-utils.ts            # API utilities
β”‚   └── utils.ts                # General utilities
β”‚
β”œβ”€β”€ models/                      # Mongoose models
β”‚   β”œβ”€β”€ Fleet.ts                # Fleet schema
β”‚   └── User.ts                 # User schema
β”‚
β”œβ”€β”€ hooks/                       # Custom React hooks
β”‚   β”œβ”€β”€ useDebounce.ts          # Debounce hook
β”‚   └── use-mobile.ts           # Mobile detection hook
β”‚
β”œβ”€β”€ public/                     # Static assets
β”‚   └── Dispatchlogo.png       # Logo file
β”‚
β”œβ”€β”€ package.json                # Dependencies & scripts
β”œβ”€β”€ pnpm-lock.yaml             # pnpm lock file
β”œβ”€β”€ tsconfig.json              # TypeScript configuration
β”œβ”€β”€ next.config.ts             # Next.js configuration
└── README.md                  # This file

πŸš€ Getting Started

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js >= 18.0.0
  • pnpm >= 8.0.0 (Install: npm install -g pnpm)
  • MongoDB connection string (or MongoDB Atlas account)

Installation

  1. Clone the repository

    git clone <repository-url>
    cd NextJS-DispatchComponents
  2. Install dependencies using pnpm

    pnpm install
  3. Set up environment variables

    Create a .env.local file in the root directory:

    JWT_SECRET=your-super-secret-jwt-key-here-minimum-32-characters
    MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database-name

    Note: The MongoDB URI is currently hardcoded in lib/mongo.ts. For production, move it to environment variables.

  4. Run the development server

    pnpm dev

    The application will start on http://localhost:2107

  5. Build for production

    pnpm build
  6. Start production server

    pnpm start

πŸ”‘ Environment Variables

Create a .env.local file in the root directory with the following variables:

Variable Description Required Example
JWT_SECRET Secret key for JWT token signing Yes your-secret-key-min-32-chars
MONGODB_URI MongoDB connection string Yes mongodb+srv://user:pass@cluster.mongodb.net/db
NODE_ENV Environment mode No development or production
NEXT_PUBLIC_BASE_PATH Base path for deployment No /repo-name
NEXT_STATIC_EXPORT Enable static export No true or false

Security Note: Never commit .env.local to version control. Add it to .gitignore.


πŸ”§ How It Works

Authentication Flow

  1. User Login

    • User submits email and password via /api/auth/login
    • Server validates credentials against MongoDB
    • JWT token is generated with user ID and authority
    • Token is stored in HTTP-only cookie
    • User is redirected to dashboard
  2. Session Validation

    • Each protected route calls getAuthUser() to verify token
    • Token is extracted from cookie and verified with JWT
    • User data is fetched from MongoDB using user ID
    • Access is granted/denied based on authority
  3. Authorization

    • HQM (Headquarters Manager): Can access all fleets
    • FM (Fleet Manager): Can only access fleets matching their location or fleet field

Data Flow

  1. Fleet Data Retrieval

    Client β†’ API Route β†’ MongoDB Query β†’ Data Filtering β†’ JSON Response β†’ Chart Components
    
  2. Chart Rendering

    • Fleet data is fetched via /api/charts/fleet/:name
    • Chart components transform data into Recharts format
    • Multiple chart types are rendered based on category
    • Search functionality filters visible charts
  3. Comparison Mode

    • Two fleets are selected via dropdowns
    • Data for both fleets is fetched in parallel
    • Charts are rendered side-by-side in a grid layout
    • Summary comparison is displayed at the bottom

Map Integration

  • Leaflet Maps render fleet locations
  • Map center is set based on fleet location coordinates
  • MapFlyTo component animates map transitions
  • Supports custom tile layers and attribution

πŸ“‘ API Documentation

Authentication Endpoints

POST /api/auth/login

Login endpoint for user authentication.

Request Body:

{
  "email": "user@example.com",
  "password": "password123"
}

Response (Success):

{
  "success": true,
  "user": {
    "_id": "user-id",
    "username": "username",
    "email": "user@example.com",
    "authority": "HQM",
    "location": "Pune",
    "fleet": "Fleet Name"
  }
}

Status Codes:

  • 200 - Success
  • 400 - Invalid request body
  • 401 - Invalid credentials
  • 500 - Server error

POST /api/auth/logout

Logout endpoint that clears authentication cookie.

Response:

{
  "success": true,
  "message": "Logged out successfully"
}

GET /api/auth/me

Get current authenticated user information.

Response:

{
  "loggedIn": true,
  "user": {
    "_id": "user-id",
    "username": "username",
    "email": "user@example.com",
    "authority": "HQM",
    "location": "Pune",
    "fleet": "Fleet Name"
  }
}

Status Codes:

  • 200 - Success (loggedIn: false if not authenticated)

GET /api/auth/user/[id]

Get user information by ID.

Response:

{
  "username": "username",
  "email": "user@example.com",
  "authority": "HQM",
  "location": "Pune",
  "fleet": "Fleet Name"
}

Charts Endpoints

GET /api/charts/fleets

Get list of all accessible fleets based on user authority.

Authorization Required: Yes

Response:

[
  {
    "name": "Zomato Fleet Pune",
    "location": {
      "lat": 18.5204,
      "lng": 73.8567
    },
    "charts": [...]
  }
]

Authority Filtering:

  • HQM: Returns all fleets
  • FM: Returns fleets matching user's location or fleet

GET /api/charts/fleet/[name]

Get specific fleet data including charts.

Parameters:

  • name (URL parameter): Fleet name (URL encoded)

Response:

{
  "name": "Zomato Fleet Pune",
  "location": {
    "lat": 18.5204,
    "lng": 73.8567
  },
  "charts": [
    {
      "category": "Revenue Growth",
      "data": [100, 120, 140, 160, 180, 200, 220],
      "summary": "Revenue increased by 120%"
    }
  ],
  "fleetId": "fleet-mongodb-id"
}

POST /api/charts/compare

Compare multiple chart categories across fleets.

Request Body:

{
  "fleet": "Zomato Fleet Pune",
  "categories": ["Revenue Growth", "Order Volume", "Fleet Utilization"]
}

Response:

[
  {
    "category": "Revenue Growth",
    "data": [100, 120, 140],
    "summary": "Revenue increased by 120%"
  }
]

πŸ—οΈ Architecture

Frontend Architecture

  • Server Components - Initial page load and data fetching
  • Client Components - Interactive UI with React hooks
  • Dynamic Imports - Code splitting for heavy components
  • Custom Hooks - Reusable logic (debounce, mobile detection)

Backend Architecture

  • API Routes - Serverless functions in app/api
  • Middleware Pattern - Authentication checks via getAuthUser()
  • Database Connection - Singleton pattern with caching (MongoDB)
  • Error Handling - Consistent error responses across endpoints

Data Models

User Schema

{
  username: string;        // Unique username
  email: string;          // Unique email
  password: string;        // Plain text (consider hashing)
  authority: "FM" | "HQM"; // User role
  location?: string;      // Optional location
  fleet?: string;         // Optional fleet assignment
}

Fleet Schema

{
  name: string;           // Unique fleet name
  location: {
    lat: number;          // Latitude
    lng: number;          // Longitude
  };
  charts: [{
    category: string;     // Chart category name
    data: number[];       // Array of data points
    summary: string;      // Summary text
  }];
}

πŸ’» Development

Available Scripts

# Start development server with Turbopack
pnpm dev

# Build for production
pnpm build

# Start production server
pnpm start

# Run linter
pnpm lint

# Static export (for GitHub Pages)
pnpm build:static

Development Server

The development server runs on port 2107 by default with Turbopack enabled for faster builds.

pnpm dev
# Server: http://localhost:2107

Code Style

  • Functions: Keep under 20 lines when possible
  • Variables: Use descriptive names
  • Code: Optimized with low time complexity
  • Reusability: Avoid duplicate code
  • Testing: Follow TDD principles (write tests before implementation)

File Organization

  • Components: Reusable UI components in components/
  • API Routes: Server endpoints in app/api/
  • Utilities: Shared functions in lib/
  • Models: Database schemas in models/
  • Hooks: Custom React hooks in hooks/

🚒 Build & Deployment

Production Build

# Install dependencies
pnpm install

# Build the application
pnpm build

# Start production server
pnpm start

Static Export (GitHub Pages)

# Set environment variable
export NEXT_STATIC_EXPORT=true

# Build and export
pnpm build:static

# Output will be in ./out directory

Deployment Options

Vercel (Recommended)

  1. Connect your GitHub repository to Vercel
  2. Set environment variables in Vercel dashboard
  3. Deploy automatically on push

Docker

FROM node:18-alpine
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install
COPY . .
RUN pnpm build
EXPOSE 3000
CMD ["pnpm", "start"]

Traditional Server

  1. Build the application: pnpm build
  2. Start the server: pnpm start
  3. Configure reverse proxy (nginx/Apache)
  4. Set up PM2 or similar process manager

πŸ” Troubleshooting

Common Issues

MongoDB Connection Error

Problem: Cannot connect to MongoDB

Solutions:

  • Verify MongoDB URI is correct
  • Check network firewall settings
  • Ensure MongoDB Atlas IP whitelist includes your IP
  • Verify credentials are correct

JWT Token Issues

Problem: Authentication fails or tokens expire

Solutions:

  • Check JWT_SECRET is set in environment variables
  • Ensure secret is at least 32 characters
  • Verify cookie settings match your domain

Port Already in Use

Problem: Port 2107 is already in use

Solutions:

  • Change port in package.json: "dev": "next dev -p 3000"
  • Kill process using port: lsof -ti:2107 | xargs kill

Build Errors

Problem: TypeScript or build errors

Solutions:

  • Run pnpm install to ensure dependencies are up to date
  • Check TypeScript version compatibility
  • Clear .next folder: rm -rf .next
  • Run pnpm lint to identify issues

Map Not Loading

Problem: Leaflet map doesn't render

Solutions:

  • Ensure react-leaflet and leaflet are installed
  • Check CSS import: import "leaflet/dist/leaflet.css"
  • Verify Leaflet styles are loaded globally

πŸ“ Additional Notes

Security Considerations

  • Password Storage: Currently passwords are stored in plain text. Implement bcrypt hashing for production.
  • JWT Secret: Use a strong, random secret (minimum 32 characters).
  • HTTP-Only Cookies: Already implemented for token storage.
  • Input Sanitization: Use sanitizeInput utility for user inputs.
  • CORS: Configure CORS if using separate frontend/backend.

Performance Optimization

  • Code Splitting: Dynamic imports for heavy components
  • Database Indexing: Add indexes on frequently queried fields
  • Caching: MongoDB connection caching implemented
  • Debouncing: Search queries are debounced to reduce API calls
  • Lazy Loading: Charts and maps load on demand

Future Enhancements

  • Add password hashing (bcrypt)
  • Implement refresh tokens
  • Add data export functionality
  • Real-time updates via WebSockets
  • Advanced filtering and sorting
  • Multi-language support
  • Unit and integration tests
  • CI/CD pipeline setup

πŸ“„ License

This project is private and proprietary. All rights reserved.


πŸ‘₯ Contributing

This is a private project. For contributions, please contact the project maintainers.


πŸ“ž Support

For issues, questions, or support, please open an issue in the repository or contact the development team.


Made with ❀️ using Next.js, React, and TypeScript

About

Website Link

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages