Sanket Frontend Cockpit
DocumentationNext.js 16.3 + React 19

Sanket Frontend Cockpit

Modern operations cockpit engineered for Indian Railways section controllers, station masters, and maintenance engineers with Next.js 16, React 19, Leaflet GIS, and TanStack Query.

Sanket Logo
Live Deployed Production CockpitOnline
https://sanket.aryanshrivastava.dev/
Launch Live App

System Overview & Cockpit Architecture

Sanket is a mission-critical operations cockpit engineered for Indian Railways. Operating dense corridors requires balancing fast-moving high-priority passenger expresses (such as Vande Bharat, Rajdhani, and Shatabdi) with essential civil, electrical (OHE), and signaling maintenance closures.

The frontend bridges real-time timetable operations, infrastructure condition monitoring, and intelligent corridor block allocation to minimize train delays while ensuring timely, safe maintenance.

Mission-Critical UI

High-contrast status pills, dark cockpit theme option, and zero clutter for 24/7 operations control centers.

Optimistic Updates

TanStack Query v5 ensures instant UI feedback on asset edits, defect reporting, and slot reservations.

Zero ML Latency

Communicates directly with the unified Django backend at /railways/ without extra ports.

Technology Stack

LayerSelected TechnologyArchitectural Rationale
Web FrameworkNext.js 16.3 (App Router)Turbopack compilation, React Server Components, Server Actions for mutations.
UI LibraryReact 19.2 + TypeScript 5Modern concurrency, strict type checking for backend API contracts.
Styling SystemTailwind CSS v4Brand theme variables, high performance, mobile touch optimizations.
Data SynchronizationTanStack React Query v5Cache invalidation, polling, and optimistic background revalidation.
Geospatial GISLeaflet & React-LeafletDark Matter CartoDB / Mapbox tiles for rendering live Indian Railways tracks.
Validation & DatesZod + date-fnsStrict runtime schema parsing and IST timezone date transformations.

Project Directory Structure

Organized by domain concern under the src/ folder:

Frontend Directory Map
frontend/
├── public/                     # Static assets, Indian Railways logos, icons
├── src/
│   ├── actions/                # Next.js Server Actions for API mutations
│   │   ├── assets.ts           # Asset CRUD actions
│   │   ├── blocks.ts           # Block window allocation actions
│   │   ├── maintenance.ts      # Maintenance task & plan actions
│   │   ├── schedules.ts        # Train schedule actions
│   │   ├── sections.ts         # Section query actions
│   │   └── trains.ts           # Train fleet actions
│   ├── app/                    # Next.js App Router
│   │   ├── assets/             # Asset management page & skeletons
│   │   ├── maintenance/        # Maintenance planning & approval cockpit
│   │   ├── trains/             # Train operations & timetable page
│   │   ├── globals.css         # Tailwind CSS v4 theme variables
│   │   ├── layout.tsx          # Root layout & query client provider
│   │   └── page.tsx            # Main dashboard with GIS railway map
│   ├── components/
│   │   ├── dashboard/          # Dashboard components & recommendation banners
│   │   ├── map/                # Leaflet India railway map & corridor overlays
│   │   ├── navigation/         # Responsive sidebar & mobile drawer navbar
│   │   ├── notifications/      # Real-time notification drawer & alerts
│   │   ├── route-selector/     # Section & route selector controls
│   │   └── ui/                 # Reusable UI primitives (Dialog, Select, Table, etc.)
│   ├── hooks/                  # TanStack Query custom hooks (useRailwayQueries)
│   ├── lib/                    # Axios client, date parsing, and theme helpers
│   └── types/                  # TypeScript interfaces matching backend models
├── .env.example                # Sample environment configuration
├── ENUMS.md                    # Comprehensive reference of backend choices/enums
├── package.json                # Dependencies and npm scripts
└── tsconfig.json               # TypeScript configuration

1. 🗺️ Corridor GIS & Real-Time Railway Map

Interactive GIS

The centerpiece of the homepage (src/app/page.tsx) is the interactive geospatial map powered by Leaflet and React-Leaflet:

Corridor & Section Dynamic Selector

Section controllers can switch dynamically between divisions (Northern Railway, North Central, West Central, Western Railway) and filter tracks by station pairs (e.g. New Delhi – Mathura, Mathura – Agra, Surat – Mumbai Central).

Visual Corridor Track Occupancy

Renders color-coded polylines representing tracks: Green for Clear / Unoccupied, Amber for Active Maintenance Window, and Red for Train Occupied. Train markers update dynamically as actual movement entry/exit timestamps sync from the backend.

Dark Mode CartoDB Tile Layer

Default tile provider is configured to CartoDB Dark Matter for crisp readability in dim control room environments:

https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png

2. 🚆 Train Operations & Traffic Management (/trains)

Traffic Control

The /trains route handles fleet-wide timetable schedules, running days bitmasks, and real-time movement monitoring:

Multi-Category Fleet Support

Every train category carries an inherent priority level (1–10) utilized by both the UI sorting and the CP-SAT optimizer:

Vande Bharat / Rajdhani / ShatabdiPriority 10
Superfast / Express / MailPriority 6–9
Passenger & Heavy FreightPriority 5

Live Movement Tracking & Delays

Cross-references scheduled entry/exit against actual movements synced by RailKit. Computes positive delay minutes and automatically flags ripple delay threats to maintenance controllers.

3. 🏗️ Infrastructure Asset Management (/assets)

Asset Health

The /assets cockpit provides comprehensive inspection and lifecycle tracking across Indian Railways' three primary infrastructure departments:

ENGINEERING (Civil)

Rails, sleepers, ballast compaction, expansion joints, switches, and bridge structures. Requires heavy mechanized tamper blocks (3–6 hours).

S&T (Signal & Telecom)

Track circuits, point machines, signal units, axle counters, and electronic interlocking systems. Typically scheduled for 45–90 minute windows.

TRACTION (TRD / OHE)

Overhead catenary wires, tension masts, power isolators, and traction substations. Requires track power shutdowns (1–3 hours).

4. 🛠️ Intelligent Maintenance & Block Planning (/maintenance)

Block Optimization

The /maintenance view provides section controllers with an AI-guided block allocation workflow:

AI Recommendation Banner & 1-Click Auto-Apply

When reviewing pending defects or conflicting windows, an intelligent banner displays the CP-SAT recommended collision-free window. Controllers can click "Accept Recommendation" to execute the mutation in a single request:

React Mutation Trigger
// Frontend 1-Click Auto-Apply Trigger
const handleApplyRecommendation = async (blockWindowId: number) => {
  const response = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/block-windows/${blockWindowId}/apply-recommendation/`,
    { method: "POST" }
  );
  if (response.ok) {
    queryClient.invalidateQueries({ queryKey: ["block-windows"] });
    toast.success("Block window rescheduled to optimal collision-free slot!");
  }
};

Maintenance Plan Status Lifecycle

Plan State Machine
[DRAFT] ──> [PENDING_APPROVAL] ──> [APPROVED] ──> [IN_PROGRESS] ──> [COMPLETED]
     │               │                 │
     └──> [CANCELLED] └──> [REJECTED]   └──> [CANCELLED]

7-Day Running Days Bitmask Formulation

Indian Railways train timetables are encoded using a 7-character binary mask representing Monday through Sunday:

"1111111": Daily (Mon–Sun)DAILY
"1111100": Weekdays (Mon–Fri)WEEKDAY
"0000011": Weekends (Sat–Sun)WEEKEND
"1000000": Mondays onlyMON_ONLY

Hydration Safety & Mobile Overlay Isolation

Leaflet relies on browser APIs (window, document) that are unavailable during Next.js server-side rendering (SSR). To eliminate hydration errors:

components/map/RailwayCorridorMap.tsx
// Dynamic import with SSR disabled in Next.js App Router
import dynamic from "next/dynamic";

export const RailwayCorridorMap = dynamic(
  () => import("./LeafletCorridorMap"),
  {
    ssr: false,
    loading: () => <MapHydrationSkeleton />,
  }
);

Backdrop-Filter Stacking Context Fix

On mobile devices, backdrop blur on route selectors could bleed through the navigation drawer. This is solved in globals.css using CSS isolation:

css
.mobile-nav-open [data-mobile-sidebar] {
  z-index: 9999 !important;
  isolation: isolate;
}

Installation & Environment Configuration

Configure .env.local in the frontend root:

frontend/.env.local
# Live Production Deployed Web App:
# https://sanket.aryanshrivastava.dev/

# Local Backend API URLs (Django REST Framework)
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000
NEXT_PUBLIC_API_URL=http://localhost:8000/railways

# Production Backend API (Render Cloud)
# NEXT_PUBLIC_BACKEND_URL=https://backend-oz3h.onrender.com
# NEXT_PUBLIC_API_URL=https://backend-oz3h.onrender.com/railways

# Map Configuration (Optional)
# Leave empty for free CartoDB Dark Matter tiles:
NEXT_PUBLIC_CARTO_API_KEY=
# NEXT_PUBLIC_MAP_TILE_URL=https://api.mapbox.com/styles/v1/mapbox/dark-v11/tiles/{z}/{x}/{y}?access_token=YOUR_TOKEN
Terminal Commands
# 1. Install dependencies
bun install   # or npm install

# 2. Run local development server
bun dev       # or npm run dev

# 3. Production build
bun run build # or npm run build