# Tarivo UML and Use Cases

Document status: Supporting product blueprint
Version: 3.0
Scope: MVP smart mobility SaaS platform for Morocco

Implementation status is tracked in `TASKS.md`. This document defines diagrams,
actors, state machines, runtime flows and module relationships for the target
system. Diagrams use PlantUML-compatible syntax where possible so they can be
rendered later without changing the source of truth.

## 1. Diagram Index

- System context
- Actor and use-case diagrams
- Backend component diagram
- Frontend component diagram
- Core domain model
- Database relationship diagram
- Sequence diagrams for ride request, chat/calls, tracking, upload/AI, offline
  sync, payment callbacks and notifications
- Activity diagrams for driver onboarding and trip lifecycle
- State diagrams for ride, trip, payment, notification, call, document and sync
- Realtime channel map
- Deployment diagram

## 2. System Context Diagram

```plantuml
@startuml
title Tarivo System Context

actor Guest
actor Passenger
actor Driver
actor "Support Agent" as Support
actor Admin
actor "Super Admin" as SuperAdmin

rectangle "Tarivo SaaS Platform" {
  component "Next.js Web App" as Web
  component "Laravel API /api/v1" as Api
  component "Laravel Reverb" as Reverb
  queue "Laravel Queues" as Queues
  database "MySQL 8" as Db
  database "Redis" as Redis
  folder "Private File Storage" as Storage
}

cloud "Google Maps API" as Maps
cloud "Stripe API" as Stripe
cloud "OpenAI API" as OpenAI
cloud "Email Provider" as Email
cloud "SMS Provider" as Sms

Guest --> Web
Passenger --> Web
Driver --> Web
Support --> Web
Admin --> Web
SuperAdmin --> Web

Web --> Api : HTTPS JSON
Web --> Reverb : WebSocket
Api --> Db : canonical state
Api --> Redis : cache, locks, rate limits
Api --> Storage : private uploads
Api --> Reverb : broadcast events
Api --> Queues : async jobs
Queues --> Db
Queues --> Storage
Queues --> Maps
Queues --> Stripe
Queues --> OpenAI
Queues --> Email
Queues --> Sms
Api --> Maps
Api --> Stripe
Api --> Email
Api --> Sms

@enduml
```

## 3. Actor Use-case Diagram

```plantuml
@startuml
title Tarivo MVP Use Cases

left to right direction

actor Guest
actor Passenger
actor Driver
actor "Support Agent" as Support
actor Admin
actor "Super Admin" as SuperAdmin
actor "External Provider" as Provider

rectangle "Identity" {
  usecase "Register" as UC_Register
  usecase "Login" as UC_Login
  usecase "Verify phone/email" as UC_Verify
  usecase "Manage profile" as UC_Profile
}

rectangle "Ride Operations" {
  usecase "Request ride" as UC_RequestRide
  usecase "Accept/reject ride" as UC_AcceptRide
  usecase "Execute trip lifecycle" as UC_TripLifecycle
  usecase "Track driver on map" as UC_Track
  usecase "Submit driver location" as UC_Location
}

rectangle "Communication" {
  usecase "Realtime chat" as UC_Chat
  usecase "Typing indicators" as UC_Typing
  usecase "Read receipts" as UC_Read
  usecase "Incoming call ringing" as UC_Ringing
  usecase "Audio call" as UC_Audio
  usecase "Video call" as UC_Video
}

rectangle "Notifications" {
  usecase "Receive persistent notification" as UC_Notify
  usecase "Hear notification sound" as UC_Sound
  usecase "Mark read/acted" as UC_ActNotify
}

rectangle "Documents and AI" {
  usecase "Upload secure file" as UC_Upload
  usecase "Queue AI processing" as UC_AIQueue
  usecase "Review AI result" as UC_AIReview
  usecase "Approve/reject document" as UC_DocReview
}

rectangle "Offline Sync" {
  usecase "Queue offline action" as UC_OfflineQueue
  usecase "Synchronize action" as UC_Sync
  usecase "Resolve conflict" as UC_Conflict
}

rectangle "Payments" {
  usecase "Pay by cash" as UC_Cash
  usecase "Pay by wallet" as UC_Wallet
  usecase "Pay by Stripe" as UC_Stripe
  usecase "Process verified callback" as UC_Webhook
  usecase "Generate invoice" as UC_Invoice
}

rectangle "Operations" {
  usecase "Handle support ticket" as UC_Ticket
  usecase "Manage users and roles" as UC_Roles
  usecase "View audit logs" as UC_Audit
  usecase "View external API logs" as UC_ApiLogs
}

Guest --> UC_Register
Guest --> UC_Login
Guest --> UC_Verify

Passenger --> UC_Profile
Passenger --> UC_RequestRide
Passenger --> UC_Track
Passenger --> UC_Chat
Passenger --> UC_Ringing
Passenger --> UC_Audio
Passenger --> UC_Video
Passenger --> UC_Notify
Passenger --> UC_Cash
Passenger --> UC_Wallet
Passenger --> UC_Stripe

Driver --> UC_Profile
Driver --> UC_AcceptRide
Driver --> UC_TripLifecycle
Driver --> UC_Location
Driver --> UC_Chat
Driver --> UC_Ringing
Driver --> UC_Audio
Driver --> UC_Video
Driver --> UC_Upload
Driver --> UC_OfflineQueue
Driver --> UC_Sync
Driver --> UC_Notify

Support --> UC_Ticket
Support --> UC_Chat
Support --> UC_Audio
Support --> UC_Video
Support --> UC_Audit

Admin --> UC_DocReview
Admin --> UC_AIReview
Admin --> UC_Audit
Admin --> UC_ApiLogs
Admin --> UC_Roles

SuperAdmin --> UC_Roles
SuperAdmin --> UC_Audit

Provider --> UC_AIQueue
Provider --> UC_Webhook

UC_RequestRide ..> UC_Notify : includes
UC_AcceptRide ..> UC_Notify : includes
UC_TripLifecycle ..> UC_Notify : includes
UC_Chat ..> UC_Read : includes
UC_Chat ..> UC_Typing : includes
UC_Audio ..> UC_Ringing : includes
UC_Video ..> UC_Ringing : includes
UC_Upload ..> UC_AIQueue : includes
UC_Sync ..> UC_Conflict : extends
UC_Stripe ..> UC_Webhook : includes
UC_Webhook ..> UC_Invoice : includes

@enduml
```

## 4. Backend Component Diagram

```plantuml
@startuml
title Laravel Backend Components

package "HTTP Layer" {
  component "API Controllers" as Controllers
  component "Form Requests" as Requests
  component "API Resources" as Resources
  component "Policies" as Policies
  component "Middleware / Rate Limiters" as Middleware
}

package "Domain Services" {
  component "AuthService" as AuthService
  component "RideRequestService" as RideService
  component "RideMatchingService" as MatchingService
  component "TripLifecycleService" as TripService
  component "TripTrackingService" as TrackingService
  component "NotificationService" as NotificationService
  component "ConversationService" as ConversationService
  component "CallSessionService" as CallService
  component "UploadService" as UploadService
  component "AiProcessingService" as AiService
  component "SyncActionService" as SyncService
  component "PaymentService" as PaymentService
  component "WalletService" as WalletService
  component "AuditLogService" as AuditService
}

package "Async Layer" {
  component "AI Jobs" as AiJobs
  component "Webhook Jobs" as WebhookJobs
  component "Notification Jobs" as NotificationJobs
  component "File Jobs" as FileJobs
}

package "Integration Services" {
  component "GoogleMapsClient" as MapsClient
  component "StripeClient" as StripeClient
  component "OpenAiClient" as OpenAiClient
  component "MailClient" as MailClient
  component "SmsClient" as SmsClient
}

database "MySQL" as Db
database "Redis" as Redis
cloud "Reverb" as Reverb
folder "Private Storage" as Storage

Controllers --> Requests
Controllers --> Policies
Controllers --> Resources
Controllers --> AuthService
Controllers --> RideService
Controllers --> MatchingService
Controllers --> TripService
Controllers --> TrackingService
Controllers --> NotificationService
Controllers --> ConversationService
Controllers --> CallService
Controllers --> UploadService
Controllers --> SyncService
Controllers --> PaymentService

RideService --> AuditService
MatchingService --> NotificationService
TripService --> NotificationService
TrackingService --> Reverb
NotificationService --> Reverb
ConversationService --> Reverb
CallService --> Reverb
UploadService --> Storage
UploadService --> AiJobs
AiJobs --> AiService
AiService --> OpenAiClient
PaymentService --> StripeClient
PaymentService --> WalletService
PaymentService --> WebhookJobs
WebhookJobs --> StripeClient

AuthService --> Db
RideService --> Db
TripService --> Db
TrackingService --> Db
NotificationService --> Db
ConversationService --> Db
CallService --> Db
SyncService --> Db
PaymentService --> Db
WalletService --> Db
AuditService --> Db
Middleware --> Redis

@enduml
```

## 5. Frontend Component Diagram

```plantuml
@startuml
title Next.js Frontend Components

package "App Router" {
  component "Auth Pages" as AuthPages
  component "Dashboard" as Dashboard
  component "Passenger Ride Request" as PassengerRide
  component "Driver Active Ride" as DriverRide
  component "Notification Center" as NotificationCenter
  component "Driver Onboarding" as Onboarding
  component "Payments UI" as PaymentsUi
  component "Support/Admin UI" as AdminUi
}

package "Client Components" {
  component "Realtime Hooks" as RealtimeHooks
  component "Map View" as MapView
  component "Chat Panel" as ChatPanel
  component "Call Panel" as CallPanel
  component "Upload Widget" as UploadWidget
  component "Offline Queue" as OfflineQueue
  component "Toast / Persistent Alerts" as Alerts
}

package "API Layer" {
  component "auth-api.ts" as AuthApi
  component "ride-api.ts" as RideApi
  component "tracking-api.ts" as TrackingApi
  component "communication-api.ts" as CommunicationApi
  component "notification-api.ts" as NotificationApi
  component "upload-api.ts" as UploadApi
  component "sync-api.ts" as SyncApi
  component "payment-api.ts" as PaymentApi
}

cloud "Laravel API" as Api
cloud "Laravel Reverb" as Reverb
cloud "Google Maps Browser SDK" as MapsSdk
database "localStorage / IndexedDB" as LocalStore

AuthPages --> AuthApi
Dashboard --> RideApi
Dashboard --> NotificationApi
PassengerRide --> RideApi
DriverRide --> RideApi
DriverRide --> TrackingApi
DriverRide --> ChatPanel
DriverRide --> CallPanel
DriverRide --> MapView
DriverRide --> OfflineQueue
NotificationCenter --> NotificationApi
Onboarding --> UploadWidget
Onboarding --> UploadApi
PaymentsUi --> PaymentApi

RealtimeHooks --> Reverb
Alerts --> RealtimeHooks
ChatPanel --> CommunicationApi
CallPanel --> CommunicationApi
MapView --> MapsSdk
OfflineQueue --> LocalStore
OfflineQueue --> SyncApi

AuthApi --> Api
RideApi --> Api
TrackingApi --> Api
CommunicationApi --> Api
NotificationApi --> Api
UploadApi --> Api
SyncApi --> Api
PaymentApi --> Api

@enduml
```

## 6. Core Domain Model

