# Libro de Guías v1 - EVENTSUD - SOK

**Identificador del Set SII:** `4841004`
**Tipo de Set:** LIBRO DE GUIAS - Version 1
**RUT Emisor:** `78073481-7`
**RUT Firmante (RutEnvia):** `16658678-K`
**Track ID:** `249684108`
**FolioNotificacion:** `2`
**Fecha:** 2026-05-26
**Estado SII envio:** OK
**Estado SII revision del set:** `SOK - SET DE PRUEBA CORRECTO`

## Contenido

Libro **TipoLibro=ESPECIAL, TipoEnvio=TOTAL** con las 3 guías del set guías
EVENTSUD (track DTE 0249677370).

**ResumenPeriodo:**
- TotGuiaAnulada=1 (caso 3 folio 3 anulada)
- TotGuiaVenta=1 (solo caso 2 cuenta como venta)
- TotMntGuiaVta=2.080.207
- TotTraslado tpo=5: CantGuia=1 (caso 1 traslado interno)

**Detalle:**

| # | Folio | Anulado | TpoOper | RUTDoc | Notas |
|---|---|---|---|---|---|
| 1 | 1 | — | 5 | 78073481-7 | Traslado interno (sin venta) |
| 2 | 2 | — | 1 | 78014612-5 | Venta + TpoDocRef=33 FolioDocRef=13 (facturada) |
| 3 | 3 | **2** | 1 | 78014612-5 | Venta anulada |

## Historial de intentos hasta SOK

| Intento | TrackID | Resultado | Diagnostico |
|---|---|---|---|
| v1 | 249680740 | LRF (firma) | C14N del SignedInfo aislado no incluia xmlns:xsi heredado del root |
| v2 | 249681614 | LRC (caratula) | RutEnvia=RUT emisor en vez de RUT firmante |
| v3 | 249682818 | SRH revisión | TotGuiaVenta contaba caso 2 y 3 como ventas; caso 3 debia ser anulada y caso 2 debia indicar TpoDocRef de factura |
| **v4** | **249684108** | **SOK** | OK |

## Fixes incorporados

1. **firmar libro construyendo SignedInfo dentro del DOM** (commit `f44525a`)
   Inclusive C14N hereda xmlns:xsi del root → c14n del SignedInfo dentro del
   libro tiene xmlns:xsi, c14n aislado no. Fix: construir Signature con
   createElementNS dentro del DOM del libro antes de calcular c14n.

2. **caratula libros: RutEnvia=cert + TipoLibro=ESPECIAL + FolioNotificacion**
   (commit `c97d47a`). El SII compara RutEnvia contra rutSender del multipart.

3. **buildGuias acepta metadatos por folio** (commit `c..` actual)
   `metadatos[folio] = {anulada: bool, factura_ref: {tipo, folio, fecha}}`.
   - `anulada=true` → `<Anulado>2</Anulado>` y la guía cuenta en TotGuiaAnulada
     (no en TotGuiaVenta).
   - `factura_ref={tipo, folio, fecha}` → agrega `<TpoDocRef>`, `<FolioDocRef>`,
     `<FchDocRef>` en el Detalle indicando la factura que cobra la guía.

## Como reproducir

```bash
php artisan tinker --execute='
use App\Models\Dte\DteDocumento;
use App\Models\Parametros\ParEmpresa;
use App\Services\FacturacionElectronica\Services\CertificateService;
use App\Services\FacturacionElectronica\Services\EnvelopeService;
use App\Services\FacturacionElectronica\Services\LibroBuilder;

$emp = ParEmpresa::find(1);
$cert = app(CertificateService::class)->loadCertificate(1);
$dtes = DteDocumento::where("track_id","0249677370")->where("tipo_dte",52)->orderBy("folio")->get();
$meta = [
    2 => ["factura_ref" => ["tipo"=>33, "folio"=>13, "fecha"=>"2026-05-26"]],
    3 => ["anulada" => true],
];
$r = app(LibroBuilder::class)->buildGuias($emp, "2026-05", $dtes, 2, $cert->getId(), "ESPECIAL", $meta);
$xml = app(EnvelopeService::class)->firmarLibro($r["xml"], $cert, $r["id"]);
file_put_contents("libro_guias.xml", $xml);
'
```

## Notas operacionales

- **Las guías facturadas en el período** (cobradas por una factura tipo 33)
  siguen contando en TotGuiaVenta pero deben indicar la factura referenciada
  con `<TpoDocRef>/<FolioDocRef>/<FchDocRef>` en el Detalle. Si no se incluye,
  el SII rechaza con "No Cuadra".
- **Las guías anuladas** no cuentan en TotGuiaVenta sino en TotGuiaAnulada.
  En el Detalle se marca `<Anulado>2</Anulado>` (2 = anulada después de
  emitir; 1 = folio anulado sin emitir).
