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)
/// </summary>
/// <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>
/// <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="400">Invalid PDF or file format</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)]
public async Task<IActionResult> ExtractFromFile(
IFormFile file,
[FromForm] string? references,
CancellationToken cancellationToken)
[FromQuery] bool raw = false,
CancellationToken cancellationToken = default)
{
if (file == null || file.Length == 0)
{
if (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
PdfBytes = pdfBytes
};
var result = await Mediator.Send(query, cancellationToken);
return Ok(result);
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="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>
/// <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="400">Invalid PDF or Base64 format</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)]
public async Task<IActionResult> ExtractFromBase64(
[FromBody] ExtractSwissQrCodeQuery query,
CancellationToken cancellationToken)
[FromQuery] bool raw = false,
CancellationToken cancellationToken = default)
{
// Direct pass-through to MediatR
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
/// Maps exceptions to HTTP status codes and RFC 7807 Problem Details
/// </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 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)
private static readonly JsonSerializerOptions ProbDetailsJsonOpt = new()
{
_next = next;
_logger = logger;
}
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>
/// Invokes the middleware to handle incoming HTTP requests and catch exceptions.
@@ -35,11 +30,10 @@ public class ExceptionHandlingMiddleware
{
try
{
await _next(context);
await Next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception: {ExceptionMessage}", ex.Message);
await HandleExceptionAsync(context, ex);
}
}
@@ -51,12 +45,7 @@ public class ExceptionHandlingMiddleware
context.Response.StatusCode = (int)statusCode;
context.Response.ContentType = "application/problem+json";
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails, options));
await context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails, ProbDetailsJsonOpt));
}
private static (HttpStatusCode StatusCode, ProblemDetails ProblemDetails) MapExceptionToProblemDetails(
@@ -78,15 +67,15 @@ public class ExceptionHandlingMiddleware
}
),
// Domain Validation Exception (400 Bad Request)
DomainValidationException domainEx => (
// Not Found Exception (404 Not Found)
BadRequestException badReqEx => (
HttpStatusCode.BadRequest,
new ProblemDetails
{
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
Title = "Domain Validation Error",
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.4",
Title = "Bad Request",
Status = (int)HttpStatusCode.BadRequest,
Detail = domainEx.Message,
Detail = badReqEx.Message,
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)
_ => (
HttpStatusCode.InternalServerError,