From c5c2dbb72cddc1bd6c78171519dd64c0609dff82 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Fri, 13 Nov 2026 15:58:36 +0100 Subject: [PATCH 1/4] feat(invoicing): add FatturaPA XML export and SDI transmission Support Italian e-invoicing with FPR12/FPA12 export, a generic HTTP SDI adapter, transmission tracking/polling, admin UI, docs, and tests. --- CHANGELOG.md | 4 + app/integrations/sdi_transport.py | 116 ++ app/models/__init__.py | 2 + app/models/client.py | 17 + app/models/invoice.py | 12 + app/models/invoice_sdi.py | 116 ++ app/models/settings.py | 26 + app/routes/admin.py | 22 + app/routes/api_v1_invoices.py | 28 + app/routes/clients.py | 18 + app/routes/invoices.py | 133 ++ app/services/__init__.py | 2 + app/services/sdi_service.py | 192 +++ app/templates/admin/settings.html | 60 + app/templates/clients/create.html | 17 + app/templates/clients/edit.html | 17 + app/templates/invoices/create.html | 8 + app/templates/invoices/edit.html | 8 + app/templates/invoices/view.html | 133 ++ app/utils/fatturapa.py | 536 ++++++ app/utils/scheduled_tasks.py | 37 + docs/admin/configuration/FATTURAPA_SDI.md | 114 ++ docs/admin/configuration/PEPPOL_EINVOICING.md | 5 +- migrations/versions/209_add_fatturapa_sdi.py | 143 ++ requirements-test.txt | 3 + tests/conftest.py | 1 + ..._del_file_xml_FatturaPA_versione_1.2.1.xsd | 1449 +++++++++++++++++ .../fatturapa/xmldsig-core-schema.xsd | 318 ++++ tests/test_fatturapa.py | 227 +++ tests/test_fatturapa_routes.py | 171 ++ tests/test_sdi_service.py | 216 +++ translations/it/LC_MESSAGES/messages.po | 99 ++ 32 files changed, 4248 insertions(+), 2 deletions(-) create mode 100644 app/integrations/sdi_transport.py create mode 100644 app/models/invoice_sdi.py create mode 100644 app/services/sdi_service.py create mode 100644 app/utils/fatturapa.py create mode 100644 docs/admin/configuration/FATTURAPA_SDI.md create mode 100644 migrations/versions/209_add_fatturapa_sdi.py create mode 100644 tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd create mode 100644 tests/fixtures/fatturapa/xmldsig-core-schema.xsd create mode 100644 tests/test_fatturapa.py create mode 100644 tests/test_fatturapa_routes.py create mode 100644 tests/test_sdi_service.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b1debb59..c29d21401 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **FatturaPA / SDI (Italy)** — Export FatturaPA 1.2 XML (`FPR12` B2B and `FPA12` public administration), send via a configurable SDI intermediary HTTP adapter, track transmissions and SDI notifications (`RC`/`NS`/`MC`/`NE`/`DT`), and poll status every 15 minutes. See `docs/admin/configuration/FATTURAPA_SDI.md`. + ## [5.20.0] - 2026-11-10 ### Added diff --git a/app/integrations/sdi_transport.py b/app/integrations/sdi_transport.py new file mode 100644 index 000000000..44ac0480b --- /dev/null +++ b/app/integrations/sdi_transport.py @@ -0,0 +1,116 @@ +"""Generic HTTP transport for Italian SDI (FatturaPA) intermediaries.""" + +from __future__ import annotations + +import base64 +import logging +from typing import Any, Dict, Optional +import requests + +logger = logging.getLogger(__name__) + + +class SdiTransportError(RuntimeError): + pass + + +def bridge_base_url(transport_url: str) -> str: + """Strip a trailing /send path to get the intermediary base URL.""" + url = (transport_url or "").rstrip("/") + if url.lower().endswith("/send"): + url = url[: -len("/send")] + return url.rstrip("/") + + +class GenericSdiTransport: + """ + HTTP adapter for a user-configured SDI intermediary. + + Send contract: + POST {url} + Authorization: Bearer {token} + JSON: { + filename, formato, recipient: {codice_destinatario, pec}, + xml_base64, sha256 + } + Response: {message_id, sdi_identifier?} + + Status contract: + GET {base}/message/{message_id}/status + Response: { + status, sdi_identifier?, + notifications: [{type: RC|NS|MC|NE|DT|AT, date, detail}] + } + """ + + def __init__(self, url: str, token: Optional[str] = None, timeout: int = 30): + self.url = (url or "").strip() + self.token = (token or "").strip() or None + self.timeout = timeout or 30 + if not self.url: + raise SdiTransportError("SDI transport URL is not configured") + + def _headers(self) -> Dict[str, str]: + headers = {"Content-Type": "application/json", "Accept": "application/json"} + if self.token: + headers["Authorization"] = f"Bearer {self.token}" + return headers + + def send( + self, + *, + filename: str, + formato: str, + codice_destinatario: str, + pec: Optional[str], + xml: str, + sha256: str, + ) -> Dict[str, Any]: + payload = { + "filename": filename, + "formato": formato, + "recipient": { + "codice_destinatario": codice_destinatario, + "pec": pec, + }, + "xml_base64": base64.b64encode(xml.encode("utf-8")).decode("ascii"), + "sha256": sha256, + } + try: + resp = requests.post(self.url, json=payload, headers=self._headers(), timeout=self.timeout) + except requests.RequestException as e: + raise SdiTransportError(f"SDI transport request failed: {e}") from e + + if resp.status_code >= 400: + raise SdiTransportError(f"SDI transport returned HTTP {resp.status_code}: {resp.text[:500]}") + + try: + data = resp.json() + except Exception as e: + raise SdiTransportError(f"SDI transport returned non-JSON response: {e}") from e + + if not isinstance(data, dict): + raise SdiTransportError("SDI transport response must be a JSON object") + if not data.get("message_id"): + raise SdiTransportError("SDI transport response missing message_id") + return data + + def get_status(self, message_id: str) -> Dict[str, Any]: + base = bridge_base_url(self.url) + status_url = f"{base}/message/{message_id}/status" + try: + resp = requests.get(status_url, headers=self._headers(), timeout=self.timeout) + except requests.RequestException as e: + raise SdiTransportError(f"SDI status request failed: {e}") from e + + if resp.status_code >= 400: + raise SdiTransportError(f"SDI status returned HTTP {resp.status_code}: {resp.text[:500]}") + + try: + data = resp.json() + except Exception as e: + raise SdiTransportError(f"SDI status returned non-JSON response: {e}") from e + + if not isinstance(data, dict): + raise SdiTransportError("SDI status response must be a JSON object") + return data diff --git a/app/models/__init__.py b/app/models/__init__.py index 1361ed675..2600540b5 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -55,6 +55,7 @@ from .invoice_image import InvoiceImage from .invoice_pdf_template import InvoicePDFTemplate from .invoice_peppol import InvoicePeppolTransmission, PeppolInboundDocument +from .invoice_sdi import InvoiceSdiTransmission from .invoice_template import InvoiceTemplate from .issue import Issue from .kanban_board_template import KanbanBoardTemplate @@ -201,6 +202,7 @@ "InvoiceEmail", "InvoicePeppolTransmission", "PeppolInboundDocument", + "InvoiceSdiTransmission", "Webhook", "WebhookDelivery", "Quote", diff --git a/app/models/client.py b/app/models/client.py index 74d6fece5..eef6cbaa4 100644 --- a/app/models/client.py +++ b/app/models/client.py @@ -30,6 +30,11 @@ class Client(db.Model): country = db.Column(db.String(2), nullable=True) # ISO 3166-1 alpha-2 vat_id = db.Column(db.String(50), nullable=True) leitweg_id = db.Column(db.String(100), nullable=True) # XRechnung BT-10 / German Leitweg-ID + # Italian FatturaPA / SDI recipient fields + sdi_codice_destinatario = db.Column(db.String(7), nullable=True) # 6=PA (FPA12), 7=B2B (FPR12) + pec_email = db.Column(db.String(200), nullable=True) + codice_fiscale = db.Column(db.String(16), nullable=True) + provincia = db.Column(db.String(2), nullable=True) default_hourly_rate = db.Column(db.Numeric(9, 2), nullable=True) status = db.Column(db.String(20), default="active", nullable=False) # 'active' or 'inactive' prepaid_hours_monthly = db.Column(db.Numeric(7, 2), nullable=True) @@ -70,6 +75,10 @@ def __init__( country=None, vat_id=None, leitweg_id=None, + sdi_codice_destinatario=None, + pec_email=None, + codice_fiscale=None, + provincia=None, default_hourly_rate=None, company=None, prepaid_hours_monthly=None, @@ -94,6 +103,10 @@ def __init__( self.country = country.strip().upper()[:2] if country else None self.vat_id = vat_id.strip() if vat_id else None self.leitweg_id = leitweg_id.strip() if leitweg_id else None + self.sdi_codice_destinatario = sdi_codice_destinatario.strip().upper() if sdi_codice_destinatario else None + self.pec_email = pec_email.strip() if pec_email else None + self.codice_fiscale = codice_fiscale.strip().upper() if codice_fiscale else None + self.provincia = provincia.strip().upper()[:2] if provincia else None self.default_hourly_rate = Decimal(str(default_hourly_rate)) if default_hourly_rate else None self.prepaid_hours_monthly = ( Decimal(str(prepaid_hours_monthly)) if prepaid_hours_monthly not in (None, "") else None @@ -298,6 +311,10 @@ def to_dict(self): "country": getattr(self, "country", None), "vat_id": getattr(self, "vat_id", None), "leitweg_id": getattr(self, "leitweg_id", None), + "sdi_codice_destinatario": getattr(self, "sdi_codice_destinatario", None), + "pec_email": getattr(self, "pec_email", None), + "codice_fiscale": getattr(self, "codice_fiscale", None), + "provincia": getattr(self, "provincia", None), "default_hourly_rate": str(self.default_hourly_rate) if self.default_hourly_rate else None, "status": self.status, "is_active": self.is_active, diff --git a/app/models/invoice.py b/app/models/invoice.py index d4280071f..fd0f4bc8b 100644 --- a/app/models/invoice.py +++ b/app/models/invoice.py @@ -58,6 +58,10 @@ class Invoice(db.Model): vat_exemption_reason = db.Column(db.Text, nullable=True) vat_exemption_code = db.Column(db.String(50), nullable=True) + # Italian public-administration procurement codes (FatturaPA DatiOrdineAcquisto) + cig = db.Column(db.String(15), nullable=True) + cup = db.Column(db.String(15), nullable=True) + # Metadata created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) @@ -108,6 +112,14 @@ def __init__(self, invoice_number, project_id, client_name, due_date, created_by self.vat_category = kwargs.get("vat_category") self.vat_exemption_reason = kwargs.get("vat_exemption_reason") self.vat_exemption_code = kwargs.get("vat_exemption_code") + self.cig = kwargs.get("cig") + self.cup = kwargs.get("cup") + if "subtotal" in kwargs and kwargs.get("subtotal") is not None: + self.subtotal = Decimal(str(kwargs["subtotal"])) + if "tax_amount" in kwargs and kwargs.get("tax_amount") is not None: + self.tax_amount = Decimal(str(kwargs["tax_amount"])) + if "total_amount" in kwargs and kwargs.get("total_amount") is not None: + self.total_amount = Decimal(str(kwargs["total_amount"])) def __repr__(self): return f"" diff --git a/app/models/invoice_sdi.py b/app/models/invoice_sdi.py new file mode 100644 index 000000000..877fcd237 --- /dev/null +++ b/app/models/invoice_sdi.py @@ -0,0 +1,116 @@ +"""FatturaPA / SDI transmission audit model.""" + +from datetime import datetime + +from app import db + +# Terminal statuses that no longer need polling +SDI_FINAL_STATUSES = frozenset({"delivered", "not_delivered", "rejected", "accepted", "refused", "expired", "failed"}) + +# Map SDI notification types to transmission status +SDI_NOTIFICATION_STATUS = { + "RC": "delivered", # Ricevuta di consegna + "NS": "rejected", # Notifica di scarto + "MC": "not_delivered", # Mancata consegna (still legally issued) + "NE": "accepted", # Notifica esito (accepted or refused — refined by detail) + "DT": "expired", # Decorrenza termini + "AT": "failed", # Attestazione di trasmissione con impossibilità di recapito +} + + +class InvoiceSdiTransmission(db.Model): + """Track SDI (FatturaPA) sends for an invoice.""" + + __tablename__ = "invoice_sdi_transmissions" + + id = db.Column(db.Integer, primary_key=True) + invoice_id = db.Column(db.Integer, db.ForeignKey("invoices.id"), nullable=False, index=True) + + filename = db.Column(db.String(100), nullable=True) + progressivo = db.Column(db.String(10), nullable=True) + formato = db.Column(db.String(5), nullable=True) # FPR12 | FPA12 + xml = db.Column(db.Text, nullable=True) + xml_sha256 = db.Column(db.String(64), nullable=True) + + # pending, sent, delivered, not_delivered, rejected, accepted, refused, expired, failed + status = db.Column(db.String(20), nullable=False, default="pending", index=True) + + sdi_identifier = db.Column(db.String(100), nullable=True) + message_id = db.Column(db.String(200), nullable=True) + notifications = db.Column(db.JSON, nullable=True) + error_message = db.Column(db.Text, nullable=True) + + created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) + sent_at = db.Column(db.DateTime, nullable=True) + updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + invoice = db.relationship("Invoice", backref=db.backref("sdi_transmissions", lazy="dynamic")) + + def mark_sent(self, message_id=None, sdi_identifier=None, response_payload=None): + self.status = "sent" + self.sent_at = datetime.utcnow() + self.updated_at = datetime.utcnow() + if message_id: + self.message_id = str(message_id) + if sdi_identifier: + self.sdi_identifier = str(sdi_identifier) + if response_payload is not None: + notes = list(self.notifications or []) + notes.append({"type": "send_response", "payload": response_payload, "date": datetime.utcnow().isoformat()}) + self.notifications = notes + + def mark_failed(self, error_message, response_payload=None): + self.status = "failed" + self.updated_at = datetime.utcnow() + self.error_message = str(error_message) if error_message is not None else "Unknown error" + if response_payload is not None: + notes = list(self.notifications or []) + notes.append({"type": "error", "payload": response_payload, "date": datetime.utcnow().isoformat()}) + self.notifications = notes + + def apply_notification(self, notif_type: str, detail=None, date=None): + """Apply an SDI notification type (RC/NS/MC/NE/DT/AT) and update status.""" + ntype = (notif_type or "").strip().upper() + notes = list(self.notifications or []) + notes.append( + { + "type": ntype, + "detail": detail, + "date": date or datetime.utcnow().isoformat(), + } + ) + self.notifications = notes + self.updated_at = datetime.utcnow() + + if ntype == "NE": + # Notifica esito: detail may indicate acceptance or refusal + detail_s = str(detail or "").lower() + if any(x in detail_s for x in ("rifiut", "refus", "ec02", "reject")): + self.status = "refused" + else: + self.status = "accepted" + return + + mapped = SDI_NOTIFICATION_STATUS.get(ntype) + if mapped: + self.status = mapped + if ntype == "NS" and detail: + self.error_message = str(detail)[:2000] + + def to_dict(self): + return { + "id": self.id, + "invoice_id": self.invoice_id, + "filename": self.filename, + "progressivo": self.progressivo, + "formato": self.formato, + "xml_sha256": self.xml_sha256, + "status": self.status, + "sdi_identifier": self.sdi_identifier, + "message_id": self.message_id, + "error_message": self.error_message, + "notifications": self.notifications, + "created_at": self.created_at.isoformat() if self.created_at else None, + "sent_at": self.sent_at.isoformat() if self.sent_at else None, + "updated_at": self.updated_at.isoformat() if self.updated_at else None, + } diff --git a/app/models/settings.py b/app/models/settings.py index fa60f6092..990cade16 100644 --- a/app/models/settings.py +++ b/app/models/settings.py @@ -103,6 +103,15 @@ class Settings(db.Model): company_country = db.Column(db.String(2), default="", nullable=True) # ISO 3166-1 alpha-2 company_iban = db.Column(db.String(34), default="", nullable=True) company_bic = db.Column(db.String(11), default="", nullable=True) + # Italian FatturaPA / SDI company fields + company_codice_fiscale = db.Column(db.String(16), default="", nullable=True) + company_regime_fiscale = db.Column(db.String(4), default="RF01", nullable=True) + company_provincia = db.Column(db.String(2), default="", nullable=True) + sdi_enabled = db.Column(db.Boolean, default=False, nullable=False) + sdi_transport_url = db.Column(db.String(500), default="", nullable=True) + sdi_transport_token = db.Column(db.String(255), default="", nullable=True) + sdi_transmitter_id = db.Column(db.String(16), default="", nullable=True) + sdi_timeout = db.Column(db.Integer, default=30, nullable=True) # PDF template customization invoice_pdf_template_html = db.Column(db.Text, default="", nullable=True) @@ -323,6 +332,14 @@ def __init__(self, **kwargs): self.company_country = kwargs.get("company_country", "") self.company_iban = kwargs.get("company_iban", "") self.company_bic = kwargs.get("company_bic", "") + self.company_codice_fiscale = kwargs.get("company_codice_fiscale", "") + self.company_regime_fiscale = kwargs.get("company_regime_fiscale", "RF01") + self.company_provincia = kwargs.get("company_provincia", "") + self.sdi_enabled = kwargs.get("sdi_enabled", False) + self.sdi_transport_url = kwargs.get("sdi_transport_url", "") + self.sdi_transport_token = kwargs.get("sdi_transport_token", "") + self.sdi_transmitter_id = kwargs.get("sdi_transmitter_id", "") + self.sdi_timeout = kwargs.get("sdi_timeout", 30) # PDF template customization self.invoice_pdf_template_html = kwargs.get("invoice_pdf_template_html", "") @@ -673,6 +690,14 @@ def to_dict(self): "company_country": getattr(self, "company_country", "") or "", "company_iban": getattr(self, "company_iban", "") or "", "company_bic": getattr(self, "company_bic", "") or "", + "company_codice_fiscale": getattr(self, "company_codice_fiscale", "") or "", + "company_regime_fiscale": getattr(self, "company_regime_fiscale", "") or "RF01", + "company_provincia": getattr(self, "company_provincia", "") or "", + "sdi_enabled": bool(getattr(self, "sdi_enabled", False)), + "sdi_transport_url": getattr(self, "sdi_transport_url", "") or "", + "sdi_transport_token_set": bool(getattr(self, "sdi_transport_token", "")), + "sdi_transmitter_id": getattr(self, "sdi_transmitter_id", "") or "", + "sdi_timeout": getattr(self, "sdi_timeout", None), "invoice_prefix": self.invoice_prefix, "invoice_number_pattern": self.invoice_number_pattern, "invoice_start_number": self.invoice_start_number, @@ -763,6 +788,7 @@ def to_dict(self): _SECRET_FIELDS = ( "mail_password", "peppol_access_point_token", + "sdi_transport_token", "ai_api_key", "jira_client_secret", "slack_client_secret", diff --git a/app/routes/admin.py b/app/routes/admin.py index e1292415c..a3c1c1068 100644 --- a/app/routes/admin.py +++ b/app/routes/admin.py @@ -1791,6 +1791,13 @@ def settings(): settings_obj.company_country = country settings_obj.company_iban = (request.form.get("company_iban", "") or "").strip().replace(" ", "") settings_obj.company_bic = (request.form.get("company_bic", "") or "").strip().replace(" ", "") + settings_obj.company_codice_fiscale = ( + request.form.get("company_codice_fiscale", "") or "" + ).strip().upper() + settings_obj.company_regime_fiscale = ( + request.form.get("company_regime_fiscale", "") or "RF01" + ).strip().upper() or "RF01" + settings_obj.company_provincia = (request.form.get("company_provincia", "") or "").strip().upper()[:2] except AttributeError: current_app.logger.debug("Company structured address columns not available", exc_info=True) @@ -1917,6 +1924,21 @@ def settings(): except AttributeError: current_app.logger.debug("Peppol settings columns not available (migration not run)", exc_info=True) + # Update SDI / FatturaPA settings (if columns exist) + try: + settings_obj.sdi_enabled = request.form.get("sdi_enabled") == "on" + settings_obj.sdi_transport_url = (request.form.get("sdi_transport_url", "") or "").strip() + sdi_token = (request.form.get("sdi_transport_token", "") or "").strip() + if sdi_token: + settings_obj.set_secret("sdi_transport_token", sdi_token) + try: + settings_obj.sdi_timeout = int(request.form.get("sdi_timeout", 30)) + except Exception: + settings_obj.sdi_timeout = 30 + settings_obj.sdi_transmitter_id = (request.form.get("sdi_transmitter_id", "") or "").strip() + except AttributeError: + current_app.logger.debug("SDI settings columns not available (migration not run)", exc_info=True) + # Update kiosk mode settings (if columns exist) try: settings_obj.kiosk_mode_enabled = request.form.get("kiosk_mode_enabled") == "on" diff --git a/app/routes/api_v1_invoices.py b/app/routes/api_v1_invoices.py index 772d1e8a7..fa7094c5e 100644 --- a/app/routes/api_v1_invoices.py +++ b/app/routes/api_v1_invoices.py @@ -451,3 +451,31 @@ def send_invoice_peppol_api(invoice_id): return jsonify(payload) payload["message"] = "Failed to send via Peppol" return jsonify(payload), 400 + + +@api_v1_invoices_bp.route("/invoices//send-sdi", methods=["POST"]) +@require_api_token("write:invoices") +def send_invoice_sdi_api(invoice_id): + """Token-auth SDI send — API twin of send_invoice_sdi_route.""" + from app.models import Invoice + from app.services import SdiService + + invoice = Invoice.query.get(invoice_id) + if not invoice: + return error_response("Invoice not found", status_code=404) + try: + service = SdiService() + success, tx, message = service.send_invoice(invoice=invoice, triggered_by_user_id=g.api_user.id) + except Exception as e: + current_app.logger.error(f"API SDI send failed: {type(e).__name__}: {e}") + return error_response("Failed to send via SDI", status_code=502) + payload = { + "success": success, + "message": message, + "sdi_tx_id": tx.id if tx else None, + "status": tx.status if tx else None, + "filename": tx.filename if tx else None, + } + if success: + return jsonify(payload) + return jsonify(payload), 400 diff --git a/app/routes/clients.py b/app/routes/clients.py index 2b5c7c428..d4fcf8fce 100644 --- a/app/routes/clients.py +++ b/app/routes/clients.py @@ -272,6 +272,12 @@ def create_client(): country = (request.form.get("country", "") or "").strip().upper()[:2] or None vat_id = sanitize_input(request.form.get("vat_id", "").strip(), max_length=50) leitweg_id = sanitize_input(request.form.get("leitweg_id", "").strip(), max_length=100) + sdi_codice_destinatario = sanitize_input( + request.form.get("sdi_codice_destinatario", "").strip(), max_length=7 + ) + pec_email = sanitize_input(request.form.get("pec_email", "").strip(), max_length=200) + codice_fiscale = sanitize_input(request.form.get("codice_fiscale", "").strip(), max_length=16) + provincia = sanitize_input(request.form.get("provincia", "").strip(), max_length=2) default_hourly_rate = request.form.get("default_hourly_rate", "").strip() prepaid_hours_input = request.form.get("prepaid_hours_monthly", "").strip() prepaid_reset_day_input = request.form.get("prepaid_reset_day", "").strip() @@ -384,6 +390,10 @@ def create_client(): country=country, vat_id=vat_id or None, leitweg_id=leitweg_id or None, + sdi_codice_destinatario=sdi_codice_destinatario or None, + pec_email=pec_email or None, + codice_fiscale=codice_fiscale or None, + provincia=provincia or None, default_hourly_rate=default_hourly_rate, prepaid_hours_monthly=prepaid_hours_monthly, prepaid_reset_day=prepaid_reset_day, @@ -627,6 +637,10 @@ def edit_client(client_id): country = (request.form.get("country", "") or "").strip().upper()[:2] or None vat_id = request.form.get("vat_id", "").strip() leitweg_id = request.form.get("leitweg_id", "").strip() + sdi_codice_destinatario = request.form.get("sdi_codice_destinatario", "").strip() + pec_email = request.form.get("pec_email", "").strip() + codice_fiscale = request.form.get("codice_fiscale", "").strip() + provincia = request.form.get("provincia", "").strip() default_hourly_rate = request.form.get("default_hourly_rate", "").strip() prepaid_hours_input = request.form.get("prepaid_hours_monthly", "").strip() prepaid_reset_day_input = request.form.get("prepaid_reset_day", "").strip() @@ -737,6 +751,10 @@ def edit_client(client_id): client.country = country client.vat_id = vat_id or None client.leitweg_id = leitweg_id or None + client.sdi_codice_destinatario = (sdi_codice_destinatario or "").strip().upper() or None + client.pec_email = pec_email or None + client.codice_fiscale = (codice_fiscale or "").strip().upper() or None + client.provincia = (provincia or "").strip().upper()[:2] or None client.default_hourly_rate = default_hourly_rate client.prepaid_hours_monthly = prepaid_hours_monthly client.prepaid_reset_day = prepaid_reset_day diff --git a/app/routes/invoices.py b/app/routes/invoices.py index ac2c261bb..164905c95 100644 --- a/app/routes/invoices.py +++ b/app/routes/invoices.py @@ -110,6 +110,8 @@ def create_invoice(): vat_category = None vat_exemption_reason = (request.form.get("vat_exemption_reason", "") or "").strip() or None vat_exemption_code = (request.form.get("vat_exemption_code", "") or "").strip() or None + cig = (request.form.get("cig", "") or "").strip() or None + cup = (request.form.get("cup", "") or "").strip() or None due_date_str = request.form.get("due_date", "").strip() tax_rate = request.form.get("tax_rate", "0").strip() notes = request.form.get("notes", "").strip() @@ -196,6 +198,8 @@ def create_invoice(): vat_category=vat_category, vat_exemption_reason=vat_exemption_reason, vat_exemption_code=vat_exemption_code, + cig=cig, + cup=cup, ) db.session.add(invoice) @@ -321,6 +325,40 @@ def view_invoice(invoice_id): ) peppol_history = [] + # SDI / FatturaPA history and readiness + sdi_history = [] + sdi_enabled_flag = False + sdi_recipient_ready = False + try: + from app.models import InvoiceSdiTransmission + from app.utils.fatturapa import resolve_codice_destinatario + + settings_for_sdi = Settings.get_settings() + sdi_enabled_flag = bool(getattr(settings_for_sdi, "sdi_enabled", False)) + sdi_history = ( + InvoiceSdiTransmission.query.filter_by(invoice_id=invoice_id) + .order_by(InvoiceSdiTransmission.created_at.desc()) + .all() + ) + try: + client = invoice.client + code, pec = resolve_codice_destinatario(client) if client else ("", None) + sdi_recipient_ready = bool(client and code) + except Exception: + current_app.logger.debug( + "Could not determine SDI recipient readiness for invoice %s", + invoice_id, + exc_info=True, + ) + sdi_recipient_ready = False + except Exception: + current_app.logger.debug( + "SDI history unavailable for invoice %s (migration may be pending)", + invoice_id, + exc_info=True, + ) + sdi_history = [] + # PEPPOL compliance warnings when invoices_peppol_compliant is on peppol_compliance_warnings = [] try: @@ -393,6 +431,9 @@ def view_invoice(invoice_id): peppol_recipient_ready=peppol_recipient_ready, peppol_compliance_warnings=peppol_compliance_warnings, invoices_peppol_compliant=getattr(Settings.get_settings(), "invoices_peppol_compliant", False), + sdi_history=sdi_history, + sdi_enabled=sdi_enabled_flag, + sdi_recipient_ready=sdi_recipient_ready, approval=approval, link_templates_by_field=link_templates_by_field, ) @@ -420,6 +461,8 @@ def edit_invoice(invoice_id): if _vc and _vc not in ("S", "Z", "E", "AE", "K", "G", "O", "L", "M"): _vc = None invoice.vat_category = _vc + invoice.cig = (request.form.get("cig", "") or "").strip() or None + invoice.cup = (request.form.get("cup", "") or "").strip() or None invoice.vat_exemption_reason = (request.form.get("vat_exemption_reason", "") or "").strip() or None invoice.vat_exemption_code = (request.form.get("vat_exemption_code", "") or "").strip() or None invoice.due_date = datetime.strptime(request.form.get("due_date"), "%Y-%m-%d").date() @@ -1312,6 +1355,50 @@ def export_invoice_xrechnung(invoice_id): return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) +@invoices_bp.route("/invoices//export/fatturapa") +@login_required +def export_invoice_fatturapa(invoice_id): + """Export invoice as FatturaPA 1.2 XML (FPR12 / FPA12).""" + from app.models import Settings + from app.utils.fatturapa import build_fatturapa_xml, progressivo_from_id, validate_fatturapa_ready + + invoice = Invoice.query.get_or_404(invoice_id) + if not current_user.is_admin and invoice.created_by != current_user.id: + flash(_("You do not have permission to export this invoice"), "error") + return safe_redirect( + request.referrer, allow_absolute_same_host=True, fallback=url_for("invoices.list_invoices") + ) + + settings = Settings.get_settings() + client = getattr(invoice, "client", None) + errors = validate_fatturapa_ready(invoice, settings, client) + if errors: + return Response( + json.dumps({"error": "fatturapa_not_ready", "messages": errors}), + status=400, + mimetype="application/json", + ) + + try: + progressivo = progressivo_from_id(invoice.id or 1) + xml, filename, _sha = build_fatturapa_xml(invoice, settings, client, progressivo) + return Response( + xml, mimetype="application/xml", headers={"Content-Disposition": f"attachment; filename={filename}"} + ) + except Exception as e: + from app.utils.error_reporting import log_and_capture + + log_and_capture( + current_app.logger, + "FatturaPA export failed for invoice %s", + invoice_id, + exc=e, + level="exception", + ) + flash(_("FatturaPA export failed. Please try again."), "error") + return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) + + @invoices_bp.route("/invoices//export/pdf") @login_required def export_invoice_pdf(invoice_id): @@ -1700,6 +1787,52 @@ def send_invoice_peppol_route(invoice_id): return client_error_response(status=500) +@invoices_bp.route("/invoices//send-sdi", methods=["POST"]) +@login_required +def send_invoice_sdi_route(invoice_id): + """Send invoice via SDI intermediary (FatturaPA).""" + invoice = Invoice.query.get_or_404(invoice_id) + + if not current_user.is_admin and invoice.created_by != current_user.id: + return jsonify({"error": "Permission denied"}), 403 + + try: + from app.services import SdiService + + service = SdiService() + success, tx, message = service.send_invoice(invoice=invoice, triggered_by_user_id=current_user.id) + if success: + flash(_("Invoice sent via SDI"), "success") + return jsonify( + {"success": True, "message": message or "Invoice sent via SDI", "sdi_tx_id": tx.id if tx else None} + ) + return jsonify( + {"error": message or "Failed to send invoice via SDI", "sdi_tx_id": tx.id if tx else None} + ), 400 + except Exception as e: + logger.error(f"Error sending invoice via SDI: {type(e).__name__}: {str(e)}") + logger.exception("Full error traceback:") + return client_error_response(status=500) + + +@invoices_bp.route("/invoices/sdi//refresh", methods=["POST"]) +@login_required +def refresh_sdi_transmission(tx_id): + """Refresh status of an SDI transmission from the intermediary.""" + from app.models import InvoiceSdiTransmission + from app.services import SdiService + + tx = InvoiceSdiTransmission.query.get_or_404(tx_id) + invoice = Invoice.query.get_or_404(tx.invoice_id) + if not current_user.is_admin and invoice.created_by != current_user.id: + return jsonify({"error": "Permission denied"}), 403 + + result = SdiService().refresh_status(tx) + if not result.get("ok"): + return jsonify({"error": result.get("error") or "Refresh failed"}), 400 + return jsonify({"success": True, "status": result.get("status"), "transmission": tx.to_dict()}) + + @invoices_bp.route("/invoices//email-history", methods=["GET"]) @login_required def get_invoice_email_history(invoice_id): diff --git a/app/services/__init__.py b/app/services/__init__.py index 9bcb56a60..f868e18a6 100644 --- a/app/services/__init__.py +++ b/app/services/__init__.py @@ -16,6 +16,7 @@ from .notification_service import NotificationService from .payment_service import PaymentService from .peppol_service import PeppolService +from .sdi_service import SdiService from .permission_service import PermissionService from .project_service import ProjectService from .quote_service import QuoteService @@ -44,6 +45,7 @@ "ImportService", "EmailService", "PeppolService", + "SdiService", "PermissionService", "BackupService", "HealthService", diff --git a/app/services/sdi_service.py b/app/services/sdi_service.py new file mode 100644 index 000000000..bd35903f9 --- /dev/null +++ b/app/services/sdi_service.py @@ -0,0 +1,192 @@ +"""Italian SDI (FatturaPA) transmission service.""" + +from __future__ import annotations + +import logging +from datetime import datetime, timedelta +from typing import Any, List, Optional, Tuple + +from flask import current_app + +from app import db +from app.integrations.sdi_transport import GenericSdiTransport, SdiTransportError +from app.models import InvoiceSdiTransmission, Settings +from app.models.invoice_sdi import SDI_FINAL_STATUSES +from app.utils.db import safe_commit +from app.utils.fatturapa import ( + build_fatturapa_xml, + determine_formato, + progressivo_from_id, + resolve_codice_destinatario, + validate_fatturapa_ready, +) + +logger = logging.getLogger(__name__) + + +class SdiService: + """Build FatturaPA XML and send via a configured SDI intermediary.""" + + def _transport(self, settings: Any) -> GenericSdiTransport: + url = (getattr(settings, "sdi_transport_url", "") or "").strip() + token = "" + try: + token = (settings.get_secret("sdi_transport_token") or "").strip() + except Exception: + token = (getattr(settings, "sdi_transport_token", "") or "").strip() + try: + timeout = int(getattr(settings, "sdi_timeout", 0) or 0) or 30 + except Exception: + timeout = 30 + return GenericSdiTransport(url=url, token=token or None, timeout=timeout) + + def send_invoice( + self, invoice, triggered_by_user_id: Optional[int] = None + ) -> Tuple[bool, Optional[InvoiceSdiTransmission], str]: + settings = Settings.get_settings() + if not bool(getattr(settings, "sdi_enabled", False)): + return False, None, "SDI is not enabled" + + client = getattr(invoice, "client", None) + errors = validate_fatturapa_ready(invoice, settings, client) + if errors: + return False, None, "; ".join(errors) + + if not (getattr(settings, "sdi_transport_url", "") or "").strip(): + return False, None, "SDI transport URL is not configured" + + formato = determine_formato(client) + codice_dest, pec = resolve_codice_destinatario(client) + + tx = InvoiceSdiTransmission( + invoice_id=invoice.id, + status="pending", + formato=formato, + progressivo="", # filled after we have an id + ) + db.session.add(tx) + if not safe_commit("sdi_create_transmission", {"invoice_id": invoice.id}): + return False, None, "Database error while creating SDI transmission" + + progressivo = progressivo_from_id(tx.id) + try: + xml, filename, sha256_hex = build_fatturapa_xml(invoice, settings, client, progressivo) + except Exception: + current_app.logger.exception("Failed to build FatturaPA XML") + tx.mark_failed("Failed to build FatturaPA XML") + safe_commit("sdi_mark_failed_build", {"invoice_id": invoice.id, "tx_id": tx.id}) + return False, tx, "Failed to build FatturaPA XML" + + tx.progressivo = progressivo + tx.filename = filename + tx.xml = xml + tx.xml_sha256 = sha256_hex + safe_commit("sdi_store_xml", {"invoice_id": invoice.id, "tx_id": tx.id}) + + try: + transport = self._transport(settings) + resp = transport.send( + filename=filename, + formato=formato, + codice_destinatario=codice_dest, + pec=pec, + xml=xml, + sha256=sha256_hex, + ) + message_id = resp.get("message_id") or resp.get("messageId") or resp.get("id") + sdi_id = resp.get("sdi_identifier") or resp.get("sdiIdentifier") + tx.mark_sent(message_id=message_id, sdi_identifier=sdi_id, response_payload=resp) + if not safe_commit("sdi_mark_sent", {"invoice_id": invoice.id, "tx_id": tx.id}): + return True, tx, "Sent via SDI, but failed to persist send status" + return True, tx, "Invoice sent via SDI" + except SdiTransportError as e: + tx.mark_failed(str(e)) + safe_commit("sdi_mark_failed", {"invoice_id": invoice.id, "tx_id": tx.id}) + current_app.logger.exception("SDI send failed") + return False, tx, f"SDI send failed: {e}" + except Exception as e: + tx.mark_failed(type(e).__name__) + safe_commit("sdi_mark_failed", {"invoice_id": invoice.id, "tx_id": tx.id}) + current_app.logger.exception("SDI send failed") + return False, tx, "SDI send failed" + + def refresh_status(self, tx: InvoiceSdiTransmission) -> dict: + """Poll intermediary for status and apply notifications.""" + if not tx.message_id: + return {"ok": False, "error": "No message_id on transmission"} + if tx.status in SDI_FINAL_STATUSES: + return {"ok": True, "status": tx.status, "skipped": True} + + settings = Settings.get_settings() + try: + transport = self._transport(settings) + data = transport.get_status(tx.message_id) + except SdiTransportError as e: + return {"ok": False, "error": str(e)} + except Exception as e: + current_app.logger.exception("SDI status refresh failed") + return {"ok": False, "error": str(e)} + + sdi_id = data.get("sdi_identifier") or data.get("sdiIdentifier") + if sdi_id: + tx.sdi_identifier = str(sdi_id) + + notifications = data.get("notifications") or [] + if isinstance(notifications, list): + for n in notifications: + if not isinstance(n, dict): + continue + ntype = n.get("type") or n.get("Tipo") or "" + # Avoid re-applying identical notification types already stored + existing = {(x.get("type") or "").upper() for x in (tx.notifications or []) if isinstance(x, dict)} + if str(ntype).upper() in existing and str(ntype).upper() not in ("NE",): + # Still allow NE updates; skip exact duplicate types for others + continue + tx.apply_notification(ntype, detail=n.get("detail") or n.get("Descrizione"), date=n.get("date")) + + # Fallback: intermediary may return a top-level status string + top_status = (data.get("status") or "").strip().lower() + if top_status and top_status in { + "sent", + "delivered", + "not_delivered", + "rejected", + "accepted", + "refused", + "expired", + "failed", + "pending", + }: + # Only upgrade if we didn't get richer notification mapping + if not notifications: + tx.status = top_status + tx.updated_at = datetime.utcnow() + + safe_commit("sdi_refresh_status", {"tx_id": tx.id}) + return {"ok": True, "status": tx.status, "data": data} + + def poll_pending(self, max_age_days: int = 30) -> int: + """Refresh non-final transmissions newer than max_age_days. Returns count refreshed.""" + settings = Settings.get_settings() + if not bool(getattr(settings, "sdi_enabled", False)): + return 0 + if not (getattr(settings, "sdi_transport_url", "") or "").strip(): + return 0 + + cutoff = datetime.utcnow() - timedelta(days=max_age_days) + pending: List[InvoiceSdiTransmission] = ( + InvoiceSdiTransmission.query.filter( + InvoiceSdiTransmission.status.notin_(list(SDI_FINAL_STATUSES)), + InvoiceSdiTransmission.created_at >= cutoff, + InvoiceSdiTransmission.message_id.isnot(None), + ) + .order_by(InvoiceSdiTransmission.created_at.asc()) + .limit(100) + .all() + ) + count = 0 + for tx in pending: + result = self.refresh_status(tx) + if result.get("ok"): + count += 1 + return count diff --git a/app/templates/admin/settings.html b/app/templates/admin/settings.html index 36f4e7ca6..71f0c9c7a 100644 --- a/app/templates/admin/settings.html +++ b/app/templates/admin/settings.html @@ -36,6 +36,7 @@ Invoices Quotes Peppol + SDI / FatturaPA Backup LDAP Kiosk @@ -395,6 +396,27 @@

{{ _('Company Branding') }}

+

{{ _('Italian sellers: Partita IVA, e.g. IT01234567890.') }}

+
+
+ + +
+
+ + +
+
+ +
@@ -626,6 +648,44 @@

Peppol e-Invoicing

+ +
+

{{ _('SDI / FatturaPA (Italy)') }}

+

+ {{ _('Generate FatturaPA XML and send invoices to the Italian Sistema di Interscambio through your accredited intermediary. See docs/admin/configuration/FATTURAPA_SDI.md for the HTTP adapter contract.') }} +

+
+
+ +
+ +

+ {{ _('When enabled, invoices can be sent via SDI using your configured intermediary URL.') }} +

+
+
+
+ + +
+
+ + +

+ {{ _('For security, the token is not shown. Leave blank to keep the current token.') }} +

+
+
+ + +
+
+ + +
+
+
+

{{ _('Backup Settings') }}

diff --git a/app/templates/clients/create.html b/app/templates/clients/create.html index 7d5e30ea6..eb04c5d53 100644 --- a/app/templates/clients/create.html +++ b/app/templates/clients/create.html @@ -97,6 +97,23 @@
+
+ + +

{{ _('6 characters = public administration (FPA12); 7 characters = B2B (FPR12). Use 0000000 with PEC.') }}

+
+
+ + +
+
+ + +
+
+ + +
{% if custom_field_definitions %} diff --git a/app/templates/clients/edit.html b/app/templates/clients/edit.html index b3b9be91b..aef205925 100644 --- a/app/templates/clients/edit.html +++ b/app/templates/clients/edit.html @@ -91,6 +91,23 @@ +
+ + +

{{ _('6 characters = public administration (FPA12); 7 characters = B2B (FPR12). Use 0000000 with PEC.') }}

+
+
+ + +
+
+ + +
+
+ + +
{% if custom_field_definitions %} diff --git a/app/templates/invoices/create.html b/app/templates/invoices/create.html index 3a9e8b76e..186f32c64 100644 --- a/app/templates/invoices/create.html +++ b/app/templates/invoices/create.html @@ -65,6 +65,14 @@ +
+ + +
+
+ + +
diff --git a/app/templates/invoices/edit.html b/app/templates/invoices/edit.html index 08bb7aaff..4fbdf5680 100644 --- a/app/templates/invoices/edit.html +++ b/app/templates/invoices/edit.html @@ -64,6 +64,14 @@
+
+ + +
+
+ + +
diff --git a/app/templates/invoices/view.html b/app/templates/invoices/view.html index 82bea99a3..1e32743f6 100644 --- a/app/templates/invoices/view.html +++ b/app/templates/invoices/view.html @@ -35,6 +35,17 @@ {{ _('Download XRechnung') }} + + {{ _('Download FatturaPA') }} + +{% if sdi_enabled %} + +{% endif %} {% if invoice.status != 'paid' and invoice.status != 'cancelled' %} {{ _('Pay Online') }} @@ -456,6 +467,55 @@

{% endif %} + +{% if sdi_history is defined and sdi_history|length > 0 %} +
+

+ {{ _('SDI History') }} +

+
+ + + + + + + + + + + + + + {% for tx in sdi_history %} + + + + + + + + + + {% endfor %} + +
{{ _('Created') }}{{ _('Status') }}{{ _('Format') }}{{ _('Filename') }}{{ _('Message ID') }}{{ _('Error') }}
{{ tx.created_at|user_datetime if tx.created_at else 'N/A' }} + + {{ tx.status|title }} + + {{ tx.formato or '—' }}{{ tx.filename or '—' }}{{ tx.message_id or '—' }}{{ tx.error_message or '—' }} + {% if tx.message_id and tx.status not in ('delivered', 'not_delivered', 'rejected', 'accepted', 'refused', 'expired', 'failed') %} + + {% endif %} +
+
+
+{% endif %} + {% if peppol_history is defined and peppol_history|length > 0 %}
@@ -769,5 +829,78 @@

{{ _('Send } }); } + +async function sendInvoiceSdi() { + {% if not sdi_recipient_ready %} + return; + {% endif %} + + if (!(await ttConfirm({{ _('Send this invoice via SDI?')|tojson }}, { confirmText: {{ _('Send')|tojson }} }))) { + return; + } + + const body = new FormData(); + body.append('csrf_token', "{{ csrf_token() }}"); + + fetch("{{ url_for('invoices.send_invoice_sdi_route', invoice_id=invoice.id) }}", { + method: 'POST', + body + }) + .then(async response => { + const contentType = response.headers.get('content-type') || ''; + const isJson = contentType.includes('application/json'); + const data = isJson ? await response.json() : { error: await response.text() }; + if (!response.ok) { + throw new Error(data.error || data.message || `HTTP ${response.status}: ${response.statusText}`); + } + return data; + }) + .then(data => { + if (data.success) { + if (window.toastManager) { + window.toastManager.success(data.message || {{ _('Sent via SDI')|tojson }}); + } else { + ttAlert(data.message || {{ _('Sent via SDI')|tojson }}); + } + setTimeout(() => window.location.reload(), 800); + } else { + const errorMsg = data.error || {{ _('Failed to send via SDI')|tojson }}; + if (window.toastManager) { + window.toastManager.error(errorMsg); + } else { + ttAlert('Error: ' + errorMsg); + } + } + }) + .catch(err => { + const msg = err && err.message ? err.message : {{ _('Failed to send via SDI')|tojson }}; + if (window.toastManager) { + window.toastManager.error(msg); + } else { + ttAlert('Error: ' + msg); + } + }); +} + +async function refreshSdiTx(txId) { + const body = new FormData(); + body.append('csrf_token', "{{ csrf_token() }}"); + fetch(`/invoices/sdi/${txId}/refresh`, { method: 'POST', body }) + .then(async response => { + const data = await response.json(); + if (!response.ok) { + throw new Error(data.error || 'Refresh failed'); + } + return data; + }) + .then(() => window.location.reload()) + .catch(err => { + if (window.toastManager) { + window.toastManager.error(err.message || 'Refresh failed'); + } else { + ttAlert('Error: ' + (err.message || 'Refresh failed')); + } + }); +} {% endblock %} diff --git a/app/utils/fatturapa.py b/app/utils/fatturapa.py new file mode 100644 index 000000000..96b589272 --- /dev/null +++ b/app/utils/fatturapa.py @@ -0,0 +1,536 @@ +""" +FatturaPA 1.2 XML export helpers (FPR12 B2B / FPA12 public administration). + +Builds Italian electronic invoices under the Agenzia delle Entrate schema. +Transmission to SDI is handled separately via SdiService + GenericSdiTransport. +""" + +from __future__ import annotations + +import hashlib +import re +import xml.etree.ElementTree as ET +from decimal import Decimal, ROUND_HALF_UP +from typing import Any, Dict, List, Optional, Tuple + +FATTURAPA_NS = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" +FATTURAPA_VERSION_FPR = "FPR12" +FATTURAPA_VERSION_FPA = "FPA12" + +# Map EN 16931 / Factur-X VAT categories to FatturaPA Natura codes (0% lines) +_VAT_CATEGORY_TO_NATURA = { + "Z": "N2.2", + "O": "N2.2", + "E": "N4", + "AE": "N6.9", + "K": "N3.2", + "G": "N3.1", +} + +_NATURA_RE = re.compile(r"^N\d(\.\d+)?$") +_BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + +def fatturapa_export_available() -> bool: + return True + + +def _strip(v: Any) -> str: + return (v or "").strip() if v is not None else "" + + +def _money(value: Any, places: int = 2) -> str: + q = Decimal("1").scaleb(-places) + try: + d = Decimal(str(value if value is not None else 0)) + except Exception: + d = Decimal("0") + return str(d.quantize(q, rounding=ROUND_HALF_UP)) + + +def _unit_price(value: Any) -> str: + """Amount8DecimalType: require at least 2 decimal places, up to 8.""" + raw = _money(value, places=8) + # Trim trailing zeros but keep at least two fractional digits (XSD pattern). + if "." in raw: + whole, frac = raw.split(".", 1) + frac = frac.rstrip("0").ljust(2, "0") + return f"{whole}.{frac}" + return f"{raw}.00" + + +def _qty(value: Any) -> str: + """QuantityType: [0-9]{1,12}\\.[0-9]{2,8}""" + return _unit_price(value) + + +def progressivo_from_id(n: int) -> str: + """Encode a positive integer as a 5-character base36 ProgressivoInvio.""" + if n < 1: + n = 1 + chars: List[str] = [] + x = n + while x > 0: + chars.append(_BASE36[x % 36]) + x //= 36 + s = "".join(reversed(chars)) or "1" + return s.zfill(5)[-5:] + + +def determine_formato(client: Any) -> str: + """FPA12 for 6-char PA codes, otherwise FPR12 (B2B).""" + code = _strip(getattr(client, "sdi_codice_destinatario", None)).upper() + if len(code) == 6 and code not in ("000000", "XXXXXX"): + return FATTURAPA_VERSION_FPA + return FATTURAPA_VERSION_FPR + + +def resolve_codice_destinatario(client: Any) -> Tuple[str, Optional[str]]: + """ + Return (CodiceDestinatario, PECDestinatario or None). + - Explicit SDI code when set + - 0000000 + PEC when only PEC is available (B2B) + - XXXXXXX for foreign buyers without an Italian SDI code + """ + code = _strip(getattr(client, "sdi_codice_destinatario", None)).upper() + pec = _strip(getattr(client, "pec_email", None)) + country = _strip(getattr(client, "country", None)).upper() or "IT" + + if code: + return code, pec if code == "0000000" and pec else (None if code != "0000000" else pec or None) + + if country and country != "IT": + return "XXXXXXX", None + + if pec: + return "0000000", pec + + return "", None + + +def _vat_category(invoice: Any, settings: Any) -> str: + cat = _strip(getattr(invoice, "vat_category", None)) + if cat: + return cat.upper() + return (_strip(getattr(settings, "invoices_default_vat_category", None)) or "S").upper() + + +def _exemption_code(invoice: Any, settings: Any) -> str: + code = _strip(getattr(invoice, "vat_exemption_code", None)) + if not code: + code = _strip(getattr(settings, "invoices_default_vat_exemption_code", None)) + return code + + +def _exemption_reason(invoice: Any, settings: Any) -> str: + reason = _strip(getattr(invoice, "vat_exemption_reason", None)) + if not reason: + reason = _strip(getattr(settings, "invoices_default_vat_exemption_reason", None)) + return reason + + +def resolve_natura(invoice: Any, settings: Any, tax_rate: Decimal) -> Optional[str]: + """Return Natura code for 0% lines, else None.""" + if tax_rate > 0: + return None + raw = _exemption_code(invoice, settings) + if raw and _NATURA_RE.match(raw): + return raw + cat = _vat_category(invoice, settings) + if cat == "S": + # Standard category with 0% is unusual; treat as non-taxable + return "N2.2" + return _VAT_CATEGORY_TO_NATURA.get(cat, "N2.2") + + +def _italian_id_parts(tax_id: str, codice_fiscale: str = "") -> Tuple[str, str, Optional[str]]: + """ + Return (IdPaese, IdCodice for IdFiscaleIVA, CodiceFiscale or None). + Prefer P.IVA (11 digits) for IdFiscaleIVA; CF goes in CodiceFiscale. + """ + vat = re.sub(r"[\s.]", "", tax_id or "") + cf = re.sub(r"[\s.]", "", codice_fiscale or "").upper() + + country = "IT" + digits = vat + if len(vat) >= 3 and vat[:2].isalpha(): + country = vat[:2].upper() + digits = vat[2:] + + id_codice = digits or None + codice_fiscale_out = cf or None + + # If only CF provided (16 chars alphanumeric), use it as CodiceFiscale and + # for sole traders without P.IVA put CF into IdCodice as well when needed. + if not id_codice and cf: + if len(cf) == 11 and cf.isdigit(): + id_codice = cf + codice_fiscale_out = None + else: + id_codice = cf + + return country, id_codice or "", codice_fiscale_out + + +def validate_fatturapa_ready(invoice: Any, settings: Any, client: Any) -> List[str]: + """Return human-readable messages for missing mandatory FatturaPA fields.""" + issues: List[str] = [] + + if not _strip(getattr(settings, "company_name", None)): + issues.append("Settings: company name is required (seller).") + if not ( + _strip(getattr(settings, "company_street", None)) or _strip(getattr(settings, "company_address", None)) + ): + issues.append("Settings: company street or address is required.") + if not _strip(getattr(settings, "company_postcode", None)): + issues.append("Settings: company postcode (CAP) is required.") + if not _strip(getattr(settings, "company_city", None)): + issues.append("Settings: company city is required.") + country = _strip(getattr(settings, "company_country", None)).upper() + if not country: + issues.append("Settings: company country (ISO 2) is required.") + elif country == "IT" and not _strip(getattr(settings, "company_provincia", None)): + issues.append("Settings: company provincia (2 letters) is required for Italian sellers.") + if not _strip(getattr(settings, "company_regime_fiscale", None)): + issues.append("Settings: RegimeFiscale is required (e.g. RF01).") + + tax_id = _strip(getattr(settings, "company_tax_id", None)) + cf = _strip(getattr(settings, "company_codice_fiscale", None)) + if not tax_id and not cf: + issues.append("Settings: company VAT ID (Partita IVA) or Codice Fiscale is required.") + + if client is None: + issues.append("Invoice must be linked to a client.") + else: + if not _strip(getattr(client, "name", None)): + issues.append("Client: name is required.") + if not (_strip(getattr(client, "street", None)) or _strip(getattr(client, "address", None))): + issues.append("Client: street or address is required.") + if not _strip(getattr(client, "postcode", None)): + issues.append("Client: postcode (CAP) is required.") + if not _strip(getattr(client, "city", None)): + issues.append("Client: city is required.") + c_country = _strip(getattr(client, "country", None)).upper() + if not c_country: + issues.append("Client: country (ISO 2) is required.") + elif c_country == "IT" and not _strip(getattr(client, "provincia", None)): + issues.append("Client: provincia (2 letters) is required for Italian buyers.") + + c_vat = _strip(getattr(client, "vat_id", None)) + if not c_vat and hasattr(client, "get_custom_field"): + c_vat = _strip(client.get_custom_field("vat_id", "") or client.get_custom_field("tax_id", "")) + c_cf = _strip(getattr(client, "codice_fiscale", None)) + if not c_vat and not c_cf: + issues.append("Client: VAT ID (Partita IVA) or Codice Fiscale is required.") + + code, pec = resolve_codice_destinatario(client) + if not code: + issues.append("Client: SDI Codice Destinatario or PEC email is required.") + formato = determine_formato(client) + if formato == FATTURAPA_VERSION_FPA and len(code) != 6: + issues.append("Client: public administration invoices require a 6-character Codice Destinatario.") + if code == "0000000" and not pec: + issues.append("Client: PEC email is required when Codice Destinatario is 0000000.") + + if not _strip(getattr(invoice, "invoice_number", None)): + issues.append("Invoice number is required.") + + return issues + + +def _sub(parent: ET.Element, tag: str) -> ET.Element: + # Local elements are unqualified (elementFormDefault=unqualified in the XSD). + return ET.SubElement(parent, tag) + + +def _set_text(parent: ET.Element, tag: str, text: str) -> ET.Element: + el = _sub(parent, tag) + el.text = text + return el + + +def _add_id_fiscale_iva(parent: ET.Element, paese: str, codice: str) -> None: + block = _sub(parent, "IdFiscaleIVA") + _set_text(block, "IdPaese", paese) + _set_text(block, "IdCodice", codice) + + +def _add_address( + parent: ET.Element, + *, + street: str, + postcode: str, + city: str, + provincia: str, + country: str, +) -> None: + addr = _sub(parent, "Sede") + _set_text(addr, "Indirizzo", (street or "N/A")[:60]) + nation = (country or "IT").upper()[:2] + if nation != "IT": + cap = "00000" + else: + digits = re.sub(r"\D", "", postcode or "") + cap = digits[:5].zfill(5) if digits else "00000" + _set_text(addr, "CAP", cap) + _set_text(addr, "Comune", (city or "N/A")[:60]) + if nation == "IT" and provincia: + _set_text(addr, "Provincia", provincia.upper()[:2]) + _set_text(addr, "Nazione", nation) + + +def _collect_lines(invoice: Any) -> List[Dict[str, Any]]: + lines: List[Dict[str, Any]] = [] + try: + for it in list(getattr(invoice, "items", []) or []): + lines.append( + { + "description": _strip(getattr(it, "description", None)) or "Item", + "quantity": getattr(it, "quantity", 1) or 1, + "unit_price": getattr(it, "unit_price", 0) or 0, + "line_total": getattr(it, "total_amount", 0) or 0, + } + ) + except Exception: + pass + try: + expenses_rel = getattr(invoice, "expenses", None) + for ex in list(expenses_rel) if expenses_rel is not None else []: + desc = _strip(getattr(ex, "title", None)) or "Expense" + if getattr(ex, "vendor", None): + desc = f"{desc} ({ex.vendor})" + amt = getattr(ex, "total_amount", 0) or 0 + lines.append({"description": desc, "quantity": 1, "unit_price": amt, "line_total": amt}) + except Exception: + pass + try: + goods_rel = getattr(invoice, "extra_goods", None) + for g in list(goods_rel) if goods_rel is not None else []: + lines.append( + { + "description": _strip(getattr(g, "name", None)) or "Good", + "quantity": getattr(g, "quantity", 1) or 1, + "unit_price": getattr(g, "unit_price", 0) or 0, + "line_total": getattr(g, "total_amount", 0) or 0, + } + ) + except Exception: + pass + if not lines: + # Fallback single line from invoice totals + subtotal = getattr(invoice, "subtotal", None) or getattr(invoice, "total_amount", 0) or 0 + lines.append( + { + "description": _strip(getattr(invoice, "notes", None)) or "Services", + "quantity": 1, + "unit_price": subtotal, + "line_total": subtotal, + } + ) + return lines + + +def _transmitter_id(settings: Any) -> str: + tid = _strip(getattr(settings, "sdi_transmitter_id", None)) + if tid: + # Strip country prefix if present + if len(tid) > 2 and tid[:2].isalpha(): + return re.sub(r"[\s.]", "", tid[2:]) + return re.sub(r"[\s.]", "", tid) + cf = _strip(getattr(settings, "company_codice_fiscale", None)) + if cf: + return re.sub(r"[\s.]", "", cf) + tax = _strip(getattr(settings, "company_tax_id", None)) + if tax: + if len(tax) >= 3 and tax[:2].isalpha(): + return re.sub(r"[\s.]", "", tax[2:]) + return re.sub(r"[\s.]", "", tax) + return "00000000000" + + +def build_fatturapa_filename(transmitter_id: str, progressivo: str) -> str: + tid = re.sub(r"[^A-Za-z0-9]", "", transmitter_id or "")[:16] + prog = (progressivo or "00001")[:10] + return f"IT{tid}_{prog}.xml" + + +def build_fatturapa_xml( + invoice: Any, + settings: Any, + client: Any, + progressivo: str, +) -> Tuple[str, str, str]: + """ + Build FatturaPA 1.2 XML. + Returns (xml_string, filename, sha256_hex). + Call validate_fatturapa_ready first in routes. + """ + formato = determine_formato(client) + codice_dest, pec_dest = resolve_codice_destinatario(client) + transmitter = _transmitter_id(settings) + progressivo = (progressivo or progressivo_from_id(getattr(invoice, "id", 1) or 1))[:10] + + try: + tax_rate = Decimal(str(getattr(invoice, "tax_rate", 0) or 0)) + except Exception: + tax_rate = Decimal("0") + natura = resolve_natura(invoice, settings, tax_rate) + rif_norm = _exemption_reason(invoice, settings) if natura else "" + + # Keep a named prefix (not default xmlns) so unqualified local children stay + # in no-namespace, matching the official XSD elementFormDefault. + ET.register_namespace("p", FATTURAPA_NS) + root = ET.Element(f"{{{FATTURAPA_NS}}}FatturaElettronica") + root.set("versione", formato) + + header = _sub(root, "FatturaElettronicaHeader") + + # --- DatiTrasmissione --- + dt = _sub(header, "DatiTrasmissione") + id_tr = _sub(dt, "IdTrasmittente") + _set_text(id_tr, "IdPaese", "IT") + _set_text(id_tr, "IdCodice", transmitter) + _set_text(dt, "ProgressivoInvio", progressivo) + _set_text(dt, "FormatoTrasmissione", formato) + _set_text(dt, "CodiceDestinatario", codice_dest or "0000000") + if pec_dest and (codice_dest or "") == "0000000": + _set_text(dt, "PECDestinatario", pec_dest) + + # --- CedentePrestatore (seller) --- + seller_vat = _strip(getattr(settings, "company_tax_id", None)) + seller_cf = _strip(getattr(settings, "company_codice_fiscale", None)) + s_paese, s_codice, s_cf = _italian_id_parts(seller_vat, seller_cf) + + cedente = _sub(header, "CedentePrestatore") + dati_anag = _sub(cedente, "DatiAnagrafici") + if s_codice: + _add_id_fiscale_iva(dati_anag, s_paese, s_codice) + if s_cf: + _set_text(dati_anag, "CodiceFiscale", s_cf) + anagrafica = _sub(dati_anag, "Anagrafica") + _set_text(anagrafica, "Denominazione", _strip(getattr(settings, "company_name", None))[:80] or "Company") + _set_text(dati_anag, "RegimeFiscale", _strip(getattr(settings, "company_regime_fiscale", None)) or "RF01") + + seller_street = _strip(getattr(settings, "company_street", None)) or _strip( + getattr(settings, "company_address", None) + ) + _add_address( + cedente, + street=seller_street, + postcode=_strip(getattr(settings, "company_postcode", None)), + city=_strip(getattr(settings, "company_city", None)), + provincia=_strip(getattr(settings, "company_provincia", None)), + country=_strip(getattr(settings, "company_country", None)) or "IT", + ) + + # --- CessionarioCommittente (buyer) --- + buyer_vat = _strip(getattr(client, "vat_id", None)) + if not buyer_vat and hasattr(client, "get_custom_field"): + buyer_vat = _strip(client.get_custom_field("vat_id", "") or client.get_custom_field("tax_id", "")) + buyer_cf = _strip(getattr(client, "codice_fiscale", None)) + b_paese, b_codice, b_cf = _italian_id_parts(buyer_vat, buyer_cf) + buyer_country = _strip(getattr(client, "country", None)).upper() or b_paese or "IT" + if buyer_country != "IT" and not b_paese: + b_paese = buyer_country + + cessionario = _sub(header, "CessionarioCommittente") + c_dati = _sub(cessionario, "DatiAnagrafici") + if b_codice: + _add_id_fiscale_iva(c_dati, b_paese or buyer_country, b_codice) + if b_cf: + _set_text(c_dati, "CodiceFiscale", b_cf) + c_anag = _sub(c_dati, "Anagrafica") + buyer_name = _strip(getattr(client, "name", None) or getattr(invoice, "client_name", None)) or "Customer" + _set_text(c_anag, "Denominazione", buyer_name[:80]) + + buyer_street = _strip(getattr(client, "street", None)) or _strip(getattr(client, "address", None)) + _add_address( + cessionario, + street=buyer_street, + postcode=_strip(getattr(client, "postcode", None)), + city=_strip(getattr(client, "city", None)), + provincia=_strip(getattr(client, "provincia", None)), + country=buyer_country, + ) + + # --- Body --- + body = _sub(root, "FatturaElettronicaBody") + dati_gen = _sub(body, "DatiGenerali") + dgd = _sub(dati_gen, "DatiGeneraliDocumento") + _set_text(dgd, "TipoDocumento", "TD01") + currency = (_strip(getattr(invoice, "currency_code", None)) or "EUR").upper()[:3] + _set_text(dgd, "Divisa", currency) + issue = getattr(invoice, "issue_date", None) + issue_s = issue.isoformat() if hasattr(issue, "isoformat") else str(issue or "")[:10] + _set_text(dgd, "Data", issue_s) + _set_text(dgd, "Numero", _strip(getattr(invoice, "invoice_number", None))[:20]) + total = getattr(invoice, "total_amount", 0) or 0 + _set_text(dgd, "ImportoTotaleDocumento", _money(total)) + + cig = _strip(getattr(invoice, "cig", None)) + cup = _strip(getattr(invoice, "cup", None)) + if cig or cup: + ordine = _sub(dati_gen, "DatiOrdineAcquisto") + _set_text(ordine, "IdDocumento", _strip(getattr(invoice, "invoice_number", None))[:20] or "1") + if cig: + _set_text(ordine, "CodiceCIG", cig[:15]) + if cup: + _set_text(ordine, "CodiceCUP", cup[:15]) + + # Line items + beni = _sub(body, "DatiBeniServizi") + lines = _collect_lines(invoice) + taxable_sum = Decimal("0") + for idx, line in enumerate(lines, start=1): + det = _sub(beni, "DettaglioLinee") + _set_text(det, "NumeroLinea", str(idx)) + _set_text(det, "Descrizione", str(line["description"])[:1000]) + _set_text(det, "Quantita", _qty(line["quantity"])) + _set_text(det, "PrezzoUnitario", _unit_price(line["unit_price"])) + line_total = Decimal(str(line["line_total"] or 0)) + taxable_sum += line_total + _set_text(det, "PrezzoTotale", _money(line_total)) + _set_text(det, "AliquotaIVA", _money(tax_rate)) + if natura: + _set_text(det, "Natura", natura) + + # Prefer invoice subtotal when present + try: + inv_sub = Decimal(str(getattr(invoice, "subtotal", None) or taxable_sum)) + except Exception: + inv_sub = taxable_sum + try: + inv_tax = Decimal(str(getattr(invoice, "tax_amount", None) or 0)) + except Exception: + inv_tax = (inv_sub * tax_rate / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + riep = _sub(beni, "DatiRiepilogo") + _set_text(riep, "AliquotaIVA", _money(tax_rate)) + if natura: + _set_text(riep, "Natura", natura) + _set_text(riep, "ImponibileImporto", _money(inv_sub)) + _set_text(riep, "Imposta", _money(inv_tax)) + _set_text(riep, "EsigibilitaIVA", "I") + if rif_norm: + _set_text(riep, "RiferimentoNormativo", rif_norm[:100]) + + # Payment + iban = _strip(getattr(settings, "company_iban", None)) + due = getattr(invoice, "due_date", None) + if iban or due: + pag = _sub(body, "DatiPagamento") + _set_text(pag, "CondizioniPagamento", "TP02") + det_pag = _sub(pag, "DettaglioPagamento") + _set_text(det_pag, "ModalitaPagamento", "MP05") + if due and hasattr(due, "isoformat"): + _set_text(det_pag, "DataScadenzaPagamento", due.isoformat()) + _set_text(det_pag, "ImportoPagamento", _money(total)) + if iban: + _set_text(det_pag, "IBAN", iban.replace(" ", "")) + + xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True) + xml_str = xml_bytes.decode("utf-8") + + filename = build_fatturapa_filename(transmitter, progressivo) + sha256_hex = hashlib.sha256(xml_str.encode("utf-8")).hexdigest() + return xml_str, filename, sha256_hex diff --git a/app/utils/scheduled_tasks.py b/app/utils/scheduled_tasks.py index 42333a1c0..331ca660c 100644 --- a/app/utils/scheduled_tasks.py +++ b/app/utils/scheduled_tasks.py @@ -735,6 +735,28 @@ def poll_peppol_inbox_with_app(): ) logger.info("Registered Peppol inbox poll task") + def poll_sdi_status_with_app(): + app_instance = app + if app_instance is None: + try: + app_instance = current_app._get_current_object() + except RuntimeError: + logger.error("No app instance available for SDI status poll") + return + with external_url_context(app_instance): + poll_sdi_status() + + _add_job( + scheduler, + func=poll_sdi_status_with_app, + trigger="cron", + minute="*/15", + id="poll_sdi_status", + name="Poll SDI transmission statuses", + replace_existing=True, + ) + logger.info("Registered SDI status poll task") + # Check for expiring quotes daily at 9:30 AM # Create a closure that captures the app instance def check_expiring_quotes_with_app(): @@ -1864,6 +1886,21 @@ def poll_peppol_inbox(): logger.error(f"Error polling Peppol inbox: {e}") +def poll_sdi_status(): + """Refresh non-final SDI (FatturaPA) transmission statuses via the intermediary. + + Note: This function should be called within an app context. + """ + try: + from app.services.sdi_service import SdiService + + count = SdiService().poll_pending(max_age_days=30) + if count: + logger.info("SDI status poll refreshed %s transmission(s)", count) + except Exception as e: + logger.error(f"Error polling SDI statuses: {e}") + + def check_expiring_quotes(): """Check for quotes expiring soon and send reminders diff --git a/docs/admin/configuration/FATTURAPA_SDI.md b/docs/admin/configuration/FATTURAPA_SDI.md new file mode 100644 index 000000000..e5504dbfb --- /dev/null +++ b/docs/admin/configuration/FATTURAPA_SDI.md @@ -0,0 +1,114 @@ +# FatturaPA and SDI (Italy) + +TimeTracker can generate **FatturaPA 1.2 XML** (B2B `FPR12` and public administration `FPA12`) and optionally send it to the Italian **Sistema di Interscambio (SDI)** through your accredited intermediary. + +Digital signature (`.p7m`) and inbound purchase invoices are out of scope; intermediaries typically sign on your behalf. + +## What you need + +1. **Company branding** (Admin → Settings): + - Partita IVA (`company_tax_id`, e.g. `IT01234567890`) and/or Codice Fiscale + - Structured address: street, CAP, city, provincia, country `IT` + - Regime fiscale (default `RF01`) + - IBAN (for payment details in the XML) +2. **Client** fields: + - VAT ID or Codice Fiscale + - Structured address + provincia (for Italian buyers) + - **SDI Codice Destinatario** (7 chars B2B / 6 chars PA) **or** PEC email +3. Optional on the invoice: **CIG** / **CUP** for public-administration procurement + +## Export + +On the invoice page, use **Download FatturaPA**. The file name follows the SDI convention: + +`IT{IdTrasmittente}_{ProgressivoInvio}.xml` + +Missing mandatory fields return HTTP 400 with a JSON list of readiness messages (same pattern as XRechnung). + +## Send via SDI + +1. Enable **SDI sending** under Admin → Settings → **SDI / FatturaPA**. +2. Set the **intermediary URL** (typically ending in `/send`) and optional bearer token. +3. On the invoice page, click **Send via SDI**. + +Transmissions are stored with status `pending` → `sent`, then updated from SDI notifications (`RC`, `NS`, `MC`, `NE`, `DT`, `AT`) via: + +- Manual **Refresh** on the invoice history table +- Scheduled job `poll_sdi_status` every 15 minutes (non-final transmissions younger than 30 days) + +API twin: `POST /api/v1/invoices//send-sdi` (scope `write:invoices`). + +## Generic intermediary HTTP contract + +TimeTracker talks to a **generic HTTP adapter** you configure (your own microservice, or a thin wrapper around Aruba / A-Cube / Openapi / etc.). + +### Send + +`POST {sdi_transport_url}` + +```http +Authorization: Bearer {token} +Content-Type: application/json +``` + +```json +{ + "filename": "IT01234567890_00001.xml", + "formato": "FPR12", + "recipient": { + "codice_destinatario": "ABC1234", + "pec": null + }, + "xml_base64": "", + "sha256": "" +} +``` + +Expected response: + +```json +{ + "message_id": "provider-message-id", + "sdi_identifier": "optional-sdi-id" +} +``` + +### Status + +`GET {base}/message/{message_id}/status` +(`base` is the transport URL with a trailing `/send` removed) + +```json +{ + "status": "delivered", + "sdi_identifier": "optional", + "notifications": [ + { "type": "RC", "date": "2026-11-08T10:00:00Z", "detail": "ok" } + ] +} +``` + +Notification types map to transmission status: + +| Type | Status | +|------|--------| +| RC | delivered | +| NS | rejected | +| MC | not_delivered (still legally issued) | +| NE | accepted or refused (from detail text) | +| DT | expired | +| AT | failed | + +## Recipient rules + +| Situation | Codice Destinatario | Notes | +|-----------|---------------------|-------| +| B2B with SDI code | 7 characters | `FPR12` | +| Public administration | 6 characters | `FPA12`; set CIG/CUP when required | +| B2B with PEC only | `0000000` | PECDestinatario is set | +| Foreign buyer | `XXXXXXX` | CAP forced to `00000` | + +## Related + +- [Peppol / Factur-X / ZUGFeRD](PEPPOL_EINVOICING.md) — EN 16931 UBL/CII formats (different schema from FatturaPA) +- [Peppol Bridge](PEPPOL_BRIDGE.md) — similar adapter pattern for Peppol diff --git a/docs/admin/configuration/PEPPOL_EINVOICING.md b/docs/admin/configuration/PEPPOL_EINVOICING.md index 71a4ba4d0..316effd3d 100644 --- a/docs/admin/configuration/PEPPOL_EINVOICING.md +++ b/docs/admin/configuration/PEPPOL_EINVOICING.md @@ -12,9 +12,10 @@ TimeTracker supports **both**: | Peppol BIS Billing 3.0 | UBL 2.1 | Supported (transport + export) | | Factur-X / ZUGFeRD 2.x | CII (EN 16931 profile) | Supported (embedded in PDF) | | PDF/A-3b | PDF archival | Supported (with ICC profile) | -| XRechnung | CII / UBL (German CIUS) | Not supported | +| XRechnung 3.0 | UBL (CIUS-DE) | Supported (XML export) | +| FatturaPA 1.2 | Italian XML (FPR12 / FPA12) | Supported (XML export + SDI send) — see [FATTURAPA_SDI.md](FATTURAPA_SDI.md) | -Peppol is the **transport**; Factur-X / ZUGFeRD is a **format** (PDF + embedded CII XML). Each uses its own XML payload — UBL for Peppol, CII for Factur-X. +Peppol is the **transport**; Factur-X / ZUGFeRD is a **format** (PDF + embedded CII XML). Each uses its own XML payload — UBL for Peppol, CII for Factur-X. FatturaPA uses a separate Italian schema and SDI transport. ## What you need diff --git a/migrations/versions/209_add_fatturapa_sdi.py b/migrations/versions/209_add_fatturapa_sdi.py new file mode 100644 index 000000000..5b8e60724 --- /dev/null +++ b/migrations/versions/209_add_fatturapa_sdi.py @@ -0,0 +1,143 @@ +"""Add FatturaPA / SDI fields and invoice_sdi_transmissions table. + +Adds Italian e-invoicing company/client/invoice columns and transmission audit +table for FatturaPA XML export and SDI intermediary sending. + +Revision ID: 209_add_fatturapa_sdi +Revises: 208_add_peppol_inbound_documents +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy import inspect + +revision = "209_add_fatturapa_sdi" +down_revision = "208_add_peppol_inbound_documents" +branch_labels = None +depends_on = None + + +def _has_column(inspector, table_name: str, column_name: str) -> bool: + try: + return column_name in {c["name"] for c in inspector.get_columns(table_name)} + except Exception: + return False + + +def _add_column_if_missing(inspector, table_name: str, column: sa.Column) -> None: + if not _has_column(inspector, table_name, column.name): + op.add_column(table_name, column) + + +def upgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + # Settings: Italian company + SDI transport + _add_column_if_missing( + inspector, "settings", sa.Column("company_codice_fiscale", sa.String(length=16), nullable=True) + ) + _add_column_if_missing( + inspector, + "settings", + sa.Column("company_regime_fiscale", sa.String(length=4), nullable=True, server_default="RF01"), + ) + _add_column_if_missing(inspector, "settings", sa.Column("company_provincia", sa.String(length=2), nullable=True)) + _add_column_if_missing( + inspector, "settings", sa.Column("sdi_enabled", sa.Boolean(), nullable=False, server_default=sa.false()) + ) + _add_column_if_missing(inspector, "settings", sa.Column("sdi_transport_url", sa.String(length=500), nullable=True)) + _add_column_if_missing(inspector, "settings", sa.Column("sdi_transport_token", sa.String(length=255), nullable=True)) + _add_column_if_missing(inspector, "settings", sa.Column("sdi_transmitter_id", sa.String(length=16), nullable=True)) + _add_column_if_missing( + inspector, "settings", sa.Column("sdi_timeout", sa.Integer(), nullable=True, server_default="30") + ) + + # Clients: FatturaPA recipient fields + inspector = inspect(bind) + _add_column_if_missing( + inspector, "clients", sa.Column("sdi_codice_destinatario", sa.String(length=7), nullable=True) + ) + _add_column_if_missing(inspector, "clients", sa.Column("pec_email", sa.String(length=200), nullable=True)) + _add_column_if_missing(inspector, "clients", sa.Column("codice_fiscale", sa.String(length=16), nullable=True)) + _add_column_if_missing(inspector, "clients", sa.Column("provincia", sa.String(length=2), nullable=True)) + + # Invoices: PA procurement codes + inspector = inspect(bind) + _add_column_if_missing(inspector, "invoices", sa.Column("cig", sa.String(length=15), nullable=True)) + _add_column_if_missing(inspector, "invoices", sa.Column("cup", sa.String(length=15), nullable=True)) + + # Transmission audit table + inspector = inspect(bind) + existing_tables = inspector.get_table_names() + if "invoice_sdi_transmissions" not in existing_tables: + op.create_table( + "invoice_sdi_transmissions", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("invoice_id", sa.Integer(), sa.ForeignKey("invoices.id"), nullable=False), + sa.Column("filename", sa.String(length=100), nullable=True), + sa.Column("progressivo", sa.String(length=10), nullable=True), + sa.Column("formato", sa.String(length=5), nullable=True), + sa.Column("xml", sa.Text(), nullable=True), + sa.Column("xml_sha256", sa.String(length=64), nullable=True), + sa.Column("status", sa.String(length=20), nullable=False, server_default="pending"), + sa.Column("sdi_identifier", sa.String(length=100), nullable=True), + sa.Column("message_id", sa.String(length=200), nullable=True), + sa.Column("notifications", sa.JSON(), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("sent_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=False), + ) + op.create_index( + "ix_invoice_sdi_transmissions_invoice_id", + "invoice_sdi_transmissions", + ["invoice_id"], + unique=False, + ) + op.create_index( + "ix_invoice_sdi_transmissions_status", + "invoice_sdi_transmissions", + ["status"], + unique=False, + ) + + +def downgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + if "invoice_sdi_transmissions" in inspector.get_table_names(): + try: + op.drop_index("ix_invoice_sdi_transmissions_status", table_name="invoice_sdi_transmissions") + except Exception: + pass + try: + op.drop_index("ix_invoice_sdi_transmissions_invoice_id", table_name="invoice_sdi_transmissions") + except Exception: + pass + op.drop_table("invoice_sdi_transmissions") + + inspector = inspect(bind) + for col in ("cup", "cig"): + if _has_column(inspector, "invoices", col): + op.drop_column("invoices", col) + + inspector = inspect(bind) + for col in ("provincia", "codice_fiscale", "pec_email", "sdi_codice_destinatario"): + if _has_column(inspector, "clients", col): + op.drop_column("clients", col) + + inspector = inspect(bind) + for col in ( + "sdi_timeout", + "sdi_transmitter_id", + "sdi_transport_token", + "sdi_transport_url", + "sdi_enabled", + "company_provincia", + "company_regime_fiscale", + "company_codice_fiscale", + ): + if _has_column(inspector, "settings", col): + op.drop_column("settings", col) diff --git a/requirements-test.txt b/requirements-test.txt index 527ebdfe5..57d56cab4 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -41,6 +41,9 @@ responses==0.26.3 # Mock HTTP responses # Optional Factur-X XSD validation (Akretion factur-x) factur-x>=7.9 +# FatturaPA XSD validation in tests +lxml>=5.0 + # Database testing sqlalchemy-utils==0.43.0 # Database utilities for testing diff --git a/tests/conftest.py b/tests/conftest.py index 45e912d63..565c92d4e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -236,6 +236,7 @@ def app(app_config): InvoiceItem, InvoicePDFTemplate, InvoicePeppolTransmission, + InvoiceSdiTransmission, InvoiceReminderSchedule, InvoiceTemplate, KanbanColumn, diff --git a/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd b/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd new file mode 100644 index 000000000..be131eb54 --- /dev/null +++ b/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd @@ -0,0 +1,1449 @@ + + + + + + + + XML schema fatture destinate a PA e privati in forma ordinaria 1.2.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Blocco relativo ai dati di trasmissione della Fattura Elettronica + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fattura verso PA + + + + + Fattura verso privati + + + + + + + + + + + + + + Blocco relativo ai Dati Generali della Fattura Elettronica + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SC = Sconto + + + + + MG = Maggiorazione + + + + + + + + + + SI = Documento emesso secondo modalità e termini stabiliti con DM ai sensi dell'art. 73 DPR 633/72 + + + + + + + + + + Cassa nazionale previdenza e assistenza avvocati e procuratori legali + + + + + Cassa previdenza dottori commercialisti + + + + + Cassa previdenza e assistenza geometri + + + + + Cassa nazionale previdenza e assistenza ingegneri e architetti liberi professionisti + + + + + Cassa nazionale del notariato + + + + + Cassa nazionale previdenza e assistenza ragionieri e periti commerciali + + + + + Ente nazionale assistenza agenti e rappresentanti di commercio (ENASARCO) + + + + + Ente nazionale previdenza e assistenza consulenti del lavoro (ENPACL) + + + + + Ente nazionale previdenza e assistenza medici (ENPAM) + + + + + Ente nazionale previdenza e assistenza farmacisti (ENPAF) + + + + + Ente nazionale previdenza e assistenza veterinari (ENPAV) + + + + + Ente nazionale previdenza e assistenza impiegati dell'agricoltura (ENPAIA) + + + + + Fondo previdenza impiegati imprese di spedizione e agenzie marittime + + + + + Istituto nazionale previdenza giornalisti italiani (INPGI) + + + + + Opera nazionale assistenza orfani sanitari italiani (ONAOSI) + + + + + Cassa autonoma assistenza integrativa giornalisti italiani (CASAGIT) + + + + + Ente previdenza periti industriali e periti industriali laureati (EPPI) + + + + + Ente previdenza e assistenza pluricategoriale (EPAP) + + + + + Ente nazionale previdenza e assistenza biologi (ENPAB) + + + + + Ente nazionale previdenza e assistenza professione infermieristica (ENPAPI) + + + + + Ente nazionale previdenza e assistenza psicologi (ENPAP) + + + + + INPS + + + + + + + + + + Fattura + + + + + Acconto / anticipo su fattura + + + + + Acconto / anticipo su parcella + + + + + Nota di credito + + + + + Nota di debito + + + + + Parcella + + + + + Integrazione fattura reverse charge interno + + + + + Integrazione/autofattura per acquisto servizi dall'estero + + + + + Integrazione per acquisto di beni intracomunitari + + + + + Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72 + + + + + Autofattura per regolarizzazione e integrazione delle fatture (ex art.6 c.8 e 9-bis d.lgs.471/97 o art.46 c.5 D.L. 331/93 + + + + + Autofattura per splafonamento + + + + + Estrazione benida Deposito IVA + + + + + Estrazione beni da Deposito IVA con versamento dell'IVA + + + + + Fattura differita di cui all'art.21, comma 4, lett. a) + + + + + Fattura differita di cui all'art.21, comma 4, terzo periodo lett. b) + + + + + Cessione di beni ammortizzabili e per passaggi interni (ex art.36 DPR 633/72) + + + + + Fattura per autoconsumo o per cessioni gratuite senza rivalsa + + + + + + + + + + Ritenuta di acconto persone fisiche + + + + + Ritenuta di acconto persone giuridiche + + + + + Contributo INPS + + + + + Contributo ENASARCO + + + + + Contributo ENPAM + + + + + Altro contributo previdenziale + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cessionario / Committente + + + + + Terzo + + + + + + + Blocco relativo ai dati del Cedente / Prestatore + + + + + + + + + + + + + + + + + + + + + + + + + + + + Regime ordinario + + + + + Regime dei contribuenti minimi (art. 1,c.96-117, L. 244/2007) + + + + + Agricoltura e attività connesse e pesca (artt. 34 e 34-bis, D.P.R. 633/1972) + + + + + Vendita sali e tabacchi (art. 74, c.1, D.P.R. 633/1972) + + + + + Commercio dei fiammiferi (art. 74, c.1, D.P.R. 633/1972) + + + + + Editoria (art. 74, c.1, D.P.R. 633/1972) + + + + + Gestione di servizi di telefonia pubblica (art. 74, c.1, D.P.R. 633/1972) + + + + + Rivendita di documenti di trasporto pubblico e di sosta (art. 74, c.1, D.P.R. 633/1972) + + + + + Intrattenimenti, giochi e altre attività di cui alla tariffa allegata al D.P.R. 640/72 (art. 74, c.6, D.P.R. 633/1972) + + + + + Agenzie di viaggi e turismo (art. 74-ter, D.P.R. 633/1972) + + + + + Agriturismo (art. 5, c.2, L. 413/1991) + + + + + Vendite a domicilio (art. 25-bis, c.6, D.P.R. 600/1973) + + + + + Rivendita di beni usati, di oggetti d’arte, d’antiquariato o da collezione (art. 36, D.L. 41/1995) + + + + + Agenzie di vendite all’asta di oggetti d’arte, antiquariato o da collezione (art. 40-bis, D.L. 41/1995) + + + + + IVA per cassa P.A. (art. 6, c.5, D.P.R. 633/1972) + + + + + IVA per cassa (art. 32-bis, D.L. 83/2012) + + + + + Regime forfettario + + + + + Altro + + + + + + + Il campo Denominazione è in alternativa ai campi Nome e Cognome + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Blocco relativo ai dati del Rappresentante Fiscale + + + + + + + + + + + + + + + Blocco relativo ai dati del Cessionario / Committente + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Blocco relativo ai dati di Beni Servizi della Fattura Elettronica + + + + + + + + + Blocco relativo ai dati dei Veicoli della Fattura Elettronica (da indicare nei casi di cessioni tra Paesi + membri di mezzi di trasporto nuovi, in base all'art. 38, comma 4 del dl 331 del 1993) + + + + + + + + + Blocco relativo ai dati di Pagamento della Fattura Elettronica + + + + + + + + + + + + + pagamento a rate + + + + + pagamento completo + + + + + anticipo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + contanti + + + + + assegno + + + + + assegno circolare + + + + + contanti presso Tesoreria + + + + + bonifico + + + + + vaglia cambiario + + + + + bollettino bancario + + + + + carta di pagamento + + + + + RID + + + + + RID utenze + + + + + RID veloce + + + + + RIBA + + + + + MAV + + + + + quietanza erario + + + + + giroconto su conti di contabilità speciale + + + + + domiciliazione bancaria + + + + + domiciliazione postale + + + + + bollettino di c/c postale + + + + + SEPA Direct Debit + + + + + SEPA Direct Debit CORE + + + + + SEPA Direct Debit B2B + + + + + Trattenuta su somme già riscosse + + + + + PagoPA + + + + + + + + + + + + + + + + + Blocco relativo ai dati del Terzo Intermediario che emette fattura elettronica per conto del Cedente/Prestatore + + + + + + + + + + + + + + + Blocco relativo ai dati di eventuali allegati + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SI = Cessione / Prestazione soggetta a ritenuta + + + + + + + + + + + + + + + + + + + + + + + esigibilità differita + + + + + esigibilità immediata + + + + + scissione dei pagamenti + + + + + + + + + Escluse ex. art. 15 + + + + + + Non soggette + + + + + Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies del DPR 633/72 + + + + + Non soggette - altri casi + + + + + + Non imponibili + + + + + Non Imponibili - esportazioni + + + + + Non Imponibili - cessioni intracomunitarie + + + + + Non Imponibili - cessioni verso San Marino + + + + + Non Imponibili - operazioni assimilate alle cessioni all'esportazione + + + + + Non Imponibili - a seguito di dichiarazioni d'intento + + + + + Non Imponibili - altre operazioni che non concorrono alla formazione del plafond + + + + + Esenti + + + + + Regime del margine/IVA non esposta in fattura + + + + + + Inversione contabile (per le operazioni in reverse charge ovvero nei casi di autofatturazione per acquisti extra UE di servizi ovvero per importazioni di beni nei soli casi previsti) + + + + + Inversione contabile - cessione di rottami e altri materiali di recupero + + + + + Inversione contabile - cessione di oro e argento puro + + + + + Inversione contabile - subappalto nel settore edile + + + + + Inversione contabile - cessione di fabbricati + + + + + Inversione contabile - cessione di telefoni cellulari + + + + + Inversione contabile - cessione di prodotti elettronici + + + + + Inversione contabile - prestazioni comparto edile e settori connessi + + + + + Inversione contabile - operazioni settore energetico + + + + + Inversione contabile - altri casi + + + + + IVA assolta in altro stato UE (prestazione di servizi di telecomunicazioni, tele-radiodiffusione ed elettronici ex art. 7-sexies lett. f, g, art. 74-sexies DPR 633/72) + + + + + + + + + + + + + + + + + + + + + + + + + socio unico + + + + + più soci + + + + + + + + + in liquidazione + + + + + non in liquidazione + + + + + + + + + + Sconto + + + + + Premio + + + + + Abbuono + + + + + Spesa accessoria + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/fixtures/fatturapa/xmldsig-core-schema.xsd b/tests/fixtures/fatturapa/xmldsig-core-schema.xsd new file mode 100644 index 000000000..df126b30e --- /dev/null +++ b/tests/fixtures/fatturapa/xmldsig-core-schema.xsd @@ -0,0 +1,318 @@ + + + + + + ]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/test_fatturapa.py b/tests/test_fatturapa.py new file mode 100644 index 000000000..87e1b7bab --- /dev/null +++ b/tests/test_fatturapa.py @@ -0,0 +1,227 @@ +"""FatturaPA 1.2 XML export tests.""" + +from datetime import date +from decimal import Decimal +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from app.utils.fatturapa import ( + FATTURAPA_VERSION_FPA, + FATTURAPA_VERSION_FPR, + build_fatturapa_filename, + build_fatturapa_xml, + determine_formato, + progressivo_from_id, + resolve_codice_destinatario, + resolve_natura, + validate_fatturapa_ready, +) + +FIXTURES = Path(__file__).parent / "fixtures" / "fatturapa" +XSD_PATH = FIXTURES / "Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd" + + +def _settings(**kwargs): + base = dict( + company_name="Acme Srl", + company_street="Via Roma 1", + company_postcode="20121", + company_city="Milano", + company_country="IT", + company_provincia="MI", + company_tax_id="IT01234567890", + company_codice_fiscale="01234567890", + company_regime_fiscale="RF01", + company_iban="IT60X0542811101000000123456", + company_bic="BPMOIT22XXX", + company_address="Via Roma 1, Milano", + company_email="billing@acme.it", + company_phone="+39 02 123456", + sdi_transmitter_id="", + invoices_default_vat_category="S", + invoices_default_vat_exemption_reason="", + invoices_default_vat_exemption_code="", + ) + base.update(kwargs) + return SimpleNamespace(**base) + + +def _client(**kwargs): + base = dict( + name="Cliente Spa", + street="Corso Italia 10", + postcode="00187", + city="Roma", + country="IT", + provincia="RM", + vat_id="IT09876543210", + codice_fiscale="09876543210", + address="Corso Italia 10", + email="acquisti@cliente.it", + phone="+39 06 123456", + sdi_codice_destinatario="ABC1234", + pec_email="", + ) + base.update(kwargs) + ns = SimpleNamespace(**base) + ns.get_custom_field = lambda key, default="": default + return ns + + +def _invoice(**kwargs): + price = Decimal("100.00") + item = SimpleNamespace(description="Consulenza", quantity=1, unit_price=price, total_amount=price) + base = dict( + id=42, + invoice_number="FT-2026-1", + issue_date=date(2026, 11, 7), + due_date=date(2026, 12, 7), + currency_code="EUR", + subtotal=price, + tax_rate=Decimal("22"), + tax_amount=Decimal("22.00"), + total_amount=Decimal("122.00"), + notes=None, + items=[item], + expenses=[], + extra_goods=[], + client_name="Cliente Spa", + vat_category=None, + vat_exemption_code=None, + vat_exemption_reason=None, + cig=None, + cup=None, + ) + base.update(kwargs) + return SimpleNamespace(**base) + + +def test_progressivo_from_id_base36_padded(): + assert progressivo_from_id(1) == "00001" + assert len(progressivo_from_id(12345)) == 5 + + +def test_determine_formato_pa_vs_b2b(): + assert determine_formato(_client(sdi_codice_destinatario="UFXYZ1")) == FATTURAPA_VERSION_FPA + assert determine_formato(_client(sdi_codice_destinatario="ABC1234")) == FATTURAPA_VERSION_FPR + + +def test_resolve_codice_pec_and_foreign(): + code, pec = resolve_codice_destinatario(_client(sdi_codice_destinatario="", pec_email="a@pec.it")) + assert code == "0000000" + assert pec == "a@pec.it" + code, pec = resolve_codice_destinatario(_client(sdi_codice_destinatario="", pec_email="", country="DE")) + assert code == "XXXXXXX" + assert pec is None + + +def test_validate_fails_without_recipient(): + issues = validate_fatturapa_ready( + _invoice(), _settings(), _client(sdi_codice_destinatario="", pec_email="") + ) + assert any("Codice Destinatario" in msg or "PEC" in msg for msg in issues) + + +def test_validate_fails_without_provincia_for_it(): + issues = validate_fatturapa_ready(_invoice(), _settings(company_provincia=""), _client()) + assert any("provincia" in msg.lower() for msg in issues) + + +def test_build_fpr12_structure(): + xml, filename, sha = build_fatturapa_xml(_invoice(), _settings(), _client(), "0002A") + assert "versione=\"FPR12\"" in xml or "versione='FPR12'" in xml + assert "FatturaElettronicaHeader" in xml + assert "CedentePrestatore" in xml + assert "CessionarioCommittente" in xml + assert "DettaglioLinee" in xml + assert "DatiRiepilogo" in xml + assert "ABC1234" in xml + assert "Consulenza" in xml + assert filename.startswith("IT") and filename.endswith("_0002A.xml") + assert len(sha) == 64 + + +def test_build_fpa12_with_cig_cup(): + client = _client(sdi_codice_destinatario="UFABC1") + inv = _invoice(cig="Z1234567890", cup="J12C3400010001") + xml, _fn, _sha = build_fatturapa_xml(inv, _settings(), client, "00001") + assert "versione=\"FPA12\"" in xml or "versione='FPA12'" in xml + assert "CodiceCIG" in xml + assert "Z1234567890" in xml + assert "CodiceCUP" in xml + + +def test_pec_fallback_xml(): + client = _client(sdi_codice_destinatario="", pec_email="cliente@pec.example.it") + xml, _fn, _sha = build_fatturapa_xml(_invoice(), _settings(), client, "00001") + assert "0000000" in xml + assert "PECDestinatario" in xml + assert "cliente@pec.example.it" in xml + + +def test_foreign_buyer_uses_xxxxxxx(): + client = _client( + sdi_codice_destinatario="", + pec_email="", + country="DE", + provincia="", + vat_id="DE123456789", + codice_fiscale="", + postcode="10115", + ) + # Foreign buyers don't need Italian provincia + settings = _settings() + issues = validate_fatturapa_ready(_invoice(), settings, client) + assert not any("provincia" in m.lower() and "Client" in m for m in issues) + xml, _fn, _sha = build_fatturapa_xml(_invoice(), settings, client, "00001") + assert "XXXXXXX" in xml + assert ">00000<" in xml # foreign CAP + + +def test_natura_mapping_zero_rate(): + inv = _invoice(tax_rate=Decimal("0"), tax_amount=Decimal("0"), total_amount=Decimal("100.00"), vat_category="E") + settings = _settings() + assert resolve_natura(inv, settings, Decimal("0")) == "N4" + xml, _fn, _sha = build_fatturapa_xml(inv, settings, _client(), "00001") + assert "N4" in xml + + +def test_natura_from_exemption_code(): + inv = _invoice( + tax_rate=Decimal("0"), + tax_amount=Decimal("0"), + total_amount=Decimal("100.00"), + vat_exemption_code="N3.1", + vat_exemption_reason="Export art. 8", + ) + assert resolve_natura(inv, _settings(), Decimal("0")) == "N3.1" + xml, _fn, _sha = build_fatturapa_xml(inv, _settings(), _client(), "00001") + assert "N3.1" in xml + assert "Export art. 8" in xml + + +def test_filename_format(): + assert build_fatturapa_filename("01234567890", "00001") == "IT01234567890_00001.xml" + + +def test_xsd_validation_fpr12(): + etree = pytest.importorskip("lxml.etree") + if not XSD_PATH.exists(): + pytest.skip("FatturaPA XSD fixture missing") + + xml, _fn, _sha = build_fatturapa_xml(_invoice(), _settings(), _client(), "00001") + + # Rewrite remote xmldsig import to local fixture for offline validation + xsd_text = XSD_PATH.read_text(encoding="utf-8-sig") + local_dsig = (FIXTURES / "xmldsig-core-schema.xsd").as_uri() + xsd_text = xsd_text.replace( + 'schemaLocation="http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"', + f'schemaLocation="{local_dsig}"', + ) + schema_doc = etree.fromstring(xsd_text.encode("utf-8")) + schema = etree.XMLSchema(schema_doc) + doc = etree.fromstring(xml.encode("utf-8")) + if not schema.validate(doc): + pytest.fail(f"XSD validation failed: {schema.error_log.filter_from_errors()}") diff --git a/tests/test_fatturapa_routes.py b/tests/test_fatturapa_routes.py new file mode 100644 index 000000000..1cc5c0294 --- /dev/null +++ b/tests/test_fatturapa_routes.py @@ -0,0 +1,171 @@ +"""Route tests for FatturaPA export and SDI send.""" + +from datetime import date +from decimal import Decimal + +import pytest + + +@pytest.fixture +def fatturapa_ready(app, db_session, authenticated_client, user): + from app.models import Client, Invoice, InvoiceItem, Project, Settings + + with app.app_context(): + settings = Settings.get_settings() + settings.company_name = "Acme Srl" + settings.company_street = "Via Roma 1" + settings.company_postcode = "20121" + settings.company_city = "Milano" + settings.company_country = "IT" + settings.company_provincia = "MI" + settings.company_tax_id = "IT01234567890" + settings.company_codice_fiscale = "01234567890" + settings.company_regime_fiscale = "RF01" + settings.company_iban = "IT60X0542811101000000123456" + settings.sdi_enabled = True + settings.sdi_transport_url = "https://adapter.example/send" + settings.set_secret("sdi_transport_token", "tok") + + client = Client( + name="FatturaPA Cliente", + email="acquisti@cliente.it", + street="Corso Italia 10", + postcode="00187", + city="Roma", + country="IT", + provincia="RM", + vat_id="IT09876543210", + codice_fiscale="09876543210", + sdi_codice_destinatario="ABC1234", + created_by=user.id, + ) + client.status = "active" + db_session.add(client) + db_session.flush() + + project = Project( + name="FatturaPA Project", + client_id=client.id, + description="FP test", + billable=True, + hourly_rate=Decimal("75.00"), + created_by=user.id, + ) + project.status = "active" + db_session.add(project) + db_session.flush() + + inv = Invoice( + invoice_number="FP-ROUTE-1", + project_id=project.id, + client_id=client.id, + client_name=client.name, + due_date=date(2026, 12, 31), + created_by=user.id, + tax_rate=Decimal("22"), + subtotal=Decimal("100.00"), + tax_amount=Decimal("22.00"), + total_amount=Decimal("122.00"), + currency_code="EUR", + issue_date=date(2026, 11, 7), + ) + db_session.add(inv) + db_session.flush() + db_session.add( + InvoiceItem( + invoice_id=inv.id, + description="Consulenza", + quantity=Decimal("1"), + unit_price=Decimal("100.00"), + ) + ) + db_session.commit() + return inv.id + + +def test_export_fatturapa_ok(authenticated_client, fatturapa_ready): + resp = authenticated_client.get(f"/invoices/{fatturapa_ready}/export/fatturapa") + assert resp.status_code == 200 + assert "xml" in (resp.mimetype or "") + body = resp.data.decode("utf-8") + assert "FatturaElettronica" in body + assert "FPR12" in body + + +def test_export_fatturapa_not_ready(authenticated_client, app, db_session, user): + from app.models import Client, Invoice, Project, Settings + + with app.app_context(): + settings = Settings.get_settings() + settings.company_name = "Acme Srl" + settings.company_street = "Via Roma 1" + settings.company_postcode = "20121" + settings.company_city = "Milano" + settings.company_country = "IT" + settings.company_provincia = "MI" + settings.company_tax_id = "IT01234567890" + settings.company_regime_fiscale = "RF01" + + client = Client( + name="Incomplete SDI Client", + email="x@example.it", + street="Via 1", + postcode="20100", + city="Milano", + country="IT", + provincia="MI", + vat_id="IT01111111111", + # intentionally no sdi_codice_destinatario / pec + created_by=user.id, + ) + client.status = "active" + db_session.add(client) + db_session.flush() + project = Project( + name="Incomplete Project", + client_id=client.id, + billable=True, + hourly_rate=Decimal("50"), + created_by=user.id, + ) + project.status = "active" + db_session.add(project) + db_session.flush() + inv = Invoice( + invoice_number="FP-BAD-1", + project_id=project.id, + client_id=client.id, + client_name=client.name, + due_date=date(2026, 12, 31), + created_by=user.id, + currency_code="EUR", + issue_date=date(2026, 11, 7), + ) + db_session.add(inv) + db_session.commit() + inv_id = inv.id + + resp = authenticated_client.get(f"/invoices/{inv_id}/export/fatturapa") + assert resp.status_code == 400 + data = resp.get_json() + assert data["error"] == "fatturapa_not_ready" + assert data["messages"] + + +def test_send_sdi_permission_and_mock(authenticated_client, fatturapa_ready, monkeypatch): + from app.services.sdi_service import SdiService + + class FakeTx: + id = 7 + status = "sent" + filename = "IT01234567890_00001.xml" + + def fake_send(self, invoice, triggered_by_user_id=None): + return True, FakeTx(), "Invoice sent via SDI" + + monkeypatch.setattr(SdiService, "send_invoice", fake_send) + resp = authenticated_client.post(f"/invoices/{fatturapa_ready}/send-sdi") + assert resp.status_code == 200 + data = resp.get_json() + assert data["success"] is True + assert data["sdi_tx_id"] == 7 diff --git a/tests/test_sdi_service.py b/tests/test_sdi_service.py new file mode 100644 index 000000000..2e9805837 --- /dev/null +++ b/tests/test_sdi_service.py @@ -0,0 +1,216 @@ +"""SDI service and transport tests with mocked HTTP.""" + +from datetime import date +from decimal import Decimal +from unittest.mock import MagicMock, patch + +import pytest + +from app.integrations.sdi_transport import GenericSdiTransport, SdiTransportError, bridge_base_url +from app.models.invoice_sdi import InvoiceSdiTransmission, SDI_FINAL_STATUSES + + +def test_bridge_base_url_strips_send(): + assert bridge_base_url("https://example.com/send") == "https://example.com" + assert bridge_base_url("https://example.com/api/send/") == "https://example.com/api" + + +def test_generic_transport_send_success(): + transport = GenericSdiTransport(url="https://adapter.example/send", token="secret", timeout=10) + mock_resp = MagicMock() + mock_resp.status_code = 200 + mock_resp.json.return_value = {"message_id": "msg-1", "sdi_identifier": "SDI123"} + with patch("app.integrations.sdi_transport.requests.post", return_value=mock_resp) as post: + data = transport.send( + filename="IT01234567890_00001.xml", + formato="FPR12", + codice_destinatario="ABC1234", + pec=None, + xml="", + sha256="abc", + ) + assert data["message_id"] == "msg-1" + args, kwargs = post.call_args + assert kwargs["headers"]["Authorization"] == "Bearer secret" + assert "xml_base64" in kwargs["json"] + + +def test_generic_transport_send_http_error(): + transport = GenericSdiTransport(url="https://adapter.example/send", token=None) + mock_resp = MagicMock() + mock_resp.status_code = 500 + mock_resp.text = "boom" + with patch("app.integrations.sdi_transport.requests.post", return_value=mock_resp): + with pytest.raises(SdiTransportError): + transport.send( + filename="x.xml", + formato="FPR12", + codice_destinatario="ABC1234", + pec=None, + xml="", + sha256="abc", + ) + + +def test_apply_notification_transitions(): + tx = InvoiceSdiTransmission(invoice_id=1, status="sent") + tx.apply_notification("RC") + assert tx.status == "delivered" + tx2 = InvoiceSdiTransmission(invoice_id=1, status="sent") + tx2.apply_notification("NS", detail="error 00404") + assert tx2.status == "rejected" + assert "00404" in (tx2.error_message or "") + tx3 = InvoiceSdiTransmission(invoice_id=1, status="sent") + tx3.apply_notification("NE", detail="Esito accettato") + assert tx3.status == "accepted" + tx4 = InvoiceSdiTransmission(invoice_id=1, status="sent") + tx4.apply_notification("NE", detail="Documento rifiutato EC02") + assert tx4.status == "refused" + assert "delivered" in SDI_FINAL_STATUSES + + +def _configure_italian_settings(settings): + settings.company_name = "Acme Srl" + settings.company_street = "Via Roma 1" + settings.company_postcode = "20121" + settings.company_city = "Milano" + settings.company_country = "IT" + settings.company_provincia = "MI" + settings.company_tax_id = "IT01234567890" + settings.company_codice_fiscale = "01234567890" + settings.company_regime_fiscale = "RF01" + settings.company_iban = "IT60X0542811101000000123456" + settings.sdi_enabled = True + settings.sdi_transport_url = "https://adapter.example/send" + settings.set_secret("sdi_transport_token", "tok-secret") + settings.sdi_timeout = 15 + + +@pytest.fixture +def sdi_ready_invoice(app, db_session, user): + """Invoice + Italian seller/client fields for SDI send (own client to avoid audit locks).""" + from app.models import Client, Invoice, InvoiceItem, Project, Settings + + with app.app_context(): + settings = Settings.get_settings() + _configure_italian_settings(settings) + + client = Client( + name="SDI Cliente Spa", + email="acquisti@cliente.it", + street="Corso Italia 10", + postcode="00187", + city="Roma", + country="IT", + provincia="RM", + vat_id="IT09876543210", + codice_fiscale="09876543210", + sdi_codice_destinatario="ABC1234", + created_by=user.id, + ) + client.status = "active" + db_session.add(client) + db_session.flush() + + project = Project( + name="SDI Project", + client_id=client.id, + description="SDI test", + billable=True, + hourly_rate=Decimal("75.00"), + created_by=user.id, + ) + project.status = "active" + db_session.add(project) + db_session.flush() + + inv = Invoice( + invoice_number="SDI-TEST-1", + project_id=project.id, + client_id=client.id, + client_name=client.name, + due_date=date(2026, 12, 31), + created_by=user.id, + tax_rate=Decimal("22"), + subtotal=Decimal("100.00"), + tax_amount=Decimal("22.00"), + total_amount=Decimal("122.00"), + currency_code="EUR", + issue_date=date(2026, 11, 7), + ) + db_session.add(inv) + db_session.flush() + db_session.add( + InvoiceItem( + invoice_id=inv.id, + description="Consulenza", + quantity=Decimal("1"), + unit_price=Decimal("100.00"), + ) + ) + db_session.commit() + return inv.id + + +def test_sdi_service_send_success(app, db_session, sdi_ready_invoice): + from app.models import Invoice, InvoiceSdiTransmission + from app.services.sdi_service import SdiService + + with app.app_context(): + inv = Invoice.query.get(sdi_ready_invoice) + mock_transport = MagicMock() + mock_transport.send.return_value = {"message_id": "m-99", "sdi_identifier": "SDI99"} + + with patch.object(SdiService, "_transport", return_value=mock_transport): + ok, tx, msg = SdiService().send_invoice(inv) + + assert ok is True + assert tx is not None + assert tx.status == "sent" + assert tx.message_id == "m-99" + assert tx.xml and "FatturaElettronica" in tx.xml + assert InvoiceSdiTransmission.query.filter_by(invoice_id=inv.id).count() == 1 + + +def test_sdi_service_send_disabled(app, db_session, sdi_ready_invoice): + from app.models import Invoice, Settings + from app.services.sdi_service import SdiService + + with app.app_context(): + Settings.get_settings().sdi_enabled = False + db_session.commit() + inv = Invoice.query.get(sdi_ready_invoice) + ok, tx, msg = SdiService().send_invoice(inv) + assert ok is False + assert tx is None + assert "not enabled" in msg.lower() + + +def test_sdi_service_refresh_status(app, db_session, sdi_ready_invoice): + from app.models import Invoice, InvoiceSdiTransmission + from app.services.sdi_service import SdiService + + with app.app_context(): + inv = Invoice.query.get(sdi_ready_invoice) + tx = InvoiceSdiTransmission( + invoice_id=inv.id, + status="sent", + message_id="m-1", + formato="FPR12", + progressivo="00001", + ) + db_session.add(tx) + db_session.commit() + + mock_transport = MagicMock() + mock_transport.get_status.return_value = { + "status": "delivered", + "sdi_identifier": "SDI1", + "notifications": [{"type": "RC", "date": "2026-11-08", "detail": "ok"}], + } + with patch.object(SdiService, "_transport", return_value=mock_transport): + result = SdiService().refresh_status(tx) + + assert result["ok"] is True + assert tx.status == "delivered" + assert tx.sdi_identifier == "SDI1" diff --git a/translations/it/LC_MESSAGES/messages.po b/translations/it/LC_MESSAGES/messages.po index 92907a78e..d9ab434b8 100644 --- a/translations/it/LC_MESSAGES/messages.po +++ b/translations/it/LC_MESSAGES/messages.po @@ -18629,3 +18629,102 @@ msgstr "" #~ msgid "Please log in to access this page" #~ msgstr "Effettua il login per accedere a questa pagina" + +msgid "Download FatturaPA" +msgstr "Scarica FatturaPA" + +msgid "Send via SDI" +msgstr "Invia via SDI" + +msgid "Client is missing SDI Codice Destinatario or PEC" +msgstr "Al cliente mancano Codice Destinatario SDI o PEC" + +msgid "SDI History" +msgstr "Cronologia SDI" + +msgid "Send this invoice via SDI?" +msgstr "Inviare questa fattura via SDI?" + +msgid "Sent via SDI" +msgstr "Inviata via SDI" + +msgid "Failed to send via SDI" +msgstr "Invio via SDI non riuscito" + +msgid "Invoice sent via SDI" +msgstr "Fattura inviata via SDI" + +msgid "FatturaPA export failed. Please try again." +msgstr "Esportazione FatturaPA non riuscita. Riprova." + +msgid "SDI Codice Destinatario (FatturaPA)" +msgstr "Codice Destinatario SDI (FatturaPA)" + +msgid "6 characters = public administration (FPA12); 7 characters = B2B (FPR12). Use 0000000 with PEC." +msgstr "6 caratteri = pubblica amministrazione (FPA12); 7 caratteri = B2B (FPR12). Usa 0000000 con PEC." + +msgid "PEC email (FatturaPA)" +msgstr "Email PEC (FatturaPA)" + +msgid "Codice Fiscale" +msgstr "Codice Fiscale" + +msgid "Provincia (IT)" +msgstr "Provincia (IT)" + +msgid "CIG (FatturaPA PA)" +msgstr "CIG (FatturaPA PA)" + +msgid "CUP (FatturaPA PA)" +msgstr "CUP (FatturaPA PA)" + +msgid "Optional procurement code" +msgstr "Codice di gara opzionale" + +msgid "Optional project code" +msgstr "Codice progetto opzionale" + +msgid "SDI / FatturaPA (Italy)" +msgstr "SDI / FatturaPA (Italia)" + +msgid "Enable SDI sending" +msgstr "Abilita invio SDI" + +msgid "When enabled, invoices can be sent via SDI using your configured intermediary URL." +msgstr "Se abilitato, le fatture possono essere inviate via SDI usando l'URL dell'intermediario configurato." + +msgid "SDI intermediary URL" +msgstr "URL intermediario SDI" + +msgid "SDI intermediary token (optional)" +msgstr "Token intermediario SDI (opzionale)" + +msgid "SDI timeout (seconds)" +msgstr "Timeout SDI (secondi)" + +msgid "IdTrasmittente (optional)" +msgstr "IdTrasmittente (opzionale)" + +msgid "Defaults to company Codice Fiscale / VAT" +msgstr "Predefinito: Codice Fiscale / Partita IVA aziendale" + +msgid "Codice Fiscale (IT)" +msgstr "Codice Fiscale (IT)" + +msgid "Regime Fiscale (FatturaPA)" +msgstr "Regime Fiscale (FatturaPA)" + +msgid "Italian sellers: Partita IVA, e.g. IT01234567890." +msgstr "Cedenti italiani: Partita IVA, es. IT01234567890." + +msgid "Token is set (enter to replace)" +msgstr "Token impostato (inserisci per sostituirlo)" + +msgid "Enter token (optional)" +msgstr "Inserisci token (opzionale)" + +msgid "For security, the token is not shown. Leave blank to keep the current token." +msgstr "Per sicurezza il token non viene mostrato. Lascia vuoto per mantenere quello attuale." + +msgid "Generate FatturaPA XML and send invoices to the Italian Sistema di Interscambio through your accredited intermediary. See docs/admin/configuration/FATTURAPA_SDI.md for the HTTP adapter contract." +msgstr "Genera XML FatturaPA e invia le fatture al Sistema di Interscambio italiano tramite il tuo intermediario accreditato. Vedi docs/admin/configuration/FATTURAPA_SDI.md per il contratto HTTP dell'adapter." From b38cd6fe550c0590278731dd5e7f67638b5f0e95 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Fri, 13 Nov 2026 16:13:00 +0100 Subject: [PATCH 2/4] fix(invoicing): satisfy black and harden SDI error responses Format FatturaPA/SDI files with black for CI lint, stop echoing exception text to clients, and document intentional empty excepts. --- app/routes/admin.py | 4 +--- app/routes/api_v1_invoices.py | 5 +++-- app/routes/clients.py | 4 +--- app/routes/invoices.py | 14 ++++++-------- app/services/sdi_service.py | 10 ++++++---- app/utils/fatturapa.py | 7 ++++--- migrations/versions/209_add_fatturapa_sdi.py | 7 ++++++- tests/test_fatturapa.py | 8 +++----- 8 files changed, 30 insertions(+), 29 deletions(-) diff --git a/app/routes/admin.py b/app/routes/admin.py index a3c1c1068..4dba87148 100644 --- a/app/routes/admin.py +++ b/app/routes/admin.py @@ -1791,9 +1791,7 @@ def settings(): settings_obj.company_country = country settings_obj.company_iban = (request.form.get("company_iban", "") or "").strip().replace(" ", "") settings_obj.company_bic = (request.form.get("company_bic", "") or "").strip().replace(" ", "") - settings_obj.company_codice_fiscale = ( - request.form.get("company_codice_fiscale", "") or "" - ).strip().upper() + settings_obj.company_codice_fiscale = (request.form.get("company_codice_fiscale", "") or "").strip().upper() settings_obj.company_regime_fiscale = ( request.form.get("company_regime_fiscale", "") or "RF01" ).strip().upper() or "RF01" diff --git a/app/routes/api_v1_invoices.py b/app/routes/api_v1_invoices.py index fa7094c5e..3552a363f 100644 --- a/app/routes/api_v1_invoices.py +++ b/app/routes/api_v1_invoices.py @@ -465,17 +465,18 @@ def send_invoice_sdi_api(invoice_id): return error_response("Invoice not found", status_code=404) try: service = SdiService() - success, tx, message = service.send_invoice(invoice=invoice, triggered_by_user_id=g.api_user.id) + success, tx, _message = service.send_invoice(invoice=invoice, triggered_by_user_id=g.api_user.id) except Exception as e: current_app.logger.error(f"API SDI send failed: {type(e).__name__}: {e}") return error_response("Failed to send via SDI", status_code=502) payload = { "success": success, - "message": message, "sdi_tx_id": tx.id if tx else None, "status": tx.status if tx else None, "filename": tx.filename if tx else None, } if success: + payload["message"] = "Invoice sent via SDI" return jsonify(payload) + payload["message"] = "Failed to send via SDI" return jsonify(payload), 400 diff --git a/app/routes/clients.py b/app/routes/clients.py index d4fcf8fce..d7a583c5d 100644 --- a/app/routes/clients.py +++ b/app/routes/clients.py @@ -272,9 +272,7 @@ def create_client(): country = (request.form.get("country", "") or "").strip().upper()[:2] or None vat_id = sanitize_input(request.form.get("vat_id", "").strip(), max_length=50) leitweg_id = sanitize_input(request.form.get("leitweg_id", "").strip(), max_length=100) - sdi_codice_destinatario = sanitize_input( - request.form.get("sdi_codice_destinatario", "").strip(), max_length=7 - ) + sdi_codice_destinatario = sanitize_input(request.form.get("sdi_codice_destinatario", "").strip(), max_length=7) pec_email = sanitize_input(request.form.get("pec_email", "").strip(), max_length=200) codice_fiscale = sanitize_input(request.form.get("codice_fiscale", "").strip(), max_length=16) provincia = sanitize_input(request.form.get("provincia", "").strip(), max_length=2) diff --git a/app/routes/invoices.py b/app/routes/invoices.py index 164905c95..9902e2b4d 100644 --- a/app/routes/invoices.py +++ b/app/routes/invoices.py @@ -1800,15 +1800,12 @@ def send_invoice_sdi_route(invoice_id): from app.services import SdiService service = SdiService() - success, tx, message = service.send_invoice(invoice=invoice, triggered_by_user_id=current_user.id) + success, tx, _message = service.send_invoice(invoice=invoice, triggered_by_user_id=current_user.id) if success: flash(_("Invoice sent via SDI"), "success") - return jsonify( - {"success": True, "message": message or "Invoice sent via SDI", "sdi_tx_id": tx.id if tx else None} - ) - return jsonify( - {"error": message or "Failed to send invoice via SDI", "sdi_tx_id": tx.id if tx else None} - ), 400 + return jsonify({"success": True, "message": "Invoice sent via SDI", "sdi_tx_id": tx.id if tx else None}) + # Static client copy only — do not echo service/exception text (CodeQL). + return jsonify({"error": "Failed to send invoice via SDI", "sdi_tx_id": tx.id if tx else None}), 400 except Exception as e: logger.error(f"Error sending invoice via SDI: {type(e).__name__}: {str(e)}") logger.exception("Full error traceback:") @@ -1829,7 +1826,8 @@ def refresh_sdi_transmission(tx_id): result = SdiService().refresh_status(tx) if not result.get("ok"): - return jsonify({"error": result.get("error") or "Refresh failed"}), 400 + # Do not forward intermediary/exception detail to the browser (CodeQL). + return jsonify({"error": "Refresh failed"}), 400 return jsonify({"success": True, "status": result.get("status"), "transmission": tx.to_dict()}) diff --git a/app/services/sdi_service.py b/app/services/sdi_service.py index bd35903f9..d773e4cc6 100644 --- a/app/services/sdi_service.py +++ b/app/services/sdi_service.py @@ -100,10 +100,11 @@ def send_invoice( return True, tx, "Sent via SDI, but failed to persist send status" return True, tx, "Invoice sent via SDI" except SdiTransportError as e: + # Persist detail on the transmission; return a generic client message. tx.mark_failed(str(e)) safe_commit("sdi_mark_failed", {"invoice_id": invoice.id, "tx_id": tx.id}) current_app.logger.exception("SDI send failed") - return False, tx, f"SDI send failed: {e}" + return False, tx, "SDI send failed" except Exception as e: tx.mark_failed(type(e).__name__) safe_commit("sdi_mark_failed", {"invoice_id": invoice.id, "tx_id": tx.id}) @@ -122,10 +123,11 @@ def refresh_status(self, tx: InvoiceSdiTransmission) -> dict: transport = self._transport(settings) data = transport.get_status(tx.message_id) except SdiTransportError as e: - return {"ok": False, "error": str(e)} - except Exception as e: + current_app.logger.warning("SDI status refresh transport error: %s", e) + return {"ok": False, "error": "SDI status refresh failed"} + except Exception: current_app.logger.exception("SDI status refresh failed") - return {"ok": False, "error": str(e)} + return {"ok": False, "error": "SDI status refresh failed"} sdi_id = data.get("sdi_identifier") or data.get("sdiIdentifier") if sdi_id: diff --git a/app/utils/fatturapa.py b/app/utils/fatturapa.py index 96b589272..ab2ccaaf7 100644 --- a/app/utils/fatturapa.py +++ b/app/utils/fatturapa.py @@ -178,9 +178,7 @@ def validate_fatturapa_ready(invoice: Any, settings: Any, client: Any) -> List[s if not _strip(getattr(settings, "company_name", None)): issues.append("Settings: company name is required (seller).") - if not ( - _strip(getattr(settings, "company_street", None)) or _strip(getattr(settings, "company_address", None)) - ): + if not (_strip(getattr(settings, "company_street", None)) or _strip(getattr(settings, "company_address", None))): issues.append("Settings: company street or address is required.") if not _strip(getattr(settings, "company_postcode", None)): issues.append("Settings: company postcode (CAP) is required.") @@ -292,6 +290,7 @@ def _collect_lines(invoice: Any) -> List[Dict[str, Any]]: } ) except Exception: + # Detached/lazy-load failures: fall through to expenses/goods/total fallback. pass try: expenses_rel = getattr(invoice, "expenses", None) @@ -302,6 +301,7 @@ def _collect_lines(invoice: Any) -> List[Dict[str, Any]]: amt = getattr(ex, "total_amount", 0) or 0 lines.append({"description": desc, "quantity": 1, "unit_price": amt, "line_total": amt}) except Exception: + # Detached/lazy-load failures: skip expenses and continue. pass try: goods_rel = getattr(invoice, "extra_goods", None) @@ -315,6 +315,7 @@ def _collect_lines(invoice: Any) -> List[Dict[str, Any]]: } ) except Exception: + # Detached/lazy-load failures: skip extra goods and continue. pass if not lines: # Fallback single line from invoice totals diff --git a/migrations/versions/209_add_fatturapa_sdi.py b/migrations/versions/209_add_fatturapa_sdi.py index 5b8e60724..007976dc7 100644 --- a/migrations/versions/209_add_fatturapa_sdi.py +++ b/migrations/versions/209_add_fatturapa_sdi.py @@ -21,6 +21,7 @@ def _has_column(inspector, table_name: str, column_name: str) -> bool: try: return column_name in {c["name"] for c in inspector.get_columns(table_name)} except Exception: + # Table may not exist yet during partial upgrades. return False @@ -47,7 +48,9 @@ def upgrade(): inspector, "settings", sa.Column("sdi_enabled", sa.Boolean(), nullable=False, server_default=sa.false()) ) _add_column_if_missing(inspector, "settings", sa.Column("sdi_transport_url", sa.String(length=500), nullable=True)) - _add_column_if_missing(inspector, "settings", sa.Column("sdi_transport_token", sa.String(length=255), nullable=True)) + _add_column_if_missing( + inspector, "settings", sa.Column("sdi_transport_token", sa.String(length=255), nullable=True) + ) _add_column_if_missing(inspector, "settings", sa.Column("sdi_transmitter_id", sa.String(length=16), nullable=True)) _add_column_if_missing( inspector, "settings", sa.Column("sdi_timeout", sa.Integer(), nullable=True, server_default="30") @@ -111,10 +114,12 @@ def downgrade(): try: op.drop_index("ix_invoice_sdi_transmissions_status", table_name="invoice_sdi_transmissions") except Exception: + # Index may already be absent on some backends after partial downgrades. pass try: op.drop_index("ix_invoice_sdi_transmissions_invoice_id", table_name="invoice_sdi_transmissions") except Exception: + # Index may already be absent on some backends after partial downgrades. pass op.drop_table("invoice_sdi_transmissions") diff --git a/tests/test_fatturapa.py b/tests/test_fatturapa.py index 87e1b7bab..837487ffb 100644 --- a/tests/test_fatturapa.py +++ b/tests/test_fatturapa.py @@ -118,9 +118,7 @@ def test_resolve_codice_pec_and_foreign(): def test_validate_fails_without_recipient(): - issues = validate_fatturapa_ready( - _invoice(), _settings(), _client(sdi_codice_destinatario="", pec_email="") - ) + issues = validate_fatturapa_ready(_invoice(), _settings(), _client(sdi_codice_destinatario="", pec_email="")) assert any("Codice Destinatario" in msg or "PEC" in msg for msg in issues) @@ -131,7 +129,7 @@ def test_validate_fails_without_provincia_for_it(): def test_build_fpr12_structure(): xml, filename, sha = build_fatturapa_xml(_invoice(), _settings(), _client(), "0002A") - assert "versione=\"FPR12\"" in xml or "versione='FPR12'" in xml + assert 'versione="FPR12"' in xml or "versione='FPR12'" in xml assert "FatturaElettronicaHeader" in xml assert "CedentePrestatore" in xml assert "CessionarioCommittente" in xml @@ -147,7 +145,7 @@ def test_build_fpa12_with_cig_cup(): client = _client(sdi_codice_destinatario="UFABC1") inv = _invoice(cig="Z1234567890", cup="J12C3400010001") xml, _fn, _sha = build_fatturapa_xml(inv, _settings(), client, "00001") - assert "versione=\"FPA12\"" in xml or "versione='FPA12'" in xml + assert 'versione="FPA12"' in xml or "versione='FPA12'" in xml assert "CodiceCIG" in xml assert "Z1234567890" in xml assert "CodiceCUP" in xml From 0bf6d09ddbfc08e071c1af12d0edcb894e823477 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 05:47:10 +0100 Subject: [PATCH 3/4] fix(lint): apply isort to FatturaPA/SDI modules CI lint failed after black because isort still needed to reorder imports in the new SDI files. --- app/integrations/sdi_transport.py | 1 + app/services/__init__.py | 2 +- app/utils/fatturapa.py | 2 +- tests/conftest.py | 2 +- tests/test_sdi_service.py | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/app/integrations/sdi_transport.py b/app/integrations/sdi_transport.py index 44ac0480b..b7d876564 100644 --- a/app/integrations/sdi_transport.py +++ b/app/integrations/sdi_transport.py @@ -5,6 +5,7 @@ import base64 import logging from typing import Any, Dict, Optional + import requests logger = logging.getLogger(__name__) diff --git a/app/services/__init__.py b/app/services/__init__.py index f868e18a6..d5f3372ad 100644 --- a/app/services/__init__.py +++ b/app/services/__init__.py @@ -16,11 +16,11 @@ from .notification_service import NotificationService from .payment_service import PaymentService from .peppol_service import PeppolService -from .sdi_service import SdiService from .permission_service import PermissionService from .project_service import ProjectService from .quote_service import QuoteService from .reporting_service import ReportingService +from .sdi_service import SdiService from .task_service import TaskService from .time_tracking_service import TimeTrackingService from .user_service import UserService diff --git a/app/utils/fatturapa.py b/app/utils/fatturapa.py index ab2ccaaf7..1fe6d0177 100644 --- a/app/utils/fatturapa.py +++ b/app/utils/fatturapa.py @@ -10,7 +10,7 @@ import hashlib import re import xml.etree.ElementTree as ET -from decimal import Decimal, ROUND_HALF_UP +from decimal import ROUND_HALF_UP, Decimal from typing import Any, Dict, List, Optional, Tuple FATTURAPA_NS = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" diff --git a/tests/conftest.py b/tests/conftest.py index 565c92d4e..42c003152 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -236,8 +236,8 @@ def app(app_config): InvoiceItem, InvoicePDFTemplate, InvoicePeppolTransmission, - InvoiceSdiTransmission, InvoiceReminderSchedule, + InvoiceSdiTransmission, InvoiceTemplate, KanbanColumn, Mileage, diff --git a/tests/test_sdi_service.py b/tests/test_sdi_service.py index 2e9805837..96ee952be 100644 --- a/tests/test_sdi_service.py +++ b/tests/test_sdi_service.py @@ -7,7 +7,7 @@ import pytest from app.integrations.sdi_transport import GenericSdiTransport, SdiTransportError, bridge_base_url -from app.models.invoice_sdi import InvoiceSdiTransmission, SDI_FINAL_STATUSES +from app.models.invoice_sdi import SDI_FINAL_STATUSES, InvoiceSdiTransmission def test_bridge_base_url_strips_send(): From b1d9cfcc8858ee13ae6238f699bf288bd8c91b8d Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 05:52:35 +0100 Subject: [PATCH 4/4] fix(lint): trim trailing whitespace in FatturaPA XSD fixtures CI trailing-whitespace hook rewrote the vendor schema fixtures; commit the cleaned copies so lint stays green. --- ..._del_file_xml_FatturaPA_versione_1.2.1.xsd | 28 ++-- .../fatturapa/xmldsig-core-schema.xsd | 142 +++++++++--------- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd b/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd index be131eb54..0a5f8db44 100644 --- a/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd +++ b/tests/fixtures/fatturapa/Schema_del_file_xml_FatturaPA_versione_1.2.1.xsd @@ -1,18 +1,18 @@  - - + - + XML schema fatture destinate a PA e privati in forma ordinaria 1.2.1 - + @@ -52,8 +52,8 @@ - - + + @@ -73,7 +73,7 @@ - + Fattura verso PA @@ -89,7 +89,7 @@ - + @@ -741,9 +741,9 @@ - + - + @@ -1446,4 +1446,4 @@ - \ No newline at end of file + diff --git a/tests/fixtures/fatturapa/xmldsig-core-schema.xsd b/tests/fixtures/fatturapa/xmldsig-core-schema.xsd index df126b30e..6a8854c03 100644 --- a/tests/fixtures/fatturapa/xmldsig-core-schema.xsd +++ b/tests/fixtures/fatturapa/xmldsig-core-schema.xsd @@ -2,7 +2,7 @@ @@ -29,7 +29,7 @@ + version="0.1" elementFormDefault="qualified"> @@ -42,16 +42,16 @@ - - - - - - + + + + + + - + @@ -64,21 +64,21 @@ - - - - - - + + + + + + - + - + @@ -88,48 +88,48 @@ - + - - - - + + + + - - - + + + - + - + - + - + - + - - + + @@ -141,26 +141,26 @@ - + - - - - - - + + + + + + - + - + @@ -169,18 +169,18 @@ - + - - + + - + @@ -194,10 +194,10 @@ - - - - + + + + @@ -205,17 +205,17 @@ - - + + - - + + - + @@ -226,13 +226,13 @@ - + - + @@ -240,40 +240,40 @@ - + - + - + - + - + - + - + - + - + - + - - + + @@ -306,10 +306,10 @@ - - + + - +