Metadata-Version: 2.5
Name: fajfield-einvoice
Version: 0.1.0
Summary: Build, check and read UAE e-invoices (Peppol PINT AE). Clear errors, logging and debug helpers. No dependencies.
Project-URL: Homepage, https://fajfield.com/e-invoicing/
Project-URL: Documentation, https://fajfield.com/developers/e-invoicing/
Project-URL: Source, https://github.com/fajfield/fajfield-einvoice
Author: Fajfield
License-Expression: MIT
License-File: LICENSE
Keywords: e-invoicing,einvoice,fta,peppol,pint-ae,uae,ubl,vat
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial :: Accounting
Requires-Python: >=3.8
Description-Content-Type: text/markdown

# fajfield-einvoice

Build, check and read **UAE e-invoices** (Peppol **PINT AE**, UBL 2.1) from Python: Django, Flask, FastAPI, Odoo and ERPNext modules, scripts. Plain dicts in, valid PINT AE XML out, with plain-language errors, logging and debugging helpers. **No dependencies**, Python 3.8+.

- **Tested against the official rules:** output is checked against the official PINT AE Schematron in CI, and the SDK reads and rebuilds all 31 official PINT AE sample invoices into files that pass those rules.
- **Same results as every Fajfield SDK:** JavaScript, Python, .NET and Dart produce byte-identical XML and the same issues for the same invoice, checked in CI.
- **Errors you can act on:** each problem names the field, says what is wrong and how to fix it, and cites the official rule.
- **All the maths done for you:** line amounts, VAT breakdown, totals, AED amounts for foreign-currency invoices, transaction type flags.
- **Read received invoices** back into the same model, with a check that their totals add up.
- **Logging and debugging built in:** trace IDs, timings, pluggable log sinks, a step-by-step explanation, and a masked debug report that is safe to attach to a support ticket.

