# Tổng quan hệ thống


Source: https://docs.fleetwork.vn/sdk/tracking-summary

> Tài liệu mô tả tổng quan luồng hoạt động của hệ thống GPS Tracking: từ thiết bị di động gửi dữ liệu lên server, đến việc hiển thị dashboard và xuất báo cáo.

---

## Mục lục

1. [Tổng quan hệ thống](#1-tổng-quan-hệ-thống)
2. [Kiến trúc tổng quan](#2-kiến-trúc-tổng-quan)
3. [Luồng tracking end-to-end](#3-luồng-tracking-end-to-end)
4. [Authentication](#4-authentication)
5. [Quick Start](#5-quick-start)
6. [Tài liệu chi tiết](#6-tài-liệu-chi-tiết)

---

## 1. Tổng quan hệ thống

Fleetwork GPS Tracking là hệ thống theo dõi hành trình thời gian thực dành cho đội xe và nhân viên di động. Hệ thống gồm 3 thành phần chính:

| Thành phần                           | Mô tả                                                            | Tài liệu                                 |
| ------------------------------------ | ---------------------------------------------------------------- | ---------------------------------------- |
| **Flutter SDK**                      | Plugin tích hợp vào ứng dụng mobile, tự động thu thập và gửi GPS (tracking nền, cache offline, phát hiện GPS giả, tối ưu pin) | [Flutter SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-flutter) · [pub.dev](https://pub.dev/packages/vietmap_tracking_plugin) |
| **GPS Tracking API**                 | Nhận dữ liệu GPS từ thiết bị, lưu trữ, truy vấn lịch sử          | [API Reference](https://docs.fleetwork.vn/sdk/tracking-api)                                                                     |
| **React SDK + Dashboard/Report API** | Hiển thị bản đồ thời gian thực, KPI, báo cáo trên web            | [React SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-react) · [npm](https://www.npmjs.com/package/@vietmap/tracking-sdk-react) |

---

## 2. Kiến trúc tổng quan

```
┌─────────────────────────────────────────────────────────────────┐
│  Thiết bị di động  (Flutter App)                                │
│                                                                 │
│  VietmapTrackingPlugin                                          │
│    • Thu thập GPS theo timer HOẶC khoảng cách (loại trừ nhau)   │
│    • Cache offline vào SQLite khi mất mạng                      │
│    • Tự động upload khi có mạng trở lại                         │
│    • Phát hiện GPS giả + Speed fallback (thiết bị thiếu speed)  │
│    • Smart Battery (opt-in): đổi tần suất theo pin & chuyển động│
└───────────────────────────────┬─────────────────────────────────┘
                                │  POST /api/v1/gps-tracking
                                │  X-API-Key: <key>
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│  GPS Tracking API  (live.fleetwork.vn)                          │
│                                                                 │
│  • Nhận dữ liệu GPS (single / batch)                            │
│  • Lưu vào time-series database                                 │
│  • Cache vị trí mới nhất (real-time query)                      │
└───────────────────────────────┬─────────────────────────────────┘
                                │  (internal)
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│  AnalyticsApi (internal :7102)                                  │
│                                                                 │
│  • KPI: users active, km hôm nay, nhiên liệu, chi phí           │
│  • Bảng trạng thái users (đang di chuyển / dừng / mất tín)     │
│  • Heatmap hoạt động theo giờ                                   │
│  • Báo cáo hành trình, nhiên liệu, thời gian hoạt động          │
└───────────────────────────────┬─────────────────────────────────┘
                                │  YARP proxy
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│  Fleetwork.Web gateway  (live.fleetwork.vn)                     │
│                                                                 │
│  • Xác thực X-API-Key, inject X-Account-Id + X-Internal-Token  │
│  • Proxy đến AnalyticsApi :7102 (YARP)                          │
└───────────────────────────────┬─────────────────────────────────┘
                                │  GET /api/v1/dashboard/...
                                │  GET /api/v1/reports/...
                                │  X-API-Key: <key>
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│  Web Application  (React SDK)                                   │
│                                                                 │
│  @vietmap/tracking-sdk-react                                    │
│    • Dashboard component (full layout hoặc từng widget)         │
│    • LiveMap (bản đồ thời gian thực, marker nhân viên, lịch sử) │
│    • Report (hành trình / nhiên liệu / giờ hoạt động)           │
│    • Hooks + Controllers (tự build UI riêng)                    │
└─────────────────────────────────────────────────────────────────┘
```

---

## 3. Luồng tracking end-to-end

### 3.1 Gửi dữ liệu GPS (Mobile → Server)

```
1. App khởi động
   └─ initializeTracking(apiKey)              ← Xác thực API key phía server
   └─ registerLifecycleObserver()             ← Tự chuyển background/foreground

2. Xin quyền
   └─ requestLocationPermissions()            ← Vị trí foreground
   └─ requestAlwaysLocationPermissions()      ← Vị trí background
   └─ Permission.notification.request()       ← Notification (Android 13+ / iOS)

3. Bắt đầu tracking  (userId là BẮT BUỘC)
   └─ startTracking(config)
        ├─ intervalMs: 30000                  ← Chế độ timer (mỗi 30 giây)
        └─ distanceFilter: 70.0               ← HOẶC chế độ khoảng cách (sàn 25m)
                                                 Chỉ dùng 1 trong 2, cái kia = null

4. SDK tự động
   ├─ Thu thập GPS point
   ├─ [Có mạng]  → POST /api/v1/gps-tracking  (realtime)
   └─ [Mất mạng] → Lưu SQLite → Upload khi có mạng lại

5. Dừng tracking
   └─ stopTracking()
```

### 3.2 Xem Dashboard (Web → Server)

```
1. Khởi tạo React SDK
   └─ <FleetworkProvider apiKey="...">

2. Render dashboard
   └─ <Dashboard date={1713225600000} />
        ├─ GET /api/v1/dashboard/gps-manager/summary
        ├─ GET /api/v1/dashboard/gps-manager/users
        ├─ GET /api/v1/dashboard/gps-manager/activity-heatmap?from=...&to=...
        ├─ GET /api/v1/dashboard/gps-manager/fuel-tracking?from=...&to=...
        └─ GET /api/v1/dashboard/gps-manager/monthly-costs?from=...&to=...

3. Bản đồ thời gian thực
   └─ <LiveMap pollInterval={10000} />
        └─ Refresh vị trí nhân viên mỗi 10 giây

4. Lịch sử hành trình
   └─ GET /api/v1/gps-tracking/history?VehicleId=...
```

### 3.3 Xuất báo cáo

```
GET /api/v1/reports/trip/summary      ← Hành trình tổng hợp
GET /api/v1/reports/trip/detail       ← Hành trình chi tiết
GET /api/v1/reports/fuel/summary      ← Nhiên liệu tổng hợp
GET /api/v1/reports/fuel/detail       ← Nhiên liệu chi tiết
GET /api/v1/reports/activity-time     ← Thời gian hoạt động

# Thêm ?format=excel hoặc ?format=csv để tải file
```

### 3.4 Logic trạng thái nhân viên

```
Nhận GPS point gần nhất
│
├─ (now - lastSeenAt) > 15 phút  → statusCode = 0  (🔴 Mất tín hiệu)
├─ lastLocation.speed = 0         → statusCode = 2  (🟡 Đang dừng)
└─ lastLocation.speed > 0         → statusCode = 1  (🟢 Đang di chuyển)
```

---

## 4. Authentication

Tất cả API đều xác thực qua **header**:

```http
X-API-Key: <your_api_key>
```

> Không truyền API key qua query string (`?apiKey=...`).

Lỗi khi sai / thiếu API key:

```json
{
  "error": "UNAUTHORIZED",
  "message": "Missing or invalid X-API-Key header",
  "code": 401
}
```

---

## 5. Quick Start

### Bước 1 — Nhận API key từ Fleetwork

Liên hệ Fleetwork để nhận `API_KEY` — dùng cho cả Flutter SDK, React SDK và gọi API trực tiếp.

### Bước 2 — Tích hợp Flutter SDK (mobile app)

```dart
final controller = VietmapTrackingController.instance;
await controller.initializeTracking('YOUR_API_KEY');
controller.registerLifecycleObserver();

await controller.requestLocationPermissions();
await controller.requestAlwaysLocationPermissions();

await controller.startTracking(
  LocationTrackingConfig(
    userId: 'EMPLOYEE_ID',   // bắt buộc
    vehicleId: 'VEHICLE_ID', // tuỳ chọn
    intervalMs: 30000,       // 30 giây / lần
    accuracy: LocationAccuracy.high,
    backgroundMode: true,
  ),
);

// Hoặc dùng preset dựng sẵn:
await controller.startTracking(
  TrackingPresets.general().copyWith(userId: 'EMPLOYEE_ID'),
);
```

→ Xem hướng dẫn đầy đủ: [Flutter SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-flutter)

### Bước 3 — Tích hợp React SDK (web app)

```tsx
import { FleetworkProvider, Dashboard, LiveMap } from "@vietmap/tracking-sdk-react";
import "@vietmap/tracking-sdk-react/styles.css";

function App() {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  return (
    <FleetworkProvider apiKey="YOUR_API_KEY">
      <Dashboard date={today.getTime()} />
      <LiveMap apiKeyTilemap="YOUR_VIETMAP_TILE_KEY" height="600px" />
    </FleetworkProvider>
  );
}
```

→ Xem hướng dẫn đầy đủ: [React SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-react)

### Bước 4 — Gọi API trực tiếp (tùy chọn)

```http
GET https://live.fleetwork.vn/api/v1/gps-tracking/latest/users/{userId}
X-API-Key: YOUR_API_KEY

GET https://live.fleetwork.vn/api/v1/dashboard/gps-manager/summary
X-API-Key: YOUR_API_KEY
```

→ Xem tham chiếu API đầy đủ: [API Reference](https://docs.fleetwork.vn/sdk/tracking-api)

---

## 6. Tài liệu chi tiết

| Tài liệu                                 | Nội dung                                                             |
| ---------------------------------------- | -------------------------------------------------------------------- |
| [API Reference](https://docs.fleetwork.vn/sdk/tracking-api)       | Tham chiếu đầy đủ tất cả endpoints: GPS Tracking, Dashboard, Báo cáo |
| [Flutter SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-flutter) | Hướng dẫn tích hợp Flutter SDK vào ứng dụng mobile                   |
| [React SDK](https://docs.fleetwork.vn/sdk/tracking-sdk-react)     | Hướng dẫn tích hợp React SDK vào ứng dụng web                        |
