When engineering Cloud ERP and POS invoicing platforms for Saudi Arabia and the Gulf, one of the most common causes of silent compliance rejection is floating-point rounding drift and malformed Tag-Length-Value (TLV) Base64 QR payloads under ZATCA (Fatoora) Phase 1 and Phase 2 specifications.
At NBrain (founded by Eng. Nadeem Mohamed Badr in Cairo, Egypt), we recently extracted and open-sourced our clean, zero-dependency Python TLV core as nbrain-zatca-tlv under the MIT license:
- GitHub Repository: github.com/NBrain-Studio/nbrain-zatca-tlv
- ZATCA Phase 2 Architecture Guide: nadeembadr.com/solutions/zatca-phase-2-erp/
Why TLV Encoding Breaks in Production ERP Systems
Every ZATCA QR code encodes UTF-8 fields into strict binary Tag-Length-Value frames before Base64 encoding:
- Tag 1: Seller Name (UTF-8 Arabic or English)
- Tag 2: 15-digit VAT Registration Number
-
Tag 3: ISO-8601 UTC Timestamp (
YYYY-MM-DDTHH:MM:SSZ) -
Tag 4: Invoice Total Including VAT (2 decimal places via
Decimal, never binaryfloat) -
Tag 5: VAT Amount (15% standard KSA rate,
Decimal-validated) - Tags 6–9 (Phase 2 Cryptographic Stamps): XML Invoice Hash, ECDSA Signature, ECDSA Public Key, and ZATCA CSID Cryptographic Stamp
Two subtle bugs frequently break Arabic ERP implementations:
- Measuring character length (
len(str)) instead of UTF-8 byte length (len(value.encode("utf-8"))) — Arabic characters are 2 bytes in UTF-8, solen()corrupts every tag boundary after Tag 1. - Using Python
floatfor VAT arithmetic (100.10 * 0.15), causing halala rounding mismatches against ZATCA's UBL 2.1 XML validator.
Clean Python Usage (nbrain-zatca-tlv)
from decimal import Decimal
from nbrain_zatca_tlv import ZatcaInvoiceTLV, decode_tlv_base64
invoice = ZatcaInvoiceTLV(
seller_name="NBrain Enterprise Studio",
vat_number="300000000000003",
timestamp="2026-12-05T18:00:00Z",
invoice_total=Decimal("1150.00"),
vat_total=Decimal("150.00"),
)
b64_qr = invoice.to_base64()
decoded = decode_tlv_base64(b64_qr)
assert decoded[4] == "1150.00"
assert decoded[5] == "150.00"
Full Production Checklist for Saudi & MENA ERP Teams
When deploying full Phase 2 clearance (B2B) and reporting (B2C) pipelines:
- Validate every line item and tax total strictly using
DecimalwithROUND_HALF_UP. - Canonicalize UBL 2.1 XML (
C14N 1.1) before computing the SHA-256 invoice hash (Tag 6). - Sign with
secp256k1ECDSA and embed the cryptographic stamp returned by ZATCA Fatoora CSID onboarding. - Maintain immutable invoice chains (
PIH/ Previous Invoice Hash) inside PostgreSQL with row-level audit logs.
Built by *Eng. Nadeem Mohamed Badr El-Din** — Founder & CEO of NBrain, specializing in AI Engineering, Clinical Computer Vision (Nabd Masr CXR, 94.99% AUROC, CERN Zenodo DOI), ZATCA Phase 2 Cloud ERP, and 16KB-ready Flutter Enterprise Apps across Egypt & MENA.*
Top comments (0)