# Hacienda Test Controller Guide

This controller lets you test sending invoices to Hacienda using the **MythicByte Provider**.

## Available Routes

### 1. Health Check
```
GET /api/v1/mythicbyte/e-invoicing/test/hacienda/health
```

Checks that the provider is configured correctly.

**Response:**
```json
{
  "status": 200,
  "data": {
    "status": "ok",
    "provider": "MythicByte",
    "message": "Provider is ready to send invoices"
  },
  "message": "Hacienda test provider is healthy"
}
```

### 2. Send Invoice to Hacienda
```
POST /api/v1/mythicbyte/e-invoicing/test/hacienda/send
Content-Type: application/json
```

**Expected Payload:**
```json
{
  "consecutive_number": "0000000002",
  "payload": {
    "Encabezado": {
      "FechaEmision": "2026-02-26T14:30:00-06:00",
      "CodigoActividadEmisor": "620900",
      "CondicionVenta": "01",
      "SituacionComprobante": "1"
    },
    "Clave": {
      "Sucursal": "001",
      "Terminal": "00001",
      "TipoComprobante": "04"
    },
    "Emisor": {
      "Nombre": "Tienda MythicByte Sociedad Anónima",
      "Identificacion": {
        "Tipo": "01",
        "Numero": "208560001"
      },
      "NombreComercial": "MythicByte Store",
      "Ubicacion": {
        "Provincia": "1",
        "Canton": "01",
        "Distrito": "01",
        "Barrio": "San José Centro",
        "OtrasSenas": "Avenida Central, 100 metros norte de la plaza principal"
      },
      "Telefono": {
        "CodigoPais": 506,
        "NumTelefono": "25551234"
      },
      "CorreoElectronico": [
        "facturacion@mythicbyte.cr"
      ]
    },
    "Receptor": {
      "Nombre": "Cliente Consumidor Final",
      "Identificacion": {
        "Tipo": "01",
        "Numero": "109870654"
      },
      "CorreoElectronico": "cliente@example.com"
    },
    "DetalleServicio": {
      "LineaDetalle": [
        {
          "NumeroLinea": 1,
          "CodigoCABYS": "4620101010000",
          "Cantidad": 3.000,
          "UnidadMedida": "Unid",
          "Detalle": "Laptop HP 15 pulgadas",
          "PrecioUnitario": 450000.00000,
          "MontoTotal": 1350000.00000,
          "SubTotal": 1350000.00000,
          "BaseImponible": 1350000.00000,
          "ImpuestoNeto": 175500.00000,
          "MontoTotalLinea": 1525500.00000,
          "Impuesto": [
            {
              "Codigo": "01",
              "CodigoTarifaIVA": "08",
              "Tarifa": 13.00,
              "Monto": 175500.00000
            }
          ]
        },
        {
          "NumeroLinea": 2,
          "CodigoCABYS": "4620201010000",
          "Cantidad": 2.000,
          "UnidadMedida": "Unid",
          "Detalle": "Mouse inalámbrico Logitech",
          "PrecioUnitario": 15000.00000,
          "MontoTotal": 30000.00000,
          "SubTotal": 30000.00000,
          "BaseImponible": 30000.00000,
          "ImpuestoNeto": 3900.00000,
          "MontoTotalLinea": 33900.00000,
          "Impuesto": [
            {
              "Codigo": "01",
              "CodigoTarifaIVA": "08",
              "Tarifa": 13.00,
              "Monto": 3900.00000
            }
          ]
        }
      ]
    },
    "ResumenFactura": {
      "CodigoTipoMoneda": {
        "CodigoMoneda": "CRC",
        "TipoCambio": 1.00000
      },
      "TotalServGravados": 0.00000,
      "TotalServExentos": 0.00000,
      "TotalServExonerado": 0.00000,
      "TotalServNoSujeto": 0.00000,
      "TotalMercanciasGravadas": 1380000.00000,
      "TotalMercanciasExentas": 0.00000,
      "TotalMercExonerada": 0.00000,
      "TotalMercNoSujeta": 0.00000,
      "TotalGravado": 1380000.00000,
      "TotalExento": 0.00000,
      "TotalExonerado": 0.00000,
      "TotalNoSujeto": 0.00000,
      "TotalVenta": 1380000.00000,
      "TotalDescuentos": 0.00000,
      "TotalVentaNeta": 1380000.00000,
      "TotalImpuesto": 179400.00000,
      "TotalImpAsumEmisorFabrica": 0.00000,
      "TotalIVADevuelto": 0.00000,
      "TotalOtrosCargos": 0.00000,
      "TotalComprobante": 1559400.00000,
      "TotalDesgloseImpuesto": [
        {
          "Codigo": "01",
          "CodigoTarifaIVA": "08",
          "TotalMontoImpuesto": 179400.00000
        }
      ],
      "MedioPago": [
        {
          "TipoMedioPago": "01",
          "TotalMedioPago": 1559400.00000
        }
      ]
    }
  }
}
```

## Controller Flow

1. **Validation**: Checks that the payload has the required structure
2. **Logging**: Stores the request in the logs
3. **Processing in MythicByteProvider**:
   - Generates the unique key (Clave) based on date, issuer, document type, etc.
   - Generates the security code
   - Transforms data with `MythicByteTransformer`
   - Generates XML with `FEXmlGeneratorService`
   - **Signs the XML** with `XmlSignerService` using XAdES-EPES
   - Base64-encodes the signed XML
   - Authenticates with **Hacienda IDP Service**
   - Sends to Hacienda's reception API
4. **Response**: Returns the sending result

## Responses

### Success (201)
```json
{
  "status": 201,
  "data": {
    "location": "https://hacienda-api.cr/endpoint/..."
  },
  "message": "Receipt received by Hacienda"
}
```

### Validation Error (422)
```json
{
  "status": 422,
  "message": "Validation error",
  "errors": {
    "consecutive_number": ["The field is required"],
    "payload.Emisor": ["The field is required"]
  }
}
```

### Send Error (400)
```json
{
  "status": 400,
  "message": "Validation error",
  "errors": [
    "Error details from Hacienda..."
  ]
}
```

### Server Error (500)
```json
{
  "status": 500,
  "message": "Error sending invoice to Hacienda: ...",
  "data": null
}
```

## Required Configuration

Make sure the following services are configured:

1. **XmlSignerService**: Must be configured with the Hacienda digital certificate
2. **HaciendaIdpService**: Must have valid credentials to authenticate with Hacienda
3. **FEXmlGeneratorService**: Generates compact XML without extra spaces (`formatOutput = false`)

## Security

⚠️ **IMPORTANT**: This route is for **TESTING** only.

- Use it only in **test** environments (staging/testing)
- **NEVER** use this in production without additional authentication
- Consider adding authentication middleware before deploying to production

## Troubleshooting

### Error: "XML was modified after being signed"
- Ensure `formatOutput = false` in `FEXmlGeneratorService`
- Verify there are no extra spaces or unwanted line breaks in the XML

### Error: "Hacienda authentication error"
- Verify IDP credentials in `src/Providers/MythicByte/haciendaConfig.php`
- Make sure the certificate is valid and not expired

### Error: "Connection refused"
- Verify the Hacienda API URL in the configuration
- Make sure you have access to Hacienda's network

## Logs

All events are logged in `storage/logs/laravel.log`:
- Incoming requests
- Validation errors
- Hacienda responses
- Exceptions and stack traces
