invoice-examples 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- invoice_examples/__init__.py +3 -0
- invoice_examples/__main__.py +5 -0
- invoice_examples/cii.py +278 -0
- invoice_examples/cli.py +115 -0
- invoice_examples/pdf.py +23 -0
- invoice_examples/targets/__init__.py +5 -0
- invoice_examples/targets/fr.py +1072 -0
- invoice_examples-0.1.0.dist-info/METADATA +96 -0
- invoice_examples-0.1.0.dist-info/RECORD +12 -0
- invoice_examples-0.1.0.dist-info/WHEEL +4 -0
- invoice_examples-0.1.0.dist-info/entry_points.txt +2 -0
- invoice_examples-0.1.0.dist-info/licenses/LICENSE +21 -0
invoice_examples/cii.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Build a Factur-X EN 16931 (CII) invoice from a dict of settings.
|
|
2
|
+
|
|
3
|
+
Totals and VAT breakdowns are computed from the lines and allowances, so a
|
|
4
|
+
mutation that changes a price or a rate stays arithmetically consistent.
|
|
5
|
+
All identifiers are fictitious but pass their check digits (Luhn, IBAN, VAT key). The SIRENs start
|
|
6
|
+
with 0, a range with no company in the SIRENE directory (recherche-entreprises.api.gouv.fr, checked
|
|
7
|
+
2026-11-05). The IBAN has a real bank code (30004) and an all-zero branch and account.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections import OrderedDict
|
|
11
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
12
|
+
|
|
13
|
+
from lxml import etree
|
|
14
|
+
|
|
15
|
+
NS = {
|
|
16
|
+
"rsm": "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
|
|
17
|
+
"ram": "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
|
|
18
|
+
"qdt": "urn:un:unece:uncefact:data:standard:QualifiedDataType:100",
|
|
19
|
+
"udt": "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100",
|
|
20
|
+
}
|
|
21
|
+
CENT = Decimal("0.01")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def luhn_ok(digits):
|
|
25
|
+
total = 0
|
|
26
|
+
for i, d in enumerate(reversed(digits)):
|
|
27
|
+
n = int(d) * (2 if i % 2 else 1)
|
|
28
|
+
total += n - 9 if n > 9 else n
|
|
29
|
+
return total % 10 == 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def luhn_complete(prefix):
|
|
33
|
+
"""Append the digit that makes prefix pass the Luhn check."""
|
|
34
|
+
return next(prefix + str(d) for d in range(10) if luhn_ok(prefix + str(d)))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def vat_fr(siren):
|
|
38
|
+
return f"FR{(12 + 3 * (int(siren) % 97)) % 97:02d}{siren}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def iban_fr(bank, branch, account):
|
|
42
|
+
rib_key = 97 - (89 * int(bank) + 15 * int(branch) + 3 * int(account)) % 97
|
|
43
|
+
bban = f"{bank}{branch}{account}{rib_key:02d}"
|
|
44
|
+
check = 98 - int(bban + "152700") % 97 # "FR00" moved to the end, F=15 R=27
|
|
45
|
+
return f"FR{check:02d}{bban}", bban
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
SELLER_SIREN = luhn_complete("01234567")
|
|
49
|
+
SELLER_SIRET = luhn_complete(SELLER_SIREN + "0001")
|
|
50
|
+
BUYER_SIREN = luhn_complete("07654321")
|
|
51
|
+
BUYER_SIRET = luhn_complete(BUYER_SIREN + "0002")
|
|
52
|
+
IBAN, RIB = iban_fr("30004", "00000", "00000000000")
|
|
53
|
+
PAYEE_SIREN = luhn_complete("03456789") # a factoring company, for the payee (BG-10) variants
|
|
54
|
+
PAYEE_SIRET = luhn_complete(PAYEE_SIREN + "0001")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def gln(prefix12):
|
|
58
|
+
"""A GLN (scheme 0088) with its check digit. Prefix 2 is GS1's restricted circulation range: no company's number."""
|
|
59
|
+
total = sum(int(d) * (3 if i % 2 else 1) for i, d in enumerate(prefix12))
|
|
60
|
+
return prefix12 + str((10 - total % 10) % 10)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# The French baseline: passes EN 16931, the Factur-X EN 16931 profile and BR-FR (target "fr").
|
|
64
|
+
FRENCH = {
|
|
65
|
+
"profile": "urn:cen.eu:en16931:2017",
|
|
66
|
+
"billing_frame": "S1", # BT-23, BR-FR-08 list
|
|
67
|
+
"number": "F2026-0042", # BT-1
|
|
68
|
+
"type_code": "380", # BT-3
|
|
69
|
+
"issue_date": "20261020", # BT-2
|
|
70
|
+
"issue_date_format": "102",
|
|
71
|
+
"notes": [
|
|
72
|
+
("PMT", "Indemnité forfaitaire pour frais de recouvrement : 40 EUR."),
|
|
73
|
+
("PMD", "Pénalités de retard : trois fois le taux d'intérêt légal."),
|
|
74
|
+
("AAB", "Pas d'escompte pour paiement anticipé."),
|
|
75
|
+
],
|
|
76
|
+
"buyer_reference": "FACTURES_PUBLIQUES", # BT-10, Chorus Pro code service
|
|
77
|
+
"seller": {
|
|
78
|
+
"name": "Atelier Exemple SAS",
|
|
79
|
+
"global_id": (SELLER_SIRET, "0009"), # BT-29
|
|
80
|
+
"legal_id": (SELLER_SIREN, "0002"), # BT-30
|
|
81
|
+
"address": ("75011", "10 rue de l'Exemple", "Paris", "FR"),
|
|
82
|
+
"endpoint": (SELLER_SIREN, "0225"), # BT-34
|
|
83
|
+
"vat": vat_fr(SELLER_SIREN), # BT-31
|
|
84
|
+
},
|
|
85
|
+
"buyer": {
|
|
86
|
+
"name": "Commune d'Exemple",
|
|
87
|
+
"global_id": (BUYER_SIRET, "0009"), # BT-46
|
|
88
|
+
"legal_id": (BUYER_SIREN, "0002"), # BT-47
|
|
89
|
+
"address": ("69001", "1 place de la Mairie", "Lyon", "FR"),
|
|
90
|
+
"endpoint": (BUYER_SIREN, "0225"), # BT-49
|
|
91
|
+
"department": None, # Chorus Pro "nom du service" (OCA puts it here)
|
|
92
|
+
},
|
|
93
|
+
"invoicee": None, # Chorus Pro "valideur" (InvoiceeTradeParty)
|
|
94
|
+
"order_reference": "1234567890", # BT-13, Chorus Pro numéro d'engagement
|
|
95
|
+
"delivery_date": "20261015",
|
|
96
|
+
"currency": "EUR", # BT-5
|
|
97
|
+
"tax_currency": None, # BT-6
|
|
98
|
+
"payment_code": "30", # BT-81
|
|
99
|
+
"iban": IBAN, # BT-84
|
|
100
|
+
"proprietary_account": None, # BT-84 when not an IBAN
|
|
101
|
+
"bic": "BNPAFRPPXXX", # BT-86
|
|
102
|
+
"due_date": "20261119",
|
|
103
|
+
"due_date_type": "5", # BT-8
|
|
104
|
+
"tax_type": "VAT",
|
|
105
|
+
"lines": [
|
|
106
|
+
# name, quantity, unit price, VAT category, VAT rate[, line allowance amount (BT-136)]
|
|
107
|
+
("Atelier de formation", "2", "450.00", "S", "20"),
|
|
108
|
+
("Support de cours", "10", "12.50", "S", "20"),
|
|
109
|
+
],
|
|
110
|
+
"allowances": [], # (amount, reason code, reason, category, rate)
|
|
111
|
+
"charges": [], # same shape, document level charges (BG-21)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def amt(value):
|
|
116
|
+
return f"{Decimal(value).quantize(CENT, ROUND_HALF_UP)}"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def el(parent, tag, text=None, **attrs):
|
|
120
|
+
prefix, name = tag.split(":")
|
|
121
|
+
node = etree.SubElement(parent, f"{{{NS[prefix]}}}{name}", {k.replace("_", ""): v for k, v in attrs.items()})
|
|
122
|
+
if text is not None:
|
|
123
|
+
node.text = str(text)
|
|
124
|
+
return node
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def date(parent, tag, value, fmt="102", ns="udt"):
|
|
128
|
+
el(el(parent, tag), f"{ns}:DateTimeString", value, format=fmt)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def party(parent, tag, p):
|
|
132
|
+
node = el(parent, tag)
|
|
133
|
+
if p.get("global_id"):
|
|
134
|
+
el(node, "ram:GlobalID", p["global_id"][0], schemeID=p["global_id"][1])
|
|
135
|
+
el(node, "ram:Name", p["name"])
|
|
136
|
+
if p.get("legal_id"):
|
|
137
|
+
el(el(node, "ram:SpecifiedLegalOrganization"), "ram:ID", p["legal_id"][0], schemeID=p["legal_id"][1])
|
|
138
|
+
if p.get("department"):
|
|
139
|
+
el(el(node, "ram:DefinedTradeContact"), "ram:DepartmentName", p["department"])
|
|
140
|
+
addr = el(node, "ram:PostalTradeAddress")
|
|
141
|
+
postcode, line, city, country = p["address"]
|
|
142
|
+
el(addr, "ram:PostcodeCode", postcode)
|
|
143
|
+
el(addr, "ram:LineOne", line)
|
|
144
|
+
el(addr, "ram:CityName", city)
|
|
145
|
+
el(addr, "ram:CountryID", country)
|
|
146
|
+
if p.get("endpoint"):
|
|
147
|
+
el(el(node, "ram:URIUniversalCommunication"), "ram:URIID", p["endpoint"][0], schemeID=p["endpoint"][1])
|
|
148
|
+
if p.get("vat"):
|
|
149
|
+
el(el(node, "ram:SpecifiedTaxRegistration"), "ram:ID", p["vat"], schemeID="VA")
|
|
150
|
+
return node
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def build(c):
|
|
154
|
+
"""Return the invoice as an lxml element tree root."""
|
|
155
|
+
root = etree.Element(f"{{{NS['rsm']}}}CrossIndustryInvoice", nsmap=NS)
|
|
156
|
+
ctx = el(root, "rsm:ExchangedDocumentContext")
|
|
157
|
+
if c["billing_frame"] is not None:
|
|
158
|
+
el(el(ctx, "ram:BusinessProcessSpecifiedDocumentContextParameter"), "ram:ID", c["billing_frame"])
|
|
159
|
+
el(el(ctx, "ram:GuidelineSpecifiedDocumentContextParameter"), "ram:ID", c["profile"])
|
|
160
|
+
|
|
161
|
+
doc = el(root, "rsm:ExchangedDocument")
|
|
162
|
+
el(doc, "ram:ID", c["number"])
|
|
163
|
+
el(doc, "ram:TypeCode", c["type_code"])
|
|
164
|
+
date(doc, "ram:IssueDateTime", c["issue_date"], c["issue_date_format"])
|
|
165
|
+
for subject, content in c["notes"]:
|
|
166
|
+
note = el(doc, "ram:IncludedNote")
|
|
167
|
+
el(note, "ram:Content", content)
|
|
168
|
+
el(note, "ram:SubjectCode", subject)
|
|
169
|
+
|
|
170
|
+
tx = el(root, "rsm:SupplyChainTradeTransaction")
|
|
171
|
+
groups = OrderedDict() # (category, rate) -> basis
|
|
172
|
+
line_total = Decimal(0)
|
|
173
|
+
for i, (name, qty, price, cat, rate, *discount) in enumerate(c["lines"], 1):
|
|
174
|
+
net = (Decimal(qty) * Decimal(price)).quantize(CENT, ROUND_HALF_UP) - sum(Decimal(d) for d in discount)
|
|
175
|
+
line_total += net
|
|
176
|
+
groups[(cat, rate)] = groups.get((cat, rate), Decimal(0)) + net
|
|
177
|
+
item = el(tx, "ram:IncludedSupplyChainTradeLineItem")
|
|
178
|
+
el(el(item, "ram:AssociatedDocumentLineDocument"), "ram:LineID", i)
|
|
179
|
+
el(el(item, "ram:SpecifiedTradeProduct"), "ram:Name", name)
|
|
180
|
+
el(el(el(item, "ram:SpecifiedLineTradeAgreement"), "ram:NetPriceProductTradePrice"), "ram:ChargeAmount", price)
|
|
181
|
+
el(el(item, "ram:SpecifiedLineTradeDelivery"), "ram:BilledQuantity", qty, unitCode="C62")
|
|
182
|
+
settle = el(item, "ram:SpecifiedLineTradeSettlement")
|
|
183
|
+
tax = el(settle, "ram:ApplicableTradeTax")
|
|
184
|
+
el(tax, "ram:TypeCode", c["tax_type"])
|
|
185
|
+
el(tax, "ram:CategoryCode", cat)
|
|
186
|
+
el(tax, "ram:RateApplicablePercent", rate)
|
|
187
|
+
for d in discount:
|
|
188
|
+
ac = el(settle, "ram:SpecifiedTradeAllowanceCharge")
|
|
189
|
+
el(el(ac, "ram:ChargeIndicator"), "udt:Indicator", "false")
|
|
190
|
+
el(ac, "ram:ActualAmount", amt(d))
|
|
191
|
+
el(ac, "ram:ReasonCode", "95")
|
|
192
|
+
el(ac, "ram:Reason", "Remise")
|
|
193
|
+
el(el(settle, "ram:SpecifiedTradeSettlementLineMonetarySummation"), "ram:LineTotalAmount", amt(net))
|
|
194
|
+
|
|
195
|
+
agree = el(tx, "ram:ApplicableHeaderTradeAgreement")
|
|
196
|
+
if c["buyer_reference"] is not None:
|
|
197
|
+
el(agree, "ram:BuyerReference", c["buyer_reference"])
|
|
198
|
+
party(agree, "ram:SellerTradeParty", c["seller"])
|
|
199
|
+
party(agree, "ram:BuyerTradeParty", c["buyer"])
|
|
200
|
+
if c["order_reference"] is not None:
|
|
201
|
+
el(el(agree, "ram:BuyerOrderReferencedDocument"), "ram:IssuerAssignedID", c["order_reference"])
|
|
202
|
+
|
|
203
|
+
delivery = el(tx, "ram:ApplicableHeaderTradeDelivery")
|
|
204
|
+
event = el(delivery, "ram:ActualDeliverySupplyChainEvent")
|
|
205
|
+
date(event, "ram:OccurrenceDateTime", c["delivery_date"])
|
|
206
|
+
|
|
207
|
+
settle = el(tx, "ram:ApplicableHeaderTradeSettlement")
|
|
208
|
+
if c["tax_currency"]:
|
|
209
|
+
el(settle, "ram:TaxCurrencyCode", c["tax_currency"][0])
|
|
210
|
+
el(settle, "ram:InvoiceCurrencyCode", c["currency"])
|
|
211
|
+
if c["invoicee"]:
|
|
212
|
+
party(settle, "ram:InvoiceeTradeParty", c["invoicee"])
|
|
213
|
+
means = el(settle, "ram:SpecifiedTradeSettlementPaymentMeans")
|
|
214
|
+
el(means, "ram:TypeCode", c["payment_code"])
|
|
215
|
+
if c["iban"] or c["proprietary_account"]:
|
|
216
|
+
account = el(means, "ram:PayeePartyCreditorFinancialAccount")
|
|
217
|
+
if c["iban"]:
|
|
218
|
+
el(account, "ram:IBANID", c["iban"])
|
|
219
|
+
if c["proprietary_account"]:
|
|
220
|
+
el(account, "ram:ProprietaryID", c["proprietary_account"])
|
|
221
|
+
if c["bic"]:
|
|
222
|
+
el(el(means, "ram:PayeeSpecifiedCreditorFinancialInstitution"), "ram:BICID", c["bic"])
|
|
223
|
+
|
|
224
|
+
allowance_total = sum((Decimal(a[0]) for a in c["allowances"]), Decimal(0))
|
|
225
|
+
charge_total = sum((Decimal(a[0]) for a in c["charges"]), Decimal(0))
|
|
226
|
+
for sign, items in ((-1, c["allowances"]), (1, c["charges"])):
|
|
227
|
+
for amount, _code, _reason, cat, rate in items:
|
|
228
|
+
groups[(cat, rate)] = groups.get((cat, rate), Decimal(0)) + sign * Decimal(amount)
|
|
229
|
+
tax_total = Decimal(0)
|
|
230
|
+
for (cat, rate), basis in groups.items():
|
|
231
|
+
vat = (basis * Decimal(rate) / 100).quantize(CENT, ROUND_HALF_UP)
|
|
232
|
+
tax_total += vat
|
|
233
|
+
tax = el(settle, "ram:ApplicableTradeTax")
|
|
234
|
+
el(tax, "ram:CalculatedAmount", amt(vat))
|
|
235
|
+
el(tax, "ram:TypeCode", c["tax_type"])
|
|
236
|
+
if cat in ("E", "AE", "K", "G", "O"):
|
|
237
|
+
el(tax, "ram:ExemptionReason", "Exonération de TVA")
|
|
238
|
+
el(tax, "ram:BasisAmount", amt(basis))
|
|
239
|
+
el(tax, "ram:CategoryCode", cat)
|
|
240
|
+
if c["due_date_type"]:
|
|
241
|
+
el(tax, "ram:DueDateTypeCode", c["due_date_type"])
|
|
242
|
+
el(tax, "ram:RateApplicablePercent", rate)
|
|
243
|
+
for indicator, amount, code, reason, cat, rate in [("false", *a) for a in c["allowances"]] + [
|
|
244
|
+
("true", *a) for a in c["charges"]
|
|
245
|
+
]:
|
|
246
|
+
ac = el(settle, "ram:SpecifiedTradeAllowanceCharge")
|
|
247
|
+
el(el(ac, "ram:ChargeIndicator"), "udt:Indicator", indicator)
|
|
248
|
+
el(ac, "ram:ActualAmount", amt(amount))
|
|
249
|
+
el(ac, "ram:ReasonCode", code)
|
|
250
|
+
el(ac, "ram:Reason", reason)
|
|
251
|
+
tax = el(ac, "ram:CategoryTradeTax")
|
|
252
|
+
el(tax, "ram:TypeCode", c["tax_type"])
|
|
253
|
+
el(tax, "ram:CategoryCode", cat)
|
|
254
|
+
el(tax, "ram:RateApplicablePercent", rate)
|
|
255
|
+
terms = el(settle, "ram:SpecifiedTradePaymentTerms")
|
|
256
|
+
el(terms, "ram:Description", "Paiement à 30 jours par virement.")
|
|
257
|
+
date(terms, "ram:DueDateDateTime", c["due_date"])
|
|
258
|
+
|
|
259
|
+
basis_total = line_total + charge_total - allowance_total
|
|
260
|
+
grand = basis_total + tax_total
|
|
261
|
+
sums = el(settle, "ram:SpecifiedTradeSettlementHeaderMonetarySummation")
|
|
262
|
+
el(sums, "ram:LineTotalAmount", amt(line_total))
|
|
263
|
+
if c["charges"]:
|
|
264
|
+
el(sums, "ram:ChargeTotalAmount", amt(charge_total))
|
|
265
|
+
if c["allowances"]:
|
|
266
|
+
el(sums, "ram:AllowanceTotalAmount", amt(allowance_total))
|
|
267
|
+
el(sums, "ram:TaxBasisTotalAmount", amt(basis_total))
|
|
268
|
+
el(sums, "ram:TaxTotalAmount", amt(tax_total), currencyID=c["currency"])
|
|
269
|
+
if c["tax_currency"]:
|
|
270
|
+
code, factor = c["tax_currency"]
|
|
271
|
+
el(sums, "ram:TaxTotalAmount", amt(tax_total * Decimal(factor)), currencyID=code)
|
|
272
|
+
el(sums, "ram:GrandTotalAmount", amt(grand))
|
|
273
|
+
el(sums, "ram:DuePayableAmount", amt(grand))
|
|
274
|
+
return root
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def to_bytes(root):
|
|
278
|
+
return etree.tostring(root, xml_declaration=True, encoding="UTF-8", pretty_print=True)
|
invoice_examples/cli.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Command line: invoice-examples list | generate.
|
|
2
|
+
|
|
3
|
+
invoice-examples list --target fr
|
|
4
|
+
invoice-examples generate --target fr --out examples/ # the valid invoice and every invalid variant
|
|
5
|
+
invoice-examples generate --target fr --rule BR-FR-10 --out . # one variant, plus the valid invoice
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from . import __version__, cii, pdf
|
|
14
|
+
from .targets import TARGETS
|
|
15
|
+
|
|
16
|
+
FORMATS = ("xml", "pdf")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _write(path, data):
|
|
20
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
path.write_bytes(data)
|
|
22
|
+
return path
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _files(out, stem, xml, formats):
|
|
26
|
+
written = {}
|
|
27
|
+
if "xml" in formats:
|
|
28
|
+
written["xml"] = _write(out / f"{stem}.xml", xml).relative_to(out).as_posix()
|
|
29
|
+
if "pdf" in formats:
|
|
30
|
+
written["pdf"] = _write(out / f"{stem}.pdf", pdf.facturx_pdf(xml)).relative_to(out).as_posix()
|
|
31
|
+
return written
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def cmd_list(args, out):
|
|
35
|
+
target = TARGETS[args.target]
|
|
36
|
+
print(f"Target {args.target}: rules {', '.join(f'{k} {v}' for k, v in target.RULES.items())}", file=out)
|
|
37
|
+
print(f" {'valid':<14} the baseline invoice, which passes every rule", file=out)
|
|
38
|
+
for v in target.VARIANTS:
|
|
39
|
+
print(f" {v.id:<14} fails {', '.join(v.fires)}: {v.en}", file=out)
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cmd_generate(args, out):
|
|
44
|
+
target = TARGETS[args.target]
|
|
45
|
+
variants = target.VARIANTS
|
|
46
|
+
if args.rule:
|
|
47
|
+
wanted = {r.strip() for r in args.rule.split(",")}
|
|
48
|
+
variants = [v for v in variants if v.id in wanted or v.rule in wanted]
|
|
49
|
+
unknown = wanted - {v.id for v in variants} - {v.rule for v in variants}
|
|
50
|
+
if unknown:
|
|
51
|
+
print(
|
|
52
|
+
f"invoice-examples: no variant for {', '.join(sorted(unknown))} in target {args.target} "
|
|
53
|
+
f"(see: invoice-examples list --target {args.target})",
|
|
54
|
+
file=sys.stderr,
|
|
55
|
+
)
|
|
56
|
+
return 2
|
|
57
|
+
formats = [f.strip() for f in args.format.split(",")]
|
|
58
|
+
root = Path(args.out) / args.target
|
|
59
|
+
entries = [
|
|
60
|
+
{
|
|
61
|
+
"id": "valid",
|
|
62
|
+
"status": "valid",
|
|
63
|
+
"fires": [],
|
|
64
|
+
"files": _files(root, "valid", cii.to_bytes(target.build()), formats),
|
|
65
|
+
"description": {"en": "Passes every rule listed.", "fr": "Passe toutes les règles listées."},
|
|
66
|
+
}
|
|
67
|
+
]
|
|
68
|
+
for v in variants:
|
|
69
|
+
entries.append(
|
|
70
|
+
{
|
|
71
|
+
"id": v.id,
|
|
72
|
+
"status": "invalid",
|
|
73
|
+
"rule": v.rule,
|
|
74
|
+
"fires": list(v.fires),
|
|
75
|
+
"files": _files(root, f"invalid/{v.id}", cii.to_bytes(target.build(v)), formats),
|
|
76
|
+
"description": {"en": v.en, "fr": v.fr},
|
|
77
|
+
}
|
|
78
|
+
)
|
|
79
|
+
manifest = {
|
|
80
|
+
"generator": f"invoice-examples {__version__}",
|
|
81
|
+
"target": args.target,
|
|
82
|
+
"syntax": "CII",
|
|
83
|
+
"profile": "Factur-X EN 16931",
|
|
84
|
+
"rules": target.RULES,
|
|
85
|
+
"licence": "CC0-1.0",
|
|
86
|
+
"examples": entries,
|
|
87
|
+
}
|
|
88
|
+
_write(root / "manifest.json", (json.dumps(manifest, indent=2, ensure_ascii=False) + "\n").encode("utf-8"))
|
|
89
|
+
print(f"wrote {len(entries)} examples ({', '.join(formats)}) and manifest.json in {root}", file=out)
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parser():
|
|
94
|
+
p = argparse.ArgumentParser(
|
|
95
|
+
prog="invoice-examples", description="Valid and invalid e-invoice examples, one per rule."
|
|
96
|
+
)
|
|
97
|
+
p.add_argument("--version", action="version", version=f"invoice-examples {__version__}")
|
|
98
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
99
|
+
ls = sub.add_parser("list", help="list the examples of a target")
|
|
100
|
+
ls.add_argument("--target", choices=sorted(TARGETS), default="fr")
|
|
101
|
+
ls.set_defaults(func=cmd_list)
|
|
102
|
+
gen = sub.add_parser("generate", help="write the valid example and the invalid variants")
|
|
103
|
+
gen.add_argument("--target", choices=sorted(TARGETS), default="fr")
|
|
104
|
+
gen.add_argument(
|
|
105
|
+
"--rule", help="only these variants (ids or rules, comma-separated); the valid example is always written"
|
|
106
|
+
)
|
|
107
|
+
gen.add_argument("--format", default="xml,pdf", help="xml, pdf or both (default: xml,pdf)")
|
|
108
|
+
gen.add_argument("--out", default="examples", help="output folder (default: examples); files go in <out>/<target>/")
|
|
109
|
+
gen.set_defaults(func=cmd_generate)
|
|
110
|
+
return p
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(argv=None, out=None):
|
|
114
|
+
args = parser().parse_args(argv)
|
|
115
|
+
return args.func(args, out or sys.stdout)
|
invoice_examples/pdf.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Wrap a CII invoice in a PDF, as Factur-X does: one page, the XML attached as factur-x.xml.
|
|
2
|
+
|
|
3
|
+
The PDF is deterministic (no dates, a fixed file identifier) so that regenerated examples do not change.
|
|
4
|
+
It is not PDF/A-3: these examples are for testing XML extraction and the XML rules, not PDF/A-3 validation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import io
|
|
8
|
+
|
|
9
|
+
from pypdf import PdfWriter
|
|
10
|
+
from pypdf.generic import ArrayObject, ByteStringObject
|
|
11
|
+
|
|
12
|
+
FILE_ID = ByteStringObject(b"invoice-examples")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def facturx_pdf(xml_bytes, name="factur-x.xml"):
|
|
16
|
+
writer = PdfWriter()
|
|
17
|
+
writer.add_blank_page(width=595, height=842) # A4
|
|
18
|
+
writer.add_attachment(name, xml_bytes)
|
|
19
|
+
writer._info = None # no /Producer, no dates
|
|
20
|
+
writer._ID = ArrayObject([FILE_ID, FILE_ID])
|
|
21
|
+
buf = io.BytesIO()
|
|
22
|
+
writer.write(buf)
|
|
23
|
+
return buf.getvalue()
|