refactor: Migrate from Minimal API to Controller-based API
Architecture decision change:
- Previous: Minimal API (DocumentEndpoints.cs) - WRONG approach
- Required: Controller-based API (per CONTROLLER_ENDPOINTS.md)
New controllers:
- PdfValidationController:
- POST /api/pdf/validation/validate
- Accepts BOTH IFormFile (multipart) AND Base64 JSON
- Returns PdfValidationResult
- SwissQrCodeController:
- POST /api/swissqrcode/extract
- Accepts BOTH IFormFile (multipart) AND Base64 JSON
- Returns SwissQrCodeExtractionResult
Controller best practices:
- Primary constructors (C# 12)
- Thin controllers (pass request to MediatR directly)
- No manual mapping (AutoMapper handles domain -> DTO)
- XML documentation for Swagger
- [ProducesResponseType] attributes
Deleted:
- API/Endpoints/v1/DocumentEndpoints.cs (Minimal API)
- ROADMAP.md (conflicting guidance with CONTROLLER_ENDPOINTS.md)
Result: Controller-based API, dual input support (multipart + JSON)
This commit is contained in:
79
DocumentOperator.API/Controllers/PdfValidationController.cs
Normal file
79
DocumentOperator.API/Controllers/PdfValidationController.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Application.ValidatePdf.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DocumentOperator.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
|
||||
});
|
||||
}
|
||||
|
||||
// Convert IFormFile to byte array
|
||||
using var memoryStream = new MemoryStream();
|
||||
await file.CopyToAsync(memoryStream, cancellationToken);
|
||||
byte[] pdfBytes = memoryStream.ToArray();
|
||||
|
||||
// Direct pass-through to MediatR
|
||||
var query = new ValidatePdfQuery { PdfBytes = pdfBytes };
|
||||
var result = await Mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a PDF document and returns metadata (Base64 JSON)
|
||||
/// </summary>
|
||||
/// <param name="query">PDF as Base64 string</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] ValidatePdfQuery query,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Direct pass-through to MediatR
|
||||
var result = await Mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
94
DocumentOperator.API/Controllers/SwissQrCodeController.cs
Normal file
94
DocumentOperator.API/Controllers/SwissQrCodeController.cs
Normal file
@@ -0,0 +1,94 @@
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Application.SwissQrCode.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DocumentOperator.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="references">Optional references (comma-separated)</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,
|
||||
[FromForm] string? references,
|
||||
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
|
||||
});
|
||||
}
|
||||
|
||||
// Convert IFormFile to byte array
|
||||
using var memoryStream = new MemoryStream();
|
||||
await file.CopyToAsync(memoryStream, cancellationToken);
|
||||
byte[] pdfBytes = memoryStream.ToArray();
|
||||
|
||||
// Parse references (comma-separated or empty)
|
||||
var referencesList = string.IsNullOrWhiteSpace(references)
|
||||
? new List<string>()
|
||||
: references.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
||||
|
||||
// Direct pass-through to MediatR
|
||||
var query = new ExtractSwissQrCodeQuery
|
||||
{
|
||||
PdfBytes = pdfBytes,
|
||||
References = referencesList
|
||||
};
|
||||
var result = await Mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts Swiss QR Code from the last page of a PDF document (Base64 JSON)
|
||||
/// </summary>
|
||||
/// <param name="query">References array + PDF as Base64 string</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] ExtractSwissQrCodeQuery query,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Direct pass-through to MediatR
|
||||
var result = await Mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Application.Features.Documents.ExtractSwissQrCode;
|
||||
using DocumentOperator.Application.Features.Documents.ValidatePdf;
|
||||
using DocumentOperator.Domain.Models.ValueObjects;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DocumentOperator.API.Endpoints.v1;
|
||||
|
||||
/// <summary>
|
||||
/// Document endpoints (Minimal API)
|
||||
/// </summary>
|
||||
public static class DocumentEndpoints
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps all document-related endpoints
|
||||
/// </summary>
|
||||
public static void MapDocumentEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/api/v1/documents")
|
||||
.WithTags("Documents");
|
||||
|
||||
// POST /api/v1/documents/validate
|
||||
group.MapPost("/validate", ValidatePdf)
|
||||
.WithName("ValidatePdf")
|
||||
.WithSummary("Validates a PDF document and returns metadata")
|
||||
.WithDescription("Validates the PDF format and extracts metadata (page count, file size, PDF version, attachments)")
|
||||
.Produces<ValidatePdfResponse>(StatusCodes.Status200OK)
|
||||
.Produces<ProblemDetails>(StatusCodes.Status400BadRequest)
|
||||
.Produces<ProblemDetails>(StatusCodes.Status500InternalServerError);
|
||||
|
||||
// POST /api/v1/documents/extract-swiss-qr-code
|
||||
group.MapPost("/extract-swiss-qr-code", ExtractSwissQrCode)
|
||||
.WithName("ExtractSwissQrCode")
|
||||
.WithSummary("Extracts Swiss QR Code from the last page of a PDF document")
|
||||
.WithDescription(@"Extracts and parses a Swiss QR Code (Swiss QR Bill Standard 2.0) from the last page of a PDF document.
|
||||
|
||||
**Requirements:**
|
||||
- PDF must contain a valid Swiss QR Code on the last page
|
||||
- QR Code must conform to Swiss QR Bill Standard 2.0
|
||||
- References array is required (can be empty)
|
||||
|
||||
**Returns:**
|
||||
- All QR code fields (IBAN, amount, creditor, debtor, reference, etc.)
|
||||
- References array (passed through from request)
|
||||
|
||||
**Use Case:**
|
||||
Extract payment information from Swiss QR invoices for automated processing.")
|
||||
.Produces<ExtractSwissQrCodeResponse>(StatusCodes.Status200OK)
|
||||
.Produces<ProblemDetails>(StatusCodes.Status400BadRequest)
|
||||
.Produces<ProblemDetails>(StatusCodes.Status404NotFound)
|
||||
.Produces<ProblemDetails>(StatusCodes.Status500InternalServerError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a PDF document and returns metadata
|
||||
/// </summary>
|
||||
/// <param name="request">PDF as Base64 string</param>
|
||||
/// <param name="mediator">MediatR instance</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>PDF metadata (page count, file size, etc.)</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>
|
||||
private static async Task<IResult> ValidatePdf(
|
||||
ValidatePdfRequest request,
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// DTO → Query (Value Objects erstellen - kann DomainValidationException werfen!)
|
||||
var query = new ValidatePdfQuery(
|
||||
Base64String.Create(request.Base64Pdf)
|
||||
);
|
||||
|
||||
// MediatR Handler aufrufen (ValidationBehavior → Handler)
|
||||
var metadata = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// PdfMetadata → Response DTO
|
||||
var response = new ValidatePdfResponse(
|
||||
metadata.PageCount,
|
||||
metadata.FileSizeBytes,
|
||||
metadata.FileSizeMB,
|
||||
metadata.PdfVersion,
|
||||
metadata.HasAttachments,
|
||||
metadata.AttachmentCount
|
||||
);
|
||||
|
||||
return Results.Ok(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts Swiss QR Code from the last page of a PDF document
|
||||
/// </summary>
|
||||
/// <param name="request">References array + PDF as Base64 string</param>
|
||||
/// <param name="mediator">MediatR instance</param>
|
||||
/// <param name="cancellationToken">Cancellation token</param>
|
||||
/// <returns>References (passed through) + Swiss QR Code data</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>
|
||||
private static async Task<IResult> ExtractSwissQrCode(
|
||||
ExtractSwissQrCodeRequest request,
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// DTO → Query (Value Objects erstellen)
|
||||
var query = new ExtractSwissQrCodeQuery(
|
||||
References: request.References,
|
||||
PdfContent: Base64String.Create(request.Base64Pdf)
|
||||
);
|
||||
|
||||
// MediatR Handler aufrufen
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// Map Domain Value Object → DTO
|
||||
var response = new ExtractSwissQrCodeResponse(
|
||||
References: result.References,
|
||||
QrCodeData: MapQrCodeDataToDto(result.QrCodeData)
|
||||
);
|
||||
|
||||
return Results.Ok(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps SwissQrCodeData domain value object to DTO
|
||||
/// </summary>
|
||||
private static SwissQrCodeDataDto MapQrCodeDataToDto(Domain.ValueObjects.SwissQrCodeData qrCodeData)
|
||||
{
|
||||
return new SwissQrCodeDataDto(
|
||||
QrType: qrCodeData.QrType,
|
||||
Version: qrCodeData.Version,
|
||||
CodingType: qrCodeData.CodingType,
|
||||
Iban: qrCodeData.Iban,
|
||||
Creditor: MapAddressToDto(qrCodeData.Creditor),
|
||||
UltimateCreditor: qrCodeData.UltimateCreditor != null ? MapAddressToDto(qrCodeData.UltimateCreditor) : null,
|
||||
Amount: qrCodeData.Amount,
|
||||
Currency: qrCodeData.Currency,
|
||||
UltimateDebtor: qrCodeData.UltimateDebtor != null ? MapAddressToDto(qrCodeData.UltimateDebtor) : null,
|
||||
ReferenceType: qrCodeData.ReferenceType,
|
||||
Reference: qrCodeData.Reference,
|
||||
UnstructuredMessage: qrCodeData.UnstructuredMessage,
|
||||
BillInformation: qrCodeData.BillInformation,
|
||||
AlternativeProcedureParameters: qrCodeData.AlternativeProcedureParameters
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps AddressData domain value object to DTO
|
||||
/// </summary>
|
||||
private static AddressDataDto MapAddressToDto(Domain.ValueObjects.AddressData address)
|
||||
{
|
||||
return new AddressDataDto(
|
||||
AddressType: address.AddressType,
|
||||
Name: address.Name,
|
||||
Street: address.Street,
|
||||
BuildingNumber: address.BuildingNumber,
|
||||
AddressLine1: address.AddressLine1,
|
||||
AddressLine2: address.AddressLine2,
|
||||
PostalCode: address.PostalCode,
|
||||
City: address.City,
|
||||
Country: address.Country
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user