# API OT Creation - Documentation

## Overview
This document outlines all tables, validations, business logic, and considerations needed to migrate OT (Orden de Trabajo) creation to an API endpoint.

---

## 1. Involved Database Tables

### 1.1 Primary Table: `OT`
**Purpose**: Main table storing order of work records

**Key Fields**:
- `id_ot` (Primary Key, Auto-increment)
- `rut_cliente` (VARCHAR, Foreign Key → `Clientes.rut_cliente`)
- `rut_tecnico` (VARCHAR, Foreign Key → `Tecnicos.rut_tecnico`)
- `direccion_instalacion` (VARCHAR, Required)
- `comuna_instalacion` (VARCHAR, Required)
- `telefono_instalacion` (VARCHAR, Required)
- `email_instalacion` (VARCHAR, Required, Email format)
- `estado_ot` (VARCHAR, Default: "pendiente")
- `empresa` (VARCHAR, Required) - Values: 'gpsimple', 'entel', 'tattersall', 'cemin', 'carflex'
- `taller` (VARCHAR, Required) - Values: 'domicilio', 'servitattersall'
- `motivo` (VARCHAR, Required) - Service type description
- `logo_taller` (VARCHAR, URL)
- `logo_servicio` (VARCHAR, URL)
- `rut_contacto` (VARCHAR, Nullable, Foreign Key → `Contactos.rut_contacto`)
- `imgfirma` (BLOB, Nullable) - Digital signature image
- `obser_ot` (TEXT, Nullable) - Observations
- `hora_llegada` (TIME, Nullable)
- `hora_salida` (TIME, Nullable)
- `fecha` (DATE, Nullable)
- `creado_en` (TIMESTAMP, Auto)
- `actualizado_en` (TIMESTAMP, Auto)

**Constraints**:
- Foreign key constraints on `rut_cliente` and `rut_tecnico`
- `estado_ot` should be one of: "pendiente", "en_proceso", "completada", etc.

---

### 1.2 Junction Table: `OT_Vehiculos`
**Purpose**: Links OT to vehicles (Many-to-Many relationship)

**Key Fields**:
- `id_ot` (INT, Foreign Key → `OT.id_ot`)
- `patente` (VARCHAR, Foreign Key → `Vehiculos.patente`)

**Constraints**:
- Composite primary key: (`id_ot`, `patente`)
- Foreign key constraints on both fields

---

### 1.3 Reference Table: `Vehiculos`
**Purpose**: Vehicle master data

**Key Fields**:
- `patente` (VARCHAR, Primary Key)
- `marca` (VARCHAR)
- `modelo` (VARCHAR)
- `color` (VARCHAR)
- `anio` (INT) - Year
- `id_tipo_vehiculo` (INT, Foreign Key → `Tipos_Vehiculos.id_tipo_vehiculo`)

**Behavior**:
- Uses `insertOrIgnore()` - if vehicle exists, ignore; if not, insert

---

### 1.4 Reference Table: `Clientes`
**Purpose**: Client master data

**Key Fields**:
- `rut_cliente` (VARCHAR, Primary Key, Format: "12345678-9")
- `nombre` (VARCHAR)
- `direccion` (VARCHAR)
- `comuna` (VARCHAR)
- `email` (VARCHAR)
- `telefono` (VARCHAR)
- `id_plan_comercial` (INT, Nullable)

**Constraints**:
- RUT must be valid Chilean RUT format
- Foreign key relationship with `OT.rut_cliente`

---

### 1.5 Reference Table: `Tecnicos`
**Purpose**: Technician/Installer master data

**Key Fields**:
- `rut_tecnico` (VARCHAR, Primary Key, Format: "12345678-9")
- `nombre` (VARCHAR)
- `idgpsimple` (INT, Foreign Key → `users.id`)

**Constraints**:
- RUT must be valid Chilean RUT format
- Foreign key relationship with `OT.rut_tecnico`

---

### 1.6 Reference Table: `Contactos`
**Purpose**: Contact persons associated with clients

**Key Fields**:
- `rut_contacto` (VARCHAR, Primary Key)
- `nombre` (VARCHAR)
- `email` (VARCHAR)
- `rut_cliente` (VARCHAR, Foreign Key → `Clientes.rut_cliente`)

