Skip to content
Vishwas1345Public

About

A comprehensive on-demand fuel delivery management system built with the MERN stack, connecting customers, fuel stations, and delivery personnel through role-based dashboards, order tracking, and route management.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

124 Commits

Folders and files

Repository files navigation

FuelMate logo FuelMate - On-Demand Fuel Delivery System

License: MIT Node.js React TypeScript

FuelMate is a comprehensive on-demand fuel delivery management system built with the MERN stack. It provides a seamless platform connecting customers, fuel stations, and delivery personnel for efficient fuel delivery services.

πŸ“‹ Table of Contents

✨ Features

Customer Features

  • πŸ” User authentication and authorization
  • πŸ“ Real-time location-based fuel ordering
  • πŸ’³ Multiple payment options
  • πŸ“± Order tracking and history
  • ⭐ Rating and review system
  • πŸ”” Push notifications for order updates

Station Features

  • πŸ“Š Dashboard with analytics
  • πŸ“¦ Order management system
  • πŸ‘₯ Delivery personnel management
  • πŸ“ˆ Revenue tracking
  • πŸ“ Service area management

Delivery Personnel Features

  • πŸ—ΊοΈ Route optimization
  • πŸ“‹ Order assignment and tracking
  • πŸ’° Earnings dashboard
  • πŸ“Š Performance metrics

Admin Features

  • πŸ‘¨β€πŸ’Ό User management
  • πŸͺ Station management
  • πŸ“Š System-wide analytics
  • πŸ”§ Configuration management

πŸ› οΈ Tech Stack

Frontend

  • React 18.3 - UI library
  • TypeScript - Type safety
  • Vite - Build tool and dev server
  • Tailwind CSS - Utility-first CSS framework
  • shadcn/ui - Component library
  • React Router - Client-side routing
  • TanStack Query - Data fetching and caching
  • Recharts - Data visualization
  • Mapbox GL - Interactive maps

Backend

  • Node.js - Runtime environment
  • Express.js - Web framework
  • MongoDB - NoSQL database
  • Mongoose - ODM for MongoDB
  • Redis - In-memory store for OTP management and analytics caching
  • ioredis - Redis client for Node.js
  • JWT - Authentication
  • bcrypt - Password hashing
  • Winston - Professional logging with file rotation

DevOps & Tools

  • ESLint - Code linting
  • Nodemon - Auto-restart server
  • Git - Version control
  • loglevel - Client-side logging

πŸ“ Project Structure

Fuel-Mate/
β”œβ”€β”€ πŸ“‚ public/                    # Static assets
β”‚   β”œβ”€β”€ favicon.ico              # App favicon
β”‚   └── robots.txt               # SEO robots file
β”‚
β”œβ”€β”€ πŸ“‚ server/                    # Backend application
β”‚   β”œβ”€β”€ πŸ“‚ controllers/          # Request handlers
β”‚   β”œβ”€β”€ πŸ“‚ middleware/           # Custom middleware
β”‚   β”œβ”€β”€ πŸ“‚ models/               # Mongoose schemas
β”‚   β”œβ”€β”€ πŸ“‚ routes/               # API routes
β”‚   β”œβ”€β”€ πŸ“‚ lib/                  # Utilities and helpers
β”‚   β”œβ”€β”€ index.js                 # Database connection
β”‚   └── server.js                # Express server setup
β”‚
β”œβ”€β”€ πŸ“‚ src/                       # Frontend application
β”‚   β”œβ”€β”€ πŸ“‚ components/           # React components
β”‚   β”‚   β”œβ”€β”€ πŸ“‚ ui/               # shadcn/ui components
β”‚   β”‚   └── ...                  # Custom components
β”‚   β”œβ”€β”€ πŸ“‚ contexts/             # React contexts
β”‚   β”œβ”€β”€ πŸ“‚ hooks/                # Custom React hooks
β”‚   β”œβ”€β”€ πŸ“‚ lib/                  # Utilities
β”‚   β”œβ”€β”€ πŸ“‚ models/               # TypeScript types/interfaces
β”‚   β”œβ”€β”€ πŸ“‚ pages/                # Page components
β”‚   β”œβ”€β”€ πŸ“‚ routes/               # Route configurations
β”‚   β”œβ”€β”€ πŸ“‚ services/             # API services
β”‚   β”œβ”€β”€ App.tsx                  # Root component
β”‚   β”œβ”€β”€ main.tsx                 # Entry point
β”‚   └── index.css                # Global styles
β”‚
β”œβ”€β”€ πŸ“„ .env                       # Environment variables (not in git)
β”œβ”€β”€ πŸ“„ .gitignore                # Git ignore rules
β”œβ”€β”€ πŸ“„ components.json           # shadcn/ui config
β”œβ”€β”€ πŸ“„ eslint.config.js          # ESLint configuration
β”œβ”€β”€ πŸ“„ index.html                # HTML template
β”œβ”€β”€ πŸ“„ package.json              # Dependencies and scripts
β”œβ”€β”€ πŸ“„ postcss.config.js         # PostCSS configuration
β”œβ”€β”€ πŸ“„ tailwind.config.ts        # Tailwind CSS config
β”œβ”€β”€ πŸ“„ tsconfig.json             # TypeScript config
β”œβ”€β”€ πŸ“„ tsconfig.app.json         # App TypeScript config
β”œβ”€β”€ πŸ“„ tsconfig.node.json        # Node TypeScript config
β”œβ”€β”€ πŸ“„ vite.config.ts            # Vite configuration
└── πŸ“„ README.md                 # This file

