Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Preserve official FeRD artifact bytes, including original line endings.
src/pax.XRechnung.NET/Resources/Zugferd/2.3.3/Schema/** -text
src/pax.XRechnung.NET.tests/Resources/zugferd/** -text
94 changes: 90 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,26 +101,112 @@ public static InvoiceBaseDto GetInvoiceBaseDto()
var xmlText = XmlInvoiceWriter.Serialize(xmlInvoice);
```

**Validate schematron - requires [Kosit validator](#java-schematron-validator)**
**Validate schema and Schematron locally (.NET and Blazor WASM)**
```csharp
var invoiceBaseDto = GetInvoiceBaseDto();
var mapper = new InvoiceMapper();
XmlInvoice xmlInvoice = mapper.ToXml(invoiceBaseDto);
var result = await XmlInvoiceValidator.ValidateSchematron(xmlInvoice);
var resultText = string.Join(Environment.NewLine, result.Validations.Select(s => $"{s.Severity}:\t{s.Message}"));
Assert.IsTrue(result.Validations.Count == 0, resultText);
var resultText = string.Join(Environment.NewLine, result.Validations.Select(s => $"{s.RuleSeverity}:\t{s.Code}: {s.Message}"));
Assert.IsTrue(result.IsValid, resultText);
```
**The InvoiceBaseDto is designed to be easily extended see [BaseDtoExtensionTests](src/pax.XRechnung.NET.tests/BaseDtoExtensionTests.cs)**

`ValidateSchematron` now runs locally when no server URI is supplied. It supports
standard XRechnung 3.0 UBL Invoice documents with customization ID
`urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0`.
The embedded rules are pinned to KoSIT configuration **2026-08-31**, using
EN 16931 **1.3.16** and XRechnung Schematron **2.6.0**. Extension, CVD, UBL
CreditNote, CII, and other profiles require an external validator.

The validator uses **[The Saxon XSLT and XQuery Processor from Saxonica Limited](https://www.saxonica.com/)**
(SaxonCS-HE 13.0.0). It works offline after application assets load and caches
compiled stylesheets. `Code`, `Path`, and `RuleSeverity` preserve business-rule
details. Warnings and information do not invalidate an invoice. Because
`XmlSeverityType` has only Error and Warning, informational messages have
`Severity == Warning` and `RuleSeverity == "information"`. Processing failures
set `Error`; ordinary rule failures appear in `Validations`. Local results have
an empty `HttpStatusCode`.

Release-published, trimmed .NET 10 Blazor WASM was tested in Chromium, including
validation with networking disabled. This is not a guarantee for all browsers
or AOT builds. The measured cold validation took about **10.7 seconds**, and
cached validations about **100 ms**, for the small test fixture on this machine.
The validation executes on the calling thread, so cold compilation can block
the browser UI. The probe's framework assets total **13.4 MB Brotli-compressed**,
compared with **2.5 MB** for a minimal matching Blazor app. These are artifact
sizes, not measured BeInX download sizes. See [the reproducible browser probe](tools/Validator.WasmProbe/README.md).

For a consumer such as BeInX, invoke `ValidateSchematron(invoice)` even when the
configured server URL is empty. If an external validator is configured, pass
its URI explicitly:

```csharp
var result = await XmlInvoiceValidator.ValidateSchematron(
xmlInvoice,
string.IsNullOrWhiteSpace(config.SchematronValidationUri)
? null
: new Uri(config.SchematronValidationUri));
```

This library change does not modify BeInX's export flow. That flow currently
skips Schematron validation when no server URL is configured.

## ZUGFeRD XML validation (EN16931 / Comfort)

```csharp
var xml = GetGeneratedCiiXml();
var result = ZugferdXmlValidator.Validate(xml);
if (!result.IsValid)
{
var details = result.Error ?? string.Join(Environment.NewLine,
result.Validations.Select(m => $"{m.Code}: {m.Message} ({m.Path})"));
// Report the errors before passing this exact XML to PDF generation.
}
```

This API validates CII with guideline ID `urn:cen.eu:en16931:2017` against
**ZUGFeRD 2.3.3 / Factur-X 1.07.3 EN16931**. Other profiles and syntaxes are
rejected. Validation checks the profile XSD first, then its compiled Schematron
XSLT and code lists; it runs locally on .NET and Blazor WASM. Compiled resources
are cached and each call uses its own validation state. Warnings do not reject
invoices; processing failures set `Error`. No invoice data leaves the process.

All normative artifacts and the test fixture come directly from the official
FeRD `ZF233_EN_01.zip`. Official filenames, relative paths, import paths, and
bytes are preserved. The complete schema dependency closure and six embedded
resource hashes are verified. See [provenance and licenses](src/pax.XRechnung.NET/Resources/Zugferd/2.3.3/PROVENANCE.md)
and [offline browser measurements](tools/Validator.WasmProbe/README.md).

This API validates the XML only. It does not certify the PDF carrier, upgrade
an invoice writer, or apply XRechnung/Peppol CIUS rules to the Comfort profile.

## Java Schematron Validator
Requires a running [Kosit](https://github.com/itplr-kosit/validator) validation server. Setup: [xrechnung usage](https://github.com/itplr-kosit/validator-configuration-xrechnung/blob/master/docs/usage.md)
External validation remains available through an explicit URI, or directly
through `InvoiceKositValidator.Validate(xmlText)`, whose default is still
`http://localhost:8080`. It requires a running [KoSIT](https://github.com/itplr-kosit/validator)
validation server. Setup: [XRechnung usage](https://github.com/itplr-kosit/validator-configuration-xrechnung/blob/master/docs/usage.md).

```csharp
var result = await XmlInvoiceValidator.ValidateSchematron(
xmlInvoice, new Uri("http://localhost:9090"));
```

The supplied URI must expose KoSIT's raw XML/HTML response; a JSON API wrapper
requires its own client. Browser HTTP validation also requires the server to
permit the application's origin through CORS.

Server start:
`java -jar .\validationtool-1.5.0-standalone.jar -s .\scenarios.xml -r ${PWD} -D`

# ChangeLog

<details open="open"><summary>v0.3.3</summary>

>- Add local ZUGFeRD 2.3.3 / Factur-X 1.07.3 EN16931 (Comfort) XML validation using untouched official FeRD schemas, compiled XSLT, and code lists. Includes offline browser verification and pinned artifact hashes.

</details>

<details open="open"><summary>v0.3.2</summary>

>- Update to dotnet 10
Expand Down
42 changes: 42 additions & 0 deletions src/pax.XRechnung.NET.tests/HttpValidationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace pax.XRechnung.NET.tests;

[TestClass]
public sealed class HttpValidationTests
{
[TestMethod]
public async Task ExplicitUriUsesHttpAndPreservesDetailedFailure()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var endpoint = (IPEndPoint)listener.LocalEndpoint;
var responseTask = Respond(listener);
var result = await XmlInvoiceValidator.ValidateSchematron("<remote-only/>", new Uri($"http://127.0.0.1:{endpoint.Port}/"));
await responseTask;
Assert.IsFalse(result.IsValid);
Assert.AreEqual("OK", result.HttpStatusCode);
Assert.HasCount(1, result.Validations);
Assert.AreEqual("TEST-ERROR", result.Validations.Single().Code);
Assert.AreEqual("/Invoice", result.Validations.Single().Path);
Assert.IsNull(result.Error);
}

private static async Task Respond(TcpListener listener)
{
using var client = await listener.AcceptTcpClientAsync();
await using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
Assert.AreEqual("POST / HTTP/1.1", await reader.ReadLineAsync());
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) { }
const string html = "<body><table><tr><th>Step</th></tr><tr><td>Rules</td><td>1</td><td>0</td><td>0</td></tr></table>"
+ "<table><tr><th>Messages</th></tr><tr><td>1</td><td>TEST-ERROR</td><td>ERROR</td><td>Rejected by reference</td></tr>"
+ "<tr><td>Pfad: /Invoice</td></tr></table></body>";
var body = Encoding.UTF8.GetBytes(html);
var headers = Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
await stream.WriteAsync(headers);
await stream.WriteAsync(body);
}
}
160 changes: 160 additions & 0 deletions src/pax.XRechnung.NET.tests/LocalValidationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using System.Reflection;
using System.Xml.Linq;
using System.Xml.Schema;

namespace pax.XRechnung.NET.tests;

[TestClass]
public sealed class LocalValidationTests
{
private static readonly XNamespace Cbc = XmlInvoiceWriter.CommonBasicComponents;
private static readonly XNamespace Cac = XmlInvoiceWriter.CommonAggregateComponents;

private static XDocument Invoice()
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
"pax.XRechnung.NET.tests.Resources.standard.01.01a-INVOICE_ubl.xml")!;
return XDocument.Load(stream);
}

public static IEnumerable<object[]> InvoiceResources => Assembly.GetExecutingAssembly()
.GetManifestResourceNames().Where(n => n.Contains(".Resources.standard.", StringComparison.Ordinal) && n.EndsWith(".xml", StringComparison.Ordinal))
.Select(n => new object[] { n });

[TestMethod]
[DynamicData(nameof(InvoiceResources))]
public async Task ValidatesStandardFixtures(string name)
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)!;
using var reader = new StreamReader(stream);
var result = await XmlInvoiceValidator.ValidateSchematron(await reader.ReadToEndAsync());
Assert.IsTrue(result.IsValid, result.Error ?? string.Join("\n", result.Validations.Select(m => m.Message)));
}

[TestMethod]
public async Task ValidInvoiceDoesNotRequireHttp()
{
var result = await XmlInvoiceValidator.ValidateSchematron(Invoice().ToString());
Assert.IsTrue(result.IsValid, result.Error);
Assert.AreEqual(string.Empty, result.HttpStatusCode);
Assert.Contains("2026-08-31", result.Conformity!);
Assert.IsTrue(result.Validations.All(m => m.RuleSeverity == "information"));
}

[TestMethod]
public async Task ReportsBusinessRuleCodesAndPaths()
{
var xml = Invoice();
xml.Descendants(Cbc + "BuyerReference").Remove();
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.IsFalse(result.IsValid);
var message = result.Validations.Single(m => m.Code == "BR-DE-15");
Assert.AreEqual(XmlSeverityType.Error, message.Severity);
Assert.IsFalse(string.IsNullOrWhiteSpace(message.Path));
Assert.IsNull(result.Error);
}

[TestMethod]
public async Task ReportsIncorrectTotals()
{
var xml = Invoice();
xml.Descendants(Cac + "TaxTotal").First().Element(Cbc + "TaxAmount")!.Value = "18.00";
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.IsFalse(result.IsValid);
Assert.IsTrue(result.Validations.Any(m => m.Code == "BR-CO-15"));
}

[TestMethod]
public async Task InvalidCurrencyIsRejected()
{
var xml = Invoice();
xml.Descendants(Cbc + "DocumentCurrencyCode").Single().Value = "ZZZ";
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.IsFalse(result.IsValid);
Assert.IsTrue(result.Validations.Any(m => m.Code == "BR-CL-04"));
}

[TestMethod]
public async Task UnitCodeOverrideRemainsAWarning()
{
var xml = Invoice();
xml.Descendants(Cbc + "InvoicedQuantity").First().SetAttributeValue("unitCode", "ZZZ");
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
var finding = result.Validations.Single(m => m.Code == "BR-CL-23");
Assert.AreEqual("warning", finding.RuleSeverity);
Assert.AreEqual(XmlSeverityType.Warning, finding.Severity);
Assert.IsTrue(result.IsValid, string.Join("\n", result.Validations.Select(m => m.Message)));
}

[TestMethod]
public async Task ItemIdentifierOverrideRemainsAWarning()
{
var xml = Invoice();
xml.Descendants(Cac + "SellersItemIdentification").First().AddAfterSelf(new XElement(Cac + "StandardItemIdentification",
new XElement(Cbc + "ID", new XAttribute("schemeID", "ZZZ"), "example")));
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.AreEqual("warning", result.Validations.Single(m => m.Code == "BR-CL-21").RuleSeverity);
Assert.IsTrue(result.IsValid, result.Error);
}

[TestMethod]
public async Task SubInvoiceLineOverrideIsAnError()
{
var xml = Invoice();
var line = xml.Descendants(Cac + "InvoiceLine").First();
var subline = new XElement(line) { Name = Cac + "SubInvoiceLine" };
line.Add(subline);
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.AreEqual("error", result.Validations.Single(m => m.Code == "UBL-CR-646").RuleSeverity);
Assert.IsFalse(result.IsValid);
}

[TestMethod]
public async Task SchemaErrorsDoNotRunSchematron()
{
var xml = Invoice();
xml.Descendants(Cbc + "IssueDate").Single().Value = "not-a-date";
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.IsFalse(result.IsValid);
Assert.IsTrue(result.Validations.Any(m => m.Severity == XmlSeverityType.Error));
Assert.IsTrue(result.Validations.All(m => m.Code is null));
}

[TestMethod]
[DataRow("")]
[DataRow("<Invoice>")]
[DataRow("<!DOCTYPE Invoice [<!ENTITY test SYSTEM 'file:///does-not-exist'>]><Invoice>&test;</Invoice>")]
[DataRow("<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2'/>")]
public async Task InvalidInputsCannotPass(string xml)
{
var result = await XmlInvoiceValidator.ValidateSchematron(xml);
Assert.IsFalse(result.IsValid);
Assert.IsFalse(string.IsNullOrWhiteSpace(result.Error));
}

[TestMethod]
public async Task UnsupportedCustomizationCannotPass()
{
var xml = Invoice();
xml.Descendants(Cbc + "CustomizationID").Single().Value = "urn:cen.eu:en16931:2017";
var result = await XmlInvoiceValidator.ValidateSchematron(xml.ToString());
Assert.IsFalse(result.IsValid);
Assert.Contains("standard XRechnung", result.Error!);
}

[TestMethod]
public async Task ConcurrentValidationHasIndependentState()
{
var valid = Invoice().ToString();
var invalid = Invoice();
invalid.Descendants(Cbc + "BuyerReference").Remove();
var invalidText = invalid.ToString();
var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(i =>
Task.Run(() => XmlInvoiceValidator.ValidateSchematron(i % 2 == 0 ? valid : invalidText))));
for (var i = 0; i < results.Length; i++)
{
Assert.AreEqual(i % 2 == 0, results[i].IsValid, results[i].Error);
Assert.AreEqual(i % 2 != 0, results[i].Validations.Any(m => m.Code == "BR-DE-15"));
}
}
}
Loading
Loading