Skip to content

Repository files navigation

Last-Mile Delivery Tracker Platform

Node.js React TypeScript Prisma Tailwind CSS License

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.


Table of Contents


Key Features

1. Dynamic Rate Calculation Engine

  • 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.

2. Auto-Assignment & Spatial Proximity Routing

  • 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.

3. Immutable Tracking & Audit Trail

  • State Machine Transitions: PLACED $\rightarrow$ ASSIGNED $\rightarrow$ PICKED_UP $\rightarrow$ IN_TRANSIT $\rightarrow$ OUT_FOR_DELIVERY $\rightarrow$ DELIVERED or FAILED $\rightarrow$ RESCHEDULED.
  • Immutable Log History: Every status transition logs timestamp, actor ID, actor role, actor name, GPS coordinates, and remarks.

4. Failed Delivery & Customer Rescheduling

  • 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 RESCHEDULED and triggers automatic fleet reassignment.

5. Multi-Role Portals & 1-Click Interactive Sandbox

  • 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.

Architecture & Tech Stack

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.

Quick Start Guide

Prerequisites

  • Node.js (v18 or v20+)
  • npm (v9+)

Installation & Execution in 3 Easy Steps

  1. Clone the Repository & Install Dependencies:

    npm run install:all
  2. Setup Database & Seed Demo Data:

    cd server
    npx prisma db push
    npm run seed
    cd ..
  3. Start Development Servers (Concurrent Backend + Frontend):

    npm run dev

Demo Credentials

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 Email 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

Rate Calculation Engine Logic

                    ┌──────────────────────────────────────┐
                    │ 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

Auto-Assignment Algorithm

When an order is created or rescheduled, the Assignment Engine:

  1. Queries all active delivery agents (AVAILABLE or ON_DELIVERY).
  2. Calculates the Haversine distance $d_i$ in km from the agent's current coordinates to the pickup location.
  3. 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)$$
  4. Sorts agents ascending by score and auto-assigns the top candidate.

Complete API Reference

Authentication

  • 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 as ADMIN, CUSTOMER, or AGENT.
  • GET /api/auth/me: Get current authenticated user profile.

Rate Cards & Pricing

  • 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.

Zones & Area Mapping

  • 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.

Orders & Tracking

  • 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).

Fleet & Telemetry

  • 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.

Database Schema

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())
}

Testing & Quality Assurance

Run automated unit and integration tests covering the Rate Calculation Engine, Volumetric Weight math, Haversine Distance, and Auto-Assignment scoring:

npm test

Test 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.

Deployment Guide

Deploying Backend to Render / Railway

  1. Set Environment Variables:
    • NODE_ENV=production
    • PORT=5000
    • JWT_SECRET=<your-production-secret>
    • DATABASE_URL="file:./dev.db"
  2. Build Command:
    cd server && npm install && npx prisma db push && npm run seed && npm run build
  3. Start Command:
    cd server && npm start

Deploying Frontend to Vercel

  1. Set Root Directory to client.
  2. Build Command: npm run build
  3. Output Directory: dist
  4. Set Environment Variable: VITE_API_URL=<backend-url>

License

MIT License. Built for Last-Mile Logistics Intelligence.

About

Enterprise Last-Mile Delivery Management Platform with Dynamic Pricing, Spatial Auto-Assignment, and Real-Time Tracking

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages