Skip to content

Commit

Permalink
Se corrigieron formatos de strings en api_client, api_exception y los…
Browse files Browse the repository at this point in the history
… servicios. Se añadió workflows. Se añadió un conjunto de tests nuevo de DTEs temporales. Se hizo un desgloce de la documentación.
  • Loading branch information
SantiagoFiol committed Dec 3, 2024
1 parent f34c532 commit fc99c7d
Show file tree
Hide file tree
Showing 19 changed files with 713 additions and 80 deletions.
62 changes: 62 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: CI

on:
push:
branches:
- master # Ejecuta pruebas al hacer push en la rama 'master'

env:
env_var: ${{ vars.ENV_CONTEXT_VAR }}

jobs:
test:
runs-on: ubuntu-latest

strategy:
matrix:
python-version: ['3.11'] # Puedes cambiar las versiones según necesites

steps:
- name: Check out repository code
uses: actions/checkout@v3

- name: Setup Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }} # Configura la versión de Python desde la matriz

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run Python tests
env:
LIBREDTE_HASH: ${{ secrets.LIBREDTE_HASH }}
LIBREDTE_RUT: ${{ vars.LIBREDTE_RUT }}
run: |
python3 tests/run.py dte_facturacion.test_generar_dte_temporal
- name: Upload pytest result report
if: failure()
uses: actions/upload-artifact@v4
with:
name: tests-results-python_${{ matrix.python-version }}.xml
path: var/tests-results.xml

- name: Upload Coverage Report
uses: actions/upload-artifact@v4
with:
name: tests-coverage-python_${{ matrix.python-version }}.xml
path: var/tests-coverage.xml

- name: Upload to Codecov
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: var/tests-coverage.xml
fail_ci_if_error: true
verbose: true

- name: Display Python version
run: python --version
41 changes: 41 additions & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Docs

on:
workflow_dispatch:
push:
branches:
- master

jobs:
docs:
name: Docs
runs-on: ubuntu-latest

steps:
- name: Check out repository
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'

- name: Install Sphinx and dependencies
run: |
python -m pip install --upgrade pip
pip install sphinx sphinx-rtd-theme
- name: Build Documentation
run: |
sphinx-build -b html docs/ docs/_build/html
- name: Create CNAME file
run: echo "api-client-python.docs.libredte.cl" > docs/_build/html/CNAME

- name: Deploy to GitHub Pages
if: success()
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build/docs
publish_branch: gh-pages
54 changes: 1 addition & 53 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,59 +12,7 @@ LibreDTE: Cliente de API en Python

Cliente para realizar la integración con los servicios web de `LibreDTE <https://www.libredte.cl>`_ desde Python.

Instalación y actualización
---------------------------

Instalar usando un entorno virtual y PIP con:

.. code:: shell
python3 -m venv venv
source venv/bin/activate
pip install libredte
Actualizar usando PIP con:

.. code:: shell
pip install libredte --upgrade
Autenticación en LibreDTE
-------------------------

Lo más simple, y recomendado, es usar una variable de entorno con el
`hash del usuario <https://libredte.cl/usuarios/perfil#datos:hashField>`_,
la cual será reconocida automáticamente por el cliente:

.. code:: shell
export LIBREDTE_HASH="aquí-tu-hash-de-usuario"
Si no se desea usar una variable de entorno, al instanciar los objetos se
deberá indicar el hash del usuario. Ejemplo:

.. code:: python
import libredte
LIBREDTE_HASH="aquí-tu-hash-de-usuario"
client = libredte.api_client.ApiClient(LIBREDTE_HASH)
Si utilizas LibreDTE Edición Comunidad deberás además configurar la URL
de tu servidor. Ejemplo:

.. code:: shell
export LIBREDTE_URL="https://libredte.example.com"
Y si deseas hacerlo sin la variable de entorno, debes pasar la URL como
segundo parámetro en el constructor del cliente:

.. code:: python
import libredte
LIBREDTE_HASH="aquí-tu-hash-de-usuario"
LIBREDTE_URL="https://libredte.example.com"
client = libredte.api_client.ApiClient(LIBREDTE_HASH, LIBREDTE_URL)
Revisa la `documentación <https://api-client-python.docs.libredte.cl>`_ de la biblioteca para más información, sus características y detalles de su uso.

Licencia
--------
Expand Down
7 changes: 7 additions & 0 deletions docs/dev.index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Desarrollo
==========

.. toctree::
:maxdepth: 1

dev.unittest
36 changes: 36 additions & 0 deletions docs/dev.unittest.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Pruebas unitarias
=================

.. important::
Al ejecutar pruebas, deberás tener configuradas las variables de entorno necesarias en el archivo test.env. Favor de duplicar test.env-dist, cambiar su nombre a test.env y rellenar las variables necesarias.

Antes de empezar, debes configurar las siguientes variables de entorno, como mínimo:

.. code:: shell
LIBREDTE_URL="https://libredte.cl"
LIBREDTE_HASH="hash-libredte"
LIBREDTE_RUT="66666666-6"
Para ejecutar las pruebas unitarias se necesita tener instaladas las dependencias del archivo requirements.txt.

Para ejecutar todas las pruebas, utilizar el siguiente comando:

.. code:: shell
python3 tests/run.py
También es posible ejecutar un archivo de pruebas específico, indicando el archivo a utilizar. Ejemplo:

.. code:: shell
python3 tests/run.py dte_facturacion.test_generar_dte_temporal
Además puedes elegir una única prueba específica, utilizando la ruta completa:

