# pavan3030-pr/roadguardian-ai architecture

> Architecture diagram of the GitHub repository pavan3030-pr/roadguardian-ai, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-31). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/pavan3030-pr/roadguardian-ai
- Repository: https://github.com/pavan3030-pr/roadguardian-ai

## Overview

1. **Overall shape**
   - This is a two-part system: a **React single-page app** in `frontend/` and a **Spring Boot backend API** in `backend/`.
   - The backend is the system of record for incidents, users, analytics, notifications, and live tracking state. The frontend is a thin client that consumes REST and WebSocket APIs.

2. **Frontend boundary**
   - The frontend is organized around **pages**, **shared UI components**, **auth context**, and **service wrappers**.
   - `src/services/api.js` and `src/services/auth.js` centralize HTTP calls, while `AuthContext.jsx` holds JWT/session state.
   - Core pages include landing, login/register/reset flows, a public dashboard, incident details, reports, admin dashboard, and an AI vision page. `PrivateRoute.jsx` enforces client-side access control for protected views.

3. **Backend layer structure**
   - The backend follows a standard layered Spring architecture:
     - **controllers** expose REST endpoints
     - **services** implement business rules
     - **repositories** persist to the database
     - **model/entity** contains JPA entities
     - **model/dto** carries request/response payloads
     - **security** handles JWT auth
     - **config** wires infrastructure like Redis, Swagger, security, and WebSockets
     - **exception** provides centralized error mapping
   - This separation is important because the actual domain logic is concentrated in services, not controllers.

4. **Primary business domain**
   - The central domain is **road accident incident management**.
   - Key entities include `Accident`, `User`, `Role`, `EmergencyResponse`, `LiveTracking`, `Notification`, `AIRecommendation`, `AnalyticsEvent`, `RefreshToken`, and `PasswordResetToken`.
   - The `Accident` workflow is the main backbone: public report, risk scoring, dispatch coordination, tracking, analytics, and notifications.

5. **Request flow for incidents**
   - A typical incident flow is:
     - frontend submits a report or update
     - backend controller validates the request DTO
     - service layer applies rules, stores entities, and may create related records
     - repositories persist to PostgreSQL/H2
     - optional side effects include AI scoring, notifications, and WebSocket updates
   - Reads for accidents are intentionally public according to the README, while writes are mostly authenticated except for a few public submission/upload endpoints.

6. **Security and identity boundary**
   - Authentication is JWT-based with **access and refresh tokens**.
   - `SecurityConfig`, `JwtAuthenticationFilter`, `JwtTokenProvider`, and `CustomUserDetailsService` implement the auth boundary.
   - Roles are seeded by `RoleDataInitializer` and include `USER`, `POLICE`, `HOSPITAL`, `AMBULANCE`, and `ADMIN`.
   - This role model drives what each responder type can see or do in the dashboard.

7. **Real-time subsystem**
   - Live coordination uses **Spring WebSocket + STOMP** via `WebSocketConfig`.
   - `LiveTrackingController` and `LiveTrackingService` manage responder movement simulation and broadcast updates.
   - On the frontend, `LiveMap.jsx` and `NotificationCenter.jsx` are the main consumers of real-time state.
   - This subsystem is separate from REST CRUD because it pushes updates asynchronously to connected clients.

8. **Analytics and operational views**
   - `AnalyticsController` and `AnalyticsService` aggregate incident counts, severity breakdowns, and response trends into dashboard-friendly responses.
   - The corresponding DTOs such as `DashboardMetricsResponse` and `PageResponse` indicate that the backend shapes data specifically for UI consumption rather than exposing raw entities.
   - `AnalyticsEvent` persists events used for reporting and trend calculations.

9. **AI / risk scoring subsystem**
   - `AIRiskEngineServiceImpl` is a **rule-based heuristic engine**, not ML.
   - It scores incidents from severity, casualties, weather, traffic density, road type, and peak-hour timing, then returns recommendations.
   - `AIController` exposes these risk-analysis endpoints, and `AIRecommendation` stores results.
   - The README explicitly says image analysis is heuristic only, so this subsystem should be drawn as deterministic rules, not model inference.

