Metadata-Version: 2.4
Name: nextpyme-sdk
Version: 1.1.0
Summary: SDK oficial de Nextpyme para facturación electrónica, nómina y servicios DIAN en Colombia
Author-email: Alvaro Dimas <alvarodimas1403@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://nextpyme.plus
Project-URL: Documentation, https://nextpyme.plus/docs
Project-URL: Repository, https://gitlab.com/nextpyme/sdk-python-nextpyme-factura-electronica
Keywords: nextpyme,facturacion-electronica,dian,colombia,nomina-electronica,ubl,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.12.0; extra == "dev"
Requires-Dist: responses>=0.25.0; extra == "dev"
Dynamic: license-file

# nextpyme-sdk

SDK oficial de **Nextpyme** para facturación electrónica, nómina electrónica, documento soporte y más servicios DIAN en Colombia.

Un solo `pip install` y tienes todo listo: autenticación, reintentos opcionales, manejo de errores tipados, y acceso a todos los endpoints de la API.

---

## Instalación

```bash
pip install nextpyme-sdk
```

Requiere **Python >= 3.9**.

---

## Inicio rápido

```python
from nextpyme import NextpymeClient

client = NextpymeClient(token="tu-bearer-token-aqui")  # 

# Consultar datos de la empresa
empresa = client.reports.company()
print(empresa)

# Emitir una factura
factura = client.invoice.create({
    "number": 1,
    "type_document_id": 1,
    "customer": { ... },
    "legal_monetary_totals": { ... },
    "invoice_lines": [ ... ],
})
print(factura)
# { "success": True, "message": "...", "dian": { ... }, ... }
```

---

## Configuración

```python
client = NextpymeClient(
    token="eyJhbGciOi...",       # Bearer token
    
    environment="production",    # "production" | "custom"
    debug=False,                 # True para ver logs en consola
    timeout_ms=30000,            # Timeout por petición (ms)
)
```

| Parámetro      | Tipo    | Default                   | Descripción                                     |
|----------------|---------|---------------------------|-------------------------------------------------|
| `token`        | `str`   | —                         | **Requerido.** Bearer token de autenticación    |
| `environment`  | `str`   | `"production"`            | Ambiente: `production` o `custom`               |
| `base_url`     | `str`   | —                         | URL base (solo si `environment` es `"custom"`)  |
| `debug`        | `bool`  | `False`                   | Habilitar logs de debug en consola              |
| `timeout_ms`   | `int`   | `30000`                   | Timeout por request en milisegundos             |
| `max_retries`  | `int`   | `2`                       | Máximo de reintentos cuando `retry=True`        |
| `user_agent`   | `str`   | `"nextpyme-sdk-python"`   | Header User-Agent personalizado                 |

### Ambientes

| Ambiente      | URL base                              |
|---------------|---------------------------------------|
| `production`  | `https://api.nextpyme.plus/api`       |
| `custom`      | La que definas en `base_url`          |

```python
# Apuntar a otra instancia de la API (por ejemplo, un ambiente de pruebas)
client = NextpymeClient(
    token="...",
    environment="custom",
    base_url="https://mi-api.ejemplo.com/api",
)
```

---

## Opciones por petición

Los métodos que aceptan `opts` admiten un diccionario con:

| Opción       | Tipo   | Default | Descripción                         |
|--------------|--------|---------|-------------------------------------|
| `retry`      | `bool` | `False` | Habilitar reintentos (429/5xx/red)  |
| `timeout_ms` | `int`  | `30000` | Timeout para esta petición          |
| `headers`    | `dict` | `{}`    | Headers adicionales                 |

```python
# Sin reintentos (default)
client.invoice.create(body)

# Con reintentos habilitados
client.invoice.create(body, opts={"retry": True})

# Con timeout extendido
client.invoice.create(body, opts={"retry": True, "timeout_ms": 60000})
```

---

## Servicios disponibles

