# API Endpoints

All endpoints are available under the prefix: `/api/v1/mythicbyte/e-invoicing`

---

## Document Submission Endpoints

### 1. Generic Endpoint (All Document Types)

**POST** `/electronic-receipts`

Send any type of electronic document in a generic way.

**Required fields:**

```json
{
  "ReceiptType": "string",  // required | Values: FE, FEE, FEC, TE, NC, ND, REP
  "IssueDate": "date",       // required | Format: YYYY-MM-DD
  "Payload": "json"          // required | Document data in JSON format
}
```

---

### 2. Electronic Invoice (FE)

**POST** `/electronic-invoice`

Generates a standard electronic invoice.

**Required fields:**

```json
{
  "CondicionVenta": "string",          // required | Values: 01-08, 10, 12-15, 99
  "CodigoActividadEmisor": "string",   // required | 6 digits
  "CodigoActividadReceptor": "string", // nullable | 6 digits
  "FechaEmision": "datetime",          // required | Format: Y-m-d\TH:i:sP
  "Emisor": {
    "Ubicacion": {}                    // required
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": "string"                 // required | Values: 01, 02, 03, 04, 05
    }
  },
  "DetalleServicio": [],               // required | Array of detail lines
  "InformacionReferencia": []          // nullable | Max: 10 references
}
```

---

### 3. Electronic Export Invoice (FEE)

**POST** `/electronic-export-invoice`

Generates an electronic invoice for export operations.

**Required fields:**

```json
{
  "CodigoActividadEmisor": "string",   // required | 6 digits
  "Emisor": {
    "Ubicacion": {}                    // required
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": "string"                 // required | Values: 01, 02, 03, 04, 05
    },
    "Ubicacion": null                  // prohibited
  },
  "DetalleServicio": {
    "LineaDetalle": [{
      "MontoExportacion": "decimal",   // nullable | Format: up to 13 integers, 5 decimals
      "BaseImponible": null,           // prohibited
      "IVACobradoFabrica": null,       // prohibited
      "ImpuestoNeto": null             // prohibited
    }]
  }
}
```

---

### 4. Electronic Purchase Invoice (FEC)

**POST** `/electronic-purchase-invoice`

Generates an electronic purchase invoice.

**Required fields:**

```json
{
  "CodigoActividadEmisor": "string",   // nullable | 6 digits
  "CodigoActividadReceptor": "string", // required | 6 digits
  "Emisor": {
    "Identificacion": {
      "Tipo": "string"                 // required
    },
    "Ubicacion": {},                   // nullable
    "OtrasSenasExtranjero": "string",  // required if Tipo = 05 | Max: 300 chars
    "CorreoElectronico": []            // nullable | Max: 4 emails
  },
  "Receptor": {
    "OtrasSenasExtranjero": null       // prohibited
  },
  "InformacionReferencia": [{
    "TipoDocIR": "string"              // required | Values: 01-18, 99
  }]
}
```

---

### 5. Electronic Ticket (TE)

**POST** `/electronic-ticket`

Generates an electronic ticket (simplified document).

**Required fields:**

```json
{
  "CodigoActividadEmisor": "string",   // required | 6 digits
  "Emisor": {
    "Ubicacion": {}                    // required
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": "string"                 // required if Identificacion exists | Values: 01-05
    },
    "OtrasSenasExtranjero": "string"   // nullable | Max: 160 chars
  },
  "DetalleServicio": {
    "LineaDetalle": [{
      "PartidaArancelaria": null,      // prohibited
      "TipoTransaccion": null          // prohibited
    }]
  },
  "InformacionReferencia": []          // nullable | Max: 10 references
}
```

---

### 6. Credit Note (NC)

**POST** `/credit-note`

Generates an electronic credit note.

**Required fields:**

```json
{
  "CodigoActividadEmisor": "string",   // nullable | 6 digits
  "CodigoActividadReceptor": "string", // nullable | 6 digits
  "Emisor": {
    "Ubicacion": {}                    // nullable
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": "string"                 // required if Identificacion exists | Values: 01-05
    }
  },
  "DetalleServicio": {
    "LineaDetalle": [{
      "CodigoCABYS": "string",         // nullable | 13 characters
      "MontoExportacion": "decimal"    // nullable | Format: up to 13 integers, 5 decimals
    }]
  }
}
```

---

### 7. Debit Note (ND)

**POST** `/debit-note`

Generates an electronic debit note.

**Required fields:**

```json
{
  "CodigoActividadEmisor": "string",   // nullable | 6 digits
  "CodigoActividadReceptor": "string", // nullable | 6 digits
  "Emisor": {
    "Ubicacion": {}                    // nullable
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": "string"                 // required if Identificacion exists | Values: 01-05
    }
  },
  "DetalleServicio": {
    "LineaDetalle": [{
      "CodigoCABYS": "string",         // nullable | 13 characters
      "MontoExportacion": "decimal"    // nullable | Format: up to 13 integers, 5 decimals
    }]
  }
}
```

