Skip to content

Commit 74e2c44

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 74e2c44

5 files changed

Lines changed: 209 additions & 2 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@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: 162 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,23 @@
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+
57+
# TODO: consider https://pypi.org/project/pyfactx/ instead of pycheval
58+
from pycheval.quantities import QuantityCode
59+
from pycheval.type_codes import DocumentTypeCode, PaymentMeansCode, TaxCategoryCode
60+
from weasyprint import Attachment
4461

4562
from weblate_web.exchange_rates import ExchangeRates
4663
from weblate_web.pdf import render_pdf
@@ -540,8 +557,14 @@ def xml_path(self) -> Path:
540557
"""XML path object."""
541558
return settings.INVOICES_PATH / self.get_filename("xml")
542559

560+
@property
561+
def en_16931_xml_path(self) -> Path:
562+
"""XML path object."""
563+
return settings.INVOICES_PATH / self.get_filename("einvoice.xml")
564+
543565
def generate_files(self) -> None:
544566
self.generate_money_s3_xml()
567+
self.generate_en_16931_xml()
545568
self.generate_pdf()
546569
self.sync_files()
547570

@@ -657,7 +680,7 @@ def add_amounts(root, in_czk: bool = False) -> None:
657680
add_element(adresa, "Ulice", self.customer.address)
658681
add_element(adresa, "Misto", self.customer.city)
659682
add_element(adresa, "PSC", self.customer.postcode)
660-
add_element(adresa, "Stat", self.customer.country)
683+
add_element(adresa, "Stat", self.customer.country.code)
661684
if self.customer.vat:
662685
add_element(prijemce, "PlatceDPH", "1")
663686
add_element(prijemce, "FyzOsoba", "0")
@@ -690,13 +713,151 @@ def generate_money_s3_xml(self) -> None:
690713
settings.INVOICES_PATH.mkdir(exist_ok=True)
691714
self.save_invoice_xml(document, self.xml_path)
692715

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

702863
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

3+
import os
34
from datetime import date, timedelta
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,7 +67,13 @@ 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(
@@ -78,8 +88,11 @@ def render_pdf(*, html: str, output: Path) -> None:
7888
font_config=font_config,
7989
url_fetcher=url_fetcher,
8090
)
91+
if attachments:
92+
renderer.metadata.attachments = attachments
8193
renderer.write_pdf(
8294
output,
8395
stylesheets=[font_style],
8496
font_config=font_config,
97+
pdf_variant=pdf_variant,
8598
)

0 commit comments

Comments
 (0)