Metadata-Version: 2.4
Name: peru-ubigeo
Version: 1.0.0
Summary: Consulta y validación de códigos ubigeo peruanos (INEI + RENIEC) para integraciones SUNAT.
Project-URL: Homepage, https://github.com/csotelo/peru-ubigeo
Project-URL: Repository, https://github.com/csotelo/peru-ubigeo
Project-URL: Bug Tracker, https://github.com/csotelo/peru-ubigeo/issues
Project-URL: Changelog, https://github.com/csotelo/peru-ubigeo/blob/main/CHANGELOG.md
Author-email: Contributors <contributors@peru-ubigeo.dev>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under the
              License, as indicated by a copyright notice that is included in or
              attached to the work.
        
              "Derivative Works" shall mean any work that is based on (or derived
              from) the Work for which the editorial revisions, annotations,
              elaborations, or other modifications represent, as a whole, an
              original work of authorship.
        
              "Contribution" shall mean any work of authorship, including the
              original version of the Work and any modifications or additions to
              that Work or Derivative Works of the Work, that is intentionally
              submitted to the Licensor for inclusion in the Work by the copyright
              owner or by an individual or Legal Entity authorized to submit on
              behalf of the copyright owner.
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              patent license to make, use, sell, offer for sale, import, and
              otherwise transfer the Work.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work; and
        
              (d) If the Work includes a "NOTICE" text file, you must include a
                  readable copy of the attribution notices contained within such
                  NOTICE file.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              shall be under the terms and conditions of this License.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor.
        
           7. Disclaimer of Warranty. Unless required by applicable law or agreed
              to in writing, Licensor provides the Work on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
        
           8. Limitation of Liability. In no event shall any Contributor be
              liable to You for damages arising out of this License or use of
              the Work.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work, You may offer acceptance of support, warranty, indemnity,
              or other liability obligations consistent with this License.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2024 Contributors
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
License-File: LICENSE
Keywords: codigos-geograficos,inei,peru,reniec,sunat,ubigeo
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Natural Language :: Spanish
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic>=2.0
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: twine>=5.0; extra == 'dev'
Description-Content-Type: text/markdown

# peru-ubigeo