---

### 8. Electronic Payment Receipt (REP)

**POST** `/electronic-payment-receipt`

Generates an electronic payment receipt.

**Required fields:**

```json
{
  "CondicionVenta": "string",          // required | Values: 09, 11
  "Emisor": {
    "RegistroFiscal8707": null,        // prohibited
    "NombreComercial": null,           // prohibited
    "Ubicacion": null,                 // prohibited
    "Telefono": null                   // prohibited
  },
  "Receptor": {
    "Identificacion": {
      "Tipo": null                     // prohibited
    },
    "NombreComercial": null,           // prohibited
    "Ubicacion": null,                 // prohibited
    "Telefono": null                   // prohibited
  }
}
```

> **Note:** The Electronic Payment Receipt has special restrictions — it does not include fields such as `Cantidad`, `PrecioUnitario`, or `ResumenFactura`.

---

### 9. Document Reception (Accept/Reject Documents)

**POST** `/document-reception`

Send confirmation documents to accept, partially accept, or reject electronic documents received from suppliers or clients. This generates response documents (Mensaje Receptor) that are sent to Hacienda.

**Supported document types:**
- `CA (05)` — Confirmación de Aceptación (Acceptance Confirmation)
- `CAP (06)` — Confirmación de Aceptación Parcial (Partial Acceptance Confirmation)
- `CR (07)` — Confirmación de Rechazo (Rejection Confirmation)

**Required fields:**

```json
{
  "Clave": {
    "Sucursal": "string",              // nullable | 3 digits
    "Terminal": "string",              // nullable | 5 digits
    "TipoComprobante": "string",       // required | Values: 05 (CA), 06 (CAP), 07 (CR)
    "SituacionComprobante": "string"   // required | Values: 1 (normal), 2 (contingency), 3 (no internet)
  },
  "FechaEmision": "datetime",          // required | Format: Y-m-d\TH:i:sP
  "Emisor": {
    "Nombre": "string",                // required | Min: 5, Max: 100 chars
    "Identificacion": {
      "Tipo": "string",                // required | Values: 01, 02, 03, 04
      "Numero": "string"               // required | Max: 20 chars
    }
  },
  "Receptor": {
    "Nombre": "string",                // required | Min: 3, Max: 100 chars
    "Identificacion": {
      "Tipo": "string",                // required | Values: 01, 02, 03, 04
      "Numero": "string"               // required | Max: 20 chars
    }
  },
  "Detalle": {
    "Clave": "string",                           // required | 50 characters | Key of the document being accepted/rejected
    "FechaEmisionDoc": "datetime",               // required | Format: Y-m-d\TH:i:sP
    "CodigoMensaje": "string",                   // required | Values: 1 (accept), 2 (partial), 3 (reject)
    "Mensaje": "string",                         // required if CodigoMensaje is 2 or 3 | Min: 5, Max: 160 chars
    "CodigoActividad": "string",                 // nullable | 6 digits
    "CondicionImpuesto": "string",               // nullable | Values: 01-05
    "MontoTotalImpuestoAcreditar": "decimal",    // nullable | Format: up to 13 integers, 5 decimals
    "MontoTotalDeGastoAplicable": "decimal",     // nullable | Format: up to 13 integers, 5 decimals
    "MontoTotalImpuesto": "decimal",             // nullable | Format: up to 13 integers, 5 decimals
    "TotalFactura": "decimal"                    // nullable | Format: up to 13 integers, 5 decimals
  }
}
```

**Message codes:**
- `1` — Accepted (Aceptado)
- `2` — Partially Accepted (Aceptación Parcial)
- `3` — Rejected (Rechazado)

**Example:**

```bash
curl -X POST http://your-domain.com/api/v1/mythicbyte/e-invoicing/document-reception \
  -H "Content-Type: application/json" \
  -d '{
    "Clave": {
      "Sucursal": "001",
      "Terminal": "00001",
      "TipoComprobante": "05",
      "SituacionComprobante": "1"
    },
    "FechaEmision": "2026-02-23T14:30:00-06:00",
    "Emisor": {
      "Nombre": "MI EMPRESA S.A.",
      "Identificacion": {
        "Tipo": "02",
        "Numero": "3101234567"
      }
    },
    "Receptor": {
      "Nombre": "PROVEEDOR EJEMPLO",
      "Identificacion": {
        "Tipo": "02",
        "Numero": "3109876543"
      }
    },
    "Detalle": {
      "Clave": "50602231000003109876543010000001001234567890123456789",
      "FechaEmisionDoc": "2026-02-23T10:00:00-06:00",
      "CodigoMensaje": "1",
      "CodigoActividad": "123456",
      "TotalFactura": 11300.00
    }
  }'
```

