Skip to content

Arshad-13/TransitOps

Repository files navigation

TransitOps

Smart Transport Operations Platform for fleet, driver, trip, maintenance, fuel, safety, and finance operations.

TransitOps is a role-aware Next.js application built for transport teams that need one place to manage vehicle availability, driver compliance, trip dispatch, maintenance workflows, cost visibility, and operational reports.

Screenshots

The project screenshots are stored in public/img. In the running Next.js app they are served from /img/...; in this README they are referenced with repository-relative paths so they render in GitHub and local Markdown viewers.

Home Login
TransitOps home screen TransitOps login screen
Driver Management Trip Management
Driver management screen Trip management screen
Fuel and Expense Notifications
Fuel and expense screen Notifications screen

Core Features

  • Credential authentication with Auth.js / NextAuth and Prisma-backed user records.
  • Role-based dashboards for Fleet Manager, Driver, Safety Officer, and Financial Analyst.
  • Fleet registry with vehicle search, filters, pagination, detail pages, create/edit/delete flows, and status controls.
  • Driver management with linked user accounts, licensing data, safety score tracking, offboarding, and compliance review.
  • Trip management with map-assisted source/destination selection, OSRM route distance calculation, trip lifecycle controls, pings, and route visualization.
  • Maintenance workflow that automatically moves active maintenance vehicles into IN_SHOP and restores availability when work is closed.
  • Fuel and expense logging for fuel, tolls, and other vehicle costs.
  • Finance dashboard with acquisition cost, fuel cost, maintenance cost, operating cost, estimated revenue, ROI, fuel efficiency, and exportable CSV/PDF reports.
  • Notifications center with unread filtering, date filters, and mark-as-read behavior.
  • Admin panel for fleet managers to view users, update roles, delete users, and review platform stats.
  • Seed data for demo users, fleet records, trips, costs, maintenance logs, and notifications.

Tech Stack

Layer Technology
Framework Next.js 16 App Router
Language TypeScript
UI React 19, Tailwind CSS 4, lucide-react, Recharts
Authentication Auth.js / NextAuth v5 credentials provider
ORM Prisma 5
Database PostgreSQL
Validation Zod
Password hashing bcryptjs
Mapping and routing Leaflet loaded on client screens, OpenStreetMap tiles, Nominatim, OSRM

Getting Started

Install dependencies:

npm install

Create environment variables from the example:

cp .env.example .env

Configure PostgreSQL in .env:

DATABASE_URL="postgresql://postgres:postgres@localhost:5433/odoo_db?schema=public"
DIRECT_URL="postgresql://postgres:postgres@localhost:5433/odoo_db?schema=public"
AUTH_SECRET="replace-with-a-strong-secret"
AUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="replace-with-a-strong-secret"
NEXTAUTH_URL="http://localhost:3000"
NEXT_PUBLIC_APP_URL="http://localhost:3000"

Run Prisma migrations and seed the demo data:

npx prisma migrate dev
npx prisma db seed

Start the development server:

npm run dev

Open http://localhost:3000.

Demo Accounts

Seeded credentials are defined in prisma/seed.ts.

Role Email Password
Fleet Manager manager@transitops.com manager123
Safety Officer safety@transitops.com safety123
Financial Analyst finance@transitops.com finance123
Driver driver1@transitops.com through driver5@transitops.com driver123

Application Architecture

flowchart TB
  subgraph Browser["Browser"]
    PublicPages["Public Pages\nHome, Login, Register"]
    Dashboards["Role Dashboards\nManager, Driver, Safety, Finance"]
    Modules["Operational Modules\nFleet, Drivers, Trips, Maintenance, Fuel, Notifications, Admin"]
    MapClient["Map Client\nOpenStreetMap tiles, Nominatim, OSRM"]
  end

  subgraph NextApp["Next.js 16 App Router"]
    Middleware["Middleware\nRoute protection and admin redirect"]
    Pages["Server and Client Pages\nsrc/app"]
    ApiRoutes["Route Handlers\nsrc/app/api"]
    Auth["Auth.js / NextAuth\nCredentials + JWT session"]
    DomainLibs["Domain Services\nstats, finance summary, state machine, safety score, notifications"]
  end

  subgraph Data["Data Layer"]
    Prisma["Prisma Client"]
    Postgres["PostgreSQL"]
  end

  subgraph External["External Services"]
    OSM["OpenStreetMap Tiles"]
    Nominatim["Nominatim Geocoding"]
    OSRM["OSRM Routing"]
  end

  PublicPages --> Pages
  Dashboards --> Pages
  Modules --> Pages
  Pages --> Middleware
  Pages --> ApiRoutes
  Pages --> Auth
  ApiRoutes --> Auth
  ApiRoutes --> DomainLibs
  DomainLibs --> Prisma
  ApiRoutes --> Prisma
  Auth --> Prisma
  Prisma --> Postgres
  MapClient --> OSM
  MapClient --> Nominatim
  MapClient --> OSRM