πŸš€ Getting Started

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v18 or higher)
  • npm or yarn
  • MongoDB (local or Atlas)
  • Redis (local via redis-server, or Docker: docker run -p 6379:6379 redis)
  • Git

Installation

  1. Clone the repository
 git clone https://github.com/Vishwas1345/Fuel-Mate.git
 cd Fuel-Mate
  1. Install dependencies
 npm install
  1. Set up environment variables
 # Create .env file in the root directory
 cp .env.example .env
 # Edit .env with your configuration

πŸ” Environment Variables

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

# Server Configuration
PORT=5000
NODE_ENV=development

# Database
MONGODB_URI=mongodb://localhost:27017/fuelmate
# Or use MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/fuelmate

# Redis
REDIS_URL=redis://localhost:6379
# Or with authentication:
# REDIS_URL=redis://:yourpassword@localhost:6379

# JWT Secret
JWT_SECRET=your_super_secret_jwt_key_here_change_in_production

# Frontend URL (for CORS)
CLIENT_URL=http://localhost:5173

# Mapbox (for maps)
VITE_MAPBOX_TOKEN=your_mapbox_token_here

# Payment Gateway (if applicable)
PAYMENT_API_KEY=your_payment_api_key

# Logging Configuration
LOG_LEVEL=debug              # Server: error, warn, info, http, debug
VITE_LOG_LEVEL=debug         # Client: trace, debug, info, warn, error

πŸ“ Logging

FuelMate uses professional logging libraries for both client and server:

Server Logging (Winston)

  • Colored console output for easy debugging
  • Daily rotating log files in server/logs/
  • Separate error logs for quick issue identification
  • Automatic exception handling

Client Logging (loglevel)

  • Colored browser console output
  • Timestamp formatting
  • Helper methods for API calls, components, and actions
  • Dynamic log level changes

Quick Start

Server:

import logger from './utils/logger.js';

logger.info('User logged in', { userId: user.id });
logger.error('Database error', { error: err.message });

Client:

import logger from '@/utils/logger';

logger.info('Component mounted');
logger.api('POST', '/api/orders', { orderId: '123' });

Documentation

  • πŸ“– Full Guide: See LOGGER_USAGE.md for comprehensive documentation
  • πŸš€ Quick Reference: See LOGGER_SETUP.md for setup summary
  • πŸ’‘ Examples: Check server/examples/ and client/examples/

Log Files (Server)

Logs are saved to server/logs/:

  • application-YYYY-MM-DD.log - All logs
  • error-YYYY-MM-DD.log - Errors only
  • exceptions-YYYY-MM-DD.log - Uncaught exceptions
  • rejections-YYYY-MM-DD.log - Unhandled rejections

## ⚑ Redis Integration

FuelMate uses Redis as a fast, expiry-aware layer alongside MongoDB. The client is set up in `server/lib/redis.js` using **ioredis** with exponential retry and graceful degradation β€” if Redis is unavailable, the app continues to function normally.

### OTP Storage

Email verification OTPs are stored entirely in Redis instead of the User document.

| Detail | Value |
|---|---|
| Key | `otp:<email>` |
| Fields | `hash` (bcrypt), `attempts` |
| TTL | **10 minutes** (auto-deleted by Redis) |
| Max attempts | 5 |

**Why Redis for OTPs?**
- OTPs are temporary β€” Redis TTL handles expiry automatically, no cleanup queries needed
- Failed attempts increment a counter in Redis, no MongoDB write required
- The `User` model stays clean β€” no `emailVerificationOtpHash`, `emailVerificationOtpExpires`, or `emailVerificationAttempts` fields

### Analytics Caching

The `GET /api/analytics` endpoint caches its aggregated result in Redis.

| Detail | Value |
|---|---|
| Key | `analytics:<userId>` |
| TTL | **5 minutes** |
| Invalidation | Immediately on order status β†’ `delivered` |

**How it works:**
1. Request hits `/api/analytics`
2. Cache hit β†’ returns JSON in ~0.2ms
3. Cache miss β†’ aggregates all delivered orders from MongoDB, stores result in Redis, responds
4. When a station marks an order as `delivered`, both the customer's and station's cache keys are deleted so the next load reflects real data

### Local Setup

Start Redis before running the server:

