Skip to content

Commit ad6ee0e

Browse files
committed
feat: generate EN 16931 compatible invoices
This is a proof of concept, I had to use several libraries to make it work. Outstanding issues: - The VAT validation fails because of zfutura/pycheval#30 - Embedding in PDF does not work for our PDFs with pycheval, using factor-x instead for that. - We really need full validation to be part of the tests, needs to be investigated. - There are definitely issues with generated XML.
1 parent a4ae79e commit ad6ee0e

4 files changed

Lines changed: 195 additions & 5 deletions

File tree

.github/workflows/test.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ jobs:
4747
run: |
4848
sudo apt update
4949
sudo apt install gettext
50+
- name: Start validation service
51+
env:
52+
# renovate: datasource=github-releases depName=gflohr/e-invoice-eu-validator versioning=loose
53+
VALIDATOR_VERSION: 2.16.4
54+
run: |
55+
curl -L "https://github.com/gflohr/e-invoice-eu-validator/releases/download/v$VALIDATOR_VERSION/validator-$VALIDATOR_VERSION-jar-with-dependencies.jar" > /tmp/validator.jar
56+
PORT=7070 java -jar /tmp/validator.jar &
5057
- name: Set up Python ${{ matrix.python-version }}
5158
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
5259
with:
@@ -63,6 +70,8 @@ jobs:
6370
run: ./manage.py collectstatic
6471
- name: Django checks
6572
run: ./manage.py check
73+
env:
74+
EINVOICE_VALIDATOR_URL: http://localhost:7070/
6675
- name: Test with Django
6776
run: |
6877
pytest --junitxml=junit.xml weblate_web

requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ django-redis==6.0.0
1111
django-stubs-ext==5.2.7
1212
django-vies==6.2.1
1313
djangosaml2==1.11.1
14+
drafthorse==2025.2.0
15+
factur-x==3.13
1416
fiobank==4.0.0
1517
hiredis==3.3.0
1618
html2text==2025.4.15
@@ -20,6 +22,7 @@ mysqlclient==2.2.7
2022
paramiko==4.0.0
2123
Pillow==12.0.0
2224
psycopg[binary]==3.2.12
25+
PyCheval==0.3.0
2326
pyopenssl==25.3.0
2427
python-dateutil==2.9.0.post0
2528
pytz==2025.2

weblate_web/invoices/models.py

Lines changed: 161 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import datetime
2222
import uuid
2323
from decimal import Decimal
24+
from io import BytesIO
2425
from pathlib import Path
2526
from shutil import copyfile
2627
from typing import TYPE_CHECKING, Literal, cast
@@ -40,7 +41,22 @@
4041
from django.utils.safestring import mark_safe
4142
from django.utils.timezone import now
4243
from django.utils.translation import gettext, override
44+
from facturx import generate_from_binary
4345
from lxml import etree
46+
from pycheval import (
47+
BankAccount,
48+
EN16931Invoice,
49+
EN16931LineItem,
50+
Money,
51+
PaymentMeans,
52+
PaymentTerms,
53+
PostalAddress,
54+
Tax,
55+
TradeParty,
56+
generate_xml,
57+
)
58+
from pycheval.quantities import QuantityCode
59+
from pycheval.type_codes import DocumentTypeCode, PaymentMeansCode, TaxCategoryCode
4460

4561
from weblate_web.exchange_rates import ExchangeRates
4662
from weblate_web.pdf import render_pdf
@@ -529,8 +545,14 @@ def xml_path(self) -> Path:
529545
"""XML path object."""
530546
return settings.INVOICES_PATH / self.get_filename("xml")
531547

548+
@property
549+
def en_16931_xml_path(self) -> Path:
550+
"""XML path object."""
551+
return settings.INVOICES_PATH / self.get_filename("einvoice.xml")
552+
532553
def generate_files(self) -> None:
533554
self.generate_money_s3_xml()
555+
self.generate_en_16931_xml()
534556
self.generate_pdf()
535557
self.sync_files()
536558

@@ -646,7 +668,7 @@ def add_amounts(root, in_czk: bool = False) -> None:
646668
add_element(adresa, "Ulice", self.customer.address)
647669
add_element(adresa, "Misto", self.customer.city)
648670
add_element(adresa, "PSC", self.customer.postcode)
649-
add_element(adresa, "Stat", self.customer.country)
671+
add_element(adresa, "Stat", self.customer.country.code)
650672
if self.customer.vat:
651673
add_element(prijemce, "PlatceDPH", "1")
652674
add_element(prijemce, "FyzOsoba", "0")
@@ -679,14 +701,148 @@ def generate_money_s3_xml(self) -> None:
679701
settings.INVOICES_PATH.mkdir(exist_ok=True)
680702
self.save_invoice_xml(document, self.xml_path)
681703

704+
def get_en_16931_xml(self) -> EN16931Invoice:
705+
type_code = DocumentTypeCode.INVOICING_DATA_SHEET
706+
if self.kind == InvoiceKind.INVOICE:
707+
type_code = DocumentTypeCode.INVOICE
708+
elif self.kind == InvoiceKind.QUOTE:
709+
type_code = DocumentTypeCode.VALIDATED_PRICED_TENDER
710+
elif self.kind == InvoiceKind.PROFORMA:
711+
type_code = DocumentTypeCode.PRO_FORMA_INVOICE
712+
total_amount = Money(self.total_amount, self.get_currency_display())
713+
714+
tax_amount = Money(self.total_vat, self.get_currency_display())
715+
tax_basis_amount = Money(self.total_amount_no_vat, self.get_currency_display())
716+
717+
tax_category = (
718+
TaxCategoryCode.STANDARD_RATE
719+
if self.vat_rate
720+
else TaxCategoryCode.REVERSE_CHARGE
721+
)
722+
tax = Tax(
723+
category_code=tax_category,
724+
calculated_amount=tax_amount,
725+
basis_amount=tax_basis_amount,
726+
rate_percent=self.vat_rate or None,
727+
exemption_reason="Reverse charge" if not self.vat_rate else None,
728+
)
729+
730+
line_items = [
731+
EN16931LineItem(
732+
id=item.package.name if item.package else "ITEM",
733+
name=item.description,
734+
net_price=Money(item.unit_price, self.get_currency_display()),
735+
billed_quantity=(
736+
item.quantity,
737+
QuantityCode.ONE,
738+
), # TODO: convert quantity_unit to QuantityCode
739+
billed_total=Money(item.total_price, self.get_currency_display()),
740+
tax_rate=self.vat_rate or None,
741+
tax_category=tax_category,
742+
billing_period=(item.start_date, item.end_date)
743+
if item.has_date_range
744+
else None,
745+
)
746+
for item in self.all_items
747+
]
748+
# TODO: There might be model for discount
749+
if self.discount:
750+
line_items.append(
751+
EN16931LineItem(
752+
id="DISCOUNT",
753+
name=self.discount.description,
754+
description=self.discount.display_percents,
755+
net_price=Money(self.total_discount, self.get_currency_display()),
756+
billed_quantity=(1, QuantityCode.ONE),
757+
billed_total=Money(
758+
self.total_discount, self.get_currency_display()
759+
),
760+
tax_rate=self.vat_rate,
761+
tax_category=tax_category,
762+
)
763+
)
764+
765+
payment_means = []
766+
if self.prepaid:
767+
prepaid_amount = total_amount
768+
due_payable_amount = Money(Decimal(0), self.get_currency_display())
769+
payment_reference = None
770+
payment_terms = None
771+
else:
772+
prepaid_amount = None
773+
due_payable_amount = total_amount
774+
payment_reference = self.number
775+
if self.currency == Currency.EUR:
776+
# TODO: support other currencies here
777+
payment_means = [
778+
PaymentMeans(
779+
type_code=PaymentMeansCode.BANK_PAYMENT,
780+
payee_account=BankAccount(
781+
name=self.bank_account.holder,
782+
bank_id=self.bank_account.bic,
783+
iban=self.bank_account.raw_iban,
784+
),
785+
payee_bic=self.bank_account.bic,
786+
)
787+
]
788+
payment_terms = PaymentTerms(due_date=self.due_date)
789+
790+
return EN16931Invoice(
791+
invoice_number=self.number,
792+
invoice_date=self.issue_date,
793+
currency_code=self.get_currency_display(),
794+
grand_total_amount=total_amount,
795+
tax_basis_total_amount=total_amount,
796+
tax_total_amounts=[tax_amount] if self.vat_rate else [],
797+
due_payable_amount=due_payable_amount,
798+
prepaid_amount=prepaid_amount,
799+
payment_reference=payment_reference,
800+
payment_means=payment_means,
801+
payment_terms=payment_terms,
802+
line_total_amount=total_amount,
803+
line_items=line_items,
804+
type_code=type_code,
805+
seller=TradeParty(
806+
name="Weblate s.r.o",
807+
address=PostalAddress(
808+
country_code="CZ",
809+
post_code="471 54",
810+
city="Cvikov",
811+
line_one="Nábřežní 694",
812+
),
813+
vat_id="CZ21668027",
814+
),
815+
buyer=TradeParty(
816+
name=self.customer.name,
817+
address=PostalAddress(
818+
country_code=self.customer.country.code,
819+
post_code=self.customer.postcode,
820+
city=self.customer.city,
821+
line_one=self.customer.address,
822+
line_two=self.customer.address_2 or None,
823+
),
824+
vat_id=self.customer.vat or None,
825+
),
826+
tax=[tax],
827+
)
828+
829+
def generate_en_16931_xml(self) -> None:
830+
invoice = self.get_en_16931_xml()
831+
xml_string = generate_xml(invoice)
832+
self.en_16931_xml_path.write_text(xml_string)
833+
682834
def generate_pdf(self) -> None:
683835
"""Render invoice as PDF."""
684836
# Create directory to store invoices
685837
settings.INVOICES_PATH.mkdir(exist_ok=True)
686-
render_pdf(
687-
html=self.render_html(),
688-
output=settings.INVOICES_PATH / self.filename,
689-
)
838+
with BytesIO() as buffer:
839+
render_pdf(html=self.render_html(), output=buffer)
840+
pdf_bytes = generate_from_binary(
841+
buffer.getvalue(), generate_xml(self.get_en_16931_xml())
842+
)
843+
# pdf_bytes = embed_invoice_in_pdf(buffer, self.get_en_16931_xml())
844+
pdf_file = settings.INVOICES_PATH / self.filename
845+
pdf_file.write_bytes(pdf_bytes)
690846

691847
def duplicate( # noqa: PLR0913
692848
self,

weblate_web/invoices/tests.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from __future__ import annotations
22

3+
import os
34
from decimal import Decimal
45
from pathlib import Path
56
from typing import cast
67

8+
import requests
79
from django.test.utils import override_settings
10+
from drafthorse.utils import validate_xml
811
from lxml import etree
912

1013
from weblate_web.models import Package, PackageCategory
@@ -112,6 +115,25 @@ def validate_invoice(self, invoice: Invoice) -> None:
112115
xml_doc = etree.parse(invoice.xml_path)
113116
S3_SCHEMA.assertValid(xml_doc)
114117

118+
einvoice = invoice.en_16931_xml_path.read_bytes()
119+
validate_xml(einvoice, "FACTUR-X_EN16931")
120+
121+
if validator_url := os.environ.get("VALIDATOR_URL"):
122+
# Validate standalone eInvoice
123+
response = requests.post(
124+
f"{validator_url}validate",
125+
files={"invoice": einvoice},
126+
timeout=20,
127+
)
128+
self.assertEqual(response.status_code, 200, response.text)
129+
# Validate eInvoice included in the PDF
130+
response = requests.post(
131+
f"{validator_url}validate",
132+
files={"invoice": invoice.path.read_bytes()},
133+
timeout=20,
134+
)
135+
self.assertEqual(response.status_code, 200, response.text)
136+
115137
def test_total(self) -> None:
116138
invoice = self.create_invoice(vat="CZ8003280318")
117139
self.assertEqual(invoice.total_amount, 100)

0 commit comments

Comments
 (0)