Metadata-Version: 2.4
Name: sri-einvoice
Version: 0.1.0
Summary: Ecuador SRI e-invoicing engine: factura XML, clave de acceso, XAdES-BES signing, SOAP reception/authorization and RIDE PDF.
Author: Martin Velez
License: Apache-2.0
Keywords: sri,ecuador,einvoicing,factura electronica,xades,comprobantes electronicos
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial :: Accounting
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: lxml>=4.9
Requires-Dist: cryptography>=41
Provides-Extra: ride
Requires-Dist: reportlab>=4.0; extra == "ride"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: reportlab>=4.0; extra == "dev"
Dynamic: license-file

# sri-einvoice

[![CI](https://github.com/OWNER/sri-einvoice/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml)
License: Apache-2.0

Framework-agnostic **Ecuador SRI electronic invoicing engine** for Python: build the
`factura` XML (v1.1.0 / v2.1.0) from a typed model or JSON, compute the 49-digit
*clave de acceso*, sign it with **XAdES-BES** using your `.p12`, send it to the SRI
*recepcion* / *autorizacion* web services and render a minimal **RIDE** PDF.

It is a plain library + CLI. No Odoo, Django or web framework required, and it is
**Apache-2.0**, so you can embed it in proprietary ERP connectors (Odoo Community,
NetSuite, Shopify, Zoho, custom POS) without AGPL obligations.

> Status: **v0.1 MVP**. Factura, Nota de Crédito, Nota de Débito and Comprobante de Retención (v2.0.0, ATS). Tested against the public SRI XSDs and an
> independent `xmlsec1` signature check; **not yet exercised end to end against
> the SRI pruebas service with an accredited certificate** (see *Known gaps*).

## Features

| Step | Module | Notes |
|---|---|---|
| Typed invoice model | `sri_einvoice.models` | `Factura`, `Emisor`, `Comprador`, `Detalle`, `Pago`; Decimal math, IVA 0/5/8/12/13/14/15 %, grouped `totalConImpuestos`, pagos must equal `importeTotal`; cedula/RUC/consumidor-final checks |
| Clave de acceso | `sri_einvoice.clave` | 49 digits, modulo-11 check digit (11 -> 0, 10 -> 1), parse + verify |
| XML builder | `sri_einvoice.xmlbuild` | `factura` v1.1.0 and v2.1.0, `id="comprobante"` |
| XSD validation | `sri_einvoice.validate` | Against the public SRI schemas, downloaded by `scripts/fetch_xsd.py` (not redistributed). For a signed file the comprobante is validated without its `ds:Signature` (the fetched factura XSDs do not allow that child) and the `ds:Signature` is validated separately against the W3C xmldsig schema |
| XAdES-BES signing | `sri_einvoice.xades` | Enveloped, C14N 1.0, RSA-SHA1 (SRI profile) or RSA-SHA256, 3 references (SignedProperties, KeyInfo, comprobante). Written from the W3C/ETSI specs |
| Signature verify | `sri_einvoice.xades.verify_xml` | Integrity check of all references + signature value, a reference must cover the comprobante root, `SigningCertificate` digest must match the embedded cert (not chain/revocation) |
| SOAP client | `sri_einvoice.soap` | stdlib `urllib`, pruebas / produccion endpoints, polling with backoff, SOAP fault handling, host allow-list, injectable transport |
| RIDE PDF | `sri_einvoice.ride` | reportlab (optional extra), Code128 barcode of the clave, from factura or `<autorizacion>` XML |
| CLI | `sri-einvoice` | `clave`, `build`, `validate`, `sign`, `verify`, `send`, `authorize`, `ride`, `test-cert` |

**Safe by default:** `send` and `authorize` are dry-runs unless you pass `--live`;
production requires `--live --produccion`. The `.p12` password is read from an
environment variable (`SRI_P12_PASSWORD`) or prompted, never taken from argv.

## Install

```bash
pip install -e ".[ride]"        # from a checkout; adds reportlab for the RIDE
python scripts/fetch_xsd.py     # optional: public SRI XSDs into .xsd-cache/
```

Dependencies: `lxml`, `cryptography` (and `reportlab` for RIDE).

## Demo (actual output)

Everything below uses the synthetic `examples/factura.json` and a self-signed test
certificate generated on the fly. No real taxpayer data, no real certificate.

```console
$ export SRI_P12_PASSWORD=demo-only
$ sri-einvoice test-cert -o out/test.p12
wrote self-signed TEST certificate out/test.p12 (the SRI will reject it; for local demos only)

$ sri-einvoice build examples/factura.json -o out/factura.xml --validate
wrote out/factura.xml  clave=1411202601099000000000110010020000001231234567819  total=462.00

$ sri-einvoice sign out/factura.xml --p12 out/test.p12 -o out/factura.signed.xml
signed out/factura.signed.xml (sha1) as CN=SRI-EINVOICE TEST ONLY,O=sri-einvoice test fixtures,C=EC

$ sri-einvoice verify out/factura.signed.xml
VALID signature  signer=CN=SRI-EINVOICE TEST ONLY,O=sri-einvoice test fixtures,C=EC  time=2026-11-14T00:28:57-05:00
note: integrity only; certificate chain/revocation is checked by the SRI

$ sri-einvoice validate out/factura.signed.xml   # factura XSD + xmldsig XSD for ds:Signature
VALID against SRI XSD

$ sri-einvoice clave check 1411202601099000000000110010020000001231234567819
{
  "fecha": "2026-11-14",
  "cod_doc": "01",
  "ruc": "0990000000001",
  "ambiente": "1",
  "estab": "001",
  "pto_emi": "002",
  "secuencial": "000000123",
  "codigo_numerico": "12345678",
  "tipo_emision": "1",
  "digito_verificador": "9"
}

$ sri-einvoice send out/factura.signed.xml
dry-run: comprobante not sent. Re-run with --live to call the SRI pruebas endpoint.
envelope: 10217 bytes, payload 7480 bytes

$ sri-einvoice ride out/factura.signed.xml -o out/ride.pdf
wrote out/ride.pdf

$ sed -i 's/462.00/1.00/' out/factura.signed.xml     # tamper with the total
$ sri-einvoice verify out/factura.signed.xml; echo exit=$?
INVALID signature  signer=CN=SRI-EINVOICE TEST ONLY,O=sri-einvoice test fixtures,C=EC  time=2026-11-14T00:28:57-05:00
  - digest mismatch for #comprobante
note: integrity only; certificate chain/revocation is checked by the SRI
exit=1
```

Independent cross-check with libxmlsec1 (also run in the test suite):

```console
$ xmlsec1 --verify --id-attr:id factura \
    --id-attr:Id 'http://uri.etsi.org/01903/v1.3.2#:SignedProperties' \
    --pubkey-cert-pem cert.pem out/factura.signed.xml
OK
SignedInfo References (ok/all): 3/3
```

Signature layout produced:

```text
ds:Signature
  ds:SignedInfo (C14N 2001-03-15, rsa-sha1)
    ds:Reference Type=...#SignedProperties  URI=#Signature…-SignedProperties…
    ds:Reference URI=#Certificate…
    ds:Reference URI=#comprobante  (enveloped-signature transform)
  ds:SignatureValue
  ds:KeyInfo Id=Certificate…  (X509Certificate + RSAKeyValue)
  ds:Object
    etsi:QualifyingProperties
      etsi:SignedProperties (SigningTime, SigningCertificate, DataObjectFormat text/xml)
```

RIDE generated from the signed XML:

![RIDE example](docs/ride-example.png)

### Library use

```python
from sri_einvoice.models import Factura
from sri_einvoice.xmlbuild import build_factura_xml
from sri_einvoice.xades import SigningIdentity, sign_xml
from sri_einvoice.soap import SriClient

factura = Factura.from_json(open("examples/factura.json").read())
identity = SigningIdentity.from_p12(open("my.p12", "rb").read(), password)
signed = sign_xml(build_factura_xml(factura), identity)

client = SriClient("pruebas")              # real network call
if client.enviar(signed).ok:
    resp = client.esperar_autorizacion(factura.clave_acceso)
    print(resp.autorizado)
```

For tests, pass `SriClient(transport=fake)` where `fake(url, body) -> bytes`.

## Why this exists / prior art

The SRI flow is well known, and several projects already implement it. Being honest
about them:

| Project | Language / license | Scope | How sri-einvoice differs |
|---|---|---|---|
| [`sri-xades-signer`](https://pypi.org/project/sri-xades-signer/) | Python, **AGPL-3.0** | XAdES signing only | Full flow (model, clave, XML, XSD, SOAP, RIDE); permissive license. No code reused from it |
| [OCA `l10n-ecuador`](https://github.com/OCA/l10n-ecuador) (`l10n_ec_account_edi`) | Python, **AGPL-3**, Odoo module | Complete EDI inside Odoo Community | Mature and the right choice if you are on Odoo. sri-einvoice is ERP-agnostic, usable from scripts, FastAPI, NetSuite/Shopify connectors |
| Odoo Enterprise `l10n_ec_edi` | proprietary | Complete EDI inside Odoo Enterprise | Same as above, plus licensing |
| [`open-api-facturacion-sri`](https://github.com/AngeloBarzolaVillamar/open-api-facturacion-sri) | TypeScript / NestJS, MIT | REST API with queues, multi-tenant, many document types | Far more complete service. sri-einvoice is an embeddable Python library, not a server |
| [`cuymo/facturacion-electronica-ec`](https://github.com/cuymo/facturacion-electronica-ec) | TypeScript, MIT | Node SDK | Python ecosystem |
| [`mcphub-ec/mcp-sri`](https://github.com/mcphub-ec/mcp-sri) | Python, **MIT** | MCP server: factura v2.1.0 XML, XAdES-BES signing, SOAP send/authorize | Closest Python prior art, also permissive. It is packaged as an MCP server (Docker, env-configured emisor); sri-einvoice is an importable library + CLI with v1.1.0 too, XSD validation, an independent `xmlsec1` check and a RIDE |
| Small Python repos on GitHub (e.g. [`angie1590/fe_ec`](https://github.com/angie1590/fe_ec)) | Python, mostly no license | Factura generation/sending | Without a license file they cannot be reused; few or no tests |
| `amephia/sri-ec`, `sri-toolkit` (Packagist) | PHP | Full flow | Python ecosystem |
| `Infoware.SRI.Firmar` (NuGet) | .NET | Signing + RIDE | Python ecosystem |
| [`digitalautonomy/goxades_sri`](https://github.com/digitalautonomy/goxades_sri) | Go, Apache-2.0 | Signing only | Python, full flow |

So the gap is narrow: permissive Python code for the SRI flow already exists
(`mcp-sri`), but not as a small, typed, framework-agnostic library with tests that
validate against the SRI XSD and cross-check signatures with an independent
implementation. If you need many document types today, look at the TypeScript or PHP
projects; if you are on Odoo, use the OCA modules; if you want an MCP server for an AI
agent, `mcp-sri` already is one.

Clean-room note: the XAdES code was written from the W3C XML-DSig and ETSI
TS 101 903 specs plus the SRI *ficha tecnica*; no code was copied from AGPL projects.
The SRI XSDs are fetched at test time and are not redistributed in this repository.

## Known gaps (v0.1)

- Only `factura` (codDoc 01). No nota de credito/debito, retencion, guia, liquidacion.
- Never run end to end against SRI *pruebas* with an accredited certificate; the
  SOAP layer is covered by synthetic response fixtures only.
- Only IVA in line taxes (no ICE / IRBPNR), no reembolsos, exports, subsidies,
  compensaciones, retenciones in factura.
- `.p12` files with several key/cert bags (some issued by Ecuadorian CAs) load only
  the first key; there is no explicit bag selection yet.
- `verify` checks integrity only, not the CA chain, validity dates or revocation.
- No offline contingency queue, no retries on network errors (only polling).
- RIDE is minimal (no logo, single template).
- Business rules beyond the XSD are partial: e.g. the USD 50 cap on facturas to
  *consumidor final* is not enforced.

See [ROADMAP.md](ROADMAP.md).

## Development

```bash
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/python scripts/fetch_xsd.py
.venv/bin/python -m pytest -q
```

Tests without the XSDs (or without `xmlsec1`) skip those checks instead of failing.

---

## En espanol

**sri-einvoice** es un motor de facturacion electronica del SRI de Ecuador en Python,
con licencia Apache-2.0 y sin depender de ningun ERP. Construye el XML de la factura
(v1.1.0 y v2.1.0) desde un modelo tipado o un JSON, calcula la clave de acceso de
49 digitos con el digito verificador modulo 11, firma con XAdES-BES usando tu `.p12`,
envia a los servicios de recepcion y autorizacion del SRI y genera un RIDE en PDF.

- Los envios al SRI son **simulados por defecto**: usa `--live` para llamar al
  ambiente de pruebas y `--live --produccion` para produccion.
- La clave del `.p12` se lee de la variable `SRI_P12_PASSWORD` o se pide por teclado.
- Los ejemplos usan datos ficticios y un certificado de prueba autofirmado, que el
  SRI rechaza: para emitir de verdad necesitas el certificado de una entidad
  acreditada.
- Si usas Odoo Community, el modulo de la OCA (`l10n_ec_account_edi`) es mas
  completo; esta libreria apunta a integraciones con otros ERP, scripts o APIs propias.

## License

Apache License 2.0. See [LICENSE](LICENSE).
