diff --git a/BLL/Integracion_DGA/BusinessLogic.cs b/BLL/Integracion_DGA/BusinessLogic.cs index 2f618ee..10e5d83 100644 --- a/BLL/Integracion_DGA/BusinessLogic.cs +++ b/BLL/Integracion_DGA/BusinessLogic.cs @@ -58,107 +58,80 @@ namespace BLL.Integracion_DGA responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers); TagviewsResponse tagviews = JsonSerializer.Deserialize(responseData, options); - List listTagsID = new List(); - foreach (Column tag in tagviews.Columns) - { - listTagsID.Add(tag.Uid); - } + List listTagsID = tagviews.Columns.Select(x => x.Uid).ToList(); - //HistoricRequest historicRequest = new HistoricRequest(); - //historicRequest.DataSource = NexusApiUrl.DataSource; - //historicRequest.Resolution = NexusApiUrl.Resolution; - //historicRequest.Uids = listTagsID; - //historicRequest.StartTs = dateStart.ToUnixTimeSeconds(); - //historicRequest.EndTs = dateEnd.ToUnixTimeSeconds(); + HistoricRequest historicRequest = new HistoricRequest + { + DataSource = NexusApiUrl.DataSource, + Resolution = NexusApiUrl.Resolution, + Uids = listTagsID, + StartTs = dateStart.ToUnixTimeSeconds(), + 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); - List listDgaMacroResultados = new List(); - foreach (Column tag in tagviews.Columns) + TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time"); + + if (item.name == "API - DGA - CAUDALES") { - 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); + 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(); - - DgaMacroResultado dgaMacroResultado = new DgaMacroResultado(); - dgaMacroResultado.TagName = tag.Name; - dgaMacroResultado.Value = historic.Value; - //dgaMacroResultado.TimeStamp = new DateTime(historic.TimeStamp); - dgaMacroResultado.TimeStamp = fechaHoraChile; - - listDgaMacroResultados.Add(dgaMacroResultado); - } + await _jobs.InsertarDgaCaudal(caudalData); } - - /**************/ - 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 + else if (item.name == "API - DGA - NIVELES") { - TagName = item.TagName, - TimeStamp = item.TimeStamp, - Value = item.Value, - Quality = item.Quality - }).ToList(); + 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(); - 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 + await _jobs.InsertarDgaNivel(nivelData); + } + else if (item.name == "API - DGA") { - 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); - /**************/ - /**************/ + 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(); + } } - WriteLineAndLog($"FIN Proceso DGA"); + + WriteLineAndLog($"INICIO REGISTRO DE MEDICIONES DGA"); + await _jobs.SpRegistrarMedicionesDga(); + WriteLineAndLog($"FIN REGISTRO DE MEDICIONES DGA"); + + WriteLineAndLog($"FIN PROCESO DGA"); } catch (Exception ex) { diff --git a/DAL/JobsDgaRepository.cs b/DAL/JobsDgaRepository.cs index c173b73..a9b8c67 100644 --- a/DAL/JobsDgaRepository.cs +++ b/DAL/JobsDgaRepository.cs @@ -1,6 +1,7 @@ using System.Data; using Dapper; using Microsoft.Data.SqlClient; +using Microsoft.Identity.Client; using Shared.DTO.Integracion_DGA; using Shared.DTO.VariablesEntorno; @@ -8,7 +9,25 @@ namespace DAL { public class JobsDgaRepository { - public async Task InsertarDgaMacroResultado(List dgaMacroResultados) + public async Task SpRegistrarMedicionesDga() + { + try + { + using (var connection = new SqlConnection(BdConexion.StringConnection)) + { + await connection.OpenAsync(); + // Ejecuta el stored procedure sin parámetros + await connection.ExecuteAsync("SP_REGISTRAR_DATOS_DGA", commandType: CommandType.StoredProcedure); + } + return true; // Éxito + } + catch (Exception ex) + { + throw new Exception($"Error: {ex.Message}"); + } + } + + public async Task InsertarDgaCaudal(List dgaMacroResultados) { try { @@ -16,9 +35,9 @@ namespace DAL { await connection.OpenAsync(); // 1. Truncar la tabla antes de insertar - await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO"); + await connection.ExecuteAsync("TRUNCATE TABLE DGA_CAUDAL"); // 2. Insertar la lista de registros - string sql = "INSERT INTO DGA_MACRO_RESULTADO (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)"; + 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; @@ -30,24 +49,19 @@ namespace DAL } } - public async Task InsertarDgaSensorResultado(List dgaSensorResultado) + public async Task InsertarDgaNivel(List dgaMacroResultados) { try { - using (var connection = new SqlConnection(BdConexion.StringConnection)) + using (SqlConnection 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); - + // 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; } } @@ -56,90 +70,5 @@ namespace DAL 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 - { - using (var connection = new SqlConnection(BdConexion.StringConnection)) - { - await connection.OpenAsync(); - // Ejecuta el stored procedure sin parámetros - await connection.ExecuteAsync("SP_CALCULO_DGA", commandType: CommandType.StoredProcedure); - } - return true; // Éxito - } - catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } - - public async Task SpCalculoDgaSupFlujSumaSnreversibilidad() - { - try - { - using (var connection = new SqlConnection(BdConexion.StringConnection)) - { - await connection.OpenAsync(); - await connection.ExecuteAsync( - "SP_CALCULO_DGA_SUP_FLUJ_SUMA_SNREVERSIBILIDAD", - commandType: CommandType.StoredProcedure - ); - } - return true; // Éxito - } - catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } - - public async Task SpTraspasoDatosAchird() - { - try - { - using (var connection = new SqlConnection(BdConexion.StringConnection)) - { - await connection.OpenAsync(); - await connection.ExecuteAsync( - "SP_TRASPASO_DATOS_ACHIRD", - commandType: CommandType.StoredProcedure - ); - } - return true; // Éxito - } - catch (Exception ex) - { - throw new Exception($"Error: {ex.Message}"); - } - } } } diff --git a/SHARED/DTO/Integracion_DGA/DGAInsert.cs b/SHARED/DTO/Integracion_DGA/DGAInsert.cs new file mode 100644 index 0000000..e1e0ce5 --- /dev/null +++ b/SHARED/DTO/Integracion_DGA/DGAInsert.cs @@ -0,0 +1,15 @@ +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; } + } +}