10. **External integrations**
   - **Geocoding** is proxied through a `GeocodingController`, likely wrapping OpenStreetMap Nominatim.
   - **Email** exists through `EmailService`, but is disabled unless configured.
   - **File handling** is managed by `FileStorageService` and `FileController`, covering uploaded images/videos and serving stored files back to clients.
   - These are side integrations rather than the core source of truth.

11. **Persistence and migration model**
   - The main production store is **PostgreSQL**; the dev profile can use **H2**.
   - **Flyway** migrations in `backend/src/main/resources/db/migration/` define schema evolution and seed data.
   - The migration history shows the data model evolved over time to normalize coordinates, add soft delete, support password reset, live tracking, and AI recommendation fields.
   - `RedisConfig` suggests optional Redis support, with fallback to in-memory behavior if unavailable.

12. **Deployment/runtime boundaries**
   - The repo supports both local development and containerized deployment.
   - `docker-compose.yml`, `backend/Dockerfile`, and `frontend/Dockerfile` indicate the system can be run as separate backend and frontend containers.
   - The README says frontend is served behind **Nginx** in Docker, while the backend listens on port 8080.
   - Vite dev server proxies `/api` to the backend during local development.

13. **API surface**
   - The backend API is grouped into clear endpoint families: auth, accidents, AI, analytics, tracking, geocoding, file uploads, and health.
   - Swagger/OpenAPI is configured through `SwaggerConfig`, making the backend’s contract discoverable.
   - The API design is mixed: some endpoints are public for reporting and reads, while operational actions require bearer-token authentication.

14. **Operational quality and testing**
   - Global error handling is centralized in `GlobalExceptionHandler`, which maps application exceptions into consistent response bodies.
   - Tests exist for at least the backend application startup, the accident controller, and the AI risk engine, indicating unit-level coverage around the most important domain logic.
   - Overall, the architecture is a conventional layered backend plus SPA frontend, with real-time WebSocket updates as the main non-CRUD subsystem.

Main entry points: [`frontend/src/App.jsx`](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/frontend/src/App.jsx) (App shell), [`frontend/src/services`](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/services) (API client), [`backend/src/main/java/com/roadguardian/backend/controller`](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/controller) (Controllers), [`backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java`](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java) (Accident flow)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend SPA"]
  node_frontend_app["App shell<br/>React SPA<br/>[App.jsx]"]
  node_frontend_pages["Pages<br/>Views"]
  node_frontend_components["Shared UI<br/>Components"]
  node_frontend_auth(("Auth state<br/>Context<br/>[AuthContext.jsx]"))
  node_frontend_services["API client<br/>HTTP wrappers"]
end

subgraph group_backend_api["Backend API"]
  node_backend_bootstrap(("Bootstrap<br/>Spring Boot"))
  node_backend_controllers["Controllers<br/>REST endpoints"]
  node_backend_services["Services<br/>Business rules"]
  node_backend_repos[("Repositories<br/>Persistence")]
  node_security_boundary["Security<br/>JWT auth"]
  node_infra_config["Config<br/>Infrastructure wiring"]
  node_error_boundary["Errors<br/>Exception mapping"]
end

subgraph group_domain["Core Domain"]
  node_backend_models["Models<br/>Entities and DTOs"]
  node_incident_core{{"Accident flow<br/>Incident domain<br/>[Accident.java]"}}
  node_identity_core{{"Identity<br/>Auth domain<br/>[User.java]"}}
  node_tracking_core{{"Live tracking<br/>Realtime domain<br/>[LiveTracking.java]"}}
  node_analytics_core{{"Analytics<br/>Metrics domain"}}
  node_ai_core{{"Risk scoring<br/>Heuristic AI"}}
end

subgraph group_runtime["Deployment"]
  node_migration_store["Flyway migrations<br/>Schema evolution"]
  node_db_runtime[("Database<br/>PostgreSQL/H2")]
  node_container_runtime["Containers<br/>Docker/Nginx<br/>[docker-compose.yml]"]
end

