Skip to content

Commit 4d9555e

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 - We really need full validation to be part of the tests, needs to be investigated. - There are definitely issues with generated XML.
1 parent fa1bbba commit 4d9555e

File tree

5 files changed

+207
-2
lines changed

5 files changed

+207
-2
lines changed

.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@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.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: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ django-redis==6.0.0
1111
django-stubs-ext==5.2.8
1212
django-vies==6.2.2
1313
djangosaml2==1.11.1
14+
drafthorse==2025.2.0
1415
fiobank==4.0.0
1516
hiredis==3.3.0
1617
html2text==2025.4.15
@@ -20,6 +21,7 @@ mysqlclient==2.2.7
2021
paramiko==4.0.0
2122
Pillow==12.0.0
2223
psycopg[binary]==3.3.2
24+
PyCheval==0.3.0
2325
pyopenssl==25.3.0
2426
python-dateutil==2.9.0.post0
2527
pytz==2025.2

weblate_web/invoices/models.py

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@
4141
from django.utils.timezone import now
4242
from django.utils.translation import gettext, override
4343
from lxml import etree
44+
from pycheval import (
45+
BankAccount,
46+
EN16931Invoice,
47+
EN16931LineItem,
48+
Money,
49+
PaymentMeans,
50+
PaymentTerms,
51+
PostalAddress,
52+
Tax,
53+
TradeParty,
54+
generate_xml,
55+
)
56+
from pycheval.quantities import QuantityCode
57+
from pycheval.type_codes import DocumentTypeCode, PaymentMeansCode, TaxCategoryCode
58+
from weasyprint import Attachment
4459

4560
from weblate_web.exchange_rates import ExchangeRates
4661
from weblate_web.pdf import render_pdf
@@ -540,8 +555,14 @@ def xml_path(self) -> Path:
540555
"""XML path object."""
541556
return settings.INVOICES_PATH / self.get_filename("xml")
542557

558+
@property
559+
def en_16931_xml_path(self) -> Path:
560+
"""XML path object."""
561+
return settings.INVOICES_PATH / self.get_filename("einvoice.xml")
562+
543563
def generate_files(self) -> None:
544564
self.generate_money_s3_xml()
565+
self.generate_en_16931_xml()
545566
self.generate_pdf()
546567
self.sync_files()
547568

@@ -657,7 +678,7 @@ def add_amounts(root, in_czk: bool = False) -> None:
657678
add_element(adresa, "Ulice", self.customer.address)
658679
add_element(adresa, "Misto", self.customer.city)
659680
add_element(adresa, "PSC", self.customer.postcode)
660-
add_element(adresa, "Stat", self.customer.country)
681+
add_element(adresa, "Stat", self.customer.country.code)
661682
if self.customer.vat:
662683
add_element(prijemce, "PlatceDPH", "1")
663684
add_element(prijemce, "FyzOsoba", "0")
@@ -690,13 +711,151 @@ def generate_money_s3_xml(self) -> None:
690711
settings.INVOICES_PATH.mkdir(exist_ok=True)
691712
self.save_invoice_xml(document, self.xml_path)
692713

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

702861
def duplicate( # noqa: PLR0913

weblate_web/invoices/tests.py

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

33
from datetime import date, timedelta
4+
import os
45
from decimal import Decimal
56
from pathlib import Path
67
from typing import cast
78

9+
import requests
810
from django.test.utils import override_settings
11+
from drafthorse.utils import validate_xml
912
from lxml import etree
1013

1114
from weblate_web.models import Package, PackageCategory
@@ -121,6 +124,25 @@ def validate_invoice(self, invoice: Invoice) -> None:
121124
xml_doc = etree.parse(invoice.xml_path)
122125
S3_SCHEMA.assertValid(xml_doc)
123126

127+
einvoice = invoice.en_16931_xml_path.read_bytes()
128+
validate_xml(einvoice, "FACTUR-X_EN16931")
129+
130+
if validator_url := os.environ.get("VALIDATOR_URL"):
131+
# Validate standalone eInvoice
132+
response = requests.post(
133+
f"{validator_url}validate",
134+
files={"invoice": einvoice},
135+
timeout=20,
136+
)
137+
self.assertEqual(response.status_code, 200, response.text)
138+
# Validate eInvoice included in the PDF
139+
response = requests.post(
140+
f"{validator_url}validate",
141+
files={"invoice": invoice.path.read_bytes()},
142+
timeout=20,
143+
)
144+
self.assertEqual(response.status_code, 200, response.text)
145+
124146
def test_dates(self) -> None:
125147
invoice = self.create_invoice(vat="CZ8003280318")
126148
self.assertEqual(invoice.tax_date, invoice.issue_date)

weblate_web/pdf.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,16 @@
1919
from __future__ import annotations
2020

2121
from pathlib import Path
22+
from typing import TYPE_CHECKING
2223

2324
from django.conf import settings
2425
from django.contrib.staticfiles import finders
2526
from weasyprint import CSS, HTML
2627
from weasyprint.text.fonts import FontConfiguration
2728

29+
if TYPE_CHECKING:
30+
from weasyprint import Attachment
31+
2832
SIGNATURE_URL = "signature:"
2933
INVOICES_URL = "invoices:"
3034
LEGAL_URL = "legal:"
@@ -63,12 +67,19 @@ def url_fetcher(url: str) -> dict[str, str | bytes]:
6367
return result
6468

6569

66-
def render_pdf(*, html: str, output: Path) -> None:
70+
def render_pdf(
71+
*,
72+
html: str,
73+
output: Path,
74+
attachments: list[Attachment] | None = None,
75+
pdf_variant: str | None = None,
76+
) -> None:
6777
font_config = FontConfiguration()
6878

6979
renderer = HTML(
7080
string=html,
7181
url_fetcher=url_fetcher,
82+
pdf_variant=pdf_variant,
7283
)
7384
fonts_css = finders.find("pdf/fonts.css")
7485
if fonts_css is None:
@@ -78,6 +89,8 @@ def render_pdf(*, html: str, output: Path) -> None:
7889
font_config=font_config,
7990
url_fetcher=url_fetcher,
8091
)
92+
if attachments:
93+
renderer.metadata.attachments = attachments
8194
renderer.write_pdf(
8295
output,
8396
stylesheets=[font_style],

0 commit comments

Comments
 (0)