| #  | Módulo        | Método                          | HTTP | Endpoint                                    | Descripción                             |
|----|---------------|---------------------------------|------|---------------------------------------------|-----------------------------------------|
| 1  | **invoice**   | `create(body, opts)`            | POST | `/ubl2.1/invoice`                           | Emitir factura de venta                 |
| 2  |               | `credit_note(body, opts)`       | POST | `/ubl2.1/credit-note`                       | Emitir nota crédito                     |
| 3  |               | `debit_note(body, opts)`        | POST | `/ubl2.1/debit-note`                        | Emitir nota débito                      |
| 4  |               | `eqdoc(body, opts)`             | POST | `/ubl2.1/eqdoc`                             | Factura POS (documento equivalente)     |
| 5  |               | `export_invoice(body, opts)`    | POST | `/ubl2.1/invoice-export`                    | Factura de exportación                  |
| 6  |               | `contingency(body, opts)`       | POST | `/ubl2.1/invoice-contingency`               | Factura en contingencia                 |
| 7  |               | `aiu(body, opts)`               | POST | `/ubl2.1/invoice-aiu`                       | Factura AIU                             |
| 8  |               | `transport(body, opts)`         | POST | `/ubl2.1/invoice-transport`                 | Factura de transporte                   |
| 9  |               | `mandate(body, opts)`           | POST | `/ubl2.1/invoice-mandate`                   | Factura de mandato                      |
| 10 | **payroll**   | `create(body, opts)`            | POST | `/ubl2.1/payroll`                           | Emitir nómina electrónica               |
| 11 |               | `adjust_note(body, opts)`       | POST | `/ubl2.1/payroll-adjust-note`               | Nota de ajuste de nómina                |
| 12 | **support_document** | `create(body, opts)`       | POST | `/ubl2.1/support-document`                  | Documento soporte                       |
| 13 |                      | `credit_note(body, opts)`  | POST | `/ubl2.1/sd-credit-note`                    | Nota crédito documento soporte          |
| 14 | **events**    | `send_with_data(body, opts)`    | POST | `/ubl2.1/send-event-data`                   | Evento RADIAN con datos                 |
| 15 |               | `send_with_xml(body, opts)`     | POST | `/ubl2.1/send-event`                        | Evento RADIAN con XML adjunto           |
| 16 | **status**    | `document(uuid)`                | POST | `/ubl2.1/status/document/{uuid}`            | Estado de documento en DIAN             |
| 17 |               | `events(uuid)`                  | POST | `/ubl2.1/status/events-document/{uuid}`     | Eventos de una factura en DIAN          |
| 18 |               | `document_info(uuid)`           | POST | `/ubl2.1/status/document-info/{uuid}`       | Documento resumen DIAN                  |
| 19 |               | `reference_notes(uuid)`         | GET  | `/ubl2.1/document/get-reference-notes`      | Notas asociadas a un documento          |
| 20 |               | `in_batch(body)`                | POST | `/ubl2.1/status/in-batch`                   | Estado en bloque de varios documentos   |
| 21 | **reports**   | `software()`                    | GET  | `/ubl2.1/reports/software`                  | Datos del software en DIAN              |
| 22 |               | `company()`                     | GET  | `/ubl2.1/config/company`                    | Datos de la empresa                     |
| 23 |               | `resolutions(filters)`          | GET  | `/ubl2.1/reports/resolutions`               | Resoluciones configuradas (filtrables)  |
| 24 |               | `dashboard(body)`               | POST | `/ubl2.1/reports/dashboard`                 | Dashboard de consumos                   |
| 25 |               | `master_tables(body)`           | POST | `/ubl2.1/reports/master/database`           | Tablas maestras (municipios, etc.)      |
| 26 |               | `certificates(nit)`             | GET  | `/ubl2.1/certificates-listing/{nit}`        | Certificados digitales y vencimiento    |
| 27 | **config**    | `logo(body)`                    | PUT  | `/ubl2.1/config/logo`                       | Configurar logotipo (base64)            |
| 28 |               | `delete_logo()`                 | DELETE | `/ubl2.1/config/logo`                     | Eliminar logotipo                       |
| 29 |               | `environment(body)`             | PUT  | `/ubl2.1/config/environment`                | Cambiar ambiente facturación/nómina     |
| 30 |               | `resolution(body)`              | PUT  | `/ubl2.1/config/resolution`                 | Configurar resolución de numeración     |
| 31 |               | `change_template(body)`         | PUT  | `/ubl2.1/config/change-template`            | Cambiar plantilla del PDF               |
| 32 | **downloads** | `download(nit, filename, opts)` | GET  | `/ubl2.1/download/{nit}/{filename}`         | Descargar archivo (PDF/XML/ZIP/base64)  |
| 33 |               | `xml_from_dian(uuid)`           | POST | `/ubl2.1/xml/document/{uuid}`               | Descargar XML desde DIAN por CUFE       |
| 34 |               | `join_pdfs(body)`               | POST | `/ubl2.1/join-pdfs`                         | Unir múltiples PDFs                     |
| 35 | **email**     | `send(body)`                    | POST | `/ubl2.1/send-email`                        | Reenviar email de un documento          |
| 36 | **plans**     | `user_info()`                   | GET  | `/ubl2.1/plan/infoplanuser`                 | Folios disponibles del usuario          |
| 37 |               | `list_packages()`               | GET  | `/ubl2.1/plan/assign-package-user`          | Paquetes asignados (solo aliados)       |
| 38 |               | `assign_package(body)`          | PUT  | `/ubl2.1/plan/assign-package-user`          | Asignar paquete (solo aliados)          |
| 39 | **dian**      | `status_document(track_id)`     | POST | `/ubl2.1/status/document/{track_id}`        | Estado de documento en DIAN por CUFE    |
| 40 |               | `numbering_range(body)`         | POST | `/ubl2.1/numbering-range`                   | Resoluciones de numeración DIAN         |
| 41 |               | `rut_rues(body)`                | POST | `/ubl2.1/rut-rues`                          | Consultar RUT/RUES de un tercero        |
| 42 |               | `invoice_data(body)`            | GET  | `/return-invoice-data`                      | Compras recibidas                       |