node_frontend_app -->|"renders"| node_frontend_pages
node_frontend_app -->|"uses"| node_frontend_components
node_frontend_app -->|"reads auth"| node_frontend_auth
node_frontend_pages -->|"calls API"| node_frontend_services
node_frontend_pages -->|"composes"| node_frontend_components
node_frontend_components -->|"fetches"| node_frontend_services
node_frontend_auth -->|"auth calls"| node_frontend_services
node_frontend_services -->|"HTTP"| node_backend_controllers
node_backend_bootstrap -->|"loads"| node_infra_config
node_backend_controllers -->|"delegates"| node_backend_services
node_backend_services -->|"persists"| node_backend_repos
node_backend_services -->|"uses DTOs/entities"| node_backend_models
node_backend_repos -->|"stores"| node_db_runtime
node_incident_core -->|"feeds"| node_analytics_core
node_incident_core -->|"updates"| node_tracking_core
node_incident_core -->|"scores"| node_ai_core
node_identity_core -->|"authenticates"| node_security_boundary
node_security_boundary -->|"guards"| node_backend_controllers
node_infra_config -->|"configures"| node_security_boundary
node_infra_config -->|"enables websocket"| node_tracking_core
node_error_boundary -->|"handles failures"| node_backend_controllers
node_migration_store -->|"evolves schema"| node_db_runtime
node_container_runtime -.->|"serves"| node_frontend_app
node_container_runtime -.->|"runs"| node_backend_bootstrap

