Metadata-Version: 2.5
Name: useyona-einvoice
Version: 0.1.0
Summary: Official Python SDK for the Yona e-invoicing API — what an API key may call: invoicing, submissions to the tax authority, buyers, items, received invoices, billing reads and webhooks
Project-URL: Homepage, https://useyona.com/docs/sdks/python/installation
Project-URL: Repository, https://github.com/Elyonar/einvoice-python
Project-URL: Issues, https://github.com/Elyonar/einvoice-python/issues
Project-URL: Changelog, https://github.com/Elyonar/einvoice-python/blob/main/CHANGELOG.md
Author-email: Yona <dev@useyona.com>
License: MIT
License-File: LICENSE
Keywords: api-client,billing,e-invoice,einvoice,electronic-invoice,invoice,nigeria,nrs,sdk,tax,tax-compliance,yona
Classifier: Development Status :: 4 - Beta
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 :: Office/Business :: Financial :: Accounting
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: typing-extensions>=4.5
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Description-Content-Type: text/markdown

# useyona-einvoice

Official Python SDK for the Yona e-invoicing API. It covers exactly what an API key may call:
invoicing, submissions to the tax authority, output and share links, items, reference data, buyers,
the read-only seller, received invoices and issued history, invoice settings, the tax connection, the
organisation (read), billing reads and webhooks (read, test, redeliver).

