facturlint 0.2.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.
@@ -0,0 +1,255 @@
1
+ Metadata-Version: 2.4
2
+ Name: facturlint
3
+ Version: 0.2.0
4
+ Summary: Official Python SDK & CLI for FacturLint — Factur-X 1.09.2, EN 16931 & BR-FR-CTC validation, PDF/A-3b envelope repair & audit API.
5
+ Author-email: FacturLint <contact@facturlint.com>
6
+ Maintainer-email: FacturLint <contact@facturlint.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://facturlint.com
9
+ Project-URL: Documentation, https://facturlint.com/docs
10
+ Project-URL: Error Catalog, https://facturlint.com/erreurs
11
+ Project-URL: Pricing & API Keys, https://facturlint.com/#tarifs
12
+ Project-URL: MCP Server, https://facturlint.com/mcp
13
+ Project-URL: Repository, https://github.com/facturlint/facturlint-python
14
+ Project-URL: Bug Tracker, https://github.com/facturlint/facturlint-python/issues
15
+ Keywords: factur-x,en16931,br-fr-ctc,chorus-pro,facturation-electronique,pdfa3,pdfa3b,einvoicing,xml-cii,peppol,mcp,ai-agent,stateless-api
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Financial and Insurance Industry
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Topic :: Software Development :: Quality Assurance
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.9
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Dynamic: license-file
34
+
35
+ # FacturLint — Factur-X 1.09.2, EN 16931 & BR-FR-CTC Python SDK & CLI
36
+
37
+ [![PyPI version](https://img.shields.io/pypi/v/facturlint.svg)](https://pypi.org/project/facturlint/)
38
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://pypi.org/project/facturlint/)
39
+ [![Stateless](https://img.shields.io/badge/privacy-100%25%20stateless-green.svg)](https://facturlint.com)
40
+ [![Factur-X](https://img.shields.io/badge/norm-Factur--X%201.09.2-orange.svg)](https://facturlint.com/docs)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
42
+
43
+ **FacturLint** est le SDK Python officiel et l'outil CLI pour valider, certifier et réparer automatiquement les factures électroniques **Factur-X 1.09.2**, **EN 16931** et **BR-FR-CTC** (Réforme française 2026 de la facturation électronique, Chorus Pro et Plateformes Agréées / PDP).
44
+
45
+ Conçu sans aucune dépendance tierce (*Pure Python Standard Library*), FacturLint s'intègre en 2 minutes dans vos pipelines CI/CD, ERP, logiciels de facturation, outils comptables et agents IA via le [Serveur MCP FacturLint](https://facturlint.com/mcp).
46
+
47
+ - 🌐 Site officiel : [https://facturlint.com](https://facturlint.com)
48
+ - 📚 Documentation API : [https://facturlint.com/docs](https://facturlint.com/docs)
49
+ - 🔍 Catalogue des 110+ règles d'erreurs : [https://facturlint.com/erreurs](https://facturlint.com/erreurs)
50
+ - 🤖 Serveur MCP & Agent IA : [https://facturlint.com/mcp](https://facturlint.com/mcp)
51
+ - 💳 Tarifs & Clés API : [https://facturlint.com/#tarifs](https://facturlint.com/#tarifs)
52
+
53
+ ---
54
+
55
+ ## ⚡ Points forts
56
+
57
+ - **100 % Déterministe & Stateless** : Aucune facture ni donnée fiscale n'est stockée en base de données (zéro rétention, conformité RGPD absolue).
58
+ - **Zéro dépendance d'exécution** : Fonctionne avec Python 3.9+ standard (`urllib`, `json`, `pathlib`). Aucun binaire C lourd à installer.
59
+ - **Validation multicouche complète** :
60
+ - Enveloppe physique PDF/A-3b (ISO 19005-3)
61
+ - Métadonnées XMP Factur-X (`fx:ConformanceLevel`, `fx:DocumentFileName`, `fx:Version`)
62
+ - Profil colorimétrique ICC sRGB (`OutputIntent`)
63
+ - Schémas XML W3C XSD officiels UN/CEFACT CII D16B
64
+ - Schematron européen CEN/TC 434 (Norme EN 16931-1)
65
+ - Règles spécifiques françaises BR-FR-CTC (DGFIP / AIFE)
66
+ - Audit d'intégrité arithmétique (HT + TVA = TTC)
67
+ - **Auto-réparation chirurgicale d'enveloppe** : Corrige les défauts techniques d'enveloppe PDF/A-3b en garantissant zéro altération des montants ni des mentions comptables.
68
+ - **Audit groupé par lot .ZIP** : Traitement en RAM avec rapport Excel CSV structuré pour les cabinets d'expertise comptable.
69
+
70
+ ---
71
+
72
+ ## 📦 Installation
73
+
74
+ ```bash
75
+ pip install facturlint
76
+ ```
77
+
78
+ Aucun paquet tiers n'est requis. Fonctionne instantanément sous Linux, Windows et macOS.
79
+
80
+ ---
81
+
82
+ ## 🚀 Utilisation en Ligne de Commande (CLI)
83
+
84
+ Une fois installé, le binaire `facturlint` est disponible dans votre terminal :
85
+
86
+ ### 1. Valider une facture (Gratuit & Stateless)
87
+
88
+ ```bash
89
+ facturlint validate facture.pdf
90
+ ```
91
+
92
+ Pour les pipelines CI/CD (ex: GitHub Actions), activez l'échec strict sur simple avertissement :
93
+ ```bash
94
+ facturlint validate facture.pdf --fail-on-warning
95
+ ```
96
+
97
+ Export au format JSON pour script shell :
98
+ ```bash
99
+ facturlint validate facture.pdf --json
100
+ ```
101
+
102
+ ### 2. Auto-réparer l'enveloppe technique PDF/A-3b
103
+
104
+ Répare le profil ICC sRGB manquant, l'en-tête XMP Factur-X ou le dictionnaire AFRelationship sans toucher au corps de la facture :
105
+
106
+ ```bash
107
+ facturlint repair facture_rejetee.pdf -o facture_conforme.pdf
108
+ ```
109
+
110
+ ### 3. Générer l'attestation officielle d'audit PDF
111
+
112
+ Produit une attestation infalsifiable avec empreinte SHA-256 certifiant la conformité au moment du contrôle :
113
+
114
+ ```bash
115
+ facturlint cert facture.pdf -o attestation_audit.pdf
116
+ ```
117
+
118
+ ### 4. Traiter un lot complet de factures (.ZIP)
119
+
120
+ Idéal pour les experts-comptables et DAF traitant des centaines de factures mensuelles :
121
+
122
+ ```bash
123
+ facturlint batch factures_mois.zip --csv rapport_excel.csv --out-zip factures_reparees.zip
124
+ ```
125
+
126
+ ### 5. Consulter le quota de votre clé API
127
+
128
+ ```bash
129
+ export FACTURLINT_API_KEY="fl_live_votre_cle_ici"
130
+ facturlint quota
131
+ ```
132
+
133
+ ### 6. Consulter le catalogue des 110+ règles normatives
134
+
135
+ ```bash
136
+ facturlint rules --category schematron_br_fr
137
+ ```
138
+
139
+ Chaque anomalie renvoie vers une fiche détaillée sur [https://facturlint.com/erreurs/{code}](https://facturlint.com/erreurs).
140
+
141
+ ---
142
+
143
+ ## 💻 Utilisation comme SDK Python
144
+
145
+ ### Validation simple (sans clé API)
146
+
147
+ ```python
148
+ from facturlint_sdk import FacturLintClient
149
+
150
+ client = FacturLintClient()
151
+
152
+ # Audit d'une facture Factur-X (PDF ou XML CII)
153
+ report = client.validate("facture.pdf")
154
+
155
+ if report["valid"]:
156
+ print(f"Facture conforme ! Profil : {report['container']['detected_profile']}")
157
+ print(f"Total TTC : {report['invoice_summary']['grand_total']} EUR")
158
+ else:
159
+ print(f"Statut : {report['status']}")
160
+ for issue in report["issues"]:
161
+ print(f"[{issue['severity'].upper()}] {issue['code']} : {issue['message']}")
162
+ print(f"👉 Guide résolution : https://facturlint.com/erreurs/{issue['code']}")
163
+ ```
164
+
165
+ ### Auto-réparation PDF/A-3b & Export
166
+
167
+ ```python
168
+ from facturlint_sdk import FacturLintClient
169
+
170
+ client = FacturLintClient(api_key="fl_live_votre_cle")
171
+
172
+ # Répare l'enveloppe et écrit directement le fichier PDF conforme
173
+ result = client.repair("facture_defectueuse.pdf", output_path="facture_reparee.pdf")
174
+
175
+ if result["repaired"]:
176
+ print("Enveloppe PDF/A-3b réparée avec succès !")
177
+ for action in result["actions_applied"]:
178
+ print(f" - {action}")
179
+ ```
180
+
181
+ ### Audit groupé par lot .ZIP (Pour cabinets comptables)
182
+
183
+ ```python
184
+ from facturlint_sdk import FacturLintClient
185
+
186
+ client = FacturLintClient(api_key="fl_live_votre_cle")
187
+
188
+ batch_res = client.batch_zip(
189
+ "lot_novembre.zip",
190
+ output_csv_path="rapport_audit.csv",
191
+ output_zip_path="lot_novembre_repare.zip",
192
+ )
193
+
194
+ summary = batch_res["summary"]
195
+ print(f"Total analysé : {summary['total_files']}")
196
+ print(f"Conformes d'origine : {summary['compliant_initial']}")
197
+ print(f"Auto-réparées : {summary['auto_repaired']}")
198
+ print(f"Rejets métier : {summary['rejected_business']}")
199
+ ```
200
+
201
+ ### Génération d'attestation PDF certifiée
202
+
203
+ ```python
204
+ from facturlint_sdk import FacturLintClient
205
+
206
+ client = FacturLintClient()
207
+ pdf_bytes = client.certificate("facture.pdf", output_path="attestation.pdf")
208
+ print(f"Attestation générée ({len(pdf_bytes)} octets).")
209
+ ```
210
+
211
+ ---
212
+
213
+ ## 🤖 Intégration Agents IA & MCP (Model Context Protocol)
214
+
215
+ FacturLint expose un serveur **Model Context Protocol** natif pour Claude Desktop, Cursor, Copilot, LangChain et AutoGen.
216
+
217
+ Configurez votre client MCP en ajoutant simplement :
218
+
219
+ ```json
220
+ {
221
+ "mcpServers": {
222
+ "facturlint": {
223
+ "url": "https://facturlint.com/mcp",
224
+ "headers": {
225
+ "X-API-Key": "fl_live_votre_cle_optionnelle"
226
+ }
227
+ }
228
+ }
229
+ }
230
+ ```
231
+
232
+ Documentation complète MCP : [https://facturlint.com/mcp](https://facturlint.com/mcp) et [Agent Card](https://facturlint.com/.well-known/agent-card.json).
233
+
234
+ ---
235
+
236
+ ## 🛠️ Matrice des Profils Factur-X Supportés
237
+
238
+ | Profil Factur-X | Description | Usage typique |
239
+ | :--- | :--- | :--- |
240
+ | **MINIMUM** | Données d'en-tête et pied de facture | Facturation B2C / Archivage |
241
+ | **BASIC WL** | Données d'en-tête sans détail de lignes | Pré-comptabilité |
242
+ | **BASIC** | Facture avec détail de lignes standard | Facturation B2B courante |
243
+ | **EN 16931** | Norme européenne complète | Marchés publics, Chorus Pro, B2B FR |
244
+ | **EXTENDED** | Données sectorielles enrichies (BTP, négoce) | Facturation complexe |
245
+
246
+ FacturLint vérifie également les extensions françaises **BR-FR-CTC** requises par la réforme 2026 (numéros de SIRET, catégories d'opérations, options de TVA).
247
+
248
+ ---
249
+
250
+ ## 📄 Licence & Mentions
251
+
252
+ Distribué sous licence **MIT**.
253
+ Édité par **FacturLint** — [https://facturlint.com](https://facturlint.com).
254
+ Support & Contact : `contact@facturlint.com`.
255
+ Consultez notre [documentation technique](https://facturlint.com/docs) et notre [catalogue de règles](https://facturlint.com/erreurs).
@@ -0,0 +1,10 @@
1
+ facturlint-0.2.0.dist-info/licenses/LICENSE,sha256=wafiG4cPWlfAeh-XscNDm7yzg2QO4V6jYuMUyaW9tqc,1092
2
+ facturlint_sdk/__init__.py,sha256=PuQp47aiBC3-A-W--05XeevcViwHs_QWQj4C3Ts9y5U,520
3
+ facturlint_sdk/cli.py,sha256=z9CKiMvDBUU8IIJy3T7E4A2aeJBTiRozlNSDUNfzMAc,13672
4
+ facturlint_sdk/client.py,sha256=lVBx8knkJIOXnCTewlZm3Uvvik1VCIj-A96K34niOPI,16060
5
+ facturlint_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ facturlint-0.2.0.dist-info/METADATA,sha256=sVWdrDLP1YjD90wL4BKvpRaid147QbLCFADRvjQIwgw,10106
7
+ facturlint-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ facturlint-0.2.0.dist-info/entry_points.txt,sha256=Bempm-Zhl8_WbPAc9X_KyTWFCJZXKvG4L8uynClf96Y,55
9
+ facturlint-0.2.0.dist-info/top_level.txt,sha256=V9zV1EwqMDUo6sAvUxMAD3aKVv2z-DYwrojPxrxKbso,15
10
+ facturlint-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ facturlint = facturlint_sdk.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FacturLint (https://facturlint.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ facturlint_sdk
@@ -0,0 +1,21 @@
1
+ """FacturLint Python SDK — Zero-dependency client & CLI for Factur-X 1.09.2 & BR-FR-CTC compliance."""
2
+
3
+ from facturlint_sdk.client import (
4
+ FacturLintAPIError,
5
+ FacturLintAuthError,
6
+ FacturLintClient,
7
+ FacturLintError,
8
+ FacturLintPaymentRequiredError,
9
+ FacturLintQuotaError,
10
+ )
11
+
12
+ __version__ = "0.2.0"
13
+ __all__ = [
14
+ "FacturLintClient",
15
+ "FacturLintError",
16
+ "FacturLintAPIError",
17
+ "FacturLintAuthError",
18
+ "FacturLintPaymentRequiredError",
19
+ "FacturLintQuotaError",
20
+ "__version__",
21
+ ]
facturlint_sdk/cli.py ADDED
@@ -0,0 +1,347 @@
1
+ """FacturLint CLI — Outil en ligne de commande pour auditer, réparer et certifier les factures Factur-X 1.09.2."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import sys
10
+ from typing import Any
11
+
12
+ from facturlint_sdk import __version__
13
+ from facturlint_sdk.client import (
14
+ FacturLintAPIError,
15
+ FacturLintAuthError,
16
+ FacturLintClient,
17
+ FacturLintError,
18
+ FacturLintPaymentRequiredError,
19
+ FacturLintQuotaError,
20
+ PRICING_URL,
21
+ )
22
+
23
+
24
+ def _format_status(status: str) -> str:
25
+ badges = {
26
+ "COMPLIANT": "✅ CONFORME (COMPLIANT)",
27
+ "REPAIRABLE_ENVELOPE": "⚠️ ENVELOPPE RÉPARABLE (REPAIRABLE_ENVELOPE)",
28
+ "BUSINESS_REJECTED": "❌ REJET MÉTIER / LÉGAL (BUSINESS_REJECTED)",
29
+ "INVALID_FORMAT": "🚫 FORMAT INVALIDE (INVALID_FORMAT)",
30
+ }
31
+ return badges.get(status, status)
32
+
33
+
34
+ def _cmd_validate(client: FacturLintClient, args: argparse.Namespace) -> int:
35
+ try:
36
+ report = client.validate(args.file)
37
+ except FacturLintError as exc:
38
+ print(f"Erreur validation FacturLint : {exc}", file=sys.stderr)
39
+ return 2
40
+
41
+ if args.json:
42
+ print(json.dumps(report, ensure_ascii=False, indent=2))
43
+ return 0 if report.get("valid") else 1
44
+
45
+ status = report.get("status", "UNKNOWN")
46
+ container = report.get("container", {})
47
+ inv = report.get("invoice_summary", {})
48
+ issues = report.get("issues", [])
49
+ maths = report.get("math_suggestions", [])
50
+
51
+ print("=" * 70)
52
+ print(f"FacturLint Audit — Factur-X 1.09.2 / EN 16931 / BR-FR-CTC")
53
+ print("=" * 70)
54
+ print(f"Fichier : {args.file}")
55
+ print(f"Statut : {_format_status(status)}")
56
+ print(f"Profil détecté: {container.get('detected_profile') or 'Non détecté'}")
57
+ print(f"PDF/A-3b : {'Oui' if container.get('is_pdfa3') else 'Non'}")
58
+ print(f"Empreinte SHA : {report.get('sha256_fingerprint', '')[:16]}...")
59
+ print(f"Temps calcul : {report.get('processing_ms', 0)} ms (100% Stateless)")
60
+
61
+ if inv.get("invoice_number") or inv.get("seller_name"):
62
+ print("-" * 70)
63
+ print("MÉTADONNÉES FACTURE :")
64
+ if inv.get("invoice_number"):
65
+ print(f" • Numéro : {inv.get('invoice_number')}")
66
+ if inv.get("issue_date"):
67
+ print(f" • Date : {inv.get('issue_date')}")
68
+ if inv.get("seller_name"):
69
+ print(f" • Émetteur : {inv.get('seller_name')} (SIREN: {inv.get('seller_siren_or_siret') or 'N/A'})")
70
+ if inv.get("buyer_name"):
71
+ print(f" • Client : {inv.get('buyer_name')} (SIREN: {inv.get('buyer_siren_or_siret') or 'N/A'})")
72
+ if inv.get("grand_total"):
73
+ print(f" • Total TTC : {inv.get('grand_total')} {inv.get('currency', 'EUR')}")
74
+
75
+ if issues:
76
+ print("-" * 70)
77
+ print(f"ANOMALIES DÉTECTÉES ({len(issues)}) :")
78
+ for idx, issue in enumerate(issues, 1):
79
+ sev = issue.get("severity", "error").upper()
80
+ code = issue.get("code", "UNKNOWN")
81
+ msg = issue.get("message", "")
82
+ raw_url = issue.get("doc_url") or f"/erreurs/{code}"
83
+ doc_url = f"https://facturlint.com{raw_url}" if raw_url.startswith("/") else raw_url
84
+ print(f"\n [{idx}] [{sev}] {code}")
85
+ print(f" {msg}")
86
+ if issue.get("fix_hint"):
87
+ print(f" 💡 Solution : {issue.get('fix_hint')}")
88
+ print(f" 🔗 Guide officiel : {doc_url}")
89
+
90
+ if maths:
91
+ print("-" * 70)
92
+ print(f"ÉCARTS ARITHMÉTIQUES ({len(maths)}) :")
93
+ for m in maths:
94
+ print(f" • {m.get('rule_code')} : {m.get('explanation')}")
95
+
96
+ print("=" * 70)
97
+
98
+ is_valid = bool(report.get("valid"))
99
+ if not is_valid and status == "REPAIRABLE_ENVELOPE":
100
+ print("\n💡 Conseil : cette anomalie d'enveloppe PDF/A-3b est auto-réparable sans altérer les montants.")
101
+ print(f" Exécutez : facturlint repair \"{args.file}\" -o conforme.pdf\n")
102
+
103
+ if args.fail_on_warning and any(i.get("severity") == "warning" for i in issues):
104
+ return 1
105
+
106
+ return 0 if is_valid else 1
107
+
108
+
109
+ def _cmd_repair(client: FacturLintClient, args: argparse.Namespace) -> int:
110
+ try:
111
+ res = client.repair(args.file, output_path=args.output)
112
+ except (FacturLintPaymentRequiredError, FacturLintQuotaError) as exc:
113
+ print(f"Erreur quota/abonnement : {exc.detail}", file=sys.stderr)
114
+ print(f"Pour débloquer les réparations illimitées : {PRICING_URL}", file=sys.stderr)
115
+ return 2
116
+ except FacturLintError as exc:
117
+ print(f"Erreur réparation FacturLint : {exc}", file=sys.stderr)
118
+ return 2
119
+
120
+ if args.json:
121
+ print(json.dumps(res, ensure_ascii=False, indent=2))
122
+ return 0 if res.get("repaired") else 1
123
+
124
+ repaired = res.get("repaired", False)
125
+ actions = res.get("actions_applied", [])
126
+ before_status = res.get("before_report", {}).get("status", "UNKNOWN")
127
+ after_status = res.get("after_report", {}).get("status", "UNKNOWN")
128
+
129
+ print("=" * 70)
130
+ print("FacturLint Auto-Réparation PDF/A-3b")
131
+ print("=" * 70)
132
+ print(f"Fichier source : {args.file}")
133
+ print(f"Statut avant : {_format_status(before_status)}")
134
+ print(f"Statut après : {_format_status(after_status)}")
135
+ print(f"Réussite : {'Oui' if repaired else 'Non'}")
136
+ if actions:
137
+ print("\nActions appliquées sur l'enveloppe :")
138
+ for a in actions:
139
+ print(f" ✓ {a}")
140
+ if args.output:
141
+ print(f"\nFacture conforme enregistrée dans : {args.output}")
142
+ print(f"\nNotice légale : {res.get('legal_notice', '')}")
143
+ print("=" * 70)
144
+
145
+ return 0 if repaired else 1
146
+
147
+
148
+ def _cmd_certificate(client: FacturLintClient, args: argparse.Namespace) -> int:
149
+ try:
150
+ raw_pdf = client.certificate(args.file, output_path=args.output)
151
+ except FacturLintError as exc:
152
+ print(f"Erreur génération attestation : {exc}", file=sys.stderr)
153
+ return 2
154
+
155
+ print(f"Attestation d'audit FacturLint générée avec succès ({len(raw_pdf)} octets).")
156
+ print(f"Fichier : {args.output}")
157
+ return 0
158
+
159
+
160
+ def _cmd_batch(client: FacturLintClient, args: argparse.Namespace) -> int:
161
+ try:
162
+ res = client.batch_zip(
163
+ args.zip_file,
164
+ output_csv_path=args.csv,
165
+ output_zip_path=args.out_zip,
166
+ )
167
+ except (FacturLintPaymentRequiredError, FacturLintQuotaError) as exc:
168
+ print(f"Erreur quota/abonnement : {exc.detail}", file=sys.stderr)
169
+ print(f"Le traitement par lot requiert un abonnement : {PRICING_URL}", file=sys.stderr)
170
+ return 2
171
+ except FacturLintError as exc:
172
+ print(f"Erreur audit par lot : {exc}", file=sys.stderr)
173
+ return 2
174
+
175
+ if args.json:
176
+ print(json.dumps(res, ensure_ascii=False, indent=2))
177
+ return 0
178
+
179
+ summary = res.get("summary", {})
180
+ print("=" * 70)
181
+ print("FacturLint — Audit Groupé par Lot .ZIP")
182
+ print("=" * 70)
183
+ print(f"Archive traitée : {args.zip_file}")
184
+ print(f"Factures analysées : {summary.get('total_files', 0)}")
185
+ print(f"Conformes d'origine: {summary.get('compliant_initial', 0)}")
186
+ print(f"Auto-réparées : {summary.get('auto_repaired', 0)}")
187
+ print(f"Conformes final : {summary.get('compliant_final', 0)}")
188
+ print(f"Rejets métier : {summary.get('rejected_business', 0)}")
189
+ print(f"Formats invalides : {summary.get('invalid_format', 0)}")
190
+ print(f"Temps traitement : {summary.get('processing_ms', 0)} ms")
191
+
192
+ if args.csv:
193
+ print(f"\nRapport Excel CSV enregistré : {args.csv}")
194
+ if args.out_zip:
195
+ print(f"Archive factures réparées : {args.out_zip}")
196
+ print("=" * 70)
197
+
198
+ return 0
199
+
200
+
201
+ def _cmd_quota(client: FacturLintClient, args: argparse.Namespace) -> int:
202
+ try:
203
+ quota_data = client.quota()
204
+ except FacturLintAuthError:
205
+ print(
206
+ "Erreur : Clé API manquante ou invalide. Définissez FACTURLINT_API_KEY ou utilisez --api-key.\n"
207
+ f"Obtenez votre clé sur {PRICING_URL}",
208
+ file=sys.stderr,
209
+ )
210
+ return 2
211
+ except FacturLintError as exc:
212
+ print(f"Erreur consultation quota : {exc}", file=sys.stderr)
213
+ return 2
214
+
215
+ if args.json:
216
+ print(json.dumps(quota_data, ensure_ascii=False, indent=2))
217
+ return 0
218
+
219
+ print("=" * 60)
220
+ print("FacturLint — Quota & Formule API")
221
+ print("=" * 60)
222
+ print(f"Formule : {str(quota_data.get('plan', '')).upper()}")
223
+ print(f"Préfixe clé : {quota_data.get('key_prefix', 'N/A')}")
224
+ print(f"Quota mensuel : {quota_data.get('monthly_quota', 0)} factures")
225
+ print(f"Utilisé ce mois : {quota_data.get('used_this_month', 0)}")
226
+ print(f"Restant ce mois : {quota_data.get('remaining_this_month', 0)}")
227
+ print(f"Max factures/lot : {quota_data.get('max_batch_files', 20)}")
228
+ print("=" * 60)
229
+ return 0
230
+
231
+
232
+ def _cmd_rules(client: FacturLintClient, args: argparse.Namespace) -> int:
233
+ try:
234
+ rules = client.list_rules(category=args.category)
235
+ except FacturLintError as exc:
236
+ print(f"Erreur consultation catalogue : {exc}", file=sys.stderr)
237
+ return 2
238
+
239
+ if args.json:
240
+ print(json.dumps(rules, ensure_ascii=False, indent=2))
241
+ return 0
242
+
243
+ print(f"FacturLint — Catalogue des règles ({len(rules)} règles répertoriées)\n")
244
+ for r in rules:
245
+ code = r.get("code")
246
+ title = r.get("title")
247
+ cat = r.get("category")
248
+ repairable = " [Auto-réparable]" if r.get("auto_repairable") else ""
249
+ print(f"• {code:<20} [{cat}] {title}{repairable}")
250
+ print(f" Guide : https://facturlint.com/erreurs/{code}")
251
+ return 0
252
+
253
+
254
+ def _cmd_embed(client: FacturLintClient, args: argparse.Namespace) -> int:
255
+ try:
256
+ raw_pdf = client.embed(args.pdf, args.xml, output_path=args.output)
257
+ except FacturLintError as exc:
258
+ print(f"Erreur encapsulation Factur-X : {exc}", file=sys.stderr)
259
+ return 2
260
+
261
+ print(f"Facture hybride Factur-X générée avec succès ({len(raw_pdf)} octets).")
262
+ print(f"Fichier : {args.output}")
263
+ return 0
264
+
265
+
266
+ def build_parser() -> argparse.ArgumentParser:
267
+ parser = argparse.ArgumentParser(
268
+ prog="facturlint",
269
+ description="FacturLint CLI — Audit & Auto-Réparation Factur-X 1.09.2 / EN 16931 / BR-FR-CTC.",
270
+ epilog="Documentation et clés API disponibles sur https://facturlint.com",
271
+ )
272
+ parser.add_argument("-v", "--version", action="version", version=f"facturlint {__version__}")
273
+ parser.add_argument("-k", "--api-key", help="Clé API FacturLint (ou variable FACTURLINT_API_KEY)")
274
+ parser.add_argument(
275
+ "--base-url",
276
+ default=os.getenv("FACTURLINT_BASE_URL", "https://facturlint.com"),
277
+ help="URL de l'API FacturLint (défaut : https://facturlint.com)",
278
+ )
279
+ parser.add_argument("--json", action="store_true", help="Affichage brut au format JSON")
280
+
281
+ subparsers = parser.add_subparsers(dest="command", required=True)
282
+
283
+ # validate
284
+ p_val = subparsers.add_parser("validate", help="Valider une facture PDF Factur-X ou XML CII")
285
+ p_val.add_argument("file", help="Chemin du fichier PDF ou XML à auditer")
286
+ p_val.add_argument("--fail-on-warning", action="store_true", help="Retourner code 1 même pour de simples warnings")
287
+
288
+ # repair
289
+ p_rep = subparsers.add_parser("repair", help="Auto-réparer l'enveloppe technique PDF/A-3b")
290
+ p_rep.add_argument("file", help="Chemin du PDF Factur-X défectueux")
291
+ p_rep.add_argument("-o", "--output", required=True, help="Chemin où enregistrer le PDF conforme réparé")
292
+
293
+ # cert
294
+ p_cert = subparsers.add_parser("certificate", aliases=["cert"], help="Générer l'attestation PDF d'audit")
295
+ p_cert.add_argument("file", help="Chemin du fichier PDF ou XML")
296
+ p_cert.add_argument("-o", "--output", required=True, help="Chemin où enregistrer l'attestation PDF")
297
+
298
+ # batch
299
+ p_bat = subparsers.add_parser("batch", help="Auditer et réparer un lot complet de factures (.ZIP)")
300
+ p_bat.add_argument("zip_file", help="Chemin de l'archive .ZIP")
301
+ p_bat.add_argument("--csv", help="Chemin où enregistrer le rapport Excel CSV")
302
+ p_bat.add_argument("--out-zip", help="Chemin où enregistrer l'archive des factures réparées")
303
+
304
+ # quota
305
+ subparsers.add_parser("quota", help="Consulter le solde restant et la formule API active")
306
+
307
+ # rules
308
+ p_rules = subparsers.add_parser("rules", help="Consulter le catalogue des règles normatives")
309
+ p_rules.add_argument("--category", help="Filtrer par catégorie (ex: schematron_br_fr, pdfa3_xmp)")
310
+
311
+ # embed
312
+ p_emb = subparsers.add_parser("embed", help="Encapsuler un XML Factur-X dans un PDF pour créer un PDF/A-3b")
313
+ p_emb.add_argument("--pdf", required=True, help="Facture visuelle PDF")
314
+ p_emb.add_argument("--xml", required=True, help="Flux XML Factur-X 1.09.2")
315
+ p_emb.add_argument("-o", "--output", required=True, help="PDF Factur-X résultant")
316
+
317
+ return parser
318
+
319
+
320
+ def main() -> None:
321
+ parser = build_parser()
322
+ args = parser.parse_args()
323
+
324
+ client = FacturLintClient(api_key=args.api_key, base_url=args.base_url)
325
+
326
+ cmd_map = {
327
+ "validate": _cmd_validate,
328
+ "repair": _cmd_repair,
329
+ "certificate": _cmd_certificate,
330
+ "cert": _cmd_certificate,
331
+ "batch": _cmd_batch,
332
+ "quota": _cmd_quota,
333
+ "rules": _cmd_rules,
334
+ "embed": _cmd_embed,
335
+ }
336
+
337
+ handler = cmd_map.get(args.command)
338
+ if not handler:
339
+ parser.print_help()
340
+ sys.exit(2)
341
+
342
+ code = handler(client, args)
343
+ sys.exit(code)
344
+
345
+
346
+ if __name__ == "__main__":
347
+ main()
@@ -0,0 +1,413 @@
1
+ """FacturLint Official Python SDK — Pure stdlib client for Factur-X 1.09.2 & EN 16931 compliance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import mimetypes
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any, BinaryIO
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ import uuid
15
+
16
+ SDK_VERSION = "0.2.0"
17
+ DEFAULT_BASE_URL = "https://facturlint.com"
18
+ PRICING_URL = "https://facturlint.com/#tarifs"
19
+
20
+
21
+ # --- Custom Exceptions ---
22
+
23
+
24
+ class FacturLintError(Exception):
25
+ """Base exception for all FacturLint SDK errors."""
26
+
27
+
28
+ class FacturLintAPIError(FacturLintError):
29
+ """Raised when the FacturLint API returns an HTTP error code."""
30
+
31
+ def __init__(
32
+ self,
33
+ status_code: int,
34
+ message: str,
35
+ payload: dict[str, Any] | None = None,
36
+ ) -> None:
37
+ super().__init__(message)
38
+ self.status_code = status_code
39
+ self.payload = payload or {}
40
+ self.code = self.payload.get("code")
41
+ self.detail = self.payload.get("detail", message)
42
+
43
+
44
+ class FacturLintAuthError(FacturLintAPIError):
45
+ """Raised on HTTP 401 Unauthorized (missing or invalid API key)."""
46
+
47
+
48
+ class FacturLintPaymentRequiredError(FacturLintAPIError):
49
+ """Raised on HTTP 402 Payment Required (quota plan limit or batch subscription needed)."""
50
+
51
+
52
+ class FacturLintQuotaError(FacturLintAPIError):
53
+ """Raised on HTTP 429 Too Many Requests (daily anonymous limit or monthly quota exhausted)."""
54
+
55
+
56
+ # --- Pure stdlib Multipart Form-Data encoder (RFC 7578) ---
57
+
58
+
59
+ def encode_multipart_formdata(
60
+ fields: dict[str, str] | None = None,
61
+ files: list[tuple[str, str, bytes, str | None]] | None = None,
62
+ ) -> tuple[bytes, str]:
63
+ """Encodes form fields and binary files into an RFC 7578 multipart/form-data payload.
64
+
65
+ Args:
66
+ fields: Mapping of form field name to string value.
67
+ files: List of tuples (field_name, filename, file_bytes, optional_content_type).
68
+
69
+ Returns:
70
+ A tuple of (encoded_body_bytes, content_type_header_with_boundary).
71
+ """
72
+ boundary = f"----FacturLintFormBoundary{uuid.uuid4().hex}"
73
+ body = bytearray()
74
+
75
+ if fields:
76
+ for name, value in fields.items():
77
+ body.extend(f"--{boundary}\r\n".encode("utf-8"))
78
+ body.extend(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("utf-8"))
79
+ body.extend(str(value).encode("utf-8"))
80
+ body.extend(b"\r\n")
81
+
82
+ if files:
83
+ for field_name, filename, content, content_type in files:
84
+ ct = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
85
+ clean_filename = Path(filename).name.replace('"', '\\"')
86
+ body.extend(f"--{boundary}\r\n".encode("utf-8"))
87
+ body.extend(
88
+ f'Content-Disposition: form-data; name="{field_name}"; filename="{clean_filename}"\r\n'.encode(
89
+ "utf-8"
90
+ )
91
+ )
92
+ body.extend(f"Content-Type: {ct}\r\n\r\n".encode("utf-8"))
93
+ body.extend(content)
94
+ body.extend(b"\r\n")
95
+
96
+ body.extend(f"--{boundary}--\r\n".encode("utf-8"))
97
+ content_type_header = f"multipart/form-data; boundary={boundary}"
98
+ return bytes(body), content_type_header
99
+
100
+
101
+ def _read_file_payload(
102
+ file_input: str | Path | bytes | BinaryIO,
103
+ default_name: str,
104
+ custom_name: str | None = None,
105
+ ) -> tuple[str, bytes]:
106
+ """Reads file input into a (filename, bytes) pair."""
107
+ if isinstance(file_input, (str, Path)):
108
+ p = Path(file_input)
109
+ if not p.is_file():
110
+ raise FileNotFoundError(f"Le fichier spécifié n'existe pas : {p}")
111
+ return custom_name or p.name, p.read_bytes()
112
+
113
+ if isinstance(file_input, bytes):
114
+ return custom_name or default_name, file_input
115
+
116
+ if hasattr(file_input, "read"):
117
+ name = custom_name or getattr(file_input, "name", default_name)
118
+ data = file_input.read()
119
+ if isinstance(data, str):
120
+ data = data.encode("utf-8")
121
+ return Path(str(name)).name, data
122
+
123
+ raise TypeError(
124
+ f"Format de fichier non pris en charge : {type(file_input)}. "
125
+ "Attendu : str, pathlib.Path, bytes ou objet fichier binaire."
126
+ )
127
+
128
+
129
+ # --- Client Class ---
130
+
131
+
132
+ class FacturLintClient:
133
+ """Official stateless Python client for the FacturLint Factur-X & BR-FR-CTC compliance API.
134
+
135
+ Uses Python standard library only (no external dependencies).
136
+ Compatible with Python 3.9+.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ api_key: str | None = None,
142
+ base_url: str | None = None,
143
+ timeout: float = 60.0,
144
+ ) -> None:
145
+ """Initializes the FacturLint client.
146
+
147
+ Args:
148
+ api_key: Optional API key (defaults to environment variable FACTURLINT_API_KEY).
149
+ Validation is free without a key. Auto-repair and batch require a key or paid plan.
150
+ base_url: Optional API root URL (defaults to FACTURLINT_BASE_URL or https://facturlint.com).
151
+ timeout: Network request timeout in seconds (default 60s).
152
+ """
153
+ self.api_key = api_key or os.getenv("FACTURLINT_API_KEY")
154
+ resolved_base = base_url or os.getenv("FACTURLINT_BASE_URL") or DEFAULT_BASE_URL
155
+ self.base_url = resolved_base.rstrip("/")
156
+ self.timeout = timeout
157
+
158
+ def _build_request(
159
+ self,
160
+ endpoint: str,
161
+ method: str = "GET",
162
+ data: bytes | None = None,
163
+ headers: dict[str, str] | None = None,
164
+ ) -> urllib.request.Request:
165
+ url = f"{self.base_url}{endpoint}"
166
+ req_headers = {
167
+ "User-Agent": f"facturlint-python-sdk/{SDK_VERSION}",
168
+ "Accept": "application/json, application/pdf, */*",
169
+ }
170
+ if self.api_key:
171
+ req_headers["X-API-Key"] = self.api_key
172
+ req_headers["Authorization"] = f"Bearer {self.api_key}"
173
+
174
+ if headers:
175
+ req_headers.update(headers)
176
+
177
+ return urllib.request.Request(url=url, data=data, headers=req_headers, method=method)
178
+
179
+ def _execute(
180
+ self,
181
+ endpoint: str,
182
+ method: str = "GET",
183
+ data: bytes | None = None,
184
+ headers: dict[str, str] | None = None,
185
+ ) -> tuple[int, dict[str, str], bytes]:
186
+ req = self._build_request(endpoint, method=method, data=data, headers=headers)
187
+ try:
188
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
189
+ status = resp.status
190
+ resp_headers = {k.lower(): v for k, v in resp.headers.items()}
191
+ raw_bytes = resp.read()
192
+ return status, resp_headers, raw_bytes
193
+ except urllib.error.HTTPError as exc:
194
+ raw_err = exc.read()
195
+ err_payload: dict[str, Any] = {}
196
+ try:
197
+ err_payload = json.loads(raw_err.decode("utf-8"))
198
+ except Exception:
199
+ err_payload = {"detail": raw_err.decode("utf-8", errors="replace")}
200
+
201
+ msg = err_payload.get("detail") or f"Erreur API FacturLint HTTP {exc.code} : {exc.reason}"
202
+
203
+ if exc.code == 401:
204
+ raise FacturLintAuthError(
205
+ status_code=401,
206
+ message=f"Authentification FacturLint échouée (401) : {msg}",
207
+ payload=err_payload,
208
+ ) from exc
209
+ if exc.code == 402:
210
+ upgrade_tip = f"\nPour débloquer ou augmenter votre quota : {PRICING_URL}"
211
+ raise FacturLintPaymentRequiredError(
212
+ status_code=402,
213
+ message=f"Abonnement ou quota requis (402) : {msg}{upgrade_tip}",
214
+ payload=err_payload,
215
+ ) from exc
216
+ if exc.code == 429:
217
+ upgrade_tip = f"\nQuota mensuel épuisé. Passez à la formule supérieure : {PRICING_URL}"
218
+ raise FacturLintQuotaError(
219
+ status_code=429,
220
+ message=f"Limite de requêtes atteinte (429) : {msg}{upgrade_tip}",
221
+ payload=err_payload,
222
+ ) from exc
223
+
224
+ raise FacturLintAPIError(
225
+ status_code=exc.code,
226
+ message=f"Erreur HTTP {exc.code} FacturLint : {msg}",
227
+ payload=err_payload,
228
+ ) from exc
229
+ except urllib.error.URLError as exc:
230
+ raise FacturLintError(
231
+ f"Impossible de joindre le serveur FacturLint sur {self.base_url} : {exc.reason}"
232
+ ) from exc
233
+
234
+ def validate(
235
+ self,
236
+ file: str | Path | bytes | BinaryIO,
237
+ filename: str | None = None,
238
+ ) -> dict[str, Any]:
239
+ """Validates a Factur-X PDF or CII XML invoice against EN 16931 & BR-FR-CTC rules.
240
+
241
+ Free & stateless endpoint. No invoice is ever stored.
242
+
243
+ Args:
244
+ file: Path to invoice file, raw bytes, or readable file object.
245
+ filename: Optional custom filename.
246
+
247
+ Returns:
248
+ Validation report dictionary matching the official FacturLint ValidationReport schema.
249
+ """
250
+ fname, content = _read_file_payload(file, "facture.pdf", filename)
251
+ body, ct = encode_multipart_formdata(files=[("file", fname, content, None)])
252
+ _, _, raw_resp = self._execute("/v1/validate", method="POST", data=body, headers={"Content-Type": ct})
253
+ return json.loads(raw_resp.decode("utf-8"))
254
+
255
+ def repair(
256
+ self,
257
+ file: str | Path | bytes | BinaryIO,
258
+ output_path: str | Path | None = None,
259
+ filename: str | None = None,
260
+ ) -> dict[str, Any]:
261
+ """Automatically repairs PDF/A-3b envelope issues (XMP metadata, ICC sRGB color profile, attachments).
262
+
263
+ Guaranteed zero accounting alteration: amounts, taxes and lines are strictly preserved.
264
+
265
+ Args:
266
+ file: Path to defective PDF, bytes, or file object.
267
+ output_path: Optional path where to write the repaired compliant PDF.
268
+ filename: Optional custom filename.
269
+
270
+ Returns:
271
+ RepairResult dictionary containing before_report, after_report, and actions_applied.
272
+ """
273
+ fname, content = _read_file_payload(file, "facture.pdf", filename)
274
+ body, ct = encode_multipart_formdata(files=[("file", fname, content, None)])
275
+ _, _, raw_resp = self._execute("/v1/repair", method="POST", data=body, headers={"Content-Type": ct})
276
+ res: dict[str, Any] = json.loads(raw_resp.decode("utf-8"))
277
+
278
+ if output_path and res.get("repaired_pdf_base64"):
279
+ repaired_bytes = base64.b64decode(res["repaired_pdf_base64"])
280
+ out_p = Path(output_path)
281
+ out_p.parent.mkdir(parents=True, exist_ok=True)
282
+ out_p.write_bytes(repaired_bytes)
283
+
284
+ return res
285
+
286
+ def certificate(
287
+ self,
288
+ file: str | Path | bytes | BinaryIO,
289
+ output_path: str | Path | None = None,
290
+ filename: str | None = None,
291
+ ) -> bytes:
292
+ """Generates an official audit certificate PDF for an invoice (hash SHA-256 + compliance proof).
293
+
294
+ Args:
295
+ file: Path to invoice, bytes, or file object.
296
+ output_path: Optional path where to write the certificate PDF.
297
+ filename: Optional custom filename.
298
+
299
+ Returns:
300
+ Binary bytes of the official audit certificate PDF.
301
+ """
302
+ fname, content = _read_file_payload(file, "facture.pdf", filename)
303
+ body, ct = encode_multipart_formdata(files=[("file", fname, content, None)])
304
+ _, _, raw_pdf = self._execute("/v1/certificate", method="POST", data=body, headers={"Content-Type": ct})
305
+
306
+ if output_path:
307
+ out_p = Path(output_path)
308
+ out_p.parent.mkdir(parents=True, exist_ok=True)
309
+ out_p.write_bytes(raw_pdf)
310
+
311
+ return raw_pdf
312
+
313
+ def batch_zip(
314
+ self,
315
+ zip_file: str | Path | bytes | BinaryIO,
316
+ output_csv_path: str | Path | None = None,
317
+ output_zip_path: str | Path | None = None,
318
+ filename: str | None = None,
319
+ ) -> dict[str, Any]:
320
+ """Audits an entire .ZIP archive of invoices, with auto-repair and Excel CSV generation.
321
+
322
+ Stateless execution in RAM. Requires an active FacturLint plan (Starter, Pro, Cabinet).
323
+
324
+ Args:
325
+ zip_file: Path to .ZIP archive, bytes, or file object.
326
+ output_csv_path: Optional path to save the generated Excel CSV report.
327
+ output_zip_path: Optional path to save the .ZIP archive containing repaired invoices.
328
+ filename: Optional custom filename.
329
+
330
+ Returns:
331
+ Dictionary with batch audit summary, individual invoice items, and quota info.
332
+ """
333
+ fname, content = _read_file_payload(zip_file, "lot_factures.zip", filename)
334
+ body, ct = encode_multipart_formdata(files=[("file", fname, content, "application/zip")])
335
+ _, _, raw_resp = self._execute("/v1/batch", method="POST", data=body, headers={"Content-Type": ct})
336
+ res: dict[str, Any] = json.loads(raw_resp.decode("utf-8"))
337
+
338
+ if output_csv_path and res.get("csv_report_base64"):
339
+ csv_bytes = base64.b64decode(res["csv_report_base64"])
340
+ csv_p = Path(output_csv_path)
341
+ csv_p.parent.mkdir(parents=True, exist_ok=True)
342
+ csv_p.write_bytes(csv_bytes)
343
+
344
+ if output_zip_path and res.get("repaired_zip_base64"):
345
+ zip_bytes = base64.b64decode(res["repaired_zip_base64"])
346
+ zip_p = Path(output_zip_path)
347
+ zip_p.parent.mkdir(parents=True, exist_ok=True)
348
+ zip_p.write_bytes(zip_bytes)
349
+
350
+ return res
351
+
352
+ def embed(
353
+ self,
354
+ pdf_file: str | Path | bytes | BinaryIO,
355
+ xml_file: str | Path | bytes | BinaryIO,
356
+ output_path: str | Path | None = None,
357
+ pdf_filename: str | None = None,
358
+ xml_filename: str | None = None,
359
+ ) -> bytes:
360
+ """Embeds a Factur-X CII XML stream into an existing visual PDF to create a PDF/A-3b hybrid invoice.
361
+
362
+ Requires an API key.
363
+
364
+ Args:
365
+ pdf_file: Visual PDF document.
366
+ xml_file: Factur-X 1.09.2 XML CII stream.
367
+ output_path: Optional destination path for the hybrid PDF.
368
+ pdf_filename: Optional custom name for the PDF.
369
+ xml_filename: Optional custom name for the XML.
370
+
371
+ Returns:
372
+ Binary bytes of the compliant Factur-X hybrid PDF.
373
+ """
374
+ p_name, p_bytes = _read_file_payload(pdf_file, "facture.pdf", pdf_filename)
375
+ x_name, x_bytes = _read_file_payload(xml_file, "factur-x.xml", xml_filename)
376
+ body, ct = encode_multipart_formdata(
377
+ files=[
378
+ ("pdf", p_name, p_bytes, "application/pdf"),
379
+ ("xml", x_name, x_bytes, "application/xml"),
380
+ ]
381
+ )
382
+ _, _, raw_pdf = self._execute("/v1/embed", method="POST", data=body, headers={"Content-Type": ct})
383
+
384
+ if output_path:
385
+ out_p = Path(output_path)
386
+ out_p.parent.mkdir(parents=True, exist_ok=True)
387
+ out_p.write_bytes(raw_pdf)
388
+
389
+ return raw_pdf
390
+
391
+ def quota(self) -> dict[str, Any]:
392
+ """Retrieves remaining API quota, current plan, and batch limits for the authenticated key.
393
+
394
+ Returns:
395
+ Quota dictionary (plan, monthly_quota, used_this_month, remaining_this_month, max_batch_files).
396
+ """
397
+ _, _, raw_resp = self._execute("/v1/quota", method="GET")
398
+ return json.loads(raw_resp.decode("utf-8"))
399
+
400
+ def list_rules(self, category: str | None = None) -> list[dict[str, Any]]:
401
+ """Retrieves the complete catalog of Factur-X, EN 16931 and BR-FR-CTC normative rules.
402
+
403
+ Args:
404
+ category: Optional filter (ex: 'schematron_br_fr', 'schematron_en16931', 'pdfa3_xmp').
405
+
406
+ Returns:
407
+ List of rule definitions with explanation, severity, and resolution hints.
408
+ """
409
+ endpoint = "/v1/rules"
410
+ if category:
411
+ endpoint = f"{endpoint}?category={urllib.parse.quote(category)}"
412
+ _, _, raw_resp = self._execute(endpoint, method="GET")
413
+ return json.loads(raw_resp.decode("utf-8"))
File without changes