Complete backend implementation for real-time IoT supply chain tracking with GPS and RFID verification.
- β 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
- Quick Start
- Project Overview
- Setup Instructions
- API Documentation
- WebSocket Events
- ESP32 Simulator
- Testing
- Project Structure
- Deployment
- Node.js v18 or higher
- MongoDB (local installation or MongoDB Atlas account)
# 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 simulatorServer will run at: http://localhost:5000
# Test health endpoint
curl http://localhost:5000/health
# Run comprehensive test suite
npm run test:fullThis 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
- 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
Option A: Local MongoDB
# Install MongoDB locally
# Start MongoDB service
mongodOption B: MongoDB Atlas (Recommended)
- Go to MongoDB Atlas
- Create a free cluster (M0)
- Create database user
- Whitelist IP address (use
0.0.0.0/0for testing) - Get connection string
- Update
.envfile with connection string
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-productionFor MongoDB Atlas:
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/supply-chainnpm run seedCreates:
- 3 Factories (Mumbai, Delhi, Bangalore)
- 5 Customers (different cities)
- 10 Orders (various statuses)
- 35+ Tracking records
- 7 Verifications
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>POST /api/orders/create- Create new orderGET /api/orders- List orders (with filters)GET /api/orders/:orderId- Get order detailsPATCH /api/orders/:orderId/status- Update order statusDELETE /api/orders/:orderId- Cancel order
POST /api/tracking/update- Update GPS locationGET /api/tracking/:orderId/latest- Get latest locationGET /api/tracking/:orderId/history- Get tracking historyGET /api/tracking/:orderId/route- Get route (GeoJSON)POST /api/tracking/:orderId/eta- Calculate ETAGET /api/tracking/active- Get active shipments
POST /api/verification/start- Start verificationPOST /api/verification/scan- Scan RFID tagPOST /api/verification/complete- Complete verificationGET /api/verification/:orderId- Get verification status
Complete API Documentation: See API_ENDPOINTS.txt
User Guide: See USER_GUIDE.txt
join:order- Join order roomleave:order- Leave order roomjoin:factory- Join factory dashboardjoin:customer- Join customer dashboard
order:created- New order createdorder:status_updated- Order status changedtracking:location_updated- GPS location updatedverification:started- Verification startedverification:item_scanned- RFID tag scannedverification:completed- Verification completedmissing:report_sent- Missing items reported
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);
});Since you don't have physical ESP32 hardware, use the simulator:
npm run simulatorFeatures:
- 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:
- Finds active orders for trucks
- Simulates truck movement along route
- Sends GPS coordinates to API
- Simulates RFID scanning at destination
# Run comprehensive test suite
npm run test:fullTests include:
- β Health check
- β User authentication (signup/login)
- β Order creation and management
- β GPS tracking updates
- β RFID verification flow
- β Error handling
- β Validation
# Test health endpoint
curl http://localhost:5000/health
# Test with test.http file (REST Client extension)
# Or use the frontend playground
npm run clientAll tests passing (100% success rate) β
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
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-secretRailway
railway login
railway init
railway upRender
- Connect GitHub repository
- Set environment variables
- Deploy
Heroku
heroku create
heroku config:set MONGODB_URI=...
heroku config:set JWT_SECRET=...
git push heroku main- Set
NODE_ENV=production - Configure MongoDB Atlas production cluster
- Set strong
JWT_SECRET - Configure
ALLOWED_ORIGINSfor CORS - Enable HTTPS
- Set up monitoring
- Configure rate limiting
- Test all endpoints
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- β 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
- API_ENDPOINTS.txt - Complete API reference
- USER_GUIDE.txt - User workflow guide
- NEXT_STEPS.txt - Development roadmap
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the ISC License.
Sasmonk
- GitHub: @Sasmonk
- Express.js community
- MongoDB documentation
- Socket.io documentation
- All open-source contributors
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