Refactor: Rename DocumentOperator to DocumentService

Updated project and solution files to rename and restructure
`DocumentOperator` to `DocumentService`. Modified project
references in `DocumentService.API.csproj`, `DocumentService.Application.csproj`,
and `DocumentService.Infrastructure.csproj` to reflect the new
naming convention. Updated `DocumentService.sln` to remove
old project references, add new ones, and adjust configuration
and nested project mappings accordingly. This change aligns
the project structure with the new naming convention.
This commit is contained in:
2026-08-30 21:33:25 +02:00
parent 050cb55bf9
commit 207c778f3a
108 changed files with 37 additions and 37 deletions

View File

@@ -0,0 +1,125 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace DocumentService.API.Configuration
{
/// <summary>
/// Swagger document filter that merges operations with same path but different [Consumes] attributes.
/// Ensures both multipart/form-data and application/json variants are visible in Swagger UI.
/// </summary>
public class DualInputDocumentFilter : IDocumentFilter
{
private readonly IApiDescriptionGroupCollectionProvider _apiDescriptionProvider;
/// <summary>
/// Initializes a new instance of the <see cref="DualInputDocumentFilter"/> class.
/// </summary>
/// <param name="apiDescriptionProvider">API description provider to access all endpoints</param>
public DualInputDocumentFilter(IApiDescriptionGroupCollectionProvider apiDescriptionProvider)
{
_apiDescriptionProvider = apiDescriptionProvider;
}
/// <summary>
/// Applies the filter to merge operations with different content types.
/// </summary>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var allApiDescriptions = _apiDescriptionProvider.ApiDescriptionGroups.Items
.SelectMany(g => g.Items)
.ToList();
// Group by path
var groupedByPath = allApiDescriptions
.GroupBy(x => "/" + x.RelativePath)
.ToList();
foreach (var group in groupedByPath)
{
var path = group.Key;
if (!swaggerDoc.Paths.ContainsKey(path))
continue;
var pathItem = swaggerDoc.Paths[path];
// Find multipart and JSON variants
var multipartDesc = group.FirstOrDefault(x =>
x.SupportedRequestFormats.Any(f => f.MediaType == "multipart/form-data"));
var jsonDesc = group.FirstOrDefault(x =>
x.SupportedRequestFormats.Any(f => f.MediaType == "application/json"));
// If we have both variants, merge them into single operation
if (multipartDesc != null && jsonDesc != null)
{
var httpMethod = multipartDesc.HttpMethod?.ToLowerInvariant();
OperationType operationType;
if (!Enum.TryParse<OperationType>(httpMethod, true, out operationType))
continue;
if (!pathItem.Operations.ContainsKey(operationType))
continue;
var operation = pathItem.Operations[operationType];
// Ensure RequestBody exists
if (operation.RequestBody == null)
{
operation.RequestBody = new OpenApiRequestBody
{
Required = true,
Content = new Dictionary<string, OpenApiMediaType>()
};
}
// Add multipart/form-data if missing
if (!operation.RequestBody.Content.ContainsKey("multipart/form-data"))
{
operation.RequestBody.Content.Add("multipart/form-data", new OpenApiMediaType
{
Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["file"] = new OpenApiSchema
{
Type = "string",
Format = "binary",
Description = "PDF file to upload"
}
},
Required = new HashSet<string> { "file" }
}
});
}
// Add application/json if missing
if (!operation.RequestBody.Content.ContainsKey("application/json"))
{
operation.RequestBody.Content.Add("application/json", new OpenApiMediaType
{
Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["base64Pdf"] = new OpenApiSchema
{
Type = "string",
Format = "byte",
Description = "Base64-encoded PDF file content"
}
},
Required = new HashSet<string> { "base64Pdf" }
}
});
}
}
}
}
}
}

View File

@@ -0,0 +1,9 @@
namespace DocumentService.API.Configuration
{
/// <summary>
/// Placeholder class for Serilog configuration extensions.
/// </summary>
public class SerilogConfiguration
{
}
}

View File

@@ -0,0 +1,50 @@
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using System.Reflection;
namespace DocumentService.API.Configuration
{
/// <summary>
/// Provides extension methods for configuring Swagger/OpenAPI documentation.
/// </summary>
public static class SwaggerConfiguration
{
/// <summary>
/// Adds Swagger documentation generation to the service collection.
/// </summary>
/// <param name="services">The service collection to add Swagger to.</param>
/// <param name="configuration">Configuration to read SwaggerSettings from.</param>
/// <returns>The modified service collection.</returns>
public static IServiceCollection AddSwaggerDocumentation(
this IServiceCollection services,
IConfiguration configuration)
{
var swaggerSettings = configuration.GetSection(SwaggerSettings.SectionName).Get<SwaggerSettings>()
?? new SwaggerSettings();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc(swaggerSettings.Version, new OpenApiInfo
{
Title = swaggerSettings.Title,
Version = swaggerSettings.Version,
Description = swaggerSettings.Description
});
// Resolve conflicting actions: Keep first variant
// DualInputDocumentFilter will merge both variants into single operation
options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
// Add document filter to merge operations with different content types
options.DocumentFilter<DualInputDocumentFilter>();
// XML-Kommentare einbinden
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});
return services;
}
}
}

View File

@@ -0,0 +1,33 @@
namespace DocumentService.API.Configuration;
/// <summary>
/// Configuration settings for Swagger/OpenAPI documentation.
/// </summary>
public class SwaggerSettings
{
/// <summary>
///
/// </summary>
public const string SectionName = "SwaggerSettings";
/// <summary>
/// Enable Swagger UI in Production environment.
/// Default: true (allows production testing/debugging).
/// </summary>
public bool EnableInProduction { get; set; } = true;
/// <summary>
/// API title displayed in Swagger UI.
/// </summary>
public string Title { get; set; } = "DocumentService API";
/// <summary>
/// API version.
/// </summary>
public string Version { get; set; } = "v1";
/// <summary>
/// API description displayed in Swagger UI.
/// </summary>
public string Description { get; set; } = "PDF document processing service";
}

View File

@@ -0,0 +1,356 @@
using DocumentService.Application.AddAttachments;
using DocumentService.Application.CheckPdfAttachments.Queries;
using DocumentService.Application.Common.DTOs;
using DocumentService.Application.ExtractPdfAttachments;
using DocumentService.Client.Models.Requests;
using DocumentService.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.API.Controllers;
/// <summary>
/// Controller for PDF attachment operations (detection, extraction, embedding)
/// </summary>
[ApiController]
[Route("api/pdf/attachments")]
[Produces("application/json")]
public class PdfAttachmentController(IMediator mediator) : ControllerBase
{
/// <summary>
/// Checks if a PDF contains embedded files (attachments) and returns their metadata.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="file">The PDF file to check for attachments</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Attachment check result with metadata for all found attachments</returns>
/// <response code="200">PDF successfully checked - returns attachment details</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("check")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CheckAttachmentsFromFile(
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 CheckPdfAttachmentsQuery { PdfStream = pdfStream };
var result = await mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Checks if a PDF contains embedded files (attachments) and returns their metadata.
/// Supports Base64-encoded PDF via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Attachment check result with metadata for all found attachments</returns>
/// <response code="200">PDF successfully checked - returns attachment details</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("check")]
[Consumes("application/json")]
[ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> CheckAttachmentsFromBase64(
[FromBody] CheckPdfAttachmentsRequest 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 CheckPdfAttachmentsQuery { PdfStream = pdfStream };
var result = await mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Extracts all embedded files from a PDF and returns them as a ZIP archive.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="file">The PDF file to extract attachments from</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>ZIP archive containing all extracted attachments</returns>
/// <response code="200">Attachments extracted successfully - returns ZIP file</response>
/// <response code="400">Invalid input (file missing, not a PDF, or corrupted)</response>
/// <response code="404">PDF contains no attachments</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("extract")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractAttachmentsFromFile(
IFormFile file,
CancellationToken cancellationToken)
{
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Send command to MediatR
var command = new ExtractPdfAttachmentsCommand { PdfStream = pdfStream };
byte[] zipBytes = await mediator.Send(command, cancellationToken);
// Return ZIP file
return File(zipBytes, "application/zip", "attachments.zip");
}
/// <summary>
/// Extracts all embedded files from a PDF and returns them as a ZIP archive.
/// Supports Base64-encoded PDF via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>ZIP archive containing all extracted attachments</returns>
/// <response code="200">Attachments extracted successfully - returns ZIP file</response>
/// <response code="400">Invalid input (Base64 format error, not a PDF, or corrupted)</response>
/// <response code="404">PDF contains no attachments</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("extract")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractAttachmentsFromBase64(
[FromBody] ExtractPdfAttachmentsRequest 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 ExtractPdfAttachmentsCommand { PdfStream = pdfStream };
byte[] zipBytes = await mediator.Send(command, cancellationToken);
// Return ZIP file
return File(zipBytes, "application/zip", "attachments.zip");
}
/// <summary>
/// Embeds one or more files as attachments in a PDF document (supports PDF/A-3).
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="pdfFile">The PDF file to add attachments to</param>
/// <param name="attachmentFiles">Files to embed as attachments (one or more)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF with embedded attachments</returns>
/// <response code="200">Attachments added successfully - returns PDF</response>
/// <response code="400">Invalid input (file missing, not a PDF, or no attachments provided)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("add")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AddAttachmentsFromFile(
IFormFile pdfFile,
List<IFormFile> attachmentFiles,
CancellationToken cancellationToken)
{
if (pdfFile == null || pdfFile.Length == 0)
{
throw new BadRequestException("PDF file is required");
}
if (attachmentFiles == null || attachmentFiles.Count == 0)
{
throw new BadRequestException("At least one attachment file is required");
}
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = pdfFile.OpenReadStream();
// Convert attachment files to AttachmentFile records
var attachments = new List<AttachmentFile>();
foreach (var file in attachmentFiles)
{
using var ms = new MemoryStream();
await file.CopyToAsync(ms, cancellationToken);
attachments.Add(new AttachmentFile
{
FileName = file.FileName,
Content = ms.ToArray(),
MimeType = file.ContentType
});
}
// Send command to MediatR
var command = new AddAttachmentsCommand
{
PdfStream = pdfStream,
Attachments = attachments
};
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return PDF with attachments
return File(resultPdf, "application/pdf", "with-attachments.pdf");
}
/// <summary>
/// Embeds one or more files as attachments in a PDF document (supports PDF/A-3).
/// Supports Base64-encoded PDF and attachments via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF and attachments</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF with embedded attachments</returns>
/// <response code="200">Attachments added successfully - returns PDF</response>
/// <response code="400">Invalid input (Base64 format error, not a PDF, or no attachments provided)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("add")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AddAttachmentsFromBase64(
[FromBody] AddAttachmentsRequest request,
CancellationToken cancellationToken)
{
// Convert Base64 PDF to stream
byte[] pdfBytes;
try
{
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
}
catch (FormatException ex)
{
throw new BadRequestException("Invalid Base64 PDF format: " + ex.Message);
}
using var pdfStream = new MemoryStream(pdfBytes);
// Convert Base64 attachments to AttachmentFile records
var attachments = new List<AttachmentFile>();
foreach (var att in request.Attachments)
{
byte[] attBytes;
try
{
attBytes = Convert.FromBase64String(att.Base64Content);
}
catch (FormatException ex)
{
throw new BadRequestException($"Invalid Base64 format for attachment '{att.FileName}': " + ex.Message);
}
attachments.Add(new AttachmentFile
{
FileName = att.FileName,
Content = attBytes,
MimeType = att.MimeType
});
}
// Send command to MediatR
var command = new AddAttachmentsCommand
{
PdfStream = pdfStream,
Attachments = attachments
};
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return PDF with attachments
return File(resultPdf, "application/pdf", "with-attachments.pdf");
}
}
/// <summary>
/// Request DTO for Base64-encoded PDF attachment check
/// </summary>
public record CheckPdfAttachmentsRequest
{
/// <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 attachment extraction
/// </summary>
public record ExtractPdfAttachmentsRequest
{
/// <summary>
/// PDF document encoded as Base64 string
/// </summary>
/// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
public required string Base64Pdf { get; init; }
}
/// <summary>
/// Request DTO for Base64-encoded PDF with attachments to add
/// </summary>
public record AddAttachmentsRequest
{
/// <summary>
/// PDF document encoded as Base64 string
/// </summary>
/// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
public required string Base64Pdf { get; init; }
/// <summary>
/// List of attachments to embed
/// </summary>
public required List<AttachmentRequestDto> Attachments { get; init; }
}
/// <summary>
/// DTO for attachment file in request
/// </summary>
public record AttachmentRequestDto
{
/// <summary>
/// File name (e.g., "invoice.xml", "document.pdf")
/// </summary>
/// <example>factur-x.xml</example>
public required string FileName { get; init; }
/// <summary>
/// File content encoded as Base64 string
/// </summary>
/// <example>PD94bWwgdmVyc2lvbj0iMS4wIj8+...</example>
public required string Base64Content { get; init; }
/// <summary>
/// MIME type (optional, e.g., "application/xml")
/// </summary>
/// <example>application/xml</example>
public string? MimeType { get; init; }
}

View File

@@ -0,0 +1,182 @@
using DocumentService.Application.ConvertFromPdfA;
using DocumentService.Application.ConvertToPdfA;
using DocumentService.Client.Models.Requests;
using DocumentService.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.API.Controllers;
/// <summary>
/// Controller for PDF conversion operations (PDF ? PDF/A)
/// </summary>
[ApiController]
[Route("api/pdf/conversion")]
[Obsolete("This endpoint is not implemented yet.")]
public class PdfConversionController(IMediator mediator) : ControllerBase
{
/// <summary>
/// Converts a standard PDF to PDF/A format.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="file">The PDF file to convert</param>
/// <param name="pdfALevel">Target PDF/A level (e.g., "PDF/A-1b", "PDF/A-2b", "PDF/A-3b")</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF/A compliant document</returns>
/// <response code="200">PDF converted to PDF/A successfully</response>
/// <response code="400">Invalid input (file missing, not a PDF, or invalid PDF/A level)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("to-pdfa")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ConvertToPdfAFromFile(
IFormFile file,
[FromQuery] string pdfALevel = "PDF/A-3b",
CancellationToken cancellationToken = default)
{
if (file == null || file.Length == 0)
{
throw new BadRequestException("PDF file is required");
}
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Send command to MediatR
var command = new ConvertToPdfACommand
{
PdfStream = pdfStream,
PdfALevel = pdfALevel
};
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return PDF/A file
return File(resultPdf, "application/pdf", "converted-pdfa.pdf");
}
/// <summary>
/// Converts a standard PDF to PDF/A format.
/// Supports Base64-encoded PDF via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF and PDF/A level</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF/A compliant document</returns>
/// <response code="200">PDF converted to PDF/A successfully</response>
/// <response code="400">Invalid input (Base64 format error, not a PDF, or invalid PDF/A level)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("to-pdfa")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ConvertToPdfAFromBase64(
[FromBody] ConvertToPdfARequest request,
CancellationToken cancellationToken = default)
{
// Convert Base64 PDF to stream
byte[] pdfBytes;
try
{
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
}
catch (FormatException ex)
{
throw new BadRequestException("Invalid Base64 PDF format: " + ex.Message);
}
using var pdfStream = new MemoryStream(pdfBytes);
// Send command to MediatR
var command = new ConvertToPdfACommand
{
PdfStream = pdfStream,
PdfALevel = request.PdfALevel ?? "PDF/A-3b"
};
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return PDF/A file
return File(resultPdf, "application/pdf", "converted-pdfa.pdf");
}
/// <summary>
/// Converts a PDF/A document to a standard PDF (removes PDF/A restrictions).
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="file">The PDF/A file to convert</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Standard PDF document</returns>
/// <response code="200">PDF/A converted to standard PDF successfully</response>
/// <response code="400">Invalid input (file missing, not a PDF)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("from-pdfa")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ConvertFromPdfAFromFile(
IFormFile file,
CancellationToken cancellationToken = default)
{
if (file == null || file.Length == 0)
{
throw new BadRequestException("PDF/A file is required");
}
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Send command to MediatR
var command = new ConvertFromPdfACommand { PdfStream = pdfStream };
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return standard PDF file
return File(resultPdf, "application/pdf", "converted-pdf.pdf");
}
/// <summary>
/// Converts a PDF/A document to a standard PDF (removes PDF/A restrictions).
/// Supports Base64-encoded PDF via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF/A</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Standard PDF document</returns>
/// <response code="200">PDF/A converted to standard PDF successfully</response>
/// <response code="400">Invalid input (Base64 format error, not a PDF)</response>
/// <response code="500">Internal server error during PDF processing</response>
[Obsolete("This endpoint is not implemented yet.")]
[HttpPost("from-pdfa")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ConvertFromPdfAFromBase64(
[FromBody] ConvertFromPdfARequest request,
CancellationToken cancellationToken = default)
{
// Convert Base64 PDF to stream
byte[] pdfBytes;
try
{
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
}
catch (FormatException ex)
{
throw new BadRequestException("Invalid Base64 PDF format: " + ex.Message);
}
using var pdfStream = new MemoryStream(pdfBytes);
// Send command to MediatR
var command = new ConvertFromPdfACommand { PdfStream = pdfStream };
byte[] resultPdf = await mediator.Send(command, cancellationToken);
// Return standard PDF file
return File(resultPdf, "application/pdf", "converted-pdf.pdf");
}
}

View File

