Skip to content

Latest commit

Β 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

IoT Supply Chain Tracking System - Backend

Node.js Express.js MongoDB Socket.io

Complete backend implementation for real-time IoT supply chain tracking with GPS and RFID verification.

🎯 Features

  • βœ… Order Management - Create and track orders with RFID-tagged items
  • βœ… Real-time GPS Tracking - Track trucks in real-time using GPS coordinates
  • βœ… RFID Verification - Verify delivered items using RFID tags
  • βœ… Discrepancy Detection - Automatically detect missing or extra items
  • βœ… WebSocket Updates - Real-time updates for dashboards
  • βœ… Authentication - JWT-based user authentication with roles
  • βœ… ESP32 Simulator - Mock hardware for testing without physical devices

πŸ“‹ Table of Contents


πŸš€ Quick Start

Prerequisites

  • Node.js v18 or higher
  • MongoDB (local installation or MongoDB Atlas account)

Installation

# 1. Clone the repository
git clone https://github.com/Sasmonk/backend_v1.git
cd backend_v1

# 2. Install dependencies
npm install

# 3. Create .env file from example
cp .env.example .env

# 4. Edit .env file with your configuration:
#    - MONGODB_URI: Your MongoDB connection string
#    - JWT_SECRET: A strong secret key for JWT tokens

# 5. Seed database with sample data
npm run seed

# 6. Start development server
npm run dev

# 7. (Optional) Start ESP32 simulator in another terminal
npm run simulator

Server will run at: http://localhost:5000

Quick Test

# Test health endpoint
curl http://localhost:5000/health

# Run comprehensive test suite
npm run test:full

🎯 Project Overview

This system tracks goods from factory to customer with:

  • Factory Dispatch: Create orders and track shipments
  • GPS Tracking: Real-time location updates from trucks
  • RFID Verification: Verify delivered items at customer location
  • Dispute Management: Handle missing items and discrepancies
  • Real-time Updates: WebSocket for live dashboard updates

Tech Stack

  • Runtime: Node.js v18+ (ES6 Modules)
  • Framework: Express.js
  • Database: MongoDB with Mongoose
  • Real-time: Socket.io
  • Authentication: JWT (jsonwebtoken)
  • Validation: Joi
  • Security: Helmet, CORS, Rate Limiting
  • Password Hashing: bcryptjs

βš™οΈ Setup Instructions

1. MongoDB Setup

Option A: Local MongoDB

# Install MongoDB locally
# Start MongoDB service
mongod

Option B: MongoDB Atlas (Recommended)

  1. Go to MongoDB Atlas
  2. Create a free cluster (M0)
  3. Create database user
  4. Whitelist IP address (use 0.0.0.0/0 for testing)
  5. Get connection string
  6. Update .env file with connection string

2. Environment Variables

Create .env file:

PORT=5000
MONGODB_URI=mongodb://localhost:27017/supply-chain
NODE_ENV=development
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
JWT_SECRET=your-strong-secret-key-change-in-production

For MongoDB Atlas:

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/supply-chain

3. Database Seeding

npm run seed

Creates:

  • 3 Factories (Mumbai, Delhi, Bangalore)
  • 5 Customers (different cities)
  • 10 Orders (various statuses)
  • 35+ Tracking records
  • 7 Verifications

πŸ“‘ API Documentation

Authentication

Signup

POST /api/auth/signup
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "Password123",
  "role": "customer"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "Password123"
}

Get Profile (requires authentication)

GET /api/auth/me
Authorization: Bearer <token>

Order Management

  • POST /api/orders/create - Create new order
  • GET /api/orders - List orders (with filters)
  • GET /api/orders/:orderId - Get order details
  • PATCH /api/orders/:orderId/status - Update order status
  • DELETE /api/orders/:orderId - Cancel order

GPS Tracking

  • POST /api/tracking/update - Update GPS location
  • GET /api/tracking/:orderId/latest - Get latest location
  • GET /api/tracking/:orderId/history - Get tracking history
  • GET /api/tracking/:orderId/route - Get route (GeoJSON)
  • POST /api/tracking/:orderId/eta - Calculate ETA
  • GET /api/tracking/active - Get active shipments

RFID Verification

  • POST /api/verification/start - Start verification
  • POST /api/verification/scan - Scan RFID tag
  • POST /api/verification/complete - Complete verification
  • GET /api/verification/:orderId - Get verification status

Complete API Documentation: See API_ENDPOINTS.txt

User Guide: See USER_GUIDE.txt


πŸ”Œ WebSocket Events

Client β†’ Server Events

  • join:order - Join order room
  • leave:order - Leave order room
  • join:factory - Join factory dashboard
  • join:customer - Join customer dashboard

Server β†’ Client Events

  • order:created - New order created
  • order:status_updated - Order status changed
  • tracking:location_updated - GPS location updated
  • verification:started - Verification started
  • verification:item_scanned - RFID tag scanned
  • verification:completed - Verification completed
  • missing:report_sent - Missing items reported

Example Client Code

import io from 'socket.io-client';

const socket = io('http://localhost:5000');

// Join order room
socket.emit('join:order', 'ORD-20251107-001');

// Listen for location updates
socket.on('tracking:location_updated', (data) => {
  console.log('Location:', data.location);
});

πŸ€– ESP32 Simulator

Since you don't have physical ESP32 hardware, use the simulator:

npm run simulator