---

## Módulos y ejemplos

### `client.invoice` — Facturación electrónica

```python
# Emitir factura de venta
factura = client.invoice.create(body)
# { "success": True, "message": "...", "dian": { ... }, "number": "...", "uuid": "..." }

# Con reintentos
factura = client.invoice.create(body, opts={"retry": True})

# Nota crédito
nc = client.invoice.credit_note(body)

# Nota débito
nd = client.invoice.debit_note(body)
```

### `client.payroll` — Nómina electrónica

```python
# Emitir nómina individual
nomina = client.payroll.create(body)

# Nota de ajuste (reemplazo o eliminación)
ajuste = client.payroll.adjust_note(body)
```

### `client.support_document` — Documento soporte

```python
# Documento soporte (proveedores no obligados a facturar)
ds = client.support_document.create(body)

# Nota crédito de documento soporte
ncds = client.support_document.credit_note(body)
```

### `client.events` — Eventos RADIAN

```python
# Evento con datos (sin XML)
evento = client.events.send_with_data({
    "event_id": 1,
    "type_rejection_id": None,
    "document_reference": {"cufe": "abc123..."},
})

# Evento con XML adjunto
evento_xml = client.events.send_with_xml({
    "event_id": 1,
    "base64_attacheddocument_name": "documento.xml",
    "base64_attacheddocument": "PD94bWwg...",
})
```

### `client.status` — Consultas de estado DIAN

```python
# Validar estado de un documento
estado = client.status.document("uuid-del-documento")

# Ver eventos de una factura
eventos = client.status.events("uuid-del-documento")

# Documento resumen DIAN
info = client.status.document_info("uuid-del-documento")

# Notas (crédito/débito) asociadas a un documento
notas = client.status.reference_notes("uuid-del-documento")

# Consultar estado en bloque de varios documentos
lote = client.status.in_batch({
    "documents": [
        {
            "get_status_response": True,
            "sendmail": False,
            "prefix": "SETP",
            "number": 990000001,
            "type_document_id": 1,
        },
    ],
})
```

