# Rule 104: Data Transfer Objects (DTOs) Standards

## 1. Context
SuiteX uses **spatie/laravel-data** (v4.x) to enforce type-safe contracts between services, API responses, and domain actions.

## 2. The Data Pipeline & Boundaries
In SuiteX, data follows a strict lifecycle. While `spatie/laravel-data` can technically handle multiple roles, we maintain these conceptual boundaries:

| Phase | Object Type | Primary Responsibility | Package/Class |
| :--- | :--- | :--- | :--- |
| **Ingress** | **Request** | HTTP Validation, Auth, Sanitization. | `FormRequest` or `Data` (as request) |
| **Contract** | **DTO** | Internal service-to-service communication. | `Data` (Immutable) |
| **Egress** | **Response** | JSON transformation, sensitive field hiding. | `Data` (as resource) |

### 2.1 The Workflow
`HTTP Request` ➔ `FormRequest (Validate)` ➔ `DTO (Type-safe Contract)` ➔ `Service` ➔ `Response DTO` ➔ `JSON`

## 3. Global Architecture Standards

## 3. The "Hybrid Flexible" Pattern (Mandatory for Multi-tenancy)
When handling models with tenant-specific custom fields:
1.  **Strictly Type** all base columns (ID, Title, external_id, etc.).
2.  **Explicit Array** for custom fields: `public array $customFields = []`.
3.  **Preservation:** Always use `fromNetSuiteRecord()` or `fromModel()` methods to ensure custom fields in the `fields` JSON column are not lost.

## 4. When to Use (Agent Decision Tree)
You MUST create a DTO if:
- A service receives an associative array as its primary input.
- A domain action has more than 3 parameters.
- Data is being imported from NetSuite (requires mapping).
- You are passing data between a Controller and a Service.

### 4.1 Request vs DTO Distinction
- **Use a Request Object** when you need to validate external user input (HTTP).
- **Use a DTO** when you are inside the Domain layer (Services/Actions). NEVER pass a `FormRequest` into a Service; convert it to a DTO first.
- **Use a Response DTO** to ensure the API never leaks internal model fields (like `deleted_at`) unless explicitly defined.

## 5. Anti-patterns
- ❌ Using `array` typehints for complex data payloads.
- ❌ Passing Eloquent Models directly into deep Service layers (violates DDD).
- ❌ Modifying DTOs after creation (they should be immutable Data objects).
