How pavan3030-pr/roadguardian-ai works
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: App.jsx App shell · services API client · controller Controllers · Accident.java Accident flow
Components 21
Frontend SPA
React client for public, authenticated, and real-time views.
- App shell · Top-level client composition and route wiring.
frontend/src/App.jsx - Pages · Landing, auth, dashboard, incident, reports, admin, and AI pages.
frontend/src/pages - Shared UI · Reusable UI plus live map, notifications, and routing guards.
frontend/src/components - Auth state · JWT/session state and client auth orchestration.
frontend/src/context/AuthContext.jsx - API client · Centralized REST/auth service calls to the backend.
frontend/src/services
Backend API
Spring Boot REST, WebSocket, and domain services.
- Bootstrap · Application entrypoint and runtime wiring.
backend/src/main/java/com/roadguardian/RoadGuardianBackendApplication.java - Controllers · HTTP API surface for auth, incidents, analytics, AI, files, geocoding, health, and tracking.
backend/src/main/java/com/roadguardian/backend/controller - Services · Domain logic, orchestration, and side effects.
backend/src/main/java/com/roadguardian/backend/service - Repositories · JPA repositories for incidents, identity, tracking, notifications, and analytics.
backend/src/main/java/com/roadguardian/backend/repository - Security · Token generation, validation, user details, and request filtering.
backend/src/main/java/com/roadguardian/backend/security - Config · Security, Swagger, Redis, role seeding, and WebSocket setup.
backend/src/main/java/com/roadguardian/backend/config - Errors · 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 · JPA entities plus request/response payloads.
backend/src/main/java/com/roadguardian/backend/model - Accident flow · Primary incident lifecycle from report to update, persistence, and read APIs.
backend/src/main/java/com/roadguardian/backend/model/entity/Accident.java - Identity · Users, roles, tokens, and password reset state.
backend/src/main/java/com/roadguardian/backend/model/entity/User.java - Live tracking · Responder movement, broadcasts, and live state.
backend/src/main/java/com/roadguardian/backend/model/entity/LiveTracking.java - Analytics · Dashboard metrics, event aggregation, and operational reporting.
backend/src/main/java/com/roadguardian/backend/model/entity/AnalyticsEvent.java - Risk scoring · 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 · Versioned schema changes and seed data for PostgreSQL/H2.
backend/src/main/resources/db/migration - Database · Primary persistence store with environment-specific profiles.
backend/src/main/resources/application.properties - Containers · Separate frontend and backend containers for local and deployed runtime.
docker-compose.yml
Connections 24
- 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.