feat: Add raw parameter to SwissQrCodeController endpoints

- Add 'raw' query parameter to both ExtractFromFile and ExtractFromBase64 methods
- Returns raw QR text lines when raw=true, parsed Bill object when raw=false (default)
- Remove obsolete 'references' parameter (not part of QR extraction logic)
- Add XML documentation for raw parameter
- Update ExceptionHandlingMiddleware to handle BadRequestException
This commit is contained in:
2026-07-16 15:48:09 +02:00
parent 1a89887056
commit a315fbf890
2 changed files with 27 additions and 57 deletions

View File

@@ -17,9 +17,9 @@ public class SwissQrCodeController(IMediator Mediator) : ControllerBase
/// Extracts Swiss QR Code from the last page of a PDF document (multipart/form-data) /// Extracts Swiss QR Code from the last page of a PDF document (multipart/form-data)
/// </summary> /// </summary>
/// <param name="file">PDF file containing Swiss QR Code</param> /// <param name="file">PDF file containing Swiss QR Code</param>
/// <param name="references">Optional references (comma-separated)</param> /// <param name="raw">If true, returns raw QR code text lines as string array; if false, returns parsed Bill object (default: false)</param>
/// <param name="cancellationToken">Cancellation token</param> /// <param name="cancellationToken">Cancellation token</param>
/// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns> /// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.) or raw text lines based on 'raw' parameter</returns>
/// <response code="200">Swiss QR Code extracted successfully</response> /// <response code="200">Swiss QR Code extracted successfully</response>
/// <response code="400">Invalid PDF or file format</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="404">No Swiss QR Code found on the last page</response>
@@ -32,46 +32,39 @@ public class SwissQrCodeController(IMediator Mediator) : ControllerBase
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractFromFile( public async Task<IActionResult> ExtractFromFile(
IFormFile file, IFormFile file,
[FromForm] string? references, [FromQuery] bool raw = false,
CancellationToken cancellationToken) CancellationToken cancellationToken = default)
{ {
if (file == null || file.Length == 0) if (file.Length == 0)
{
return BadRequest(new ProblemDetails return BadRequest(new ProblemDetails
{ {
Title = "Invalid file", Title = "Invalid file",
Detail = "File is required and cannot be empty", Detail = "File is required and cannot be empty",
Status = StatusCodes.Status400BadRequest Status = StatusCodes.Status400BadRequest
}); });
}
// Convert IFormFile to byte array // Convert IFormFile to byte array
using var memoryStream = new MemoryStream(); using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream, cancellationToken); await file.CopyToAsync(memoryStream, cancellationToken);
byte[] pdfBytes = memoryStream.ToArray(); 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 // Direct pass-through to MediatR
var query = new ExtractSwissQrCodeQuery var query = new ExtractSwissQrCodeQuery
{ {
PdfBytes = pdfBytes, PdfBytes = pdfBytes
References = referencesList
}; };
var result = await Mediator.Send(query, cancellationToken); var result = await Mediator.Send(query, cancellationToken);
return Ok(result); return Ok(raw ? result.RawLines : result.Bill);
} }
/// <summary> /// <summary>
/// Extracts Swiss QR Code from the last page of a PDF document (Base64 JSON) /// Extracts Swiss QR Code from the last page of a PDF document (Base64 JSON)
/// </summary> /// </summary>
/// <param name="query">References array + PDF as Base64 string</param> /// <param name="query">References array + PDF as Base64 string</param>
/// <param name="raw">If true, returns raw QR code text lines as string array; if false, returns parsed Bill object (default: false)</param>
/// <param name="cancellationToken">Cancellation token</param> /// <param name="cancellationToken">Cancellation token</param>
/// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns> /// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.) or raw text lines based on 'raw' parameter</returns>
/// <response code="200">Swiss QR Code extracted successfully</response> /// <response code="200">Swiss QR Code extracted successfully</response>
/// <response code="400">Invalid PDF or Base64 format</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="404">No Swiss QR Code found on the last page</response>
@@ -84,11 +77,12 @@ public class SwissQrCodeController(IMediator Mediator) : ControllerBase
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ExtractFromBase64( public async Task<IActionResult> ExtractFromBase64(
[FromBody] ExtractSwissQrCodeQuery query, [FromBody] ExtractSwissQrCodeQuery query,
CancellationToken cancellationToken) [FromQuery] bool raw = false,
CancellationToken cancellationToken = default)
{ {
// Direct pass-through to MediatR // Direct pass-through to MediatR
var result = await Mediator.Send(query, cancellationToken); var result = await Mediator.Send(query, cancellationToken);
return Ok(result); return Ok(raw ? result.RawLines : result.Bill);
} }
} }

View File

@@ -11,21 +11,16 @@ namespace DocumentOperator.API.Middleware;
/// Central exception handling middleware /// Central exception handling middleware
/// Maps exceptions to HTTP status codes and RFC 7807 Problem Details /// Maps exceptions to HTTP status codes and RFC 7807 Problem Details
/// </summary> /// </summary>
public class ExceptionHandlingMiddleware /// <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 readonly RequestDelegate _next; private static readonly JsonSerializerOptions ProbDetailsJsonOpt = new()
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="logger">The logger instance for exception logging.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{ {
_next = next; PropertyNamingPolicy = JsonNamingPolicy.CamelCase
_logger = logger; };
}
/// <summary> /// <summary>
/// Invokes the middleware to handle incoming HTTP requests and catch exceptions. /// Invokes the middleware to handle incoming HTTP requests and catch exceptions.
@@ -35,11 +30,10 @@ public class ExceptionHandlingMiddleware
{ {
try try
{ {
await _next(context); await Next(context);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Unhandled exception: {ExceptionMessage}", ex.Message);
await HandleExceptionAsync(context, ex); await HandleExceptionAsync(context, ex);
} }
} }
@@ -51,12 +45,7 @@ public class ExceptionHandlingMiddleware
context.Response.StatusCode = (int)statusCode; context.Response.StatusCode = (int)statusCode;
context.Response.ContentType = "application/problem+json"; context.Response.ContentType = "application/problem+json";
var options = new JsonSerializerOptions await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails, ProbDetailsJsonOpt));
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails, options));
} }
private static (HttpStatusCode StatusCode, ProblemDetails ProblemDetails) MapExceptionToProblemDetails( private static (HttpStatusCode StatusCode, ProblemDetails ProblemDetails) MapExceptionToProblemDetails(
@@ -78,15 +67,15 @@ public class ExceptionHandlingMiddleware
} }
), ),
// Domain Validation Exception (400 Bad Request) // Not Found Exception (404 Not Found)
DomainValidationException domainEx => ( BadRequestException badReqEx => (
HttpStatusCode.BadRequest, HttpStatusCode.BadRequest,
new ProblemDetails new ProblemDetails
{ {
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1", Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4",
Title = "Domain Validation Error", Title = "Bad Request",
Status = (int)HttpStatusCode.BadRequest, Status = (int)HttpStatusCode.BadRequest,
Detail = domainEx.Message, Detail = badReqEx.Message,
Instance = context.Request.Path Instance = context.Request.Path
} }
), ),
@@ -117,19 +106,6 @@ public class ExceptionHandlingMiddleware
} }
), ),
// PDF Processing Exception (500 Internal Server Error)
PdfProcessingException pdfEx => (
HttpStatusCode.InternalServerError,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.6.1",
Title = "PDF Processing Error",
Status = (int)HttpStatusCode.InternalServerError,
Detail = pdfEx.Message,
Instance = context.Request.Path
}
),
// Generic Exception (500 Internal Server Error) // Generic Exception (500 Internal Server Error)
_ => ( _ => (
HttpStatusCode.InternalServerError, HttpStatusCode.InternalServerError,