```bash
# Option A β€” local Redis
redis-server

# Option B β€” Docker
docker run -p 6379:6379 redis

Set REDIS_URL in server/.env:

REDIS_URL=redis://localhost:6379

πŸƒ Running the Application

Development Mode

Run Frontend (Vite Dev Server)

npm run dev

The frontend will be available at http://localhost:5173

Run Backend (Node.js Server)

npm run server:dev

The backend API will be available at http://localhost:5000

Run Both Concurrently

# In separate terminals:
# Terminal 1:
npm run dev

# Terminal 2:
npm run server:dev

Production Mode

Build Frontend

npm run build

Run Backend

npm run server

Preview Production Build

npm run preview

πŸ“š API Documentation

Base URL

http://localhost:5000/api

Authentication Endpoints

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User login
  • GET /api/auth/me - Get current user

Order Endpoints

  • GET /api/orders - Get all orders
  • POST /api/orders - Create new order
  • GET /api/orders/:id - Get order by ID
  • PUT /api/orders/:id - Update order
  • DELETE /api/orders/:id - Delete order

User Endpoints

  • GET /api/users - Get all users
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Challenges and solutions

FuelMate sits between customers, stations, and field delivery, so several design tensions show up in the product and codebase:

Challenge Solution
Identity and trust on signup β€” email accounts need to be real before users order fuel or stations go live. Email OTP for local registration (bounded attempts, resend + expiry), Google OAuth for verified-email sign-in, and JWT + httpOnly refresh so sessions stay usable without exposing long-lived tokens in JS.
One product, two roles (and one data model) β€” customers and stations share auth and listings but need different profiles, dashboards, and permissions. A single User collection with role (customer / station) and role-specific fields; stations are users referenced by stationId on orders so analytics and listings stay consistent.
Analytics when history is thin or APIs partial β€” charts and β€œinsights” break if there are no delivered orders or missing profile fragments (e.g. pump location). Server-side aggregates where possible, client fallbacks rebuilt from delivered orders, defensive UI (optional chaining / placeholders), and rules-based dashboard copy instead of hard-coded fake AI so messaging tracks real data.
OAuth hijacking the whole browser tab β€” a full redirect to Google pulls users out of sign-up context and feels heavy. Popup-based Google sign-in (window.open to /api/auth/google), **postMessage** from /auth/callback back to the opener, then the main tab finishes login; refresh cookies still work because they are scoped to the API host, not the window.
Deliverability and local development β€” OTP and notifications must send in production but engineers often lack mail infra locally. Central **mailService** using SendGrid when **SENDGRID_API_KEY** is set; clear logging / safe fallbacks when mail is disabled so verification flows remain testable without leaking secrets in responses.
Short-lived access tokens vs smooth UX β€” aggressive access JWT expiry improves security but breaks tabs mid-session. **POST /api/auth/refresh-token** with httpOnly refresh cookies (and optional stored refresh fallback), plus a fetch layer that only retries with refresh on protected routesβ€”not on login/register/verify, so bad credentials are not mistaken for expired sessions.
Onboarding fatigue for returning users β€” new flows should not repeat after every login or OAuth return. **isProfileComplete** on the user record plus a per-user β€œonboarding seen” flag in localStorage so first-time signups see setup once, while returning users go straight to the customer or station dashboard.
Temporary OTP state polluting the User model β€” storing hash, expiry, and attempt count as MongoDB fields means manual cleanup and a write on every failed attempt. OTP stored entirely in Redis (otp:<email> hash, 10-minute TTL). Redis TTL handles expiry automatically, failed attempts increment a counter in-place without a MongoDB write, and the key self-destructs on success β€” the User document never holds OTP state.
Analytics recalculated on every dashboard load β€” full MongoDB scan of delivered orders on every request is slow and wasteful for both the station and customer dashboards. Redis cache (analytics:<userId>, 5-minute TTL). Cache hit returns in ~0.2ms. Cache is invalidated immediately when an order is marked delivered so dashboards always reflect real data without polling.

Future enhancements

Short-term and longer-term directions that would deepen FuelMate without changing the core MERN shape of the product:

  • Payments and fulfilment β€” Integrate a real payment gateway (UPI / cards) with webhooks for settlement status, plus SMS or WhatsApp order updates so customers and drivers are notified outside the browser.
  • Operations β€” Driver mobile app or PWA with GPS pings, dispatch rules (auto-assign, SLA alerts), and inventory / bowser checks so stations cannot oversell capacity in peak windows.
  • Trust and scale β€” KYC-lite for stations, richer review moderation, admin console for disputes and pricing audits, and horizontal scaling (job queues for mail/analytics, read replicas, or caching hot station lists).

🀝 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

πŸ“ License

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

πŸ‘¨β€πŸ’» Author

Vishwas

πŸ™ Acknowledgments


Made with ❀️ by Vishwas

About

A comprehensive on-demand fuel delivery management system built with the MERN stack, connecting customers, fuel stations, and delivery personnel through role-based dashboards, order tracking, and route management.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages