# Sistema de Reserva de Cajas - Guía Rápida

## Comandos de Instalación

```bash
# 1. Migrar base de datos
php artisan migrate

# 2. Crear permisos
php artisan db:seed --class=ReservationPermissionsSeeder

# 3. Limpiar caché
php artisan optimize:clear
```

## Flujo de Uso

### 1️⃣ Crear Reserva
```
Web: /reservations/create
- Seleccionar cliente
- Guardar
```

### 2️⃣ Descargar Inventario
```
Web: /reservations/inventory/available
- Descarga Excel con cajas disponibles
```

### 3️⃣ Marcar Cajas
```
Excel:
- Columna SELECCIONAR: poner "X" o "1"
- Guardar archivo
```

### 4️⃣ Importar Cajas
```
Web: /reservations/{id}/import
- Subir Excel
- Sistema crea reserva virtual
```

### 5️⃣ Confirmar Físicamente
```
Web: /order-preparation (pestaña Reservas)
- Seleccionar reserva
- Escanear cajas
- Completar → Crea orden
```

## API Endpoints Principales

### Gestión de Reservas
```bash
# Listar reservas
GET /reservations

# Crear reserva
POST /reservations
{
  "client_id": 1,
  "notes": "Reserva de prueba"
}

# Ver detalle
GET /reservations/{id}

# Importar cajas
POST /reservations/{id}/import
Content-Type: multipart/form-data
file: archivo.xlsx

# Cancelar reserva
DELETE /reservations/{id}/cancel
```

### Confirmación Física
```bash
# Listar reservas activas
GET /api/order-preparation/box-reservations

# Iniciar confirmación
POST /api/order-preparation/start-box-reservation
{
  "reservation_id": 1
}

# Confirmar escaneo de caja
POST /api/order-preparation/confirm-box-scan
{
  "reservation_id": 1,
  "box_number": "CAJA001"
}

# Agregar caja extra
POST /api/order-preparation/add-extra-box
{
  "reservation_id": 1,
  "box_number": "CAJA999"
}

# Completar reserva
POST /api/order-preparation/complete-box-reservation
{
  "reservation_id": 1
}
```

## Estados del Sistema

### Estados de Reserva
- `pending` - Creada, esperando confirmación
- `in_progress` - En proceso de confirmación
- `completed` - Completada y orden creada
- `cancelled` - Cancelada

### Estados de Item de Reserva
- `reserved` - Reservado virtualmente
- `confirmed` - Confirmado físicamente
- `cancelled` - Cancelado

### Estados de Inventario
- `available` - Disponible para reservar
- `reserved` - Reservado virtualmente
- `confirmed` - Confirmado físicamente

## Consultas SQL Útiles

```sql
-- Ver todas las reservas
SELECT 
    r.id,
    r.reservation_code,
    c.client_name,
    r.status,
    COUNT(ri.id) as total_boxes,
    SUM(CASE WHEN ri.status = 'confirmed' THEN 1 ELSE 0 END) as confirmed_boxes
FROM box_reservations r
JOIN clients c ON r.client_id = c.id
LEFT JOIN box_reservation_items ri ON r.id = ri.reservation_id
GROUP BY r.id;

-- Ver cajas de una reserva
SELECT 
    ri.box_number,
    ri.status,
    ri.scanned_at,
    i.cadena as marca,
    i.seccion,
    i.ubicacion
FROM box_reservation_items ri
JOIN inventory i ON ri.inventory_id = i.id
WHERE ri.reservation_id = 1;

-- Ver inventario reservado
SELECT 
    i.n_carton,
    i.reservation_status,
    c.client_name as reserved_for,
    r.reservation_code
FROM inventory i
LEFT JOIN clients c ON i.reserved_for_client_id = c.id
LEFT JOIN box_reservations r ON i.reservation_id = r.id
WHERE i.reservation_status != 'available';
```

## Pruebas con cURL

### Crear Reserva
```bash
curl -X POST http://localhost/reservations \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": 1,
    "notes": "Reserva de prueba"
  }'
```

### Listar Reservas Activas
```bash
curl http://localhost/api/order-preparation/box-reservations
```

### Confirmar Escaneo
```bash
curl -X POST http://localhost/api/order-preparation/confirm-box-scan \
  -H "Content-Type: application/json" \
  -d '{
    "reservation_id": 1,
    "box_number": "CAJA001"
  }'
```

## Solución Rápida de Problemas

### "Permission denied"
```bash
php artisan db:seed --class=ReservationPermissionsSeeder
php artisan permission:cache-reset
```

### "Table not found"
```bash
php artisan migrate
```

### "Class not found"
```bash
composer dump-autoload
php artisan optimize:clear
```

### Cajas no se marcan como reservadas
```sql
-- Verificar estado
SELECT reservation_status, COUNT(*) 
FROM inventory 
GROUP BY reservation_status;

-- Corregir manualmente si es necesario
UPDATE inventory 
SET reservation_status = 'available' 
WHERE reservation_id IS NULL;
```

## Archivos Importantes

**Backend**:
- `app/Models/BoxReservation.php`
- `app/Models/BoxReservationItem.php`
- `app/Http/Controllers/ReservationController.php`
- `app/Http/Controllers/OrderPreparationController.php`

**Migraciones**:
- `database/migrations/*_create_box_reservations_table.php`
- `database/migrations/*_create_box_reservation_items_table.php`
- `database/migrations/*_add_reservation_fields_to_inventory.php`

**Import/Export**:
- `app/Imports/ReservationBoxesImport.php`
- `app/Exports/InventoryAvailableExport.php`

**Rutas**:
- `routes/web.php` (líneas 303-333)

## Próximos Pasos

1. ✅ Backend completo
2. ✅ Rutas configuradas
3. ✅ Permisos listos
4. ⏳ Crear vistas Blade
5. ⏳ Actualizar UI order-preparation
6. ⏳ Testing completo
