diff --git a/BLL/Integracion_DGA/BusinessLogic.cs b/BLL/Integracion_DGA/BusinessLogic.cs index 10e5d83..2f618ee 100644 --- a/BLL/Integracion_DGA/BusinessLogic.cs +++ b/BLL/Integracion_DGA/BusinessLogic.cs @@ -58,80 +58,107 @@ namespace BLL.Integracion_DGA responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers); TagviewsResponse tagviews = JsonSerializer.Deserialize(responseData, options); - List listTagsID = tagviews.Columns.Select(x => x.Uid).ToList(); - - HistoricRequest historicRequest = new HistoricRequest + List listTagsID = new List(); + foreach (Column tag in tagviews.Columns) { - DataSource = NexusApiUrl.DataSource, - Resolution = NexusApiUrl.Resolution, - Uids = listTagsID, - StartTs = dateStart.ToUnixTimeSeconds(), - EndTs = dateEnd.ToUnixTimeSeconds() - }; + listTagsID.Add(tag.Uid); + } + + //HistoricRequest historicRequest = new HistoricRequest(); + //historicRequest.DataSource = NexusApiUrl.DataSource; + //historicRequest.Resolution = NexusApiUrl.Resolution; + //historicRequest.Uids = listTagsID; + //historicRequest.StartTs = dateStart.ToUnixTimeSeconds(); + //historicRequest.EndTs = dateEnd.ToUnixTimeSeconds(); WriteLineAndLog($"Obteniendo Tagviews Historic"); string apiUrlHistoric = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}/realtime"; responseData = await _apiService.PostApiResponseAsync(apiUrlHistoric, headers, listTagsID); List historicResponse = JsonSerializer.Deserialize>(responseData, options); - TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time"); - - if (item.name == "API - DGA - CAUDALES") + List listDgaMacroResultados = new List(); + foreach (Column tag in tagviews.Columns) { - var caudalData = tagviews.Columns - .SelectMany(tag => - historicResponse.Where(h => h.Uid == tag.Uid) - .Select(h => new DGAInsert - { - TAG = tag.Name, - VALOR = h.Value?.ToString(), - FECHAMEDICION = TimeZoneInfo.ConvertTimeFromUtc( - new DateTime(1970, 1, 1).AddSeconds(h.TimeStamp).ToUniversalTime(), - zonaHorariaChile) - }) - ).ToList(); + IEnumerable filter = historicResponse.Where(h => h.Uid == tag.Uid); + foreach (HistoricResponse historic in filter) + { + TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time"); + DateTime now = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(historic.TimeStamp); + DateTime fechaHoraChile = TimeZoneInfo.ConvertTimeFromUtc(now, zonaHorariaChile); - await _jobs.InsertarDgaCaudal(caudalData); - } - else if (item.name == "API - DGA - NIVELES") - { - var nivelData = tagviews.Columns - .SelectMany(tag => - historicResponse.Where(h => h.Uid == tag.Uid) - .Select(h => new DGAInsert - { - TAG = tag.Name, - VALOR = h.Value?.ToString(), - FECHAMEDICION = TimeZoneInfo.ConvertTimeFromUtc( - new DateTime(1970, 1, 1).AddSeconds(h.TimeStamp).ToUniversalTime(), - zonaHorariaChile) - }) - ).ToList(); - await _jobs.InsertarDgaNivel(nivelData); + DgaMacroResultado dgaMacroResultado = new DgaMacroResultado(); + dgaMacroResultado.TagName = tag.Name; + dgaMacroResultado.Value = historic.Value; + //dgaMacroResultado.TimeStamp = new DateTime(historic.TimeStamp); + dgaMacroResultado.TimeStamp = fechaHoraChile; + + listDgaMacroResultados.Add(dgaMacroResultado); + } } - else if (item.name == "API - DGA") + + /**************/ + WriteLineAndLog($"Inicia Envio DGA", ConsoleColor.Green); + WriteLineAndLog($"\t Descargar datos historian: Insertar DgaMacroResultado"); + var resultMacro = await _jobs.InsertarDgaMacroResultado(listDgaMacroResultados); + + WriteLineAndLog($"\t Descargar datos historian: Insertar DgaSensorResultado"); + List listDgaSensorResultado = listDgaMacroResultados.Select(item => new DgaSensorResultado { - var nivelData = tagviews.Columns - .SelectMany(tag => - historicResponse.Where(h => h.Uid == tag.Uid) - .Select(h => new - { - TAG = tag.Name, - NIVEL_FREATICO = h.Value?.ToString(), - FECHAMEDICION = TimeZoneInfo.ConvertTimeFromUtc( - new DateTime(1970, 1, 1).AddSeconds(h.TimeStamp).ToUniversalTime(), - zonaHorariaChile) - }) - ).ToList(); - } + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSensor = await _jobs.InsertarDgaSensorResultado(listDgaSensorResultado); + + WriteLineAndLog($"\t Calculo DGA"); + var resultCalculo = await _jobs.SpCalculoDga(); + + WriteLineAndLog($"\t descargar datos suma reversibilidad : Insertar DgaMacroResultadoSupFlujSuma"); + List listDgaMacroResultadoSupFlujSuma = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFlujSuma + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSupFlujSuma = await _jobs.InsertarDgaMacroResultadoSupFlujSuma(listDgaMacroResultadoSupFlujSuma); + + WriteLineAndLog($"\t Calculo Suma"); + var resultCalculoDgaSup = await _jobs.SpCalculoDgaSupFlujSumaSnreversibilidad(); + + + WriteLineAndLog($"\t Traspaso datos achird"); + var result = await _jobs.SpTraspasoDatosAchird(); + WriteLineAndLog($"Fin Envio DGA", ConsoleColor.Green); + /**************/ + /**************/ + WriteLineAndLog($"Inicio Envio DGA Sup Fluj", ConsoleColor.Green); + WriteLineAndLog($"\t Descargar datos historian: Insertar InsertarDgaMacroResultadoSupFluj"); + List listDgaMacroResultadoSupFluj = listDgaMacroResultados.Select(item => new DgaMacroResultadoSupFluj + { + TagName = item.TagName, + TimeStamp = item.TimeStamp, + Value = item.Value, + Quality = item.Quality + }).ToList(); + + var resultSensorSup = await _jobsSupFluj.InsertarDgaMacroResultadoSupFluj(listDgaMacroResultadoSupFluj); + + WriteLineAndLog($"\t Calculo Suma"); + var resultCalculoSup = await _jobsSupFluj.SpCalculoDgaSupFluj(); + + + WriteLineAndLog($"\t Traspaso datos achird"); + var resultAchirdSup = await _jobsSupFluj.SpTraspasoDatosAchirdSupFluj(); + WriteLineAndLog($"Fin Envio DGA Sup Fluj", ConsoleColor.Green); + /**************/ + /**************/ } - - WriteLineAndLog($"INICIO REGISTRO DE MEDICIONES DGA"); - await _jobs.SpRegistrarMedicionesDga(); - WriteLineAndLog($"FIN REGISTRO DE MEDICIONES DGA"); - - WriteLineAndLog($"FIN PROCESO DGA"); + WriteLineAndLog($"FIN Proceso DGA"); } catch (Exception ex) { diff --git a/DAL/JobsDgaRepository.cs b/DAL/JobsDgaRepository.cs index a9b8c67..c173b73 100644 --- a/DAL/JobsDgaRepository.cs +++ b/DAL/JobsDgaRepository.cs @@ -1,7 +1,6 @@ using System.Data; using Dapper; using Microsoft.Data.SqlClient; -using Microsoft.Identity.Client; using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; @@ -9,7 +8,83 @@ namespace DAL { public class JobsDgaRepository { - public async Task SpRegistrarMedicionesDga() + public async Task InsertarDgaMacroResultado(List dgaMacroResultados) + { + try + { + using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + // 1. Truncar la tabla antes de insertar + await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO"); + // 2. Insertar la lista de registros + string sql = "INSERT INTO DGA_MACRO_RESULTADO (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + // Esto inserta todos los elementos de la lista en la tabla + await connection.ExecuteAsync(sql, dgaMacroResultados); + return true; + } + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } + + public async Task InsertarDgaSensorResultado(List dgaSensorResultado) + { + try + { + using (var connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + + // 1. Truncar la tabla DGA_SENSOR_RESULTADO + await connection.ExecuteAsync("TRUNCATE TABLE DGA_SENSOR_RESULTADO"); + + // 2. Llamar al stored procedure SP_CALCULO_DGA + await connection.ExecuteAsync("SP_CALCULO_DGA", commandType: System.Data.CommandType.StoredProcedure); + + // 3. Insertar todos los registros de la lista con Dapper + string sql = "INSERT INTO DGA_SENSOR_RESULTADO (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + await connection.ExecuteAsync(sql, dgaSensorResultado); + + return true; + } + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } + + public async Task InsertarDgaMacroResultadoSupFlujSuma(List dgaMacroResultadoSupFlujSuma) + { + try + { + // Configurar la conexión a la base de datos + using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + // Truncar la tabla antes de insertar + await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA"); + + // Crear un adaptador de datos + SqlDataAdapter adapter = new SqlDataAdapter(); + + // Configurar el comando de inserción + string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ_SUMA (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + await connection.ExecuteAsync(sql, dgaMacroResultadoSupFlujSuma); + + return true; // Éxito + } + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } + + public async Task SpCalculoDga() { try { @@ -17,7 +92,7 @@ namespace DAL { await connection.OpenAsync(); // Ejecuta el stored procedure sin parámetros - await connection.ExecuteAsync("SP_REGISTRAR_DATOS_DGA", commandType: CommandType.StoredProcedure); + await connection.ExecuteAsync("SP_CALCULO_DGA", commandType: CommandType.StoredProcedure); } return true; // Éxito } @@ -27,21 +102,19 @@ namespace DAL } } - public async Task InsertarDgaCaudal(List dgaMacroResultados) + public async Task SpCalculoDgaSupFlujSumaSnreversibilidad() { try { - using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + using (var connection = new SqlConnection(BdConexion.StringConnection)) { await connection.OpenAsync(); - // 1. Truncar la tabla antes de insertar - await connection.ExecuteAsync("TRUNCATE TABLE DGA_CAUDAL"); - // 2. Insertar la lista de registros - string sql = "INSERT INTO DGA_CAUDAL (TAG, CAUDAL, FECHAMEDICION) VALUES (@TAG, @VALOR, @FECHAMEDICION)"; - // Esto inserta todos los elementos de la lista en la tabla - await connection.ExecuteAsync(sql, dgaMacroResultados); - return true; + await connection.ExecuteAsync( + "SP_CALCULO_DGA_SUP_FLUJ_SUMA_SNREVERSIBILIDAD", + commandType: CommandType.StoredProcedure + ); } + return true; // Éxito } catch (Exception ex) { @@ -49,21 +122,19 @@ namespace DAL } } - public async Task InsertarDgaNivel(List dgaMacroResultados) + public async Task SpTraspasoDatosAchird() { try { - using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection)) + using (var connection = new SqlConnection(BdConexion.StringConnection)) { await connection.OpenAsync(); - // 1. Truncar la tabla antes de insertar - await connection.ExecuteAsync("TRUNCATE TABLE DGA_NIVEL"); - // 2. Insertar la lista de registros - string sql = "INSERT INTO DGA_NIVEL (TAG, NIVEL_FREATICO, FECHAMEDICION) VALUES (@TAG, @VALOR, @FECHAMEDICION)"; - // Esto inserta todos los elementos de la lista en la tabla - await connection.ExecuteAsync(sql, dgaMacroResultados); - return true; + await connection.ExecuteAsync( + "SP_TRASPASO_DATOS_ACHIRD", + commandType: CommandType.StoredProcedure + ); } + return true; // Éxito } catch (Exception ex) { diff --git a/SHARED/DTO/Integracion_DGA/DGAInsert.cs b/SHARED/DTO/Integracion_DGA/DGAInsert.cs deleted file mode 100644 index e1e0ce5..0000000 --- a/SHARED/DTO/Integracion_DGA/DGAInsert.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Shared.DTO.Integracion_DGA -{ - public partial class DGAInsert - { - public string TAG { get; set; } = string.Empty; - public string? VALOR { get; set; } - public DateTime FECHAMEDICION { get; set; } - } -}