**Behavior**:
- Created/updated via `updateOrCreate()` when signature is captured
- Not required at OT creation time

---

### 1.7 Related Tables (Not directly involved in creation, but referenced later)

- `Servicios` - Services performed on vehicles
- `OT_Actividades` - Activities linked to services
- `Actividades` - Activity types catalog
- `Vehiculos_Gps` - GPS devices installed in vehicles
- `Gps` - GPS device master data
- `Tipos_Gps` - GPS device types catalog
- `Tipos_Vehiculos` - Vehicle types catalog
- `Diagnosticos` - Diagnostic codes catalog
- `OT_Diagnosticos` - Diagnostics linked to services
- `Trabajos` - Work types catalog
- `OT_Trabajos` - Works linked to services
- `Imagenes` - Images associated with services

---

## 2. Input Parameters & Validations

### 2.1 Required Input Fields

#### Client Information
- `rut_cliente` (String) - RUT without verification digit, dots, or dashes
- `nom_cliente` (String) - Client name (from select dropdown)
- `dir_cliente` (String) - Installation address
- `comuna_cliente` (String) - Installation commune/municipality
- `tel_cliente` (String) - Contact phone
- `email_cliente` (String) - Valid email format

#### Technician Information
- `rut_instal` (String) - Technician RUT without verification digit, dots, or dashes

#### Service Configuration
- `presGPS` (String) - GPS provider: 'gpsimple', 'entel', 'tattersall', 'cemin', 'carflex'
- `tiposerv` (String) - Service type: 'instalacion_gps', 'visita_tecnica', 'desinstalacion_gps'
- `taller_install` (String) - Installation location: 'cartec', 'servitattersall'

#### Vehicle Information (Array)
- `patente_Tvehi[]` (Array of Strings) - Vehicle license plates
- `marca_Tvehi[]` (Array of Strings) - Vehicle brands
- `modelo_Tvehi[]` (Array of Strings) - Vehicle models
- `color_Tvehi[]` (Array of Strings) - Vehicle colors
- `anho_Tvehi[]` (Array of Integers) - Vehicle years

**Note**: All vehicle arrays must have the same length (one entry per vehicle)

---

### 2.2 Validation Rules

#### RUT Validation
- **Format**: Chilean RUT format (12345678-9)
- **Cleaning**: Remove dots, dashes, and verification digit before validation
- **Verification**: Calculate verification digit using Chilean RUT algorithm (modulo 11)
- **Library**: Uses `malahierba-lab/chile-rut` package (`RUT` class)
- **Processing**:
  1. Clean input: `preg_replace('/[^0-9]/', '', $rut)`
  2. Validate numeric
  3. Calculate verification digit: `$rutm->digitoVerificador($rut_clean)`
  4. Format: `$rut_clean . '-' . $digitoVerificador`

#### Email Validation
- Must be valid email format
- Frontend uses HTML5 `type="email"` validation
- Backend should validate format

#### Required Field Validation
- All client fields are required (frontend uses `required` attribute)
- At least one vehicle must be provided
- All vehicle arrays must have matching lengths

#### Business Rule Validations
- `rut_cliente` must exist in `Clientes` table (or be created)
- `rut_tecnico` must exist in `Tecnicos` table
- `presGPS` must be one of valid values
- `tiposerv` must be one of valid values
- `taller_install` must be one of valid values

---

## 3. Business Logic & Processing

### 3.1 Service Type Mapping

The `tiposerv` input is mapped to a descriptive string based on GPS provider:

| presGPS | tiposerv | Result |
|---------|----------|--------|
| gpsimple | instalacion_gps | "Instalación GPS" |
| entel | instalacion_gps | "Instalación GPS FollowMyCar" |
| tattersall | instalacion_gps | "Instalación GPS Tattersall" |
| cemin | instalacion_gps | "Instalación GPS Cemin" |
| carflex | instalacion_gps | "Instalación GPS CarFlex" |
| * | visita_tecnica | "Visita_tecnica GPS" |
| * | desinstalacion_gps | "Desinstalación GPS" |

---

### 3.2 GPS Provider & Logo Mapping

| presGPS | empresa | logo_servicio |
|---------|---------|--------------|
| gpsimple | 'gpsimple' | 'https://media.recuperauto.cl/Media/Cartec/gpsimple-logo.png' |
| entel | 'entel' | 'https://media.recuperauto.cl/Media/Cartec/follow-logo.png' |
| tattersall | 'tattersall' | 'https://media.recuperauto.cl/Media/Cartec/tattersall.png' |
| cemin | 'cemin' | 'https://media.recuperauto.cl/Media/Cartec/cemin.png' |
| carflex | 'carflex' | 'https://media.recuperauto.cl/Media/Cartec/carflex.png' |

**Default**: If not specified, defaults to:
- `empresa` = 'gpsimple'
- `logo_servicio` = 'https://media.recuperauto.cl/Media/Cartec/gpsimple-logo.png'

---

### 3.3 Taller & Logo Mapping

| taller_install | taller | logo_taller |
|----------------|--------|-------------|
| cartec | 'domicilio' | 'https://media.recuperauto.cl/Media/Cartec/cartec-logo.png' |
| servitattersall | 'servitattersall' | 'https://media.recuperauto.cl/Media/Cartec/servitattersall-logo.svg' |

**Default**: If not specified, defaults to:
- `taller` = 'domicilio'
- `logo_taller` = 'https://media.recuperauto.cl/Media/Cartec/cartec-logo.png'

---

### 3.4 Processing Flow

1. **Input Sanitization**
   - Clean RUTs (remove formatting)
   - Validate RUT format
   - Calculate verification digits
   - Format RUTs with verification digits

2. **Business Logic Application**
   - Map `presGPS` → `empresa` and `logo_servicio`
   - Map `taller_install` → `taller` and `logo_taller`
   - Map `tiposerv` + `presGPS` → `motivo`

3. **OT Creation**
   - Create new `OT` record with:
     - Client and technician RUTs (formatted)
     - Installation address and contact info
     - Service configuration (empresa, taller, motivo, logos)
     - Default `estado_ot` = "pendiente"
   - Get generated `id_ot`

4. **Vehicle Processing**
   - For each vehicle in arrays:
     - Insert or ignore into `Vehiculos` table (upsert behavior)
     - Link vehicle to OT via `OT_Vehiculos` junction table

5. **Response**
   - Return `id_ot` for redirect to work execution page

---

## 4. Database Constraints & Checks

### 4.1 Foreign Key Constraints

- `OT.rut_cliente` → `Clientes.rut_cliente`
  - **Action**: Must exist or be created first
  - **Cascade**: Update cascade, Delete set null

- `OT.rut_tecnico` → `Tecnicos.rut_tecnico`
  - **Action**: Must exist
  - **Cascade**: Update cascade, Delete set null

- `OT_Vehiculos.id_ot` → `OT.id_ot`
  - **Action**: Must exist
  - **Cascade**: Delete cascade

- `OT_Vehiculos.patente` → `Vehiculos.patente`
  - **Action**: Must exist (created via insertOrIgnore)

### 4.2 Data Integrity Checks

- **RUT Format**: Must be valid Chilean RUT format after processing
- **Email Format**: Must be valid email format
- **Array Consistency**: All vehicle arrays must have same length
- **Required Fields**: All required fields must be present and non-empty
- **Enum Values**: `empresa`, `taller`, `estado_ot` must match allowed values

---

## 5. API Endpoint Design Considerations

### 5.1 Endpoint Structure

**POST** `/api/ot/create`

### 5.2 Request Body Structure

```json
{
  "cliente": {
    "rut": "12345678",
    "nombre": "Juan Pérez",
    "direccion": "Av. Principal 123",
    "comuna": "Santiago",
    "telefono": "+56912345678",
    "email": "cliente@example.com"
  },
  "tecnico": {
    "rut": "98765432"
  },
  "servicio": {
    "presGPS": "gpsimple",
    "tiposerv": "instalacion_gps",
    "taller_install": "cartec"
  },
  "vehiculos": [
    {
      "patente": "ABCD12",
      "marca": "Toyota",
      "modelo": "Corolla",
      "color": "Blanco",
      "anio": 2020
    }
  ]
}
```

### 5.3 Response Structure

**Success Response (201 Created)**:
```json
{
  "success": true,
  "message": "OT creada exitosamente",
  "data": {
    "id_ot": 12345,
    "estado": "pendiente",
    "created_at": "2024-01-15T10:30:00Z"
  }
}
```

**Error Response (400 Bad Request)**:
```json
{
  "success": false,
  "message": "Error de validación",
  "errors": {
    "cliente.rut": ["RUT inválido"],
    "vehiculos": ["Debe incluir al menos un vehículo"]
  }
}
```

**Error Response (404 Not Found)**:
```json
{
  "success": false,
  "message": "Técnico no encontrado",
  "error": "El RUT del técnico no existe en el sistema"
}
```

---

## 6. Implementation Checklist

### 6.1 Pre-API Checks

- [ ] Verify `rut_cliente` exists in `Clientes` table
  - If not exists, create client record first
  - Or return error requiring client creation

- [ ] Verify `rut_tecnico` exists in `Tecnicos` table
  - Must exist, cannot be created automatically
  - Return 404 if not found

- [ ] Validate all required fields are present
- [ ] Validate RUT formats (client and technician)
- [ ] Validate email format
- [ ] Validate vehicle arrays consistency
- [ ] Validate enum values (`presGPS`, `tiposerv`, `taller_install`)

### 6.2 Transaction Management

- [ ] Wrap OT creation in database transaction
- [ ] Rollback on any error during vehicle processing
- [ ] Ensure atomicity: either all vehicles linked or none

### 6.3 Error Handling

- [ ] Handle foreign key constraint violations
- [ ] Handle duplicate key violations
- [ ] Handle validation errors
- [ ] Handle database connection errors
- [ ] Return appropriate HTTP status codes

### 6.4 Logging & Monitoring

- [ ] Log all OT creation attempts
- [ ] Log validation failures
- [ ] Log database errors
- [ ] Track creation metrics (success rate, average time)

---

## 7. Security Considerations

### 7.1 Authentication & Authorization

- [ ] Require authentication token (JWT/Bearer)
- [ ] Verify user has permission to create OT
- [ ] Check user role (may need specific role)
- [ ] Rate limiting to prevent abuse

### 7.2 Input Sanitization

- [ ] Sanitize all string inputs
- [ ] Validate and sanitize RUT inputs
- [ ] Validate email format
- [ ] Prevent SQL injection (use parameterized queries)
- [ ] Prevent XSS attacks (sanitize before storage)

### 7.3 Data Validation