### `client.reports` — Reportes y consultas

```python
# Datos del software registrado en DIAN
sw = client.reports.software()
# { "success": True, "message": "...", "data": { ... } }

# Datos de la empresa
empresa = client.reports.company()

# Resoluciones configuradas
res = client.reports.resolutions()

# Resoluciones filtradas (prefix, type_document_id, resolution)
res_fe = client.reports.resolutions({"prefix": "FE", "type_document_id": 1})

# Dashboard de consumos por rango de fechas
dashboard = client.reports.dashboard({
    "date_between": True,
    "start_date": "2025-01-01 00:00:00",
    "end_date": "2025-12-31 23:59:59",
})

# Tablas maestras (municipios, departamentos, etc.)
tablas = client.reports.master_tables({
    "tables": [{"table": "municipalities"}, {"table": "departments"}]
})

# Certificados digitales y vencimiento
certs = client.reports.certificates("900123456")
```

### `client.config` — Configuración de la empresa

```python
# Configurar logotipo (solo JPG, base64 sin prefijo)
client.config.logo({"logo": "/9j/4AAQSkZJRg..."})

# Cambiar ambiente de facturas (1=Producción, 2=Pruebas)
client.config.environment({"type_environment_id": 2})

# Cambiar ambiente de factura POS (1=Producción, 2=Pruebas)
client.config.environment({"eqdocs_type_environment_id": 2})

# Cambiar ambiente de nómina (1=Producción, 2=Pruebas)
client.config.environment({"payroll_type_environment_id": 2})

# Configurar resolución de numeración
client.config.resolution({
    "type_document_id": 1,
    "prefix": "SETP",
    "resolution": "18764000001",
    "resolution_date": "2019-01-19",
    "technical_key": "fc8e...",
    "from": 990000000,
    "to": 995000000,
    "date_from": "2019-01-19",
    "date_to": "2030-01-19",
})

# Cambiar plantilla del PDF ("2", "one", "two", "four")
client.config.change_template({"template_name": "one"})

# Eliminar el logotipo
client.config.delete_logo()
```

### `client.downloads` — Descargas de archivos

Los nombres de archivo siguen el patrón de la API:

| Tipo              | Nombre de archivo                       |
|-------------------|-----------------------------------------|
| PDF               | `FES-{prefix}{number}.pdf`              |
| XML Invoice       | `FES-{prefix}{number}.xml`              |
| AttachedDocument  | `Attachment-{prefix}{number}.xml`       |
| ZIP               | `ZipAttachm-{prefix}{number}.zip`       |
| Respuesta DIAN    | `RptaFE-{prefix}{number}.xml`           |

```python
NIT = "900123456"

# Descargar PDF
pdf = client.downloads.download(NIT, "FES-SETP990000001.pdf")

# Descargar XML Invoice
xml = client.downloads.download(NIT, "FES-SETP990000001.xml")

# Descargar ZIP
zip_file = client.downloads.download(NIT, "ZipAttachm-SETP990000001.zip")

# Descargar en base64
pdf_b64 = client.downloads.download(NIT, "FES-SETP990000001.pdf", opts={"base64": True})

# Descargar XML directamente desde DIAN por CUFE
xml_dian = client.downloads.xml_from_dian("cufe-del-documento...")

# Unir múltiples PDFs en uno
joined = client.downloads.join_pdfs({
    "name_joined_pdfs": "reporte-mensual",
    "pdfs": [
        {"type_document_id": 1, "prefix": "SETP", "number": "990000001"},
        {"type_document_id": 1, "prefix": "SETP", "number": "990000002"},
    ],
})
```

### `client.email` — Envío de emails

```python
client.email.send({
    "prefix": "SETP",
    "number": "990000001",
    "alternate_email": "cliente@example.com",
    "showacceptrejectbuttons": True,
    "email_cc_list": [{"email": "copia@example.com"}],
    "send_email_cc_list_as_email_cc": True,
})
```

### `client.plans` — Planes y recargas