**Success response:**

```json
{
  "success": true,
  "message": "Document created successfully and queued for sending to provider",
  "data": {
    "receipt_id": 42,
    "consecutive_number": "00100001050000000001",
    "status": "queued",
    "message": "Receipt queued for processing"
  }
}
```

> The document is queued for asynchronous processing. Check its status using the `/document-status/{ui_key}` endpoint.

---

## Webhook & Document Retrieval Endpoints

### 10. Hacienda Webhook

**POST** `/hacienda/webhook`

Receives webhook notifications from Hacienda (Ministry of Finance) through the provider. This endpoint processes status updates for submitted electronic documents automatically.

**Configuration:** Register this URL in your provider's system parameters:

```
https://your-app-domain/api/v1/mythicbyte/e-invoicing/hacienda/webhook
```

---

### 11. Get All Documents

**GET** `/documents`

Retrieves all electronic documents stored in the system, regardless of type.

**Response example:**

```json
{
  "success": true,
  "data": [
    {
      "ui_key": "550e8400-e29b-41d4-a716-446655440000",
      "receipt_type": "FE",
      "issue_date": "2026-02-04",
      "consecutive": "00100001010000000001"
    }
  ]
}
```

---

### 12. Get All Electronic Invoices

**GET** `/electronic-invoices`

Retrieves all electronic invoices (FE) stored in the system.

---

### 13. Get All Electronic Export Invoices

**GET** `/electronic-export-invoices`

Retrieves all electronic export invoices (FEE) stored in the system.

---

### 14. Get All Electronic Purchase Invoices

**GET** `/electronic-purchase-invoices`

Retrieves all electronic purchase invoices (FEC) stored in the system.

---

### 15. Get All Electronic Tickets

**GET** `/electronic-tickets`

Retrieves all electronic tickets (TE) stored in the system.

---

### 16. Get All Credit Notes

**GET** `/credit-notes`

Retrieves all credit notes (NC) stored in the system.

---

### 17. Get All Debit Notes

**GET** `/debit-notes`

Retrieves all debit notes (ND) stored in the system.

---

### 18. Get All Electronic Payment Receipts

**GET** `/electronic-payment-receipts`

Retrieves all electronic payment receipts (REP) stored in the system.

---

### 19. Get Document Status

**GET** `/document-status/{ui_key}`

Retrieves the current Hacienda processing status of a specific document.

**Parameters:**
- `ui_key` (string, required): The unique identifier of the document

**Response example:**

```json
{
  "success": true,
  "data": {
    "id": 1,
    "receipt_type": "FE",
    "ui_key": "550e8400-e29b-41d4-a716-446655440000",
    "emission_date": "2026-02-17T10:30:00-06:00",
    "sent_to_hacienda_at": "2026-02-17T10:30:15-06:00",
    "receipt_status": "accepted",
    "hacienda_response": {
      "response_at": "2026-02-17T10:35:00-06:00",
      "status": "accepted"
    }
  }
}
```

**Possible status values:**
- `pending` — Document submitted, awaiting response
- `accepted` — Document accepted by Hacienda
- `rejected` — Document rejected by Hacienda
- `error` — Error processing the document

---

### 20. Get Document by UI Key

**GET** `/document/{ui_key}`

Retrieves the complete document information using its unique identifier.

**Parameters:**
- `ui_key` (string, required): The unique identifier of the document

**Response example:**

```json
{
  "success": true,
  "data": {
    "id": 1,
    "receipt_type": "FE",
    "consecutive_number": "00100001010000000001",
    "ui_key": "550e8400-e29b-41d4-a716-446655440000",
    "emission_date": "2026-02-17T10:30:00-06:00",
    "sent_to_hacienda_at": "2026-02-17T10:30:15-06:00",
    "receipt_status": "accepted",
    "emissor": {
      "name": "EMPRESA EJEMPLO S.A.",
      "number": "3101234567",
      "type_identification": "02"
    },
    "receiver": {
      "name": "CLIENTE EJEMPLO",
      "number": "109870654",
      "type_identification": "01"
    },
    "amounts": {
      "total_amount": 11300.00,
      "tax_amount": 1300.00,
      "total_discount": 0.00,
      "total_voucher": 11300.00,
      "currency": "CRC",
      "exchange_rate": 1.00
    },
    "payload": {
      "Clave": "50602172600003101234567012345678901234567812345",
      "CodigoActividad": "123456",
      "NumeroConsecutivo": "00100001010000000001",
      "FechaEmision": "2026-02-17T10:30:00-06:00"
    },
    "hacienda_response": {
      "response_at": "2026-02-17T10:35:00-06:00",
      "status": "accepted"
    },
    "created_at": "2026-02-17T10:30:00.000000Z",
    "updated_at": "2026-02-17T10:35:00.000000Z"
  }
}
```
