Urgent.News

What's breaking now, across hundreds of outlets.

Tech

How to Generate Official Saudi ZATCA Phase-1 TLV QR Codes in Pure TypeScript (Fixing the Arabic UTF-8 Bug)

If you have ever built an e-invoicing app for Saudi Arabia (KSA), you know ZATCA Phase-1 (Fatoora) requires every simplified tax invoice to carry a Base64-encoded TLV (Tag-Length-Value) QR code with 5 fields: Tag 1: Seller Name Tag 2: Seller VAT Registration Number (15 digits) Tag 3: Invoice Timestamp (ISO 8601) Tag 4: Invoice Grand Total (including VAT) Tag 5: VAT Total Amount The #1 Bug That…

In the realm of e-invoicing applications for Saudi Arabia, ZATCA Phase-1 (known as Fatoora) mandates that every simplified tax invoice include a Base64-encoded TLV (Tag-Length-Value) QR code. This QR code contains five crucial fields: the seller's name, their VAT registration number, the invoice timestamp, the invoice grand total (including VAT), and the VAT total amount individually.

However, a significant bug has plagued many quick JavaScript snippets that aim to generate these QR codes. The bug primarily lies in the calculation of the TLV (Tag-Length-Value) Length byte. In languages like JavaScript, the `string.length` method is commonly used as the TLV Length byte. While this works fine for English or Latin characters, it falls short when dealing with Arabic text. This is because `string.length` in JavaScript measures the number of Unicode code units, not the actual number of UTF-8 bytes.

For example, the Arabic word "شركة" (meaning "company") consists of 8 UTF-8 bytes, but the `string.length` method would incorrectly return 4. This discrepancy leads to the TLV frame being corrupted and subsequently, the ZATCA's Fatoora QR scanner failing to validate the invoice correctly.

The fix to this problem lies in utilizing the `TextEncoder` API, a browser-native implementation, in TypeScript. This method accurately calculates the UTF-8 byte length for the seller's name, even when it contains Arabic characters. The implementation is straightforward and does not require any external dependencies.

A TypeScript function named `encodeTlvField` is created to encapsulate this logic. This function takes two parameters: the tag number and the value string. It first trims the value string, then encodes it into UTF-8 bytes using the `TextEncoder`. Following this, it creates a new `Uint8Array` with a length of 2 plus the actual byte length of the value.

The tag number is placed at the first byte position, the byte length follows at the second byte, and the actual UTF-8 bytes are set starting from the third position. This ensures that the TLV frame is correctly formed for Arabic texts as well.

Finally, the `generateZatcaPhase1Base64` function is provided to generate the complete Base64-encoded TLV QR code. This function accepts an object of type `ZatcaInvoiceInput`, which contains all the necessary data for an invoice. It maps each invoice field to a TLV field using the `encodeTlvField` function, merges these segments into a single byte array, and finally encodes this array into a Base64 string.

For those interested in testing this implementation, a live demo is available online. It allows users to input data, including Arabic seller names, and generates a QR code compliant with ZATCA Phase-1 requirements. This tool supports A4 PDF export, digital signatures, and conversion from quote to invoice, all without requiring any server setup.

The complete source code, which includes comprehensive tests for UTF-8 Arabic TLV units, is available on Codester for those who wish to self-host this solution for their own applications.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

Stop Data Leaks in Multi-Tenant Apps with PostgreSQL Row-Level Security

Most multi-tenant SaaS bugs are not complex logic failures. They are simple, silent data leaks. They happen when a query is missing a single WHERE tenant_id = $1 clause.

  • Multi-tenant apps leak data due to missing WHERE clauses
  • PostgreSQL's Row-Level Security (RLS) provides isolation
  • Implement RLS by enabling it and defining policies on tables

HackerGadgets 4-in-1 Pi 5 HAT: RTL2832U, SX1262, GPS & RTC

The Guangzhou-based HackerGadgets RTL-SDR/LoRa/GPS/RTC HAT is a 4-in-1 RF expansion board for Raspberry Pi. It eliminates external USB dongles, though it still requires an internal USB bridge and caps…

  • HackerGadgets releases 4-in-1 Pi 5 HAT
  • Features RTL2832U, SX1262, GPS, and RTC
  • Compatible with Raspberry Pi 5's GPIO header

I benchmarked 5 ways to auto-tune a robot arm's PID gains. Random search broke the safety limits in 73.8% of trials. Safe BO: 1.8%.

Hand-tuning PID gains is slow, and every payload change means starting over. Letting an optimiser explore on the real machine is tempting — but a "trial" there isn't a wasted data point, it's a torque…

  • Random search broke safety limits in 73.8% of trials
  • Safe Bayesian Optimization achieved only 1.8% unsafe trials
  • Warm-starting proved more effective than advanced acquisition functions

Why I moved my file tools to the browser (and what broke along the way)

Every "convert HEIC to PNG" or "compare two files" site I used had the same quiet problem: my file went to someone's server. For a holiday photo, fine.

  • Author moved file tools to browser to reduce server storage and improve privacy.
  • Encountered issues with image conversion, diffing, and JSON handling in browser processing.

Analyzing doctors data using SQL

Today, I focused on analyzing hospital records from a doctor's perspective. Instead of writing queries just to retrieve rows, I started asking meaningful questions that someone in hospital management…

  • Hospital doctors' data analyzed using SQL to answer management questions
  • Queries written to find available doctors, patients per doctor, gender distribution
  • Concepts like GROUP BY, COUNT(), ORDER BY, WHERE, ILIKE used for analysis

More from Tuesday 24 November →