# Guía demo: facturación OT y mora

Cómo probar facturación Softnet y bloqueo por mora con los datos del seeder demo.

## Requisitos previos

```bash
# Backend
cd taller_back
composer install
cp .env.example .env   # si aún no existe
php artisan key:generate
php artisan migrate:fresh --seed
# Si el entorno tiene modo Obreque activo:
# SEED_MODE=demo php artisan migrate:fresh --seed
php artisan serve

# Frontend (API real)
cd taller_front
cp .env.example .env
# VITE_USE_MOCK=false y URL del API apuntando al back (p. ej. http://127.0.0.1:8000)
npm install
npm run dev
```

### Usuarios demo

| Email | Password | Rol |
| --- | --- | --- |
| admin@taller.cl | demo | admin |
| recepcion@taller.cl | demo | reception |
| tecnico@taller.cl | demo | technician |
| bodega@taller.cl | demo | warehouse |

Los seeds viven en [`database/seeders/DatabaseSeeder.php`](../database/seeders/DatabaseSeeder.php).

---

## Mora

### Cómo se marca una mora

Hoy **no se marca desde la UI** del taller. El sistema solo **consulta** si el cliente tiene mora.

1. Existe la tabla `client_pending_situations` (en el front se menciona como “tabla Alex”).
2. Al elegir un cliente en el wizard de ingreso, el front llama  
   `GET /api/v1/clients/{id}/pending-situation`.
3. Si hay un registro activo (`tiene_situacion_pendiente = true`, fechas vigentes), se muestra la alerta y se bloquea el avance / la creación del ingreso.

**Cómo “marcar” mora hoy:** insertando (o dejando en seed) una fila en esa tabla, por RUT del cliente. Ejemplo del seeder (FleetCorp):

```php
ClientPendingSituation::create([
    'rut' => '77.888.999-0',
    'fecha_desde' => now()->subDays(60)->toDateString(),
    'fecha_hasta' => null,           // null = sin vencimiento
    'tiene_situacion_pendiente' => true,
    'tipo_situacion' => 'mora',
]);
```

Para **quitar** la mora: poner `tiene_situacion_pendiente = false`, o una `fecha_hasta` ya pasada, o borrar el registro.

**Qué no hay:**

- No hay pantalla de admin para marcar/quitar mora.
- No hay `POST`/`PATCH` de situación pendiente en la API del taller.
- No hay sync Softnet de mora en este código: solo lookup local de esa tabla.

En resumen: la mora se **carga en BD** (seed, SQL o proceso externo a “tabla Alex”); el taller solo la **lee y bloquea**.

### Qué deja el seed

`seedMoraMock()` crea una situación pendiente tipo **mora** para:

- Cliente: **FleetCorp Chile** (`c3`)
- RUT: `77.888.999-0`
- `tiene_situacion_pendiente = true`, `tipo_situacion = mora`

### Prueba manual (HTTP)

1. Login (admin o recepción).
2. Ir a **Ingresos a Taller** → **Nuevo ingreso**.
3. Buscar **FleetCorp Chile** y seleccionarlo.
4. Debe aparecer la alerta de mora (`mora-alert` / “situación pendiente”).
5. El botón **Siguiente** queda deshabilitado.

### Prueba automática

```bash
cd taller_front
npx playwright test ingresos.spec.ts -g "cliente moroso"
```

### API

```http
GET /api/v1/clients/{id}/pending-situation
Authorization: Bearer {token}
```

Feature test backend: `php artisan test --filter=MoraLookupTest`.

---

## Facturación OT (Softnet)

### Qué deja el seed

| Dato | Uso |
| --- | --- |
| **OT-2026-013** | Lista para **previsualizar/emitir**: `economic_closure_status = facturable`, sin `invoiced_at`, con ítems cobrables, cliente **Transportes Andes SpA** (giro, sin HES/OC obligatorio) |
| OT-2026-004 + Sale `F-12345` | Ya facturada (búsqueda / historial) |
| OT-2026-005 | Facturada sin Sale asociada (búsqueda tipo factura vía OT) |

### Prueba manual (HTTP)

1. Configurar Softnet en `taller_back/.env` (`SOFTNET_BASE_URL`, `SOFTNET_BEARER_TOKEN`, etc.).
2. `migrate:fresh --seed` + API + front con mock desactivado.
3. Login como **admin** (`admin@taller.cl` / `demo`).
4. Órdenes de trabajo → buscar **OT-2026-013** (o abrir su detalle por ID).
5. Botón **Facturar** → previsualización Softnet → **Emitir**.
6. Si Softnet responde OK: OT queda con `invoiced_at` y se crea la Sale.

> La emisión real depende de Softnet. Si el token/ambiente falla, el preview puede mostrar errores de cliente/producto/HES; los tests de Feature fakesan Softnet.

### Prueba automática (API)

```bash
cd taller_back
php artisan test --filter=WorkOrderInvoiceTest
```

### Prueba UI mock (sin Softnet real)

En mock el front usa la OT `wo7` / `#OT-00007` ya marcada facturable:

```bash
cd taller_front
npm run test:e2e:mock -- facturacion-ot.spec.ts
```

O manual: `VITE_USE_MOCK=true` → abrir `/ordenes-trabajo/wo7` → Facturar.

### Ventas (boleta / factura de mostrador)

```bash
cd taller_front
npx playwright test ventas.spec.ts
```

Cliente con giro para factura: **Transportes Andes SpA**.

---

## Comandos útiles

```bash
# Reset demo completo
cd taller_back && SEED_MODE=demo php artisan migrate:fresh --seed

# E2E HTTP (levanta back :8010 + Vite; hace migrate:fresh --seed)
cd taller_front && npm run test:e2e -- ingresos.spec.ts
cd taller_front && npm run test:e2e -- facturacion-ot.spec.ts   # preferir mock para wo7
cd taller_front && npm run test:e2e:mock -- facturacion-ot.spec.ts

# Cobertura facturación / mora (back)
cd taller_back && composer test:coverage
```

---

## Resumen

| Tema | Seed | Cómo probar |
| --- | --- | --- |
| Mora | FleetCorp Chile | Wizard ingreso o E2E `ingresos.spec.ts` |
| Emitir factura OT | **OT-2026-013** facturable | UI admin + Softnet, o `WorkOrderInvoiceTest` |
| Factura ya emitida | Sale `F-12345` / OT-2026-004 | Búsqueda o detalle OT |
| Facturar en mock | `wo7` | `test:e2e:mock facturacion-ot.spec.ts` |
