Metadata-Version: 2.5
Name: finansfatura
Version: 0.4.0
Summary: Python client for the Finansfatura e-invoice (e-Fatura / e-Arşiv) API
Project-URL: Homepage, https://github.com/finansfatura/ff-python
Project-URL: Issues, https://github.com/finansfatura/ff-python/issues
Author: Finansfatura
License: MIT
License-File: LICENSE
Keywords: e-invoice,earsiv,efatura,finansfatura,gib,invoicing
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.8
Requires-Dist: requests>=2.25
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Description-Content-Type: text/markdown

# finansfatura

Python client for the [Finansfatura](https://finansfatura.com) API — turn orders
into sales, issue e-Fatura / e-Arşiv documents, and follow their status.
Full API reference: [apidocs.finansfatura.com](https://apidocs.finansfatura.com).

## Install

```bash
pip install finansfatura
```

## The flow

An integration is two steps, in this order:

```
1. create_order()   POST /v1/integrations/orders     → transaction_id
2. issue_invoice()  POST /v1/invoicing/invoices/     → invoice_id
   order_status()   GET  /v1/integrations/…/status   → invoice_number
```

Step 2 is **optional** — if you only push sales, the taxpayer invoices them from
the panel, one by one or in bulk. That is the smoothest start for most
integrations.

Step 1 is not optional, and neither is the buyer inside it. The sale is what puts
the order in the turnover report and the stock, and what keeps the order alive
when invoicing fails (no credits, bad VKN, GİB down). The buyer is **copied onto
the sale** as the document's billing recipient — no current account ("cari") is
created — so `title` (or `contact_name`) is required: it names who the document
is issued to.

The copy is deliberate: a document carries the recipient as they were when it was
issued.

| buyer field | on the document |
|---|---|
| `title` — required, falls back to `contact_name` | Unvan / Ad Soyad |
| `tax_number` (10) / `tckn` (11) | VKN/TCKN — **one** field; `tax_number` wins if both are sent |
| `tax_office` | Vergi dairesi |
| `address` | Adres |
| `email` | E-posta — see below |
| `phone` | Telefon |

Neither identity is required (your channel may not hold it), but send it when you
have it: without a VKN we cannot look the recipient up at GİB and upgrade the
document to e-Fatura. Send `email` too — on an e-Arşiv document GİB's mandatory
delivery-type field is derived from it: `ELEKTRONIK` when there is an address,
`KAGIT` when there is not.

Which makes the chain fixed: **buyer → sale → document.** `transaction_header_id` is required
when you do reach step 2; the only exception is a refund (`invoice_type_code="IADE"`), which stays
unattached so the sale is not counted twice.

## Quickstart

```python
import os
from finansfatura import FinansfaturaClient, build_earsiv_payload

ff = FinansfaturaClient(api_key=os.environ["FINANSFATURA_API_KEY"])  # ff_live_...

# 1 — the sale. Prices KDV-INCLUSIVE, vat_rate as a percentage.
sale = ff.create_order({
    "provider": "ECOMSOFT",              # your brand; unknown values show as FINANSFATURA
    "external_id": "ORD-2026-00184",     # your stable order id
    "order_number": "184",
    "payment_status": "PAID",
    "currency": "TRY",
    "total_price": 120.0,
    # Belgenin alıcısı: unvan/ad soyad, VKN/TCKN, vergi dairesi, adres, e-posta, telefon
    "buyer": {"title": "Ahmet Yılmaz", "tckn": "11111111111",
              "email": "ahmet@example.com", "phone": "5551112233",
              "address": "Kadıköy / İstanbul"},
    "lines": [{"sku": "SKU-1042", "title": "Kablosuz Kulaklık",
               "quantity": 1, "unit_price": 120.0, "total_price": 120.0,
               "vat_rate": 20}],
})

# 2 — the invoice. Prices KDV-EXCLUSIVE, vat_rate as a ratio.
payload = build_earsiv_payload(
    recipient={"vkn_tckn": "11111111111", "title": "Ahmet Yılmaz"},
    lines=[{"title": "Kablosuz Kulaklık", "product_code": "SKU-1042",
            "qty": 1, "unit_price": 100.0, "vat_rate": 0.20}],
    transaction_header_id=sale["transaction_id"],
)
result = ff.issue_invoice(payload, idempotency_key="ORD-2026-00184")
print(result["invoice_id"], result["status"])   # -> ... QUEUED
```

> **The two endpoints disagree about VAT on purpose.** The order body carries
> KDV-**inclusive** prices with a percentage (`120`, `20`); the invoice body
> carries KDV-**exclusive** prices with a ratio (`100`, `0.20`). This is the most
> common integration bug — the builders keep the invoice side honest, the order
> side is yours.

`transaction_header_id` links the invoice to the sale — the builder raises
without it, and so does the API. A document that hangs off no sale is invisible to
the turnover report, the current account and stock.

### Sandbox

```python
from finansfatura import SANDBOX_BASE_URL

ff = FinansfaturaClient(api_key="ff_test_...", base_url=SANDBOX_BASE_URL)
```

Sandbox and production are entirely separate systems — keys, OAuth clients and
data never cross over.

### Typed inputs (optional)

Prefer autocomplete and early "missing field" errors over raw dicts? Pass
`Party` / `Line` dataclasses instead — same result, no extra dependency:

```python
from finansfatura import Party, Line, build_earsiv_payload

payload = build_earsiv_payload(
    recipient=Party(vkn_tckn="11111111111", title="Ahmet Yılmaz", email="ahmet@example.com"),
    lines=[Line(title="Kablosuz Kulaklık", qty=1, unit_price=100.0, vat_rate=0.20)],
    transaction_header_id=sale["transaction_id"],
)
```

Dicts and dataclasses are interchangeable everywhere; use whichever you like.

`build_earsiv_payload` computes totals from the lines (Decimal, no float drift)
and applies the API's exact field casing for you: the outer layer is snake_case
(`document_type`, `canonical`) but everything inside `canonical` is PascalCase
(`Recipient`, `Lines`, `Totals`, `VKNorTCKN`). A snake_case key inside `canonical`
is silently ignored by the server, so let the builder handle it.

## Idempotency

`idempotency_key` is **required** on `issue_invoice` and can be any unique string
(use your order id). Retrying with the same key never double-issues and never
charges credits twice. Likewise, resending the same `external_id` to
`create_order` never duplicates the sale — you get `200` with
`already_imported: true` instead of `201`. Both are what make retries safe.

## Following the status

The invoice number is **not** in the issue response — the provider assigns it a
moment later. Read it from the bulk status endpoint:

```python
res = ff.order_status("ecomsoft", ["ORD-2026-00184", "ORD-2026-00185"])
for s in res["statuses"]:
    print(s["external_id"], s["invoice_status"], s.get("invoice_number"))
```

Up to 50 ids per call. Orders we never received are simply absent from the
response, so match on `external_id` — don't trust the order. Statuses are
`NOT_INVOICED`, `QUEUED`, `ISSUED`, `ACCEPTED`, `REJECTED`, `CANCELLED`; the last
three are final.

Check once in the first minute after issuing, then every few minutes for the
records that are not final yet. Polling faster does not make GİB answer sooner.

## Reading & lifecycle

```python
ff.get_invoice(invoice_id)
ff.list_invoices(page=1, page_size=20)
pdf_bytes = ff.download(invoice_id, "pdf")  # or "html" / "xml"
ff.cancel(invoice_id)                       # e-Arşiv outright; e-Fatura is a process
```

## VAT exemption

**A zero-VAT line cannot be invoiced without an exemption reason** — GİB rejects
it. The reason is document-level and lands only on the zero-VAT lines, so a mixed
document never looks like the exemption covers the taxed lines too.

```python
payload = build_earsiv_payload(
    recipient=recipient,
    lines=[
        {"title": "Mal ihracatı", "qty": 1, "unit_price": 1000.0, "vat_rate": 0},
        {"title": "Kargo", "qty": 1, "unit_price": 100.0, "vat_rate": 0.20},
    ],
    transaction_header_id=sale["transaction_id"],
    exemption_code="301",                   # GİB 2xx (partial) / 3xx (full)
    exemption_reason="11/1-a Mal ihracatı",
)
```

Both are required together: GİB will not take an empty `cbc:TaxExemptionReason`,
and a code with no text declares nothing. On a sale, send
`invoice_exemption_code` + `invoice_exemption_reason` instead — it is then stored
on the sale and the invoice reads it from there.

**Do not send the invoice type.** The server derives it (zero-VAT + exemption →
`ISTISNA`).

## Scenario (e-Fatura only)

`TEMELFATURA` or `TICARIFATURA`. The difference is legal, not cosmetic: on a
TEMEL invoice the recipient cannot answer and the document is final; on a TİCARİ
one they may send KABUL/RED within 8 days. Default is TICARIFATURA; e-Arşiv has
no choice.

```python
build_efatura_payload(
    recipient=recipient, lines=lines,
    transaction_header_id=sale["transaction_id"],
    scenario="TEMELFATURA",
)
```

## Refunds

A refund is its own document (`IADE`) with its own idempotency key, deliberately
not attached to the sale — attaching it would count the sale twice.

```python
ff.refund({
    "external_id": "REF-2026-0007",        # your stable refund id
    "order_external_id": "ORD-2026-00184",  # the sale being refunded
    "currency": "TRY",
    "total_price": 120.0,
    "lines": [...],   # same shape as the sale's lines
    "buyer": {...},   # same recipient
})
```

Lines carry **positive** amounts; the document type, not the sign, says it is a
refund. Prices are KDV-INCLUSIVE and `vat_rate` is a percentage, as in
`createOrder()`.

Refunding a foreign-currency sale uses the ORIGINAL sale's rate, not today's:
leave `exchange_rate` out and we look it up from the sale we hold. Refunding a
months-old sale at today's rate is a wrong declaration.

### Issuing the refund document yourself

It needs the ORIGINAL invoice it refunds — GİB rejects a refund without that
reference:

```python
build_earsiv_payload(
    recipient=recipient, lines=lines,
    invoice_type_code="IADE",            # or TEVKIFATIADE / YTBIADE
    return_info={"number": "FF32026000000123", "issue_date": "2026-09-27"},
)
```

The date is sent as RFC 3339 for you; a bare `2026-09-27` would fail to parse
server-side. This is also the one document where `currency` / `exchangeRate`
matter — there is no sale to take them from.

## Withholding and special tax base

Both are per line, and they are opposite situations — withholding splits who
*pays* the VAT, a special tax base changes what the VAT is *computed on*:

```python
build_efatura_payload(
    recipient=recipient,
    lines=[
        {"title": "Temizlik hizmeti", "qty": 1, "unit_price": 1000.0, "vat_rate": 0.20,
         "withholding_code": "612", "withholding_name": "Temizlik hizmeti"},
        {"title": "İkinci el araç", "qty": 1, "unit_price": 550000.0, "vat_rate": 0.20,
         "tax_base_amount": 50000.0, "tax_base_code": "812",
         "tax_base_reason": "İkinci el araç kâr marjı"},
    ],
    transaction_header_id=sale["transaction_id"],
)
```

**You do not send the withholding rate.** Each GİB code carries a fixed legal
rate and the server derives it from the code — `612` (cleaning) went from 7/10
to 9/10 in 2023. If the rate came from you, a GİB update would leave your
integration filing wrong declarations for years.

`8xx` codes exist in *both* lists (withholding 801-825, special base 801-812) but
are different UBL elements and different fields.

## Exchange rates

**You usually don't need to supply one.** Leave `exchange_rate` off a
foreign-currency sale (or send `0`) and the server fills in the TCMB rate, then
tells you what it used:

```python
sale = ff.create_order({
    "external_id": "ORD-1", "currency": "USD",  # no exchange_rate
    "buyer": buyer, "lines": lines,
})
sale["exchange_rate"]         # 41.37
sale["exchange_rate_source"]  # "TCMB" — ours. "MANUAL" when you sent your own
sale["exchange_rate_date"]    # "27.09.2026" — the bulletin's date
```

Send your own rate when you want yours instead of ours: it is used verbatim and
never compared against TCMB. The bulletin is published on weekdays around 15:30
and not at weekends, so a Monday-morning document carries Friday's rate.

A rate is never invented: if the bulletin does not carry that currency the
request fails with `ERROR_EXCHANGE_RATE_REQUIRED`.

## Errors

Failed calls raise a typed exception carrying `.status`, `.body` and `.retryable`:

| Exception | HTTP | Meaning | Retry |
|-----------|------|---------|-------|
| `ValidationError` | 400, 422 | bad body — `.body["errors"]` names the fields | ❌ |
| `AuthError` | 401 | key/token missing, invalid, revoked or expired | ❌ |
| `InsufficientCredits` | 402 | not enough credits (kontör) | ❌ |
| `ScopeError` | 403 | missing scope, or endpoint closed to API keys | ❌ |
| `OnboardingRequired` | 412 | the taxpayer's e-invoice setup is unfinished | ❌ |
| `RateLimitError` | 429 | too many requests | ✅ |
| `ProviderError` | 5xx | transient upstream / provider unreachable | ✅ |
| `FinansfaturaError` | other | base class | — |

```python
from finansfatura import FinansfaturaError, OnboardingRequired

try:
    ff.issue_invoice(payload, idempotency_key=f"order-{order.id}")
except OnboardingRequired:
    # The sale is safe. Tell the merchant to finish setup in the panel; the
    # pending sales can be invoiced later.
    ...
except FinansfaturaError as e:
    if e.retryable:
        schedule_retry(order.id)   # 1s, 2s, 4s, 8s …
    else:
        log.error("issue failed [%s]: %s", e.status, e.body)
```

## e-Fatura vs e-Arşiv

Send `EARSIV` and let the server correct it. When `RecipientAlias` is left empty
(the default), we ask GİB about the recipient's VKN: registered taxpayers are
upgraded to `EFATURA` with the mailbox alias resolved, everyone else stays
`EARSIV`. You don't need to run the lookup yourself.

```python
from finansfatura import build_efatura_payload

payload = build_efatura_payload(
    recipient={"vkn_tckn": "1234567890", "title": "Kurum A.Ş."},
    lines=[...],
    transaction_header_id=sale["transaction_id"],
    # recipient_alias="urn:mail:defaultpk@example.com",  # only if you already know it
)
```

Other document types (`EIRSALIYE`, `ESMM`, `EMM`, `EADISYON`) go through
`build_payload(document_type, ...)`.

## OAuth 2.0

API keys bind to one company. If your product serves many taxpayers, register an
OAuth client (partner@finansfatura.com) and drop the copy-paste step:

```python
from finansfatura import FinansfaturaClient, OAuth, generate_pkce

oauth = OAuth(client_id=..., client_secret=..., redirect_uri="https://app.example.com/ff/callback")

# 1 — send the taxpayer to the consent screen
verifier, challenge = generate_pkce()        # keep `verifier` in the session
session["ff_verifier"] = verifier
redirect(oauth.authorize_url(code_challenge=challenge, state=csrf_token))

# 2 — the callback comes back with ?code=…
token = oauth.exchange_code(request.args["code"], code_verifier=session["ff_verifier"])
store(token["access_token"], token["refresh_token"], token["expires_in"])

# 3 — use it
ff = FinansfaturaClient(access_token=token["access_token"])
```

```python
token = oauth.refresh(stored_refresh_token)   # store the NEW refresh token
oauth.revoke(stored_refresh_token)            # end the connection
```

- `redirect_uri` must match a registered address **exactly**; partial matches are
  rejected.
- Every refresh invalidates the previous refresh token. Persist the newest one or
  the connection dies.
- Scopes: `invoice:read` (status/reads) and `invoice:write` (sales, issuing,
  cancelling). Ask only for what you use.
- Token and revoke URLs keep their **trailing slash** — the client handles it.

## Notes

- Seller identity (`Issuer`) is filled server-side from your company profile —
  don't send it. Make sure the profile VKN is set, or issuing returns 503.
- Keep the API key server-side and encrypted; it acts on the taxpayer's company.
  Never ship it to a browser or mobile app.
- `base_url` is the API host only (`https://api.finansfatura.com`) — paths are
  built by the client. Since 0.2.0 it no longer includes `/v1/invoicing`.

## Changelog

See [CHANGELOG.md](CHANGELOG.md).

## Development

```bash
pip install -e ".[dev]"
python -m pytest        # or: python -m unittest discover tests
```

## License

MIT
