using FastEndpoints; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using GB5Shared.FastEndPoint; using PayRollBLL.SAP; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using static GB5Shared.GB5Constant.Constant; namespace PayRollSL.EndPoints.SAP { /// /// GET /SAP/DownloadITDeclarationJson /// Streams a JSON file download for a single SAP infotype. /// Requires Infotype parameter (580–586). /// public class DownloadITDeclarationJson : BaseEndpoint> { private readonly IITDeclarationSapBLL _bll; public DownloadITDeclarationJson(IITDeclarationSapBLL bll) => _bll = bll; public override void Configure() { Get("/SAP/DownloadITDeclarationJson"); AllowAnonymous(); } public record DownloadITDeclarationJsonParameters( [property: FromHeader] string Login, [property: QueryParam] int DeclarationId, [property: QueryParam] int EmployeeId, [property: QueryParam] int PeriodId, [property: QueryParam] int Infotype, // required: 580–586 [property: QueryParam] string? Date, [property: QueryParam] string? Remarks ); protected override string? GetCacheKey(DownloadITDeclarationJsonParameters req, LoginDTO login) => null; protected override async Task> ExecuteAsync( DownloadITDeclarationJsonParameters req, LoginDTO login, CancellationToken ct) { try { if (req.Infotype == 0) throw new ArgumentException("Infotype must be specified (580–586) for download."); string date = string.IsNullOrWhiteSpace(req.Date) ? DateTime.Today.ToString("dd.MM.yyyy") : req.Date; var payloads = await _bll.GenerateSapPayloadsAsync( req.DeclarationId, req.EmployeeId, req.PeriodId, req.Infotype, date, req.Remarks ?? string.Empty, login, ct); string json = payloads.TryGetValue(req.Infotype, out var j) ? j : "{}"; string fileName = $"ITDeclaration_{req.Infotype}_{DateTime.Today:yyyyMMdd}.json"; using var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); await Send.StreamAsync( ms, contentType: "application/json", fileName: fileName, cancellation: ct); return default!; // response already sent via stream } catch (Exception ex) { return await GB5Shared.ResponseStandard.Response .CreateExceptionError(ex, CacheKeyLevel.NOT_REQUIRED, login, ex.Message, 500); } } } }