Metadata-Version: 2.5
Name: useyona-einvoice
Version: 0.2.2
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<3,>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff<0.17,>=0.16; extra == 'dev'
Description-Content-Type: text/markdown

# useyona-einvoice

The official Python SDK for the [Yona](https://useyona.com) e-invoicing API: create and manage
invoices, report them to the tax authority, and work with buyers, items, received invoices, billing,
collections and webhooks. Python 3.10+, fully typed.

Every Yona SDK has the same modules and methods; in Python the names are `snake_case`
(`client.invoices.issue_credit_note`).

## Install

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

## Quick start

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

client = EInvoice(api_key=os.environ["YONA_API_KEY"])

# 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
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
invoice = client.invoices.create({
    "invoiceKind": "B2B",
    "invoiceDate": "2026-10-05",
    "currency": "NGN",
    "buyerId": buyer["id"],
    "lineItems": [{"itemId": item["id"], "quantity": 2}],
})

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

The client holds a connection pool: close it with `client.close()` or use `with EInvoice(...) as client:`.

## Sandbox and live

The key is the only configuration. An `sk_test_…` key works in the sandbox and an `sk_live_…` key
in live, on the same host; `client.mode` tells you which. Going live means deploying a live key,
nothing else changes.

To make a deployment refuse a key of the wrong kind:

```python
EInvoice(api_key=key, assert_mode="live")
```

## Responses and pagination

Methods return the API's answer as a typed dictionary with the API's field names
(`invoice["invoiceNumber"]`). List methods return a page:

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

`paginate` walks every page for you:

```python
from useyona.einvoice import paginate

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

Received invoices and issued history return a `Paginated` object with the items under
`res.data["items"]`. PDF downloads return a `BinaryResponse` (`data` bytes, `content_type`, `file_name`).

## Errors

A refused request raises an exception chosen by status:

| Status | Exception |
|---|---|
| 400, 422 | `EInvoiceValidationError` |
| 401 | `EInvoiceAuthenticationError` |
| 402 | `EInvoiceInsufficientCreditsError` |
| 403 | `EInvoicePermissionError` |
| 404 | `EInvoiceNotFoundError` |
| 409 | `EInvoiceConflictError` |
| 429 | `EInvoiceRateLimitError` |
| 5xx | `EInvoiceServerError` |

All extend `EInvoiceApiError`, which carries `status`, `error_code`, `errors` (per field),
`request_id` and `retry_after`:

```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`, not on the message. Problems before the API answers are
`EInvoiceTimeoutError`, `EInvoiceConnectionError` and `EInvoiceConfigError`; all SDK errors extend
`EInvoiceError`.

Some codes worth a branch of their own: on a buyer's address, 400 `VAL202` (the state is not on the
list) and `VAL203` (the LGA is not on the list, or belongs to another state); from
`organization.create_sub_organization`, 403 `BIZ003` (a sandbox key), 402 `BIZ016` (the plan allows no
more organisations) and 409 `RES002` (the name is already taken under the parent).

## Retries and idempotency

Reads, and writes that carry an `Idempotency-Key`, are retried automatically on network errors,
timeouts, 408, 429 and 5xx, with backoff and respecting `Retry-After`. Other writes are never retried.

Where the API accepts an `Idempotency-Key` (creating an invoice, submitting, sending, downloading…)
the SDK generates one per call, so a retry is never applied or charged twice. Pass your own to make a
retry safe across restarts:

```python
from useyona.einvoice import RequestOptions

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

Tune the defaults with `timeout` and `retry=RetryConfig(...)` when creating the client, or per call
with `RequestOptions` (`timeout`, `headers`, `max_retries`).

## 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
```

`verify_webhook` checks the `Yona-Signature` header over the raw body and returns the event. Always
pass the raw bytes, and deduplicate on `event["id"]`. `sign_webhook_payload` signs a payload the way
Yona does, so you can test your handler locally. Endpoints are registered in the dashboard; the SDK
can list and test them and inspect deliveries.

## Guides

[`examples/`](examples/) holds seven complete, runnable walkthroughs. Run them against your sandbox key
with `YONA_API_KEY=sk_test_… make examples`.

| Example | Shows |
|---|---|
| [`first-invoice.py`](examples/first-invoice.py) | a buyer, an item, a draft, finalising and reporting it to the tax authority |
| [`webhooks.py`](examples/webhooks.py) | verifying a delivery, testing an endpoint, reading deliveries |
| [`errors-and-retries.py`](examples/errors-and-retries.py) | `error_code`, `status`, `request_id`, `retry_after`; idempotency keys; a safe retry helper |
| [`sandbox-and-live.py`](examples/sandbox-and-live.py) | the mode from the key, `assert_mode`, and why going live changes only the key |
| [`received-invoices.py`](examples/received-invoices.py) | received invoices: filters and walking every page with `paginate` |
| [`states-and-lgas.py`](examples/states-and-lgas.py) | the state and LGA lists, an LGA picker filtered by state, a buyer saved with the codes, `VAL202` and `VAL203` |
| [`sub-organisations.py`](examples/sub-organisations.py) | listing sub-organisations with a key, their readiness for live and their tax connections, creating one with a live key |

## API reference

126 methods in 27 modules. Every method takes an optional trailing `options: RequestOptions`. Request
and query dictionaries are typed after the operation (`CreateInvoiceBody`, `ListInvoicesQuery`) in
`useyona.einvoice.types`.

| Module | Methods |
|---|---|
| `client.invoices` | `create`, `list`, `get`, `update`, `delete`, `finalise`, `reopen`, `revise`, `cancel`, `issue_credit_note`, `issue_debit_note`, `get_overview`, `get_statistics`, `get_summary` |
| `client.submissions` | `submit`, `issue`, `create_and_submit`, `batch_submit`, `retry`, `renumber`, `query_status`, `get_status`, `record_payment`, `get_authority_copy` |
| `client.output` | `get_download_link`, `download_pdf`, `send` |
| `client.share_links` | `create`, `list`, `revoke` |
| `client.items` | `list`, `create`, `get`, `update`, `delete`, `archive`, `unarchive`, `list_used_codes` |
| `client.reference` | `list_hs_codes`, `list_hs_code_categories`, `list_resources`, `get_resource`, `lookup_tax_id`, `validate_invoice` |
| `client.buyers` | `create`, `list`, `get`, `update`, `delete`, `bulk_delete`, `verify_tax_number`, `get_verification_status`, `search`, `check_reachability`, `check_with_tax_authority` |
| `client.sellers` | `list`, `get`, `get_verification_status`, `search` |
| `client.inbound_invoices` | `list`, `get`, `get_analytics`, `list_history_runs`, `get_history_run` |
| `client.issued_history` | `list`, `get`, `download_pdf` |
| `client.invoice_settings` | `get` |
| `client.tax_connection` | `get`, `list_for_sub_organizations` |
| `client.organization` | `get`, `get_readiness`, `list_sub_organizations`, `list_sub_organizations_readiness`, `create_sub_organization` |
| `client.billing.accounts` | `get_mine`, `get_stats`, `check_balance` |
| `client.billing.payments` | `list`, `get` |
| `client.billing.sandbox` | `list_transactions`, `get_usage` |
| `client.billing.statements` | `get` |
| `client.billing.subscriptions` | `get_active`, `list`, `get`, `list_renewals`, `preview_plan_change`, `get_deal_offer`, `quote_sub_org_slot` |
| `client.billing.transactions` | `list`, `get`, `get_usage_analytics`, `get_usage_by_cost_code` |
| `client.billing.usage` | `get_invoices`, `quote_overage` |
| `client.billing.plans` | `get_recommendation` |
| `client.billing.partner` | `get`, `get_offer`, `quote_seat`, `quote_basket`, `quote_plan_change` |
| `client.collections` | `list_accounts`, `create_account`, `get_account`, `get_account_status`, `deactivate_account`, `quote_fee`, `list_payments`, `list_buyer_credits`, `list_exceptions`, `resolve_exception`, `list_settlement_accounts`, `get_settlement_account`, `list_banks` |
| `client.webhooks.endpoints` | `list`, `get`, `test` |
| `client.webhooks.deliveries` | `list`, `get`, `redeliver` |
| `client.webhooks.events` | `list`, `get`, `redeliver` |
| `client.webhooks.event_types` | `list` |
| `useyona.einvoice.webhooks` | `verify_webhook`, `sign_webhook_payload`, `compute_webhook_signature`, `parse_signature_header` |

`client.tax_connection.get({"identifier": "true"})` also says which number the tax authority holds
for the organisation (its TIN or its 13-digit Tax ID): `einvoicingIdentifier`, or
`identifierNextAction` when it holds neither. `{"fresh": "true"}` asks the authority again. Both are
rationed; pass them only when you need that answer. `client.tax_connection.get(options)` keeps working.

The connection's `state` can be `awaiting_authority_listing`: the business asked to connect and the tax
authority does not list it under any of its numbers yet. Yona asks the authority again every 6 hours
and carries on by itself once the business is listed. `listing` then holds `since`, `checkedAt`,
`nextCheckAt` and the last `answer` (`unknown`, `elsewhere`, `unanswered` or `held_elsewhere`); it is
`None` in every other state. `connectWaits` says whether connecting now would wait like this instead of
being refused. The `tax_connection.action_required` webhook is sent for this state too, and
`invoice.finalised` can carry `reporting` (`InvoiceFinalisedData` in `useyona.einvoice.types`), so a
handler can tell a held invoice from one being reported.

**Held invoices.** While an organisation's connection to the tax authority is still in progress, an
invoice it issues is not refused: `client.submissions.issue` answers `reporting: "held"` with
`notReportedReason: "awaiting_connection"`, the invoice is sent to the buyer, and Yona reports it
automatically once the connection completes. Until then the invoice's `reporting["state"]` is `held`;
`client.invoices.list({"reporting": "held"})` lists them and `client.invoices.get_summary()` counts them
in `held`. If one cannot be reported when the connection completes, its `reporting["reason"]` is
`release_refused`: report it yourself with `client.submissions.submit`.

`client.reference.get_resource("states")` and `get_resource("lgas")` are typed: a state is
`{code, name}` (`NG-LA` Lagos, `StateOption`) and an LGA is `{code, name, stateCode}` (`NG-LA-IKE`
Ikeja, in `NG-LA`, `LgaOption`). For a State and LGA picker, read both once and filter the LGAs by the
chosen state's `code`. `get_resource("countries")` is `{code, name}` (`CountryOption`). For a Nigerian
address, a buyer's `address["state"]` and `address["lga"]` are a state and an LGA from those lists: the
`code`, or the exact `name`, which is stored as the code. A value that is not on the list is refused
with 400 `VAL202` (state) or `VAL203` (LGA, also when it belongs to another state). Both are optional,
and free text for other countries.

An organisation that runs several businesses holds them as sub-organisations. No key preset includes
`organization.children.read` or `organization.children.create`: an Owner or Admin adds them to a key by
name, under Sub-organisations in the dashboard's Create API Key dialog.

- `client.organization.list_sub_organizations({"page", "limit", "search", "ids"})`
  (`GET /a/v1/organizations/me/children`, `organization.children.read`) answers a page, newest first,
  with the total in `pagination`; 100 a page at most. `ids` (a list, or a comma-separated string, at
  most 100) keeps only the ones named. It works in sandbox and live, and with `paginate`.
- `list_sub_organizations_readiness` (`GET /a/v1/organizations/me/children/readiness`, the same
  permission) answers the same page with each sub-organisation's checklist, `liveStatus` and `nextStep`.
- `create_sub_organization({"businessName", "email", "phoneNumber"?, "website"?})`
  (`POST /a/v1/organizations`, `organization.children.create`) needs a live key (a sandbox key is
  refused with 403 `BIZ003`). The new organisation is recorded under the parent's longest-standing Owner
  and is `pending_verification` until it completes its own onboarding. No `Idempotency-Key` is sent and
  the SDK does not retry it: a name is unique under its parent, so a repeat answers 409 `RES002`. 402
  `BIZ016` when the plan allows no more organisations; 60 calls a minute for each key.
- `client.tax_connection.list_for_sub_organizations({"ids": [...]})`
  (`GET /i/v1/tax-connection/children?ids=`, `tax_connection.read`) is for a parent organisation: the
  state of each named sub-organisation's connection in the key's mode, and whether a submission would
  pass. `ids` is a list (or a comma-separated string) of at most 100 ids, each once. An id that is not
  one of the organisation's sub-organisations is left out of the answer.
- The parent's `organization.child.created` webhook carries `keyId` when a key created the
  sub-organisation (`OrganizationChildCreatedData` in `useyona.einvoice.types`).

`client.billing.partner.get({"page": 2, "limit": 50})` pages the businesses the partner pays for; the
answer's `businessesPage` says which page and how many there are in all.
`client.billing.partner.get(options)` keeps working.

`client.collections` answers only where collections are switched on for the key's mode; elsewhere
every call is 409 `BIZ120` (`EInvoiceConflictError`). Its writes take no `Idempotency-Key` and are
not retried. `billing.plans.get_recommendation`, `billing.usage.get_invoices`,
`billing.partner.get_offer` and `billing.subscriptions.get_deal_offer` return `None` when there is
nothing to show.

Account management (users, roles, API keys, purchases, webhook endpoint settings) is done in the
Yona dashboard, not through the API key; so is managing a sub-organisation (its profile, members,
onboarding and tax connection), signed in to that sub-organisation. The payments service's reads (bank account, transfers) join
the SDK when payments launches.

## Configuration

`EInvoice(api_key, ...)` accepts:

| Option | Purpose |
|---|---|
| `timeout` | per-attempt timeout in seconds (default 30) |
| `retry=RetryConfig(...)` | `max_retries` (2), `base_delay` (0.5 s), `max_delay` (8 s), `max_retry_after` (60 s) |
| `headers` | headers sent on every request |
| `http_client` | your own `httpx.Client` (proxy, TLS) |
| `base_url` | another gateway, for local development only; the key decides sandbox or live |

## Development

```bash
make test        # pytest with coverage
make lint        # ruff + mypy --strict
make examples    # run the examples against your sandbox key (YONA_API_KEY)
make sync        # regenerate the typed models from the API definition
make release     # prepare a release: version, CHANGELOG, guides, checks (DRY=1 to preview)
```

## License

MIT