```python
# Consultar folios disponibles
info = client.plans.user_info()

# Ver paquetes asignados (solo aliados)
paquetes = client.plans.list_packages()

# Asignar paquete de documentos (solo aliados)
client.plans.assign_package({
    "user_identification_number": 900123456,
    "absolut_start_plan_date": "2025-01-01",
    "absolut_documents": 1000,
})
```

### `client.dian` — Consultas directas DIAN

```python
# Consultar estado de un documento en DIAN por CUFE/UUID
estado = client.dian.status_document("002515775b03ae7674b470788f07...")
# {
#   "success": True,
#   "message": "Consulta generada con éxito",
#   "dian": {
#     "is_valid": True,
#     "status_code": "00",
#     "status_description": "Procesado Correctamente.",
#     "status_message": "La Factura electrónica FE212, ha sido autorizada.",
#     "error_message": [],
#   },
# }

# Consultar resoluciones de numeración en DIAN
rangos = client.dian.numbering_range({"IDSoftware": "tu-id-software"})
# Respuesta normalizada (siempre lista, lista para config.resolution):
# {
#   "success": True,
#   "message": "Acción completada OK.",
#   "resolutions": [
#     {
#       "prefix": "SETP",
#       "resolution": "18764000001",
#       "resolution_date": "2021-08-25",
#       "technical_key": "fc8e...",
#       "from": 990000000,
#       "to": 995000000,
#       "date_from": "2019-01-19",
#       "date_to": "2030-01-19",
#     },
#   ],
# }

# Usar la resolución directamente en config:
rangos = client.dian.numbering_range({"IDSoftware": "..."})
if rangos["resolutions"]:
    client.config.resolution({
        "type_document_id": 1,
        **rangos["resolutions"][0],  # spread directo
    })

# Consultar RUT/RUES de un tercero
rut = client.dian.rut_rues({
    "identification_number": 900123456,
    "type_document_identification_id": 3,  # 1=CC, 2=CE, 3=NIT, etc.
    "rues": True,
})

# Ver compras recibidas
compras = client.dian.invoice_data({"fecha": "2025-01-01"})
```

---

## Formato de respuestas

### Módulos con respuesta DIAN normalizada

Los módulos `invoice`, `payroll`, `support_document`, `events`, `status` y `dian` devuelven una respuesta normalizada. El blob `ResponseDian` (SOAP pesado) se elimina y se expone un campo `dian` limpio:

```python
{
    "success": True,
    "message": "Factura generada exitosamente.",
    "number": "SETP990000001",
    "uuid": "abc123...",
    "dian": {
        "is_valid": True,
        "status_code": "00",
        "status_description": "Procesado Correctamente.",
        "status_message": "La Factura electrónica...",
        "error_message": [],   # siempre lista, puede estar vacía
    },
}
```

### Módulo `reports` (respuesta formateada)

```python
{
    "success": True,
    "message": "...",
    "data": { ... },   # datos extraídos automáticamente
}
```

### `dian.numbering_range()` (respuesta normalizada)

Normaliza las 4 variantes de respuesta DIAN (array, objeto, sin datos, SOAP Fault):

```python
{
    "success": True,          # False si SOAP Fault (certificado expirado, etc.)
    "message": "...",
    "resolutions": [ ... ],   # siempre lista (vacía si no hay datos)
}
```

---

## Manejo de errores

El SDK tiene una jerarquía de errores tipados:

```python
from nextpyme import NextpymeClient, NextpymeError, AuthError, ValidationError, ServerError

try:
    factura = client.invoice.create(body)
except ValidationError as e:
    # 422 — Campos inválidos
    print(e.code)     # "VALIDATION_FAILED"
    print(e.status)   # 422
    print(e.details)  # { "success": False, "errors": { "campo": ["..."] } }
except AuthError as e:
    # 401/403 — Token inválido o expirado
    print(e.code)     # "AUTH_INVALID"
except ServerError as e:
    # 500-504 — Error del servidor
    print(e.code)     # "SERVER_ERROR"
except NextpymeError as e:
    # Cualquier error del SDK (incluye los anteriores)
    print(e.to_dict())  # Estructura uniforme con success: False
```