The same surface as [`@useyona/einvoice-js`](https://github.com/Elyonar/einvoice-js), module for
module, with the same names in `snake_case`.

## Features

- **One key, nothing else to configure.** `sk_test_…` is the sandbox, `sk_live_…` is live, on the same host.
- **Typed.** Every request and response shape is a `TypedDict` generated from the API's OpenAPI; `py.typed` ships.
- **Safe retries.** GET, PUT, DELETE and writes carrying an `Idempotency-Key` are retried on network
  errors, timeouts, 408, 429 and 5xx, honouring `Retry-After`. The SDK generates the key on the
  routes that accept one, so its own retry is never charged twice.
- **Typed errors.** `EInvoiceValidationError`, `EInvoiceNotFoundError`, `EInvoiceRateLimitError`… all
  carry `status`, `error_code`, `errors`, `request_id` and `retry_after`.
- **Webhooks.** `verify_webhook` checks the `Yona-Signature` over the raw body in constant time.
- **Light.** `httpx` and `typing_extensions` are the only dependencies. Python 3.10+.

## Installation

```bash
pip install useyona-einvoice
```

## Quick start

```python
import os
from useyona.einvoice import EInvoice

client = EInvoice(api_key=os.environ["YONA_API_KEY"])
client.mode  # "sandbox" for sk_test_… keys, "live" for sk_live_… keys

# 1. A buyer
buyer = client.buyers.create(
    {
        "name": "Acme Nigeria Ltd",
        "taxId": "12345678-0001",
        "email": "accounts@acme.ng",
        "partyType": "company",
        "address": {"line1": "1 Marina", "city": "Lagos", "country": "NG"},
    }
)

# 2. A saved item (optional: a line can also carry its own description, unit code and codes)
item = client.items.create(
    {
        "name": "Laptop",
        "itemType": "goods",
        "hsnCode": "8471.30",
        "productCategory": "Machinery",
        "unitCode": "EA",
        "unitPriceMinor": "45000000",
        "currency": "NGN",
        "taxCategory": "STANDARD_VAT",
    }
)

# 3. A draft invoice: invoiceKind and taxCategory, never taxPercent
invoice = client.invoices.create(
    {
        "invoiceKind": "B2B",
        "invoiceDate": "2026-10-05",
        "currency": "NGN",
        "buyerId": buyer["id"],
        "lineItems": [{"itemId": item["id"], "quantity": 2}],
    }
)

# 4. Finalise and report it to the tax authority
client.invoices.finalise(invoice["id"])
client.submissions.submit(invoice["id"])  # 202: queued
status = client.submissions.get_status(invoice["id"])
```

That is all the configuration an integration needs: the key. The SDK talks to the production
gateway for both modes; the key's prefix decides whether you are in the sandbox or live.

To fail fast when a deployment is given the wrong key:

```python
EInvoice(api_key=key, assert_mode="live")  # raises EInvoiceConfigError for an sk_test_ key
```

A malformed key is refused at construction with `EInvoiceConfigError` (the key is never echoed).

The client holds a connection pool; close it with `client.close()` or use it as a context manager
(`with EInvoice(api_key=key) as client:`).

## Guides

The recipes in [`examples/`](examples/) are the developer guides of the Yona portal (Developers,
Overview): your first invoice, webhooks, errors and retries, sandbox and live, received invoices.
Each runs end to end against a sandbox key (`YONA_API_KEY=sk_test_… make examples`).

## Verifying your setup

```bash
YONA_API_KEY=sk_test_… make smoke-remote
```

runs free reads across every module and then the first-invoice example against the real API, with
your own sandbox key, and prints a table method → OK/FAIL with the error code and request id of any
failure. It refuses a live key and never prints the key. The example creates sandbox data in your
organisation: a buyer, an item and an invoice submitted to the tax authority's sandbox.

## Responses and pagination

Methods return the API's `data` as a `TypedDict` with the wire names (`invoice["invoiceNumber"]`).
List methods return a `Page`:

```python
page = client.buyers.list({"limit": 50})
page.data  # list[BuyerViewDto]
page.pagination  # {"total", "page", "pageSize", "totalPages", "hasNext", "hasPrevious"}
page.request_id
```

`paginate` walks every page for you:

```python
from useyona.einvoice import paginate

for buyer in paginate(client.buyers.list, {"limit": 100}):
    ...
```

Received invoices and issued history answer an object with `items`, so they return a `Paginated`:
`res.data["items"]` and `res.pagination`.

PDF downloads return a `BinaryResponse`: `data` (bytes), `content_type`, `file_name`, `request_id`.

## Errors

Every refusal of the API raises a subclass of `EInvoiceApiError`, chosen by status:

| Status | Class | Typical `error_code` |
|---|---|---|
| 400, 422 | `EInvoiceValidationError` | `VAL…` |
| 401 | `EInvoiceAuthenticationError` | `AUTH…` (a revoked, expired or malformed key) |
| 402 | `EInvoiceInsufficientCreditsError` | `BIZ001` |
| 403 | `EInvoicePermissionError` | `AUTH019` (capability), `AUTH018` (user-only route) |
| 404 | `EInvoiceNotFoundError` | `RES001` |
| 409 | `EInvoiceConflictError` | `BIZ…` (state), `RES002` (duplicate) |
| 429 | `EInvoiceRateLimitError` | `SYS005`, with `retry_after` |
| 5xx | `EInvoiceServerError` | `SYS001` |

```python
from useyona.einvoice import EInvoiceApiError, EInvoiceValidationError

try:
    client.invoices.create(params)
except EInvoiceValidationError as err:
    for e in err.errors:
        print(e.field, e.message)
except EInvoiceApiError as err:
    print(err.status, err.error_code, err.request_id)  # quote request_id to support
```

Branch on `error_code`, never on the message. Outside the API: `EInvoiceTimeoutError`,
`EInvoiceConnectionError`, `EInvoiceConfigError`, `EInvoiceWebhookError`; all extend `EInvoiceError`.

## Retries and idempotency

```python
from useyona.einvoice import EInvoice, RetryConfig

client = EInvoice(api_key=key, timeout=30, retry=RetryConfig(max_retries=3, base_delay=0.5, max_delay=8, max_retry_after=30))
```

The SDK retries GET, PUT and DELETE, and writes that carry an `Idempotency-Key`, on network errors,
timeouts, 408, 429 and 5xx, with exponential backoff and jitter; a `Retry-After` on 429/503 is
waited out up to `max_retry_after` seconds (a longer one is raised at once, with `retry_after` set).
Other writes are never retried for you. `timeout` (seconds) bounds each attempt, headers and body.

On routes that accept an `Idempotency-Key` (`invoices.create`, `submissions.submit`, `output.send`,
the downloads…) the SDK generates one per call, so its own retries are never applied or charged
twice. Pass your own to make a retry across process restarts safe:

```python
from useyona.einvoice import RequestOptions

client.invoices.create(params, RequestOptions(idempotency_key=f"order-{order_id}"))
```

`RequestOptions` also takes `timeout`, `headers` and `max_retries` for one call.

## Webhooks

```python
from useyona.einvoice.webhooks import verify_webhook


@app.post("/webhooks/yona")
def yona_webhook():
    event = verify_webhook(request.get_data(), request.headers, os.environ["YONA_WEBHOOK_SECRET"])
    if event["type"] == "invoice.accepted":
        ...
    return "", 200
```

Yona signs `t + "." + raw body` with HMAC-SHA256 and sends `Yona-Signature: t=…,v1=…` (a second
`v1=` while a rotated secret overlaps). `verify_webhook` accepts the delivery when a signature
matches in constant time and `t` is within ±300 s, and returns the parsed event. Pass the raw body
bytes, never a re-serialised object. Deduplicate on `event["id"]`. `sign_webhook_payload` signs a
payload exactly as Yona does, for testing your handler. Endpoints are registered in the dashboard;
the key can list and test them (`client.webhooks.endpoints`), read deliveries and redeliver.

## What an API key cannot do

Users, invitations, roles, API keys, organisation management, collections, purchases and webhook
endpoint writes are done by a signed-in user in the dashboard; the API answers 403 `AUTH018` to a
key. The seller is the organisation itself (read-only; `sellers.create/update/delete` are 409
`BIZ205` and have no method). `EXCLUDED_OPERATIONS` lists the API-key operations the SDK deliberately
has no method for, with the reason.

## API reference

Every method takes an optional trailing `options: RequestOptions`. Query and body parameters are
`TypedDict`s named after the operation (`ListInvoicesQuery`, `CreateInvoiceBody`), all in
`useyona.einvoice.types`.

#### `client.invoices`
`create(params)`, `list(query)`, `get(id)`, `update(id, params)`, `delete(id)`, `finalise(id)`, `reopen(id)`, `revise(id)`, `cancel(id, params)`, `issue_credit_note(id, params)`, `issue_debit_note(id, params)`, `get_overview(query)`, `get_statistics(query)`, `get_summary(query)`

#### `client.submissions`
`submit(id, query)`, `issue(id)`, `create_and_submit(params)`, `batch_submit(params)`, `retry(id)`, `renumber(id)`, `query_status(id)`, `get_status(id)`, `record_payment(id, params)`, `get_authority_copy(id)`

#### `client.output`
`get_download_link(id)`, `download_pdf(id)` → `BinaryResponse`, `send(id, params)`

#### `client.share_links`
`create(invoice_id, params)`, `list(invoice_id)`, `revoke(invoice_id, link_id)`

#### `client.items`
`list(query)`, `create(params)`, `get(id)`, `update(id, params)`, `delete(id)`, `archive(id)`, `unarchive(id)`, `list_used_codes(query)`

#### `client.reference`
`list_hs_codes(query)`, `list_hs_code_categories()`, `list_resources()`, `get_resource(type)`, `lookup_tax_id(value, query)`, `validate_invoice(params)`

#### `client.buyers`
`create(params)`, `list(query)`, `get(id)`, `update(id, params)`, `delete(id)`, `bulk_delete(params)`, `verify_tax_number(id)`, `get_verification_status(id)`, `search(query)`, `check_reachability(query)`, `check_with_tax_authority(params)`

#### `client.sellers`
`list(query)`, `get(id)`, `get_verification_status(id)`, `search(query)`

#### `client.inbound_invoices`
`list(query)` → `Paginated`, `get(id)`, `get_analytics(query)`, `list_history_runs(query)` → `Paginated`, `get_history_run(run_id)`, `load_older()` (deprecated)

#### `client.issued_history`
`list(query)` → `Paginated`, `get(id)`, `download_pdf(id)` → `BinaryResponse`

#### `client.invoice_settings` · `client.tax_connection`
`get()`

#### `client.organization`
`get(org_id)`, `get_readiness()`

#### `client.billing.accounts`
`get_mine(query)`, `get_stats(account_id="me", query)`, `check_balance(account_id, query)`

#### `client.billing.payments`
`list(query)`, `get(id)`

#### `client.billing.sandbox`
`list_transactions(query)`, `get_usage()`

#### `client.billing.statements`
`get(period, query)`

#### `client.billing.subscriptions`
`get_active()`, `list(query)`, `get(id)`, `list_renewals(query)`, `preview_plan_change(id, query)`

#### `client.billing.transactions`
`list(query)`, `get(id)`, `get_usage_analytics(query)`, `get_usage_by_cost_code(query)`

#### `client.webhooks.endpoints`
`list()`, `get(id)`, `test(id, params=None)`

#### `client.webhooks.deliveries`
`list(query)`, `get(id)`, `redeliver(id)`

#### `client.webhooks.events`
`list(query)`, `get(id)`, `redeliver(id, params)`

#### `client.webhooks.event_types`
`list()`

#### `useyona.einvoice.webhooks`
`verify_webhook(payload, headers, secret, *, tolerance_seconds=300, now=None)`, `sign_webhook_payload(payload, secrets, timestamp=None)`, `compute_webhook_signature(payload, secret, timestamp)`, `parse_signature_header(header)`

## Advanced: `base_url`

`base_url` points the client at another gateway (a local one in development). It never changes
the mode: the key does. Never switch hosts by mode in your own code.

## Development

```bash
make install        # a venv is recommended: python3 -m venv .venv && . .venv/bin/activate
make test           # pytest with coverage, parity included
make lint           # ruff + mypy --strict
make sync           # copy the snapshot and vectors from einvoice-js and regenerate the models (needs Node 22)
make sync-check     # CI: the three must match the pinned einvoice-js commit
make guides         # examples/ → guides/guides.json (a test fails when it is stale)
make examples       # run the examples (YONA_API_KEY; YONA_BASE_URL to point elsewhere)
make smoke-remote   # verify your own sandbox key (see "Verifying your setup")
```

The models (`useyona/einvoice/types/generated.py`), the API snapshot and the webhook test vectors come
from [`einvoice-js`](https://github.com/Elyonar/einvoice-js), the source of truth for every Yona SDK;
`tests/test_parity.py` fails when a method and the snapshot disagree.

## License

MIT
