Metadata-Version: 2.5
Name: eracun-hr
Version: 0.1.0
Summary: Build, read and validate Croatian eRačun documents (UBL 2.1, EN 16931, CIUS-HR with extensions / Fiskalizacija 2.0)
Project-URL: Homepage, https://github.com/wozimon/eracun-hr
Project-URL: Documentation, https://github.com/wozimon/eracun-hr#readme
Project-URL: Issues, https://github.com/wozimon/eracun-hr/issues
Project-URL: Changelog, https://github.com/wozimon/eracun-hr/blob/main/CHANGELOG.md
Author: eracun-hr contributors
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: cius-hr,croatia,e-invoice,einvoice,en16931,eracun,fiskalizacija,ubl
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial :: Accounting
Classifier: Topic :: Text Processing :: Markup :: XML
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: lxml>=5.2
Requires-Dist: pydantic>=2.6
Requires-Dist: saxonche>=12.5
Requires-Dist: typer>=0.12
Provides-Extra: dev
Requires-Dist: lxml-stubs>=0.5; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pypdf==6.21.2; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# eracun-hr

Build, read and validate Croatian **eRačun** documents in Python — UBL 2.1
invoices and credit notes according to EN 16931 and the Croatian
*Specifikacija osnovne uporabe eRačuna s proširenjima* (CIUS-HR with
extensions, **Fiskalizacija 2.0**), including the `HRFISK20Data` extension,
HR-TB-2 VAT category tags, KPD classification and OIB checks.

> [!IMPORTANT]
> **Disclaimer.** This library helps you produce and check eRačun documents.
> It is **not a certified solution** and does **not guarantee compliance with
> the Zakon o fiskalizaciji** or any other regulation. Validation results are
> only as good as the official artefacts they run; always confirm with your
> information intermediary and the Tax Administration.

## Features

* **Models** — pydantic v2 models for the full EN 16931 semantic model plus every
  CIUS-HR business term (HR-BT-1 … HR-BT-25). Amounts are `decimal.Decimal`
  only; floats are rejected.
* **Writer / reader** — UBL 2.1 `Invoice` and `CreditNote` XML in official schema
  order; lossless round-trip of all 20 official examples.
* **Calculation** — line amounts, document totals, VAT breakdown and the HR VAT
  breakdown (`HRFISK20Data`), reproducing every official example.
* **Validation with the official artefacts**, nothing re-implemented by hand:
  1. XSD — *UBL 2.1 eRačun* schemas (Porezna uprava);
  2. EN 16931 — CEN/TC 434 Schematron (BR-*, BR-CO-*, BR-CL-*, UBL-*);
  3. CIUS-HR — the Tax Administration's `HR-CIUS-EXT-EN16931-UBL` Schematron (HR-BR-*).

  Each finding carries the rule ID, XPath, line, severity, the Croatian and
  English message and the place in the specification. No Java needed
  (Saxon runs via [`saxonche`](https://pypi.org/project/saxonche/)).
* **CLI** — `eracun validate | build | inspect | rules | artifacts`.
* **Code lists** — KPD, HR-TB-1, HR-TB-2, UNTDID 1001/4461/5189/5305/7161, ISO
  4217/3166, UN/ECE Rec 20, EAS, VATEX — generated from the official Schematron.

## Installation

```console
pip install eracun-hr
```

Python 3.11 or newer. The distribution is `eracun-hr`, the import package is
`eracun_hr` and the command-line tool is `eracun`.

## Official artefacts, caching and offline use

The official XSD and Schematron files are **not bundled** (see
[docs/sources.md](docs/sources.md)). On first use they are downloaded from the
pinned official URLs (Porezna uprava, CEN on GitHub, SchXslt on Maven Central),
checked against pinned **SHA-256** hashes and unpacked into a cache; a file whose
hash does not match is rejected. About 3 MB is downloaded once; the compiled HR
Schematron is cached as well.

```console
eracun artifacts fetch      # download and verify the validation artefacts up front
eracun artifacts list       # pinned versions, cache location, cached or missing
```

| Variable | Effect |
|---|---|
| `ERACUN_ARTIFACTS_DIR` | Cache directory. Default: `%LOCALAPPDATA%\eracun-hr\artifacts` on Windows, `$XDG_CACHE_HOME/eracun-hr/artifacts` or `~/.cache/eracun-hr/artifacts` elsewhere. |
| `ERACUN_OFFLINE=1` | Never touch the network; a missing artefact raises `ArtifactError` instead of downloading. |

**Offline / air-gapped machines:** run `eracun artifacts fetch` on a machine with
network access, copy the cache directory, point `ERACUN_ARTIFACTS_DIR` at it and
set `ERACUN_OFFLINE=1`. The hashes are checked again when an archive is unpacked.

**CI:** cache the directory between runs, keyed on the installed version (the pins
live in the package, so a new version may pin new artefacts). GitHub Actions:

```yaml
env:
  ERACUN_ARTIFACTS_DIR: ${{ github.workspace }}/.eracun-artifacts
steps:
  - uses: actions/cache@v4
    with:
      path: .eracun-artifacts
      key: eracun-artifacts-${{ hashFiles('requirements*.txt', 'pyproject.toml', 'poetry.lock', 'uv.lock') }}
  - run: pip install eracun-hr
  - run: eracun artifacts fetch
  - run: eracun validate invoices/*.xml
```

## Build an invoice

```python
from datetime import date, time
from eracun_hr import Invoice, complete, to_xml, validate
from eracun_hr.models import Address, Buyer, Identifier, Item, ItemClassification, Line
from eracun_hr.models import Operator, Price, Seller, TaxCategory

oib = lambda n: Identifier(value=n, scheme_id="9934")  # OIB as electronic address
invoice = complete(Invoice(  # complete() computes line amounts, totals, VAT and HR breakdown
    number="1-P1-1", issue_date=date(2026, 3, 2), issue_time=time(12, 0), due_date=date(2026, 4, 1),
    process_type="P1",
    seller=Seller(name="Primjer d.o.o.", vat_id="HR12345678903", endpoint=oib("12345678903"),
                  address=Address(city="Zagreb", country_code="HR"),
                  operator=Operator(name="Operater1", oib="12345678903")),
    buyer=Buyer(name="Kupac d.o.o.", vat_id="HR11111111119", endpoint=oib("11111111119"),
                address=Address(city="Rijeka", country_code="HR")),
    lines=[Line(id="1", quantity=2, unit_code="H87", price=Price(amount="49.90"), item=Item(
        name="Usluga", classifications=[ItemClassification(code="62.20.20", list_id="CG")],
        tax_category=TaxCategory(code="S", percent=25, hr_tag="HR:PDV25")))],
))
xml = to_xml(invoice)
```

A longer example lives in [examples/build_invoice.py](examples/build_invoice.py).

## Validate

```python
report = validate(xml)  # bytes, str, path, lxml element or model
assert report.is_valid
for issue in report.errors:  # fatal findings of all three layers
    print(issue.rule_id, issue.xpath, issue.line, issue.message_hr, issue.message_en)
```

`report.warnings` also contains CEN syntax warnings such as *UBL-CR-006 "A UBL
invoice should not include the IssueTime"*: CIUS-HR requires those elements, so
every Croatian document triggers them. They keep their official severity and are
labelled with `issue.expected_for_cius_hr` (the HR business term involved).

Read an existing document:

```python
from eracun_hr import from_xml

doc = from_xml(xml)
assert doc.totals.payable_amount == invoice.totals.payable_amount
```

## Command line

```console
$ eracun validate racun.xml --lang hr
racun.xml: INVALID (1 errors, 3 warnings)
  fatal   HR-BR-34     line 2: Oznaka procesa (BT-23) MORA biti navedena. Koriste se vrijednosti P1-P12 ili P99:Oznaka kupca
          at /Invoice[1]
$ eracun validate racun.xml --json      # machine-readable report; exit code 1 if invalid
$ eracun inspect racun.xml              # summary; --json dumps the model
$ eracun build racun.json -o racun.xml --validate
$ eracun rules --layer hr               # list the rules of the official Schematron
```

## Limitations

* **Out of scope (interfaces only, see `eracun_hr.adapters`)**: XML signature,
  sending over AS4 / eDelivery, information intermediaries (Moj-eRačun, …),
  fiscalisation and eIzvještavanje requests, B2C fiscalisation.
* Signing must be the last step: re-serialising a signed document breaks the
  signature. The reader keeps `sig:UBLDocumentSignatures` verbatim but does not
  verify it.
* The model covers the EN 16931 semantic model plus the CIUS-HR extensions;
  other UBL elements are ignored when reading.
* `calc.vat_breakdown` copies the VAT exemption reason (BT-120/BT-121) from the
  first contributing line or allowance/charge — the specification does not define
  this, so review it for mixed exemptions.
* English messages for HR-BR-* rules are unofficial translations; the Croatian
  text is the official one.
* All 62 HR-BR rules have dedicated positive and negative tests; the 982 CEN rules
  run from the official artefact and only a sample has dedicated tests (see
  [docs/rules.md](docs/rules.md)).
* The validator version of the Tax Administration is not public; this library
  pins CEN artefacts 1.3.17 and HR Schematron `13032026-2`.

## Known issues in the official materials

Found while building the test suite (details and sources in
[docs/sources.md](docs/sources.md)). They are reported here so that results of
this library can be compared with other validators.

1. **The official examples fail the current official validator.** All 20 files of
   *Primjeri eRačuna* (2025-12-12) use the placeholder OIB `12345678901`, whose
   ISO 7064 check digit is wrong (HR-BR-9, HR-BR-53), and issue dates in 2025,
   which HR-BR-40 (added in specification 1.6) rejects. With a valid OIB and 2026
   dates, 19 of 20 pass all three layers.
2. `Racun za leasing PDV PPMV-aktivacija.xml` has an invoice line without a KPD
   code, which HR-BR-25 rejects.
3. The specification's path column gives `ext:Extensions/ext:Extension/…` for
   HR-BG-1 … HR-BG-3 and `cac:TaxCategory` for HR-BT-18, while the XSD and the
   Schematron use `ext:UBLExtensions/ext:UBLExtension/…` and `hrextac:HRTaxCategory`.
   This library follows the XSD.
4. HR-BG-1 (`HRFISK20Data`) is described as mandatory for invoices subject to
   Fiskalizacija 2.0, but 12 of the 20 official examples do not contain it and the
   Schematron only requires it in the HR-BR-26 / HR-BR-30 cases.
5. The text of HR-BT-15 differs between the specification ("Obračun prema
   naplaćenoj naknadi" / "… naplaćenim naknadama") and the official example
   ("Obračun po naplaćenoj naknadi").
6. The specification does not say how the exemption reason in the VAT breakdown
   (BT-120/BT-121) and in the HR VAT breakdown (HR-BT-20/HR-BT-21) is derived;
   the official examples are not consistent with each other.
7. HR-BR-35 appears only in the change log; HR-BR-13 refers to HR-BT-6/HR-BT-7
   where the tables define HR-BT-7/HR-BT-8; HR-BR-CL-2 reports its message as
   `[HR-BR-25]`.
8. Possible defects in the official HR Schematron: for an `Invoice`, HR-BR-41 is
   only evaluated when `cac:PaymentMeans/cbc:PaymentDueDate` exists, so an invalid
   `cbc:DueDate` alone is not reported; HR-BR-29 passes whenever *any* HR VAT
   breakdown entry has a tax amount of 0.

## Hrvatski

**eracun-hr** je Python biblioteka za izradu, čitanje i provjeru eRačuna (UBL 2.1)
prema normi EN 16931 i *Specifikaciji osnovne uporabe eRačuna s proširenjima*
(Fiskalizacija 2.0), uključujući proširenje `HRFISK20Data`, oznake kategorija
PDV-a iz tablice HR-TB-2, KPD klasifikaciju i provjeru OIB-a.

**Instalacija:** `pip install eracun-hr` (Python 3.11 ili noviji); paket se
uvozi kao `eracun_hr`, a naredba je `eracun`. Službene XSD i Schematron datoteke
Porezne uprave i CEN-a preuzimaju se pri prvoj uporabi sa službenih adresa,
provjeravaju SHA-256 sažetkom i spremaju u lokalnu privremenu pohranu
(`ERACUN_ARTIFACTS_DIR`); za rad bez mreže postavite `ERACUN_OFFLINE=1`.

**Izrada računa:** vidi primjer *Build an invoice* gore — `complete()` izračunava
iznose stavaka, ukupne iznose, raspodjelu PDV-a i HR raspodjelu PDV-a, a
`to_xml()` stvara UBL XML.

**Provjera:** `validate(xml)` provodi provjeru u tri sloja (XSD, EN 16931,
HR-CIUS-EXT) službenim artefaktima. Iz naredbenog retka:
`eracun validate racun.xml --lang hr` ispisuje službene poruke na hrvatskom.

**Ograničenja:** biblioteka ne potpisuje račune, ne šalje ih (AS4, informacijski
posrednici), ne fiskalizira i ne provodi eIzvještavanje — za to postoje samo
sučelja u modulu `eracun_hr.adapters`.

**Odricanje od odgovornosti:** biblioteka pomaže pri izradi i provjeri
dokumenata, ali **nije certificirano rješenje** i **ne jamči usklađenost sa
Zakonom o fiskalizaciji**.

## Documentation

* [docs/research.md](docs/research.md) — survey of existing implementations
* [docs/sources.md](docs/sources.md) — official sources, versions, licences, known issues
* [docs/rules.md](docs/rules.md) — every validation rule and its status
* [CONTRIBUTING.md](CONTRIBUTING.md), [CHANGELOG.md](CHANGELOG.md)

## Licence

Apache-2.0 for the code (see [LICENSE](LICENSE) and [NOTICE](NOTICE)). The
official artefacts downloaded at run time keep their own terms: CEN artefacts
EUPL-1.2; Porezna uprava material may be reproduced with attribution of the
source; SchXslt MIT; Saxon-HE (`saxonche`) MPL-2.0.