### Códigos de error

| Código              | Clase             | HTTP    | Descripción                             |
|---------------------|-------------------|---------|-----------------------------------------|
| `AUTH_INVALID`      | `AuthError`       | 401/403 | Token inválido, expirado o sin permisos |
| `VALIDATION_FAILED` | `ValidationError` | 422     | Campos requeridos o datos inválidos     |
| `SERVER_ERROR`      | `ServerError`     | 500-504 | Error interno del servidor              |
| `HTTP_ERROR`        | `NextpymeError`   | Otros   | Cualquier otro error HTTP               |
| `TIMEOUT`           | `NextpymeError`   | —       | La petición excedió el timeout          |
| `NETWORK_ERROR`     | `NextpymeError`   | —       | Sin conexión o DNS no resuelto          |

### Estructura uniforme (`to_dict()`)

```python
# En un endpoint de Flask/FastAPI:
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.post("/facturas")
def emitir_factura():
    try:
        result = client.invoice.create(request.json)
        return jsonify(result)
    except NextpymeError as e:
        return jsonify(e.to_dict()), e.status or 500
```

Resultado de `to_dict()`:

```json
{
  "success": false,
  "message": "Error de validación.",
  "code": "VALIDATION_FAILED",
  "status": 422,
  "method": "POST",
  "path": "/ubl2.1/invoice",
  "errors": { "campo": ["El campo es requerido."] }
}
```

---

## Reintentos

Los reintentos están **desactivados por defecto**. Se habilitan por petición con `opts={"retry": True}`:

```python
# Sin reintentos (default)
client.invoice.create(body)

# Con reintentos
client.invoice.create(body, opts={"retry": True})
```

| Se reintenta             | No se reintenta           |
|--------------------------|---------------------------|
| HTTP 429 (rate limiting) | HTTP 401/403 (auth)       |
| HTTP 500-504 (servidor)  | HTTP 422 (validación)     |
| Errores de red           | HTTP 404 (no encontrado)  |

Espera entre reintentos (backoff exponencial): **500ms → 1s → 2s → 4s...**

El máximo de reintentos se configura con `max_retries` (default: `2`).

---

## Modo debug

```python
client = NextpymeClient(token="...", debug=True)
```

```
[NEXTPYME SDK] [DEBUG] POST /ubl2.1/invoice → request
[NEXTPYME SDK] [DEBUG] POST /ubl2.1/invoice ← 200 (432ms)
```

---

## Middlewares personalizados

```python
def mi_middleware(ctx, call_next):
    ctx["headers"]["X-Custom-Header"] = "valor"
    response = call_next()
    print(f"Response status: {response['status']}")
    return response

client.http.use_middleware(mi_middleware)
```

---

## Plugins

```python
class MiPlugin:
    name = "mi-plugin"

    def setup(self, client, http):
        http.use_middleware(self._interceptor)

    def _interceptor(self, ctx, call_next):
        # interceptar peticiones
        return call_next()

client = NextpymeClient(token="...")
client.use(MiPlugin())
```

---

## Ejemplo completo: Flask + SDK

```python
from flask import Flask, request, jsonify
from nextpyme import NextpymeClient, ValidationError, AuthError
import os

app = Flask(__name__)

client = NextpymeClient(
    token=os.environ["NEXTPYME_TOKEN"],
    environment="production",
)

# Emitir factura
@app.post("/api/facturas")
def emitir_factura():
    try:
        result = client.invoice.create(request.json)
        return jsonify(result)
    except ValidationError as e:
        return jsonify(e.to_dict()), 422
    except AuthError as e:
        return jsonify(e.to_dict()), 401
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500

# Consultar estado
@app.get("/api/facturas/<uuid>/estado")
def consultar_estado(uuid):
    try:
        estado = client.status.document(uuid)
        return jsonify(estado)
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500

if __name__ == "__main__":
    app.run(port=3000)
```

---

## Licencia

MIT
