DEV Community

Anthony Leignel
Anthony Leignel

Posted on Edited on

⚙️ PHP Invoicing Engine Architecture: Factur-X, State Management, and Traceability Without a Database

Factur-X EN16931 pipeline — structured invoicing engine


title: PHP Invoicing Engine Architecture: Factur-X, State Management, and Traceability Without a Database
published: true
description: A technical overview of a PHP invoicing engine using Factur-X, CLI execution, file-based state management, batch processing, and explicit business rules.
tags: php, backend, architecture, automation

Use a ratio of 100:42 for best results.

published_at: 2026-03-04 21:41 +0000


Factur-X EN16931 pipeline: structured invoicing engine

Generating an electronic invoice involves more than producing a PDF document and embedding an XML file. In an automated system, the final document is the result of a processing pipeline that must ensure data consistency, invoice numbering, billing period management, and operational traceability.

The complexity increases when the same engine must support recurring invoices, batch processing, multiple VAT rates, or services covering several months.

This article presents an invoicing architecture developed in PHP, built around CLI scripts, structured files, and an explicit separation of responsibilities, without a database server.


1. General Engine Architecture

The system is organized around several independent components. Invoice generation, business rules, data validation, payments, and accounting exports each have their own responsibilities.

The public project structure is as follows:

automation-system/
│
├── engine/
├── data/
├── tools/
├── exports/
├── downloads/
├── clients/
├── contracts/
│
├── LICENCE.md
├── LICENSE.md
│
└── docs/
    ├── README_FR.md
    ├── README.md
    ├── SERVICE_MEMO_FR.md
    ├── SERVICE_MEMO.md
    ├── README_DEPLOY_FR.md
    ├── README_DEPLOY_EN.md
    ├── VUE_DENSEMBLE_AUTOMATION.md
    └── SYSTEM_OVERVIEW_AUTOMATION.md
Enter fullscreen mode Exit fullscreen mode

This directory structure represents the logical organization of the system. Internal script names and production files are not exposed in the public documentation.

Each directory has a distinct responsibility:

Directory Responsibility
engine/ Processing execution and invoicing logic
data/ Storage of data, invoices, and operational states
tools/ Maintenance, diagnostics, and additional processing
exports/ Accounting data generation
downloads/ Distribution of generated documents
clients/ Client configuration
contracts/ Contractual documents
docs/ Technical documentation

Pricing rules, line grouping, VAT rates, and service periods are centralized in the business logic layer.

This separation prevents billing rules from being scattered across document generation components. Pricing changes can therefore be handled independently of PDF and XML generation.


2. Two Invoicing Pipelines

The engine distinguishes between two generation modes.

Direct Invoicing

The first mode relies on individual client configuration files. It supports recurring or one-time invoices based on predefined billing rules.

The engine determines whether an invoice must be generated for the relevant period, checks existing execution states, and applies business rules before producing the document.

Client configuration
         │
         ▼
    Invoicing engine
         │
         ▼
     Business rules
         │
         ▼
   Factur-X generation
         │
         ▼
   Archiving and logging
Enter fullscreen mode Exit fullscreen mode

Batch Invoicing

The second mode processes CSV sources containing the data required to generate multiple invoices.

A CSV file is not treated as an invoice. It is a data source from which the engine constructs documents according to business rules.

CSV source
    │
    ▼
Data validation
    │
    ▼
Source archiving
    │
    ▼
Invoice composition
    │
    ▼
Calculations and business rules
    │
    ▼
Factur-X generation
    │
    ▼
Invoice archiving
Enter fullscreen mode Exit fullscreen mode

The engine supports composed invoices containing multiple line items, different VAT rates, or multiple service periods.

The complexity of the final document does not change the overall execution cycle. Both simple and composed invoices follow the same validation, generation, and archiving stages.


3. Strict Input Data Validation

In an invoicing engine, invalid data should not be silently corrected.

The import layer checks CSV structure, expected columns, and data formats before processing.

When required data is missing or invalid, the affected batch is stopped and an alert is generated.

This approach prioritizes data integrity over producing a partially correct result.

A CSV file may contain information about services, amounts, VAT rates, and recipient identification.

The data preparation workflow remains independent of the engine:

Invoicing data
      │
      ▼
   CSV file
      │
      ▼
Strict validation
      │
      ├── Invalid → Stop and alert
      │
      └── Valid
            │
            ▼
      Source archiving
            │
            ▼
         Invoicing
Enter fullscreen mode Exit fullscreen mode

The source file is archived before it is consumed. This frozen copy preserves the data used during execution, regardless of subsequent changes to the working file.

Stopping at the first error prevents further processing of data whose consistency has not been established. However, stopping execution does not automatically guarantee that previously completed operations can be rolled back.


4. Multi-Period Invoicing as a State Management Problem

An invoice covering several months introduces more than a calculation challenge. It also raises questions about consistency between service periods and previously issued documents.

Consider a conceptual example:

Client A

January  : Service worth €100
February : Service worth €100
March    : Service worth €100
Enter fullscreen mode Exit fullscreen mode

These three services can be grouped into a single invoice totaling €300 excluding VAT.

Once the invoice has been issued, the corresponding services must be identified as already invoiced. A subsequent execution must not generate a second invoice for the same operations.

The engine relies on execution markers and archives to preserve the information required for these checks.

A simplified representation of the states could be:

Client A
├── 2026-01 → invoiced
├── 2026-02 → invoiced
└── 2026-03 → invoiced
Enter fullscreen mode Exit fullscreen mode

This diagram illustrates the business principle, independently of the exact file format used by the engine.

The service period, invoice issue date, and invoice number represent distinct pieces of information. An invoice issued in April may cover services delivered between January and March without those periods being treated as new operations during the next execution.

Any necessary correction must be handled through an explicit accounting operation rather than a silent modification of the original document.


5. Native Factur-X Electronic Invoice Generation

Factur-X generation is integrated directly into both invoicing pipelines.

Factur-X is a hybrid format combining a human-readable PDF/A-3 document with a structured XML file that can be processed by software.

The engine targets the Comfort profile, corresponding to the requirements of the European EN 16931 standard.

The generation pipeline consists of several stages:

  • Construction of the invoice business data
  • Generation of the PDF representation
  • Construction of the structured XML
  • XML validation using XSD and Schematron
  • Embedding the XML into the PDF/A-3 document

The workflow can be represented as follows:

Validated business data
          │
          ├───────────────────┐
          ▼                   ▼
    PDF generation      XML generation
          │                   │
          │             XML validation
          │             XSD / Schematron
          │                   │
          └─────────┬─────────┘
                    ▼
              XML embedding
                    │
                    ▼
          PDF/A-3 + embedded XML
                    │
                    ▼
              Factur-X invoice
Enter fullscreen mode Exit fullscreen mode

Both representations of the invoice are generated from the same business data. This organization reduces the risk of inconsistencies between the amounts displayed in the PDF and those contained in the XML.

XSD validation checks the structure of the XML document, while Schematron verifies rules that go beyond basic syntactic validity.

The engine uses mPDF 8.3 as part of its document generation pipeline.

The final result is a single hybrid document containing the structured XML within the PDF.

Generating a document that complies with the Factur-X format must, however, be distinguished from transmitting it through a regulated electronic invoicing framework. Document compliance and document delivery are two separate responsibilities.


6. Invoice Numbering and Duplicate Processing Prevention

Invoice generation is an operation that must not be repeated unintentionally.

A subsequent engine execution must not create another invoice for an already processed operation or incorrectly reuse an invoice number.

The architecture relies on several complementary mechanisms:

  • Annual sequential counters for invoice numbering
  • Explicit execution markers
  • Immutable archives
  • Consistency checks
  • Duplicate processing prevention mechanisms
  • Operational logging

The underlying principle is to inspect existing states before deciding whether an operation should be executed.

New execution
      │
      ▼
State verification
      │
      ├── Already processed → Skip
      │
      └── Pending
            │
            ▼
        Generation
            │
            ▼
         Archiving
            │
            ▼
      State recording
Enter fullscreen mode Exit fullscreen mode

This mechanism addresses an idempotency objective: repeating an already completed operation should not produce an additional business effect.

However, preventing repeated sequential processing must be distinguished from protecting against concurrent executions.

A simple file existence check does not constitute an atomic lock. If two processes inspect the same state simultaneously before it is updated, both may consider the operation available for processing.

In a PHP architecture without a database, an exclusive lock can be implemented using flock().

$lock = fopen($lockPath, 'c');

if ($lock === false) {
    throw new RuntimeException(
        'Unable to open lock file'
    );
}

if (!flock($lock, LOCK_EX | LOCK_NB)) {
    fclose($lock);
    exit;
}

try {
    // Check the operation state.
    // Generate only if necessary.
    // Record the result and final state.
} finally {
    flock($lock, LOCK_UN);
    fclose($lock);
}
Enter fullscreen mode Exit fullscreen mode

This example illustrates one possible approach to protecting against concurrent executions. It is not an excerpt from the engine presented in this article.

Execution locks and business state markers address two different requirements. The former controls concurrent access to an operation, while the latter preserves a durable record of its completion.

This distinction becomes particularly important when multiple processes may access the same counter or set of billing periods.


7. Cron-Driven CLI Execution

The engine does not rely on a persistent process. PHP scripts are executed from the command line, typically through cron jobs.

Each execution starts, reads the available data and states, processes the required operations, logs the results, and terminates.

Cron
  │
  ▼
Process startup
  │
  ▼
Configuration loading
  │
  ▼
State verification
  │
  ▼
Operation processing
  │
  ▼
Archiving and logging
  │
  ▼
Process termination
Enter fullscreen mode Exit fullscreen mode

Scheduling and business decisions remain separate. Cron triggers execution, but the engine determines whether an operation should actually be performed.

Invoice generation and transmission are also separate operations.

An invoice can be generated and archived without being transmitted immediately. Document distribution is an additional stage governed by its own execution conditions.

This organization preserves business safeguards independently of how frequently scheduled tasks run.

It also avoids maintaining a persistent service whose only purpose would be to wait for the next invoicing operation.


8. Targeted Recovery and Error Handling

The absence of a persistent process simplifies the execution model, but it does not eliminate the need to handle interruptions.

An error may occur after a document has been generated, before its final state has been recorded, or during its transmission.

The engine maintains archives, execution markers, and logs that help identify completed operations and those requiring further verification.

Some CLI components also accept a parameter that targets a single client:

--client=<client_id>
Enter fullscreen mode Exit fullscreen mode

This mode allows targeted diagnostics or recovery without restarting processing for every client.

It does not alter business rules and preserves duplicate prevention controls and execution states.

Reliable recovery nevertheless requires checking the consistency of the different artifacts. The presence of a PDF does not necessarily mean that the entire operation has been completed.

In a file-based architecture, handling interruptions between multiple write operations is therefore an important consideration.

The absence of a database does not remove the need to define consistency and recovery rules.


9. Separating Invoicing from Payments

Generating an invoice and recording a payment are two distinct business operations.

The engine stores issued documents, invoicing data, recorded payments, and calculated balances separately.

Issued invoices       Recorded payments
       │                       │
       └───────────┬───────────┘
                   ▼
           Data reconciliation
                   │
                   ▼
             Client balances
Enter fullscreen mode Exit fullscreen mode

Payments are recorded manually based on received bank transfers. The engine does not initiate automatic payment collection and does not depend on a payment provider.

The reconciliation layer compares invoiced amounts with recorded payments to calculate the outstanding balance.

A simplified example:

Total invoiced      : €1,200
Total paid          :   €800
Outstanding balance :   €400
Enter fullscreen mode Exit fullscreen mode

Updating the balance does not modify existing invoices.

An additional tool can also produce paid invoice documents after payment has been confirmed.

This tool accepts ZIP archives containing multiple PDF invoices and can apply an explicit payment stamp with the payment date. The FPDI library is used for reading and overlaying PDF documents.

Paid invoice documents are derived versions of the original invoices, which remain unchanged.

This separation allows financial tracking mechanisms to evolve without modifying the document generation pipeline.


10. Traceability, Archiving, and Accounting Exports

Storage relies on structured files rather than a database server.

Each category of data has a distinct responsibility. Archived CSV sources, issued invoices, logs, and payment records provide the information required to trace operations.

Accounting exports are generated from these source records.

Invoices + Payments + Archives
                │
                ▼
           Export layer
                │
                ▼
       Monthly or annual CSV
Enter fullscreen mode Exit fullscreen mode

Exports can be regenerated without modifying the original documents.

It is important, however, to distinguish archives from operational states. An issued invoice or archived CSV source is intended to remain unchanged, while a counter or client balance necessarily evolves over time.

Using files does not automatically provide the transactional guarantees of a database.

Reliability depends on disciplined write operations, concurrent access management, backups, and consistency between the different artifacts.

This architecture prioritizes readability and traceability, but it does not claim to replace database transaction mechanisms in every context.


11. Separating Web Interfaces from the Engine

The invoicing engine is designed to run exclusively through server-side CLI execution.

Separate web interfaces can nevertheless supply the system with data, particularly for preparing client configurations, uploading CSV files, and distributing generated documents.

The public structure of this layer is as follows:

web/
│
├── library/
│   ├── onboarding-client-fr.html
│   ├── onboarding-client-en.html
│   ├── service-agreement-fr.html
│   ├── service-agreement-en.html
│   ├── import-clients-fr.html
│   ├── import-clients-en.html
│   └── invoice-layout.html
│
├── contract-builder.php
├── process-import.php
│
├── secure_downloads/
│   └── access.php
│
└── temp_tokens/
    ├── activity.log
    └── secure_tokens.json
Enter fullscreen mode Exit fullscreen mode

These components have limited responsibilities related to data preparation, collection, or document distribution.

They do not provide a direct execution interface for the financial engine.

Controlled web interface
           │
           ▼
   Structured input data
           │
           ▼
       Input storage
           │
           ▼
     CLI / cron engine
           │
           ▼
  Private data and documents
Enter fullscreen mode Exit fullscreen mode

This separation reduces the engine's attack surface by avoiding direct browser exposure of execution scripts and financial data.

It does not eliminate the risks associated with public interfaces, which must maintain their own access controls, validation mechanisms, and data protection measures.


Conclusion

Designing an automated invoicing engine involves considerably more than producing a PDF and an XML file.

Billing period management, duplicate processing prevention, invoice numbering, data validation, and the separation between invoicing and payments are the primary architectural challenges.

An organization built around PHP, CLI scripts, and structured files makes it possible to construct an invoicing pipeline without a database server or a critical dependency on a SaaS platform.

This approach offers advantages in terms of readability and traceability, but it also requires explicit handling of concurrency, recovery after interruptions, and state consistency.

Factur-X generation becomes one stage within a larger system whose reliability depends primarily on how its execution lifecycle is managed.

Technical Documentation

The GitHub repository presents the architecture, design principles, and system documentation. It does not contain downloadable source code or production files.

Architecture documentation on GitHub


https://palks-studio.com

Top comments (0)