.. code:: shell
python3 tests/run.py dte_facturacion.test_buscar_documento_emitido.TestBuscarDocumentoEmitido.test_dte_buscar_documento_emitido
.. important::
Para el ejemplo anterior, se necesita tener al menos 1 DTE emitido.
77 changes: 77 additions & 0 deletions docs/gettingstarted.example.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
Ejemplo
============

Ejemplo de Generar un DTE temporal
----------------------------------

Antes de probar, integrar y/o utilizar el cliente de API, necesitas haber definido previamente las variables de entorno.

.. seealso::
Para más información sobre este paso, referirse al la guía en `Configuración <gettingstarted.setup>`_.

El siguiente es un ejemplo básico de cómo emitir un DTE usando el cliente de API de LibreDTE:

.. code:: python
# Importación de biblioteca de DTE del API Client, y biblioteca json.
from libredte.api_client.dte import Dte
from datetime import datetime
import json
# Instanciación de cliente de API
dte = Dte()
# RUT del emisor, con DV.
emisor_rut = '12345678-9'
# Datos del DTE temporal a crear.
datos = {
'Encabezado': {
'IdDoc': {
'TipoDTE': 33,
'FchEmis': datetime.now().strftime("%Y-%m-%d"),
},
'Emisor': {
'RUTEmisor': emisor_rut
},
'Receptor': {
'RUTRecep': '60803000-K',
'RznSocRecep': 'Servicio de Impuestos Internos (SII)',
'GiroRecep': 'Administración Pública',
'Contacto': '+56 2 3252 5575',
'CorreoRecep': 'facturacionmipyme@sii.cl',
'DirRecep': 'Teatinos 120',
'CmnaRecep': 'Santiago',
}
},
'Detalle': [
{
#'IndExe': 1, # para items exentos
'NmbItem': 'Asesoría de LibreDTE',
'QtyItem': 1,
'PrcItem': 1000,
}
],
'Referencia': [
{
'TpoDocRef': 801,
'FolioRef': 'OC123',
'FchRef': '2015-10-01',
}
],
}
# Se efectua la solicitud HTTP llamando a un método del API client,
# y se guarda la respuesta.
response = dte.emitir_dte_temporal(datos)
# Se transforma el contenido a formato JSON.
dte_temporal = response.json()
print('\nGENERAR DTE TEMP', json.dumps(dte_temporal),'\n')
# Se genera un DTE real utilizando datos del DTE temporal recientemente
# generado.
dte_real = dte.emitir_dte_real(dte_temporal)
print('\nGENERAR DTE REAL', json.dumps(dte_real),'\n')
.. seealso::
Para saber más sobre los parámetros posibles y el cómo consumir los servicios de la API, referirse a la `documentación de LibreDTE. <https://developers.libredte.cl/>`_
10 changes: 10 additions & 0 deletions docs/gettingstarted.index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Empezando
=========

.. toctree::
:maxdepth: 1

gettingstarted.legal
gettingstarted.install
gettingstarted.setup
gettingstarted.example
16 changes: 16 additions & 0 deletions docs/gettingstarted.install.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Instalación y actualización
===========================

Instalar usando un entorno virtual y PIP con:

.. code:: shell
python3 -m venv venv
source venv/bin/activate
pip install libredte
Actualizar usando PIP con:

.. code:: shell
pip install libredte --upgrade
16 changes: 16 additions & 0 deletions docs/gettingstarted.legal.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Licencia
========

Este programa es software libre: usted puede redistribuirlo y/o modificarlo
bajo los términos de la GNU Lesser General Public License (LGPL) publicada
por la Fundación para el Software Libre, ya sea la versión 3 de la Licencia,
o (a su elección) cualquier versión posterior de la misma.

Este programa se distribuye con la esperanza de que sea útil, pero SIN
GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la GNU Lesser General
Public License (LGPL) para obtener una información más detallada.

Debería haber recibido una copia de la GNU Lesser General Public License
(LGPL) junto a este programa. En caso contrario, consulte
`GNU Lesser General Public License <http://www.gnu.org/licenses/lgpl.html>`_.
39 changes: 39 additions & 0 deletions docs/gettingstarted.setup.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
Configuración
=============

Autenticación en LibreDTE
-------------------------

Lo más simple, y recomendado, es usar una variable de entorno con el
`hash del usuario <https://libredte.cl/usuarios/perfil#datos:hashField>`_,
la cual será reconocida automáticamente por el cliente:

.. code:: shell
export LIBREDTE_HASH="aquí-tu-hash-de-usuario"
Si no se desea usar una variable de entorno, al instanciar los objetos se
deberá indicar el hash del usuario. Ejemplo:

.. code:: python
import libredte
LIBREDTE_HASH="aquí-tu-hash-de-usuario"
client = libredte.api_client.ApiClient(LIBREDTE_HASH)
Si utilizas LibreDTE Edición Comunidad deberás además configurar la URL
de tu servidor. Ejemplo:

.. code:: shell
export LIBREDTE_URL="https://libredte.example.com"
Y si deseas hacerlo sin la variable de entorno, debes pasar la URL como
segundo parámetro en el constructor del cliente:

.. code:: python
import libredte
LIBREDTE_HASH="aquí-tu-hash-de-usuario"
LIBREDTE_URL="https://libredte.example.com"
client = libredte.api_client.ApiClient(LIBREDTE_HASH, LIBREDTE_URL)
Loading

0 comments on commit fc99c7d

Please sign in to comment.