Add ZUGFeRD detection and extraction functionality
Introduced `ZugferdController` to handle ZUGFeRD-related operations, including detection and extraction of ZUGFeRD XML from PDFs via file upload or Base64-encoded payloads. Integrated `MediatR` for query/command handling. Added `ZugferdSettings` for configurable file names and patterns, and updated `appsettings.json` and `Program.cs` to support this configuration. Implemented `HasZugferdQuery` and `ExtractZugferdCommand` with their respective handlers and validators. Added DTOs (`ZugferdCheckResult`, `ZugferdExtractionResult`) for operation results. Included `ZUGFeRD-Example.pdf` for testing and integrated `Serilog.Ui.Core.Extensions` for logging.
This commit is contained in:
182
DocumentOperator.API/Controllers/ZugferdController.cs
Normal file
182
DocumentOperator.API/Controllers/ZugferdController.cs
Normal file
@@ -0,0 +1,182 @@
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Application.ExtractZugferd;
|
||||
using DocumentOperator.Application.HasZugferd.Queries;
|
||||
using DocumentOperator.Domain.Common.Exceptions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DocumentOperator.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for ZUGFeRD operations (detection, extraction)
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/pdf/zugferd")]
|
||||
[Produces("application/json")]
|
||||
public class ZugferdController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks if a PDF contains ZUGFeRD XML attachment.
|
||||
/// Supports multipart/form-data file upload.
|
||||
/// </summary>
|
||||
/// <param name="file">The PDF file to check for ZUGFeRD</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>ZUGFeRD check result with metadata</returns>
|
||||
/// <response code="200">PDF successfully checked - returns ZUGFeRD status</response>
|
||||
/// <response code="400">Invalid input (file missing, not a PDF, or corrupted)</response>
|
||||
/// <response code="500">Internal server error during PDF processing</response>
|
||||
[HttpPost("has-zugferd")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[ProducesResponseType(typeof(ZugferdCheckResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> HasZugferdFromFile(
|
||||
IFormFile file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Use IFormFile stream directly (no intermediate byte[] conversion)
|
||||
using var pdfStream = file.OpenReadStream();
|
||||
|
||||
// Send query to MediatR (ValidationBehavior runs automatically)
|
||||
var query = new HasZugferdQuery { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a PDF contains ZUGFeRD XML attachment.
|
||||
/// Supports Base64-encoded PDF via JSON payload.
|
||||
/// </summary>
|
||||
/// <param name="request">Request containing Base64-encoded PDF</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>ZUGFeRD check result with metadata</returns>
|
||||
/// <response code="200">PDF successfully checked - returns ZUGFeRD status</response>
|
||||
/// <response code="400">Invalid input (Base64 format error, not a PDF, or corrupted)</response>
|
||||
/// <response code="500">Internal server error during PDF processing</response>
|
||||
[HttpPost("has-zugferd")]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ZugferdCheckResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> HasZugferdFromBase64(
|
||||
[FromBody] HasZugferdRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Convert Base64 to stream (wrap in try-catch to throw BadRequestException)
|
||||
byte[] pdfBytes;
|
||||
try
|
||||
{
|
||||
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new BadRequestException("Invalid Base64 format: " + ex.Message);
|
||||
}
|
||||
|
||||
using var pdfStream = new MemoryStream(pdfBytes);
|
||||
|
||||
// Send query to MediatR (ValidationBehavior runs automatically)
|
||||
var query = new HasZugferdQuery { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts ZUGFeRD XML from a PDF document.
|
||||
/// Supports multipart/form-data file upload.
|
||||
/// </summary>
|
||||
/// <param name="file">The PDF file to extract ZUGFeRD from</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>ZUGFeRD XML content and metadata</returns>
|
||||
/// <response code="200">ZUGFeRD XML extracted successfully</response>
|
||||
/// <response code="400">Invalid input (file missing, not a PDF, or corrupted)</response>
|
||||
/// <response code="404">PDF contains no ZUGFeRD XML</response>
|
||||
/// <response code="500">Internal server error during PDF processing</response>
|
||||
[HttpPost("extract")]
|
||||
[Consumes("multipart/form-data")]
|
||||
[ProducesResponseType(typeof(ZugferdExtractionResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> ExtractZugferdFromFile(
|
||||
IFormFile file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Use IFormFile stream directly (no intermediate byte[] conversion)
|
||||
using var pdfStream = file.OpenReadStream();
|
||||
|
||||
// Send command to MediatR
|
||||
var command = new ExtractZugferdCommand { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts ZUGFeRD XML from a PDF document.
|
||||
/// Supports Base64-encoded PDF via JSON payload.
|
||||
/// </summary>
|
||||
/// <param name="request">Request containing Base64-encoded PDF</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>ZUGFeRD XML content and metadata</returns>
|
||||
/// <response code="200">ZUGFeRD XML extracted successfully</response>
|
||||
/// <response code="400">Invalid input (Base64 format error, not a PDF, or corrupted)</response>
|
||||
/// <response code="404">PDF contains no ZUGFeRD XML</response>
|
||||
/// <response code="500">Internal server error during PDF processing</response>
|
||||
[HttpPost("extract")]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ZugferdExtractionResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> ExtractZugferdFromBase64(
|
||||
[FromBody] ExtractZugferdRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Convert Base64 to stream (wrap in try-catch to throw BadRequestException)
|
||||
byte[] pdfBytes;
|
||||
try
|
||||
{
|
||||
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new BadRequestException("Invalid Base64 format: " + ex.Message);
|
||||
}
|
||||
|
||||
using var pdfStream = new MemoryStream(pdfBytes);
|
||||
|
||||
// Send command to MediatR
|
||||
var command = new ExtractZugferdCommand { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request DTO for Base64-encoded PDF ZUGFeRD check
|
||||
/// </summary>
|
||||
public record HasZugferdRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// PDF document encoded as Base64 string
|
||||
/// </summary>
|
||||
/// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
|
||||
public string Base64Pdf { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request DTO for Base64-encoded PDF ZUGFeRD extraction
|
||||
/// </summary>
|
||||
public record ExtractZugferdRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// PDF document encoded as Base64 string
|
||||
/// </summary>
|
||||
/// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
|
||||
public required string Base64Pdf { get; init; }
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Serilog.Ui.Web.Extensions;
|
||||
using Scalar.AspNetCore;
|
||||
using DocumentOperator.Infrastructure.Configuration;
|
||||
using DocumentOperator.Application;
|
||||
using DocumentOperator.Application.Common.Configuration;
|
||||
using DocumentOperator.Infrastructure;
|
||||
using DocumentOperator.API.Middleware;
|
||||
using DocumentOperator.API.Configuration;
|
||||
@@ -32,6 +33,9 @@ try
|
||||
builder.Services.Configure<DocumentOperatorSettings>(
|
||||
builder.Configuration.GetSection(DocumentOperatorSettings.SectionName));
|
||||
|
||||
builder.Services.Configure<ZugferdSettings>(
|
||||
builder.Configuration.GetSection("ZugferdSettings"));
|
||||
|
||||
builder.Services.Configure<RedisSettings>(
|
||||
builder.Configuration.GetSection(RedisSettings.SectionName));
|
||||
|
||||
|
||||
@@ -61,6 +61,22 @@
|
||||
"EnableDetailedLogging": true
|
||||
},
|
||||
|
||||
"ZugferdSettings": {
|
||||
"ZugferdFileNames": [
|
||||
"factur-x.xml",
|
||||
"zugferd-invoice.xml",
|
||||
"ZUGFeRD-invoice.xml",
|
||||
"xrechnung.xml",
|
||||
"XRechnung.xml"
|
||||
],
|
||||
"ZugferdFileNamePatterns": [
|
||||
"factur",
|
||||
"zugferd",
|
||||
"xrechnung",
|
||||
"peppol"
|
||||
]
|
||||
},
|
||||
|
||||
"RedisSettings": {
|
||||
"ConnectionString": "localhost:6379",
|
||||
"InstanceName": "DocumentOperator:",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace DocumentOperator.Application.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration settings for ZUGFeRD/Factur-X/XRechnung detection
|
||||
/// </summary>
|
||||
public class ZugferdSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Exact ZUGFeRD/Factur-X/XRechnung file names to check (case-insensitive)
|
||||
/// </summary>
|
||||
public List<string> ZugferdFileNames { get; set; } = new()
|
||||
{
|
||||
"factur-x.xml",
|
||||
"zugferd-invoice.xml",
|
||||
"ZUGFeRD-invoice.xml",
|
||||
"xrechnung.xml"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Partial filename patterns for ZUGFeRD detection (case-insensitive)
|
||||
/// </summary>
|
||||
public List<string> ZugferdFileNamePatterns { get; set; } = new()
|
||||
{
|
||||
"factur",
|
||||
"zugferd",
|
||||
"xrechnung",
|
||||
"peppol"
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace DocumentOperator.Application.Common.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// DTO for ZUGFeRD check result
|
||||
/// </summary>
|
||||
public record ZugferdCheckResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates whether the PDF contains ZUGFeRD XML attachment
|
||||
/// </summary>
|
||||
public bool HasZugferd { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// ZUGFeRD XML file name (e.g., "factur-x.xml")
|
||||
/// </summary>
|
||||
public string? ZugferdFileName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// ZUGFeRD XML file size in bytes
|
||||
/// </summary>
|
||||
public long? ZugferdFileSize { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// MIME type of the ZUGFeRD XML file
|
||||
/// </summary>
|
||||
public string? ZugferdMimeType { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using DocumentOperator.Application.Common.Configuration;
|
||||
using DocumentOperator.Application.Common.Interfaces;
|
||||
using DocumentOperator.Domain.Common.Exceptions;
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DocumentOperator.Application.ExtractZugferd;
|
||||
|
||||
/// <summary>
|
||||
/// Command to extract ZUGFeRD XML from a PDF document
|
||||
/// </summary>
|
||||
public record ExtractZugferdCommand : IRequest<ZugferdExtractionResult>
|
||||
{
|
||||
/// <summary>
|
||||
/// PDF document stream. Must be positioned at the beginning (Position = 0).
|
||||
/// </summary>
|
||||
public required Stream PdfStream { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handler for ExtractZugferdCommand.
|
||||
/// Extracts ZUGFeRD XML from PDF and returns XML content
|
||||
/// </summary>
|
||||
public class ExtractZugferdCommandHandler(
|
||||
IPdfProcessor pdfProcessor,
|
||||
IOptions<ZugferdSettings> settings)
|
||||
: IRequestHandler<ExtractZugferdCommand, ZugferdExtractionResult>
|
||||
{
|
||||
private readonly ZugferdSettings _settings = settings.Value;
|
||||
|
||||
public async Task<ZugferdExtractionResult> Handle(ExtractZugferdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get all attachments
|
||||
var attachmentInfo = await pdfProcessor.CheckAttachmentsAsync(request.PdfStream);
|
||||
|
||||
// Find ZUGFeRD XML file using configured names and patterns
|
||||
var zugferdAttachment = attachmentInfo.Attachments.FirstOrDefault(a =>
|
||||
_settings.ZugferdFileNames.Any(name =>
|
||||
a.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) ||
|
||||
_settings.ZugferdFileNamePatterns.Any(pattern =>
|
||||
a.FileName.Contains(pattern, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
if (zugferdAttachment == null)
|
||||
{
|
||||
throw new NotFoundException("ZUGFeRD XML not found in PDF attachments");
|
||||
}
|
||||
|
||||
// Reset stream position for extraction
|
||||
request.PdfStream.Position = 0;
|
||||
|
||||
// Extract all attachments as ZIP
|
||||
byte[] zipBytes = await pdfProcessor.ExtractAttachmentsAsync(request.PdfStream);
|
||||
|
||||
// Find ZUGFeRD XML in ZIP
|
||||
using var zipStream = new MemoryStream(zipBytes);
|
||||
using var zipArchive = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode.Read);
|
||||
|
||||
var zugferdEntry = zipArchive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals(zugferdAttachment.FileName, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (zugferdEntry == null)
|
||||
{
|
||||
throw new NotFoundException($"ZUGFeRD XML '{zugferdAttachment.FileName}' not found in extracted attachments");
|
||||
}
|
||||
|
||||
// Read XML content
|
||||
using var entryStream = zugferdEntry.Open();
|
||||
using var reader = new StreamReader(entryStream);
|
||||
string xmlContent = await reader.ReadToEndAsync(cancellationToken);
|
||||
|
||||
return new ZugferdExtractionResult
|
||||
{
|
||||
FileName = zugferdAttachment.FileName,
|
||||
XmlContent = xmlContent,
|
||||
FileSize = zugferdAttachment.SizeBytes
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validator for ExtractZugferdCommand.
|
||||
/// </summary>
|
||||
public class ExtractZugferdCommandValidator : AbstractValidator<ExtractZugferdCommand>
|
||||
{
|
||||
public ExtractZugferdCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.PdfStream)
|
||||
.NotNull()
|
||||
.WithMessage("PDF stream is required");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result DTO for ZUGFeRD extraction
|
||||
/// </summary>
|
||||
public record ZugferdExtractionResult
|
||||
{
|
||||
/// <summary>
|
||||
/// ZUGFeRD XML file name
|
||||
/// </summary>
|
||||
public required string FileName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// ZUGFeRD XML content as string
|
||||
/// </summary>
|
||||
public required string XmlContent { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// File size in bytes
|
||||
/// </summary>
|
||||
public long FileSize { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using DocumentOperator.Application.Common.Configuration;
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Application.Common.Interfaces;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DocumentOperator.Application.HasZugferd.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// Query for checking if PDF contains ZUGFeRD XML attachment
|
||||
/// </summary>
|
||||
public record HasZugferdQuery : IRequest<ZugferdCheckResult>
|
||||
{
|
||||
/// <summary>
|
||||
/// PDF as stream (caller is responsible for disposal)
|
||||
/// </summary>
|
||||
public required Stream PdfStream { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handler for HasZugferdQuery
|
||||
/// Checks if PDF contains ZUGFeRD/Factur-X XML attachment
|
||||
/// </summary>
|
||||
public class HasZugferdQueryHandler(
|
||||
IPdfProcessor pdfProcessor,
|
||||
IOptions<ZugferdSettings> settings)
|
||||
: IRequestHandler<HasZugferdQuery, ZugferdCheckResult>
|
||||
{
|
||||
private readonly ZugferdSettings _settings = settings.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Checks if PDF contains ZUGFeRD XML and returns metadata
|
||||
/// </summary>
|
||||
public async Task<ZugferdCheckResult> Handle(HasZugferdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get all attachments
|
||||
var attachmentInfo = await pdfProcessor.CheckAttachmentsAsync(request.PdfStream);
|
||||
|
||||
// Check for ZUGFeRD/Factur-X XML files using configured names and patterns
|
||||
var zugferdAttachment = attachmentInfo.Attachments.FirstOrDefault(a =>
|
||||
_settings.ZugferdFileNames.Any(name =>
|
||||
a.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) ||
|
||||
_settings.ZugferdFileNamePatterns.Any(pattern =>
|
||||
a.FileName.Contains(pattern, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
if (zugferdAttachment != null)
|
||||
{
|
||||
return new ZugferdCheckResult
|
||||
{
|
||||
HasZugferd = true,
|
||||
ZugferdFileName = zugferdAttachment.FileName,
|
||||
ZugferdFileSize = zugferdAttachment.SizeBytes,
|
||||
ZugferdMimeType = zugferdAttachment.MimeType
|
||||
};
|
||||
}
|
||||
|
||||
return new ZugferdCheckResult
|
||||
{
|
||||
HasZugferd = false
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace DocumentOperator.Application.HasZugferd.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// Validator for HasZugferdQuery
|
||||
/// </summary>
|
||||
public class HasZugferdQueryValidator : AbstractValidator<HasZugferdQuery>
|
||||
{
|
||||
public HasZugferdQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.PdfStream)
|
||||
.NotNull()
|
||||
.WithMessage("PDF stream is required");
|
||||
}
|
||||
}
|
||||
BIN
DocumentOperator.Tests/TestData/Pdfs/ZUGFeRD-Example.pdf
Normal file
BIN
DocumentOperator.Tests/TestData/Pdfs/ZUGFeRD-Example.pdf
Normal file
Binary file not shown.
Reference in New Issue
Block a user