[![Python](https://img.shields.io/badge/python-3.11%2B-blue)](https://python.org)
[![License](https://img.shields.io/badge/license-Apache%202.0-green)](LICENSE)
[![Pydantic v2](https://img.shields.io/badge/pydantic-v2-orange)](https://docs.pydantic.dev)

Librería Python agnóstica de framework para consulta y validación de códigos
ubigeo peruanos. Diseñada para integración con librerías de documentos
electrónicos SUNAT (einvoice, GRE, SIRE, CPE).

---

## Características

- **Sistema de código dual** — códigos INEI + RENIEC con mapeo por distrito
- **Modelos Pydantic v2** — `Country`, `Department`, `Province`, `District`,
  tipo validado `UbigeoCode`
- **Sin dependencia de framework** — Python puro; compatible con FastAPI, Django,
  Tryton o scripts independientes
- **Arquitectura Hexagonal** — cambia la fuente de datos sin tocar la lógica de negocio
- **Datos embebidos estáticos** — sin llamadas a red; los datos se actualizan con
  cada nueva versión del paquete
- **Tipado completo** — PEP 561 (`py.typed`), compatible con mypy modo estricto
- **Python 3.11+** — tipado moderno en todo el código

---

## Instalación

```bash
pip install peru-ubigeo
```

---

## Inicio rápido

```python
from peru_ubigeo import UbigeoRegistry

registry = UbigeoRegistry()

# ── Búsqueda ──────────────────────────────────────────────────────────
district = registry.get_by_code("150101")        # INEI (por defecto)
print(district.name)                             # LIMA
print(district.department_code)                  # 15
print(district.province_code)                    # 1501

district = registry.get_by_reniec_code("150101") # búsqueda RENIEC

# ── Consultas jerárquicas ─────────────────────────────────────────────
departments = registry.get_departments()          # list[Department] — 25 en total
provinces   = registry.get_provinces("15")        # list[Province]
districts   = registry.get_districts("15", "01") # list[District]

# ── Validación ───────────────────────────────────────────────────────
registry.is_valid_code("150101")   # True
registry.is_valid_code("XXXXXX")   # False

# ── Normalización ────────────────────────────────────────────────────
registry.normalize(" 150101 ")     # "150101"  (elimina espacios)
registry.normalize("10101")        # "010101"  (rellena con ceros a la izquierda)
```

---

## Arquitectura

```
peru_ubigeo/
├── __init__.py                # API pública
├── py.typed                   # Marcador PEP 561
├── domain/
│   ├── __init__.py
│   ├── models.py              # Modelos Pydantic v2 + tipo UbigeoCode
│   ├── exceptions.py          # Jerarquía UbigeoError
│   └── ports.py               # UbigeoRepositoryPort (ABC)
├── application/
│   ├── __init__.py
│   └── registry.py            # UbigeoRegistry (casos de uso)
├── infrastructure/
│   ├── __init__.py
│   └── json_repository.py     # Adaptador JsonUbigeoRepository
└── data/
    ├── inei/                  # ubigeo_inei.json
    └── reniec/                # ubigeo_reniec.json
```

Dirección de dependencias: `infrastructure` → `application` → `domain`

---

## Repositorio personalizado

Inyecta cualquier fuente de datos que implemente `UbigeoRepositoryPort`:

```python
from peru_ubigeo import UbigeoRegistry
from peru_ubigeo.domain.ports import UbigeoRepositoryPort

class MyDatabaseRepository(UbigeoRepositoryPort):
    ...

registry = UbigeoRegistry(repository=MyDatabaseRepository())
```

---

## Manejo de errores

```python
from peru_ubigeo import (
    UbigeoRegistry,
    InvalidUbigeoCodeError,
    UbigeoNotFoundError,
    DataSourceError,
)

registry = UbigeoRegistry()

try:
    district = registry.get_by_code("XYZ")
except InvalidUbigeoCodeError as e:
    print(e)  # mensaje en español
except UbigeoNotFoundError as e:
    print(e)  # mensaje en español
except DataSourceError as e:
    print(e)  # mensaje en español
```

| Excepción | Cuándo se lanza |
|---|---|
| `InvalidUbigeoCodeError` | El código no tiene 6 dígitos numéricos |
| `UbigeoNotFoundError` | Formato válido pero sin coincidencia en los datos |
| `DataSourceError` | Archivo JSON faltante o corrupto |

Todas heredan de `UbigeoError`.

---

## Fuentes de datos

| Fuente | Estándar | Uso |
|---|---|---|
| INEI | Códigos geográficos nacionales oficiales | Por defecto |
| RENIEC | Códigos del registro civil (pueden diferir del INEI) | Documentos electrónicos SUNAT |

Los datos están embebidos estáticamente en el paquete; las actualizaciones
se distribuyen como nuevas versiones.

---

## Desarrollo

```bash
git clone https://github.com/csotelo/peru-ubigeo
cd peru-ubigeo
pip install -e ".[dev]"

# Ejecutar tests
pytest

# Tests con reporte de cobertura
pytest --cov=peru_ubigeo --cov-report=term-missing
```

---

## Integración con librerías SUNAT

`UbigeoCode` es un tipo validado que puedes importar directamente en
`peru-einvoice`, `peru-gre`, `peru-sire` y `peru-cpe`:

```python
from peru_ubigeo import UbigeoRegistry, UbigeoCode

def build_address(ubigeo_str: str) -> dict:
    registry = UbigeoRegistry()
    code: UbigeoCode = registry.normalize(ubigeo_str)
    district = registry.get_by_code(code)
    return {
        "ubigeo": code,
        "district": district.name,
        "province": district.province_code,
        "department": district.department_code,
    }
```

---

## Licencia

Distribuido bajo la licencia **Apache 2.0**. Ver [LICENSE](LICENSE) para más detalles.

```
Copyright 2024 Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

---

## Descargo de responsabilidad

> **Este proyecto no es un producto oficial de SUNAT, INEI ni RENIEC.**
>
> `peru-ubigeo` es una librería open source desarrollada de forma independiente
> por la comunidad. Los datos de ubigeo incluidos provienen de fuentes públicas
> oficiales (INEI y RENIEC), pero este paquete no está respaldado, afiliado ni
> avalado por ninguna entidad del Estado peruano.
>
> El uso de esta librería es bajo la responsabilidad del desarrollador. Se
> recomienda verificar los datos con las fuentes oficiales ante cualquier
> uso en producción que tenga implicancias legales o tributarias.
