Metadata-Version: 2.5
Name: pyefris
Version: 1.0.0
Summary: Python client for URA EFRIS system-to-system e-invoicing integration
Project-URL: Homepage, https://efris.ura.go.ug/
Author: pyefris contributors
License: MIT
License-File: LICENSE
Keywords: e-invoicing,efris,fiscal,uganda,ura
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.10
Requires-Dist: cryptography>=42
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.7
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# pyefris

Python client for the **URA EFRIS** (Electronic Fiscal Receipting and Invoicing
Solution) system-to-system API, per *Interface Design for EFRIS v24.0.1*.

Features:

- Full wire protocol: `{data, globalInfo, returnStateInfo}` envelope, one POST
  endpoint, `dataDescription` encryption flags per interface.
- Online-mode crypto exactly as URA requires:
  `content = base64(AES-ECB/PKCS7(json))`, `signature = base64(SHA1withRSA(content))`,
  T104 session-key unwrap (RSA/PKCS1), auto-refresh on returnCode `401`/`402`.
- Offline-mode payload profile (base64 content, empty signature).
- **ACID outbox**: every submission is recorded atomically in a SQLite
  (WAL, `synchronous=FULL`) store before it goes on the wire — idempotent
  retries, crash-safe replay, append-only audit log.
- Typed pydantic v2 models for the core ~40 interfaces; `client.call(code, ...)`
  generic escape hatch for the rest of the 74-code registry.
- Sync `EfrisClient` and `AsyncEfrisClient` (httpx).
- Python ≥ 3.10. Dependencies: `httpx`, `pydantic>=2`, `cryptography`.

## Install

```bash
pip install -e .          # local
pip install -e ".[dev]"   # with test/lint tooling
```

## Quickstart

```python
from pyefris import EfrisClient, EfrisConfig

cfg = EfrisConfig(
    tin="1000029771",
    device_no="TCS9e0df01728335239",
    private_key_path="keys/taxpayer_private.pem",  # RSA-2048, registered w/ URA
    environment="test",                            # or "prod"
    store_path="pyefris.db",
)

with EfrisClient(cfg) as client:
    client.sync_clock()                     # T101: requestTime within ±10min
    result = client.invoicing.upload_invoice(invoice, reference_no="INV-0001")
    doc = result.model.exist_invoice_list[0]
    print(doc.invoice_no, doc.antifake_code, doc.qr_code)
```

Domain services: `client.session` (T101–T105), `.taxpayer` (T119/T137/T138/T180),
`.dictionary` (T115/T123–T126/T134/T146), `.goods` (T127/T128/T130/T144),
`.stock` (T131/T139/T145/T147–T149/T160), `.invoicing`
(T106–T114/T116–T118/T120–T122/T129). Unmodeled interfaces:
`client.call("T167", {...})`.

## ACID guarantees

| Property | Mechanism |
|---|---|
| **Atomicity** | intent (PENDING) + sealed envelope (SEALED) written in one `BEGIN IMMEDIATE` tx before network I/O; outcome + audit row in a second tx |
| **Consistency** | `UNIQUE(tin, device_no, interface_code, reference_no)` blocks double-fiscalization; `CHECK` on status enum |
| **Isolation** | WAL + busy_timeout; claims are compare-and-swap `UPDATE ... WHERE status=?` — threads/processes can't double-send |
| **Durability** | `synchronous=FULL`; sealed envelope persisted before send; append-only `audit_log` (triggers forbid UPDATE/DELETE) |

Recovery: `client.relay_pending()` re-sends the **byte-identical** stored
envelope (same `dataExchangeId`, signature) so URA can dedupe. Run it on a
schedule or `client.start_worker()` for a background thread. Retries use
exponential backoff (`RetryPolicy`) for transport failures; business
rejections (`EfrisReturnCodeError`) are terminal by design.

```python
result = client.invoicing.upload_invoice(inv, reference_no="INV-1")          # raises on dup
result = client.invoicing.upload_invoice(inv, reference_no="INV-1",
                                         on_duplicate="return")            # returns stored record
```

## Config reference

`EfrisConfig(tin, device_no, private_key_pem|_path, environment="test"|"prod",
mode="online"|"offline", endpoint=..., store_path=..., timeout_seconds=30,
retry=RetryPolicy(...), server_public_key_pem=...)`. Also `EfrisConfig.from_env()`
reads `PYEFRIS_*` variables. CLI: `python -m pyefris server-time|login|
sync-dictionaries|relay|call`.

## Security notes

- SHA1withRSA signatures and AES-ECB are **required by the URA spec**, not a
  design choice of this package.
- The decrypted AES session key is cached in the SQLite `kv_state` table —
  protect the store file with filesystem permissions.
- `RedactingFilter` (pyefris.logging) scrubs keys/blobs from log records.
- T102's white-box `clientPriKey`/`keyTable` decryption is AP01-only and not
  implemented (S2S/AP04 uses your own registered keypair).

## Spec caveats captured in code

- `passowrdDes`, `buyerPlaceOfBusi`, `VehichleNo` keep the spec's spellings.
- T113/T114/T105/T120/T122 return unencrypted responses even though the
  request is encrypted.
- `InvoiceUpload` allows spec additions via `extra="allow"` — unknown fields
  round-trip instead of being dropped.

## Development

```bash
python -m pytest tests/          # 50 tests, no network needed
python -m ruff check src tests
python -m mypy src/pyefris       # strict mode
```

See `AGENTS.md` for architecture notes.
