An enterprise-grade, full-stack Last-Mile Delivery Management Platform built with Express, TypeScript, React (Vite), Tailwind CSS, Prisma ORM, and Leaflet Maps. It features a dynamic multi-factor pricing engine, volumetric weight billing, spatial proximity auto-assignment, immutable audit logs, delivery failure rescheduling, and multi-role dashboards for Admins, Customers, and Delivery Agents.
- Key Features
- Architecture & Tech Stack
- Quick Start Guide
- Demo Credentials
- Rate Calculation Engine Logic
- Auto-Assignment Algorithm
- Order Lifecycle & Rescheduling Flow
- Complete API Reference
- Database Schema
- Testing & Quality Assurance
- Deployment Guide
-
Volumetric Weight Formula: Calculates volumetric weight using
$\frac{\text{Length} \times \text{Breadth} \times \text{Height}}{\text{Volumetric Divisor (5000)}}$ in cm³/kg. - Higher of Actual vs Volumetric Weight: Automatically identifies and charges on the higher effective weight.
- Admin-Configurable Rate Cards: Separate rate cards for B2C Standard Consumer and B2B Enterprise Bulk Freight (Intra-zone rate, Inter-zone rate, base fare, minimum chargeable weight, tax rate). No hardcoded rates.
- COD Handling: Calculates fixed fee + percentage-based cash handling surcharges for Cash on Delivery shipments.
- Live Reactive Rate Preview: Real-time pricing breakdown preview as parcel dimensions and addresses are entered.
- Haversine Distance Formula: Computes exact great-circle distance between delivery agents and pickup coordinates.
- Multi-Factor Candidate Scoring: Factors in distance, zone affinity bonus, active concurrency workload penalty, and agent ratings to select the optimal rider.
- Fleet Telemetry: Live interactive Leaflet map rendering pickup, drop, and live agent location with real-time route polylines.
- Simulated GPS Movement: Agents can update/nudge their coordinates in real time.
-
State Machine Transitions:
PLACED$\rightarrow$ ASSIGNED$\rightarrow$ PICKED_UP$\rightarrow$ IN_TRANSIT$\rightarrow$ OUT_FOR_DELIVERY$\rightarrow$ DELIVEREDorFAILED$\rightarrow$ RESCHEDULED. - Immutable Log History: Every status transition logs timestamp, actor ID, actor role, actor name, GPS coordinates, and remarks.
- Failure Capture: Delivery agent reports failure with categorized reasons (Customer unavailable, Incorrect address, Customer refused, etc.).
- Automated Customer Notification: Dispatches notification with direct rescheduling link.
- Zero-Friction Reschedule: Customer selects a new delivery date; the order resets to
RESCHEDULEDand triggers automatic fleet reassignment.
- Admin Portal: Operational KPI overview, revenue metrics, rate cards studio with pricing sandbox, zone/pincode manager, and master shipment queue with manual assign & status overrides.
- Customer Portal: 3D parcel booking wizard with live zone pills, shipment dashboard, and public live tracking.
- Delivery Agent Portal: Mobile-friendly console with action sheets (
Confirm Pickup,In Transit,Complete Delivery,Report Failure) and GPS updater. - 1-Click Sandbox Role Switcher: Instant switching between Admin, Customer, and Agent accounts with pre-loaded state.
lastmile-delivery-tracker/
├── server/ # Express + TypeScript Backend
│ ├── prisma/
│ │ ├── schema.prisma # SQLite relational data model
│ │ └── dev.db # SQLite database file
│ └── src/
│ ├── services/ # Rate Engine, Auto-Assignment, Order Lifecycle, Notifications
│ ├── controllers/ # Route controllers for Auth, Zones, Rate Cards, Orders, Fleet
│ ├── routes/ # RESTful API route endpoints
│ ├── __tests__/ # Automated Jest test suites
│ └── seed.ts # Rich database seeder
├── client/ # React + Vite Frontend
│ └── src/
│ ├── api/ # API Client wrapper
│ ├── context/ # Auth Context & Quick Demo Switcher
│ ├── components/ # Layout, Navbar, StatusBadge, Modal, MapViewer (Leaflet)
│ └── pages/ # Admin, Customer, Agent, and Auth views
├── SYSTEM_DESIGN.md # In-depth system design write-up (800 words)
├── README.md # Complete documentation
└── package.json # Monorepo orchestration scripts
- Backend: Node.js v20+, Express.js, TypeScript, Prisma ORM, SQLite, bcryptjs, jsonwebtoken, Jest.
- Frontend: React 18, Vite, TypeScript, Tailwind CSS, Lucide Icons, Leaflet / React-Leaflet.
- Node.js (v18 or v20+)
- npm (v9+)
-
Clone the Repository & Install Dependencies:
npm run install:all
-
Setup Database & Seed Demo Data:
cd server npx prisma db push npm run seed cd ..
-
Start Development Servers (Concurrent Backend + Frontend):
npm run dev
- Frontend UI: http://localhost:5173
- Backend API: http://localhost:5000
- API Health Check: http://localhost:5000/api/health
You can use the 1-Click Interactive Sandbox Switcher at the top of the application or log in manually with the following pre-seeded demo accounts:
| Role | Password | Description | |
|---|---|---|---|
| Admin | admin@lastmile.com |
password123 |
Full access to dispatch, rate card studio, zones, and overrides |
| Customer (B2B) | sarah@acme-corp.com |
password123 |
Enterprise account with wholesale shipments & pallet freight |
| Customer (B2C) | john.doe@gmail.com |
password123 |
Retail customer booking consumer express packages |
| Agent (Bike) | rajesh.agent@lastmile.com |
password123 |
Delivery rider in Central Business Hub |
| Agent (Van) | vikram.agent@lastmile.com |
password123 |
Delivery driver in South Metro Zone |
┌──────────────────────────────────────┐
│ Length (cm) × Width (cm) × Height(cm)│
└──────────────────┬───────────────────┘
│ ÷ Volumetric Divisor (5000)
▼
Volumetric Weight (kg)
│
┌──────────────────────┴──────────────────────┐
▼ ▼
Actual Weight (kg) Volumetric Weight (kg)
└──────────────────────┬──────────────────────┘
│ Higher of two
▼
Chargeable Weight (kg)
│
┌────────────────┴────────────────┐
▼ ▼
Intra-Zone Delivery Inter-Zone Delivery
(Same Origin & Drop) (Different Origin & Drop)
│ │
Apply Intra-Zone Rate/kg Apply Inter-Zone Rate/kg
└────────────────┬────────────────┘
│
▼
Base Fare + (Chargeable Wt × Rate/kg)
│
▼
+ COD Surcharge (if COD)
│
▼
+ GST / Tax (18%)
│
▼
Grand Total Fare
When an order is created or rescheduled, the Assignment Engine:
- Queries all active delivery agents (
AVAILABLEorON_DELIVERY). - Calculates the Haversine distance
$d_i$ in km from the agent's current coordinates to the pickup location. - Computes a multi-attribute candidate score:
$$\text{Score} = (d_i \times 10) + \text{ZoneAffinityBonus} + (\text{ActiveLoad} \times 20) + \text{AvailabilityBonus} + ((5.0 - \text{Rating}) \times 5)$$ - Sorts agents ascending by score and auto-assigns the top candidate.
POST /api/auth/login: Authenticate with email & password. Returns JWT.POST /api/auth/register: Register new customer or agent.POST /api/auth/demo-login: 1-Click login asADMIN,CUSTOMER, orAGENT.GET /api/auth/me: Get current authenticated user profile.
GET /api/rate-cards: Fetch active B2B & B2C rate cards.POST /api/rate-cards: Create or update rate card parameters (Admin only).POST /api/rate-cards/test-calculate: Sandbox rate calculation preview.
GET /api/zones: List all delivery zones with mapped pincodes.GET /api/zones/lookup/:pincode: Lookup zone for a given postal code.POST /api/zones: Create new zone (Admin only).POST /api/zones/:id/areas: Map new pincode and coordinates to a zone.DELETE /api/zones/areas/:areaId: Delete pincode mapping.
POST /api/orders/preview-rate: Calculate live price breakdown before order confirmation.POST /api/orders: Create new delivery order.GET /api/orders: Query orders with filters (status,zoneId,agentId,orderType,search).GET /api/orders/:id: Get order details with immutable tracking history.GET /api/orders/track/:trackingNumber: Public live tracking by tracking number.PATCH /api/orders/:id/status: Update order status (Agent/Admin).POST /api/orders/:id/reschedule: Reschedule failed delivery for a new date.POST /api/orders/:id/auto-assign: Trigger smart auto-assignment to nearest agent.POST /api/orders/:id/manual-assign: Manually assign specific agent (Admin).
GET /api/agents: List all delivery agents and active loads.GET /api/agents/candidates/:orderId: Get ranked candidate scores for an order.PATCH /api/agents/profile: Update agent status and GPS coordinates.
model User {
id String @id @default(uuid())
email String @unique
passwordHash String
name String
phone String?
role String @default("CUSTOMER") // ADMIN, CUSTOMER, AGENT
avatar String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Zone {
id String @id @default(uuid())
name String @unique
code String @unique
description String?
color String @default("#3b82f6")
isActive Boolean @default(true)
areas ZoneArea[]
}
model ZoneArea {
id String @id @default(uuid())
zoneId String
pincode String @unique
areaName String
city String
state String
latitude Float
longitude Float
}
model RateCard {
id String @id @default(uuid())
name String
orderType String @unique // B2B, B2C
minWeightKg Float @default(0.5)
baseFare Float @default(50.0)
intraZonePerKgRate Float @default(30.0)
interZonePerKgRate Float @default(60.0)
volumetricDivisor Float @default(5000.0)
codSurchargeFixed Float @default(20.0)
codSurchargePercent Float @default(2.0)
taxPercent Float @default(18.0)
isActive Boolean @default(true)
}
model Order {
id String @id @default(uuid())
trackingNumber String @unique
customerId String
orderType String @default("B2C") // B2B, B2C
paymentType String @default("PREPAID") // PREPAID, COD
pickupPincode String
dropPincode String
packageLength Float
packageBreadth Float
packageHeight Float
packageActualWeight Float
packageVolumetricWeight Float
chargeableWeight Float
isSameZone Boolean @default(false)
basePrice Float
weightPrice Float
codSurcharge Float @default(0.0)
taxAmount Float @default(0.0)
totalPrice Float
status String @default("PLACED")
assignedAgentId String?
failureReason String?
rescheduleCount Int @default(0)
rescheduledDate DateTime?
}
model OrderTrackingLog {
id String @id @default(uuid())
orderId String
status String
actorId String?
actorRole String @default("ADMIN")
actorName String?
locationLat Float?
locationLng Float?
locationDescription String?
remarks String?
timestamp DateTime @default(now())
}Run automated unit and integration tests covering the Rate Calculation Engine, Volumetric Weight math, Haversine Distance, and Auto-Assignment scoring:
npm testTest Results:
RateEngineService: Volumetric calculation, higher-of-actual-vs-volumetric weight, Intra vs Inter-zone rates, COD surcharges.AssignmentEngineService: Haversine formula distance accuracy, agent ranking and scoring.
- Set Environment Variables:
NODE_ENV=productionPORT=5000JWT_SECRET=<your-production-secret>DATABASE_URL="file:./dev.db"
- Build Command:
cd server && npm install && npx prisma db push && npm run seed && npm run build
- Start Command:
cd server && npm start
- Set Root Directory to
client. - Build Command:
npm run build - Output Directory:
dist - Set Environment Variable:
VITE_API_URL=<backend-url>
MIT License. Built for Last-Mile Logistics Intelligence.