# OT Creation API - Standalone Implementation

This folder contains a complete standalone implementation for creating OT (Orden de Trabajo) via API endpoint.

## Files Included

1. **OTCreationService.php** - Core service class with all business logic
2. **OTCreationController.php** - API controller endpoint
3. **routes_example.php** - Example route definitions
4. **README.md** - This file
5. **test_example.php** - Example test file
6. **request_example.json** - Example request payload
7. **mock_ot_creation.js** - Standalone Node.js mock script (no dependencies)
8. **FLOW_REVIEW.md** - High-level flow review documentation

## Installation

### 1. Copy Files

Copy the service and controller files to your Laravel application:

```bash
# Copy service
cp api_implementation/OTCreationService.php app/Services/OTCreationService.php

# Copy controller
cp api_implementation/OTCreationController.php app/Http/Controllers/Api/OTCreationController.php
```

### 2. Create Service Directory (if it doesn't exist)

```bash
mkdir -p app/Services
```

### 3. Register Routes

Add to `routes/api.php`:

```php
use App\Http\Controllers\Api\OTCreationController;

Route::middleware(['auth:api'])->group(function () {
    Route::post('/ot/create', [OTCreationController::class, 'create'])->name('api.ot.create');
});
```

### 4. Register Service Provider (if using dependency injection)

Add to `app/Providers/AppServiceProvider.php`:

```php
use App\Services\OTCreationService;

public function register()
{
    $this->app->singleton(OTCreationService::class, function ($app) {
        return new OTCreationService();
    });
}
```

## Usage

### Request Format

**Endpoint**: `POST /api/ot/create`

**Headers**:
```
Authorization: Bearer {your_token}
Content-Type: application/json
```

**Request Body**:
```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
    }
  ]
}
```

### Success Response (201 Created)

```json
{
  "success": true,
  "message": "OT creada exitosamente",
  "data": {
    "id_ot": 12345,
    "estado": "pendiente",
    "created_at": "2024-01-15T10:30:00Z"
  },
  "errors": null
}
```

### Error Response (400 Bad Request)

```json
{
  "success": false,
  "message": "Error de validación",
  "data": null,
  "errors": {
    "cliente.rut": ["RUT de cliente inválido"],
    "vehiculos": ["Debe incluir al menos un vehículo"]
  }
}
```

### Error Response (404 Not Found)

```json
{
  "success": false,
  "message": "Técnico no encontrado",
  "data": null,
  "errors": {
    "tecnico.rut": ["El RUT del técnico no existe en el sistema"]
  }
}
```

## Features

### ✅ Complete Validation
- Input validation using Laravel Validator
- RUT format validation and verification digit calculation
- Email format validation
- Required field validation
- Vehicle data validation

### ✅ Business Logic
- GPS provider mapping (gpsimple, entel, tattersall, cemin, carflex)
- Service type mapping
- Taller configuration mapping
- Logo URL assignment

### ✅ Database Operations
- Transaction management for atomicity
- Client auto-creation if not exists
- Client auto-update if data differs
- Vehicle upsert (insert or ignore)
- OT-Vehicle linking

### ✅ Error Handling
- Comprehensive error messages
- Appropriate HTTP status codes
- Detailed logging
- Exception handling

### ✅ Security
- Input sanitization
- SQL injection prevention (using Eloquent/Query Builder)
- Authentication middleware support
- Rate limiting support

## Mock Simulation (Node.js)

A standalone Node.js script is included that simulates the complete OT creation flow without requiring any database or dependencies.

### Running the Mock Script

```bash
node mock_ot_creation.js
```

The script includes:
- Complete flow simulation (all 8 steps)
- Mock database (in-memory)
- RUT validation and formatting
- Business logic processing
- Transaction simulation
- Multiple test scenarios
- Detailed console output

**No installation required** - Just run with Node.js!

## Testing

### Using cURL

```bash
curl -X POST http://your-domain.com/api/ot/create \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d @request_example.json
```

### Using Postman

1. Set method to `POST`
2. URL: `http://your-domain.com/api/ot/create`
3. Headers:
   - `Authorization: Bearer YOUR_TOKEN`
   - `Content-Type: application/json`
4. Body: Raw JSON (use `request_example.json`)

### Unit Testing

See `test_example.php` for example unit tests.

## Dependencies

- Laravel 6.0+
- PHP 7.2+
- MySQL/MariaDB
- `malahierba-lab/chile-rut` package for RUT validation

## Configuration

### GPS Providers

Edit `OTCreationService.php` to modify GPS provider configuration:

```php
private const GPS_PROVIDERS = [
    'your_provider' => [
        'empresa' => 'your_empresa',
        'logo' => 'https://your-logo-url.png',
        'service_types' => [
            'instalacion_gps' => 'Your Service Name'
        ]
    ]
];
```

### Taller Configuration

Edit `OTCreationService.php` to modify taller configuration:

```php
private const TALLER_CONFIG = [
    'your_taller' => [
        'taller' => 'your_taller_value',
        'logo' => 'https://your-logo-url.png'
    ]
];
```

## Logging

All operations are logged. Check your Laravel log file (`storage/logs/laravel.log`) for:

- OT creation attempts
- Validation failures
- Database errors
- Success confirmations

## Troubleshooting

### Common Issues

1. **"Técnico no encontrado"**
   - Ensure technician RUT exists in `Tecnicos` table
   - Verify RUT format is correct

2. **"RUT inválido"**
   - Check RUT format (should be numbers only, without verification digit)
   - Verify RUT library is installed: `composer require malahierba-lab/chile-rut`

3. **Database errors**
   - Check foreign key constraints
   - Verify all tables exist
   - Check database connection

4. **Authentication errors**
   - Verify API token is valid
   - Check middleware configuration

## Support

For issues or questions, refer to:
- Main documentation: `API_OT_CREATION_DOCUMENTATION.md`
- Laravel documentation: https://laravel.com/docs/6.x
- RUT library: https://github.com/malahierba-lab/chile-rut

## License

This implementation follows the same license as the main project.

