Metadata-Version: 2.5
Name: verifiquemos
Version: 0.36.0
Summary: Official Python SDK for the Verifiquemos compliance API
Project-URL: Homepage, https://verifiquemos.com
Project-URL: Documentation, https://app.verifiquemos.com/api-docs/reference
Author-email: Verifiquemos <info@verifiquemos.com>
License-Expression: MIT
License-File: LICENSE
Keywords: api,compliance,guatemala,kyc,ofac,renap,sdk,verifiquemos
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
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: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic[email]>=2.7
Requires-Dist: python-ulid>=3.0
Provides-Extra: dev
Requires-Dist: datamodel-code-generator>=0.26; extra == 'dev'
Requires-Dist: hatch>=1.13; extra == 'dev'
Requires-Dist: mypy>=1.13; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff>=0.7; extra == 'dev'
Description-Content-Type: text/markdown

# verifiquemos

Official Python SDK for the [Verifiquemos](https://verifiquemos.com) compliance API.

> KYC, RENAP, OFAC, ONU, Lista Engel, PEP, CPE — Guatemala-specific compliance in one API call.

## Requirements

- Python >= 3.10 (tested on 3.10, 3.11, 3.12, 3.13, 3.14)

## Install

```bash
pip install verifiquemos
```

## Quickstart (sync)

```python
from verifiquemos import VerifiquemosClient

with VerifiquemosClient(api_key="vfq_...") as client:
    validation = client.validations.create(
        naturaleza="persona_individual",
        cui="1234567890101",
        nombre_completo="Juan Pérez",
        actividad_economica="asalariados",
        tipo_cliente="individual_nacional_renap",
        producto_servicio="cuentas_pasivas",
        perfil_ingreso="ingresos_bajos",
    )
    print(f"Validation submitted: {validation['id']}")
```

## Quickstart (async)

```python
import asyncio
from verifiquemos import AsyncVerifiquemosClient
from verifiquemos.models import BeneficiarioFinalRequest, JuridicaDeclarationRequest

async def main():
    async with AsyncVerifiquemosClient(api_key="vfq_...") as client:
        validation = await client.validations.create(
            naturaleza="persona_juridica",
            nit="60265825",
            razon_social="ACME S.A.",
            actividad_economica="comercio_general",
            tipo_cliente="juridica_nacional_registrada",
            producto_servicio="servicios_economicos",
            perfil_ingreso="ingresos_altos",
            # Requerido en toda jurídica desde el contrato 0.206.0.
            declaracion_juridica=JuridicaDeclarationRequest(
                representante_legal="Juan Pérez García",
                representante_es_pep=False,
                exencion_beneficiarios="no_exento",
                beneficiarios=[
                    BeneficiarioFinalRequest(
                        nombre="María Fernanda Ruiz",
                        participacion_pct=60,
                        es_pep=False,
                    ),
                ],
            ),
        )
        print(f"Validation submitted: {validation['id']}")

asyncio.run(main())
```

## Juridical clients: representative and beneficial owners

A company declares its legal representative and its beneficial owners in one
block. Every name in it is screened against the compliance lists, and a PEP —
declared with the flag or matched on the list — raises the validation to high
risk.

```python
client.validations.create(
    naturaleza="persona_juridica",
    nit="60265825",
    razon_social="Servicios Integrales, S.A.",
    actividad_economica="comercio_general",
    tipo_cliente="juridica_nacional_registrada",
    producto_servicio="servicios_economicos",
    perfil_ingreso="ingresos_altos",
    declaracion_juridica={
        "representante_legal": "Mario Reyes",
        "representante_es_pep": False,
        # Catalog key: client.catalogs.exenciones_beneficiario()
        "exencion_beneficiarios": "no_exento",
        "beneficiarios": [
            {"nombre": "Ana Ruiz", "participacion_pct": 60},
            {"nombre": "Luis Coto", "participacion_pct": 40, "es_pep": True},
        ],
    },
)
```

Up to six `beneficiarios`, each with an **integer** `participacion_pct` from 15
to 100 that must not add up past 100. The list is empty when an exemption is
declared; with `no_exento` an empty list is itself the declaration — the
company had to report its owners and did not — and it raises the validation to
high risk.

The typed model works too, and buys autocomplete plus a misspelled field caught
before the API answers 422:

```python
from verifiquemos.models import BeneficiarioFinalRequest, JuridicaDeclarationRequest

client.validations.create(
    ...,
    declaracion_juridica=JuridicaDeclarationRequest(
        representante_legal="Mario Reyes",
        exencion_beneficiarios="no_exento",
        beneficiarios=[BeneficiarioFinalRequest(nombre="Ana Ruiz", participacion_pct=60)],
    ),
)
```

The block is REQUIRED for `persona_juridica` since contract 0.206.0 — omitting
it returns 422 and consumes no consulta — and it belongs to `persona_juridica`
only: sending it with `persona_individual` also returns 422.

## Re-evaluating a subject early

Once a subject has history, the API schedules its next review. Submitting a new
validation before that date requires a reason — without one the call returns
`422` and **no query is consumed**.

```python
client.validations.create(
    naturaleza="persona_individual",
    cui="1234567890101",
    nombre_completo="Juan Pérez",
    actividad_economica="asalariados",
    tipo_cliente="individual_nacional_renap",
    producto_servicio="cuentas_pasivas",
    perfil_ingreso="ingresos_bajos",
    review_reason_code="noticia_negativa_grave",
)
```

Each module has its own catalog: a code from another one is a 422. Pass
`review_reason_notes` (max 500 chars) alongside `otro`.

| Module | Codes |
| --- | --- |
| Client | `nueva_coincidencia_listas`, `noticia_negativa_grave`, `requerimiento_autoridad_competente`, `cambio_beneficiario_final`, `revision_programada_cartera`, `otro` |
| Employee | `nueva_coincidencia_listas`, `noticia_negativa_grave`, `requerimiento_autoridad_competente`, `alerta_interna_empleado`, `revision_programada_cartera`, `otro` |
| Provider | the client's six plus `incidente_proveedor`, `incumplimiento_contractual_auditoria`, `incidente_seguridad_informacion` |

The three are exported as enums — `ClientReviewReasonCode`,
`EmployeeReviewReasonCode` and `ProviderReviewReasonCode` — so you don't have
to spell them:

```python
from verifiquemos.models import ProviderReviewReasonCode

client.validations.create_provider(
    ...,
    review_reason_code=ProviderReviewReasonCode.incidente_seguridad_informacion.value,
)
```

The response carries the comparison against the previous run: `score_delta`,
`review_outcome`, and `scoring_model_version`. It also reads back the reason
itself — `review_reason_code` and `review_reason_notes` — so you can tell why a
subject was reviewed ahead of schedule without keeping your own record. The code
comes back as a plain string, not one of the enums above: a run stored before a
code left the catalog still names it. The six outcomes are exported as
an enum, so you don't have to spell them:

```python
from verifiquemos.models import ReviewOutcome

if result["review_outcome"] == ReviewOutcome.baja_pendiente.value:
    # The run proposes a lower level and is waiting for authorization —
    # the subject keeps the previous level until someone approves it.
    ...
```

## Poll and download the report

`create()` returns immediately; the validation runs asynchronously. Poll `get()` until
the status reaches a terminal state, then fetch the report via the signed URL the API
returns.

```python
import time
import httpx

while True:
    result = client.validations.get(validation["id"])
    if result["status"] in ("completed", "completed_partial", "failed", "cancelled"):
        break
    time.sleep(3)

# A report is only generated for completed runs. Skip the round-trip on
# failed / cancelled so the example doesn't make a noisy request for an
# artifact the API won't return.
if result["status"] in ("completed", "completed_partial"):
    report = client.validations.report(validation["id"])
    # report = {"report_url": "https://...", "expires_at": None}
    # report_url is always present per the schema; expires_at may be None
    # until the SAS-signing layer lands on the server.
    pdf = httpx.get(report["report_url"]).content
    with open("report.pdf", "wb") as f:
        f.write(pdf)
```

## Employee validations (KYE)

`POST /external/v1/employee-validations` is the only employee-specific route,
so it lives next to the client create — read the result back with the
subject-agnostic `get` / `report` / `cancel`:

```python
employee = client.validations.create_employee(
    cui="1234567890101",             # passport number when residencia != "nacional"
    nombre_completo="Juan Pérez",
    puesto="sin_exposicion",         # client.catalogs.puestos()
    fecha_ingreso="2019-03-01",      # a datetime.date works too
    residencia="nacional",
    tipo_vinculo_laboral="propio",   # required: "propio" | "tercerizado" | "temporal"
    endeudamiento_pct=30,             # 0-100, declared by the employee
)
result = client.validations.get(employee["id"])
```

Optional declarations: `pep_declarado`, `parentesco_pep`, `asociado_cercano_pep`,
`vinculo_empleado`, `actividad_paralela`, `vinculo_cliente` and
`vinculo_aclarado=False` when a declared relationship was left unexplained.
The async client exposes the same call.

**`nombre` and `nivel_riesgo` stop being optional when the job grants access to
client onboarding.** Which jobs those are is not something to hardcode — each
entry of `catalogs.puestos()` carries `grants_onboarding_access`:

```python
puesto = next(p for p in client.catalogs.puestos()["items"] if p["key"] == "alta_clientes")
if puesto["grants_onboarding_access"]:
    # nombre + nivel_riesgo required, or the API answers 422 without
    # consuming a query
    ...
```

Both nested blocks accept the typed models as well as dicts:

```python
from verifiquemos.models import EmployeeAnnual, VinculoCliente

client.validations.create_employee(
    ...,
    vinculo_cliente=VinculoCliente(declarado=True, nombre="ACME S.A.", nivel_riesgo="alto"),
    # Declare the period with `anual` whenever there is something to declare,
    # including on a first validation: the three fields score from the first
    # run. Nothing here waits for a previous run.
    anual=EmployeeAnnual(alertas=["reporte_pld"], rotacion_repetida=True),
)
```

The dict form keeps working (`{"declarado": True, "nombre": ..., "nivel_riesgo": "alto"}`,
`{"alertas": [...], "rotacion_repetida": True}`); the models buy autocomplete
and catch a misspelled field before the API answers 422.

Tenure and the job change are not declared: the engine derives them from the
previous run.

## Provider validations (KYS)

`POST /external/v1/provider-validations` is the only provider-specific route,
same shape as the employee one — read the result back with `get` / `report` /
`cancel`:

```python
provider = client.validations.create_provider(
    nit="60265825",
    razon_social="Servicios Integrales, S.A.",
    representante_legal="Mario Reyes",
    bf_estado="no_identificado",            # identificado | no_identificado | negativa
    estructura="simple_nacional",           # client.catalogs.proveedor_estructuras()
    domicilio="guatemala",                  # client.catalogs.proveedor_domicilio()
    flujo="sin_riesgo",                     # client.catalogs.proveedor_flujo()
    actividad="servicios_profesionales",    # client.catalogs.proveedor_actividades()
    criticidad="operativo_contacto",        # client.catalogs.proveedor_criticidades()
    origen_territorial="nacional",          # client.catalogs.proveedor_territorial()
)
result = client.validations.get(provider["id"])
```

**Store the id.** `client.validations.list()` returns client validations only,
so a provider validation is reachable only through the id the create call
returns — lose it and the record cannot be found through this API. The same
applies to employee validations.

**`tipo_documento` declares which identifier `nit` carries**, and it is the
field the wrapper cannot guess for you:

```python
client.validations.create_provider(
    nit="98-7654321",
    tipo_documento="tax_id_extranjero",             # default is "nit"
    origen_territorial="extranjera_sin_presencia",  # must not be "nacional"
    ...,
)
```

`"tax_id_extranjero"` skips the SAT registry lookup — which only knows
Guatemalan NITs — and the score degrades without penalty.

**It is constrained by `origen_territorial`, in one direction only.**
`origen_territorial="nacional"` with `tipo_documento="tax_id_extranjero"`
returns 422: a national provider is identified by its NIT. The other three
pairings are all accepted, including the common one — a foreign company with a
registered local branch (`extranjera_presencia_local`) normally carries a
Guatemalan NIT, so a foreign origin does not imply a foreign document.

Optional: `maneja_informacion`, `condiciones` (keys from
`catalogs.proveedor_condiciones()`) and, with
`bf_estado="identificado"`, up to six `beneficiarios_finales` — each above 15%
and at most 100% ownership (Decreto 15-2026). Both nested blocks take the typed models as well
as dicts:

```python
from verifiquemos.models import ProviderAnnual, ProviderBeneficiarioFinal

client.validations.create_provider(
    ...,
    bf_estado="identificado",
    beneficiarios_finales=[ProviderBeneficiarioFinal(nombre="Ana Ruiz", participacion_pct=60)],
    # Declare the period with `anual` whenever there is something to declare,
    # including on a first validation: all five facts score from the first run.
    anual=ProviderAnnual(cambio_bf=True, incidente_seguridad=False),
)
```

**Omitting `anual` is not the same as declaring it all-false**: omitting it says
the period was not reviewed, declaring it says it was reviewed and nothing
happened. The async client exposes the same call.

## List, cancel and catalogs

```python
# Paginated list (filter by status optional)
page = client.validations.list(status="pending", limit=20, offset=0)
print(page["total"], "validations,", len(page["items"]), "in this page")
# Each row carries id, status, risk_level, naturaleza, created_at, plus
# review_outcome and review_reason_code — enough to filter without fetching
# every detail. The free-text notes live on the detail call only.

# Cancel an in-flight validation (idempotent — second call replays the first)
cancelled = client.validations.cancel(validation["id"])

# Catalogs the SDK exposes for client-side dropdowns
client.catalogs.naturalezas()           # 2 SIB-regulated values
client.catalogs.actividades_economicas()
client.catalogs.tipos_cliente()
client.catalogs.productos_servicios()
client.catalogs.perfiles_ingreso()
client.catalogs.exenciones_beneficiario()  # juridica beneficial-owner exemptions
client.catalogs.puestos()               # employee (KYE) job catalog

# The seven provider (KYS) catalogs — one per create_provider field (condiciones is optional)
client.catalogs.proveedor_actividades()
client.catalogs.proveedor_criticidades()
client.catalogs.proveedor_estructuras()
client.catalogs.proveedor_domicilio()
client.catalogs.proveedor_flujo()
client.catalogs.proveedor_territorial()
client.catalogs.proveedor_condiciones()

# Country lookups (Guatemala-specific compliance: OFAC/GAFI sanctions list)
client.countries.list(search="guate")
client.countries.list_sanctioned()
```

## Error handling

```python
from verifiquemos import ApiError, RateLimitError, NetworkError, VerifiquemosClient

with VerifiquemosClient(api_key="vfq_...") as client:
    try:
        client.validations.create(...)
    except RateLimitError as e:
        print(f"Retry after {e.retry_after_seconds}s")
    except ApiError as e:
        if e.is_payment_required:
            print("Payment required (402)")
        else:
            raise
    except NetworkError:
        print("Connection failed")
```

## Configuration

| Argument | Default | Description |
|---|---|---|
| `api_key` | (required) | Server-issued API key. Starts with `vfq_`. |
| `base_url` | `https://api.verifiquemos.com/external/v1` | Override for staging/dev. |
| `timeout` | 30.0 | httpx timeout in seconds. |

## Documentation

- API reference: <https://api.verifiquemos.com/openapi-external.json> (OpenAPI contract)
- Interactive reference: <https://app.verifiquemos.com/api-docs/reference> (requires a platform account)
- Release notes: [`CHANGELOG.md`](./CHANGELOG.md)

## Development

```bash
cd verifiquemos-sdk-python
pip install -e ".[dev]"
pytest tests/ -v                              # tests (respx mockea httpx)
ruff check verifiquemos/ tests/
mypy verifiquemos/ --ignore-missing-imports

# Los modelos en verifiquemos/_generated/ se generan desde el OpenAPI externo
# del API. No editarlos a mano; regenerar tras cambios de contrato (requiere
# el repo hermano ../verifiquemos-api):
bash scripts/regen_models.sh             # lee ../verifiquemos-api/openapi-external.json
```

El script invoca `datamodel-codegen` por PATH, así que hay que correrlo con el venv
activado. Sin eso falla con `scripts/regen_models.sh: line 24: datamodel-codegen:
command not found` — no falta la dependencia, no está en el PATH. Sin activar el venv:
`PATH="$PWD/.venv/bin:$PATH" bash scripts/regen_models.sh`.

## Release

Publishing to PyPI is triggered by pushing a git tag `v<version>`. On the tag the
Azure pipeline runs the test matrix (Python 3.10–3.14) and then the Publish stage,
which is exactly:

```bash
pip install hatch twine
hatch build                                   # wheel + sdist → dist/
TWINE_USERNAME=__token__ TWINE_PASSWORD=$PYPI_TOKEN twine upload dist/* --skip-existing
```

Bump `version` in `pyproject.toml` — that is the only place it lives.
`__version__` is not a separate literal: `client.py` reads it from the installed
package metadata and `__init__.py` re-exports it, so the two cannot drift. (One
consequence: in an editable checkout `__version__` reports whatever version was
last `pip install`ed, not what `pyproject.toml` says.) Update
[`CHANGELOG.md`](./CHANGELOG.md) before tagging.

A push to `develop` runs the test matrix only — it never publishes (the Publish
stage is gated on the `v*` tag). There is no prerelease channel: to try the SDK
against staging, build it locally (`pip install -e .`) and set `base_url` to the
staging API.

## License

MIT