click node_frontend_app "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/frontend/src/App.jsx"
click node_frontend_pages "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/pages"
click node_frontend_components "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/components"
click node_frontend_auth "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/frontend/src/context/AuthContext.jsx"
click node_frontend_services "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/services"
click node_backend_bootstrap "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/RoadGuardianBackendApplication.java"
click node_backend_controllers "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/controller"
click node_backend_services "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/service"
click node_backend_repos "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/repository"
click node_backend_models "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/model"
click node_incident_core "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java"
click node_identity_core "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/User.java"
click node_tracking_core "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/LiveTracking.java"
click node_analytics_core "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/AnalyticsEvent.java"
click node_ai_core "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/service/impl/AIRiskEngineServiceImpl.java"
click node_security_boundary "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/security"
click node_infra_config "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/config"
click node_error_boundary "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/exception"
click node_migration_store "https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/resources/db/migration"
click node_db_runtime "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/resources/application.properties"
click node_container_runtime "https://github.com/pavan3030-pr/roadguardian-ai/blob/main/docker-compose.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend_app,node_frontend_pages,node_frontend_components,node_frontend_auth,node_frontend_services toneBlue
class node_backend_bootstrap,node_backend_controllers,node_backend_services,node_backend_repos,node_security_boundary,node_infra_config,node_error_boundary toneAmber
class node_backend_models,node_incident_core,node_identity_core,node_tracking_core,node_analytics_core,node_ai_core toneMint
class node_migration_store,node_db_runtime,node_container_runtime toneRose
```

## Components

### Frontend SPA

React client for public, authenticated, and real-time views.

- [App shell](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/frontend/src/App.jsx): React SPA · Top-level client composition and route wiring. · `frontend/src/App.jsx`
- [Pages](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/pages): Views · Landing, auth, dashboard, incident, reports, admin, and AI pages. · `frontend/src/pages`
- [Shared UI](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/components): Components · Reusable UI plus live map, notifications, and routing guards. · `frontend/src/components`
- [Auth state](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/frontend/src/context/AuthContext.jsx): Context · JWT/session state and client auth orchestration. · `frontend/src/context/AuthContext.jsx`
- [API client](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/frontend/src/services): HTTP wrappers · Centralized REST/auth service calls to the backend. · `frontend/src/services`

### Backend API

Spring Boot REST, WebSocket, and domain services.

- [Bootstrap](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/RoadGuardianBackendApplication.java): Spring Boot · Application entrypoint and runtime wiring. · `backend/src/main/java/com/roadguardian/RoadGuardianBackendApplication.java`
- [Controllers](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/controller): REST endpoints · HTTP API surface for auth, incidents, analytics, AI, files, geocoding, health, and tracking. · `backend/src/main/java/com/roadguardian/backend/controller`
- [Services](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/service): Business rules · Domain logic, orchestration, and side effects. · `backend/src/main/java/com/roadguardian/backend/service`
- [Repositories](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/repository): Persistence · JPA repositories for incidents, identity, tracking, notifications, and analytics. · `backend/src/main/java/com/roadguardian/backend/repository`
- [Security](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/security): JWT auth · Token generation, validation, user details, and request filtering. · `backend/src/main/java/com/roadguardian/backend/security`
- [Config](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/config): Infrastructure wiring · Security, Swagger, Redis, role seeding, and WebSocket setup. · `backend/src/main/java/com/roadguardian/backend/config`
- [Errors](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/exception): Exception mapping · Centralized application exception handling and error responses. · `backend/src/main/java/com/roadguardian/backend/exception`

### Core Domain

Incident, identity, analytics, tracking, and AI state.

- [Models](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/java/com/roadguardian/backend/model): Entities and DTOs · JPA entities plus request/response payloads. · `backend/src/main/java/com/roadguardian/backend/model`
- [Accident flow](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java): Incident domain · Primary incident lifecycle from report to update, persistence, and read APIs. · `backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java`
- [Identity](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/User.java): Auth domain · Users, roles, tokens, and password reset state. · `backend/src/main/java/com/roadguardian/backend/model/entity/User.java`
- [Live tracking](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/LiveTracking.java): Realtime domain · Responder movement, broadcasts, and live state. · `backend/src/main/java/com/roadguardian/backend/model/entity/LiveTracking.java`
- [Analytics](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/model/entity/AnalyticsEvent.java): Metrics domain · Dashboard metrics, event aggregation, and operational reporting. · `backend/src/main/java/com/roadguardian/backend/model/entity/AnalyticsEvent.java`
- [Risk scoring](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/java/com/roadguardian/backend/service/impl/AIRiskEngineServiceImpl.java): Heuristic AI · Rule-based incident scoring and recommendations. · `backend/src/main/java/com/roadguardian/backend/service/impl/AIRiskEngineServiceImpl.java`

### Deployment

Containerized runtime, database, and migration boundaries.

- [Flyway migrations](https://github.com/pavan3030-pr/roadguardian-ai/tree/main/backend/src/main/resources/db/migration): Schema evolution · Versioned schema changes and seed data for PostgreSQL/H2. · `backend/src/main/resources/db/migration`
- [Database](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/backend/src/main/resources/application.properties): PostgreSQL/H2 · Primary persistence store with environment-specific profiles. · `backend/src/main/resources/application.properties`
- [Containers](https://github.com/pavan3030-pr/roadguardian-ai/blob/main/docker-compose.yml): Docker/Nginx · Separate frontend and backend containers for local and deployed runtime. · `docker-compose.yml`

## Connections

- App shell → Pages: renders · App shell routes into page views.
- App shell → Shared UI: uses · Shared UI and route guards are composed into the app.
- App shell → Auth state: reads auth · Client shell depends on session state and protected routing.
- Pages → API client: calls API · Pages consume REST wrappers for backend data.
- Pages → Shared UI: composes · Pages use reusable UI, live map, and notification components.
- Shared UI → API client: fetches · Live and notification UI may poll or subscribe through service wrappers.
- Auth state → API client: auth calls · Login, register, reset, and token-aware requests go through service wrappers.
- API client → Controllers: HTTP · Frontend talks to the backend REST API.
- Bootstrap → Config: loads · Application startup wires infrastructure configuration.
- Controllers → Services: delegates · Controllers validate input and hand off to services.
- Services → Repositories: persists · Services coordinate repository access.
- Services → Models: uses DTOs/entities · Business logic operates on entities and shaped payloads.
- Repositories → Database: stores · Repositories persist to the database.
- Accident flow → Analytics: feeds · Incident activity contributes to metrics and reporting.
- Accident flow → Live tracking: updates · Incident workflow drives live coordination state.
- Accident flow → Risk scoring: scores · Accident attributes are evaluated by the risk engine.
- Identity → Security: authenticates · Users, roles, and tokens underpin JWT security.
- Security → Controllers: guards · Authentication and authorization filter incoming requests.
- Config → Security: configures · Security setup is assembled from configuration classes.
- Config → Live tracking: enables websocket · WebSocket/STOMP config supports live updates.
- Errors → Controllers: handles failures · Exceptions are mapped to consistent API responses.
- Flyway migrations → Database: evolves schema · Flyway defines database structure and seed data.
- Containers → App shell: serves · Frontend is packaged for containerized delivery.
- Containers → Bootstrap: runs · Backend is deployed as a separate service container.