Fajfield is not an accredited service provider (ASP). This SDK produces the invoice file; your ASP sends it on the Peppol network and reports it to the FTA. For connecting any software to any ASP without code, see the [Fajfield e-invoicing gateway](https://fajfield.com/e-invoicing/).

## Install

```sh
pip install fajfield-einvoice
```

## Build an invoice

```python
from fajfield_einvoice import EInvoicing

ei = EInvoicing(log_level='info')

result = ei.build({
    'number': 'INV-2026-0452',
    'issueDate': '2026-11-30',
    'dueDate': '2026-12-14',
    'seller': {
        'name': 'Harbour Foods Trading LLC',
        'trn': '100234567800003',          # VAT registration number (TRN)
        'tin': '1002345678',               # tax identification number, also the Peppol address
        'legalId': {'type': 'TL', 'id': 'CN-1234567', 'authority': 'Dubai Department of Economy and Tourism'},
        'address': {'street': 'Warehouse 14, Al Quoz Industrial 3', 'city': 'Dubai', 'emirate': 'DXB'},
    },
    'buyer': {
        'name': 'Fresh Mart Supermarket LLC',
        'trn': '100987654300003',
        'tin': '1009876543',
        'legalId': {'type': 'TL', 'id': 'CN-7654321', 'authority': 'Abu Dhabi Department of Economic Development'},
        'address': {'street': 'Shop 3, Al Wahda Mall', 'city': 'Abu Dhabi', 'emirate': 'AUH'},
    },
    'payment': {'means': '30', 'accountId': 'AE070331234567890123456'},
    'lines': [
        {'name': 'Basmati rice 5 kg', 'quantity': 40, 'price': 18.5, 'vat': {'category': 'S'}, 'itemType': 'G', 'hsCode': '100630'},
        {'name': 'Delivery service', 'quantity': 1, 'price': 75, 'vat': {'category': 'S'}, 'itemType': 'S'},
    ],
})

if result.ok:
    send_to_your_asp(result.xml)            # the PINT AE XML
    save_uuid(result.invoice['uuid'])       # generated if you did not give one: keep it
else:
    print(ei.format(result.errors))
```

The model uses the same camelCase keys as every Fajfield SDK, so the JSON in [`spec/invoices`](../spec/invoices) works as is. `build()` checks first and only writes XML when there are no errors. Use `throw_on_error=True` to get an `EInvoiceError` (with `.code` and `.issues`) instead, or `strict=False` to write it anyway.

## Errors in plain words

```
✗ buyer.trn: The buyer's TRN "12345" is not valid.
    → A TRN has 15 digits, starts with 1 and ends with 03, for example 100234567800003.  [ibr-132-ae]
✗ seller.address.emirate: "Dubai" is not an emirate code.
    → Use one of: AUH (Abu Dhabi), DXB (Dubai), SHJ (Sharjah), UAQ (Umm Al Quwain), FUJ (Fujairah), AJM (Ajman), RAK (Ras Al Khaimah).  [ibr-128-ae]
✗ lines[0].vat.exemptionCode: Line 1 is exempt, so the exemption reason code is required.
    → For example 'DL8.46.2'.  [ibr-167-ae]
```

Each issue is a dict: `severity`, `code`, `path`, `message`, `hint`, `rule`. Match on `code` (stable) to highlight the right field in your own screens.

## Logging and debugging

```python
from fajfield_einvoice import EInvoicing, create_logger, json_sink, memory_sink

ei = EInvoicing(log_level='debug')                       # while integrating: everything to the console

recent = memory_sink(500)                                # in production: JSON lines + recent entries for support
ei = EInvoicing(logger=create_logger('info', [json_sink(), recent]))

# or send entries to the standard logging module
import logging
log = logging.getLogger('einvoice')
ei = EInvoicing(log_level='info', sink=lambda e: log.info('%s %s', e['event'], e['message'], extra=e))
```

Every entry for one invoice carries the same trace ID (`result.trace_id`).

```python
print(ei.explain(invoice))                               # how every amount was calculated
report = ei.debug_report(invoice, logs=recent.entries, trace_id=result.trace_id)   # masked by default
```

Other helpers: `describe_transaction_type('10000001')` → `['Free zone supply', 'Export']`, `describe('vat', 'AE')` → `'Reverse charge'`, `redact(invoice)`, `mask(value)`, `calculate(invoice)`.

## Read a received invoice

```python
parsed = ei.parse(xml_from_your_asp)
if parsed['mismatches']:
    print('Totals do not add up:', parsed['mismatches'])
book_purchase_invoice(parsed['invoice'])                 # same model as the invoices you send
```

## What's supported

| | |
|---|---|
| Documents | Tax invoice (380), commercial invoice (480), tax credit note (381), credit note (81) |
| VAT | Standard 5%, zero-rated, exempt (with reason code), out of scope, reverse charge, additional rate |
| Special transactions | Free zone, deemed supply, margin scheme, summary, continuous supplies, disclosed agent, e-commerce, exports (the 8 flags of BTAE-02) |
| Amounts | Line discounts and charges, price discounts, document allowances and charges, prepaid amounts, rounding |
| Currency | Any currency, with the AED VAT total, AED line amounts and AED total the UAE requires |
| Parties | TRN, TIN, Peppol address, trade licence / Emirates ID / passport / cabinet decision, addresses, contacts |
| Items | Goods/services type, HS code, service accounting code (SAC), GTIN, reverse charge type |
| Payment | Payment means, bank account, card (last 4 digits), payment terms |

Coming next: Oman (PINT OM), Saudi Arabia (ZATCA), India (IRP).

## Not tax advice

This SDK is software. It follows the published PINT AE specification and validation rules; your accountant or tax adviser decides how each transaction should be invoiced. Always test with your ASP before going live.

## License

MIT. Made by [Fajfield](https://fajfield.com): research and development for ERP, warehouse, POS and business data.
