Metadata-Version: 2.5
Name: useyona-einvoice
Version: 0.2.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<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`.

## 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 complete, runnable walkthroughs: your first invoice, webhooks, errors
and retries, sandbox and live, received invoices. Run them against your sandbox key with
`YONA_API_KEY=sk_test_… make examples`.

## API reference

122 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`, `client.tax_connection` | `get` |
| `client.organization` | `get`, `get_readiness` |
| `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.

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