```plantuml
@startuml
title Tarivo Core Domain Model

class User {
  id
  uuid
  name
  phone
  email
  status
  preferred_language
}

class Driver {
  id
  user_id
  city_id
  status
  availability
  rating_average
}

class Vehicle {
  id
  driver_id
  vehicle_type_id
  city_id
  status
  registration_number
}

class DriverDocument {
  id
  driver_id
  file_id
  type
  status
  ai_status
}

class RideRequest {
  id
  uuid
  passenger_id
  city_id
  vehicle_type_id
  pickup
  dropoff
  payment_method
  status
}

class Trip {
  id
  uuid
  ride_request_id
  passenger_id
  driver_id
  vehicle_id
  status
  final_price
}

class TripLocation {
  id
  trip_id
  driver_id
  latitude
  longitude
  recorded_at
}

class Notification {
  id
  uuid
  user_id
  type
  priority
  persistence
  read_at
  acted_at
}

class Conversation {
  id
  uuid
  type
  trip_id
  status
}

class Message {
  id
  uuid
  conversation_id
  sender_id
  type
  status
}

class CallSession {
  id
  uuid
  conversation_id
  caller_id
  recipient_id
  type
  status
}

class File {
  id
  uuid
  owner_id
  disk
  path
  visibility
  status
}

class AiProcessingJob {
  id
  uuid
  file_id
  task
  status
  result
}

class SyncAction {
  id
  uuid
  user_id
  idempotency_key
  action_type
  status
}

class Payment {
  id
  uuid
  trip_id
  user_id
  provider
  amount
  status
}

class Wallet {
  id
  user_id
  balance
  status
}

class Transaction {
  id
  uuid
  wallet_id
  user_id
  trip_id
  type
  amount
  status
}

class Invoice {
  id
  uuid
  payment_id
  trip_id
  invoice_number
}

User "1" -- "0..1" Driver
Driver "1" -- "0..*" Vehicle
Driver "1" -- "0..*" DriverDocument
DriverDocument "1" -- "1" File
User "1" -- "0..*" RideRequest : passenger
RideRequest "1" -- "0..1" Trip
Trip "1" -- "0..*" TripLocation
Trip "1" -- "0..*" Conversation
Conversation "1" -- "0..*" Message
Conversation "1" -- "0..*" CallSession
User "1" -- "0..*" Notification
User "1" -- "0..*" File
File "1" -- "0..*" AiProcessingJob
User "1" -- "0..*" SyncAction
Trip "1" -- "0..*" Payment
User "1" -- "0..1" Wallet
Wallet "1" -- "0..*" Transaction
Payment "1" -- "0..1" Invoice

@enduml
```

## 7. Database Relationship Diagram

```plantuml
@startuml
title MVP Database Relationships

entity users
entity drivers
entity vehicles
entity driver_documents
entity files
entity ai_processing_jobs
entity cities
entity vehicle_types
entity ride_requests
entity ride_request_driver_responses
entity trips
entity trip_status_events
entity trip_locations
entity notifications
entity conversations
entity conversation_participants
entity messages
entity call_sessions
entity sync_actions
entity wallets
entity transactions
entity payments
entity payment_webhook_events
entity invoices
entity support_tickets
entity audit_logs
entity external_api_logs

users ||--o| drivers
cities ||--o{ drivers
drivers ||--o{ vehicles
vehicle_types ||--o{ vehicles
cities ||--o{ vehicles
drivers ||--o{ driver_documents
files ||--o{ driver_documents
files ||--o{ ai_processing_jobs
users ||--o{ files

users ||--o{ ride_requests
cities ||--o{ ride_requests
vehicle_types ||--o{ ride_requests
ride_requests ||--o{ ride_request_driver_responses
drivers ||--o{ ride_request_driver_responses
ride_requests ||--o| trips
users ||--o{ trips : passenger_id
drivers ||--o{ trips
vehicles ||--o{ trips
trips ||--o{ trip_status_events
trips ||--o{ trip_locations
drivers ||--o{ trip_locations

users ||--o{ notifications
trips ||--o{ conversations
conversations ||--o{ conversation_participants
users ||--o{ conversation_participants
conversations ||--o{ messages
users ||--o{ messages
files ||--o{ messages
conversations ||--o{ call_sessions
users ||--o{ call_sessions : caller_id
users ||--o{ call_sessions : recipient_id

users ||--o{ sync_actions
users ||--o| wallets
wallets ||--o{ transactions
users ||--o{ transactions
trips ||--o{ transactions
trips ||--o{ payments
users ||--o{ payments
payments ||--o| invoices
trips ||--o{ invoices

users ||--o{ support_tickets
trips ||--o{ support_tickets
users ||--o{ audit_logs

@enduml
```

## 8. Sequence Diagrams

### 8.1 Ride Request and Driver Acceptance

```plantuml
@startuml
title Ride Request and Acceptance

actor Passenger
actor Driver
participant "Next.js Web" as Web
participant "Laravel API" as Api
participant "RideRequestService" as RideService
participant "RideMatchingService" as MatchService
participant "NotificationService" as Notify
participant "Reverb" as Reverb
database "MySQL" as Db

Passenger -> Web : submit pickup/dropoff/payment
Web -> Api : POST /api/v1/rides
Api -> RideService : validate and create ride
RideService -> Db : insert ride_requests
RideService -> Notify : create incoming ride notifications
Notify -> Db : insert notifications
Notify -> Reverb : broadcast notification.created
Api --> Web : 201 ride resource

Driver -> Web : accept ride
Web -> Api : POST /api/v1/rides/{ride}/accept
Api -> MatchService : accept ride
MatchService -> Db : lock ride, create trip, response, status event
MatchService -> Db : update driver availability busy
MatchService -> Notify : notify passenger and resolve driver alert
Notify -> Reverb : broadcast notification.created
MatchService -> Reverb : broadcast trip.status.updated
Api --> Web : 201 trip resource

@enduml
```

### 8.2 Realtime Chat, Ringing, Audio Call and Video Call

```plantuml
@startuml
title Chat and Call Flow

actor Passenger
actor Driver
participant "Next.js Chat UI" as ChatUi
participant "Laravel API" as Api
participant "ConversationService" as ConvService
participant "CallSessionService" as CallService
participant "NotificationService" as Notify
participant "Reverb" as Reverb
database "MySQL" as Db

Passenger -> ChatUi : send message
ChatUi -> Api : POST /api/v1/messages
Api -> ConvService : authorize participant and persist
ConvService -> Db : insert message status=sent
ConvService -> Reverb : message.sent
Api --> ChatUi : message resource

Driver -> ChatUi : mark conversation read
ChatUi -> Api : POST /api/v1/messages/read
Api -> ConvService : update read receipt
ConvService -> Db : update participant last_read_at
ConvService -> Reverb : conversation.read

Passenger -> ChatUi : start video call
ChatUi -> Api : POST /api/v1/calls
Api -> CallService : create ringing call session
CallService -> Db : insert call_sessions status=ringing
CallService -> Notify : create incoming_call notification
Notify -> Reverb : notification.created with sound_key
CallService -> Reverb : call.ringing

Driver -> ChatUi : accept call
ChatUi -> Api : POST /api/v1/calls/{call}/accept
Api -> CallService : accept
CallService -> Db : status=accepted, answered_at
CallService -> Reverb : call.updated

Passenger -> Api : POST /calls/{call}/signal offer
Api -> CallService : authorize signal
CallService -> Reverb : call.signal on presence-call.{id}
Driver -> Api : POST /calls/{call}/signal answer/ice
Api -> CallService : authorize signal
CallService -> Reverb : call.signal on presence-call.{id}

@enduml
```

### 8.3 Persistent Notification with Sound and Action State

```plantuml
@startuml
title Persistent Notification Delivery

participant "Domain Service" as Domain
participant "NotificationService" as Notify
database "MySQL" as Db
participant "Reverb" as Reverb
participant "Next.js Alert Surface" as Ui
actor User

Domain -> Notify : create critical notification
Notify -> Db : insert notification read_at=null acted_at=null
Notify -> Reverb : notification.created
Reverb -> Ui : push payload
Ui -> User : show blocking alert and play sound
User -> Ui : acts on notification
Ui -> Notify : PATCH /notifications/{id}/acted
Notify -> Db : set acted_at and read_at
Notify --> Ui : updated notification

@enduml
```

### 8.4 Realtime Geolocation on Map

```plantuml
@startuml
title Driver Location Tracking

actor Driver
actor Passenger
participant "Driver Web App" as DriverWeb
participant "Passenger Web App" as PassengerWeb
participant "Laravel API" as Api
participant "TripTrackingService" as Tracking
participant "Reverb" as Reverb
database "MySQL" as Db
cloud "Google Maps" as Maps

Passenger -> PassengerWeb : open active trip map
PassengerWeb -> Api : GET /trips/{trip}/tracking
Api -> Tracking : authorize and build snapshot
Tracking -> Db : read last known location
Tracking --> Api : route context and stream state
PassengerWeb -> Maps : render map and route context

Driver -> DriverWeb : browser geolocation update
DriverWeb -> Api : POST /trips/{trip}/location
Api -> Tracking : validate, authorize, rate limit
Tracking -> Db : insert trip_locations
Tracking -> Reverb : trip.location.updated
Reverb -> PassengerWeb : authorized location event
PassengerWeb -> Maps : update marker

@enduml
```

### 8.5 Secure Upload and AI Processing

```plantuml
@startuml
title Upload and AI Processing

actor Driver
actor Admin
participant "Next.js Upload UI" as Ui
participant "Laravel API" as Api
participant "UploadService" as Upload
participant "AI Job" as Job
participant "OpenAI Client" as OpenAI
participant "NotificationService" as Notify
database "MySQL" as Db
folder "Private Storage" as Storage

Driver -> Ui : upload identity/license/insurance file
Ui -> Api : POST /drivers/documents multipart
Api -> Upload : validate type, MIME, size, owner
Upload -> Storage : store private server-named file
Upload -> Db : insert files and driver_documents
Upload -> Db : insert ai_processing_jobs queued
Api --> Ui : 202 or 201 document resource

Job -> Db : claim ai_processing_job
Job -> Storage : read private file
Job -> OpenAI : OCR / image analysis / validation
OpenAI --> Job : structured result
Job -> Db : store result separately from file metadata
Job -> Notify : notify admin review required

Admin -> Api : POST /admin/drivers/documents/{id}/review
Api -> Db : approve/reject with reason
Api -> Notify : notify driver

@enduml
```

### 8.6 Offline Start or Finish Trip Synchronization

```plantuml
@startuml
title Offline Trip Action Sync

actor Driver
participant "Driver Web App" as Web
database "Local Queue" as Local
participant "Laravel API" as Api
participant "SyncActionService" as Sync
participant "TripLifecycleService" as TripService
database "MySQL" as Db
participant "NotificationService" as Notify
participant "Reverb" as Reverb

Driver -> Web : tap Start Trip while offline
Web -> Local : store action with idempotency_key
Web -> Driver : show pending sync

Web -> Api : POST /sync/actions/batch after reconnect
Api -> Sync : validate batch and idempotency keys
Sync -> Db : insert sync_actions received
Sync -> TripService : replay trip_start
TripService -> Db : validate state and update trip
TripService -> Db : insert trip_status_events
TripService -> Notify : create participant notification
TripService -> Reverb : trip.status.updated
Sync -> Db : mark sync_action applied
Api --> Web : applied result
Web -> Driver : show synced

alt canonical trip state changed
  Sync -> Db : mark sync_action conflict
  Api --> Web : 409 offline_sync_conflict
  Web -> Driver : show conflict state
end

@enduml
```

### 8.7 Payment or Transaction with Automatic Callback

```plantuml
@startuml
title Stripe Payment Callback

actor Passenger
participant "Next.js Payment UI" as Ui
participant "Laravel API" as Api
participant "PaymentService" as Payment
participant "Stripe" as Stripe
participant "Webhook Controller" as Webhook
participant "Webhook Job" as Job
participant "NotificationService" as Notify
database "MySQL" as Db

Passenger -> Ui : choose card payment
Ui -> Api : POST /payments
Api -> Payment : create Stripe payment intent
Payment -> Db : insert payment pending
Payment -> Stripe : create payment intent
Stripe --> Payment : client secret / reference
Api --> Ui : payment resource

Stripe -> Webhook : POST /payments/webhooks/stripe
Webhook -> Webhook : verify signature
Webhook -> Db : store provider event id
Webhook -> Job : dispatch processing job
Webhook --> Stripe : 200 accepted

Job -> Db : lock webhook event and payment
Job -> Payment : apply provider result idempotently
Payment -> Db : update payment/transaction/wallet
Payment -> Db : create invoice if confirmed
Payment -> Notify : create success or failure notification
Notify -> Db : insert notification
Notify -> Ui : realtime notification through Reverb

@enduml
```

## 9. Activity Diagrams

### 9.1 Driver Onboarding Activity

```plantuml
@startuml
title Driver Onboarding Activity

start
:Driver creates account;
:Driver creates driver profile;
:Driver adds vehicle;
:Driver uploads required documents;
:Validate MIME, extension and size;
if (Valid upload?) then (yes)
  :Store private file;
  :Create document record;
  :Queue AI processing;
  :AI stores structured result;
  :Admin reviews document;
  if (Approved?) then (yes)
    :Mark document approved;
    if (All required docs approved?) then (yes)
      :Approve driver;
      :Notify driver;
    else (no)
      :Wait for remaining documents;
    endif
  else (no)
    :Reject document with reason;
    :Reject or block driver approval;
    :Notify driver;
  endif
else (no)
  :Return validation error;
endif
stop

@enduml
```

### 9.2 Trip Lifecycle Activity

```plantuml
@startuml
title Trip Lifecycle Activity

start
:Passenger requests ride;
:Eligible drivers receive persistent alert;
:Driver accepts ride;
:Create trip accepted;
:Driver goes to pickup;
:Driver marks arrived;
:Passenger notified;
:Driver starts trip;
if (Connection lost?) then (yes)
  :Store start/finish action locally;
  :Show pending sync;
  :Replay action after reconnect;
  if (Backend conflict?) then (yes)
    :Show conflict;
    stop
  else (no)
    :Show synced;
  endif
endif
:Driver may pause/resume;
:Driver finishes trip;
:Calculate final price backend-side;
:Trigger payment flow;
:Generate invoice after confirmed payment;
:Notify passenger and driver;
stop

@enduml
```

## 10. State Diagrams

### 10.1 Ride Request Status

```plantuml
@startuml
title Ride Request State

[*] --> requested
requested --> searching
requested --> cancelled
searching --> accepted
searching --> cancelled
searching --> expired
accepted --> [*]
cancelled --> [*]
expired --> [*]

@enduml
```

### 10.2 Trip Status

```plantuml
@startuml
title Trip State

[*] --> accepted
accepted --> driver_arriving
driver_arriving --> driver_arrived
driver_arrived --> started
started --> paused
paused --> started
started --> completed
accepted --> cancelled
driver_arriving --> cancelled
driver_arrived --> cancelled
started --> cancelled
paused --> cancelled
completed --> [*]
cancelled --> [*]

@enduml
```

### 10.3 Payment Status

```plantuml
@startuml
title Payment State

[*] --> pending
pending --> authorized
authorized --> captured
captured --> completed
pending --> completed : cash confirmed / wallet settled
pending --> failed
authorized --> failed
captured --> failed
completed --> refunded
failed --> [*]
refunded --> [*]
completed --> [*]

@enduml
```

### 10.4 Notification Status

```plantuml
@startuml
title Persistent Notification State

[*] --> unread
unread --> read : user reads
unread --> acted : user acts
read --> acted : user acts
unread --> expired
read --> expired
acted --> resolved
expired --> [*]
resolved --> [*]

@enduml
```

### 10.5 Call Session Status

```plantuml
@startuml
title Call Session State

[*] --> ringing
ringing --> accepted
ringing --> declined
ringing --> missed
ringing --> failed
accepted --> ended
accepted --> failed
declined --> [*]
missed --> [*]
ended --> [*]
failed --> [*]

@enduml
```

### 10.6 Driver Document Status

```plantuml
@startuml
title Driver Document State

[*] --> pending
pending --> processing
processing --> approved
processing --> rejected
pending --> approved : manual review
pending --> rejected : manual review
approved --> [*]
rejected --> [*]

@enduml
```

### 10.7 Offline Sync Status

```plantuml
@startuml
title Offline Sync Action State

[*] --> queued_locally
queued_locally --> received
received --> applied
received --> rejected
received --> conflict
applied --> [*]
rejected --> [*]
conflict --> [*]

@enduml
```

## 11. Realtime Channel Map

```text
private-user.{userId}
  Authorization:
    authenticated user id equals {userId}
  Events:
    notification.created
    trip.status.updated for participant
    call.ringing for recipient
  Uses:
    persistent notifications, sound, action state, incoming ride, incoming call,
    payment failure, document decision

private-trip.{tripId}
  Authorization:
    passenger, assigned driver user, support, admin or super admin
  Events:
    trip.status.updated
    trip.location.updated
  Uses:
    live trip state and realtime map tracking

private-conversation.{conversationId}
  Authorization:
    conversation participant or authorized operations user added as participant
  Events:
    message.sent
    conversation.read
    conversation.typing
    call.ringing
    call.updated
  Uses:
    realtime chat, typing indicators, delivery/read receipts and call state

presence-call.{callSessionId}
  Authorization:
    caller or recipient of active call session
  Events:
    call.signal
    call.updated
  Uses:
    WebRTC offer, answer, ICE candidates and call presence

private-admin.operations
  Authorization:
    support, admin or super admin
  Events:
    operational alert
    support queue update
    payment webhook failure
    AI review required
  Uses:
    operations dashboard and support workflows
```

## 12. Deployment Diagram

```plantuml
@startuml
title Production Deployment View

node "Browser" {
  component "Next.js Web UI"
}

node "Web/Application Server" {
  component "Reverse Proxy / TLS"
  component "Next.js Runtime"
  component "PHP-FPM Laravel API"
  component "Laravel Reverb Process"
  component "Laravel Scheduler"
}

node "Worker Server or Process Group" {
  component "Default Queue Worker"
  component "Payment/Webhook Worker"
  component "AI/Upload Worker"
}

database "MySQL 8" as Mysql
database "Redis" as Redis
folder "Private File Storage" as Files
cloud "Google Maps"
cloud "Stripe"
cloud "OpenAI"
cloud "Email/SMS"

"Next.js Web UI" --> "Reverse Proxy / TLS" : HTTPS
"Next.js Web UI" --> "Laravel Reverb Process" : WSS
"Reverse Proxy / TLS" --> "Next.js Runtime"
"Reverse Proxy / TLS" --> "PHP-FPM Laravel API"
"PHP-FPM Laravel API" --> Mysql
"PHP-FPM Laravel API" --> Redis
"PHP-FPM Laravel API" --> Files
"PHP-FPM Laravel API" --> "Laravel Reverb Process"
"PHP-FPM Laravel API" --> "Default Queue Worker"
"Default Queue Worker" --> Mysql
"Payment/Webhook Worker" --> Mysql
"AI/Upload Worker" --> Mysql
"AI/Upload Worker" --> Files
"PHP-FPM Laravel API" --> "Google Maps"
"Payment/Webhook Worker" --> Stripe
"AI/Upload Worker" --> OpenAI
"Default Queue Worker" --> "Email/SMS"

@enduml
```

## 13. Required Diagram Coverage by MVP Capability

| Capability | Covered by diagrams |
| --- | --- |
| Realtime chat, notifications, ringing, audio and video calls | Use case, backend component, frontend component, chat/call sequence, call state, realtime channels |
| Persistent notifications like Glovo / Uber Eats | Use case, notification sequence, notification state, realtime channels |
| Realtime geolocation on map | Use case, frontend component, tracking sequence, realtime channels |
| Upload files with AI processing | Use case, backend component, upload/AI sequence, onboarding activity, document state |
| Offline mode and synchronization | Use case, offline sync sequence, trip activity, sync state |
| Payment or transaction with automatic callback | Use case, payment callback sequence, payment state, deployment |
| External API integrations | System context, backend component, deployment |

## 14. Maintenance Rules

- Update this file when a new module, state, event, table or external provider is
  introduced.
- Keep implementation status out of this file; use `TASKS.md`.
- If an endpoint changes behavior, update `API_SPEC.md` and the relevant
  sequence diagram.
- If a table or relation changes, update `DATABASE.md` and the database
  relationship diagram.
