> For the complete documentation index, see [llms.txt](https://t420.gitbook.io/t420/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://t420.gitbook.io/t420/data_flow.md).

# FleetOS Data Flow — Production Reference

## Service Request Lifecycle

```
Fleet creates Work Order
  ↓
  QueryService.createServiceRequest()
    → INSERT INTO service_requests (status='pending')
    → EventLogService.log('service_request_created')
    → NotificationService.notifyOrganisation(supplier_company_id)
      → Find contact: contactHint → lastActiveContact → company default
      → Generate magic link (7-day expiry, rfq-scoped)
      → Send via Email (Resend) OR WhatsApp (Twilio)
  ↓
Supplier sees request in dashboard
  ↓
  useFleetOSDashboard.loadData()
    → QueryService.getCompanyServiceRequests({ companyRole: 'supplier' })
    → SELECT * FROM service_requests WHERE supplier_company_id = ?
  ↓
Supplier accepts (acknowledges)
  ↓
  QueryService.acknowledgeRequest()
    → UPDATE service_requests SET status='acknowledged', quoted_amount, technician_name, ...
    → EventLogService.log('request_acknowledged')
    → NotificationService.notifyOrganisation(fleet_company_id) — notify fleet
  ↓
Supplier accepts (formal)
  ↓
  QueryService.acceptRequest()
    → UPDATE service_requests SET status='accepted', accepted_at
    → EventLogService.log('request_accepted')
    → Notify fleet with quote details
  ↓
Supplier starts work
  ↓
  QueryService.startRequest()
    → UPDATE service_requests SET status='in_progress', started_at
    → EventLogService.log('request_started')
    → Notify fleet
  ↓
Supplier completes work
  ↓
  QueryService.completeRequest()
    → UPDATE service_requests SET status='completed', completed_at, final_cost, completion_photo_url
    → EventLogService.log('request_completed')
    → Notify fleet with final cost
```

## Notification Routing

```
NotificationService.notifyOrganisation(orgId)
  ↓
  Step 1: Find recipient
    → If contactHint provided (phone/email) → use directly
    → Else: QueryService.getLastActiveCompanyContact(orgId)
      → SELECT * FROM contacts WHERE company_id = ? ORDER BY last_seen_at DESC
    → Else: SELECT default_notification_channel FROM companies WHERE company_id = ?
    → Else: FAIL (no routing target)
  ↓
  Step 2: Generate magic link
    → MagicLinkService.encodeToken({ companyId, targetPath, rfqId, exp })
    → URL: https://fleetos.us/auth/magic?token=PAYLOAD.SIG
  ↓
  Step 3: Send notification
    → If email: fetch(SUPABASE_URL/functions/v1/send-email)
      → Resend API: POST https://api.resend.com/emails
    → If phone: fetch(SUPABASE_URL/functions/v1/send-whatsapp)
      → Twilio API: POST https://api.twilio.com/.../Messages.json
```

## Database Tables

### service\_requests

| Column                 | Type        | Description                                                           |
| ---------------------- | ----------- | --------------------------------------------------------------------- |
| request\_id            | UUID PK     | Auto-generated                                                        |
| fleet\_company\_id     | UUID FK     | Company that created the request                                      |
| supplier\_company\_id  | UUID FK     | Company assigned to handle it                                         |
| status                 | VARCHAR     | pending → acknowledged → accepted → in\_progress → completed/declined |
| fleet\_name            | VARCHAR     | Fleet company display name                                            |
| vehicle\_identifier    | VARCHAR     | e.g., "Truck #42"                                                     |
| location               | VARCHAR     | Service location                                                      |
| description            | TEXT        | What's needed                                                         |
| urgency                | VARCHAR     | URGENT / TODAY / SCHEDULED                                            |
| tracking\_token        | VARCHAR     | UUID for /track/:token magic link                                     |
| quoted\_amount         | DECIMAL     | Supplier's quote                                                      |
| final\_cost            | DECIMAL     | Actual cost at completion                                             |
| currency               | VARCHAR     | USD (default)                                                         |
| technician\_name       | VARCHAR     | Assigned technician                                                   |
| completion\_photo\_url | TEXT        | Proof of completion                                                   |
| created\_at            | TIMESTAMPTZ | Request creation                                                      |
| acknowledged\_at       | TIMESTAMPTZ | Supplier first saw it                                                 |
| accepted\_at           | TIMESTAMPTZ | Supplier formally accepted                                            |
| started\_at            | TIMESTAMPTZ | Work began                                                            |
| completed\_at          | TIMESTAMPTZ | Work finished                                                         |

### contacts

| Column           | Type        | Description                           |
| ---------------- | ----------- | ------------------------------------- |
| contact\_id      | UUID PK     | Auto-generated                        |
| company\_id      | UUID FK     | Which company this contact belongs to |
| contact\_value   | VARCHAR     | Email or phone (E.164)                |
| contact\_type    | VARCHAR     | email / phone / whatsapp              |
| display\_name    | VARCHAR     | Human name                            |
| last\_active\_at | TIMESTAMPTZ | Last interaction                      |

### companies

| Column                         | Type    | Description                                     |
| ------------------------------ | ------- | ----------------------------------------------- |
| company\_id                    | UUID PK | Auto-generated                                  |
| domain                         | VARCHAR | Email domain (or slugified name for free email) |
| company\_name                  | VARCHAR | Display name                                    |
| default\_notification\_channel | VARCHAR | email / whatsapp                                |
| default\_notification\_target  | VARCHAR | Fallback contact value                          |

### event\_log

| Column              | Type        | Description                                            |
| ------------------- | ----------- | ------------------------------------------------------ |
| event\_type         | VARCHAR     | service\_request\_created, request\_acknowledged, etc. |
| company\_id         | UUID FK     | Who performed the action                               |
| contact\_id         | UUID FK     | Which contact acted                                    |
| target\_request\_id | UUID FK     | Which request was affected                             |
| metadata            | JSONB       | Action-specific data                                   |
| created\_at         | TIMESTAMPTZ | When it happened                                       |

## Magic Link Structure

```
Token = Base64(JSON payload) + "." + DJBX33A signature

Payload:
{
  companyId: UUID,          // Scope: which company
  companyName: string,      // Display name
  targetPath: string,       // e.g., /supplier/requests/{rfqId}
  accessType: string,       // rfq_scoped | org_daily_access
  rfqId: UUID,              // Optional: specific request
  exp: number               // Expiration timestamp (7 days default)
}
```

## Who Sees What

| Event                | Fleet Sees                          | Supplier Sees                   | Notification Sent To      |
| -------------------- | ----------------------------------- | ------------------------------- | ------------------------- |
| Work order created   | In their dashboard immediately      | In their dashboard on next load | Supplier (email/WhatsApp) |
| Request acknowledged | Status updates on refresh           | Status changes to "Accepted"    | Fleet (email/WhatsApp)    |
| Request accepted     | Status + quote visible              | Status confirmed                | Fleet (email/WhatsApp)    |
| Work started         | Status = "In Progress"              | Can track progress              | Fleet (email/WhatsApp)    |
| Work completed       | Status = "Completed" + photo        | Final cost visible              | Fleet (email/WhatsApp)    |
| Request declined     | Status = "Declined" (visible, grey) | Status = "Declined"             | Fleet (email/WhatsApp)    |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://t420.gitbook.io/t420/data_flow.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
