//using ClosedXML.Excel; //using DocumentFormat.OpenXml; //using DocumentFormat.OpenXml.Packaging; //using DocumentFormat.OpenXml.Spreadsheet; //using FastEndpoints; //using GB5Shared.DTO.Framework.Criteria; //using GB5Shared.DTO.Framework.Logging; //using GB5Shared.DTO.Framework.Login; //using GB5Shared.DTO.Report; //using GB5Shared.ExcelExport; //using GB5Shared.FastEndPoint; //using GB5Shared.QueryExecutor; //using Microsoft.AspNetCore.Http.Features; //using MMBLL.MMReports; //using MMDAL.DTO.MMHead; //using Newtonsoft.Json; //using System.Diagnostics; //using System.Reflection; //using System.Runtime.CompilerServices; //using System.Text; //using static GB5Shared.GB5Constant.Constant; //using static iText.IO.Image.Jpeg2000ImageData; //namespace MMSL.EndPoints.MMReports //{ // public class GetMMHeadRegisterWithDetail : Endpoint // { // private readonly IMMReportsBLL MMReportsBLL; // private readonly ILogger Logger; // private readonly IExcelExport ExcelExport; // private readonly IHttpContextAccessor _httpContextAccessor; // private readonly IQueryExecutor _queryExecutor; // public GetMMHeadRegisterWithDetail( // IMMReportsBLL MMReportsBLL, // ILogger Logger, // IExcelExport ExcelExport, // IHttpContextAccessor httpContextAccessor, // IQueryExecutor QueryExecutor) // { // this.MMReportsBLL = MMReportsBLL; // this.Logger = Logger; // this.ExcelExport = ExcelExport; // _httpContextAccessor = httpContextAccessor; // _queryExecutor = QueryExecutor; // } // public override void Configure() // { // Post("/MMReports/GetMMHeadRegisterWithDetail"); // AllowAnonymous(); // } // public record GetMMHeadRegisterWithDetailParameters( // [property: QueryParam] int Type, // [property: QueryParam] int FirstNumber, // [property: QueryParam] int MaxResult, // [property: QueryParam] int IsStream, // 0 = non-stream, 1 = stream // [property: QueryParam] string? Format, // "json" or "excel" "csv" // [property: QueryParam] int ResponseType, // [property: FromHeader] string Login, // [property: FromBody] CriteriaDTO CriteriaDTO // ); // public override async Task HandleAsync(GetMMHeadRegisterWithDetailParameters req, CancellationToken cancellationToken) // { // LoginDTO? loginDTO = null; // try // { // loginDTO = JsonConvert.DeserializeObject(req.Login); // if (loginDTO == null) // { // return await GB5Shared.ResponseStandard.Response.CreateExceptionError( // new Exception("LoginDTO is null"), // CacheKeyLevel.NOT_REQUIRED, // null!, // "LoginDTO is null", // 400 // ); // } // } // catch (Exception ex) // { // return await GB5Shared.ResponseStandard.Response.CreateExceptionError( // ex, // CacheKeyLevel.NOT_REQUIRED, // loginDTO!, // ex.Message, // 500 // ); // } // // 2️⃣ Create a single ReportCallingDTO instance // var reportCalling = new ReportCallingDTO // { // ReportViewId = req.Type, // map appropriately // ReportTitle = "MM Head Register", // ReportUri = "/MMReports/GetMMHeadRegisterWithDetail" // }; // try // { // HttpContext.Features.Get()?.DisableBuffering(); // var parameters = new Dictionary // { // { "OUId", loginDTO.WorkOUId }, // { "UserId", loginDTO.UserId }, // { "CriteriaJson", JsonConvert.SerializeObject(req.CriteriaDTO) } // }; // if (req.ResponseType == 0) // { // if (req.IsStream == 1) // { // var dataStream = MMReportsBLL.GetMMHeadRegisterWithDetailStream( // req.Type, req.FirstNumber, req.MaxResult, req.CriteriaDTO, loginDTO, cancellationToken // ); // switch (req.Format?.ToLower()) // { // case "excel": // await ProcessStreamExcelFormat(dataStream, loginDTO, reportCalling, cancellationToken); // break; // case "csv": // await ProcessStreamCsvFormat(dataStream, loginDTO, reportCalling, cancellationToken); // break; // default: // await ProcessStreamJsonFormat(dataStream, loginDTO, cancellationToken); // break; // } // return null; // } // else // { // var sw = Stopwatch.StartNew(); // // Non-streaming case // var data = await MMReportsBLL.GetMMHeadRegisterWithDetail(req.Type, req.FirstNumber, req.MaxResult, req.IsStream, req.CriteriaDTO, loginDTO, false, false, cancellationToken); // var reportStandard = await ExcelExport.BuildReportStandard(reportCalling, loginDTO, cancellationToken); // switch (req.Format?.ToLower()) // { // case "excel": // await ProcessExcelFormat(data, cancellationToken, loginDTO, reportCalling, reportStandard); // break; // case "csv": // await ProcessCsvFormat(data, cancellationToken, loginDTO, reportCalling, reportStandard); // break; // default: // await ProcessJsonFormat(data, loginDTO, cancellationToken); // break; // } // return null; // } // } // else // { // var raw = await MMReportsBLL.MMHeadRegisterWithDetail( // req.Type, // req.FirstNumber, // req.MaxResult, // req.IsStream, // req.CriteriaDTO, // loginDTO, // false, // false, // cancellationToken); // if (raw == null) // { // await SendAsync(new { Message = "No data available" }, 200, cancellation: cancellationToken); // return null!; // } // await SendAsync(raw, 200, cancellation: cancellationToken); // return null!; // } // } // catch (Exception ex) // { // Logger.LogError(ex, "Error in GetMMHeadRegisterWithDetail"); // HttpContext.Response.StatusCode = 500; // return new { Message = ex.Message }; // } // } // private async Task ProcessJsonFormat(List data, LoginDTO loginDTO, CancellationToken cancellationToken) // { // HttpContext.Response.ContentType = "application/json"; // var sw = Stopwatch.StartNew(); // ✅ Start timer // var response = await GB5Shared.ResponseStandard.Response.CreateSuccessResponse( // data, // CacheKeyLevel.NOT_REQUIRED, // loginDTO // ); // var settings = new JsonSerializerSettings // { // DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ", // Formatting = Formatting.None, // NullValueHandling = NullValueHandling.Ignore // }; // string oldjson = JsonConvert.SerializeObject(response, settings); // string json = JsonConvert.SerializeObject(data); // var result = await GB5Shared.ResponseStandard.Response.GB4CreateSuccessResponseGZipCompress(json, CacheKeyLevel.NOT_REQUIRED, loginDTO); // string Responce = JsonConvert.SerializeObject(result); // await HttpContext.Response.WriteAsync(Responce, cancellationToken); // sw.Stop(); // Logger.LogInformation( // "MMHeadRegister NON-STREAM JSON executed in {Elapsed} ms, Rows={Count}", // sw.ElapsedMilliseconds, data?.Count ?? 0 // ); // } // private async Task ProcessStreamJsonFormat(IAsyncEnumerable dataStream, LoginDTO loginDTO, CancellationToken cancellationToken) // { // HttpContext.Response.ContentType = "application/json"; // await HttpContext.Response.StartAsync(cancellationToken); // await HttpContext.Response.WriteAsync("[", cancellationToken); // bool first = true; // var sw = Stopwatch.StartNew(); // ✅ Start timer // int rowCount = 0; // await foreach (var item in dataStream.WithCancellation(cancellationToken)) // { // if (!first) await HttpContext.Response.WriteAsync(",", cancellationToken); // string json = JsonConvert.SerializeObject(item); // await HttpContext.Response.WriteAsync(json, cancellationToken); // first = false; // rowCount++; // ✅ Count rows // } // sw.Stop(); // Logger.LogInformation( // "MMHeadRegister STREAM JSON executed in {Elapsed} ms, Rows={Count}", // sw.ElapsedMilliseconds, rowCount // ); // await HttpContext.Response.WriteAsync("]", cancellationToken); // } // private async Task ProcessExcelFormat(List data, CancellationToken cancellationToken, LoginDTO loginDTO, ReportCallingDTO reportCalling, ReportStandardDTO reportStandard) // { // var sw = Stopwatch.StartNew(); // // 1️⃣ Get headers from ReportCallingDTO // var headers = (await ExcelExport.GetReportViewHeader( // reportCalling.ReportViewId, // reportCalling, // loginDTO // )).ToList(); // // 2️⃣ Export to Excel // var excelBytes = await ExcelExport.NonStreamExcelExport( // data, // "MMHeadRegister", // headers, // reportStandard, // loginDTO, // cancellationToken // ); // // 3️⃣ Set HTTP response headers // if (!HttpContext.Response.Headers.ContainsKey("Content-Disposition")) // { // HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"MMHeadRegister.xlsx\""); // } // // 4️⃣ Write Excel to response // await HttpContext.Response.Body.WriteAsync(excelBytes, 0, excelBytes.Length, cancellationToken); // sw.Stop(); // Logger.LogInformation( // "MMHeadRegister NON-STREAM EXCEL executed in {Elapsed} ms, Rows={Count}", // sw.ElapsedMilliseconds, data?.Count ?? 0 // ); // } // private async Task ProcessStreamExcelFormat(IAsyncEnumerable dataStream, LoginDTO loginDTO, ReportCallingDTO reportCalling, CancellationToken cancellationToken) // { // HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // HttpContext.Response.Headers["Content-Disposition"] = "attachment; filename=\"MMHeadRegister.xlsx\""; // HttpContext.Features.Get()?.DisableBuffering(); // var sw = Stopwatch.StartNew(); // try // { // var headers = (await ExcelExport.GetReportViewHeader(reportCalling.ReportViewId, reportCalling, loginDTO)).ToList(); // var reportStandard = await ExcelExport.BuildReportStandard(reportCalling, loginDTO, cancellationToken); // // 1️⃣ Use a MemoryStream first // using var ms = new MemoryStream(); // // 2️⃣ Call library function, write into MemoryStream // await ExcelExport.StreamExcelExport( // dataStream, // "MMHeadRegister", // headers, // reportStandard, // loginDTO, // ms, // cancellationToken // ); // ms.Position = 0; // reset position to read from start // // 3️⃣ Copy MemoryStream to HTTP Response // await ms.CopyToAsync(HttpContext.Response.Body, cancellationToken); // sw.Stop(); // Logger.LogInformation("STREAM EXCEL executed in {Elapsed} ms", sw.ElapsedMilliseconds); // await HttpContext.Response.Body.FlushAsync(cancellationToken); // } // catch (Exception ex) // { // Logger.LogError(ex, "Error during STREAM EXCEL export"); // HttpContext.Response.StatusCode = 500; // await HttpContext.Response.WriteAsync($"Error generating Excel: {ex.Message}", cancellationToken); // } // } // private async Task ProcessCsvFormat(List data, CancellationToken cancellationToken, LoginDTO loginDTO, ReportCallingDTO reportCalling, ReportStandardDTO reportStandard) // { // var sw = Stopwatch.StartNew(); // // 1️⃣ Get headers from ReportCallingDTO // var headers = (await ExcelExport.GetReportViewHeader( // reportCalling.ReportViewId, // reportCalling, // loginDTO // )).ToList(); // // 2️⃣ Export to CSV // var csvBytes = await ExcelExport.NonStreamCSVExport( // data, // headers, // reportStandard, // loginDTO // ); // // 3️⃣ Set HTTP response headers // if (!HttpContext.Response.Headers.ContainsKey("Content-Disposition")) // { // HttpContext.Response.ContentType = "text/csv"; // HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"MMHeadRegister.csv\""); // } // // 4️⃣ Write CSV to response // await HttpContext.Response.Body.WriteAsync(csvBytes, 0, csvBytes.Length, cancellationToken); // sw.Stop(); // Logger.LogInformation( // "MMHeadRegister CSV executed in {Elapsed} ms, Rows={Count}", // sw.ElapsedMilliseconds, data?.Count ?? 0 // ); // } // private async Task ProcessStreamCsvFormat(IAsyncEnumerable dataStream, LoginDTO loginDTO, ReportCallingDTO reportCalling, CancellationToken cancellationToken) // { // HttpContext.Response.ContentType = "text/csv"; // HttpContext.Response.Headers["Content-Disposition"] = "attachment; filename=\"MMHeadRegister.csv\""; // HttpContext.Features.Get()?.DisableBuffering(); // var sw = Stopwatch.StartNew(); // try // { // // 1️⃣ Get headers dynamically // var headers = (await ExcelExport.GetReportViewHeader(reportCalling.ReportViewId, reportCalling, loginDTO)) // .ToList(); // // 2️⃣ Build report standard // var reportStandard = await ExcelExport.BuildReportStandard(reportCalling, loginDTO, cancellationToken); // // 3️⃣ Stream CSV to Response.Body using your helper // await ExcelExport.StreamCsvExport( // dataStream, // headers, // reportStandard, // loginDTO, // HttpContext.Response.Body, // cancellationToken // ); // sw.Stop(); // Logger.LogInformation("STREAM CSV executed in {Elapsed} ms", sw.ElapsedMilliseconds); // await HttpContext.Response.Body.FlushAsync(cancellationToken); // } // catch (Exception ex) // { // Logger.LogError(ex, "Error during STREAM CSV export"); // HttpContext.Response.StatusCode = 500; // await HttpContext.Response.WriteAsync($"Error generating CSV: {ex.Message}", cancellationToken); // } // } // } //}