=== Tropratik e-Facture ===
Contributors: tropratik
Tags: factur-x, chorus pro, facturation electronique, woocommerce, e-invoicing
Requires at least: 6.2
Tested up to: 7.0
Requires PHP: 8.1
Stable tag: 1.1.4
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Factur-X (EN 16931) invoices for WooCommerce orders and transmission to Chorus Pro. Compliant with the French e-invoicing reform.

== Description ==

**Tropratik e-Facture** generates, for every WooCommerce order, a **PDF invoice** that can be **sent automatically by e-mail** to your customer.

The plugin also provides **optional transmission to Chorus Pro**, the French State platform. This transmission is never mandatory: you can use Tropratik e-Facture **solely to produce electronic invoices in a format compliant with the French reform**, even when you invoice **businesses (B2B)**, without sending anything to Chorus Pro.

As of today, Chorus Pro only accepts invoices addressed to the **public sector**. The plugin is designed to **evolve** and connect to the **other approved platforms (PDP/PPF)** as they open, within the framework of the **French electronic invoicing reform**.

Beyond the classic PDF, **Tropratik e-Facture** turns your orders into genuine electronic invoices compliant with the European **Factur-X (EN 16931)** standard: a human-readable PDF embedding the structured XML data required by the administration.

The plugin is designed for the **French electronic invoicing reform (2026)**:

* **Public sector (B2G)** — direct transmission to **Chorus Pro** through the PISTE API (sandbox and production environments).
* **Business-to-business (B2B)** — architecture ready to evolve towards the approved platforms (PDP/PPF) as the flows open.

= Key features =

* Automatic generation of **Factur-X / ZUGFeRD** invoices (PDF/A-3 with embedded EN 16931 XML).
* **Sending to Chorus Pro**, manual (from the orders list) or automatic on order completion.
* Configurable automatic **sending scope**: public sector (B2G) by default, with B2B / B2C options.
* Configurable invoice **numbering**: custom prefix, dynamic tags (year, month…) and periodic reset.
* **Appearance customization**: logo, accent colors, font, and an invoice template that can be overridden from your theme.
* **Direct connection or dedicated VPS proxy** to bypass a WAF block (403 error) on the hosting side, with a built-in connection test button.
* Diagnostic tools: test of the **PISTE (OAuth2)** credentials, of the **Chorus Pro technical account** and of the **proxy connection**.
* **Encrypted secrets in the database**: the PISTE client_secret, the Chorus Pro technical passwords and the proxy password are stored encrypted (libsodium / OpenSSL), never in clear text.
* **HPOS compatible** (High-Performance Order Storage) and classic order storage mode.
* **WooCommerce REST API**: each order exposes a read-only `tropratik_ef_invoice` field (invoice number, generation date, client type, Chorus Pro status and flow id, PDF SHA-256), for your integrations and exports.
* **Translation ready** (text domain `tropratik-e-facture`).

= Prerequisites =

Using Chorus Pro requires steps independent from this plugin, carried out once:

1. Creation of an account on **PISTE** (the French State API portal) and retrieval of the OAuth2 credentials (Client ID / Secret).
2. Creation of a **Chorus Pro technical account** (qualification then production).
3. Declaration of the API connection for your organization.

The plugin provides, in its "Chorus Pro" tab, a step-by-step guide and test buttons to validate each step.

= Learn more =

A detailed walkthrough of the plugin and its features is available on our website: [Facturez vos commandes WooCommerce au format Factur-X](https://tropratik.fr/facturez-vos-commandes-woocommerce-au-format-factur-x).

= Trademarks and affiliation =

Tropratik e-Facture is an **independent** product, **not affiliated with nor endorsed by** the organizations or vendors mentioned. The names **Chorus Pro** and **PISTE** (French State / AIFE trademarks), **Factur-X** (FNFE-MPE trademark) and **WooCommerce** (trademark of Automattic Inc.) are used only for **descriptive** purposes, to indicate the plugin's compatibility and interoperability. All trademarks cited belong to their respective owners.

= Published by =

[Tropratik.fr](https://www.tropratik.fr)

= En français =

**Tropratik e-Facture** génère, pour chaque commande WooCommerce, une **facture PDF** qui peut être **envoyée automatiquement par e-mail** à votre client. Au-delà du PDF classique, le module transforme vos commandes en véritables **factures électroniques Factur-X (EN 16931)** : un PDF lisible embarquant les données structurées XML exigées par l'administration.

Le module assure aussi, **de façon optionnelle**, la **transmission à Chorus Pro** (plateforme de l'État) via l'API PISTE, en bac à sable comme en production. Cette transmission n'est jamais obligatoire : vous pouvez l'utiliser **uniquement pour produire des factures conformes à la réforme française de la facturation électronique (2026)**, y compris en B2B, sans rien envoyer à Chorus Pro.

Principales fonctionnalités : génération Factur-X / ZUGFeRD (PDF/A-3), envoi manuel ou automatique à Chorus Pro, périmètre d'envoi configurable (B2G / B2B / B2C), numérotation personnalisable, personnalisation de l'apparence et modèle surchargeable depuis le thème, connexion directe ou via proxy VPS dédié (contournement d'un blocage WAF 403), outils de test des identifiants, secrets chiffrés en base (libsodium / OpenSSL), exposition des données de facture dans l'API REST WooCommerce (champ `tropratik_ef_invoice` en lecture seule sur chaque commande), compatibilité HPOS et prêt pour la traduction.

L'utilisation de Chorus Pro nécessite des démarches indépendantes réalisées une seule fois : compte **PISTE** (identifiants OAuth2), **compte technique Chorus Pro** (qualification puis production) et déclaration du raccordement API. L'onglet « Chorus Pro » fournit un guide pas à pas et des boutons de test pour valider chaque étape.

Une présentation détaillée du module et de ses fonctionnalités est disponible sur notre site : [Facturez vos commandes WooCommerce au format Factur-X](https://tropratik.fr/facturez-vos-commandes-woocommerce-au-format-factur-x).

Tropratik e-Facture est un produit **indépendant**, non affilié ni approuvé par les organismes cités. Les marques **Chorus Pro**, **PISTE**, **Factur-X** et **WooCommerce** ne sont utilisées qu'à des fins descriptives et appartiennent à leurs détenteurs respectifs.

== External services ==

This plugin can connect to **Chorus Pro**, the French State's public-sector e-invoicing platform, through the **PISTE** API gateway (operated by the AIFE, French State). These connections are **optional**: they only happen when you enter your own credentials and either send an invoice manually or enable automatic sending. If you never configure credentials and never trigger a transmission, the plugin sends no data to any external service.

**PISTE — API gateway of the French State**
Used to authenticate your access to the Chorus Pro API. The plugin performs an OAuth2 "client_credentials" request to obtain a short-lived access token. Data sent: your PISTE credentials (client_id and client_secret), each time a new token is required. Endpoints: https://oauth.piste.gouv.fr (production) and https://sandbox-oauth.piste.gouv.fr (test).
Terms of use / GDPR: https://piste.gouv.fr/cgu — Legal notice: https://piste.gouv.fr/mentions-legales

**Chorus Pro — public-sector e-invoicing platform (AIFE)**
Used to submit your invoices to the public sector and to check their processing status. Data sent, only when you submit or track an invoice: the Factur-X PDF file (which contains the invoice data — your company details, the customer's billing details, order lines, amounts and VAT), your Chorus Pro technical account identifier, and, when checking a status, the deposit flow identifier returned by Chorus Pro. Endpoints: https://api.piste.gouv.fr/cpro/ (production) and https://sandbox-api.piste.gouv.fr/cpro/ (test).
Terms of use: https://portail.chorus-pro.gouv.fr/aife_csm?id=aife_cgu — Personal data & security: https://portail.chorus-pro.gouv.fr/aife_csm?id=aife_security — Legal notice: https://portail.chorus-pro.gouv.fr/aife_csm?id=aife_legal

**Optional self-hosted proxy**
To work around a hosting firewall (WAF) that blocks PISTE, you may route these requests through a proxy server **that you set up and control yourself**. This is not a third-party service operated by us or by anyone else: no additional data is sent to any party other than the services listed above and your own proxy.

= En français =
Ce plugin se connecte, de façon optionnelle, à **PISTE** (passerelle d'API de l'État) pour s'authentifier, puis à **Chorus Pro** (plateforme de facturation électronique du secteur public, AIFE) pour déposer vos factures et suivre leur statut. Aucune donnée n'est transmise tant que vous n'avez pas saisi vos identifiants et déclenché un envoi (manuel ou automatique). Sont alors transmis : vos identifiants OAuth2 PISTE (pour obtenir un jeton), le PDF Factur-X de la facture (données de facturation) et l'identifiant de votre compte technique Chorus Pro. Un proxy que vous hébergez vous-même peut éventuellement relayer ces requêtes (contournement d'un WAF) ; aucune donnée n'est envoyée à un tiers autre que les services ci-dessus.
CGU PISTE : https://piste.gouv.fr/cgu — CGU Chorus Pro : https://portail.chorus-pro.gouv.fr/aife_csm?id=aife_cgu — Données personnelles : https://portail.chorus-pro.gouv.fr/aife_csm?id=aife_security

== Installation ==

1. Make sure **WooCommerce** is installed and active, and that your server runs **PHP 8.1 or higher**.
2. Upload the plugin folder to `/wp-content/plugins/`, or install it from the WordPress "Plugins" screen.
3. Activate the plugin through the "Plugins" menu.
4. Go to **WooCommerce → Tropratik e-Facture** to configure:
   * the **Issuer & Options** tab (your legal information and the numbering),
   * the **Invoice appearance** tab (logo, colors, template),
   * the **Chorus Pro** tab (PISTE credentials, technical account, proxy and automatic sending).
5. Use the test buttons in the "Chorus Pro" tab to validate your credentials before the first transmission.

== Frequently Asked Questions ==

= Does the plugin send my invoices to Chorus Pro automatically? =

Only if you enable the "Automatic sending" option in the Chorus Pro tab. By default, only invoices addressed to the public sector (B2G) are sent. Manual sending remains always available from the orders list.

= Are my invoices compliant with the 2026 reform? =

Invoices are generated in the Factur-X format compliant with the European standard EN 16931, the foundation of the French reform. The plugin is designed to evolve towards the approved platforms (PDP/PPF) as the B2B flows open.

= My host is blocked by PISTE (403 error). What can I do? =

The Chorus Pro tab offers a "Via VPS proxy" connection. You install a proxy on a dedicated server, enter its parameters in the plugin, then use the "Test proxy connection" button to verify that it correctly relays requests to PISTE. This test depends neither on the PISTE credentials nor on the technical account.

= Can I customize the invoice layout? =

Yes. The "Invoice appearance" tab lets you set the logo, colors and font. To go further, you can download the `invoice.php` template, modify it, then place it in your theme (for example `wp-content/themes/your-theme/tropratik-e-facture/invoice.php`): it will replace the default template. This theme override follows the standard WooCommerce practice and survives plugin updates.

= Is the plugin HPOS compatible? =

Yes, the plugin is compatible with High-Performance Order Storage (HPOS) and with the classic order storage mode.

= Can I retrieve the invoice data through the WooCommerce REST API? =

Yes. For every order, the plugin adds a read-only `tropratik_ef_invoice` field to the WooCommerce REST API response (for example `GET /wp-json/wc/v3/orders/{id}`). It contains the invoice number, the generation date (site time and UTC), the client type (in English: `individual`, `business` or `public_sector`), the Chorus Pro status and flow id, and the SHA-256 hash of the PDF. The field is `null` when no invoice exists yet, is never writable, and never exposes the server file path. Access requires the standard WooCommerce REST API authentication and read permission on orders.

= How are my credentials and sensitive passwords stored? =

The most sensitive secrets — the **PISTE client_secret**, the **Chorus Pro technical passwords** and the **proxy password** — are never kept in clear text in the database. They are **encrypted at rest** using libsodium (with an OpenSSL AES-256-GCM fallback) and decrypted only when contacting the APIs. This protection limits exposure if the database alone leaks (stolen SQL backup, SQL injection from another plugin, etc.).

The encryption key is derived from the security *salts* of your `wp-config.php` file. **Important:** if these *salts* are regenerated, the secrets will have to be re-entered in the "Chorus Pro" tab. To make the key independent from the *salts* (useful during a migration or a site restore), define a dedicated constant in `wp-config.php`:

`define( 'TROPRATIK_EF_ENCRYPTION_KEY', 'a-long-random-and-secret-string' );`

Credentials already stored in clear text by an earlier version are encrypted automatically the next time the form is saved, with no action required on your part.

== Screenshots ==

1. Example of a generated Factur-X invoice (PDF/A-3 with embedded EN 16931 XML).
2. WooCommerce orders list: the "Facture / Chorus Pro" column shows, for each order, the invoice status and its transmission to Chorus Pro (Sent, Accepted), with one-click actions.
3. "Invoice appearance" tab: logo, colors and template override via the theme.
4. "Chorus Pro" tab: configuration of the PISTE credentials, the technical account and the VPS proxy, with test buttons.

== Changelog ==

= 1.1.4 =
* New: PEPPOL addressing fully aligned with the French e-invoicing reform (XP Z12-012): seller (BT-34) and buyer (BT-49) electronic addresses now use scheme `0225` with SIREN, SIREN+SIRET, SIREN+Suffix or SIREN+SIRET+RoutingCode formats. Configurable in the emetteur settings and at checkout for B2B/public-sector orders.
* New: buyer identifier `GlobalID` (BT-46) now included in the XML for B2B and public-sector orders (SIREN with scheme `0225`), improving automatic routing on PDP platforms.
* New: seller identifier `GlobalID` (BT-29) now included (SIREN with scheme `0225`).
* New: buyer reference (BT-10) now set for B2B orders (WooCommerce order number), satisfying PEPPOL rule R003.
* New: actual delivery date (BT-72) and delivery address (BG-15) now included in the Factur-X XML.
* Fix: invoice date (BT-2) now reflects the generation date instead of the order creation date, in compliance with art. 289 CGI.
* Fix: VAT category code (BT-95) now correctly set to `E` (Exempt) when the seller is in franchise en base (`tva_assujetti = non`), regardless of the buyer\'s VAT status.
* New: SIRET and PEPPOL format fields are now required at checkout for B2B clients. Suffixe/routing-code fields become required when their format is selected.
* New: computed PEPPOL address preview (BT-49) added at checkout and in the admin order detail.
* New: PEPPOL addresses (BT-34, BT-49) and invoice date/number now shown on the customer order page and in the WooCommerce admin order panel.
* New: PEPPOL addresses (BT-34, BT-49) added to the generated PDF invoice.
* Fix: minimum WordPress version bumped to 6.2 (required for `$wpdb->prepare()` with `%i` identifier placeholder).

= 1.1.3 =
* Fix: Factur-X XML field BT-34 (Seller electronic address) now uses the issuer SIRET with EAS scheme `0009` (the standard French identifier) instead of the email with scheme `EM`, which was not in the official EAS code list and caused some platforms (PDP/PPF) to report the field as missing.
* Fix: Factur-X XML field BT-49 (Buyer electronic address) now uses the customer SIRET with scheme `0009` for B2B/public-sector orders. For individual buyers, BT-49 is omitted (it is an optional field in EN 16931 and there is no valid EAS scheme for a private email address).
* Fix: EN 16931 mandatory rule BR-61 — when the payment method is WooCommerce bank transfer (`bacs`), the seller IBAN and BIC are now included in the Factur-X XML (BT-84 and BT-86), read from the payment gateway settings. All other payment methods now use the correct UNTDID 4461 code without triggering the BR-61 violation.
* Fix: Factur-X XML field BT-121 (Tax exemption reason code) is now populated with the appropriate VATEX code (`VATEX-EU-O`, `VATEX-EU-IC`, `VATEX-EU-G`) matching the exemption reason configured in the plugin settings.
* Fix: WooCommerce payment methods are now mapped to their correct UNTDID 4461 codes. Coverage extended to Stripe (all types), Mollie, PayPal/PPCP, Braintree, Square, Klarna, Alma, WooCommerce Payments and more. SEPA direct debit uses code 59; third-party bank transfers use code 42; unknown methods default to code 97 (not defined) to avoid BR-61.
* Fix: database upgrade routine `migrate_1_2()` now creates the `tropratik_ef_invoice_number` table before attempting to add columns. This prevents a silent failure when upgrading from v1.0.x to v1.1.x via the WordPress update button (without deactivating and reactivating the plugin first). No action required on existing installations.

= 1.1.2 =
* Fix: fatal error (HTTP 500) on every WooCommerce REST API request when reading orders — `Tropratik_EF_Invoice_Number::get_sequence()` was missing from the published 1.1.1 package due to a missing SVN commit before tagging. No database change or manual action required.

= 1.1.1 =
* Change: in the WooCommerce REST API invoice field, the formatted invoice number has moved from `number` to the new `formatted_number` key. If you read this field in an integration, update the key accordingly.
* New: the `number` key now holds the legal numbering sequence position as an integer (for example `11`), distinct from the internal row `id`.
* New: the REST API invoice field now also exposes `file_slug` (the PDF file name without extension) and `file_name` (with the `.pdf` extension). The server file path is still never exposed.
* New: the REST API invoice field now exposes `facturx_profile`, the Factur-X profile actually used to generate the invoice (`MINIMUM`, `BASICWL`, `BASIC`, `EN16931`, `EXTENDED`). This value is now stored per invoice; invoices generated by earlier versions return `null`. A database column is added automatically on update, no action required.

= 1.1.0 =
* New: read-only `tropratik_ef_invoice` field added to the WooCommerce REST API order response (invoice number, generation date in site time and UTC, client type, Chorus Pro status and flow id, PDF SHA-256). Read-only, never exposes the server file path.
* New: the `client_type` value in the REST API is now returned in English (`individual`, `business`, `public_sector`). The French labels shown in the admin UI and on the PDF invoice are unchanged (rendered through the plugin's translations).
* Fix: on the PDF invoice, when no logo is set, the issuer name is now displayed in the top-right block together with its address (previously shown in the top-left corner).

= 1.0.0 =
* Initial release.
* Generation of Factur-X invoices (EN 16931).
* Manual and automatic sending to Chorus Pro through the PISTE API (sandbox and production).
* Direct connection or via VPS proxy, with test buttons (PISTE, technical account, proxy).
* Configurable numbering and invoice appearance customization.
* HPOS compatibility.

== Upgrade Notice ==

= 1.1.4 =
Adds PEPPOL 0225 addressing (BT-34/BT-49) for the French e-invoicing reform, fixes invoice date (BT-2) and VAT category for franchise sellers. SIRET is now required at checkout for B2B. Requires WordPress 6.2+.

= 1.1.3 =
Fixes EN 16931 XML compliance: PEPPOL addressing (BT-34/BT-49), IBAN for bank transfers (BR-61), VAT exemption codes (BT-121), and extended payment method mapping. Database migration safety fix included. No data migration needed.

= 1.1.1 =
The REST API formatted invoice number moves from `number` to `formatted_number`; `number` now holds the integer numbering sequence, and a new `facturx_profile` field is exposed. This version adds a database column automatically (no action required). Update your integrations if you read these fields.

= 1.1.0 =
Adds a read-only invoice field to the WooCommerce REST API order response and fixes the issuer name position on the PDF when no logo is set. No database change and no configuration required.

= 1.0.0 =
Initial release of the plugin.