Features:

  • Sends GPS updates every 5 seconds
  • Simulates RFID scanning every 10 seconds (when truck stops)
  • Automatically finds active orders
  • Shows real-time progress in console

What it does:

  1. Finds active orders for trucks
  2. Simulates truck movement along route
  3. Sends GPS coordinates to API
  4. Simulates RFID scanning at destination

πŸ§ͺ Testing

Automated Test Suite

# Run comprehensive test suite
npm run test:full

Tests include:

  • βœ… Health check
  • βœ… User authentication (signup/login)
  • βœ… Order creation and management
  • βœ… GPS tracking updates
  • βœ… RFID verification flow
  • βœ… Error handling
  • βœ… Validation

Manual Testing

# Test health endpoint
curl http://localhost:5000/health

# Test with test.http file (REST Client extension)
# Or use the frontend playground
npm run client

Test Results

All tests passing (100% success rate) βœ…


πŸ“¦ Project Structure

backend_v1/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ db.js              # MongoDB connection
β”‚   β”‚   └── socket.js          # Socket.io configuration
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ Order.js           # Order model
β”‚   β”‚   β”œβ”€β”€ Tracking.js        # GPS tracking model
β”‚   β”‚   β”œβ”€β”€ Verification.js    # RFID verification model
β”‚   β”‚   β”œβ”€β”€ Factory.js         # Factory model
β”‚   β”‚   β”œβ”€β”€ Customer.js        # Customer model
β”‚   β”‚   └── User.js            # User model (authentication)
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ orderRoutes.js     # Order API routes
β”‚   β”‚   β”œβ”€β”€ trackingRoutes.js  # Tracking API routes
β”‚   β”‚   β”œβ”€β”€ verificationRoutes.js # Verification API routes
β”‚   β”‚   └── authRoutes.js      # Authentication routes
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ orderController.js
β”‚   β”‚   β”œβ”€β”€ trackingController.js
β”‚   β”‚   β”œβ”€β”€ verificationController.js
β”‚   β”‚   └── authController.js
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”œβ”€β”€ errorHandler.js    # Global error handler
β”‚   β”‚   β”œβ”€β”€ validation.js      # Joi validation
β”‚   β”‚   β”œβ”€β”€ rateLimiter.js     # Rate limiting
β”‚   β”‚   └── auth.js            # JWT authentication
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ responseFormatter.js
β”‚   β”‚   β”œβ”€β”€ idGenerator.js
β”‚   β”‚   └── distanceCalculator.js
β”‚   β”œβ”€β”€ scripts/
β”‚   β”‚   β”œβ”€β”€ seedDatabase.js    # Database seeding
β”‚   β”‚   β”œβ”€β”€ esp32Simulator.js  # ESP32 mock simulator
β”‚   β”‚   β”œβ”€β”€ testAPI.js         # Basic API tests
β”‚   β”‚   └── fullTestSuite.js   # Comprehensive test suite
β”‚   └── server.js              # Main server file
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ index.html             # Simple playground UI
β”‚   └── app.js                 # Frontend JavaScript
β”œβ”€β”€ .env.example               # Environment variables template
β”œβ”€β”€ .gitignore                 # Git ignore rules
β”œβ”€β”€ package.json               # Dependencies and scripts
β”œβ”€β”€ README.md                  # This file
β”œβ”€β”€ API_ENDPOINTS.txt          # Complete API documentation
β”œβ”€β”€ USER_GUIDE.txt             # User workflow guide
└── NEXT_STEPS.txt             # Development roadmap

πŸš€ Deployment

Environment Variables

Set these in your production environment:

PORT=5000
MONGODB_URI=mongodb+srv://...
NODE_ENV=production
ALLOWED_ORIGINS=https://your-frontend.com
JWT_SECRET=strong-production-secret

Deployment Platforms

Railway

railway login
railway init
railway up

Render

  • Connect GitHub repository
  • Set environment variables
  • Deploy

Heroku

heroku create
heroku config:set MONGODB_URI=...
heroku config:set JWT_SECRET=...
git push heroku main

Production Checklist

  • Set NODE_ENV=production
  • Configure MongoDB Atlas production cluster
  • Set strong JWT_SECRET
  • Configure ALLOWED_ORIGINS for CORS
  • Enable HTTPS
  • Set up monitoring
  • Configure rate limiting
  • Test all endpoints

πŸ“ Available Scripts

npm start          # Start production server
npm run dev        # Start development server (with auto-reload)
npm run seed       # Seed database with sample data
npm run simulator  # Start ESP32 simulator
npm test           # Run basic API tests
npm run test:full  # Run comprehensive test suite
npm run client     # Start frontend playground

πŸ” Security

  • βœ… Password hashing with bcryptjs
  • βœ… JWT token authentication
  • βœ… Rate limiting on all endpoints
  • βœ… Input validation with Joi
  • βœ… Helmet.js security headers
  • βœ… CORS configuration
  • βœ… MongoDB injection prevention

πŸ“š Documentation


🀝 Contributing

  1. Fork the repository
  2. Create your 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 ISC License.


πŸ‘€ Author

Sasmonk


πŸ™ Acknowledgments

  • Express.js community
  • MongoDB documentation
  • Socket.io documentation
  • All open-source contributors

πŸ“ž Support

For issues and questions:

  • Open an issue on GitHub
  • Check documentation files
  • Review API_ENDPOINTS.txt for API details

Last Updated: November 2024
Version: 1.0.0

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages