# Data Flow

## Overview

This document describes how data flows through the Building Management System, from client request to database and back.

## Request Lifecycle

```
┌─────────┐    ┌─────────────┐    ┌────────────┐    ┌─────────────┐
│ Client  │───▶│  Middleware │───▶│ Controller │───▶│   Service   │
└─────────┘    └─────────────┘    └────────────┘    └─────────────┘
                                                           │
                                                           ▼
┌─────────┐    ┌─────────────┐    ┌────────────┐    ┌─────────────┐
│ Client  │◀───│  Resource   │◀───│ Controller │◀───│    Model    │
└─────────┘    └─────────────┘    └────────────┘    └─────────────┘
```

## Detailed Request Flow

### 1. HTTP Request Entry

```
Client Request
     │
     ▼
┌─────────────────────────────────────────────────────────────────┐
│                        public/index.php                          │
│                     (Application Bootstrap)                      │
└─────────────────────────────────────────────────────────────────┘
     │
     ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Router                                   │
│                    (routes/apis/api.php)                         │
│                                                                  │
│  Route::prefix('v1')->group(function () {                       │
│      Route::apiResource('users', UserController::class);         │
│  });                                                             │
└─────────────────────────────────────────────────────────────────┘
```

### 2. Middleware Pipeline

```
┌─────────────────────────────────────────────────────────────────┐
│                      Global Middleware                           │
├─────────────────────────────────────────────────────────────────┤
│  1. TrustProxies                                                │
│  2. HandleCors                                                  │
│  3. PreventRequestsDuringMaintenance                            │
│  4. ValidatePostSize                                            │
│  5. TrimStrings                                                 │
│  6. ConvertEmptyStringsToNull                                   │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                       API Middleware                             │
├─────────────────────────────────────────────────────────────────┤
│  1. APILanguageMiddleware    (Set language from header)         │
│  2. auth:sanctum             (Authenticate token)               │
│  3. VerifyAccountingBalance  (Check financial constraints)      │
│  4. ModifyCurrencyRequest    (Currency handling)                │
│  5. CheckAccountMiddleware   (Account verification)             │
│  6. CheckBranchSetup         (Branch configuration)             │
└─────────────────────────────────────────────────────────────────┘
```

### 3. Request Validation

```php
// Form Request Validation
class StoreUserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', User::class);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users'],
            'role_id' => ['required', 'exists:roles,id'],
        ];
    }
}
```

```
┌─────────────────────────────────────────────────────────────────┐
│                     Request Validation                           │
├─────────────────────────────────────────────────────────────────┤
│  1. authorize()  → Check permissions                            │
│  2. rules()      → Validate input data                          │
│  3. messages()   → Custom error messages                        │
│  4. validated()  → Return clean data                            │
└─────────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┴───────────────┐
              │                               │
         Valid Data                    Invalid Data
              │                               │
              ▼                               ▼
        Continue to                    422 Response
        Controller                     (Validation Errors)
```

### 4. Controller Processing

```php
class UserController extends Controller
{
    public function __construct(
        private UserService $userService
    ) {}

    public function store(StoreUserRequest $request): JsonResponse
    {
        // 1. Create DTO from validated request
        $dto = UserDTO::fromRequest($request);

        // 2. Delegate to service layer
        $user = $this->userService->create($dto);

        // 3. Return transformed response
        return response()->json([
            'success' => true,
            'data' => new UserResource($user)
        ], 201);
    }
}
```

### 5. Service Layer Processing

```php
class UserService
{
    public function __construct(
        private UserRepository $repository
    ) {}

    public function create(UserDTO $dto): User
    {
        // 1. Business logic validation
        $this->validateBusinessRules($dto);

        // 2. Create entity
        $user = $this->repository->create($dto->toArray());

        // 3. Dispatch domain events
        event(new UserCreated($user));

        // 4. Return entity
        return $user;
    }
}
```

### 6. Model/Database Interaction

```
┌─────────────────────────────────────────────────────────────────┐
│                       Eloquent Model                             │
├─────────────────────────────────────────────────────────────────┤
│  1. Mutators/Casts    → Transform data before saving           │
│  2. Observers         → Lifecycle hooks (creating, created)     │
│  3. Query Builder     → Build SQL query                         │
│  4. Database          → Execute query                           │
└─────────────────────────────────────────────────────────────────┘
```

```php
class User extends Model
{
    // Attribute casting
    protected $casts = [
        'email_verified_at' => 'datetime',
        'settings' => 'array',
    ];

    // Mutator
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => Hash::make($value),
        );
    }
}
```

### 7. Response Transformation

```php
class UserResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'role' => new RoleResource($this->whenLoaded('role')),
            'created_at' => $this->created_at->toISOString(),
        ];
    }
}
```

```
┌─────────────────────────────────────────────────────────────────┐
│                    Response Structure                            │
├─────────────────────────────────────────────────────────────────┤
│  {                                                               │
│    "success": true,                                              │
│    "code": 200,                                                  │
│    "message": "User created successfully",                       │
│    "data": {                                                     │
│      "id": 1,                                                    │
│      "name": "John Doe",                                         │
│      "email": "john@example.com",                                │
│      "created_at": "2026-02-08T10:30:00.000Z"                   │
│    }                                                             │
│  }                                                               │
└─────────────────────────────────────────────────────────────────┘
```

## Complete Flow Diagram

```
┌──────────────────────────────────────────────────────────────────────────┐
│                              CLIENT                                       │
│                    POST /api/v1/users                                     │
│                    Authorization: Bearer {token}                          │
│                    Content-Type: application/json                         │
│                    {"name": "John", "email": "john@example.com"}          │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  MIDDLEWARE PIPELINE                                                      │
│  ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐            │
│  │   CORS     │→│  Sanctum   │→│  Language  │→│   Branch   │            │
│  └────────────┘ └────────────┘ └────────────┘ └────────────┘            │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  FORM REQUEST                                                            │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  StoreUserRequest                                                │    │
│  │  - authorize(): Check 'users.create' permission                  │    │
│  │  - rules(): Validate name, email, role_id                        │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  CONTROLLER                                                              │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  UserController@store                                            │    │
│  │  - Create UserDTO from request                                   │    │
│  │  - Call UserService->create()                                    │    │
│  │  - Return UserResource response                                  │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  SERVICE                                                                 │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  UserService                                                     │    │
│  │  - Validate business rules                                       │    │
│  │  - Call Repository->create()                                     │    │
│  │  - Dispatch UserCreated event                                    │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  MODEL + DATABASE                                                        │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  User::create()                                                  │    │
│  │  - UserObserver->creating(): Hash password                       │    │
│  │  - INSERT INTO users ...                                         │    │
│  │  - UserObserver->created(): Log activity                         │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  RESPONSE                                                                │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │  HTTP 201 Created                                                │    │
│  │  {                                                               │    │
│  │    "success": true,                                              │    │
│  │    "data": { "id": 1, "name": "John", ... }                     │    │
│  │  }                                                               │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────────────┘
```

## Asynchronous Data Flow

### Event-Driven Processing

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Action    │────▶│   Event     │────▶│   Queue     │────▶│  Listener   │
│             │     │  Dispatch   │     │   (Redis)   │     │  (Worker)   │
└─────────────┘     └─────────────┘     └─────────────┘     └─────────────┘
                                                                   │
                                                                   ▼
                                                            ┌─────────────┐
                                                            │  Database   │
                                                            │  / Email    │
                                                            │  / External │
                                                            └─────────────┘
```

### Background Job Processing

```php
// Dispatch job
ProcessPayroll::dispatch($payrollRun)->onQueue('payroll');

// Job execution (via queue worker)
class ProcessPayroll implements ShouldQueue
{
    public function handle(): void
    {
        // Long-running payroll calculation
    }
}
```

## Data Transformation Layers

```
┌─────────────────────────────────────────────────────────────────┐
│                    Data Transformation                           │
├──────────────┬──────────────┬──────────────┬───────────────────┤
│    Layer     │    Input     │    Output    │    Transformer    │
├──────────────┼──────────────┼──────────────┼───────────────────┤
│  Request     │  Raw JSON    │  Validated   │  FormRequest      │
│  DTO         │  Validated   │  Domain Obj  │  DTO::fromRequest │
│  Model       │  Domain Obj  │  Eloquent    │  Mutators/Casts   │
│  Resource    │  Eloquent    │  API JSON    │  JsonResource     │
└──────────────┴──────────────┴──────────────┴───────────────────┘
```