- [ ] Server-side validation (don't trust client)
- [ ] Validate RUT format and verification digit
- [ ] Validate email format
- [ ] Validate phone number format (optional)
- [ ] Validate URL format for logos
- [ ] Validate array lengths match

---

## 8. Dependencies

### 8.1 External Libraries

- **RUT Validation**: `malahierba-lab/chile-rut` package
  - Class: `RUT`
  - Method: `digitoVerificador($rut)`
  - Must be available in API environment

### 8.2 Database Dependencies

- MySQL/MariaDB database
- All referenced tables must exist
- Foreign key constraints must be enabled
- Proper indexes on foreign keys

### 8.3 Service Dependencies

- Client must exist or be creatable
- Technician must exist (cannot be auto-created)
- Vehicle records can be auto-created via `insertOrIgnore`

---

## 9. Post-Creation Actions

### 9.1 Immediate Actions

- Redirect to work execution page (`/realizarot/{id_ot}`)
- Return `id_ot` in API response

### 9.2 Future Actions (Not in creation flow)

- Service creation (`Servicios` table)
- Activity linking (`OT_Actividades`)
- GPS device linking (`Vehiculos_Gps`)
- Image uploads (`Imagenes`)
- Signature capture (`Contactos`, `OT.rut_contacto`, `OT.imgfirma`)
- PDF generation
- Email notifications

---

## 10. Testing Considerations

### 10.1 Unit Tests

- [ ] RUT validation and formatting
- [ ] Service type mapping logic
- [ ] Logo URL mapping logic
- [ ] Vehicle array processing
- [ ] Error handling scenarios

### 10.2 Integration Tests

- [ ] Complete OT creation flow
- [ ] Foreign key constraint handling
- [ ] Transaction rollback on errors
- [ ] Vehicle upsert behavior
- [ ] Database constraint violations

### 10.3 Edge Cases

- [ ] Empty vehicle array
- [ ] Invalid RUT formats
- [ ] Missing required fields
- [ ] Invalid enum values
- [ ] Non-existent technician
- [ ] Non-existent client (with/without auto-create)
- [ ] Duplicate vehicle plates
- [ ] Very long strings (field length limits)
- [ ] Special characters in strings
- [ ] SQL injection attempts

---

## 11. Migration Strategy

### 11.1 Backward Compatibility

- Keep existing web form endpoint functional
- API endpoint should mirror web form behavior
- Ensure same validation rules
- Ensure same business logic

### 11.2 Gradual Migration

1. **Phase 1**: Create API endpoint alongside web form
2. **Phase 2**: Update frontend to use API (optional)
3. **Phase 3**: Deprecate web form endpoint (future)

### 11.3 Data Consistency

- Ensure API creates same data structure as web form
- Verify all fields are populated correctly
- Test with existing data to ensure compatibility

---

## 12. Additional Notes

### 12.1 Default Values

- `estado_ot` = "pendiente" (hardcoded)
- `empresa` = "gpsimple" (if not specified)
- `taller` = "domicilio" (if not specified)
- `tiposerv` = "Visita_tecnica GPS" (if not specified)

### 12.2 Timestamps

- `creado_en` - Auto-set by Laravel/Eloquent
- `actualizado_en` - Auto-set by Laravel/Eloquent
- `fecha` - Can be set later (nullable)

### 12.3 Optional Fields (Set Later)

- `rut_contacto` - Set when signature is captured
- `imgfirma` - Set when signature is captured
- `obser_ot` - Set during work execution
- `hora_llegada` - Set during work execution
- `hora_salida` - Set during work execution

---

## 13. API Endpoint Example Implementation

### 13.1 Route Definition

```php
Route::post('/api/ot/create', [OrdentrabajoController::class, 'createOT'])->middleware(['auth:api']);
```

### 13.2 Controller Method Signature

```php
public function createOT(Request $request)
{
    // Validation
    // Business logic
    // Database operations
    // Response
}
```

### 13.3 Validation Rules (Laravel)

```php
$validated = $request->validate([
    'cliente.rut' => 'required|string',
    'cliente.nombre' => 'required|string|max:255',
    'cliente.direccion' => 'required|string|max:255',
    'cliente.comuna' => 'required|string|max:100',
    'cliente.telefono' => 'required|string|max:20',
    'cliente.email' => 'required|email|max:255',
    'tecnico.rut' => 'required|string',
    'servicio.presGPS' => 'required|in:gpsimple,entel,tattersall,cemin,carflex',
    'servicio.tiposerv' => 'required|in:instalacion_gps,visita_tecnica,desinstalacion_gps',
    'servicio.taller_install' => 'required|in:cartec,servitattersall',
    'vehiculos' => 'required|array|min:1',
    'vehiculos.*.patente' => 'required|string|max:10',
    'vehiculos.*.marca' => 'required|string|max:50',
    'vehiculos.*.modelo' => 'required|string|max:50',
    'vehiculos.*.color' => 'required|string|max:30',
    'vehiculos.*.anio' => 'required|integer|min:1900|max:' . (date('Y') + 1),
]);
```

---

## 14. Summary

### Key Points

1. **Tables Involved**: `OT`, `OT_Vehiculos`, `Vehiculos`, `Clientes`, `Tecnicos`
2. **Critical Validations**: RUT format, email format, required fields, enum values
3. **Business Logic**: Service type mapping, logo URL mapping, RUT formatting
4. **Transaction Safety**: Use database transactions for atomicity
5. **Error Handling**: Comprehensive error responses with appropriate HTTP codes
6. **Security**: Authentication, authorization, input sanitization, SQL injection prevention

### Next Steps

1. Review and approve this documentation
2. Design API endpoint structure
3. Implement validation layer
4. Implement business logic layer
5. Implement database layer with transactions
6. Add error handling and logging
7. Write comprehensive tests
8. Deploy and monitor

---

**Document Version**: 1.0  
**Last Updated**: 2024-01-15  
**Author**: AI Assistant  
**Status**: Draft for Review

