# TrackerVeh Project Documentation

## Architecture Overview

TrackerVeh is a C++ web application built with the **Drogon framework**.
The application uses **CSP (C++ Server Pages)** for dynamic HTML view rendering, and connects directly to a **MySQL/MariaDB** database via Drogon's ORM and asynchronous SQL interfaces.

### Core Stack
- **Backend:** C++ (C++20) + Drogon Web Framework
- **Frontend:** HTML, Vanilla CSS, Vanilla JavaScript
- **Mapping:** Leaflet.js (integrated dynamically)
- **Database:** MySQL
- **Build System:** CMake

## Routing & Controllers

All core pages and authentication endpoints are managed by `WebController` (`controllers/WebController.cc`). Custom API endpoints (if any) reside in `AppController`.

### Routes Summary
- `GET /login` : Displays the login form
- `POST /login` : Authenticates user credentials against the `Agents` table.
- `GET /` : Home page. Displays user greeting and dashboard.
- `GET /agents` : Re-routes agents. For admins, lists all agents in the system and provides an interface to edit and add agents.
- `GET /trackers` : Lists all trackers. For agents, it only shows trackers that match their `sector_id`.
- `GET /map` : A full-screen geographical visualization utilizing Leaflet to draw path histories of all accessible trackers.
- `GET /logout` : Clears the current session.

*(Admin Only POST endpoints)*
- `POST /agents/add` : Creates a new agent.
- `POST /agents/update` : Edits an existing agent properties.
- `POST /trackers/add` : Creates a new tracker.
- `POST /trackers/update` : Edits an existing tracker properties.

## Database Schema Highlights

The database interface and configuration definition can be found in `services/dbControllService.cc` and `include/Constants.h`.

1. **Agents:** Stores user credentials. Key fields: `login`, `password_hash`, `role` (either `agent` or `admin`), `sector_id`.
2. **Trackers:** Stores individual tracker details. Key fields: `serial_number`, `status`, `sector_id`.
3. **Point_History:** Captures chronological geographical points generated by tracking hardware. Key fields: `tracker_id`, `timestamp`, `latitude`, `longitude`.

## Roles & Permissions

The platform supports two explicit roles:
1. **admin**: Can view, edit, and create tracking devices and user agents. Has access to the `/agents` route. Sees map markers for *all* sectors.
2. **agent**: Can only *view* trackers. Has restricted access to the map and tracker lists, only viewing trackers where the tracker's `sector_id` matches the configured `sector_id` of the logged-in agent.

## Map Visualization (Leaflet)

The maps utilize the Leaflet library. 
To pass history data from the database securely to JS:
- `WebController` directly queries `Point_History`, ordering geographically coordinate points by `timestamp` ascending.
- Points are clustered by `tracker_id`, transformed into a JSON structure (`{"tracker_id": [[lat1, lng1], [lat2, lng2]]}`) and passed to the frontend views via `HttpViewData`.
- JavaScript parses this JSON to generate continuous `L.polyline` routes and a `L.circleMarker` terminating at the final recorded location. Bounds are dynamically recalculated via `map.fitBounds()` to ensure the entire route is framed elegantly on screen.

## REST API Endpoints

The Drogon backend exposes REST API endpoints located in `AppController.cc` returning `JSON` data. This is built primarily to support the external mobile/desktop Agent Application. The API relies on standard session cookies (`JSESSIONID`) acquired upon successful login.

### 1. Authentication
**`POST /api/auth/login`**
- **Payload (`application/json`)**: `{"userId": "agent", "password": "123"}`
- **Success Response**: `{"status": "success", "role": "agent", "sectorId": "1", "userName": "Agent Smith"}`
- *Note: On success, Drogon writes the `JSESSIONID` cookie to the client header. Further requests must supply this cookie.*

**`GET /api/auth/status`**
- **Description**: Utility to check active session validity.
- **Success Response**: `{"status": "success", "role": "agent", "sectorId": "1", "userName": "Agent Smith"}`

**`POST /api/auth/logout`** (Також працює через GET)
- **Description**: Clears the active authentication session.
- **Success Response**: `{"status": "success", "message": "Logged out successfully"}`

### 2. General Data
**`GET /api/trackers`**
- **Description**: Retrieves trackers. Crucially, the controller filters output automatically according to the user's role (Agents merely receive trackers in their bounded `sectorId`). 
- **Response Format**: 
  ```json
  {
    "status": "success",
    "data": [
      {
        "trackerId": "1",
        "serialNumber": "TRK-2024",
        "sectorId": "1",
        "status": "active",
        "rentalStart": "...",
        "rentalEnd": "",
        "history": [
          {"timestamp": "2026-04-19 10:00:00", "lat": 47.37, "lng": 8.54, "alt": 400.0}
        ]
      }
    ]
  }
  ```

## Compilation and Execution

To rebuild and start the server natively:
```bash
cmake -B build
cmake --build build
cd build && ./TrackerVeh
```