Loading

Architecture Notes

  • src/app contains App Router pages, layouts, and route handlers.
  • src/app/api contains REST-style API endpoints implemented as Next.js route handlers.
  • src/auth.ts configures credentials authentication, JWT sessions, Prisma adapter integration, and session enrichment with role/avatar fields.
  • src/middleware.ts protects /dashboard/* and /admin/*, redirects authenticated users away from auth pages, and restricts /admin to fleet managers.
  • src/lib/prisma.ts provides the Prisma client.
  • src/lib/statemachine.ts owns trip and maintenance lifecycle transition rules.
  • src/lib/safetyScore.ts owns the driver safety score event model.
  • src/lib/dashboard-stats.ts computes operations and safety KPIs.
  • src/lib/finance-summary.ts computes finance metrics and builds CSV/PDF exports.
  • src/lib/notifications.ts centralizes notification creation helpers.
  • prisma/schema.prisma defines the domain model and enum constraints.
  • prisma/seed.ts creates demo data and login credentials.

Site Map

Route Access Purpose
/ Public Marketing/home page with entry points to login and registration.
/login Public, redirects if signed in Credential sign-in page.
/register Public, redirects if signed in Self-registration page. New users default to Driver.
/dashboard Authenticated Role-specific dashboard shell: operations, driver, safety, or finance view.
/dashboard/fleet Authenticated roles per sidebar Fleet registry with search, filters, pagination, and delete actions.
/dashboard/fleet/new Fleet Manager Create a vehicle.
/dashboard/fleet/[id] Authenticated Vehicle detail with maintenance and fuel history.
/dashboard/fleet/[id]/edit Fleet Manager Edit vehicle metadata and status.
/dashboard/drivers Fleet Manager, Safety Officer Driver registry, active/offboarded views, compliance data.
/dashboard/drivers/new Fleet Manager, Safety Officer Create driver and linked user account.
/dashboard/drivers/[id] Fleet Manager, Safety Officer Driver profile, trips, stats, offboarding action.
/dashboard/drivers/[id]/edit Fleet Manager, Safety Officer Edit licensing, contact, status, and safety score.
/dashboard/trips Fleet Manager, Driver, Safety Officer Trip list plus map visualization. Drivers see their own trips through the API.
/dashboard/trips/new Fleet Manager Create trip with map selection, address search, route distance, available vehicle and driver lists.
/dashboard/trips/[id] Fleet Manager, assigned Driver, Safety Officer view via list access Trip detail, route map, lifecycle actions, tracking pings.
/dashboard/maintenance Fleet Manager, Safety Officer Maintenance log list and close/delete actions.
/dashboard/maintenance/new Fleet Manager Create active or closed maintenance record.
/dashboard/fuel Fleet Manager, Driver, Financial Analyst Fuel and expense list, cost summaries, filters.
/dashboard/fuel/new Fleet Manager, Driver Create fuel, toll, or other expense log.
/dashboard/notifications Authenticated Notification inbox with filters and mark-as-read actions.
/profile/edit Authenticated Update display name, avatar URL, and password.
/profile/[id] Public API-backed page Public user profile view.
/admin Fleet Manager User administration, role updates, delete user, platform stats.

Role Model

Role Primary Capabilities
FLEET_MANAGER Full operations control: fleet CRUD, trip creation/dispatch/cancel/delete, maintenance management, fuel management, admin panel, reports.
DRIVER Driver dashboard, own trip visibility, trip completion, tracking pings, fuel/expense creation, notifications, profile.
SAFETY_OFFICER Safety dashboard, driver compliance management, fleet visibility, maintenance visibility, trip visibility, notifications.
FINANCIAL_ANALYST Finance dashboard, reports, fleet/fuel visibility, export workflows, notifications.

Domain Model

erDiagram
  User ||--o| Driver : "may have"
  User ||--o{ Trip : "creates"
  User ||--o{ Notification : "receives"
  Driver ||--o{ Trip : "assigned"
  Vehicle ||--o{ Trip : "assigned"
  Vehicle ||--o{ MaintenanceLog : "has"
  Vehicle ||--o{ FuelLog : "has"
  Trip ||--o{ TrackingPing : "records"

  User {
    string id
    string email
    string passwordHash
    Role role
    string avatarUrl
  }

  Driver {
    string id
    string userId
    string licenseNumber
    datetime licenseExpiryDate
    float safetyScore
    DriverStatus status
    boolean isActive
  }

  Vehicle {
    string id
    string registrationNumber
    string nameModel
    string type
    float maxLoadCapacity
    float odometer
    float acquisitionCost
    VehicleStatus status
    string region
  }

  Trip {
    string id
    string sourceAddress
    string destinationAddress
    float plannedDistanceKm
    float cargoWeightKg
    TripStatus status
    boolean deviationFlag
  }

  MaintenanceLog {
    string id
    string vehicleId
    string type
    float cost
    MaintStatus status
    float predictedRiskScore
  }

  FuelLog {
    string id
    string vehicleId
    float liters
    float cost
    ExpenseType expenseType
    boolean anomalyFlag
  }

  TrackingPing {
    string id
    string tripId
    float lat
    float lng
    datetime timestamp
  }

  Notification {
    string id
    string userId
    string type
    string message
    string link
    boolean read
  }
Loading

Business Rules

  • Vehicle registration numbers are unique.
  • Driver license numbers are unique.
  • Only fleet managers can create, edit, and delete vehicles.
  • Only fleet managers and safety officers can create and edit driver records.
  • Driver delete is implemented as offboarding; trip history is preserved.
  • Drivers currently ON_TRIP cannot be offboarded.
  • Only fleet managers can create trips.
  • Trip cargo weight cannot exceed selected vehicle capacity.
  • Trip dispatch requires an available vehicle and an available driver.
  • Trip dispatch blocks expired-license drivers.
  • Trip dispatch moves vehicle and driver to ON_TRIP.
  • Trip completion requires a final odometer reading greater than or equal to the current vehicle odometer.
  • Trip completion restores vehicle and driver to AVAILABLE, updates vehicle odometer, and applies safety score events.
  • Trip cancellation requires a reason and restores locked vehicle/driver resources if the trip was dispatched.
  • Only DRAFT trips can be deleted.
  • Creating active maintenance moves the vehicle to IN_SHOP.
  • Closing the last active maintenance record restores the vehicle to AVAILABLE if it is not otherwise retired.
  • Tracking pings can only be recorded for DISPATCHED trips.

Endpoint Catalog

All endpoints are implemented under src/app/api.

Authentication

Method Endpoint Auth Description
POST /api/auth/register Public Register a new user as DRIVER.
GET/POST /api/auth/[...nextauth] Public/Auth.js Auth.js handlers for sign-in, session, and auth callbacks.

Admin

Method Endpoint Auth Description
GET /api/admin/stats Fleet Manager Return total users, vehicles, drivers, and active maintenance count.
GET /api/admin/users Fleet Manager List users with role, email, avatar, and creation date.
PATCH /api/admin/users/[id] Fleet Manager Update a user's role. Cannot update own role.
DELETE /api/admin/users/[id] Fleet Manager Delete a user. Cannot delete self.

Dashboard and Finance

Method Endpoint Auth Query Description
GET /api/dashboard/stats Authenticated type, status, region Operations KPIs, vehicle status counts, driver counts, trip counts, maintenance counts.
GET /api/finance/summary Authenticated None Compact finance summary used by legacy/alternate finance widgets.
GET /api/reports/summary Authenticated type, status, region Full finance report data including cost, ROI, utilization, fuel efficiency, highlights, and breakdowns.
GET /api/reports/export Authenticated type, status, region, format=csv|pdf Export finance report as CSV or PDF.
GET /api/costs Public in current code vehicleId Compute fuel, toll, other, maintenance, and total cost per vehicle.

Vehicles

Method Endpoint Auth Query/Body Description
GET /api/vehicles Authenticated search, type, status, region, page, limit Paginated vehicle registry with filters.
POST /api/vehicles Fleet Manager Vehicle create body Create a vehicle after validating uniqueness and required fields.
GET /api/vehicles/[id] Public in current code Path id Get vehicle detail with maintenance and fuel logs.
PATCH /api/vehicles/[id] Fleet Manager Partial vehicle update body Update vehicle fields with registration uniqueness and maintenance status guard.
DELETE /api/vehicles/[id] Fleet Manager Path id Delete a vehicle.

Drivers

Method Endpoint Auth Query/Body Description
GET /api/drivers Authenticated search, status, tab=active|offboarded, page, limit Paginated driver registry with linked user and trip counts.
POST /api/drivers Fleet Manager, Safety Officer Driver create body Create a driver and linked user account, or link an existing user.
GET /api/drivers/me Authenticated None Return the current user's driver profile and latest trips.
GET /api/drivers/[id] Public in current code Path id Get driver profile, user info, recent trips, and stats.
PATCH /api/drivers/[id] Fleet Manager, Safety Officer Partial driver update body Update driver/user fields, status, license data, safety score, or score event.
DELETE /api/drivers/[id] Fleet Manager Path id Soft-offboard a driver unless currently on trip.

Trips and Tracking

Method Endpoint Auth Query/Body Description
GET /api/trips Authenticated status, driverId, vehicleId, page, limit Paginated trips. Drivers are scoped to their own driver record.
POST /api/trips Fleet Manager Trip create body Create a DRAFT trip after validating vehicle capacity.
GET /api/trips/[id] Authenticated Path id Get trip detail. Drivers can only view assigned trips.
PATCH /api/trips/[id] Fleet Manager, assigned Driver { status, finalOdometer, fuelConsumed, cancellationReason, deviationFlag } Transition trip state and apply related resource/status changes. Drivers can only complete assigned trips.
DELETE /api/trips/[id] Fleet Manager Path id Delete a DRAFT trip.
GET /api/trips/[id]/pings Authenticated Path id List tracking pings for a trip. Drivers can only read assigned trip pings.
POST /api/trips/[id]/pings Authenticated { lat, lng } Record a tracking ping for a dispatched trip and update vehicle last-known location.

Maintenance

Method Endpoint Auth Query/Body Description
GET /api/maintenance Public in current code vehicleId, status, page, limit Paginated maintenance logs with vehicle summary.
POST /api/maintenance Fleet Manager Maintenance create body Create maintenance log; active logs move vehicle to IN_SHOP.
GET /api/maintenance/[id] Public in current code Path id Get one maintenance record.
PATCH /api/maintenance/[id] Fleet Manager Partial maintenance update body Update maintenance data and close active maintenance using lifecycle validation.
DELETE /api/maintenance/[id] Fleet Manager Path id Delete maintenance record and restore vehicle availability when appropriate.

Fuel and Expenses

Method Endpoint Auth Query/Body Description
GET /api/fuel-logs Public in current code vehicleId, expenseType, page, limit Paginated fuel/expense logs with vehicle summary.
POST /api/fuel-logs Fleet Manager, Driver Fuel/expense create body Create fuel, toll, or other expense. Fuel entries require liters greater than zero.
GET /api/fuel-logs/[id] Public in current code Path id Get one fuel/expense log.
PATCH /api/fuel-logs/[id] Fleet Manager Partial fuel/expense update body Update expense type, liters, cost, or date.
DELETE /api/fuel-logs/[id] Fleet Manager Path id Delete a fuel/expense log.

Notifications and Profiles

Method Endpoint Auth Query/Body Description
GET /api/notifications Authenticated type, read, from, to, page, limit List notifications for the signed-in user.
POST /api/notifications Authenticated { type, message, link, targetRole? } Create a notification for self or for all users in a target role.
PATCH /api/notifications/[id]/read Notification owner Path id Mark a notification as read.
PUT /api/profile Authenticated { name?, avatarUrl?, password? } Update signed-in user's profile.
GET /api/profile/[id] Public in current code Path id Get public profile fields and linked driver record.

Key Workflows

Trip Lifecycle

stateDiagram-v2
  [*] --> DRAFT
  DRAFT --> DISPATCHED: Fleet Manager dispatches
  DRAFT --> CANCELLED: Fleet Manager cancels
  DISPATCHED --> COMPLETED: Fleet Manager or assigned Driver completes
  DISPATCHED --> CANCELLED: Fleet Manager cancels
  COMPLETED --> [*]
  CANCELLED --> [*]
Loading

Maintenance Lifecycle

stateDiagram-v2
  [*] --> ACTIVE
  ACTIVE --> CLOSED: Fleet Manager closes work order
  CLOSED --> [*]
Loading

Dispatch Side Effects

sequenceDiagram
  actor Manager as Fleet Manager
  participant UI as Trip UI
  participant API as /api/trips/[id]
  participant DB as PostgreSQL via Prisma
  participant Notify as Notifications

  Manager->>UI: Dispatch draft trip
  UI->>API: PATCH status=DISPATCHED
  API->>DB: Validate trip transition
  API->>DB: Check driver AVAILABLE and license valid
  API->>DB: Check vehicle AVAILABLE
  API->>DB: Update trip, driver, vehicle in transaction
  API->>Notify: Create driver notification
  API-->>UI: Updated dispatched trip
Loading

Project Structure

.
|-- docs/
|-- prisma/
|   |-- migrations/
|   |-- schema.prisma
|   `-- seed.ts
|-- public/
|   `-- img/
|-- scripts/
|-- src/
|   |-- app/
|   |   |-- api/
|   |   |-- dashboard/
|   |   |-- login/
|   |   |-- register/
|   |   `-- profile/
|   |-- components/
|   |-- lib/
|   |-- types/
|   |-- auth.ts
|   `-- middleware.ts
|-- package.json
|-- next.config.ts
|-- tsconfig.json
`-- README.md

Development Commands

Command Purpose
npm run dev Start the Next.js development server.
npm run build Build the production app.
npm run start Start the production server after build.
npm run lint Run ESLint.
npx prisma migrate dev Apply migrations locally and regenerate Prisma client.
npx prisma db seed Seed demo data.
npx prisma studio Open Prisma Studio for database inspection.

Architecture Plan

Current State

TransitOps is implemented as a monolithic Next.js application with colocated UI routes and API route handlers. Business logic is split between route handlers and shared library modules. PostgreSQL is the source of truth, Prisma enforces schema-level relationships, and Zod handles request validation.

Recommended Near-Term Improvements

  • Add authentication checks to read endpoints currently marked public in this README, such as vehicle detail, driver detail, maintenance reads, fuel-log reads, costs, and public profile reads if those should not be externally visible.
  • Consolidate repeated auth/role/error handling by moving more endpoints to the createApiRoute helper.
  • Add route-handler tests for business rules: dispatch blocking, maintenance status restoration, trip completion odometer validation, and driver offboarding.
  • Add database indexes for frequently filtered fields: vehicle status, type, region; trip status, driverId, vehicleId; notification userId/read/createdAt.
  • Store route geometry from OSRM in Trip.routePolyline during trip creation so trip detail pages can render persisted planned routes.
  • Add a scheduled notification job for license expiry and maintenance due alerts.
  • Add audit logs for role changes, trip transitions, vehicle status changes, and driver safety score changes.

Future Architecture Direction

flowchart LR
  UI["Next.js Web App"] --> API["Next.js API Layer"]
  API --> Services["Domain Service Layer"]
  Services --> DB["PostgreSQL"]
  Services --> Jobs["Background Jobs\nLicense expiry, maintenance due, anomaly scans"]
  Services --> Audit["Audit Log"]
  Jobs --> Notify["Notification Service"]
  API --> Maps["Map/Routing Adapter\nNominatim + OSRM"]
  Services --> Reports["Report Builder\nCSV + PDF"]
Loading

The next clean architecture step is to move business workflows into explicit domain services and keep route handlers thin. This makes the lifecycle rules testable outside HTTP and prepares the project for background jobs, audit trails, and richer analytics.

Security Notes

  • Passwords are hashed with bcrypt before storage.
  • Auth sessions use JWT strategy and include role metadata.
  • Middleware protects primary app routes.
  • Admin UI and admin APIs are restricted to FLEET_MANAGER.
  • Several read endpoints currently do not call auth(); review the endpoint catalog before production deployment and lock down reads according to product requirements.

License

Private project. Add a license before public distribution.

About

Smart Transport Operations Platform for fleet, driver, trip, maintenance, fuel, safety, and finance operations.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages