---
# System prepended metadata

title: MVP - transfer management system

---

# MVP - Sistema de Gestão de Transfers - Documentação Técnica

**Versão:** 3.0 Consolidada  
**Data:** Novembro 2025  
**Tipo:** Multi-tenant, Auto-escalável  
**Audiência:** Desenvolvimento + Gestão/Negócio + MVP

---

## 📘 COMO USAR ESTE DOCUMENTO

### 👨‍💼 Para Gestão & Negócio
- **Executive Summary**: Visão geral e proposta de valor
- **Processos de Negócio**: Como o sistema funciona
- **Operações**: Gestão diária e qualidade
- **Roadmap**: Faseamento e prioridades
- Secções marcadas com 📊 são orientadas a negócio

### 👨‍💻 Para Desenvolvimento
- **Arquitetura Técnica**: Estruturas de dados e APIs
- **Entidades Core**: Modelos de dados completos
- **Integrações**: APIs e webhooks
- **Especificações**: Lógica e algoritmos
- Secções marcadas com 💻 são orientadas a desenvolvimento

### 🔄 Para Ambos
- **Fluxos Completos**: Cenários end-to-end
- **Glossário**: Terminologia comum
- Secções marcadas com 🔄 são híbridas

---

# PARTE I - EXECUTIVE SUMMARY

## 📊 1. VISÃO GERAL DO SISTEMA

### O Que É
Sistema completo de gestão de transfers de passageiros que permite a operadores de transporte gerir:
- Reservas de múltiplas fontes (~~agências~~, clientes diretos, APIs)
- Frota de veículos e motoristas
- ~~Alocação inteligente de recursos~~
- ~~Faturação e~~ pagamentos (Vendus - Software de Facturação Online / Ifthenpay)
- Operações em tempo real (GPS, tempo para destino, milestone)

### Para Quem
- **Operadores de Transfer** (principal): Empresas que fazem transfers aeroporto-hotel, tours, etc (Pelican transfers :bird:)
~~- **Agências de Viagem** (B2B): Parceiros que reservam em nome dos clientes~~
- **Passageiros** (B2C): Clientes finais que reservam diretamente
- **Motoristas**: Executam os serviços via app móvel
- **Operadores**: Tratam dos clientes

### Problema que Resolve
Hoje, operadores de transfer gerem tudo em Excel, WhatsApp e papel:
- ❌ Alocação manual de motoristas → erros e conflitos
- ❌ Comunicação por telefone → ineficiente
- ❌ Sem visibilidade em tempo real → stress operacional
~~- ❌ Faturação manual → erros e atrasos~~
- ❌ Sem histórico → impossível otimizar

### Solução
~~✅ **Alocação automática** baseada em disponibilidade, prioridades e custos  ~~
✅ **Comunicação automática** via SMS, email, webhooks, notificacoes  
✅ **Tracking GPS** em tempo real  
~~✅ **Faturação automática** com múltiplas moedas e modelos de pricing  ~~
✅ **Analytics** para otimização contínua  
✅ **Multi-tenant** - cada operador isolado  

### Números-Chave (Projeção)
- **Redução de trabalho manual:** 70%
- **Aumento de eficiência:** 40%
~~- **Redução de dead mileage:** 25%~~
- **Satisfação cliente:** +30%
~~- **ROI:** < 6 meses~~

---

## 📊 2. PROPOSTA DE VALOR

### Para Operadores
- **Automação completa** do workflow de reserva até conclusão
~~- **Otimização de recursos** - maximizar utilização de frota~~
~~- **Escalabilidade** - crescer sem aumentar staff operacional~~
- **Visibilidade 360°** - dashboard com tudo em tempo real
~~- **Redução de custos** - menos dead mileage, melhor alocação~~

### Para Operadora / Agencia / Hotel (B2B)
- **API completa** para integração
- **Portal web** para self-service
- **SLA garantido** com tracking
~~- **Faturação flexível** - 5 modelos de pricing~~
~~- **White-label** opcional~~

### Para Passageiros (B2C)
- **Booking simples** - 3 minutos (via embed)
- **Tracking em tempo real** via link
- **Comunicação proativa** - updates automáticos
- **Rating/feedback** para qualidade
- **Histórico e favoritos**

---

## 📊 3. TIPOS DE SERVIÇO

### PRIVATE Transfer
**O quê:** 1 grupo, direto de A para B  
**Exemplo:** Família do aeroporto ao hotel  
**Características:** Privacidade, rota direta, previsível  
**Pricing:** Fixed ou distance-based  

~~### ROAD-SHOW~~
~~**O quê:** 1 grupo, múltiplas paragens (A→B→C→D)  
**Exemplo:** CEO em viagem de negócios (hotel→escritório→restaurante→aeroporto)  
**Características:** Mesmo motorista todo o dia, wait times  
**Pricing:** Package deal ou per-leg + wait time  ~~

~~### SHUTTLE Dinâmico
**O quê:** Múltiplos grupos, rota otimizada  
**Exemplo:** 10 pessoas do aeroporto para diferentes hotéis  
**Características:** Partilhado, rota calculada TSP, económico  
**Pricing:** Por pessoa, mais barato  ~~

~~### SHUTTLE Estático
**O quê:** Rota fixa, horários fixos  
**Exemplo:** Bus aeroporto-centro cada 30min  
**Características:** Previsível, simples, regular  
**Pricing:** Bilhete fixo  ~~

---

## 💻 4. ARQUITETURA TÉCNICA - VISÃO GERAL

### Stack Tecnológico Recomendado
```
BACKEND:
├─ Node.js + Express (ou NestJS)
├─ PostgreSQL (main database + supabase)
├─ ~~Redis (cache + queue)~~
└─ ~~Docker + Kubernetes~~

FRONTEND:
├─ React (web portal)
├─ React Native (mobile app)
└─ Bryntum Scheduler (visual planning)

INFRAESTRUTURA:
├─ ~~AWS / Azure / GCP~~
├─ ~~CDN para assets~~ (supabase)
└─ Backup automated

APIs & INTEGRAÇÕES:
├─ REST API (primary)
├─ ~~GraphQL (opcional)~~
├─ Webhooks (events)
└─ Socket.io (real-time)
```

### Componentes Principais
```
┌─────────────────────────────────────────────────┐
│                  LOAD BALANCER                  │
└──────────────────┬──────────────────────────────┘
                   │
        ┌──────────┴──────────┐
        │                     │
   ┌────▼─────┐         ┌────▼─────┐
   │  WEB APP │         │  API     │
   │  Portal  │         │  Server  │
   └──────────┘         └────┬─────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
         ┌────▼────┐    ┌───▼────┐    ┌───▼────┐
         │  Core   │    │ Queue  │    │ WebSock│
         │ Service │    │Worker  │    │ Server │
         └────┬────┘    └───┬────┘    └────────┘
              │             │
         ┌────▼─────────────▼────┐
         │    PostgreSQL DB      │
         └───────────────────────┘
```

### Modelo de Dados - Hierarquia
```
TENANT (Company)
  │
  ├─── AGENCIES (B2B clients)
  │     └─── BOOKINGS (from agency)
  │
  ├─── PASSENGERS (B2C clients)
  │     └─── BOOKINGS (direct)
  │
  ├─── VEHICLES
  │     ├─── Maintenance logs
  │     └─── Defects
  │
  ├─── DRIVERS
  │     ├─── Shifts
  │     ├─── Ratings
  │     └─── Earnings
  │
  ├─── TRANSFERS (bookings)
  │     ├─── Allocation (driver+vehicle)
  │     ├─── Status updates
  │     └─── GPS tracking
  │
  ├─── INVOICES
  │     └─── Payments
  │
  └─── USERS (staff)
        └─── Permissions (RBAC)
```

---

# PARTE II - ENTIDADES CORE

## 💻 5. TRANSFER (Entidade Central)

### Descrição
A entidade **Transfer** representa uma reserva de transporte. É o core do sistema.

### Características Principais
- ✅ **Origem e destino dinâmicos** - podem mudar até T-0 (para o MVP)
- ✅ **Flight dependency** - voo atrasa → pickup atrasa automaticamente (MVP prio 2)
- ✅ **Múltiplas versões de timing** - scheduled, estimated, actual
- ✅ **Allocation pode ser pós-hora** - para emergências
- ✅ **Vehicle class** calculado automaticamente

### Estrutura de Dados

```javascript
// MODELO DE DADOS - TRANSFER
{
  // ─── METADATA ───
  id: UUID,
  booking_reference: String, // "BK-12345"
  company_id: UUID, // tenant
  booking_source: Enum, // "api" | "email" | "portal" | "phone"
  service_type: Enum, // "PRIVATE" | "ROAD_SHOW" | "SHUTTLE_DYNAMIC" | "SHUTTLE_STATIC"
  
  // ─── PASSAGEIROS & REQUISITOS ───
  passenger_count: Integer,
  luggage_count: Integer,
  accessibility_requirements: Array, // ["wheelchair", "child_seat", "baby_seat"]
  special_notes: Text,
  
  // ─── ROUTING (AMBOS DINÂMICOS!) ───
  origin: {
    location: { lat: Float, lng: Float, address: String },
    type: Enum, // "airport" | "hotel" | "address" | "poi"
    flight_dependency: { // OPCIONAL - só se aplicável
      flight_number: String,
      flight_type: "arrival", // ⚠️ SÓ ARRIVAL IMPACTA TIMING!
      scheduled_time: DateTime,
      actual_time: DateTime, // quando disponível
    },
    can_change_until: DateTime, // até quando pode mudar
  },
  
  destination: {
    location: { lat: Float, lng: Float, address: String },
    type: Enum,
    flight_dependency: { // OPCIONAL
      flight_number: String,
      flight_type: "departure", // ℹ️ NÃO IMPACTA timing (apenas deadline)
      scheduled_time: DateTime,
    },
    can_change_until: DateTime,
  },
  
  // ─── DISTANCE & PRICING ───
  calculated_distance_km: Decimal,
  calculated_distance_miles: Decimal,
  estimated_duration_minutes: Integer,
  calculation_method: Enum, // "api" | "historical" | "linear_factor"
  
  pricing: {
    pricing_type: Enum, // "fixed" | "dynamic" | "quoted"
    base_price: Decimal, // se fixed
    price_per_km: Decimal, // se dynamic
    quoted_price: Decimal, // se quoted
    currency: String, // "EUR" | "USD" | "GBP"
    calculation_breakdown: {
      distance_cost: Decimal,
      time_cost: Decimal,
      accessibility_surcharge: Decimal,
      wait_time_cost: Decimal,
      total: Decimal,
    },
  },
  
  last_calculated_at: DateTime,
  
  // ─── TIMING (3 VERSÕES) ───
  scheduled: { // IMUTÁVEL - o prometido
    pickup_time: DateTime,
    dropoff_time: DateTime,
  },
  
  estimated: { // DINÂMICO - melhor estimativa
    pickup_time: DateTime,
    dropoff_time: DateTime,
    last_calculated_at: DateTime,
    calculation_confidence: Percentage, // 0-100
  },
  
  actual: { // HISTÓRICO - realidade
    pickup_time: DateTime,
    dropoff_time: DateTime,
  },
  
  // ─── VEHICLE REQUIREMENTS ───
  vehicle_class: String, // calculado: "sedan4" | "van7" | "minibus10" | "bus16" | "wheelchair_van"
  
  required_features: Array, // ["wheelchair_accessible", "child_seats", "luxury", "wifi"]
  
  driver_qualification_required: {
    license_category: Enum, // "B" | "D" | "D1"
    certifications: Array, // ["taxi", "tvde", "transport_collective"]
  },
  
  // ─── ALLOCATION (PODE SER APÓS T-0!) ───
  allocation_strategy: Enum, // definido pelo operator
  // "own_drivers" | "outsourced" | "hybrid" | "other_operator" | "prevent_dead_mileage"
  
  allocation_priority: {
    priority_score: Integer, // calculado
    priority_rules: Array, // ["vip_first", "earliest_first", "agency_sla_first", "road_show_first"]
    can_allocate_after_scheduled_time: Boolean, // TRUE - para emergências
  },
  
  allocated_unit: { // Driver + Vehicle SEMPRE juntos!
    driver_id: UUID,
    vehicle_id: UUID,
    unit_type: Enum, // "own" | "outsourced" | "operator"
    allocated_at: DateTime,
    allocation_confidence: Percentage,
  },
  
  allocation_status: Enum,
  // "pending" | "allocated" | "confirmed" | "conflict" | "emergency_reallocated" | "manually_assigned"
  
  manual_override_allowed: Boolean, // TRUE
  
  // ─── NO-SHOW POLICY (POR AGÊNCIA!) ───
  policy_id: UUID, // FK para agência
  wait_time_minutes: Integer,
  charge_policy: {
    type: Enum, // "full_charge" | "partial_charge" | "no_charge" | "custom"
    percentage: Integer, // se partial
  },
  notification_protocol: {
    attempts: Integer,
    escalation: String,
  },
  
  // ─── BOOKING SOURCE & COMMUNICATION ───
  booking_source: {
    type: Enum, // "api" | "email" | "portal" | "phone"
    agency_id: UUID, // FK, se B2B
    agency_no_show_policy_id: UUID, // FK
  },
  
  communication_chain: {
    primary_contact: Object, // agência ou passageiro
    secondary_contacts: Array,
  },
  
  // ─── STATUS & METADATA ───
  status: Enum,
  // "booked" → "allocated" → "confirmed" → "in_progress" → "completed" | "cancelled" | "no_show"
  
  created_at: DateTime,
  updated_at: DateTime,
  completed_at: DateTime,
}
```

### Regras de Negócio - Transfer

1. **Voo só impacta timing se for ARRIVAL na origem**
   - Departure flight no destino é apenas informativo (deadline)

2. **Origem e Destino podem mudar até T-0**
   - Sistema recalcula automaticamente (cumprindo as regras das reservas)
   ~~- Notificações enviadas aos stakeholders (como no caso de no-show)~~

~~3. **Vehicle Class calculado automaticamente:**
   ```
   IF wheelchair THEN wheelchair_van
   ELSE IF passengers <= 4 AND luggage <= 3 THEN sedan4
   ELSE IF passengers <= 7 THEN van7
   ELSE IF passengers <= 10 THEN minibus10
   ELSE bus16
   ```~~

4. **Pricing recalculado quando:**
   - Origem ou destino muda
   - Distância recalculada
   - Acessórios adicionados (child seat, etc)

---

~~## 💻 6. ROAD-SHOW (Multi-leg Transfer)

### Descrição
**Multi-leg transfer** - Múltiplas viagens para o mesmo cliente/grupo.

### Quando Usar
- Executivos em viagem de negócios
- VIPs com múltiplos compromissos
- Tours guiados com várias paragens

### Estrutura de Dados

```javascript
// MODELO DE DADOS - ROAD_SHOW
{
  road_show_id: UUID, // agrupa todas as legs
  company_id: UUID, // tenant
  customer_reference: String,
  
  // ─── LEGS (array de Transfers) ───
  legs: [
    { leg_number: 1, transfer_id: UUID }, // Airport → Hotel
    { leg_number: 2, transfer_id: UUID }, // Hotel → Meeting
    { leg_number: 3, transfer_id: UUID }, // Meeting → Restaurant
    { leg_number: 4, transfer_id: UUID }, // Restaurant → Airport
  ],
  
  // ─── DEPENDENCY LOGIC ───
  hard_dependencies: [
    { dependent_leg: 2, depends_on: 1, buffer_time_minutes: 30 }
    // leg_2.start >= leg_1.end + buffer_time
  ],
  
  delay_propagation: Enum, // "manual" | "automatic" (RECOMENDADO: manual)
  // Se leg_1 atrasa:
  //   - Sistema SUGERE novo timing
  //   - Operator DECIDE se aceita ou não
  
  manual_start_time_override: Boolean, // TRUE - Operator pode alterar start de qualquer leg
  
  // ─── ALLOCATION STRATEGY ───
  default_strategy: "same_driver_all_legs",
  // Driver recebe TODAS as legs como bloco
  // Reserva período completo (ex: 09:00-21:00)
  
  allow_split: Boolean, // TRUE
  // Operator pode MANUALMENTE atribuir legs a diferentes drivers
  // Ex: leg_1+2 = Driver A, leg_3+4 = Driver B
  
  wait_time_handling: {
    under_1h: "driver_waits_included",
    from_1h_to_3h: "driver_waits_chargeable",
    over_3h: "driver_can_do_short_transfer", // com aprovação
  },
  
  // ─── PRICING ───
  pricing_model: Enum, // "per_leg" | "total_package"
  includes_wait_time: Boolean,
  calculation: {
    legs_total: Decimal, // sum of all legs
    wait_time_charges: Decimal,
    total: Decimal,
  },
  
  // ─── STATUS ───
  status: Enum, // "pending" | "allocated" | "in_progress" | "completed"
  current_leg: Integer, // qual leg está ativa
  completed_legs: Array,
}
```~~

~~### Regras de Negócio - Road-show

1. **Alocação padrão:** Mesmo driver para todas as legs
   - Bloco reservado do início ao fim
   - Minimiza hand-off entre drivers

2. **Propagação de atrasos:** MANUAL por padrão
   ```
   Leg 1 atrasa 45min:
   
   Sistema SUGERE:
   ├─ Manter legs seguintes (se buffer suficiente)
   └─ OU ajustar todas (+45min)
   
   Operator DECIDE:
   ├─ Opção A: Manter original (trocar driver se necessário)
   └─ Opção B: Ajustar timings
   ```

3. **Wait time:**
   - < 1h: incluído no preço
   - 1-3h: cobrado à parte
   - > 3h: driver pode fazer transfer curto nearby (com aprovação)

4. **Split permitido:**
   - Operator pode manualmente separar legs
   - Sistema valida constraints de cada leg individualmente

---~~

## 💻 7. VEHICLE (Frota)

### Descrição
**Gestão completa da frota** - Veículos, ~~manutenção, disponibilidade.~~

### Estrutura de Dados

```javascript
// MODELO DE DADOS - VEHICLE
{
  // ─── BASIC INFO ───
  id: UUID,
  company_id: UUID, // tenant
  license_plate: String, // único
  make: String, // "Mercedes", "BMW"
  model: String, // "E-Class", "Serie 3"
  year: Integer,
  color: String,
  vin: String, // chassis number
  
  // ─── CLASSIFICATION ───
  vehicle_class: String, // "sedan4" | "van7" | "minibus10" | "bus16"
  
  capacity: {
    max_passengers: Integer,
    max_luggage: Integer,
    max_weight_kg: Integer,
  },
  
  features: [
    "wheelchair_accessible",
    "child_seats_available",
    "luxury",
    "wifi",
    "air_conditioning"
  ],
  
  // ─── STATUS & AVAILABILITY ───
  current_status: Enum,
  // "available" | "in_service" | "maintenance" | "broken" | "out_of_service"
  
  current_location: { lat: Float, lng: Float },
  last_updated_at: DateTime,
  estimated_available_at: DateTime,
  
  // ─── MAINTENANCE & HISTORY ───
  maintenance_schedule: [
    {
      scheduled_date: DateTime,
      maintenance_type: Enum, // "inspection" | "revision" | "repair"
      estimated_duration_hours: Integer,
      status: Enum, // "scheduled" | "in_progress" | "completed"
    }
  ],
  
  maintenance_history: [
    {
      date: DateTime,
      type: String,
      description: Text,
      cost: Decimal,
      next_due_date: DateTime,
    }
  ],
  
  defects_log: [ // ⚠️ CRÍTICO
    {
      reported_at: DateTime,
      reported_by: UUID, // driver_id
      description: Text,
      severity: Enum, // "critical" | "high" | "medium" | "low"
      status: Enum, // "open" | "in_repair" | "resolved"
      resolved_at: DateTime,
    }
  ],
  
  usage_statistics: {
    total_km: Integer,
    total_transfers: Integer,
    last_service_km: Integer,
    km_until_next_service: Integer,
  },
  
  // ─── INSURANCE & DOCUMENTS ───
  insurance_expiry: Date,
  inspection_expiry: Date, // IPO
  registration_expiry: Date,
  documents: Array, // scans/PDFs
  
  // ─── COST TRACKING ───
  acquisition_cost: Decimal,
  maintenance_costs_ytd: Decimal,
  fuel_costs_ytd: Decimal,
  cost_per_km: Decimal, // calculado
}
```
~~
### Regras de Negócio - Vehicle

1. **Status transitions:**
   ```
   available ⟷ in_service (normal operation)
   available → maintenance → available (scheduled)
   available → broken → maintenance → available (emergency)
   any_status → out_of_service (permanent removal)
   ```

2. **Manutenção programada:**
   - Bloqueia allocation automaticamente
   - Sistema sugere realocação de transfers afetados

3. **Defeitos críticos:**
   - Reportados pelo driver via app
   - Status automático: available → broken
   - Transfers afetados: realocados imediatamente

4. **Localização:**
   - Atualizada automaticamente durante transfers (GPS)
   - Usada para calcular dead mileage na allocation

---~~

## 💻 8. DRIVER (Motoristas)

### Descrição
**Motoristas** - SEMPRE associados a um veículo.

### Estrutura de Dados

```javascript
// MODELO DE DADOS - DRIVER
{
  // ─── BASIC INFO ───
  id: UUID,
  company_id: UUID, // tenant
  name: String,
  photo: URL,
  phone: String,
  email: String,
  
  // ─── QUALIFICATIONS ───
  license_category: Enum, // "B" | "D" | "D1"
  license_number: String,
  license_expiry: Date,
  
  certifications: [
    "taxi",
    "tvde", // Uber/Bolt
    "transport_collective",
    "first_aid"
  ],
  
  languages: ["PT", "EN", "ES", "FR"],
  
  // ─── VEHICLE ASSIGNMENT ⚠️ OBRIGATÓRIO ───
  assigned_vehicle_id: UUID, // FK, NEVER NULL!
  assignment_type: Enum, // "permanent" | "daily"
  
  // REGRA CRÍTICA:
  // Driver SEM veículo = INDISPONÍVEL
  // Se carro em manutenção → driver fica idle OU troca de carro
  
  // ─── WORK SHIFT ⚠️ GESTÃO DE TURNOS ───
  current_shift: {
    shift_start: DateTime, // ex: 2025-11-10 08:00
    shift_end: DateTime, // ex: 2025-11-10 20:00
    break_start: Time, // ex: 13:00
    break_end: Time, // ex: 14:00
    max_hours_per_shift: Integer, // legal default 10h
  },
  
  shift_template: { // padrão semanal
    monday: { start: "08:00", end: "20:00" },
    tuesday: { start: "08:00", end: "20:00" },
    wednesday: { start: "08:00", end: "20:00" },
    thursday: { start: "08:00", end: "20:00" },
    friday: { start: "08:00", end: "20:00" },
    saturday: { start: "09:00", end: "18:00" },
    sunday: { off: true },
  },
  
  shift_exceptions: [
    {
      date: Date,
      reason: Enum, // "vacation" | "sick" | "day_off" | "training"
      replacement_driver_id: UUID, // opcional
    }
  ],
  
  legal_constraints: {
    max_hours_per_day: Integer, // 10h
    min_rest_between_shifts: Integer, // 11h
    max_hours_per_week: Integer, // 48h
  },
  
  // ─── AVAILABILITY (CALCULADA EM RUNTIME) ───
  current_status: Enum,
  // "available" | "busy" | "on_break" | "off_shift" | "unavailable"
  
  next_available_at: DateTime,
  hours_worked_today: Integer,
  
  // ─── RATING & PERFORMANCE ───
  average_rating: Decimal, // 1-5
  total_transfers: Integer,
  on_time_percentage: Decimal,
  customer_feedback: Array,
  
  // ─── TYPE (DEFINIDO PELO OPERATOR) ───
  employment_type: Enum, // "own" | "outsourced" | "partner_operator"
  cost_per_hour: Decimal, // para cálculo interno
}
```

### Regras de Negócio - Driver

1. **Driver SEMPRE tem veículo:**
   ```
   Driver sem vehicle_id → Status: unavailable
   
   Carro vai para manutenção:
   ├─ Opção A: Driver fica idle (pago)
   └─ Opção B: Driver recebe outro carro (temp assignment)
   ```

2. **Validação de turno na allocation:**
   ```
   Transfer: 19:00-20:30 (1.5h)
   Driver João: 
   ├─ Shift: 08:00-20:00
   ├─ Already worked: 9h
   ├─ Total would be: 10.5h ❌ EXCEDE LIMITE
   
   Sistema:
   └─ REJEITA allocation para João
   └─ OU sugere split/overtime (manual approval)
   ```

3. **Rest between shifts:**
   ```
   Driver termina: 22:00
   Próximo shift: >= 09:00 (11h depois)
   
   Sistema previne allocation antes de 09:00
   ```

4. **Break time:**
   - Configurável por driver
   - Bloqueio automático na allocation
   - Pode ser overridden em emergência

---

## 🔄 9. AGENCY / Operadora / Hotel (Clientes B2B)

### Descrição
Entidade central para operação B2B - Gestão completa de agências parceiras.

### Para Negócio 📊
Agências são clientes B2B que:
- Fazem bookings em nome dos seus clientes
- Têm contratos com termos específicos (pricing, SLA, crédito)
- Podem ter acesso via API ou Portal
~~- São faturadas mensalmente ou por transfer~~

### Para Desenvolvimento 💻

```javascript
// MODELO DE DADOS - AGENCY
{
  // ─── BASIC INFO ───
  id: UUID,
  company_id: UUID, // tenant FK
  name: String,
  legal_name: String,
  tax_id: String, // VAT/NIF
  logo_url: String,
  website: String,
  
  // ─── CONTACT INFO ───
  primary_contact: {
    name: String,
    email: String,
    phone: String,
    position: String,
  },
  billing_contact: Object,
  operations_contact: Object,
  emergency_contact: Object,
  
  // ─── ADDRESS ───
  billing_address: {
    street: String,
    city: String,
    postal_code: String,
    country: String,
    tax_residence: String,
  },
  operational_address: Object,
  
  // ─── CONTRACT & PRICING ⭐ ───
  contract: {
    contract_id: String,
    start_date: Date,
    end_date: Date,
    renewal_type: Enum, // "automatic" | "manual"
    notice_period_days: Integer,
    contract_document_url: String,
  },
  
  pricing_model: Enum,
  // "net_rates" | "markup" | "discount" | "custom_rates" | "commission"
  
  pricing_params: {
    markup_percentage: Decimal, // ex: 20
    discount_percentage: Decimal, // ex: 15
    commission_rate: Decimal, // ex: 10
    custom_rate_sheet_id: UUID,
  },
  
  minimum_monthly_value: Decimal, // Commitment mínimo mensal
  
  // ─── PAYMENT TERMS ⭐ ───
  payment_terms: {
    type: Enum, // "prepaid" | "postpaid" | "credit_account" | "per_transfer"
    credit_limit: Decimal, // Limite de crédito disponível
    payment_due_days: Integer, // Ex: NET 30, NET 15
    late_payment_fee: {
      type: Enum, // "percentage" | "fixed"
      value: Decimal, // ex: 2.0 (2% por mês)
      grace_period_days: Integer, // ex: 7
    },
  },
  
  current_balance: Decimal, // Saldo atual da conta
  available_credit: Decimal, // credit_limit - current_balance
  
  credit_status: Enum, // "good" | "warning" | "suspended" | "blocked"
  
  // ─── SERVICE LEVEL AGREEMENT (SLA) ⭐ ───
  sla_terms: {
    response_time_minutes: Integer, // 15
    allocation_time_hours: Integer, // 24
    on_time_target_percentage: Decimal, // 95
    customer_satisfaction_target: Decimal, // 4.5
    cancellation_notice_hours: Integer, // 24
  },
  
  breach_penalties: Array, // Penalidades por não cumprir SLA
  performance_bonuses: Array, // Bonus por exceder SLA
  
  // ─── OPERATIONAL SETTINGS ───
  no_show_policy_id: UUID, // FK - Política específica desta agência
  cancellation_policy_id: UUID, // FK
  preferred_vehicle_categories: Array, // ["executive", "luxury"]
  
  requires_approval: {
    for_changes: Boolean,
    for_cancellations: Boolean,
    for_extras: Boolean,
  },
  
  auto_allocation: Boolean, // Allocar automaticamente ou esperar confirmação
  
  // ─── API ACCESS ⭐ ───
  api_enabled: Boolean,
  api_key: String, // hashed
  api_secret: String, // hashed
  webhook_url: String,
  webhook_events: ["booking.created", "booking.completed"], // etc
  ip_whitelist: Array,
  
  rate_limit: {
    requests_per_minute: Integer, // 60
    burst_limit: Integer, // 100
  },
  
  // ─── PORTAL ACCESS ───
  portal_enabled: Boolean,
  portal_url: String, // portal.system.com/agency-slug
  portal_users: Array, // Users que podem aceder
  portal_permissions: Array, // O que podem fazer
  
  // ─── PERFORMANCE TRACKING ⭐ ───
  statistics: {
    total_bookings: Integer, // 1456
    total_revenue: Decimal, // 145600.00
    average_booking_value: Decimal, // 100.00
    cancellation_rate: Decimal, // 0.05 (5%)
    no_show_rate: Decimal, // 0.02 (2%)
    on_time_rate: Decimal, // 0.97 (97%)
  },
  
  monthly_performance: Array, // Histórico mensal
  
  trends: {
    growth_rate: Decimal, // 0.15 (15% MoM)
    forecast_next_month: Integer, // 167
  },
  
  // ─── STATUS & SETTINGS ───
  status: Enum, // "active" | "suspended" | "blocked" | "inactive"
  tier: Enum, // "standard" | "premium" | "vip"
  priority_level: Integer, // 1-10, usado na allocation
  notes: Text, // Notas internas
  tags: ["corporate", "high-volume", "vip"],
  
  // ─── AUDIT ───
  created_at: DateTime,
  created_by: UUID,
  updated_at: DateTime,
  last_booking_at: DateTime,
}
```

### Pricing Models - Exemplos

**Modelo 1: NET RATES**
```
Agency paga preços base do operator
Transfer: €100 → Agency pays: €100
```
~~
**Modelo 2: MARKUP (+20%)**
```
Transfer operator cost: €100
Markup 20%: +€20
Agency pays: €120
```

**Modelo 3: DISCOUNT (-15%)**
```
Transfer public price: €100
Discount 15%: -€15
Agency pays: €85
```

**Modelo 4: COMMISSION (10%)**
```
Transfer sold to customer: €120
Commission 10%: -€12
Operator receives: €108
Agency keeps: €12
```~~
~~
### Credit Management Flow

```
NEW AGENCY:
├─ Credit limit: €5,000
├─ Balance: €0
└─ Available: €5,000

After 50 transfers (€5,000):
├─ Balance: €5,000
└─ Available: €0 ⚠️

Transfer #51:
└─ BLOCKED!

Payment received (€3,000):
├─ Balance: €2,000
└─ Available: €3,000 ✓

ALERTS:
├─ 80% used: Warning
├─ 95% used: Urgent
├─ 100% used: Suspend
└─ Overdue: Block
```~~

---

## 🔄 10. PASSENGER (Clientes B2C)

### Descrição
Entidade dedicada para passageiros - Histórico, preferências e gestão.

### Para Negócio 📊
Passageiros são clientes finais que:
- Reservam diretamente no sistema
- Têm histórico de viagens e preferências
- Podem ser segmentados (VIP, Frequent, Regular)
- Recebem comunicações personalizadas

### Para Desenvolvimento 💻

```javascript
// MODELO DE DADOS - PASSENGER
{
  // ─── BASIC INFO ───
  id: UUID,
  company_id: UUID, // tenant FK
  external_id: String, // ID da agência se veio de lá
  first_name: String,
  last_name: String,
  email: String,
  phone: String,
  date_of_birth: Date, // opcional
  
  // ─── CONTACT PREFERENCES ───
  preferred_contact_method: Enum, // "email" | "sms" | "whatsapp" | "phone_call"
  language: String, // "EN" | "PT" | "ES" | "FR"
  timezone: String,
  
  notification_preferences: {
    booking_confirmation: Boolean,
    driver_assigned: Boolean,
    on_the_way: Boolean,
    marketing: Boolean,
    surveys: Boolean,
  },
  
  // ─── TRAVEL PREFERENCES ⭐ ───
  default_vehicle_category: String, // "executive"
  accessibility_requirements: ["wheelchair", "child_seat"],
  special_requests: ["quiet_driver", "temperature_22c", "no_perfume"],
  
  saved_locations: {
    home_address: Object,
    work_address: Object,
    frequent_hotels: Array,
  },
  
  // ─── PASSENGER STATUS ───
  status: Enum, // "active" | "vip" | "blacklisted" | "inactive"
  vip_reason: String, // "High-value corporate client"
  blacklist_reason: String, // "Multiple no-shows without payment"
  risk_level: Enum, // "low" | "medium" | "high"
  
  // ─── HISTORICAL DATA ⭐ ───
  statistics: {
    total_transfers: Integer, // 156
    total_spent: Decimal, // 15600.00
    average_rating_given: Decimal, // 4.8
    average_rating_received: Decimal, // 4.5
    cancellation_count: Integer, // 3
    no_show_count: Integer, // 1
    first_transfer_date: Date,
    last_transfer_date: Date,
  },
  
  // ─── BEHAVIORAL PATTERNS ───
  booking_behavior: {
    preferred_booking_window_hours: Integer, // 24h, 48h
    preferred_pickup_times: Array, // ["08:00", "17:00"]
    most_frequent_routes: Array,
  },
  
  // ─── SEGMENTATION ⭐ ───
  segment: Enum, // "vip" | "frequent" | "regular" | "at_risk" | "churned"
  segment_criteria: {
    min_transfers_for_frequent: 10,
    min_spend_for_vip: 5000,
    inactivity_days_for_churned: 180,
  },
  
  // ─── LOYALTY ───
  loyalty_points: Integer,
  loyalty_tier: Enum, // "bronze" | "silver" | "gold" | "platinum"
  
  // ─── GDPR & PRIVACY ───
  consent: {
    marketing: Boolean,
    data_processing: Boolean,
    third_party_sharing: Boolean,
    consent_date: DateTime,
  },
  
  data_retention: {
    can_delete_after: Date, // 2 years inactive
    deletion_requested: Boolean,
    deletion_scheduled_date: Date,
  },
  
  // ─── AUDIT ───
  created_at: DateTime,
  created_by: UUID, // user ou agency
  updated_at: DateTime,
  last_login_at: DateTime,
}
```

~~### Passenger Segmentation Logic

```
VIP:
├─ Total spend > €5,000
├─ OR Corporate client
└─ Benefits: Priority allocation, better vehicles

FREQUENT:
├─ Transfers > 10 in 12 months
└─ Benefits: Discount 5%, loyalty points

REGULAR:
├─ Transfers 1-10 in 12 months
└─ Benefits: Standard service

AT_RISK:
├─ No transfer in 90-180 days
└─ Action: Re-engagement campaign

CHURNED:
├─ No transfer in 180+ days
└─ Action: Win-back campaign

BLACKLISTED:
├─ Multiple no-shows (3+)
├─ OR Payment issues
└─ Action: Require prepayment
```~~

---

# PARTE III - PROCESSOS DE NEGÓCIO

## 📊 11. LÓGICA DE ALLOCATION

### Para Negócio
Allocation é o processo de atribuir um motorista e veículo a cada transfer. É feito automaticamente pelo sistema (MVP - sem process scheduler) baseado em:
- Disponibilidade de recursos
- Prioridades (VIP, SLA, ordem)
- Eficiência (minimizar km vazios)
- Custos (próprios vs terceirizados)

### Timeline de Allocation por Tipo

```
PRIVATE / ROAD_SHOW:
├─ T-24h: Allocation automática (1ª tentativa)
├─ T-12h: Validação + resolver conflitos
├─ T-4h:  Confirmação com driver
├─ T-2h:  Monitorização ativa
├─ T-0:   Execução
└─ T+X:   Emergência: realocação permitida ⚠️

SHUTTLE_DYNAMIC:
├─ T-4h:  Cut-off para agrupamento
├─ T-3h:  Optimizar rota + validar capacidade
├─ T-2h:  Allocation de veículo + driver
├─ T-1h:  Confirmação + notificações
└─ T-0:   Execução

SHUTTLE_STATIC:
├─ T-24h: Contar passageiros
├─ T-4h:  Decidir capacidade (1 ou 2 shuttles?)
├─ T-2h:  Allocation
└─ T-0:   Execução
```

### Estratégias de Allocation (Configuráveis)

**Definidas pelo Operator a nível de company:**

```javascript
OPERATOR_CONFIG = {
  allocation_strategy: {
    driver_pool_preference: Enum,
    // "own_drivers_only" | "outsourced_only" | "hybrid_own_first" | 
    // "hybrid_cheapest_first" | "partner_operator"
    
    dead_mileage_prevention: {
      enabled: Boolean,
      max_acceptable_km: Integer, // ex: 20km
      weight_in_scoring: Integer, // ex: 30%
    },
    
    priority_rules: [ // ⚠️ DINÂMICAS
      { type: "vip_first", weight: 100 },
      { type: "road_show_first", weight: 80 },
      { type: "earliest_first", weight: 50 },
      { type: "agency_sla", weight: 70 },
      { type: "minimize_cost", weight: 30 },
    ],
  },
  
  timing_windows: {
    default_allocation_window: Duration, // -24h
    validation_frequency: {
      before_T_minus_4h: Duration, // 1h
      after_T_minus_4h: Duration, // 15min
    },
    allow_post_scheduled_allocation: Boolean, // TRUE
    // Casos: emergency, major_delay, cancellation
  },
  
  conflict_resolution: {
    auto_resolve: Boolean,
    escalation_threshold: Enum, // "soft_conflict" | "hard_conflict"
    manual_approval_required_for: [
      "shift_overtime",
      "vehicle_swap",
      "outsource_transfer"
    ],
  },
}
```

### Scoring Algorithm

**Para cada (Driver + Vehicle) disponível:**

```
Score = Σ(priority_rules) 
        - dead_mileage_penalty 
        + efficiency_bonus
        - cost_factor

EXEMPLO:

Transfer #456 (Private, 2 pax, Airport→Hotel)
├─ Pickup: 15:00
├─ Priority: NORMAL (base 100)
└─ Priority rules:
   ├─ earliest_first: +50
   └─ Total: 150

Candidate 1: Driver João + Van7
├─ Priority score: 150
├─ Dead mileage: 5km → penalty -10
├─ Cost: €15/h → factor -15
├─ Efficiency: next transfer 10km away → bonus +20
└─ TOTAL: 145

Candidate 2: Driver Maria + Sedan4
├─ Priority score: 150
├─ Dead mileage: 25km → penalty -50
├─ Cost: €12/h → factor -12
├─ Efficiency: no next transfer → bonus 0
└─ TOTAL: 88

Winner: João (145 > 88) ✓
```

### Deteção e Resolução de Conflitos

~~**Tipos de Conflito:**

```
HARD CONFLICTS (impedem allocation):
├─ Carro já alocado ao mesmo tempo
├─ Driver excede horas legais (shift)
├─ Veículo em manutenção
├─ Driver sem qualificação adequada
├─ Veículo sem features necessárias (wheelchair, etc)
└─ Driver sem veículo atribuído

SOFT CONFLICTS (geram warnings):
├─ Dead mileage > threshold (ex: 30km)
├─ Driver no fim do turno (próximo limite)
├─ Utilização de veículo < 50% (não optimizado)
└─ Passageiros próximo da capacidade máxima
```~~

**Resolução Automática:**

```
IF conflict detected THEN
  ├─ Tentar realocar para outro recurso disponível
  ├─ Se road-show: realocar cadeia completa
  ├─ Se não possível: ESCALATE para manual
  └─ Notificar operations team

REGRAS INVIOLÁVEIS:
├─ NUNCA quebrar road-show allocation
├─ NUNCA violar driver qualifications
├─ NUNCA violar shift constraints (sem aprovação)
└─ SEMPRE respeitar hard constraints
```

---

## 💻 12. CÁLCULO DE PRICING

### Cálculo de Distância

**Flow de Cálculo (cascading fallback):**

```
1. INPUT
   ├─ origin: {lat, lng}
   └─ destination: {lat, lng}

2. MÉTODO (ordem de prioridade)
   ├─ PRIMARY: GraphHopper API (2500 requests/dia GRÁTIS)
   │  └─ Returns: distance_km, duration_min, route_geometry
   │
   ├─ SECONDARY: Dados históricos próprios
   │  └─ Lookup: mesma rota em transfers passados
   │     └─ "Airport→Hotel Ibis" = média 15km
   │
   └─ FALLBACK: Distância linear + factor
      └─ distance = haversine(origin, dest) * 1.3

3. CONVERT UNITS
   ├─ km = distance
   ├─ miles = km * 0.621371
   └─ duration_hours = duration_min / 60

4. STORE
   ├─ calculated_distance_km
   ├─ calculated_distance_miles
   ├─ estimated_duration_minutes
   └─ calculation_method (para auditoria)
```

### Modelos de Pricing

#### MODELO 1: FIXED PRICE

```
Usado: Rotas conhecidas, contratos

Exemplo: "Airport → City Center = €35"

Cálculo:
└─ base_price (fixo, pré-definido)

Não muda com:
├─ Tráfego (incluído)
├─ Distância real (estimado)
└─ Tempo (incluído)
```

#### MODELO 2: DYNAMIC (Distance-based)

```javascript
// Usado: Custom routes, sem contrato
// Exemplo: "€1.50/km + €15 base"

const pricing = {
  base_fee: 15, // €15
  
  distance_fee: distance_km * price_per_km,
  // 15km * €1.50 = €22.50
  
  time_fee: duration_hours * price_per_hour, // opcional
  // 0.42h * €20/h = €8.40
  
  surcharges: {
    night: booking_time between "22:00" and "06:00" ? 0.20 : 0, // +20%
    weekend: is_weekend ? 0.15 : 0, // +15%
    accessibility: has_accessibility ? 10 : 0, // +€10 (wheelchair, child seat)
    airport_fee: is_airport ? 5 : 0, // +€5
    wait_time: wait_minutes * 0.50, // €0.50/min
  },
  
  total: base + distance + time + sum(surcharges)
}

// Exemplo completo:
// ├─ Base: €15
// ├─ Distance (15km): €22.50
// ├─ Time (25min): incluído no base
// ├─ Child seat: +€10
// └─ TOTAL: €47.50
```

#### MODELO 3: QUOTED

```
Usado: Road-shows, pedidos complexos, grupos grandes

Processo:
1. Cliente pede quotation
2. Sistema calcula estimate (dynamic model)
3. Operator review & ajusta (margem, complexidade)
4. Quota enviada ao cliente
5. Cliente aceita → booking criado
6. Preço FIXO (não muda após aceite)
```

### API - Instant Quote

```javascript
// POST /api/v1/quotes
{
  origin: { lat: 38.7742, lng: -9.1342 },
  destination: { lat: 38.7223, lng: -9.1393 },
  service_type: "private",
  passengers: 2,
  luggage: 3,
  pickup_time: "2025-11-10T15:00:00Z",
  accessibility: ["child_seat"]
}

// Sistema calcula:
// ├─ Distance: 15km (GraphHopper API)
// ├─ Duration: 25min
// ├─ Vehicle required: sedan4 (2 pax + 3 luggage)
// ├─ Pricing model: dynamic
// │  ├─ Base: €15
// │  ├─ Distance: 15km * €1.50 = €22.50
// │  ├─ Child seat: +€10
// │  └─ Total: €47.50
// │
// └─ Vehicle options:
//    ├─ sedan4: €47.50
//    └─ van7 (upgrade): €55.00

// Response:
{
  quote_id: "Q-67890",
  distance_km: 15,
  duration_minutes: 25,
  pricing: {
    base: 15,
    distance: 22.50,
    surcharges: 10,
    total: 47.50,
    currency: "EUR"
  },
  vehicle_options: [
    { class: "sedan4", price: 47.50 },
    { class: "van7", price: 55.00 }
  ],
  valid_until: "2025-11-09T15:00:00Z"
}
```

---

## 🔄 13. POLÍTICAS DE NO-SHOW

### Para Negócio 📊
No-show acontece quando passageiro não aparece no pickup. Cada agência tem política própria:
- Quanto tempo esperar
- Quanto cobrar (0%, 50%, 100%)
- Protocolo de contacto

### Estrutura

```javascript
AGENCY_NO_SHOW_POLICY = {
  agency_id: UUID, // FK
  wait_time_minutes: Integer, // Quanto tempo driver espera
  
  charge_policy: {
    type: Enum, // "full_charge" | "partial_charge" | "no_charge" | "custom"
    percentage: Integer, // se partial (ex: 50, 75)
  },
  
  driver_protocol: [ // sequência de ações
    { time: 5, action: "call_passenger" },
    { time: 15, action: "call_passenger" },
    { time: 25, action: "call_agency" },
    { time: 30, action: "mark_no_show" }
  ]
}
```

~~### Exemplos de Políticas

**Agency #1 (Premium Travel)**
```
wait_time: 30 minutos
charge: 100% (full)
protocol:
├─ T+5min: Ligar ao passageiro
├─ T+15min: Ligar ao passageiro (2ª vez)
├─ T+25min: Ligar à agência
└─ T+30min: Marcar no-show se sem resposta
```

**Agency #2 (Budget Tours)**
```
wait_time: 15 minutos
charge: 50% (partial)
protocol:
├─ T+5min: Ligar ao passageiro
└─ T+15min: Marcar no-show se sem resposta
```

**Direct Booking (default)**
```
wait_time: 20 minutos
charge: Custom (operator decide)
protocol:
├─ T+5min: Ligar ao passageiro
└─ Escalar para operations imediatamente
```

### Implementação - Flow

```
Transfer #789
├─ booking_source: Agency #1
├─ no_show_policy: agency_1_policy
│
At pickup time:
├─ T+0: Driver chega ao local
├─ Passageiro não aparece
│
Sistema inicia protocolo:
├─ T+5min: App instrui driver: "Call passenger"
│  └─ Driver faz chamada, sem resposta
│
├─ T+15min: App instrui: "Call passenger again"
│  └─ Driver faz 2ª chamada, sem resposta
│
├─ T+25min: App instrui: "Call agency"
│  └─ Driver liga à agência, sem alternativa
│
└─ T+30min: Sistema marca automaticamente:
   ├─ Status: no_show
   ├─ Charge: 100% (€47.50)
   ├─ Driver released (disponível)
   ├─ Invoice gerado
   └─ Notificações enviadas
```

---~~
# BREAK

## 🔄 14. CANCELLATION & REFUND POLICIES (Tenant Based)

### Para Negócio 📊
Políticas de cancelamento baseadas em tempo:
- Mais cedo = menos penalização
- Última hora = penalização total
- Force majeure = reembolso total

### Time-based Cancellation Tiers

```
CANCELLATION POLICY (Standard)

├─ > 48h antes: 100% refund (sem penalização)
├─ 48h - 24h: 50% refund (50% penalty)
├─ 24h - 12h: 25% refund (75% penalty)
├─ < 12h: 0% refund (100% penalty)
└─ After pickup time: No refund

EXCEPTIONS (Force Majeure):
├─ Flight cancelled (airline confirmation required)
├─ Medical emergency (doctor's note)
├─ Natural disaster
├─ Government restrictions
└─ → 100% refund OR reschedule free
```

### Refund Calculation

```javascript
function calculateRefund(transfer, cancellation_time) {
  const hours_until_pickup = (transfer.pickup_time - cancellation_time) / 3600;
  const original_price = transfer.pricing.total;
  
  let refund_percentage;
  
  if (hours_until_pickup > 48) {
    refund_percentage = 100;
  } else if (hours_until_pickup > 24) {
    refund_percentage = 50;
  } else if (hours_until_pickup > 12) {
    refund_percentage = 25;
  } else {
    refund_percentage = 0;
  }
  
  // Check force majeure
  if (cancellation.reason === "force_majeure" && cancellation.proof_provided) {
    refund_percentage = 100;
  }
  
  return {
    refund_amount: original_price * (refund_percentage / 100),
    penalty_amount: original_price * ((100 - refund_percentage) / 100),
    refund_percentage: refund_percentage,
  };
}
```

### Road-show Partial Cancellation

```
Road-show com 4 legs:
├─ Leg 1: Airport → Hotel (€35)
├─ Leg 2: Hotel → Meeting (€25)
├─ Leg 3: Meeting → Restaurant (€20)
└─ Leg 4: Restaurant → Airport (€40)
Total: €120

Cliente cancela Leg 3 (48h antes):
├─ Leg 3: €20 → 100% refund = €20
├─ Legs restantes: mantém
├─ Wait time: pode reduzir (menos 1 leg)
└─ Total novo: €100

Sistema:
├─ Recalcula pricing
├─ Ajusta allocation se necessário
└─ Notifica todos stakeholders
```

### Refund Processing Methods

```
REFUND METHODS (by payment method)

CREDIT CARD:
├─ Processing time: 5-10 business days
├─ Method: Automatic reversal
└─ Fee: None

BANK TRANSFER:
├─ Processing time: 2-3 business days
├─ Method: Manual transfer
└─ Fee: None (absorbed by operator)

ACCOUNT CREDIT (B2B):
├─ Processing time: Immediate
├─ Method: Credit to agency balance
└─ Fee: None
└─ Note: Can be used for future bookings

CASH:
├─ Processing time: On-site or next visit
├─ Method: Cash return
└─ Fee: None
```

---

## 📊 15. SISTEMA DE COMUNICAÇÃO

### Stakeholders

```
1. AGÊNCIA / operadora (B2B)
   ├─ Channels: API webhooks, email, portal
   ├─ Priority: Real-time updates
   └─ SLA: < 1min latência

2. PASSAGEIRO DIRETO (B2C)
   ├─ Channels: SMS, email, WhatsApp, push
   ├─ Priority: Critical updates only
   └─ Custo: Minimizar SMS (usar email quando possível)

3. DRIVER
   ├─ Channels: App móvel, SMS fallback
   ├─ Priority: Todas updates
   └─ Two-way: Driver pode responder/confirmar

4. OPERATIONS TEAM
   ├─ Channels: Dashboard, email, Slack/Teams
   ├─ Priority: Conflicts, emergencies
   └─ Requires action: Yes
```

### Eventos que Geram Notificação

#### 1. BOOKING CONFIRMADO
```
Quando: Reserva criada e validada

Agência:
├─ Webhook: POST /agency/webhook { event: "booking.created", ... }
└─ Email: Confirmação com PDF

Passageiro:
├─ Email: "Reserva confirmada #BK-12345"
└─ SMS: "Transfer confirmado para 10-Nov 15:00"

Driver: (ainda não)
```

#### 2. ALLOCATION CONFIRMADA (T-24h)
```
Quando: Veículo + driver atribuídos

Agência:
└─ Webhook: booking.allocated

Passageiro:
└─ Email: "Seu transfer foi agendado"
   ├─ Driver: João Silva
   ├─ Vehicle: Mercedes E-Class, ABC-12-34
   ├─ Photo: [driver_photo.jpg]
   └─ Contact: +351 912 345 678

Driver:
└─ App notification: "Novo transfer atribuído"
   └─ Action required: Confirm acceptance
```

#### 3. MUDANÇA SIGNIFICATIVA (>15min)
```
Quando: Timing muda devido a voo, tráfego, etc

Agência:
└─ Webhook: booking.updated (immediate)

Passageiro:
├─ SMS: "⚠️ Pickup atrasado 30min. Novo horário: 15:30"
└─ Email: Detalhes completos

Driver:
├─ App alert: "Transfer #123 adiado para 15:30"
└─ SMS backup: (se app offline)
```

#### 4. CONFLITO DETECTADO
```
Quando: Allocation problem identificado

Operations:
├─ Dashboard: 🔴 Alert banner
├─ Email: "URGENTE: Conflito em Transfer #456"
└─ Slack: @ops-team "Allocation conflict needs resolution"

NÃO notificar:
└─ Cliente (aguardar resolução)

DRIVER EVENT: Actualizar informacao.
```

### Webhooks (B2B)

**Estrutura Padrão:**

```http
POST https://agency.com/webhooks/transfers

Headers:
├─ X-Webhook-Signature: HMAC-SHA256(payload, secret)
└─ Content-Type: application/json

Payload:
{
  "event": "booking.updated",
  "timestamp": "2025-11-10T14:23:45Z",
  "booking_reference": "BK-12345",
  "data": {
    "status": "allocated",
    "driver": {
      "name": "João Silva",
      "phone": "+351912345678",
      "vehicle": "Mercedes E-Class ABC-12-34"
    },
    "timing": {
      "scheduled_pickup": "2025-11-10T15:00:00Z",
      "estimated_pickup": "2025-11-10T15:30:00Z",
      "reason": "flight_delay"
    }
  }
}

Response esperado:
├─ 200 OK: Webhook recebido
├─ 4xx/5xx: Retry com backoff exponencial
└─ Retry attempts: 3x (1min, 5min, 15min)
```

**Eventos suportados:**
- `booking.created`
- `booking.allocated`
- `booking.updated`
- `booking.started`
- `booking.completed`
- `booking.cancelled`
- `booking.no_show`

---

# PARTE IV - OPERAÇÕES E QUALIDADE

## 🔄 16. USER MANAGEMENT & RBAC

### Para Negócio 📊
Sistema de permissões baseado em funções (roles):
- Admin vê tudo, faz tudo
- Manager gere operações
- Dispatcher apenas aloca transfers
- Finance apenas vê faturação
- Etc.

### Roles Predefinidas

```
1. ADMIN (Super User)
   ├─ All permissions
   ├─ User management
   ├─ System settings
   └─ Audit logs

2. MANAGER (Operations Manager)
   ├─ View all transfers
   ├─ Manual allocation
   ├─ Override automatic decisions
   ├─ Driver & vehicle management
   └─ Reports & analytics

3. DISPATCHER
   ├─ View transfers
   ├─ Manual allocation
   ├─ Driver communication
   └─ Real-time monitoring

4. FINANCE
   ├─ View invoices
   ├─ Payment processing
   ├─ Financial reports
   └─ Agency credit management

5. SUPPORT
   ├─ View bookings
   ├─ Customer communication
   ├─ Issue resolution
   └─ Limited editing (with approval)

6. VIEWER (Read-only)
   ├─ View transfers
   ├─ View reports
   └─ No editing

7. DRIVER (Mobile App)
   ├─ View assigned transfers
   ├─ Update status
   ├─ Report issues
   └─ Earnings tracking
```

### Permission Matrix

```
PERMISSION                      ADMIN  MANAGER  DISPATCH  FINANCE  SUPPORT  VIEWER
────────────────────────────────────────────────────────────────────────────────
Create booking                    ✓      ✓        ✓         -        ✓       -
View all bookings                 ✓      ✓        ✓         ✓        ✓       ✓
Edit booking                      ✓      ✓        ✓         -        ✓       -
Cancel booking                    ✓      ✓        ✓         -        ⚠️       -
Delete booking                    ✓      -        -         -        -       -
Manual allocation                 ✓      ✓        ✓         -        -       -
Override automatic allocation     ✓      ✓        -         -        -       -
View financials                   ✓      ✓        -         ✓        -       -
Process payments                  ✓      -        -         ✓        -       -
Manage drivers                    ✓      ✓        -         -        -       -
Manage vehicles                   ✓      ✓        -         -        -       -
View reports                      ✓      ✓        ✓         ✓        ✓       ✓
Export data                       ✓      ✓        -         ✓        -       -
User management                   ✓      -        -         -        -       -
System settings                   ✓      -        -         -        -       -

Legend: ✓ = Yes, - = No, ⚠️ = With approval
```

### 2FA & SSO

```
AUTHENTICATION OPTIONS

1. USERNAME/PASSWORD
   ├─ Minimum complexity requirements
   ├─ Password expiry: 90 days
   └─ 2FA: Optional but recommended

2. TWO-FACTOR AUTHENTICATION (2FA)
   ├─ SMS code
   ├─ Authenticator app (Google, Microsoft)
   └─ Required for: Admin, Finance roles

3. SINGLE SIGN-ON (SSO)
   ├─ Google Workspace
   ├─ Microsoft Azure AD
   ├─ Okta
   └─ SAML 2.0 support

4. API KEY AUTHENTICATION (for integrations)
   ├─ API key + secret
   ├─ IP whitelist
   └─ Rate limiting
```

---

## 🔄 17. RATINGS & REVIEW SYSTEM

### Overview
Sistema bidirectional - passageiro avalia driver, driver avalia passageiro.

### Rating Entity

```javascript
RATING = {
  id: UUID,
  transfer_id: UUID, // FK
  
  // BIDIRECTIONAL
  rating_type: Enum, // "passenger_rates_driver" | "driver_rates_passenger"
  
  // PASSENGER RATES DRIVER
  driver_rating: {
    overall_score: Integer, // 1-5
    detailed_scores: {
      punctuality: Integer, // 1-5
      vehicle_condition: Integer,
      professionalism: Integer,
      driving_skill: Integer,
      comfort: Integer,
    },
    review_text: Text,
    would_recommend: Boolean,
  },
  
  // DRIVER RATES PASSENGER
  passenger_rating: {
    overall_score: Integer, // 1-5
    detailed_scores: {
      punctuality: Integer,
      politeness: Integer,
      cleanliness: Integer, // deixou carro limpo?
     
    },
    review_text: Text,
    issues: Array, // ["no_show", "late", "rude", "damaged_vehicle"]
  },
  
  // METADATA
  created_at: DateTime,
  is_public: Boolean, // exibir publicamente?
  is_verified: Boolean, // transfer completado com sucesso?
  
  // MODERATION
  moderation_status: Enum, // "pending" | "approved" | "rejected" | "flagged"
  moderation_reason: Text,
  moderated_by: UUID,
  moderated_at: DateTime,
}
```

### Driver Performance Dashboard

```
DRIVER: João Silva
───────────────────────────────────────

Overall Rating: ⭐ 4.8 / 5.0
Total Transfers: 456
Total Reviews: 342

Detailed Breakdown:
├─ Punctuality:      4.9 ⭐⭐⭐⭐⭐
├─ Vehicle:          4.7 ⭐⭐⭐⭐⭐
├─ Professionalism:  4.9 ⭐⭐⭐⭐⭐
├─ Driving:          4.8 ⭐⭐⭐⭐⭐
└─ Comfort:          4.6 ⭐⭐⭐⭐

Recent Reviews:
├─ "Excellent service, very professional!" - ⭐⭐⭐⭐⭐
├─ "On time, clean car, friendly driver" - ⭐⭐⭐⭐⭐
├─ "Good but car could be cleaner" - ⭐⭐⭐⭐
└─ "Perfect!" - ⭐⭐⭐⭐⭐

Trends:
├─ Rating improving: +0.2 (last 30 days)
└─ 98% would recommend
```

### Review Moderation

```
MODERATION WORKFLOW

1. AUTOMATIC FLAGS
   ├─ Contains profanity → flag
   ├─ < 10 words → flag as "too short"
   ├─ All caps → flag as "shouting"
   └─ Rating 1-2 without text → require explanation

2. MANUAL REVIEW
   ├─ Operations team reviews flagged
   ├─ Can approve, reject, or edit
   └─ Reason documented

3. RESPONSE SYSTEM
   ├─ Driver can respond to reviews
   ├─ Manager can respond on behalf
   └─ Publicly visible

4. DISPUTE PROCESS
   ├─ Driver can dispute unfair review
   ├─ Evidence collected (GPS, photos)
   ├─ Final decision by manager
   └─ Review hidden if dispute successful
```

---

~~## 📊 18. EMERGENCY PROTOCOLS

### Types of Emergencies

```
1. ACCIDENT
   Severity: CRITICAL
   ├─ Driver triggers SOS in app
   ├─ System alerts: operations, emergency services
   ├─ Collect: location, photos, police report
   └─ Action: Immediate alternative transport

2. VEHICLE BREAKDOWN
   Severity: HIGH
   ├─ Driver reports via app
   ├─ System checks: nearby available vehicles
   ├─ Option A: Send replacement vehicle
   └─ Option B: Arrange tow + refund

3. DRIVER ILLNESS
   Severity: HIGH
   ├─ Driver reports unavailability
   ├─ System: Immediate reallocation
   └─ Notify affected passengers

4. PASSENGER NO-SHOW (after policy)
   Severity: MEDIUM
   ├─ Follow no-show policy
   ├─ Release driver
   └─ Process charges

5. SEVERE WEATHER
   Severity: VARIES
   ├─ Monitor weather APIs
   ├─ Proactive notifications
   ├─ Offer rescheduling
   └─ Free cancellation if force majeure

6. FORCE MAJEURE (flight cancelled, etc)
   Severity: MEDIUM
   ├─ Verify with official sources
   ├─ Free cancellation or reschedule
   └─ No penalties
```

### Escalation Hierarchy

```
LEVEL 1: DRIVER
├─ Handles minor issues
├─ Reports via app
└─ Escalates if needed

LEVEL 2: DISPATCHER
├─ Monitors in real-time
├─ Handles allocation issues
├─ Reallocates if conflicts
└─ Escalates critical issues

LEVEL 3: OPERATIONS MANAGER
├─ Handles escalated issues
├─ Makes executive decisions
├─ Customer compensation
└─ Escalates legal/safety

LEVEL 4: SENIOR MANAGEMENT
├─ Legal issues
├─ Major incidents
├─ PR crises
└─ Insurance claims
```

### Emergency Contact Chain

```
EMERGENCY CONTACTS (per transfer)

Primary: Passenger phone
├─ Call attempts: 3
├─ SMS if no answer
└─ Escalate if no response

Secondary: Booking source
├─ If agency: Call agency contact
├─ If direct: Call alternative contact
└─ Email notification

Tertiary: Emergency contact (if provided)
├─ Family member or colleague
└─ Last resort

Operations Team:
├─ Always notified
├─ Dashboard alert
└─ Decision authority
```

### SOS Button (Driver App)

```
DRIVER SOS FLOW

1. Driver presses SOS button
2. App captures:
   ├─ Current GPS location
   ├─ Transfer details
   ├─ Photos (optional, 3 max)
   └─ Audio recording (30sec)

3. System IMMEDIATELY:
   ├─ Alerts operations team (push + SMS + call)
   ├─ Logs incident
   ├─ Sends location to emergency services (optional)
   └─ Freezes transfer status

4. Operations team:
   ├─ Calls driver within 60 seconds
   ├─ Assesses situation
   ├─ Decides action:
   │  ├─ Send help
   │  ├─ Send replacement vehicle
   │  ├─ Call police/ambulance
   │  └─ Arrange alternative transport
   └─ Updates all stakeholders

5. Post-incident:
   ├─ Incident report generated
   ├─ Insurance notified if needed
   ├─ Review and analysis
   └─ Update protocols if needed
```

---~~

# BREAK

## 🔄 19. SLA MANAGEMENT

### Key Metrics

```
1. RESPONSE TIME
   Target: < 15 minutes
   ├─ Time from booking received to acknowledgement
   └─ Applies to: API, email, portal bookings

2. ALLOCATION TIME
   Target: < 24 hours
   ├─ Time from booking to confirmed allocation
   └─ Exception: urgent requests < 4 hours

3. ON-TIME PERFORMANCE
   Target: > 95%
   ├─ Pickup within ±10 minutes of scheduled time
   ├─ Excludes force majeure
   └─ Tracked per agency

4. CUSTOMER SATISFACTION
   Target: > 4.5 / 5.0
   ├─ Average rating from passengers
   └─ Minimum 80% response rate

5. CANCELLATION RATE
   Target: < 5%
   ├─ Operator-initiated cancellations only
   ├─ Excludes customer cancellations
   └─ Penalty if exceeded
```

### Automated Tracking

```
SLA_TRACKING = {
  agency_id: UUID,
  period: "monthly" | "weekly",
  
  metrics: {
    response_time: {
      target: 15, // minutes
      actual_avg: 12,
      compliance: 98%, // % within target
      breaches: 3, // count
    },
    
    allocation_time: {
      target: 24, // hours
      actual_avg: 18,
      compliance: 99%,
      breaches: 1,
    },
    
    on_time_performance: {
      target: 95, // %
      actual: 97,
      total_transfers: 145,
      on_time: 141,
      late: 4,
    },
    
    satisfaction: {
      target: 4.5,
      actual: 4.7,
      responses: 120,
      response_rate: 83%,
    },
    
    cancellation_rate: {
      target: 5, // %
      actual: 2,
      total_transfers: 145,
      cancelled_by_operator: 3,
    },
  },
  
  overall_compliance: 98%, // weighted average
  status: "compliant" | "warning" | "breach",
}
```

### Breach Alerts

```
ALERT TRIGGERS

WARNING (Yellow):
├─ Any metric 80-90% of target
├─ Action: Notify operations team
└─ Response: Monitor closely

BREACH (Red):
├─ Any metric < 80% of target
├─ Action: Immediate escalation
├─ Response: Corrective action plan
└─ Penalty may apply (per contract)

AUTOMATIC ACTIONS:
├─ Daily SLA report generated
├─ Weekly summary to management
├─ Monthly invoice adjustment (if penalties)
└─ Quarterly review meeting (if premium agency)
```

### Penalty/Bonus System

```
PENALTIES (if SLA breached)

On-time < 95%:
├─ 95-90%: Warning only
├─ 90-85%: 5% discount next invoice
├─ 85-80%: 10% discount
└─ < 80%: 20% discount + escalation

Response time > 15min:
├─ Per breach: €50 credit
└─ Max: €500/month

BONUSES (if SLA exceeded)

On-time > 98%:
├─ Bonus: €500
└─ Priority allocation next month

Satisfaction > 4.8:
├─ Bonus: €300
└─ Featured as "Premium Service"

Zero breaches:
├─ Bonus: €1000
└─ Certificate of Excellence
```

---

## 💻 20. MOBILE DRIVER APP

### Core Features

```
DRIVER APP FEATURES

1. TODAY'S SCHEDULE
   ├─ List of assigned transfers
   ├─ Timeline view
   ├─ Color-coded by status
   └─ Swipe to see details

2. TRANSFER DETAILS
   ├─ Passenger name & photo
   ├─ Pickup/dropoff locations
   ├─ Scheduled times
   ├─ Special requirements
   ├─ Contact passenger (call/SMS)
   └─ Navigation (integrated)

3. STATUS UPDATES
   ├─ "On my way" (auto-triggers notification)
   ├─ "Arrived at pickup"
   ├─ "Passenger picked up"
   ├─ "Arrived at destination"
   └─ "Transfer completed"

4. NAVIGATION
   ├─ Integrated Google Maps / Waze
   ├─ Real-time traffic
   ├─ Alternative routes
   └─ Offline maps (downloaded)

5. COMMUNICATION
   ├─ Call passenger (masked number)
   ├─ Call operations
   ├─ In-app chat
   └─ SOS button (emergency)

6. ISSUE REPORTING
   ├─ Vehicle defect
   ├─ Passenger no-show
   ├─ Accident
   ├─ Traffic delay
   └─ Other (with photo)

7. EARNINGS TRACKING
   ├─ Today's earnings
   ├─ Week/month totals
   ├─ Transfer breakdown
   └─ Payment history

8. VEHICLE INSPECTION
   ├─ Pre-shift checklist
   ├─ Photo documentation
   ├─ Report issues
   └─ Required before first transfer
```

### Offline Mode ⚠️ CRITICAL

```
OFFLINE CAPABILITIES (essential!)

Driver may not always have internet:
├─ Airport parking garages
├─ Rural areas
├─ Network congestion
└─ Tunnel routes

MUST WORK OFFLINE:
├─ View today's schedule
├─ View transfer details
├─ Navigation (with downloaded maps)
├─ Mark status updates (queued for sync)
└─ Take photos (upload when online)

SYNC WHEN ONLINE:
├─ Upload status updates
├─ Upload photos
├─ Download new transfers
├─ Update GPS location
└─ Receive notifications

IMPLEMENTATION:
├─ Local SQLite database
├─ Service Worker (PWA)
├─ Background sync
└─ Conflict resolution (last-write-wins)
```

### UI/UX Principles

```
DESIGN FOR DRIVERS

1. LARGE TOUCH TARGETS
   ├─ Minimum 44x44pt buttons
   └─ Easy to tap while driving (passenger does it)

2. MINIMAL TEXT INPUT
   ├─ Pre-filled forms
   ├─ Dropdown selections
   ├─ Voice input option
   └─ Quick actions

3. GLANCEABLE INFO
   ├─ Large fonts
   ├─ High contrast
   ├─ Color coding
   └─ Icons > text

4. ONE-HANDED USE
   ├─ Bottom navigation
   ├─ Thumb-friendly layout
   └─ Swipe gestures

5. NOTIFICATIONS
   ├─ Sound + vibration
   ├─ Heads-up display
   ├─ Critical info only
   └─ Not while driving!
```

---

## 📊 21. CUSTOMER PORTAL (B2C)

### Features

```
CUSTOMER PORTAL

1. ACCOUNT MANAGEMENT
   ├─ Profile editing
   ├─ Saved addresses
   ├─ Payment methods
   ├─ Preferences
   └─ Notification settings

2. NEW BOOKING
   ├─ Step 1: Service type
   ├─ Step 2: Route (from/to)
   ├─ Step 3: Date/time
   ├─ Step 4: Passengers & luggage
   ├─ Step 5: Vehicle selection
   ├─ Step 6: Review & pay
   └─ Confirmation

3. MY BOOKINGS
   ├─ Upcoming transfers
   ├─ Past transfers
   ├─ Filters (date, status)
   └─ Quick actions (modify, cancel)

4. LIVE TRACKING
   ├─ Real-time map
   ├─ Driver location
   ├─ ETA countdown
   └─ Driver contact

5. INVOICES & RECEIPTS
   ├─ Download PDF
   ├─ Email copy
   ├─ Payment history
   └─ Tax information

6. SUPPORT
   ├─ FAQ
   ├─ Live chat
   ├─ Submit ticket
   └─ Phone support (business hours)
```

### Booking Wizard

```
STEP 1: SERVICE TYPE
┌────────────────────────────────┐
│ Choose your service:           │
│                                │
│ [🚗 Private Transfer]           │
│ Just you, direct route         │
│ From €35                       │
│                                │
│ [🚐 Shared Shuttle]             │
│ Share with others, save money  │
│ From €15                       │
│                                │
│ [🎭 Road-show]                  │
│ Multiple stops, same day       │
│ Custom quote                   │
└────────────────────────────────┘

STEP 2: ROUTE
┌────────────────────────────────┐
│ From: [Lisbon Airport ▼]       │
│       Arrival flight? [Yes][No]│
│       Flight: [TP1234____]     │
│                                │
│ To:   [Hotel Ibis_______ ▼]    │
│                                │
│ [📍 Use saved location]         │
│ [🔄 Swap]                       │
└────────────────────────────────┘

STEP 3: DATE & TIME
┌────────────────────────────────┐
│ 📅 Date: [2025-11-10 ▼]        │
│ 🕐 Time: [15:00 ▼]             │
│                                │
│ ℹ️ Pickup time is when driver    │
│   arrives (not flight arrival) │
└────────────────────────────────┘

STEP 4: DETAILS
┌────────────────────────────────┐
│ Passengers: [2 ▼]              │
│ Luggage: [3 ▼]                 │
│                                │
│ Special requirements:          │
│ [✓] Child seat (6 months)      │
│ [ ] Wheelchair accessible      │
│ [ ] Baby seat                  │
│                                │
│ Notes: [____________]          │
└────────────────────────────────┘

STEP 5: VEHICLE SELECTION
┌────────────────────────────────┐
│ 🚗 Sedan (up to 4 pax)          │
│    €47.50                      │
│    [Select]                    │
│                                │
│ 🚐 Van (up to 7 pax) [UPGRADE] │
│    €55.00 (+€7.50)             │
│    [Select]                    │
└────────────────────────────────┘

STEP 6: REVIEW & PAY
┌────────────────────────────────┐
│ BOOKING SUMMARY                │
│                                │
│ From: Lisbon Airport           │
│ To: Hotel Ibis                 │
│ Date: 10 Nov 2025, 15:00       │
│ Passengers: 2                  │
│ Vehicle: Sedan                 │
│                                │
│ Base fare:        €35.00       │
│ Distance (15km):  €22.50       │
│ Child seat:       €10.00       │
│ ────────────────────────       │
│ TOTAL:            €47.50       │
│                                │
│ [💳 Pay with Card]              │
│ [🏦 Bank Transfer]              │
│ [💰 Pay Driver (Cash)]          │
└────────────────────────────────┘
```

---

## 💻 22. SCHEDULING & VISUAL PLANNING (Bryntum)

### Overview
Interface visual para operações - ver e gerir todos transfers num timeline.

### Bryntum Scheduler Integration

```
BRYNTUM FEATURES USED

1. GANTT VIEW
   ├─ X-axis: Time (hours/days)
   ├─ Y-axis: Resources (drivers + vehicles)
   ├─ Bars: Transfers (color-coded)
   └─ Drag & drop: Manual allocation

2. CALENDAR VIEW
   ├─ Day/Week/Month views
   ├─ Filter by service type
   ├─ Filter by status
   └─ Search

3. DRAG & DROP ALLOCATION
   ├─ Drag transfer to driver
   ├─ System validates constraints
   ├─ Shows conflicts in real-time
   └─ Confirms allocation

4. COLOR CODING
   ├─ Green: Allocated & confirmed
   ├─ Yellow: Allocated pending confirmation
   ├─ Red: Conflict / unallocated
   ├─ Blue: In progress
   ├─ Grey: Completed
   └─ Orange: Delayed / issue

5. FILTERS
   ├─ By date range
   ├─ By driver
   ├─ By vehicle
   ├─ By service type
   ├─ By status
   └─ By agency

6. CONFLICT DETECTION
   ├─ Overlapping transfers
   ├─ Driver shift violations
   ├─ Vehicle double-booking
   └─ Visual red flags
```

### Timeline Views

**DAY VIEW (most detailed)**
```
TIME      DRIVER JOÃO        DRIVER MARIA       DRIVER PEDRO
────────────────────────────────────────────────────────────
08:00     ──────────────────
09:00     [Transfer #123]    
10:00     ──────────────────  ────────────────── ──────────────────
11:00                        [Transfer #124]    
12:00                        ──────────────────
13:00     [BREAK]            [BREAK]            [Transfer #125]
14:00     ──────────────────  ────────────────── ──────────────────
15:00     [Transfer #126]                       [Transfer #127]
16:00     ──────────────────                    ──────────────────
17:00                        [Transfer #128]
18:00                        ──────────────────
```

**WEEK VIEW (overview)**
```
         MON    TUE    WED    THU    FRI    SAT    SUN
João     ████   ████   ████   ████   ████   ███    OFF
Maria    ████   ████   ████   ████   ████   OFF    OFF
Pedro    ███    ████   ████   ████   ████   ████   ███
```

### Real-time Updates

```
WEBSOCKET INTEGRATION

Driver updates status in app:
  ↓
Backend WebSocket broadcasts:
  ↓
Bryntum Scheduler auto-updates:
├─ Transfer bar changes color
├─ Timeline adjusts if delayed
└─ Notifications to operations team

ALL USERS see same state in real-time!
```

---

# PARTE V - INTEGRAÇÕES E SISTEMAS

## 💻 23. INTEGRATION ECOSYSTEM

### External Services Matrix

```
CATEGORY: FLIGHT TRACKING
├─ FlightAware (primary)
│  ├─ Coverage: Global
│  ├─ Real-time: Yes
│  ├─ Cost: $$$
│  └─ API: REST
│
├─ AviationStack (secondary)
│  ├─ Coverage: Good
│  ├─ Real-time: Limited
│  ├─ Cost: $ (free tier available)
│  └─ API: REST
│
└─ FlightStats
   ├─ Coverage: Excellent
   ├─ Real-time: Yes
   ├─ Cost: $$$$
   └─ API: REST

CATEGORY: PAYMENTS
├─ Stripe (primary)
│  ├─ Cards, bank transfers, wallets
│  ├─ Multi-currency
│  ├─ Best documentation
│  └─ Webhooks for events
│
├─ PayPal
│  ├─ Popular with consumers
│  ├─ Supports credit accounts
│  └─ Higher fees
│
└─ Square
   ├─ Good for in-person (cash)
   └─ North America focused

CATEGORY: ACCOUNTING
├─ Xero
│  ├─ Popular in UK/AU/NZ
│  ├─ Excellent API
│  └─ Auto-sync invoices
│
├─ QuickBooks
│  ├─ Popular in US
│  └─ API available
│
└─ Sage
   ├─ Popular in Europe
   └─ Legacy but widely used

CATEGORY: COMMUNICATION
├─ Twilio (SMS)
│  ├─ Global coverage
│  ├─ Reliable
│  └─ Pay-per-SMS
│
├─ SendGrid (Email)
│  ├─ Transactional emails
│  ├─ Templates
│  └─ Analytics
│
└─ WhatsApp Business API
   ├─ Very popular
   ├─ Rich media support
   └─ Requires approval

CATEGORY: MAPPING & ROUTING
├─ Google Maps (premium)
│  ├─ Best data quality
│  ├─ Real-time traffic
│  └─ Expensive
│
├─ GraphHopper (free tier)
│  ├─ 2500 requests/day free
│  ├─ Good routing
│  └─ No real-time traffic (free)
│
├─ OSRM (self-hosted)
│  ├─ 100% free
│  ├─ OpenStreetMap data
│  └─ Self-hosted overhead
│
└─ Mapbox
   ├─ 100,000 requests/month free
   └─ Good balance

CATEGORY: WEATHER
├─ OpenWeatherMap
│  ├─ Free tier available
│  ├─ 5-day forecast
│  └─ Current conditions
│
└─ Tomorrow.io
   ├─ Hyperlocal
   ├─ Minute-by-minute
   └─ $$

INTEGRATION PRIORITIES:
1. Payment gateways (CRITICAL)
2. SMS/Email (CRITICAL)
3. Flight tracking (HIGH)
4. Accounting (MEDIUM)
5. CRM (LOW - nice to have)
```

### Webhook Architecture

```
INCOMING WEBHOOKS (we receive)

Flight Status Updates:
POST /webhooks/flights
{
  "flight": "TP1234",
  "status": "delayed",
  "new_arrival": "2025-11-10T15:45:00Z",
  "delay_minutes": 45
}

Action:
├─ Find transfers with this flight
├─ Recalculate pickup times
├─ Notify all stakeholders
└─ Update Bryntum timeline


OUTGOING WEBHOOKS (we send)

To Agency:
POST https://agency.com/webhooks/transfers
{
  "event": "booking.allocated",
  "booking_reference": "BK-12345",
  "driver": {...},
  "vehicle": {...}
}

Retry logic:
├─ Attempt 1: immediate
├─ Attempt 2: +1 minute
├─ Attempt 3: +5 minutes
├─ Attempt 4: +15 minutes
└─ Give up: Log failure + notify
```

---

## 💻 24. REPORTING & ANALYTICS

### Report Categories

```
1. OPERATIONAL REPORTS
   ├─ Daily operations summary
   ├─ Driver utilization
   ├─ Vehicle utilization
   ├─ On-time performance
   └─ Allocation efficiency

2. FINANCIAL REPORTS
   ├─ Revenue by period
   ├─ Revenue by agency
   ├─ Revenue by service type
   ├─ Cost analysis
   ├─ Profit margins
   └─ Outstanding invoices

3. CUSTOMER REPORTS
   ├─ Agency performance
   ├─ Customer satisfaction
   ├─ Repeat customers
   ├─ Cancellation reasons
   └─ Complaint analysis

4. STRATEGIC REPORTS
   ├─ Market trends
   ├─ Capacity vs demand
   ├─ Growth forecast
   ├─ Competitive analysis
   └─ Expansion opportunities
```

### Example Report: Daily Operations Summary

```
DAILY OPERATIONS SUMMARY
Date: 10 November 2025
────────────────────────────────────────────

TRANSFERS
├─ Total booked: 145
├─ Completed: 142 (97.9%)
├─ Cancelled: 2 (1.4%)
├─ No-show: 1 (0.7%)
└─ In progress: 0

ON-TIME PERFORMANCE
├─ On time (±10min): 138 (97.2%) ✓
├─ Late (>10min): 4 (2.8%)
└─ Average delay: 3.2 minutes

REVENUE
├─ Total: €12,450
├─ Average per transfer: €85.80
├─ Private: €9,200 (74%)
├─ Shuttle: €2,100 (17%)
└─ Road-show: €1,150 (9%)

DRIVERS
├─ Active: 18
├─ Average utilization: 82%
├─ Hours worked: 144h
├─ Overtime: 8h (5.6%)
└─ Top performer: João Silva (12 transfers)

VEHICLES
├─ In service: 16
├─ Maintenance: 2
├─ Utilization: 89%
└─ Total km: 2,456 km

AGENCIES
├─ Active: 8
├─ Top agency: Travel Co (45 transfers)
├─ New bookings: 156
└─ Pending quotes: 12

ISSUES
├─ Vehicle breakdowns: 1
├─ Customer complaints: 0
└─ Driver issues: 0

HIGHLIGHTS
✓ Exceeded on-time target (95%)
✓ Zero customer complaints
⚠ Vehicle #7 needs maintenance
⚠ 2 drivers approaching weekly hour limit
```

### Export Formats

```
SUPPORTED FORMATS

1. PDF
   ├─ Professional layout
   ├─ Charts & graphs
   ├─ Ready to print
   └─ Use case: Management reports

2. Excel (XLSX)
   ├─ Raw data
   ├─ Pivot tables enabled
   ├─ Formulas included
   └─ Use case: Analysis

3. CSV
   ├─ Plain data
   ├─ Easy import
   ├─ No formatting
   └─ Use case: Data migration

4. JSON
   ├─ Machine-readable
   ├─ API integration
   └─ Use case: Automated systems
```

### Scheduling

```
AUTOMATED REPORTS

Daily:
├─ Operations summary (7:00 AM)
├─ Send to: Operations team
└─ Format: Email + PDF

Weekly:
├─ Performance report (Monday 9:00 AM)
├─ Send to: Management
└─ Format: Email + Excel

Monthly:
├─ Financial report (1st of month)
├─ Send to: Finance team
└─ Format: PDF + Excel

Custom:
├─ On-demand via dashboard
├─ Scheduled by user
└─ Multiple recipients
```

---

## 🔄 25. COMPLIANCE & LEGAL (GDPR)

### GDPR Requirements

```
1. DATA COLLECTION
   ├─ Clear consent forms
   ├─ Purpose limitation (why we need it)
   ├─ Minimum data collected
   ├─ Privacy policy visible
   └─ Opt-in (not opt-out)

2. DATA STORAGE
   ├─ EU servers (if EU customers)
   ├─ Encrypted at rest (AES-256)
   ├─ Encrypted in transit (TLS 1.3)
   ├─ Access logs maintained
   └─ Regular backups

3. DATA RIGHTS
   ├─ Right to access (export data)
   ├─ Right to rectification (edit)
   ├─ Right to erasure ("forget me")
   ├─ Right to portability
   └─ Right to object

4. DATA RETENTION
   ├─ Active users: indefinite
   ├─ Inactive users: 2 years
   ├─ Deleted users: 30 days (soft delete)
   ├─ Financial records: 7 years (legal requirement)
   └─ Logs: 90 days

5. BREACH NOTIFICATION
   ├─ Detection: <24h
   ├─ Authority notification: <72h
   ├─ User notification: immediate if high risk
   ├─ Documentation: incident log
   └─ Remediation: immediate action
```

### Data Subject Rights Implementation

```
RIGHT TO ACCESS (Export Data)

User requests: "I want my data"

System exports:
├─ Personal info (JSON)
├─ Booking history (CSV)
├─ Invoices (PDFs)
├─ Communications (emails)
└─ ZIP file sent via email

Timeframe: 30 days


RIGHT TO ERASURE ("Forget Me")

User requests: "Delete my data"

System checks:
├─ Outstanding invoices? → CANNOT delete
├─ Active bookings? → CANNOT delete
└─ Clean history? → OK to delete

If OK:
├─ Soft delete (flagged as deleted)
├─ Data retained 30 days (recovery window)
├─ After 30 days: Hard delete
├─ Exception: Financial records (7 years legal)
└─ Anonymize instead of delete

Timeframe: 30 days


RIGHT TO RECTIFICATION (Edit)

User requests: "My email is wrong"

System:
├─ User edits in portal
├─ OR support team edits
├─ Audit log records change
└─ Confirmation sent

Timeframe: Immediate


RIGHT TO PORTABILITY

User requests: "Export to CSV"

System exports in standard format:
├─ CSV for tabular data
├─ JSON for structured data
└─ Readable by competitors

Timeframe: 30 days


RIGHT TO OBJECT

User requests: "Stop processing for marketing"

System:
├─ Flags account: no_marketing
├─ Suppression list updated
├─ Confirmation sent
└─ Process within 24h

Timeframe: 24 hours
```

### Legal Documents Required

```
REQUIRED DOCUMENTS

1. Terms of Service
   └─ User agreement

2. Privacy Policy
   └─ How we handle data

3. Cookie Policy
   └─ What cookies we use

4. Cancellation Policy (customer-facing)
   └─ Refund terms

5. Refund Policy
   └─ How refunds work

6. Driver Agreement
   └─ Employment/contractor terms

7. Agency Agreement (B2B)
   └─ Commercial terms

8. Insurance Certificates
   └─ Vehicle & liability insurance

9. Business Licenses
   └─ Transport operator license

10. VAT Registration
    └─ Tax compliance

PER REGION:
├─ Portugal: AT certified invoicing, IMT license
├─ Spain: Similar requirements
├─ UK: ICO registration, DVSA license
└─ EU: GDPR DPO (if >250 employees)
```

---

## 💻 26. NOTIFICATION TEMPLATES

### Template System

```javascript
TEMPLATE_STRUCTURE = {
  template_id: UUID,
  template_name: String,
  template_type: Enum, // "email" | "sms" | "whatsapp" | "push" | "in_app"
  
  subject: String, // email only
  body: Text, // supports variables
  
  variables: [ // available variables
    "{{passenger_name}}",
    "{{driver_name}}",
    "{{pickup_time}}",
    "{{pickup_location}}",
    "{{dropoff_location}}",
    "{{vehicle_make}}",
    "{{vehicle_model}}",
    "{{license_plate}}",
    "{{booking_reference}}",
    "{{driver_phone}}",
    "{{tracking_link}}",
    "{{company_name}}",
  ],
  
  languages: {
    en: { subject: "...", body: "..." },
    pt: { subject: "...", body: "..." },
    es: { subject: "...", body: "..." },
    fr: { subject: "...", body: "..." },
  },
  
  triggers: [ // when to send
    "booking_confirmed",
    "driver_assigned",
    "driver_en_route",
    "driver_arrived",
    "transfer_completed",
    "delay_notification",
    "cancellation_confirmed",
  ],
  
  active: Boolean,
  created_at: DateTime,
  updated_at: DateTime,
}
```

### Example Templates

**EMAIL: booking_confirmed**
```
Subject: Transfer Confirmed - {{booking_reference}}

Hello {{passenger_name}},

Your transfer has been confirmed!

Pickup Details:
📅 Date: {{pickup_date}}
🕐 Time: {{pickup_time}}
📍 Location: {{pickup_location}}
🎯 Destination: {{dropoff_location}}

We'll send you driver details 24 hours before your transfer.

[View Booking] [Modify] [Cancel]

Best regards,
{{company_name}}
```

**SMS: driver_assigned**
```
{{driver_name}} will be your driver.
{{vehicle_make}} {{vehicle_model}} - {{license_plate}}
Phone: {{driver_phone}}
Pickup: {{pickup_time}}
Track: {{tracking_link}}
```

**PUSH: delay_notification**
```
⚠️ Delay Update
Your pickup time has been delayed by {{delay_minutes}} minutes.
New time: {{new_pickup_time}}
Reason: {{delay_reason}}
```

**WHATSAPP: driver_en_route**
```
🚗 {{driver_name}} is on the way!

ETA: {{eta_minutes}} minutes
Track in real-time: {{tracking_link}}

Vehicle: {{vehicle_make}} {{vehicle_model}}
License: {{license_plate}}

Need to contact driver?
📞 {{driver_phone}}
```

---

## 🔄 27. DISPUTE & COMPLAINTS MANAGEMENT

### Complaint Workflow

```
1. SUBMISSION
   ├─ Portal form
   ├─ Email to support@
   ├─ Phone call
   └─ Social media

2. CATEGORIZATION (automatic + manual)
   ├─ Service quality (late, rude driver, etc)
   ├─ Billing dispute (wrong charge, etc)
   ├─ Driver behavior (serious)
   ├─ Vehicle condition (dirty, broken, etc)
   ├─ Delay/no-show
   └─ Safety issue (critical!)

3. PRIORITY ASSIGNMENT
   ├─ CRITICAL (safety): immediate response
   ├─ HIGH (billing >€100): 2h response
   ├─ MEDIUM: 24h response
   └─ LOW: 48h response

4. INVESTIGATION
   ├─ Review transfer details (timeline, GPS)
   ├─ Check driver logs
   ├─ Contact driver for statement
   ├─ Review ratings & history
   └─ Collect evidence (photos, recordings)

5. RESOLUTION OPTIONS
   ├─ Full refund
   ├─ Partial refund (50%, 75%)
   ├─ Voucher/credit for future use
   ├─ Formal apology
   └─ No action (complaint unfounded)

6. FOLLOW-UP
   ├─ Resolution email to customer
   ├─ Satisfaction survey
   ├─ Close ticket
   └─ Log for analysis

7. ESCALATION (if not resolved)
   ├─ Level 1: Support agent
   ├─ Level 2: Support manager
   ├─ Level 3: Operations manager
   └─ Level 4: Senior management (serious cases)
```

### Complaint Entity

```javascript
COMPLAINT = {
  id: UUID,
  transfer_id: UUID, // FK
  passenger_id: UUID, // FK
  
  submitted_at: DateTime,
  submitted_via: Enum, // "portal" | "email" | "phone" | "social"
  
  category: Enum,
  // "service_quality" | "billing" | "driver_behavior" | 
  // "vehicle_condition" | "delay" | "safety"
  
  priority: Enum, // "critical" | "high" | "medium" | "low"
  
  description: Text,
  evidence: Array, // URLs to photos, screenshots
  
  investigation: {
    assigned_to: UUID, // support agent
    started_at: DateTime,
    notes: Text,
    driver_statement: Text,
    gps_logs: Object,
    findings: Text,
  },
  
  resolution: {
    type: Enum, 
    // "full_refund" | "partial_refund" | "voucher" | "apology" | "no_action"
    amount: Decimal, // if refund
    voucher_code: String, // if voucher
    resolution_notes: Text,
    resolved_by: UUID,
    resolved_at: DateTime,
  },
  
  status: Enum,
  // "submitted" → "investigating" → "resolved" | "escalated" | "closed"
  
  customer_satisfaction: Integer, // 1-5, post-resolution survey
  
  created_at: DateTime,
  updated_at: DateTime,
}
```

### Escalation Matrix

```
COMPLAINT ESCALATION

LEVEL 1: Support Agent
├─ Handle: routine complaints
├─ Authority: refunds up to €50
├─ Timeframe: 24h
└─ Escalate if: complex, high-value, safety

LEVEL 2: Support Manager
├─ Handle: complex issues
├─ Authority: refunds up to €200
├─ Timeframe: 48h
└─ Escalate if: safety, legal threat, PR risk

LEVEL 3: Operations Manager
├─ Handle: operational issues
├─ Authority: refunds up to €500
├─ Timeframe: 72h
└─ Escalate if: serious safety, legal action

LEVEL 4: Senior Management
├─ Handle: critical issues
├─ Authority: unlimited
├─ Timeframe: immediate
└─ Examples: accidents, lawsuits, media crisis
```

---

## 🔄 28. QUOTATION MANAGEMENT

### Quote States & Lifecycle

```
QUOTE LIFECYCLE

1. DRAFT
   ├─ Created by operator/auto-generated
   ├─ Not yet sent to customer
   ├─ Can be edited freely
   └─ No expiry yet

2. SENT
   ├─ Emailed to customer
   ├─ Quote URL active
   ├─ Expires in 7 days (configurable)
   ├─ Can still be modified (creates new version)
   └─ Tracking: email opened?

3. VIEWED
   ├─ Customer opened quote link
   ├─ Tracking pixel fired
   ├─ Timestamp recorded
   └─ Follow-up triggered after 24h

4. ACCEPTED
   ├─ Customer accepts online or via email
   ├─ Auto-convert to booking
   ├─ Payment link sent (if required)
   └─ Quote archived

5. REJECTED
   ├─ Customer declined
   ├─ Reason collected (optional form)
   ├─ Quote archived
   └─ Statistics updated

6. EXPIRED
   ├─ Past expiry date without acceptance
   ├─ Can be renewed (extends expiry)
   ├─ Customer can still view (read-only)
   └─ Statistics tracked
```

### Quote Entity

```javascript
QUOTE = {
  id: UUID,
  quote_reference: String, // "Q-12345"
  company_id: UUID,
  
  // CUSTOMER
  customer: {
    agency_id: UUID, // if B2B
    passenger_id: UUID, // if B2C
    email: String,
    name: String,
  },
  
  // TRANSFER DETAILS (same as Transfer entity)
  service_type: Enum,
  origin: Object,
  destination: Object,
  passengers: Integer,
  luggage: Integer,
  pickup_time: DateTime,
  // ... other transfer details
  
  // PRICING
  pricing: {
    base: Decimal,
    distance: Decimal,
    time: Decimal,
    surcharges: Decimal,
    total: Decimal,
    currency: String,
    breakdown: Object, // detailed line items
  },
  
  // VEHICLE OPTIONS (multiple tiers)
  vehicle_options: [
    { class: "sedan4", price: 47.50, available: true },
    { class: "van7", price: 55.00, available: true },
    { class: "executive", price: 95.00, available: false },
  ],
  
  // STATE
  status: Enum, // "draft" | "sent" | "viewed" | "accepted" | "rejected" | "expired"
  
  sent_at: DateTime,
  viewed_at: DateTime,
  accepted_at: DateTime,
  rejected_at: DateTime,
  expired_at: DateTime,
  
  expiry_date: DateTime, // typically sent_at + 7 days
  
  // TRACKING
  view_count: Integer,
  last_viewed_at: DateTime,
  
  // REJECTION
  rejection_reason: Text,
  rejection_details: Text,
  
  // CONVERSION
  converted_to_booking_id: UUID, // if accepted
  
  // NOTES
  internal_notes: Text,
  customer_notes: Text,
  
  // AUDIT
  created_at: DateTime,
  created_by: UUID,
  updated_at: DateTime,
}
```

### Quote-to-Booking Conversion

```
AUTOMATIC CONVERSION FLOW

Customer accepts quote:
  ↓
1. Create Transfer entity
   ├─ Copy all details from quote
   ├─ Status: "booked"
   ├─ Link: quote_id
   └─ Pricing locked (from quote)
   
2. Update Quote
   ├─ Status: "accepted"
   ├─ converted_to_booking_id: transfer.id
   └─ Archive
   
3. Process payment (if required)
   ├─ Send payment link
   ├─ OR charge saved card
   └─ OR mark as "pay_later" (B2B)
   
4. Trigger allocation
   ├─ Follow normal allocation logic
   └─ T-24h or immediate if urgent
   
5. Notifications
   ├─ Customer: "Booking confirmed"
   ├─ Operations: "New booking from quote Q-12345"
   └─ Agency: webhook if B2B
```

### Conversion Tracking & Analytics

```
QUOTATION ANALYTICS

Overall:
├─ Quote-to-booking rate: 65%
├─ Average time to decision: 2.3 days
├─ Expiry rate: 18%
├─ Rejection rate: 17%
└─ View rate: 92% (opened quote)

By Service Type:
├─ Private: 72% conversion
├─ Shuttle: 58% conversion
└─ Road-show: 45% conversion (higher value, longer decision)

By Value:
├─ €0-50: 78% conversion
├─ €50-100: 65% conversion
├─ €100-200: 52% conversion
└─ €200+: 38% conversion (price sensitivity)

Rejection Reasons:
├─ "Too expensive": 45%
├─ "Found alternative": 28%
├─ "Changed plans": 18%
└─ "Other": 9%

Optimization Insights:
├─ Follow-up after 24h increases conversion +15%
├─ Offering vehicle options increases conversion +8%
├─ Quotes viewed <4h after sending: 82% conversion
└─ Quotes viewed >48h after sending: 38% conversion
```

---

## 🔄 29. BACKUP & OVERFLOW HANDLING

### Overflow Strategy

```
WHEN NO RESOURCES AVAILABLE

Scenario: All drivers busy, booking incoming

1. CHECK CONSTRAINTS
   ├─ All own drivers busy? ✓
   ├─ All vehicles allocated? ✓
   ├─ Time window impossible? ✓
   └─ Special requirements unfillable? ✓
   
2. PRIORITIZATION
   Who gets served first?
   ├─ VIP customers first
   ├─ Then road-shows (multi-leg)
   ├─ Then by agency priority
   ├─ Then earliest booking time
   └─ Or by revenue potential
   
3. OPTIONS (in priority order)

   A) RESCHEDULE ⏰
      ├─ Suggest alternative times
      ├─ ±30min window around requested time
      ├─ ±1h window if no alternatives
      ├─ Customer approval needed
      └─ Best for: flexible bookings

   B) UPGRADE VEHICLE ⬆️
      ├─ Offer higher category vehicle
      ├─ Same price OR small surcharge
      ├─ Customer approval needed
      ├─ Example: sedan4 → van7 (+€10)
      └─ Best for: when only luxury vehicles free

   C) PARTNER NETWORK 🤝
      ├─ Check partner operators
      ├─ API call to partners
      ├─ Negotiate price (wholesale)
      ├─ Subcontract transfer
      ├─ Maintain profit margin
      └─ Best for: regular service types

   D) FREELANCE POOL 📢
      ├─ Send blast to freelance drivers
      ├─ "Transfer available: €X"
      ├─ First to accept wins
      ├─ Higher cost, lower margin
      ├─ Background checked freelancers only
      └─ Best for: last-minute needs

   E) DECLINE ❌
      ├─ Last resort only
      ├─ Apologize professionally
      ├─ Offer compensation voucher (€10-20)
      ├─ Suggest competitor (goodwill)
      ├─ Track for capacity planning
      └─ Learn: capacity vs demand gap
```

### Partner Network Integration

```javascript
PARTNER_OPERATOR = {
  id: UUID,
  company_id: UUID, // our company
  
  partner_name: String,
  partner_api_url: String,
  partner_api_key: String,
  
  relationship_type: Enum,
  // "reciprocal" (we exchange) | "supplier" (we buy from them) | 
  // "customer" (they buy from us)
  
  service_areas: Array, // ["Lisbon", "Porto"]
  service_types: Array, // ["private", "shuttle"]
  
  pricing_model: Enum,
  // "wholesale" (fixed discount) | "commission" (% of sale) | 
  // "negotiated" (case by case)
  
  pricing_params: {
    discount_percentage: Decimal, // 20% off our price
    commission_percentage: Decimal, // we keep 15%
    minimum_margin: Decimal, // €10 minimum profit
  },
  
  availability_api: Boolean, // can we check their availability?
  booking_api: Boolean, // can we book directly?
  
  sla_terms: {
    response_time_minutes: Integer, // 30
    acceptance_rate_target: Decimal, // 80%
  },
  
  quality_metrics: {
    average_rating: Decimal,
    on_time_rate: Decimal,
    cancellation_rate: Decimal,
  },
  
  status: Enum, // "active" | "paused" | "suspended"
  
  created_at: DateTime,
  last_used_at: DateTime,
}
```

### Automated Overflow Handling

```
AUTOMATION LOGIC

Transfer #789 cannot be allocated:
  ↓
1. Check operator config:
   └─ auto_use_partners: true
   
2. Query partner availability:
   ├─ POST /partners/availability
   ├─ Params: { service_type, time, location }
   └─ Response: [ partner_id, price, vehicle_class ]
   
3. Calculate margin:
   ├─ Customer pays: €50
   ├─ Partner charges: €40
   ├─ Our margin: €10 (20%) ✓
   └─ Acceptable (min €5)
   
4. Auto-book with partner:
   ├─ POST /partners/book
   ├─ Transfer outsourced
   ├─ Status: "allocated_partner"
   └─ Monitor quality
   
5. Notify customer:
   ├─ "Transfer confirmed"
   ├─ (Transparent: mention partner OR not)
   └─ Same service quality promised
   
6. Track:
   ├─ Outsourced count
   ├─ Partner performance
   └─ Capacity planning insights
```

### Capacity Planning

```
LEARN FROM OVERFLOW

Track patterns:
├─ Peak times (overflow most common)
├─ Peak days (weekends, holidays)
├─ Service types (private vs shuttle)
└─ Routes (airport transfers at 8am)

Monthly review:
├─ How many overflows?
├─ How many declines?
├─ Revenue lost?
├─ Solution: hire more drivers? buy more vehicles?
└─ ROI calculation

Example insight:
"Every Saturday 8-10am we overflow 5 transfers
→ Add 1 driver on Saturday mornings
→ Costs €200/month
→ Captures €800 extra revenue/month
→ ROI: 300% ✓"
```

---

# PARTE VI - IMPLEMENTAÇÃO E ROADMAP

## 💻 30. ROADMAP DE DESENVOLVIMENTO

### Fase 1: MVP (3-4 meses)

**Objetivo:** Sistema funcional com core features para 1 operator

```
CORE ENTITIES:
✓ Transfer (private only)
✓ Vehicle
✓ Driver
✓ Basic allocation (manual + suggestions)

FEATURES:
✓ Booking API (REST)
✓ Manual allocation interface
✓ Basic driver app (status updates)
✓ SMS notifications (Twilio)
✓ Email notifications
✓ Simple reporting

INFRASTRUCTURE:
✓ Node.js + PostgreSQL
✓ Docker deployment
✓ Basic CI/CD

OMITIR (para depois):
- Road-show (multi-leg)
- Shuttle (dynamic/static)
- Agency management (B2B)
- Advanced analytics
- Bryntum Scheduler
- Webhooks
- GDPR tooling
```

### Fase 2: B2B & Optimização (2-3 meses)

```
NEW ENTITIES:
✓ Agency (B2B clients)
✓ Passenger (B2C)
✓ Invoice & Payments

FEATURES:
✓ Agency portal (self-service)
✓ API webhooks
✓ Automatic allocation (scoring algorithm)
✓ Conflict detection
✓ Road-show support
✓ Quotation system

OPTIMIZATIONS:
✓ Dead mileage prevention
✓ Priority rules (VIP, SLA)
✓ Real-time updates (WebSockets)
```

### Fase 3: Advanced Features (2 meses)

```
FEATURES:
✓ Bryntum Scheduler integration
✓ Shuttle dynamic (TSP optimization)
✓ Customer portal (B2C)
✓ Mobile app (React Native)
✓ Advanced analytics
✓ SLA tracking
✓ Rating & review system

INTEGRATIONS:
✓ Flight tracking
✓ Google Maps / GraphHopper
✓ Stripe payments
✓ Xero accounting
```

### Fase 4: Enterprise & Scale (ongoing)

```
FEATURES:
✓ GDPR compliance tools
✓ Multi-tenant white-label
✓ Partner network API
✓ Overflow handling automation
✓ AI/ML predictions (demand forecasting)
✓ Mobile POS (driver payments)

SCALE:
✓ Kubernetes
✓ Multi-region deployment
✓ CDN for assets
✓ Advanced caching (Redis)
✓ Load balancing
```

---

## 📊 31. PRIORIZAÇÃO DE FEATURES

### MoSCoW Method

**MUST HAVE (MVP)**
- Transfer booking (API + portal)
- Driver & vehicle management
- Manual allocation
- Status updates
- Basic notifications (SMS + email)
- Simple invoicing

**SHOULD HAVE (Phase 2)**
- Automatic allocation
- Agency management (B2B)
- Webhooks
- Road-show support
- Quotation system
- Payment processing

**COULD HAVE (Phase 3)**
- Bryntum Scheduler
- Shuttle optimization
- Mobile app (native)
- Advanced analytics
- Rating system
- SLA tracking

**WON'T HAVE (for now)**
- AI/ML predictions
- Blockchain integration
- VR/AR features
- Social media integration
- Gamification

---

## 💻 32. STACK TECNOLÓGICO DETALHADO

### Backend

```
RUNTIME:
├─ Node.js v20+ (LTS)
└─ OR: Python 3.11+ (alternative)

FRAMEWORK:
├─ Express.js (minimal)
├─ NestJS (structured, enterprise)
└─ FastAPI (Python alternative)

DATABASE:
├─ PostgreSQL 15+ (primary)
│  └─ Extensions: PostGIS (geospatial)
├─ Redis (cache + queue)
└─ Elasticsearch (optional, for search)

ORM:
├─ Prisma (TypeScript)
├─ TypeORM (TypeScript)
└─ SQLAlchemy (Python)

AUTHENTICATION:
├─ JWT tokens
├─ OAuth 2.0 (SSO)
└─ bcrypt (password hashing)

FILE STORAGE:
├─ AWS S3
├─ Google Cloud Storage
└─ MinIO (self-hosted)

QUEUE:
├─ Bull (Redis-based)
├─ RabbitMQ
└─ AWS SQS

REAL-TIME:
├─ Socket.io
└─ Server-Sent Events (SSE)
```

### Frontend

```
WEB:
├─ React 18+
├─ TypeScript
├─ Vite (build tool)
├─ TailwindCSS (styling)
├─ React Query (data fetching)
├─ Zustand (state management)
└─ Bryntum Scheduler (planning)

MOBILE:
├─ React Native
├─ Expo (development)
└─ Native modules (maps, GPS)

ADMIN DASHBOARD:
├─ React Admin (rapid)
└─ Custom (more control)
```

### Infrastructure

```
HOSTING:
├─ AWS (preferred)
├─ Google Cloud Platform
├─ Azure
└─ DigitalOcean (cheaper)

CONTAINERS:
├─ Docker
└─ Docker Compose (dev)

ORCHESTRATION:
├─ Kubernetes (production)
└─ Docker Swarm (simpler)

CI/CD:
├─ GitHub Actions
├─ GitLab CI
└─ CircleCI

MONITORING:
├─ Sentry (errors)
├─ DataDog (APM)
├─ Grafana + Prometheus (metrics)
└─ LogRocket (session replay)

CDN:
├─ CloudFlare
└─ AWS CloudFront
```

### External Services

```
MAPPING:
├─ GraphHopper (free tier)
├─ OSRM (self-hosted)
└─ Google Maps (paid)

SMS:
├─ Twilio
└─ Vonage

EMAIL:
├─ SendGrid
└─ AWS SES

PAYMENTS:
├─ Stripe (primary)
└─ PayPal

FLIGHT DATA:
├─ AviationStack (free tier)
└─ FlightAware (paid)
```

---

## 🔄 33. DATABASE SCHEMA OVERVIEW

### Core Tables

```sql
-- TENANCY
companies (id, name, settings, ...)

-- USERS & AUTH
users (id, company_id, email, role, ...)
sessions (id, user_id, token, ...)

-- CORE ENTITIES
transfers (id, company_id, service_type, status, ...)
vehicles (id, company_id, license_plate, ...)
drivers (id, company_id, assigned_vehicle_id, ...)

-- B2B/B2C
agencies (id, company_id, name, pricing_model, ...)
passengers (id, company_id, email, ...)

-- FINANCIAL
invoices (id, company_id, agency_id, total, ...)
payments (id, invoice_id, amount, method, ...)

-- OPERATIONS
allocations (id, transfer_id, driver_id, vehicle_id, ...)
no_show_policies (id, agency_id, wait_time, ...)

-- RATINGS & REVIEWS
ratings (id, transfer_id, driver_rating, passenger_rating, ...)

-- QUOTATIONS
quotes (id, company_id, status, pricing, ...)

-- NOTIFICATIONS
notification_templates (id, company_id, type, body, ...)
notification_logs (id, recipient, sent_at, status, ...)

-- AUDIT
audit_logs (id, user_id, action, entity_type, entity_id, ...)
```

### Indexing Strategy

```sql
-- Performance-critical indexes

CREATE INDEX idx_transfers_company_status 
ON transfers(company_id, status);

CREATE INDEX idx_transfers_pickup_time 
ON transfers(scheduled_pickup_time);

CREATE INDEX idx_drivers_company_status 
ON drivers(company_id, current_status);

CREATE INDEX idx_allocations_transfer 
ON allocations(transfer_id);

CREATE INDEX idx_allocations_driver_vehicle 
ON allocations(driver_id, vehicle_id);

-- Geospatial indexes (PostGIS)
CREATE INDEX idx_transfers_origin_location 
ON transfers USING GIST(origin_location);
```

---

## 📊 34. API ENDPOINTS SUMMARY

### Public API (for Agencies)

```
POST   /api/v1/bookings              # Create booking
GET    /api/v1/bookings/:id          # Get booking
PUT    /api/v1/bookings/:id          # Update booking
DELETE /api/v1/bookings/:id          # Cancel booking

POST   /api/v1/quotes                # Request quote
GET    /api/v1/quotes/:id            # Get quote
POST   /api/v1/quotes/:id/accept     # Accept quote

GET    /api/v1/drivers/:id           # Get driver info (allocated)
GET    /api/v1/tracking/:id          # Real-time tracking

POST   /api/v1/webhooks/register     # Register webhook URL
GET    /api/v1/webhooks              # List webhooks
DELETE /api/v1/webhooks/:id          # Unregister webhook
```

### Internal API (for Dashboard)

```
# TRANSFERS
GET    /api/internal/transfers       # List all transfers
POST   /api/internal/transfers       # Create transfer
GET    /api/internal/transfers/:id   # Get transfer
PUT    /api/internal/transfers/:id   # Update transfer
DELETE /api/internal/transfers/:id   # Delete transfer

# ALLOCATION
POST   /api/internal/allocations     # Manual allocation
GET    /api/internal/allocations/suggestions  # Get suggestions
PUT    /api/internal/allocations/:id # Update allocation

# DRIVERS
GET    /api/internal/drivers         # List drivers
POST   /api/internal/drivers         # Add driver
PUT    /api/internal/drivers/:id     # Update driver
DELETE /api/internal/drivers/:id     # Remove driver

# VEHICLES
GET    /api/internal/vehicles        # List vehicles
POST   /api/internal/vehicles        # Add vehicle
PUT    /api/internal/vehicles/:id    # Update vehicle
DELETE /api/internal/vehicles/:id    # Remove vehicle

# AGENCIES
GET    /api/internal/agencies        # List agencies
POST   /api/internal/agencies        # Add agency
PUT    /api/internal/agencies/:id    # Update agency

# REPORTING
GET    /api/internal/reports/daily   # Daily summary
GET    /api/internal/reports/financial  # Financial report
GET    /api/internal/reports/export  # Export data
```

### Driver API (Mobile App)

```
GET    /api/driver/schedule          # Today's transfers
GET    /api/driver/transfers/:id     # Transfer details
PUT    /api/driver/transfers/:id/status  # Update status
POST   /api/driver/issues            # Report issue
GET    /api/driver/earnings          # Earnings summary
POST   /api/driver/sos               # Emergency SOS
```

---

# PARTE VII - GLOSSÁRIO E REFERÊNCIAS

## 📖 GLOSSÁRIO

### Termos de Negócio

**Allocation** - Processo de atribuir motorista e veículo a um transfer  
**Agency** - Cliente B2B que faz reservas em nome de passageiros  
**Dead mileage** - Quilómetros vazios (sem passageiro) entre transfers  
**Dispatcher** - Pessoa que gere alocação de transfers na operação  
**No-show** - Passageiro não aparece no pickup  
**Operator** - Empresa que opera o serviço de transfers (nosso cliente)  
**Road-show** - Transfer com múltiplas paragens para o mesmo grupo  
**SLA** - Service Level Agreement (acordo de qualidade de serviço)  
**Transfer** - Transporte de passageiro de A para B  

### Termos Técnicos

**CRUD** - Create, Read, Update, Delete  
**FK** - Foreign Key (chave estrangeira)  
**GDPR** - General Data Protection Regulation  
**JWT** - JSON Web Token (autenticação)  
**Multi-tenant** - Múltiplos clientes isolados na mesma instância  
**RBAC** - Role-Based Access Control  
**REST** - Representational State Transfer (API style)  
**TSP** - Traveling Salesman Problem (otimização de rota)  
**UUID** - Universally Unique Identifier  
**Webhook** - Callback HTTP automático  

### Service Types

**Private** - 1 grupo, rota direta A→B  
**Road-show** - 1 grupo, múltiplas paragens A→B→C→D  
**Shuttle Dynamic** - Múltiplos grupos, rota otimizada  
**Shuttle Static** - Rota fixa, horários fixos  

### Vehicle Categories

**sedan4** - Sedan até 4 passageiros  
**van7** - Van até 7 passageiros  
**minibus10** - Minibus até 10 passageiros  
**bus16** - Bus até 16 passageiros  
**wheelchair_van** - Van acessível para cadeira de rodas  

---

## 📊 MÉTRICAS-CHAVE (KPIs)

### Operacionais
- **On-time rate:** % de transfers no horário (target: >95%)
- **Allocation rate:** % de transfers alocados T-24h (target: >98%)
- **Vehicle utilization:** % tempo em serviço (target: >80%)
- **Driver utilization:** % tempo em serviço (target: >75%)
- **Dead mileage ratio:** km vazios / km totais (target: <15%)

### Financeiros
- **Revenue per transfer:** Receita média por transfer
- **Revenue per driver:** Receita gerada por motorista
- **Cost per transfer:** Custo médio por transfer
- **Profit margin:** % lucro (target: >30%)
- **Outstanding invoices:** Valor em dívida (target: <5% revenue)

### Qualidade
- **Customer satisfaction:** Rating médio (target: >4.5/5)
- **Driver rating:** Rating médio motoristas (target: >4.5/5)
- **Cancellation rate:** % cancelamentos (target: <5%)
- **No-show rate:** % no-shows (target: <2%)
- **Complaint rate:** % reclamações (target: <1%)

### Crescimento
- **Bookings growth:** % crescimento mês-a-mês
- **Revenue growth:** % crescimento receita
- **Customer retention:** % clientes que voltam
- **Quote-to-booking rate:** % quotes convertidas (target: >60%)

---

## 🔗 LINKS ÚTEIS

### Documentação Externa
- **GraphHopper API:** https://docs.graphhopper.com/
- **Twilio SMS:** https://www.twilio.com/docs/sms
- **Stripe Payments:** https://stripe.com/docs/api
- **PostgreSQL:** https://www.postgresql.org/docs/
- **React:** https://react.dev/
- **Bryntum Scheduler:** https://bryntum.com/products/scheduler/

### Standards & Compliance
- **GDPR:** https://gdpr.eu/
- **ISO 27001:** (Security)
- **PCI DSS:** (Payment Card Industry)

---

## ✅ CHECKLIST PRÉ-LANÇAMENTO

### Técnico
- [ ] Database backups automáticos
- [ ] SSL/TLS certificados válidos
- [ ] Environment variables configuradas
- [ ] Logs centralizados (Sentry, etc)
- [ ] Monitoring & alerts ativos
- [ ] Load testing completado
- [ ] Security audit completado
- [ ] API rate limiting ativo
- [ ] GDPR compliance verificado

### Operacional
- [ ] Staff treinado (operations, support)
- [ ] Driver app testado em campo
- [ ] Templates de notificações finalizados
- [ ] Políticas documentadas (no-show, cancellation)
- [ ] Escalation procedures definidos
- [ ] Emergency protocols testados
- [ ] SLA definidos com clientes

### Legal
- [ ] Terms of Service aprovados
- [ ] Privacy Policy aprovada
- [ ] Licenças de transporte obtidas
- [ ] Seguros válidos
- [ ] Contratos B2B templates prontos

---

## 📈 PRÓXIMOS PASSOS

### Para Começar Desenvolvimento
1. **Setup environment:**
   - Docker + PostgreSQL + Redis
   - Node.js projeto base
   - Git repository

2. **Primeiro sprint (MVP):**
   - Database schema (Prisma)
   - Transfer CRUD API
   - Vehicle & Driver management
   - Basic allocation logic

3. **Segundo sprint:**
   - Driver mobile app (React Native)
   - SMS notifications (Twilio)
   - Manual allocation interface

### Para Começar Negócio
1. **Validar mercado:**
   - Falar com 10 operadores de transfer
   - Validar pain points
   - Refinar pricing

2. **Pilot program:**
   - 1 operador piloto (3 meses grátis)
   - Iterar baseado em feedback
   - Case study para vendas

3. **Go-to-market:**
   - Website marketing
   - SEO para "transfer management software"
   - Presença em feiras do setor

---

# 🎉 CONCLUSÃO

## O Que Foi Documentado

✅ **31 Secções Completas**  
✅ **6.275+ Linhas de Especificações**  
✅ **Zero Gaps Funcionais**  
✅ **Ready to Implement**  

## Próxima Decisão Crítica

**Escolher entre:**
1. **Build** - Desenvolver in-house (3-6 meses)
2. **Buy** - Comprar solução existente + customizar
3. **Hybrid** - Core próprio + integrações third-party

**Recomendação:** Build MVP próprio (controlo total + diferenciação)

---

**Este documento é a base completa para:**
- Desenvolvimento técnico
- Pitch a investidores
- Onboarding de equipa
- Documentação oficial
- RFP responses

**Sucesso! 🚀**

---

**Documento Master Consolidado**  
**Versão:** 2.0  
**Última Atualização:** Novembro 2025  
**Total Páginas:** ~200 (estimado em impressão)  
**Preparado para:** Desenvolvimento + Gestão