@@ -0,0 +1,728 @@
using DocumentService.Application.AddAnnotation;
using DocumentService.Application.AddStamp;
using DocumentService.Application.MergePdfs;
using DocumentService.Domain.Common.Exceptions;
using DocumentService.Domain.Models.ValueObjects;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.API.Controllers;
/// <summary>
/// Controller for PDF operations (merge, stamp, annotate).
/// </summary>
[ApiController]
[Route("api/pdf/operations")]
public class PdfOperationsController(IMediator mediator) : ControllerBase
{
/// <summary>
/// Merges multiple PDF files into a single PDF.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="files">PDF files to merge (minimum 2 required)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Merged PDF file</returns>
/// <response code="200">PDFs merged successfully - returns merged PDF</response>
/// <response code="400">Invalid input (fewer than 2 files, corrupted PDF)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("merge", Name = "MergeFromFiles")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> MergeFromFiles(
[FromForm] List<IFormFile> files,
CancellationToken cancellationToken)
{
// Convert IFormFile[] to Stream[] (use OpenReadStream directly - no buffering)
var streams = files.Select(f => f.OpenReadStream()).ToList();
// Send command to MediatR (no page ranges for now - multipart binding is complex)
var command = new MergePdfsCommand
{
PdfStreams = streams,
PageRanges = null
};
byte[] mergedPdf = await mediator.Send(command, cancellationToken);
// Return merged PDF
return File(mergedPdf, "application/pdf", "merged.pdf");
}
/// <summary>
/// Merges multiple PDF files into a single PDF.
/// Supports Base64-encoded PDFs via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDFs and optional page ranges</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Merged PDF file</returns>
/// <response code="200">PDFs merged successfully - returns merged PDF</response>
/// <response code="400">Invalid input (Base64 format error, fewer than 2 files, corrupted PDF, invalid page range)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("merge", Name = "MergeFromBase64")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> MergeFromBase64(
[FromBody] MergePdfsBase64Request request,
CancellationToken cancellationToken)
{
// Convert Base64[] to MemoryStream[]
List<Stream> streams = [];
try
{
foreach (var base64Pdf in request.Base64Pdfs)
{
byte[] pdfBytes = Convert.FromBase64String(base64Pdf);
streams.Add(new MemoryStream(pdfBytes));
}
}
catch (FormatException ex)
{
// Dispose opened streams on error
foreach (var stream in streams) stream.Dispose();
throw new BadRequestException("Invalid Base64 format: " + ex.Message);
}
var command = new MergePdfsCommand
{
PdfStreams = streams,
PageRanges = request.PageRanges
};
byte[] mergedPdf = await mediator.Send(command, cancellationToken);
// Cleanup streams (important for MemoryStreams we created)
foreach (var stream in streams) stream.Dispose();
return File(mergedPdf, "application/pdf", "merged.pdf");
}
/// <summary>
/// Adds an annotation to a PDF document.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="request">Multipart form data containing PDF file and annotation parameters</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Annotated PDF file</returns>
/// <response code="200">Annotation added successfully - returns annotated PDF</response>
/// <response code="400">Invalid input (invalid page number, missing required parameters)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("annotate", Name = "AnnotateFromFile")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AnnotateFromFile(
[FromForm] AddAnnotationMultipartRequest request,
CancellationToken cancellationToken)
{
// Calculate X2, Y2 from Width/Height if provided
double x2 = request.X2 ?? request.X1 + (request.Width ?? throw new BadRequestException("Either X2 or Width must be provided"));
double y2 = request.Y2 ?? request.Y1 + (request.Height ?? throw new BadRequestException("Either Y2 or Height must be provided"));
var command = new AddAnnotationCommand
{
PdfStream = request.File.OpenReadStream(),
AnnotationType = request.AnnotationType,
PageNumber = request.PageNumber,
Rectangle = (request.X1, request.Y1, x2, y2),
Content = request.Content,
Author = request.Author,
Color = request.Color,
TextMarkupStyle = request.TextMarkupStyle,
Origin = request.Origin
};
byte[] annotatedPdf = await mediator.Send(command, cancellationToken);
return File(annotatedPdf, "application/pdf", "annotated.pdf");
}
/// <summary>
/// Adds an annotation to a PDF document.
/// Supports Base64-encoded PDF via JSON payload.
/// </summary>
/// <param name="command">Command containing all annotation parameters (including Base64 PDF)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Annotated PDF file</returns>
/// <response code="200">Annotation added successfully - returns annotated PDF</response>
/// <response code="400">Invalid input (Base64 format error, invalid page number, missing required parameters)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("annotate", Name = "AnnotateFromBase64")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AnnotateFromBase64(
[FromBody] AddAnnotationBase64Command command,
CancellationToken cancellationToken)
{
// Convert Base64 to MemoryStream
Stream pdfStream;
try
{
byte[] pdfBytes = Convert.FromBase64String(command.Base64Pdf);
pdfStream = new MemoryStream(pdfBytes);
}
catch (FormatException ex)
{
throw new BadRequestException("Invalid Base64 format: " + ex.Message);
}
// Calculate X2, Y2 from Width/Height if provided
double x2 = command.X2 ?? command.X1 + (command.Width ?? throw new BadRequestException("Either X2 or Width must be provided"));
double y2 = command.Y2 ?? command.Y1 + (command.Height ?? throw new BadRequestException("Either Y2 or Height must be provided"));
var annotationCommand = new AddAnnotationCommand
{
PdfStream = pdfStream,
AnnotationType = command.AnnotationType,
PageNumber = command.PageNumber,
Rectangle = (command.X1, command.Y1, x2, y2),
Content = command.Content,
Author = command.Author,
Color = command.Color,
TextMarkupStyle = command.TextMarkupStyle,
Origin = command.Origin
};
byte[] annotatedPdf = await mediator.Send(annotationCommand, cancellationToken);
// Cleanup stream
pdfStream.Dispose();
return File(annotatedPdf, "application/pdf", "annotated.pdf");
}
/// <summary>
/// Adds a stamp (text, image, or predefined) to PDF pages.
/// Supports multipart/form-data file upload.
/// </summary>
/// <param name="request">Multipart form data containing PDF file and stamp parameters</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Stamped PDF file</returns>
/// <response code="200">Stamp added successfully - returns stamped PDF</response>
/// <response code="400">Invalid input (invalid page number, missing required parameters, invalid image format)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("stamp", Name = "AddStampFromFile")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AddStampFromFile(
[FromForm] AddStampMultipartRequest request,
CancellationToken cancellationToken)
{
// Convert ImageFile to byte[] if provided
byte[]? imageBytes = null;
if (request.ImageFile != null)
{
using var ms = new MemoryStream();
await request.ImageFile.CopyToAsync(ms, cancellationToken);
imageBytes = ms.ToArray();
}
var command = new AddStampCommand
{
PdfStream = request.File.OpenReadStream(),
StampType = request.StampType,
PageNumbers = request.PageNumbers,
Position = (request.X, request.Y),
Size = request.Width.HasValue && request.Height.HasValue
? (request.Width.Value, request.Height.Value)
: null,
Origin = request.Origin,
Text = request.Text,
FontName = request.FontName,
FontSize = request.FontSize,
Color = request.Color,
Opacity = request.Opacity,
Rotation = request.Rotation,
Placement = request.Placement,
ImageBytes = imageBytes,
PredefinedType = request.PredefinedType
};
byte[] stampedPdf = await mediator.Send(command, cancellationToken);
return File(stampedPdf, "application/pdf", "stamped.pdf");
}
/// <summary>
/// Adds a stamp (text, image, or predefined) to PDF pages.
/// Supports Base64-encoded PDF and image via JSON payload.
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF, stamp parameters, and optional Base64 image</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Stamped PDF file</returns>
/// <response code="200">Stamp added successfully - returns stamped PDF</response>
/// <response code="400">Invalid input (Base64 format error, invalid page number, missing required parameters)</response>
/// <response code="500">Internal server error during PDF processing</response>
[HttpPost("stamp", Name = "AddStampFromBase64")]
[Consumes("application/json")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> AddStampFromBase64(
[FromBody] AddStampBase64Request request,
CancellationToken cancellationToken)
{
// Convert Base64 PDF to MemoryStream
Stream pdfStream;
try
{
byte[] pdfBytes = Convert.FromBase64String(request.Base64Pdf);
pdfStream = new MemoryStream(pdfBytes);
}
catch (FormatException ex)
{
throw new BadRequestException("Invalid Base64 PDF format: " + ex.Message);
}
// Convert Base64 image to byte[] if provided
byte[]? imageBytes = null;
if (!string.IsNullOrWhiteSpace(request.Base64Image))
{
try
{
imageBytes = Convert.FromBase64String(request.Base64Image);
}
catch (FormatException ex)
{
pdfStream.Dispose();
throw new BadRequestException("Invalid Base64 image format: " + ex.Message);
}
}
var command = new AddStampCommand
{
PdfStream = pdfStream,
StampType = request.StampType,
PageNumbers = request.PageNumbers,
Position = (request.X, request.Y),
Size = request.Width.HasValue && request.Height.HasValue
? (request.Width.Value, request.Height.Value)
: null,
Origin = request.Origin,
Text = request.Text,
FontName = request.FontName,
FontSize = request.FontSize,
Color = request.Color,
Opacity = request.Opacity,
Rotation = request.Rotation,
Placement = request.Placement,
ImageBytes = imageBytes,
PredefinedType = request.PredefinedType
};
byte[] stampedPdf = await mediator.Send(command, cancellationToken);
// Cleanup stream
pdfStream.Dispose();
return File(stampedPdf, "application/pdf", "stamped.pdf");
}
}
/// <summary>
/// Request DTO for multipart/form-data annotation operation
/// </summary>
public class AddAnnotationMultipartRequest
{
/// <summary>
/// PDF file to annotate
/// </summary>
public required IFormFile File { get; set; }
/// <summary>
/// Type of annotation (TextMarkup, FreeText, StickyNote, Circle, Square)
/// </summary>
public required AnnotationType AnnotationType { get; set; }
/// <summary>
/// Target page number (1-indexed)
/// </summary>
public required int PageNumber { get; set; }
/// <summary>
/// Rectangle X1 coordinate (left)
/// </summary>
public required double X1 { get; set; }
/// <summary>
/// Rectangle Y1 coordinate (top or bottom depending on Origin)
/// </summary>
public required double Y1 { get; set; }
/// <summary>
/// Rectangle X2 coordinate (right). Optional if Width is provided.
/// </summary>
public double? X2 { get; set; }
/// <summary>
/// Rectangle Y2 coordinate (bottom or top depending on Origin). Optional if Height is provided.
/// </summary>
public double? Y2 { get; set; }
/// <summary>
/// Rectangle width. Alternative to X2 (X2 = X1 + Width). Optional if X2 is provided.
/// </summary>
public double? Width { get; set; }
/// <summary>
/// Rectangle height. Alternative to Y2 (Y2 = Y1 + Height). Optional if Y2 is provided.
/// </summary>
public double? Height { get; set; }
/// <summary>
/// Annotation content (required for FreeText/StickyNote)
/// </summary>
public string? Content { get; set; }
/// <summary>
/// Author name (optional)
/// </summary>
public string? Author { get; set; }
/// <summary>
/// Hex color (6 digits, e.g., "FF0000" for red)
/// </summary>
public string? Color { get; set; }
/// <summary>
/// Markup style (Highlight/Underline/Strikeout, required for TextMarkup)
/// </summary>
public TextMarkupStyle? TextMarkupStyle { get; set; }
/// <summary>
/// Coordinate origin (BottomLeft = PDF native, TopLeft = UI-friendly). Default: BottomLeft
/// </summary>
public AnnotationOrigin Origin { get; set; } = AnnotationOrigin.BottomLeft;
}
/// <summary>
/// Request DTO for Base64-encoded PDF merge operation (API layer only - converts to MergePdfsCommand)
/// </summary>
public record MergePdfsBase64Request
{
/// <summary>
/// Array of Base64-encoded PDF files (minimum 2 required)
/// </summary>
/// <example>["JVBERi0xLjQK...", "JVBERi0xLjQK..."]</example>
public required List<string> Base64Pdfs { get; init; }
/// <summary>
/// Optional page ranges per PDF (null = all pages).
/// Format: "1-3,5" means pages 1, 2, 3, and 5.
/// If provided, array length must match Base64Pdfs length.
/// </summary>
/// <example>["1-2", "1,3,5", null]</example>
public List<string?>? PageRanges { get; init; }
}
/// <summary>
/// Request DTO for Base64-encoded PDF annotation (API layer only - converts to AddAnnotationCommand)
/// </summary>
public record AddAnnotationBase64Command
{
/// <summary>
/// Base64-encoded PDF file
/// </summary>
/// <example>"JVBERi0xLjQK..."</example>
public required string Base64Pdf { get; init; }
/// <summary>
/// Type of annotation to add
/// </summary>
/// <example>TextMarkup</example>
public required AnnotationType AnnotationType { get; init; }
/// <summary>
/// Target page number (1-indexed)
/// </summary>
/// <example>1</example>
public required int PageNumber { get; init; }
/// <summary>
/// Rectangle X1 coordinate (left)
/// </summary>
/// <example>100.0</example>
public required double X1 { get; init; }
/// <summary>
/// Rectangle Y1 coordinate (top or bottom depending on Origin)
/// </summary>
/// <example>100.0</example>
public required double Y1 { get; init; }
/// <summary>
/// Rectangle X2 coordinate (right). Optional if Width is provided.
/// </summary>
/// <example>200.0</example>
public double? X2 { get; init; }
/// <summary>
/// Rectangle Y2 coordinate (bottom or top depending on Origin). Optional if Height is provided.
/// </summary>
/// <example>120.0</example>
public double? Y2 { get; init; }
/// <summary>
/// Rectangle width. Alternative to X2 (X2 = X1 + Width). Optional if X2 is provided.
/// </summary>
/// <example>100.0</example>
public double? Width { get; init; }
/// <summary>
/// Rectangle height. Alternative to Y2 (Y2 = Y1 + Height). Optional if Y2 is provided.
/// </summary>
/// <example>20.0</example>
public double? Height { get; init; }
/// <summary>
/// Annotation content (required for FreeText and StickyNote)
/// </summary>
/// <example>"Important text to highlight"</example>
public string? Content { get; init; }
/// <summary>
/// Author name (optional)
/// </summary>
/// <example>"John Doe"</example>
public string? Author { get; init; }
/// <summary>
/// Hex color (6 digits, e.g., "FF0000" for red). Optional - defaults vary by annotation type.
/// </summary>
/// <example>"FFFF00"</example>
public string? Color { get; init; }
/// <summary>
/// Text markup style (Highlight, Underline, or Strikeout). Required for TextMarkup annotations.
/// </summary>
/// <example>Highlight</example>
public TextMarkupStyle? TextMarkupStyle { get; init; }
/// <summary>
/// Coordinate origin (BottomLeft = PDF native, TopLeft = UI-friendly). Default: BottomLeft
/// </summary>
/// <example>BottomLeft</example>
public AnnotationOrigin Origin { get; init; } = AnnotationOrigin.BottomLeft;
}
/// <summary>
/// Request DTO for multipart/form-data stamp operation
/// </summary>
public class AddStampMultipartRequest
{
/// <summary>
/// PDF file to stamp
/// </summary>
public required IFormFile File { get; set; }
/// <summary>
/// Type of stamp (Text, Image, or Predefined)
/// </summary>
public required StampType StampType { get; set; }
/// <summary>
/// Target page numbers (1-indexed). Null or empty = all pages.
/// </summary>
/// <example>[1, 3, 5]</example>
public int[]? PageNumbers { get; set; }
/// <summary>
/// Stamp position X coordinate
/// </summary>
/// <example>100.0</example>
public required double X { get; set; }
/// <summary>
/// Stamp position Y coordinate
/// </summary>
/// <example>100.0</example>
public required double Y { get; set; }
/// <summary>
/// Stamp width (optional, auto-size for images if not specified)
/// </summary>
/// <example>200.0</example>
public double? Width { get; set; }
/// <summary>
/// Stamp height (optional, auto-size for images if not specified)
/// </summary>
/// <example>50.0</example>
public double? Height { get; set; }
/// <summary>
/// Coordinate origin (BottomLeft = PDF native, TopLeft = UI-friendly). Default: BottomLeft
/// </summary>
/// <example>BottomLeft</example>
public AnnotationOrigin Origin { get; set; } = AnnotationOrigin.BottomLeft;
/// <summary>
/// Text content (required for Text stamps)
/// </summary>
/// <example>"CONFIDENTIAL"</example>
public string? Text { get; set; }
/// <summary>
/// Font name (default: Arial)
/// </summary>
/// <example>"Arial"</example>
public string? FontName { get; set; }
/// <summary>
/// Font size in points (default: 12)
/// </summary>
/// <example>24.0</example>
public double? FontSize { get; set; }
/// <summary>
/// Hex color (6 digits, e.g., "FF0000" for red, default: "000000")
/// </summary>
/// <example>"FF0000"</example>
public string? Color { get; set; }
/// <summary>
/// Opacity (0.0 = transparent, 1.0 = opaque, default: 0.5)
/// </summary>
/// <example>0.5</example>
public double? Opacity { get; set; }
/// <summary>
/// Rotation angle in degrees (0-360, default: 0)
/// </summary>
/// <example>45.0</example>
public double? Rotation { get; set; }
/// <summary>
/// Stamp placement (Foreground = on top, Background = watermark effect, default: Foreground)
/// </summary>
/// <example>Foreground</example>
public StampPlacement Placement { get; set; } = StampPlacement.Foreground;
/// <summary>
/// Image file (required for Image stamps, PNG/JPEG)
/// </summary>
public IFormFile? ImageFile { get; set; }
/// <summary>
/// Predefined stamp type (required for Predefined stamps)
/// </summary>
/// <example>Confidential</example>
public PredefinedStampType? PredefinedType { get; set; }
}
/// <summary>
/// Request DTO for Base64-encoded PDF stamp operation (API layer only - converts to AddStampCommand)
/// </summary>
public record AddStampBase64Request
{
/// <summary>
/// Base64-encoded PDF file
/// </summary>
/// <example>"JVBERi0xLjQK..."</example>
public required string Base64Pdf { get; init; }
/// <summary>
/// Type of stamp (Text, Image, or Predefined)
/// </summary>
/// <example>Text</example>
public required StampType StampType { get; init; }
/// <summary>
/// Target page numbers (1-indexed). Null or empty = all pages.
/// </summary>
/// <example>[1, 3, 5]</example>
public int[]? PageNumbers { get; init; }
/// <summary>
/// Stamp position X coordinate
/// </summary>
/// <example>100.0</example>
public required double X { get; init; }
/// <summary>
/// Stamp position Y coordinate
/// </summary>
/// <example>100.0</example>
public required double Y { get; init; }
/// <summary>
/// Stamp width (optional, auto-size for images if not specified)
/// </summary>
/// <example>200.0</example>
public double? Width { get; init; }
/// <summary>
/// Stamp height (optional, auto-size for images if not specified)
/// </summary>
/// <example>50.0</example>
public double? Height { get; init; }
/// <summary>
/// Coordinate origin (BottomLeft = PDF native, TopLeft = UI-friendly). Default: BottomLeft
/// </summary>
/// <example>BottomLeft</example>
public AnnotationOrigin Origin { get; init; } = AnnotationOrigin.BottomLeft;
/// <summary>
/// Text content (required for Text stamps)
/// </summary>
/// <example>"CONFIDENTIAL"</example>
public string? Text { get; init; }
/// <summary>
/// Font name (default: Arial)
/// </summary>
/// <example>"Arial"</example>
public string? FontName { get; init; }
/// <summary>
/// Font size in points (default: 12)
/// </summary>
/// <example>24.0</example>
public double? FontSize { get; init; }
/// <summary>
/// Hex color (6 digits, e.g., "FF0000" for red, default: "000000")
/// </summary>
/// <example>"FF0000"</example>
public string? Color { get; init; }
/// <summary>
/// Opacity (0.0 = transparent, 1.0 = opaque, default: 0.5)
/// </summary>
/// <example>0.5</example>
public double? Opacity { get; init; }
/// <summary>
/// Rotation angle in degrees (0-360, default: 0)
/// </summary>
/// <example>45.0</example>
public double? Rotation { get; init; }
/// <summary>
/// Stamp placement (Foreground = on top, Background = watermark effect, default: Foreground)
/// </summary>
/// <example>Foreground</example>
public StampPlacement Placement { get; init; } = StampPlacement.Foreground;
/// <summary>
/// Base64-encoded image (required for Image stamps, PNG/JPEG)
/// </summary>
/// <example>"iVBORw0KGgoAAAANSUhEUgAA..."</example>
public string? Base64Image { get; init; }
/// <summary>
/// Predefined stamp type (required for Predefined stamps)
/// </summary>
/// <example>Confidential</example>
public PredefinedStampType? PredefinedType { get; init; }
}

View File

@@ -0,0 +1,170 @@
using DocumentService.Application.Common.DTOs;
using DocumentService.Application.ValidatePdf.Queries;
using DocumentService.Application.ValidatePdfA.Queries;
using DocumentService.Client.Models.Requests;
using DocumentService.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.API.Controllers;
/// <summary>
/// PDF validation operations
/// </summary>
[ApiController]
[Route("api/pdf/validation")]
[Produces("application/json")]
public class PdfValidationController(IMediator Mediator) : ControllerBase
{
/// <summary>
/// Validates a PDF document and returns metadata (multipart/form-data)
/// </summary>
/// <param name="file">PDF file to validate</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF metadata (page count, file size, PDF version, attachments)</returns>
/// <response code="200">PDF is valid, metadata returned</response>
/// <response code="400">Invalid PDF or file format</response>
/// <response code="500">Internal server error during validation</response>
[HttpPost("validate")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(PdfValidationResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ValidateFromFile(
IFormFile file,
CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest(new ProblemDetails
{
Title = "Invalid file",
Detail = "File is required and cannot be empty",
Status = StatusCodes.Status400BadRequest
});
}
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Direct pass-through to MediatR
var query = new ValidatePdfQuery { PdfStream = pdfStream };
var result = await Mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Validates a PDF document and returns metadata (Base64 JSON)
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF metadata (page count, file size, PDF version, attachments)</returns>
/// <response code="200">PDF is valid, metadata returned</response>
/// <response code="400">Invalid PDF or Base64 format</response>
/// <response code="500">Internal server error during validation</response>
[HttpPost("validate")]
[Consumes("application/json")]
[ProducesResponseType(typeof(PdfValidationResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ValidateFromBase64(
[FromBody] ValidatePdfBase64Request 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);
// Direct pass-through to MediatR
var query = new ValidatePdfQuery { PdfStream = pdfStream };
var result = await Mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Validates a PDF/A document and checks conformance level (multipart/form-data)
/// </summary>
/// <param name="file">PDF file to validate</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF/A metadata (conformance level, errors, warnings)</returns>
/// <response code="200">PDF/A validation completed, results returned</response>
/// <response code="400">Invalid PDF or file format</response>
/// <response code="500">Internal server error during validation</response>
[HttpPost("validate-pdfa")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(PdfAValidationResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ValidatePdfAFromFile(
IFormFile file,
CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest(new ProblemDetails
{
Title = "Invalid file",
Detail = "File is required and cannot be empty",
Status = StatusCodes.Status400BadRequest
});
}
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Direct pass-through to MediatR
var query = new ValidatePdfAQuery { PdfStream = pdfStream };
var result = await Mediator.Send(query, cancellationToken);
return Ok(result);
}
/// <summary>
/// Validates a PDF/A document and checks conformance level (Base64 JSON)
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>PDF/A metadata (conformance level, errors, warnings)</returns>
/// <response code="200">PDF/A validation completed, results returned</response>
/// <response code="400">Invalid PDF or Base64 format</response>
/// <response code="500">Internal server error during validation</response>
[HttpPost("validate-pdfa")]
[Consumes("application/json")]
[ProducesResponseType(typeof(PdfAValidationResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ValidatePdfAFromBase64(
[FromBody] ValidatePdfABase64Request 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);
// Direct pass-through to MediatR
var query = new ValidatePdfAQuery { PdfStream = pdfStream };
var result = await Mediator.Send(query, cancellationToken);
return Ok(result);
}
}

View File

@@ -0,0 +1,113 @@
using DocumentService.Application.Common.DTOs;
using DocumentService.Application.SwissQrCode.Queries;
using DocumentService.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.API.Controllers;
/// <summary>
/// Swiss QR Code extraction operations
/// </summary>
[ApiController]
[Route("api/pdf/qr-code")]
[Produces("application/json")]
public class SwissQrCodeController(IMediator Mediator) : ControllerBase
{
/// <summary>
/// Extracts Swiss QR Code from the last page of a PDF document (multipart/form-data)
/// </summary>
/// <param name="file">PDF file containing Swiss QR Code</param>
/// <param name="raw">If true, returns raw QR text lines instead of parsed Bill object</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns>
/// <response code="200">Swiss QR Code extracted successfully</response>
/// <response code="400">Invalid PDF or file format</response>
/// <response code="404">No Swiss QR Code found on the last page</response>
/// <response code="500">Internal server error during extraction</response>
[HttpPost("extract-swiss")]
[Consumes("multipart/form-data")]
[ProducesResponseType(typeof(SwissQrCodeExtractionResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractFromFile(
IFormFile file,
[FromQuery] bool raw = false,
CancellationToken cancellationToken = default)
{
if (file.Length == 0)
return BadRequest(new ProblemDetails
{
Title = "Invalid file",
Detail = "File is required and cannot be empty",
Status = StatusCodes.Status400BadRequest
});
// Use IFormFile stream directly (no intermediate byte[] conversion)
using var pdfStream = file.OpenReadStream();
// Direct pass-through to MediatR
var query = new ExtractSwissQrCodeQuery
{
PdfStream = pdfStream
};
var result = await Mediator.Send(query, cancellationToken);
return Ok(raw ? result.RawLines : result.Bill);
}
/// <summary>
/// Extracts Swiss QR Code from the last page of a PDF document (Base64 JSON)
/// </summary>
/// <param name="request">Request containing Base64-encoded PDF</param>
/// <param name="raw">If true, returns raw QR text lines instead of parsed Bill object</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns>
/// <response code="200">Swiss QR Code extracted successfully</response>
/// <response code="400">Invalid PDF or Base64 format</response>
/// <response code="404">No Swiss QR Code found on the last page</response>
/// <response code="500">Internal server error during extraction</response>
[HttpPost("extract-swiss")]
[Consumes("application/json")]
[ProducesResponseType(typeof(SwissQrCodeExtractionResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractFromBase64(
[FromBody] ExtractSwissQrCodeBase64Request request,
[FromQuery] bool raw = false,
CancellationToken cancellationToken = default)
{
// 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);
// Direct pass-through to MediatR
var query = new ExtractSwissQrCodeQuery { PdfStream = pdfStream };
var result = await Mediator.Send(query, cancellationToken);
return Ok(raw ? result.RawLines : result.Bill);
}
}
/// <summary>
/// Request DTO for Base64-encoded Swiss QR Code extraction
/// </summary>
public record ExtractSwissQrCodeBase64Request
{
/// <summary>
/// PDF document encoded as Base64 string
/// </summary>
/// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
public required string Base64Pdf { get; init; }
}

View File

@@ -0,0 +1,179 @@
using DocumentService.Application.Common.DTOs;
using DocumentService.Application.ExtractZugferd;
using DocumentService.Application.HasZugferd.Queries;
using DocumentService.Client.Models.Requests;
using DocumentService.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DocumentService.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="asFile">if true, 'file' (returns XML file directly); otherwise output format: 'json' (default, returns metadata + XML content)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>ZUGFeRD XML content and metadata (JSON) or XML file (application/xml)</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(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractZugferdFromFile(
IFormFile file,
[FromQuery] bool asFile = true,
CancellationToken cancellationToken = default)
{
// 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 as file or JSON based on format parameter
if (asFile)
{
byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(result.XmlContent);
return File(xmlBytes, "application/xml", result.FileName);
}
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="format">Output format: 'json' (default, returns metadata + XML content) or 'file' (returns XML file directly)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>ZUGFeRD XML content and metadata (JSON) or XML file (application/xml)</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(FileContentResult), 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,
[FromQuery] string format = "json",
CancellationToken cancellationToken = default)
{
// 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 as file or JSON based on format parameter
if (format.Equals("file", StringComparison.OrdinalIgnoreCase))
{
byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(result.XmlContent);
return File(xmlBytes, "application/xml", result.FileName);
}
return Ok(result);
}
}

View File

@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageId>DocumentOperator.API</PackageId>
<Authors>Digital Data GmbH</Authors>
<Company>Digital Data GmbH</Company>
<Product>DocumentOperator.API</Product>
<Version>1.0.0</Version>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<InformationalVersion>1.0.0</InformationalVersion>
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
<Description>PDF Document Operations REST API - Validation, Swiss QR Code extraction, attachments, merge, annotation, stamp operations powered by DevExpress Office File API</Description>
<PackageTags>pdf document operator validation swiss-qr-code annotations stamp devexpress</PackageTags>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Http" Version="8.1.1" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.28" />
<PackageReference Include="Scalar.AspNetCore" Version="1.2.58" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.SQLite" Version="7.0.0" />
<PackageReference Include="Serilog.UI" Version="3.2.0" />
<PackageReference Include="Serilog.UI.SqliteProvider" Version="1.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DocumentService.Application\DocumentService.Application.csproj" />
<ProjectReference Include="..\DocumentService.Client\DocumentService.Client.csproj" />
<ProjectReference Include="..\DocumentService.Domain\DocumentService.Domain.csproj" />
<ProjectReference Include="..\DocumentService.Infrastructure\DocumentService.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@DocumentService.API_HostAddress = http://localhost:5028
GET {{DocumentService.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,109 @@
using DocumentService.Domain.Common.Exceptions;
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Text.Json;
namespace DocumentService.API.Middleware;
/// <summary>
/// Central exception handling middleware
/// Maps exceptions to HTTP status codes and RFC 7807 Problem Details
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </remarks>
/// <param name="Next">The next middleware in the pipeline.</param>
public class ExceptionHandlingMiddleware(RequestDelegate Next)
{
private static readonly JsonSerializerOptions ProbDetailsJsonOpt = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>
/// Invokes the middleware to handle incoming HTTP requests and catch exceptions.
/// </summary>
/// <param name="context">The HTTP context for the current request.</param>
public async Task InvokeAsync(HttpContext context)
{
try
{
await Next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var (statusCode, problemDetails) = MapExceptionToProblemDetails(exception, context);
context.Response.StatusCode = (int)statusCode;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails, ProbDetailsJsonOpt));
}
private static (HttpStatusCode StatusCode, ProblemDetails ProblemDetails) MapExceptionToProblemDetails(
Exception exception,
HttpContext context)
{
return exception switch
{
// FluentValidation (400 Bad Request)
ValidationException validationEx => (
HttpStatusCode.BadRequest,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
Title = "Validation Error",
Status = (int)HttpStatusCode.BadRequest,
Detail = string.Join("; ", validationEx.Errors.Select(e => e.ErrorMessage)),
Instance = context.Request.Path
}
),
// Bad Request Exception (400 Bad Request)
BadRequestException badReqEx => (
HttpStatusCode.BadRequest,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4",
Title = "Bad Request",
Status = (int)HttpStatusCode.BadRequest,
Detail = badReqEx.Message,
Instance = context.Request.Path
}
),
// Not Found Exception (404 Not Found)
NotFoundException notFoundEx => (
HttpStatusCode.NotFound,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4",
Title = "Resource Not Found",
Status = (int)HttpStatusCode.NotFound,
Detail = notFoundEx.Message,
Instance = context.Request.Path
}
),
// Generic Exception (500 Internal Server Error)
_ => (
HttpStatusCode.InternalServerError,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.6.1",
Title = "Internal Server Error",
Status = (int)HttpStatusCode.InternalServerError,
Detail = "An unexpected error occurred. Please contact support.",
Instance = context.Request.Path
}
)
};
}
}

View File

@@ -0,0 +1,9 @@
namespace DocumentService.API.Middleware
{
/// <summary>
/// Placeholder middleware for HTTP request/response logging.
/// </summary>
public class RequestLoggingMiddleware
{
}
}

View File

@@ -0,0 +1,9 @@
namespace DocumentService.API.Middleware
{
/// <summary>
/// Placeholder middleware for multi-tenancy resolution via X-API-Key header.
/// </summary>
public class TenantResolutionMiddleware
{
}
}

View File

@@ -0,0 +1,545 @@
# ?? DocumentService - Phasenplan (Feature-Driven Development)
> **Stand:** 17.01.2025 | **Aktuell:** Feature 3 - ExtractAttachments ? NEXT | **Projektdauer:** 6 Wochen
---
## ?? Übersicht
| Woche | Features / Concerns | Status | Fortschritt |
|-------|---------------------|--------|-------------|
| **W1** | Feature 1: ValidatePDF | ? Abgeschlossen | 100% (Foundation + Application + API + Swagger fertig) |
| **W1-W2** | Feature 2: ExtractSwissQrCode | ? Abgeschlossen | 100% (Domain + Infrastructure + Application + API + Swagger fertig) |
| **W2** | Feature 3: ExtractAttachments | ? Nächstes Feature | 0% |
| **W2** | Feature 4: ApplyStamp | ? Geplant | 0% |
| **W3** | Feature 5: EmbedCertificate | ? Geplant | 0% |
| **W3** | Feature 6: ConcatenatePDFs (Async) | ? Geplant | 0% |
| **W4** | Multi-Tenancy (X-API-Key Header) | ? Geplant | 0% |
| **W5** | Health Checks + Polly + Logging | ? Geplant | 0% |
| **W6** | Production Deployment | ? Geplant | 0% |
---
## ?? NEUE VORGEHENSWEISE
**Was hat sich geändert?**
? **Feature-by-Feature Development** statt Layer-by-Layer
- Jedes Feature wird KOMPLETT umgesetzt (Domain ? Infrastructure ? Application ? API ? Tests ? Swagger)
- Feature ist erst "DONE" wenn es im Swagger testbar ist
- Dann nächstes Feature
? **Kleine Schritte** (1 Layer pro Step)
- Nach jedem Step: ROADMAP + PHASENPLAN aktualisieren
- Commit nach jedem Step
- Dann weiter
? **Multi-Tenancy & Cross-Cutting Concerns später**
- Erst alle synchronen Features (1-4)
- Dann Multi-Tenancy für ALLE Endpoints
- Dann Health Checks, Polly, Logging
---
## ?? DETAILLIERTER PLAN
### WOCHE 1 - Feature 1: ValidatePDF | ? ABGESCHLOSSEN - 100%
**Ziel:** POST /api/v1/documents/validate Endpoint im Swagger testbar
#### ? Step 1.0: Foundation (ABGESCHLOSSEN)
**Dauer:** ~2 Tage
**Was wurde erstellt:**
- ? Solution Structure (4 Projekte)
- ? Domain Layer (Exceptions, Enums, Value Objects)
- ? Infrastructure Layer (DevExpressPdfProcessor.ValidateAsync)
- ? Tests (DevExpressPdfProcessorTests.cs - 6 Tests)
- ? Build erfolgreich
---
#### ? Step 1.1: Application Layer (MediatR Setup + ValidatePDF Feature) - **ABGESCHLOSSEN**
**Dauer:** ~4 Stunden
**Was wurde erstellt:**
1. **MediatR Setup**
- ? `Application/DependencyInjection.cs` (Service Registration)
- ? `Application/Common/Behaviors/ValidationBehavior.cs` (FluentValidation Pipeline)
- ? `Application/Common/Behaviors/LoggingBehavior.cs` (Logging Pipeline mit ILogger<T>)
2. **ValidatePDF Feature (Vertical Slice)**
- ? `Application/Features/Documents/ValidatePdf/ValidatePdfQuery.cs`
- ? `Application/Features/Documents/ValidatePdf/ValidatePdfHandler.cs`
- ? `Application/Features/Documents/ValidatePdf/ValidatePdfValidator.cs`
3. **DTOs**
- ? `Application/Common/DTOs/ValidatePdfRequest.cs`
- ? `Application/Common/DTOs/ValidatePdfResponse.cs`
4. **Tests**
- ? `Tests/Unit/Application/Features/ValidatePdf/ValidatePdfHandlerTests.cs` (2 Tests)
**Akzeptanzkriterien:**
- ? Build erfolgreich
- ? Tests grün (Handler Tests: 2/2 passed)
- ? MediatR Pipeline funktioniert (Validation + Logging)
---
#### ? Step 1.2: API Layer (Endpoint + Exception Middleware) - **ABGESCHLOSSEN**
**Dauer:** ~3 Stunden
**Was wurde erstellt:**
1. **Exception Middleware**
- ? `API/Middleware/ExceptionHandlingMiddleware.cs`
- Exception ? HTTP Status Code Mapping (400, 404, 422, 500)
- RFC 7807 Problem Details
2. **Minimal API Endpoint**
- ? `API/Endpoints/v1/DocumentEndpoints.cs`
- POST /api/v1/documents/validate
3. **Infrastructure DI**
- ? `Infrastructure/DependencyInjection.cs`
- IPdfProcessor ? DevExpressPdfProcessor registriert
4. **Program.cs Updates**
- ? Exception Middleware registriert (FIRST in pipeline!)
- ? DocumentEndpoints registriert
- ? Application + Infrastructure Services registriert
5. **Integration Tests**
- ? `Tests/Integration/API/DocumentEndpointsTests.cs` (3 Tests)
- ? Test: `POST_ValidatePdf_ValidPdf_Returns200`
- ? Test: `POST_ValidatePdf_InvalidBase64_Returns400`
- ? Test: `POST_ValidatePdf_EmptyPdf_Returns400`
**Akzeptanzkriterien:**
- ? Build erfolgreich
- ? Integration Tests grün (3/3 passed)
- ? Endpoint gibt korrekte HTTP Status Codes zurück
---
#### ? Step 1.3: Swagger Dokumentation - **ABGESCHLOSSEN**
**Dauer:** ~1 Stunde
**Was wurde erstellt:**
1. **Swagger Configuration**
- ? `API/Configuration/SwaggerConfiguration.cs`
- ? `AddSwaggerDocumentation()` Extension Method
- ? XML Comments aktiviert
2. **XML-Dokumentation aktiviert**
- ? `API/DocumentService.API.csproj`
- ? `<GenerateDocumentationFile>true</GenerateDocumentationFile>`
3. **Endpoint Dokumentation**
- ? `API/Endpoints/v1/DocumentEndpoints.cs`
- ? XML Comments für `ValidatePdf` Methode
- ? Swagger-Annotationen (`.WithSummary()`, `.WithDescription()`, `.Produces<>()`)
4. **DTOs Dokumentation**
- ? `Application/Common/DTOs/ValidatePdfRequest.cs` (XML Comments)
- ? `Application/Common/DTOs/ValidatePdfResponse.cs` (XML Comments + `FileSizeMB` hinzugefügt)
5. **Program.cs Updates**
- ? `builder.Services.AddSwaggerDocumentation()` statt `AddSwaggerGen()`
- ? `using DocumentService.API.Configuration;` hinzugefügt
**Akzeptanzkriterien:**
- ? Build erfolgreich
- ? Alle Tests grün (11/11)
- ? XML-Dokumentation wird generiert (`DocumentService.API.xml`)
- ? Swagger UI zeigt Endpoint `/api/v1/documents/validate` mit Dokumentation
- ? Request/Response-Schemas sind dokumentiert
- ? Endpoint ist im Swagger UI testbar
---
#### ? Feature 1 ABGESCHLOSSEN!
**Gesamtdauer:** ~1 Tag
**Ergebnis:**
- ? POST /api/v1/documents/validate im Swagger testbar
- ? Unit Tests + Integration Tests grün (11/11)
- ? Clean Architecture eingehalten
- ? TDD angewendet
- ? Swagger-Dokumentation vollständig
---
### WOCHE 1-2 - Feature 2: ExtractSwissQrCode | ? ABGESCHLOSSEN - 100%
**Dauer:** ~1-2 Tage
**Status:** ? Abgeschlossen
**Endpoint:** POST /api/v1/documents/extract-swiss-qr-code
**Was wurde gebaut:**
- Client sendet Referenzen (Array) + PDF (Base64)
- API extrahiert Swiss QR Code von **letzter Seite**
- API gibt Referenzen + alle QR Code Felder zurück (Swiss QR Bill Standard 2.0)
**Technologie:**
- **DevExpress PDF Document API** (PDF-Zugriff, letzte Seite)
- **ZXing.Net.Bindings.Windows.Compatibility** (QR Code Detection)
- **Codecrete.SwissQRBill.Generator** (Swiss QR Code Parsing - Standard 2.0)
- **System.Drawing.Common** (Bitmap Support)
**Steps:**
- ? Step 2.1: Domain Layer (SwissQrCodeData Value Object) - ABGESCHLOSSEN
- ? Step 2.2: Infrastructure Layer (ISwissQrCodeProcessor + DevExpressSwissQrCodeProcessor + Library Integration) - ABGESCHLOSSEN
- ? Step 2.3: Application Layer (ExtractSwissQrCodeQuery + Handler + Validator + DTOs) - ABGESCHLOSSEN
- ? Step 2.4: API Layer (Endpoint + Exception Mapping + Integration Tests) - ABGESCHLOSSEN
- ? Step 2.5: Swagger Dokumentation (XML Comments + Examples) - ABGESCHLOSSEN
**Akzeptanzkriterien:**
- ? QR Code wird von letzter Seite extrahiert
- ? Alle Swiss QR Bill Felder werden geparst (Standard 2.0)
- ? Referenzen werden durchgeschliffen (Echo)
- ? Fehler wenn kein QR Code gefunden (404 Not Found)
- ? Swagger-testbar
- ? Tests grün (19/19)
**Ergebnis:**
- ? POST /api/v1/documents/extract-swiss-qr-code im Swagger testbar
- ? Nested Response Structure (References + SwissQrCodeData)
- ? SwissQrCodeNotFoundException wird zu 404 gemappt
- ? Unit Tests + Integration Tests grün (19/19)
- ? Clean Architecture eingehalten
- ? Swagger-Dokumentation vollständig
---
### WOCHE 2 - Features 3 & 4 | ? Geplant - 0%
#### Feature 3: ExtractAttachments (Synchron)
**Dauer:** ~1 Tag
**Status:** ? Pending
**Endpoint:** POST /api/v1/documents/extract-attachments
**Steps:**
- ? Step 3.1: Infrastructure Layer (DevExpressPdfProcessor.ExtractAttachmentsAsync)
- ? Step 3.2: Application Layer (ExtractAttachmentsCommand + Handler + Validator)
- ? Step 3.3: API Layer (Endpoint)
- ? Step 3.4: Swagger Dokumentation
**Akzeptanzkriterien:**
- ? Endpoint im Swagger testbar
- ? Tests grün
---
#### Feature 4: ApplyStamp (Synchron)
**Dauer:** ~1 Tag
**Status:** ? Pending
**Endpoint:** POST /api/v1/documents/apply-stamp
**Steps:**
- ? Step 4.1: Infrastructure Layer (DevExpressPdfProcessor.ApplyStampAsync)
- ? Step 4.2: Application Layer (ApplyStampCommand + Handler + Validator)
- ? Step 4.3: API Layer (Endpoint)
- ? Step 4.4: Swagger Dokumentation
**Akzeptanzkriterien:**
- ? Endpoint im Swagger testbar
- ? Stamp wird korrekt angewendet
- ? Tests grün
---
### WOCHE 3 - Features 5 & 6 | ? Geplant - 0%
#### Feature 5: EmbedCertificate (Synchron)
**Dauer:** ~1 Tag
**Status:** ? Pending
**Endpoint:** POST /api/v1/documents/embed-certificate
**Steps:**
- ? Step 5.1: Infrastructure Layer (DevExpressPdfProcessor.EmbedCertificateAsync)
- ? Step 5.2: Application Layer (EmbedCertificateCommand + Handler + Validator)
- ? Step 5.3: API Layer (Endpoint)
- ? Step 5.4: Swagger Dokumentation
**Akzeptanzkriterien:**
- ? Endpoint im Swagger testbar
- ? Zertifikat wird korrekt eingebettet
- ? Tests grün
---
#### Feature 6: ConcatenatePDFs (Asynchron)
**Dauer:** ~2 Tage
**Status:** ? Pending
**Endpoints:**
- POST /api/v1/documents/concatenate (Async, gibt JobId zurück)
- GET /api/v1/jobs/{jobId} (Job-Status abfragen)
- GET /api/v1/jobs/{jobId}/download (Ergebnis herunterladen)
**Steps:**
- ? Step 6.1: Infrastructure Layer (In-Memory Queue + Background Worker)
- ? Step 6.2: Application Layer (SubmitConcatenateJobCommand + GetJobStatusQuery)
- ? Step 6.3: API Layer (Async Endpoints)
- ? Step 6.4: Swagger Dokumentation
**Akzeptanzkriterien:**
- ? POST /concatenate gibt JobId zurück
- ? GET /jobs/{jobId} zeigt Status (Pending, Processing, Success, Failed)
- ? GET /jobs/{jobId}/download gibt PDF zurück
- ? Background Worker verarbeitet Jobs korrekt
- ? Tests grün
---
### WOCHE 4 - Multi-Tenancy | ? Geplant - 0%
**Ziel:** X-API-Key Header für ALLE Endpoints
**Was wird gebaut:**
- EF Core + SQLite (Tenant-Datenbank)
- Redis Cache (API-Key Lookups - optional)
- TenantResolutionMiddleware (X-API-Key ? Tenant)
- BCrypt API-Key Hashing
- Admin API (Tenant CRUD)
**Steps:**
#### Step MT.1: EF Core Setup
**Dauer:** ~3 Stunden
**Was wird erstellt:**
- `Infrastructure/Data/TenantDbContext.cs`
- `Infrastructure/Data/Entities/Tenant.cs`
- `Infrastructure/Data/Entities/TenantSettings.cs`
- EF Core Migration (InitialCreate)
- SQLite Database erstellen
**Akzeptanzkriterien:**
- ? Datenbank erstellt
- ? Tenant-Tabelle existiert
- ? Build erfolgreich
---
#### Step MT.2: TenantResolutionMiddleware
**Dauer:** ~2 Stunden
**Was wird erstellt:**
- `API/Middleware/TenantResolutionMiddleware.cs`
- `Application/Common/Interfaces/ITenantContext.cs`
- `Infrastructure/Services/TenantContext.cs`
**Akzeptanzkriterien:**
- ? X-API-Key Header wird gelesen
- ? Tenant aus DB geladen
- ? ITenantContext im Request Scope verfügbar
- ? Ungültiger API-Key ? HTTP 401
---
#### Step MT.3: Redis Cache Integration (Optional)
**Dauer:** ~1 Stunde
**Was wird erstellt:**
- Redis Cache für API-Key Lookups
- TTL: 1 Stunde
**Akzeptanzkriterien:**
- ? API-Key Lookup cached (weniger DB-Calls)
- ? Cache Invalidation funktioniert
---
#### Step MT.4: Admin API (Tenant Management)
**Dauer:** ~2 Stunden
**Was wird erstellt:**
- POST /api/v1/admin/tenants (Create Tenant)
- PUT /api/v1/admin/tenants/{id}/rotate-key (API-Key rotieren)
- PATCH /api/v1/admin/tenants/{id}/deactivate (Tenant deaktivieren)
- GET /api/v1/admin/tenants (Liste aller Tenants)
**Akzeptanzkriterien:**
- ? Endpoints im Swagger testbar
- ? API-Key wird gehashed (BCrypt)
- ? Tests grün
---
#### Step MT.5: Alle Endpoints mit X-API-Key absichern
**Dauer:** ~1 Stunde
**Was wird geändert:**
- Alle Feature-Endpoints bekommen X-API-Key Header Requirement
- Swagger zeigt API-Key Security Scheme
**Akzeptanzkriterien:**
- ? Alle Endpoints erfordern X-API-Key Header
- ? Swagger zeigt Security Scheme
- ? Tests aktualisiert (mit API-Key)
---
### WOCHE 5 - Health Checks + Polly + Logging | ? Geplant - 0%
#### Health Checks
**Dauer:** ~2 Stunden
**Was wird gebaut:**
- `/health` Endpoint (Liveness/Readiness Probes)
- DevExpressPdfHealthCheck (Smoke Test)
- Database Health Check (SQLite)
- Redis Health Check (optional)
**Akzeptanzkriterien:**
- ? /health gibt HTTP 200 wenn alles OK
- ? /health gibt HTTP 503 wenn DevExpress nicht funktioniert
---
#### Polly Resilience
**Dauer:** ~3 Stunden
**Was wird gebaut:**
- Retry Policy (3x mit Exponential Backoff)
- Circuit Breaker (nach 5 Fehlern 30s öffnen)
- Timeout Policy (30s max)
**Akzeptanzkriterien:**
- ? DevExpress Calls werden mit Polly gewickelt
- ? Retry funktioniert bei Transient Errors
- ? Circuit Breaker öffnet bei vielen Fehlern
---
#### Logging & Monitoring
**Dauer:** ~3 Stunden
**Was wird gebaut:**
- CorrelationIdMiddleware (X-Correlation-ID Header)
- Seq Sink (Log-Browsing UI)
- File Logging (Production)
- LoggingBehavior erweitert (Performance-Tracking)
**Akzeptanzkriterien:**
- ? Correlation IDs in allen Logs
- ? Seq UI zeigt Logs (Development)
- ? File Logging funktioniert (Production)
---
### WOCHE 6 - Production Deployment | ? Geplant - 0%
**Ziel:** Service ist produktionsreif
**Was wird gebaut:**
- appsettings.Production.json (Production Settings)
- IIS Web.config (Kestrel Settings)
- SSL/TLS Zertifikat konfigurieren
- Deployment-Skript (PowerShell)
**Steps:**
#### Deployment Vorbereitung
**Dauer:** ~4 Stunden
**Was wird erstellt:**
- `appsettings.Production.json` (Prod-Settings)
- `Web.config` (IIS Integration)
- PowerShell Deploy-Skript
- Dokumentation (README.md)
**Akzeptanzkriterien:**
- ? Build in Release Mode erfolgreich
- ? IIS Deployment funktioniert
- ? HTTPS funktioniert
---
#### Production Testing
**Dauer:** ~4 Stunden
**Was wird getestet:**
- Alle Endpoints im Production-Modus
- Health Checks
- Multi-Tenancy
- Performance (Load Testing)
**Akzeptanzkriterien:**
- ? Alle Features funktionieren in Production
- ? Health Checks grün
- ? Performance OK (< 1s Response Time)
---
## ?? FORTSCHRITTS-TRACKING
### Gesamt-Fortschritt
| Kategorie | Status | Fortschritt |
|-----------|--------|-------------|
| **Foundation** | ? Abgeschlossen | 100% |
| **Feature 1** | ? Abgeschlossen | 100% |
| **Feature 2-5** | ? Pending | 0% |
| **Multi-Tenancy** | ? Pending | 0% |
| **Cross-Cutting** | ? Pending | 0% |
| **Production** | ? Pending | 0% |
---
## ?? NEXT STEPS
### Nächstes Feature
**Feature 3: ExtractAttachments** - **NEXT**
1. ?? Step 3.1: Domain Layer (Attachment Value Object)
2. ?? Step 3.2: Infrastructure Layer (IAttachmentProcessor + DevExpressAttachmentProcessor)
3. ?? Step 3.3: Application Layer (ExtractAttachmentsQuery + Handler + Validator + DTOs)
4. ?? Step 3.4: API Layer (Endpoint + Integration Tests)
5. ?? Step 3.5: Swagger Dokumentation
**Erwarteter Zeitaufwand:** ~1 Tag
**Akzeptanzkriterien:**
- ? POST /api/v1/documents/extract-attachments im Swagger testbar
- ? Alle Attachments werden extrahiert
- ? Attachment-Metadaten werden zurückgegeben
- ? Alle Tests grün
- ? Clean Architecture eingehalten
---
## ?? UPDATE LOG
| Date | Feature/Step | Changes |
|------|--------------|---------|
| 2024-XX-XX | Foundation | Project setup, dependencies, folder structure |
| 2024-XX-XX | Domain Layer | Exceptions, Enums, Value Objects |
| 17.01.2025 | Infrastructure | DevExpressPdfProcessor.ValidateAsync implementiert |
| 17.01.2025 | Tests | DevExpressPdfProcessorTests.cs erstellt (6 Tests) |
| 17.01.2025 | **PHASENPLAN** | ?? **Komplett umstrukturiert** (Feature-basiert + Datum korrigiert 23.06.2026 ? 17.01.2025) |
| 17.01.2025 | **Feature 1 - Step 1.1** | ? **ABGESCHLOSSEN** - Application Layer (MediatR, Behaviors, ValidatePDF Feature, DTOs, Tests - 2/2 grün) |
| 17.01.2025 | **Feature 1 - Step 1.2** | ? **ABGESCHLOSSEN** - API Layer (ExceptionMiddleware, Endpoint, Program.cs, Integration Tests - 3/3 grün) |
| 17.01.2025 | **Feature 1 - Step 1.3** | ? **ABGESCHLOSSEN** - Swagger Dokumentation (SwaggerConfiguration, XML Comments, Endpoint/DTO-Dokumentation - 11/11 Tests grün) |
| 17.01.2025 | **Feature 1** | ? **KOMPLETT ABGESCHLOSSEN** - ValidatePDF Feature testbar im Swagger UI! |
| 17.01.2025 | **Fix: Attachment Detection (Multiple Attachments)** | ? **KORRIGIERT** - ValidatePDF erkennt jetzt auch PDFs mit mehreren Attachments korrekt (globale Suche statt 1000-Zeichen-Limit) - 13/13 Tests grün |
| 17.01.2025 | **Fix: Attachment Count (6 Attachments)** | ? **KORRIGIERT** - AttachmentCount wird jetzt korrekt gezählt (objectCount statt objectCount/2). PDFs mit 6 Attachments werden korrekt erkannt - 13/13 Tests grün |
| 17.01.2025 | **PHASENPLAN** | ?? **Feature-Reihenfolge geändert** - Neues Feature 2: ExtractSwissQrCode (Swiss QR Bill Standard 2.0) eingefügt. Alte Features 2-5 werden zu Features 3-6. |
| 17.01.2025 | **Feature 2 - Step 2.1** | ? **ABGESCHLOSSEN** - Domain Layer (SwissQrCodeData, AddressData, SwissQrCodeNotFoundException) |
| 17.01.2025 | **Feature 2 - Step 2.2** | ? **ABGESCHLOSSEN** - Infrastructure Layer (ISwissQrCodeProcessor, DevExpressSwissQrCodeProcessor, ZXing + Codecrete Integration) |
| 17.01.2025 | **Feature 2 - Step 2.3** | ? **ABGESCHLOSSEN** - Application Layer (ExtractSwissQrCodeQuery, Handler, Validator, Request/Response DTOs, Unit Tests) |
| 17.01.2025 | **Feature 2 - Step 2.4** | ? **ABGESCHLOSSEN** - API Layer (Endpoint, Exception Mapping, Integration Tests - 19/19 Tests grün) |
| 17.01.2025 | **Feature 2 - Step 2.5** | ? **ABGESCHLOSSEN** - Swagger Dokumentation (XML Comments, Examples, Endpoint Description) |
| 17.01.2025 | **Feature 2** | ? **KOMPLETT ABGESCHLOSSEN** - ExtractSwissQrCode Feature testbar im Swagger UI! (19/19 Tests grün) |
---
**END OF PHASENPLAN**
*This document is a living document and will be updated after each completed step.*

View File

@@ -0,0 +1,147 @@
using Serilog;
using Serilog.Ui.Core.Extensions;
using Serilog.Ui.SqliteDataProvider.Extensions;
using Serilog.Ui.Web.Extensions;
using Scalar.AspNetCore;
using DocumentService.Infrastructure.Configuration;
using DocumentService.Application;
using DocumentService.Application.Common.Configuration;
using DocumentService.Infrastructure;
using DocumentService.API.Middleware;
using DocumentService.API.Configuration;
var builder = WebApplication.CreateBuilder(args);
// ========================================
// 1. Serilog Configuration
// ========================================
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "DocumentService")
.CreateLogger();
builder.Host.UseSerilog();
Log.Information("Starting DocumentService API...");
try
{
// ========================================
// 2. Options Pattern Configuration
// ========================================
builder.Services.Configure<DocumentServiceSettings>(
builder.Configuration.GetSection(DocumentServiceSettings.SectionName));
builder.Services.Configure<ZugferdSettings>(
builder.Configuration.GetSection("ZugferdSettings"));
builder.Services.Configure<RedisSettings>(
builder.Configuration.GetSection(RedisSettings.SectionName));
builder.Services.Configure<ApiKeySettings>(
builder.Configuration.GetSection(ApiKeySettings.SectionName));
builder.Services.Configure<SwaggerSettings>(
builder.Configuration.GetSection(SwaggerSettings.SectionName));
// ========================================
// 3. Services (Clean Architecture Layers)
// ========================================
builder.Services.AddApplication(builder.Configuration); // Application Layer (MediatR, FluentValidation, Behaviors)
builder.Services.AddInfrastructure(); // Infrastructure Layer (DevExpress, Services)
builder.Services.AddControllers(); // Controllers (Controller-based API)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerDocumentation(builder.Configuration);
// ========================================
// 4. Serilog.UI Configuration
// ========================================
var logDirectory = builder.Configuration.GetValue<string>("Application:LogDirectory")
?? throw new InvalidOperationException("Application:LogDirectory not found in configuration.");
var sqliteDbPath = Path.Combine(logDirectory, "logs.db");
builder.Services.AddSerilogUi(logUIOpt =>
{
logUIOpt.UseSqliteServer(dbOpt =>
{
dbOpt.WithConnectionString($"Data Source={sqliteDbPath}");
dbOpt.WithTable("Logs");
});
});
// ========================================
// 5. Build App
// ========================================
var app = builder.Build();
// ========================================
// 5. Middleware Pipeline (Order matters!)
// ========================================
// Exception Handling FIRST (catches all exceptions from subsequent middleware)
app.UseMiddleware<ExceptionHandlingMiddleware>();
// ========================================
// Swagger/OpenAPI (Conditional based on settings)
// ========================================
var swaggerSettings = builder.Configuration.GetSection(SwaggerSettings.SectionName).Get<SwaggerSettings>()
?? new SwaggerSettings();
if (app.Environment.IsDevelopment() || swaggerSettings.EnableInProduction)
{
app.UseSwagger();
// Swagger UI (classic)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint($"/swagger/{swaggerSettings.Version}/swagger.json",
$"{swaggerSettings.Title} {swaggerSettings.Version}");
options.RoutePrefix = "swagger"; // /swagger
});
// Scalar UI (modern alternative)
app.MapScalarApiReference(options =>
{
options
.WithTitle(swaggerSettings.Title)
.WithTheme(ScalarTheme.DeepSpace)
.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
});
}
app.UseSerilogRequestLogging(); // Log HTTP Requests
app.UseHttpsRedirection();
// ========================================
// 6. Serilog.UI Dashboard
// ========================================
app.UseSerilogUi(); // Accessible at /serilog-ui
// ========================================
// 7. Endpoints (Controller-based API)
// ========================================
app.MapControllers(); // Maps all [ApiController] controllers
Log.Information("DocumentService API started successfully");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application startup failed");
throw;
}
finally
{
Log.CloseAndFlush();
}
// Make Program class accessible for Integration Tests
/// <summary>
/// Entry point class for the DocumentService API.
/// Made partial and public for integration test access.
/// </summary>
public partial class Program { }

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project>
<PropertyGroup>
<WebPublishMethod>Package</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<ExcludeApp_Data>false</ExcludeApp_Data>
<ProjectGuid>c60bc965-d293-ea64-b153-1941f0648df4</ProjectGuid>
<DesktopBuildPackageLocation>M:\App&amp;Service\0 DD - Smart UP\DocumentService\PreRelease\API\net8\$(Version)\DocumentService.API.zip</DesktopBuildPackageLocation>
<PackageAsSingleFile>true</PackageAsSingleFile>
<DeployIisAppPath>DocumentService.API</DeployIisAppPath>
<_TargetId>IISWebDeployPackage</_TargetId>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:62933",
"sslPort": 44304
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5028",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7186;http://localhost:5028",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,387 @@
# DocumentService API - Manual Testing Guide
This guide contains manual test scenarios for validating the DocumentService API endpoints using Swagger UI or tools like Postman.
---
## Prerequisites
1. **Start the API:**
```powershell
dotnet run --project DocumentService.API
```
Default URL: `https://localhost:5001` (check console output for actual port)
2. **Open Swagger UI:**
Navigate to `https://localhost:<port>/swagger`
3. **Test PDFs:**
- Use PDFs from `fake-pdf/` folder (form.pdf, multi-page.pdf, one-page.pdf, with-image.pdf)
- Or use your own PDF files
---
## Feature 1: Basic PDF Validation
### Endpoint: `POST /api/pdf/validation/validate`
#### Test Case 1.1: Valid PDF (Multipart Upload)
**Objective:** Verify basic PDF validation works with file upload
**Steps:**
1. Open Swagger UI → `/api/pdf/validation/validate`
2. Click "Try it out"
3. Select **multipart/form-data** from dropdown
4. Click "Choose File" and select `fake-pdf/one-page.pdf`
5. Click "Execute"
**Expected Result:**
- **Status Code:** 200 OK
- **Response Body:**
```json
{
"pageCount": 1,
"fileSizeBytes": 7168,
"fileSizeMB": 0.01,
"pdfVersion": "1.4",
"hasAttachments": false,
"attachmentCount": 0
}
```
---
#### Test Case 1.2: Valid PDF (Base64 JSON)
**Objective:** Verify Base64 input works
**Steps:**
1. Convert a PDF to Base64:
```powershell
$bytes = [System.IO.File]::ReadAllBytes("fake-pdf/one-page.pdf")
$base64 = [Convert]::ToBase64String($bytes)
Write-Output $base64
```
2. Open Swagger UI → `/api/pdf/validation/validate`
3. Click "Try it out"
4. Select **application/json** from dropdown
5. Paste into Request Body:
```json
{
"base64Pdf": "<paste-your-base64-here>"
}
```
6. Click "Execute"
**Expected Result:**
- **Status Code:** 200 OK
- Same response as Test 1.1
---
#### Test Case 1.3: Invalid Base64 String
**Objective:** Verify validation rejects malformed Base64
**Steps:**
1. Open Swagger UI → `/api/pdf/validation/validate`
2. Select **application/json**
3. Paste into Request Body:
```json
{
"base64Pdf": "invalid-base64!!!"
}
```
4. Click "Execute"
**Expected Result:**
- **Status Code:** 400 Bad Request
- **Error Message:** Contains "Base64"
---
#### Test Case 1.4: Empty File Upload
**Objective:** Verify empty files are rejected
**Steps:**
1. Create an empty file (`empty.pdf`)
2. Upload via multipart/form-data
**Expected Result:**
- **Status Code:** 400 Bad Request
- **Error Message:** Contains "cannot be empty"
---
#### Test Case 1.5: Large Multi-Page PDF
**Objective:** Verify handling of larger PDFs
**Steps:**
1. Upload `fake-pdf/multi-page.pdf` (49 KB)
**Expected Result:**
- **Status Code:** 200 OK
- **Response:**
```json
{
"pageCount": 3,
"fileSizeBytes": 49152,
"fileSizeMB": 0.05,
"pdfVersion": "1.7",
"hasAttachments": false,
"attachmentCount": 0
}
```
---
#### Test Case 1.6: PDF with Images
**Objective:** Verify image-heavy PDFs are processed
**Steps:**
1. Upload `fake-pdf/with-image.pdf` (256 KB)
**Expected Result:**
- **Status Code:** 200 OK
- **Response:**
```json
{
"pageCount": 1,
"fileSizeBytes": 262144,
"fileSizeMB": 0.25,
"pdfVersion": "1.6",
"hasAttachments": false,
"attachmentCount": 0
}
```
---
## Feature 3: PDF/A Validation
### Endpoint: `POST /api/pdf/validation/validate-pdfa`
#### Test Case 3.1: PDF/A Compliant Document (Multipart)
**Objective:** Verify PDF/A validation detects conformance
**Steps:**
1. Open Swagger UI → `/api/pdf/validation/validate-pdfa`
2. Select **multipart/form-data**
3. Upload a PDF/A-compliant PDF (if available)
4. Click "Execute"
**Expected Result (if PDF/A compliant):**
- **Status Code:** 200 OK
- **Response:**
```json
{
"isValid": true,
"pdfVersion": "1.7",
"pageCount": 1,
"fileSize": 12345,
"encrypted": false,
"pdfAVersion": "PDF/A-3b",
"pdfACompliant": true,
"errors": [],
"warnings": []
}
```
---
#### Test Case 3.2: Non-PDF/A Document
**Objective:** Verify regular PDFs are detected as non-compliant
**Steps:**
1. Upload `fake-pdf/one-page.pdf` (regular PDF, NOT PDF/A)
**Expected Result:**
- **Status Code:** 200 OK
- **Response:**
```json
{
"isValid": true,
"pdfVersion": "1.4",
"pageCount": 1,
"fileSize": 7168,
"encrypted": false,
"pdfAVersion": null,
"pdfACompliant": false,
"errors": [],
"warnings": ["Manual verification recommended: PDF/A compliance requires all fonts to be embedded"]
}
```
---
#### Test Case 3.3: Encrypted PDF
**Objective:** Verify encrypted PDFs are flagged
**Steps:**
1. Create or obtain a password-protected PDF
2. Upload via multipart/form-data
**Expected Result:**
- **Status Code:** 200 OK
- **Response:**
```json
{
"isValid": true,
"pdfVersion": "1.7",
"pageCount": 1,
"fileSize": 12345,
"encrypted": true,
"pdfAVersion": null,
"pdfACompliant": false,
"errors": ["Encrypted PDFs cannot be PDF/A compliant"],
"warnings": []
}
```
---
#### Test Case 3.4: Invalid Base64 (PDF/A Endpoint)
**Objective:** Verify validation works on PDF/A endpoint
**Steps:**
1. Select **application/json**
2. Paste:
```json
{
"base64Pdf": "not-base64!!!"
}
```
**Expected Result:**
- **Status Code:** 400 Bad Request
- **Error Message:** Contains "Base64"
---
#### Test Case 3.5: Empty Request
**Objective:** Verify both inputs missing is rejected
**Steps:**
1. Select **application/json**
2. Paste:
```json
{
"pdfBytes": null,
"base64Pdf": ""
}
```
**Expected Result:**
- **Status Code:** 400 Bad Request
- **Error Message:** "Either PdfBytes or Base64Pdf must be provided, but not both"
---
## Feature 2: Swiss QR Code Extraction
### Endpoint: `POST /api/swissqrcode/extract`
#### Test Case 2.1: PDF with Swiss QR Code
**Objective:** Extract Swiss QR Bill from PDF
**Steps:**
1. Open Swagger UI → `/api/swissqrcode/extract`
2. Select **multipart/form-data**
3. Upload a PDF containing Swiss QR Code on the **last page**
4. Click "Execute"
**Expected Result (if QR code present):**
- **Status Code:** 200 OK
- **Response:** Contains Swiss QR Bill details (IBAN, amount, creditor, debtor, reference)
---
#### Test Case 2.2: PDF without QR Code
**Objective:** Verify graceful handling when no QR code exists
**Steps:**
1. Upload `fake-pdf/one-page.pdf` (no QR code)
**Expected Result:**
- **Status Code:** 404 Not Found
- **Error Message:** "Swiss QR Code not found in PDF"
---
## Common Error Scenarios
### Test Case E1: Missing File in Multipart Request
**Steps:**
1. Any multipart endpoint
2. Don't select a file, click "Execute"
**Expected Result:**
- **Status Code:** 400 Bad Request
---
### Test Case E2: Both PdfBytes AND Base64Pdf Provided
**Steps:**
1. Attempt to send JSON with both fields populated
```json
{
"pdfBytes": [1,2,3],
"base64Pdf": "dGVzdA=="
}
```
**Expected Result:**
- **Status Code:** 400 Bad Request
- **Error Message:** "Either PdfBytes or Base64Pdf must be provided, but not both"
---
### Test Case E3: Corrupted PDF File
**Steps:**
1. Create a text file with `.pdf` extension containing "FAKE PDF CONTENT"
2. Upload it
**Expected Result:**
- **Status Code:** 500 Internal Server Error
- **Error Message:** Contains "PDF processing error"
---
## Test Coverage Summary
| Feature | Endpoint | Test Cases |
|---------|----------|------------|
| Basic PDF Validation | `POST /api/pdf/validation/validate` | 6 |
| PDF/A Validation | `POST /api/pdf/validation/validate-pdfa` | 5 |
| Swiss QR Code | `POST /api/swissqrcode/extract` | 2 |
| Error Handling | All endpoints | 3 |
| **TOTAL** | | **16 Manual Test Cases** |
---
## Notes
- All endpoints support **BOTH** `multipart/form-data` (file upload) AND `application/json` (Base64)
- FluentValidation runs before handlers (400 errors indicate validation failures)
- DevExpress evaluation warnings (DX1000/DX1001) are expected and can be ignored
- Test PDFs in `fake-pdf/` folder are small samples; use real-world PDFs for comprehensive testing
---
## Quick PowerShell Helpers
**Convert PDF to Base64:**
```powershell
$bytes = [System.IO.File]::ReadAllBytes("path\to\file.pdf")
$base64 = [Convert]::ToBase64String($bytes)
$base64 | Set-Clipboard # Copies to clipboard
```
**Create empty PDF for testing:**
```powershell
New-Item -Path "empty.pdf" -ItemType File -Force
```
**Check if file is valid PDF:**
```powershell
$header = Get-Content -Path "file.pdf" -TotalCount 1 -Encoding Byte
# Should start with: 0x25 0x50 0x44 0x46 (%PDF)
```

View File

@@ -0,0 +1,16 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug"
}
},
"DocumentServiceSettings": {
"TempFolderPath": "C:\\Temp\\DocumentService\\Dev",
"EnableDetailedLogging": true
},
"RedisSettings": {
"ConnectionString": "localhost:6379"
}
}

View File

@@ -0,0 +1,102 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Application": {
"LogDirectory": "E:\\LogFiles\\Digital Data\\DocumentService.API"
},
"SwaggerSettings": {
"EnableInProduction": true,
"Title": "DocumentService API",
"Version": "v1",
"Description": "PDF document processing service using DevExpress"
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
}
},
{
"Name": "SQLite",
"Args": {
"sqliteDbPath": "E:\\LogFiles\\Digital Data\\DocumentService.API\\logs.db",
"tableName": "Logs",
"storeTimestampInUtc": true
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
},
"DocumentServiceSettings": {
"TempFolderPath": "C:\\Temp\\DocumentService",
"TempFileRetentionHours": 24,
"MaxPdfSizeMB": 50,
"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": "DocumentService:",
"CacheExpirationMinutes": 60
},
"ApiKeySettings": {
"EnableValidation": true,
"Keys": {
"customer-a-key-12345": {
"TenantId": "customer-a",
"TenantName": "Customer A GmbH",
"IsActive": true
},
"customer-b-key-67890": {
"TenantId": "customer-b",
"TenantName": "Customer B AG",
"IsActive": true
}
}
},
"LuckyPennySoftLicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODE2MTI4MDAwIiwiaWF0IjoiMTc4NDYyNDU1NyIsImFjY291bnRfaWQiOiIwMTk4M2M1OWU0YjM3MjhlYmZkMzEwM2MyYTQ4NmU4NSIsImN1c3RvbWVyX2lkIjoiMDE5ODNjNTllNGIzNzI4ZWJmZDMxMDNjMmE0ODZlODUiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiJ9.IUUO926m9crYGYxMjjKD_n9BnUm-EDyjFIn0YmMUCo7C-QTwvB8WhXP8veTSFsBq-leIIDJ4jyl7Pgc_7ciwg1XhUSIs4mkQroEUaSFCGOxw7Pi41WM8MK5YFSaqLTYYXec9zxgiJbGzABbh3CHTSup3okGnVm_CMoPEs91l2c0A6N1JyZy74urd_tF0KGVKf0MOvzdlQIWLQ8o73S4pTv2N-F6UlzI0fdMtTHMLNNQyr0NdWdnuBk_jMBXO-gy5RE_oCRfMTTYRX2n3XLK6pTfXE0Ct338o9F5sH8Ph2lTXSu56cpdsfZOQZGqCH0LoFp1Dd7RJgIgNmBiTGfvDnA"
}