using System.Text; using AccountsBLL.ETDS; using FastEndpoints; using GB5Shared.DTO.Framework.Criteria; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using Newtonsoft.Json; namespace AccountsSL.EndPoints.TDSCategory { // Faithful port of GB4 TDSCategory.svc's Form24Q123 (EtdsDAL.GetTDSReturnForm) — builds the // NSDL/TIN e-TDS quarterly-return flat file for a single TDSReturnId. GB4 wrote the file to // local disk; per explicit direction, GB5 streams the generated content back as an HTTP // download instead, so this is a plain Endpoint (not BaseEndpoint) following the same // file-download convention as DMS/DMSSL/EndPoints/ESSDocument/DownloadDocument.cs. public class Form24Q123 : Endpoint { private readonly IEtdsBLL _etdsBLL; public Form24Q123(IEtdsBLL etdsBLL) { _etdsBLL = etdsBLL; } public record Form24Q123Parameters( [property: FromHeader] string Login, [property: FromBody] CriteriaDTO CriteriaDTO ); public override void Configure() { Post("/TDSCategory/ETDS/Form24Q123"); AllowAnonymous(); } public override async Task HandleAsync(Form24Q123Parameters req, CancellationToken ct) { LoginDTO? loginDTO; try { loginDTO = JsonConvert.DeserializeObject(req.Login); if (loginDTO is null) throw new Exception("Null LoginDTO"); } catch { await WriteErrorAsync(401, "Login token is missing or invalid. Please sign in again.", ct); return; } try { var (fileName, content) = await _etdsBLL.GetTDSReturnForm(req.CriteriaDTO, loginDTO).ConfigureAwait(false); var bytes = Encoding.UTF8.GetBytes(content); using var ms = new MemoryStream(bytes); HttpContext.Response.StatusCode = 200; HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.Headers.Append( "Content-Disposition", $"attachment; filename=\"{Uri.EscapeDataString(fileName)}\""); await ms.CopyToAsync(HttpContext.Response.Body, ct).ConfigureAwait(false); } catch (Exception ex) { await WriteErrorAsync(500, ex.Message, ct); } } private Task WriteErrorAsync(int httpStatus, string message, CancellationToken ct) { var body = new ResponseStandardDTO { Status = GB5Shared.DTO.Framework.Enum.FrameworkEnumDTO.ResponseStatus.Failed, Body = message, ErrorBody = message }; HttpContext.Response.StatusCode = httpStatus; HttpContext.Response.ContentType = "application/json"; return HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(body), ct); } } }