Compare commits
7 commits
e7372f2ae6
...
747391eade
Author | SHA1 | Date | |
---|---|---|---|
|
747391eade | ||
|
7bc8400980 | ||
|
b52be74bfa | ||
|
657fd50ac9 | ||
|
5db07294f9 | ||
|
6edec57054 | ||
|
4b5b3ae3d9 |
30 changed files with 572 additions and 768 deletions
|
@ -1,187 +0,0 @@
|
|||
using System.Text.Json;
|
||||
using DAL;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.DTO.Integracion_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
using Shared.Helper;
|
||||
|
||||
namespace BLL.Integracion_DGA
|
||||
{
|
||||
public class BusinessLogic
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ApiService _apiService;
|
||||
private readonly JobsDgaRepository _jobs;
|
||||
private readonly JobsDgaSupFlujRepository _jobsSupFluj;
|
||||
private readonly FileLoggerHelper _fileLoggerHelper;
|
||||
|
||||
public BusinessLogic(IConfiguration configuration, ApiService apiService, JobsDgaRepository jobs, JobsDgaSupFlujRepository jobsSupFluj)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_apiService = apiService;
|
||||
_jobs = jobs;
|
||||
_jobsSupFluj = jobsSupFluj;
|
||||
FileLoggerHelper.ConfigureLogger(_configuration);
|
||||
}
|
||||
|
||||
public async Task Run()
|
||||
{
|
||||
|
||||
DateTimeOffset dateEnd = DateTimeOffset.Now;
|
||||
DateTimeOffset dateStart = dateEnd.AddHours(-1);
|
||||
|
||||
JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
//FileLoggerHelper.ConfigureLogger(_configuration);
|
||||
WriteLineAndLog($"Inicia Proceso DGA");
|
||||
try
|
||||
{
|
||||
string apiUrlBase = NexusApiUrl.ApiUrl;
|
||||
Dictionary<string, string> headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "nexustoken", NexusApiUrl.ApiKey },
|
||||
{ "nexusapiversion", NexusApiUrl.Version },
|
||||
{ "accept", "application/json" }
|
||||
};
|
||||
|
||||
WriteLineAndLog($"Obteniendo Documentos");
|
||||
string apiUrlDocuments = apiUrlBase + "/api/Documents";
|
||||
|
||||
// Utiliza el servicio para realizar la solicitud a la API con URL y encabezados personalizados
|
||||
string responseData = await _apiService.GetApiResponseAsync(apiUrlDocuments, headers);
|
||||
|
||||
var documento = JsonSerializer.Deserialize<List<DocumentResponse>>(responseData, options);
|
||||
foreach (DocumentResponse item in documento)
|
||||
{
|
||||
WriteLineAndLog($"Obteniendo Tagviews");
|
||||
string apiUrlTagViews = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}";
|
||||
responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers);
|
||||
TagviewsResponse tagviews = JsonSerializer.Deserialize<TagviewsResponse>(responseData, options);
|
||||
|
||||
List<string> listTagsID = new List<string>();
|
||||
foreach (Column tag in tagviews.Columns)
|
||||
{
|
||||
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}/historic";
|
||||
responseData = await _apiService.PostApiResponseAsync(apiUrlHistoric, headers, historicRequest);
|
||||
List<HistoricResponse> historicResponse = JsonSerializer.Deserialize<List<HistoricResponse>>(responseData, options);
|
||||
|
||||
List<DgaMacroResultado> listDgaMacroResultados = new List<DgaMacroResultado>();
|
||||
foreach (Column tag in tagviews.Columns)
|
||||
{
|
||||
IEnumerable<HistoricResponse> 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);
|
||||
|
||||
|
||||
DgaMacroResultado dgaMacroResultado = new DgaMacroResultado();
|
||||
dgaMacroResultado.TagName = $"SCADA001.{tag.Name}.F_CV";
|
||||
dgaMacroResultado.Value = historic.Value;
|
||||
//dgaMacroResultado.TimeStamp = new DateTime(historic.TimeStamp);
|
||||
dgaMacroResultado.TimeStamp = fechaHoraChile;
|
||||
|
||||
listDgaMacroResultados.Add(dgaMacroResultado);
|
||||
}
|
||||
}
|
||||
|
||||
/**************/
|
||||
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<DgaSensorResultado> listDgaSensorResultado = listDgaMacroResultados.Select(item => new DgaSensorResultado
|
||||
{
|
||||
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<DgaMacroResultadoSupFlujSuma> 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<DgaMacroResultadoSupFluj> 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($"FIN Proceso DGA");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FileLoggerHelper.LogError($"{ex.Message}", ex);
|
||||
WriteLineAndLog($"{ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void WriteLineAndLog(string msj, ConsoleColor? color = null)
|
||||
{
|
||||
if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value))
|
||||
{
|
||||
Console.ForegroundColor = (ConsoleColor)color;
|
||||
Console.WriteLine(msj);
|
||||
Console.ResetColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{msj}");
|
||||
}
|
||||
|
||||
FileLoggerHelper.LogInformation($"{msj}");
|
||||
}
|
||||
}
|
||||
}
|
138
BLL/Integracion_DGA/ObtencionDatosDga.cs
Normal file
138
BLL/Integracion_DGA/ObtencionDatosDga.cs
Normal file
|
@ -0,0 +1,138 @@
|
|||
using DAL;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shared.DTO;
|
||||
using Shared.DTO.Integracion_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
using Shared.Helper;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BLL.Integracion_DGA
|
||||
{
|
||||
public class ObtencionDatosDga
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ApiService _apiService;
|
||||
private readonly JobsDgaRepository _jobs;
|
||||
private readonly LogEnvioRepository _logEnvioRepository;
|
||||
|
||||
public ObtencionDatosDga(IConfiguration configuration, ApiService apiService, JobsDgaRepository jobs, LogEnvioRepository logEnvioRepository)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_apiService = apiService;
|
||||
_jobs = jobs;
|
||||
FileLoggerHelper.ConfigureLogger(_configuration);
|
||||
_logEnvioRepository = logEnvioRepository;
|
||||
}
|
||||
|
||||
public async Task ObtenerDatosDga()
|
||||
{
|
||||
await _logEnvioRepository.InsertarLogProcesoAsync(new LogProceso
|
||||
{
|
||||
FechaEjecucion = DateTime.UtcNow,
|
||||
NombreProceso = "OBTENCION DATOS DGA"
|
||||
});
|
||||
|
||||
DateTimeOffset dateEnd = DateTimeOffset.Now;
|
||||
DateTimeOffset dateStart = dateEnd.AddHours(-1);
|
||||
|
||||
JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"INICIO OBTENER DATOS DGA");
|
||||
try
|
||||
{
|
||||
string apiUrlBase = NexusApiUrl.ApiUrl;
|
||||
Dictionary<string, string> headers = new Dictionary<string, string>
|
||||
{
|
||||
{ "nexustoken", NexusApiUrl.ApiKey },
|
||||
{ "nexusapiversion", NexusApiUrl.Version },
|
||||
{ "accept", "application/json" }
|
||||
};
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"OBTENIENDO DOCUMENTOS");
|
||||
string apiUrlDocuments = apiUrlBase + "/api/Documents";
|
||||
|
||||
// Utiliza el servicio para realizar la solicitud a la API con URL y encabezados personalizados
|
||||
string responseData = await _apiService.GetApiResponseAsync(apiUrlDocuments, headers);
|
||||
|
||||
var documento = JsonSerializer.Deserialize<List<DocumentResponse>>(responseData, options);
|
||||
|
||||
if (documento == null || documento.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (DocumentResponse item in documento)
|
||||
{
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"OBTENIENDO TAGVIEWS");
|
||||
string apiUrlTagViews = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}";
|
||||
responseData = await _apiService.GetApiResponseAsync(apiUrlTagViews, headers);
|
||||
TagviewsResponse tagviews = JsonSerializer.Deserialize<TagviewsResponse>(responseData, options) ?? new TagviewsResponse();
|
||||
|
||||
List<string> listTagsID = tagviews.Columns.Select(x => x.Uid).ToList();
|
||||
|
||||
HistoricRequest historicRequest = new HistoricRequest
|
||||
{
|
||||
DataSource = NexusApiUrl.DataSource,
|
||||
Resolution = NexusApiUrl.Resolution,
|
||||
Uids = listTagsID,
|
||||
StartTs = dateStart.ToUnixTimeSeconds(),
|
||||
EndTs = dateEnd.ToUnixTimeSeconds()
|
||||
};
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"OBTENIENDO TAGVIEWS HISTORIC");
|
||||
string apiUrlHistoric = $"{apiUrlBase}/api/Documents/tagviews/{item.uid}/historic";
|
||||
responseData = await _apiService.PostApiResponseAsync(apiUrlHistoric, headers, historicRequest);
|
||||
List<HistoricResponse> historicResponse = JsonSerializer.Deserialize<List<HistoricResponse>>(responseData, options) ?? new List<HistoricResponse>();
|
||||
|
||||
TimeZoneInfo zonaHorariaChile = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time");
|
||||
|
||||
if (item.name == "API - DGA - CAUDALES")
|
||||
{
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"OBTENIENDO DATOS DGA CAUDAL");
|
||||
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();
|
||||
|
||||
await _jobs.InsertarDgaCaudal(caudalData);
|
||||
}
|
||||
else if (item.name == "API - DGA - NIVELES")
|
||||
{
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"OBTENIENDO DATOS DGA NIVEL");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"INICIO REGISTRO DE MEDICIONES DGA");
|
||||
await _jobs.SpRegistrarMedicionesDga();
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"FIN REGISTRO DE MEDICIONES DGA");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FileLoggerHelper.LogError($"{ex.Message}", ex);
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"{ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
using System.Text.Json;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using DAL;
|
||||
using DAS;
|
||||
using Shared.DTO;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
using Shared.Helper;
|
||||
|
@ -9,68 +11,44 @@ namespace BLL.Recuperacion_DGA
|
|||
{
|
||||
public class EnvioDGA
|
||||
{
|
||||
private readonly MedicionScadaRepository _dGAMedicionScadaRepository;
|
||||
private readonly MedicionDGARepository _dGAMedicionRepository;
|
||||
private readonly RegistrarMedicion _registrarMedicion;
|
||||
private readonly LogEnvioRepository _logEnvioRepository;
|
||||
|
||||
public EnvioDGA(MedicionScadaRepository dGAMedicionScadaRepository, RegistrarMedicion registrarMedicion)
|
||||
public EnvioDGA(MedicionDGARepository dGAMedicionRepository, RegistrarMedicion registrarMedicion, LogEnvioRepository logEnvioRepository)
|
||||
{
|
||||
_dGAMedicionScadaRepository = dGAMedicionScadaRepository;
|
||||
_dGAMedicionRepository = dGAMedicionRepository;
|
||||
_registrarMedicion = registrarMedicion;
|
||||
_logEnvioRepository = logEnvioRepository;
|
||||
}
|
||||
|
||||
public async Task<bool> RegistrarMedicionesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await WriteLineAndLog("INICIO", "Inicio proceso de recuperación DGA", "");
|
||||
WriteLineAndLog("Obteniendo Mediciones Scada", ConsoleColor.Green);
|
||||
var mediciones = await _dGAMedicionScadaRepository.ObtenerMedicionesAsync();
|
||||
var listaMediciones = new List<Object>();
|
||||
await _logEnvioRepository.InsertarLogProcesoAsync(new LogProceso
|
||||
{
|
||||
FechaEjecucion = DateTime.UtcNow,
|
||||
NombreProceso = "ENVIO DATOS DGA"
|
||||
});
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogEventoAsync("INICIO", "Inicio proceso de recuperación DGA", "");
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo("Obteniendo Mediciones Scada", ConsoleColor.Green);
|
||||
|
||||
var logsEnviados = new List<LogMedicionEnvio>();
|
||||
|
||||
var pageNumber = 1;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var mediciones = await _dGAMedicionRepository.ObtenerMedicionesPorLoteAsync(pageNumber);
|
||||
|
||||
if (mediciones == null || !mediciones.Any()){ break; }
|
||||
|
||||
foreach (var medicion in mediciones)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(medicion.Code))
|
||||
{
|
||||
var rutEmpresa = string.Empty;
|
||||
if (medicion.tipo_empresa == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (medicion.tipo_empresa == "AV")
|
||||
{
|
||||
rutEmpresa = CredencialDGA.RutAv;
|
||||
}
|
||||
if (medicion.tipo_empresa == "EV")
|
||||
{
|
||||
rutEmpresa = CredencialDGA.RutEsval;
|
||||
}
|
||||
|
||||
List<string> vacios = new List<string>();
|
||||
if (medicion.Caudal == null || medicion.Caudal.Equals(""))
|
||||
{
|
||||
vacios.Add("caudal");
|
||||
}
|
||||
|
||||
if (medicion.DateOrigen == null)
|
||||
{
|
||||
vacios.Add("fecha origen");
|
||||
}
|
||||
|
||||
if (medicion.nivelFreaticoDelPozo == null || medicion.nivelFreaticoDelPozo.ToString().Equals(""))
|
||||
{
|
||||
vacios.Add("nivel freatico");
|
||||
}
|
||||
|
||||
if (medicion.Totalizador == null || medicion.Totalizador.Equals(""))
|
||||
{
|
||||
vacios.Add("totalizador");
|
||||
}
|
||||
|
||||
if (vacios.Count > 0)
|
||||
{
|
||||
await FileLoggerHelper.InsertarLogsAsync("REGISTRAR", $"Medicion {medicion.Code} no registra {string.Join(", ", vacios)}","");
|
||||
}
|
||||
var fechaEnvio = DateTime.UtcNow;
|
||||
|
||||
var body = new MedicionSubterraneaRequest
|
||||
|
@ -78,76 +56,55 @@ namespace BLL.Recuperacion_DGA
|
|||
Autenticacion = new Autenticacion
|
||||
{
|
||||
Password = CredencialDGA.Password,
|
||||
RutEmpresa = rutEmpresa,
|
||||
RutEmpresa = medicion.TIPO_EMPRESA == "EV" ? CredencialDGA.RutEsval : CredencialDGA.RutAv,
|
||||
RutUsuario = CredencialDGA.RutUsuario
|
||||
},
|
||||
MedicionSubterranea = new Medicion
|
||||
{
|
||||
Caudal = medicion.Caudal.ToString() ?? "",
|
||||
FechaMedicion = medicion.DateOrigen?.ToString("yyyy-MM-dd") ?? "",
|
||||
HoraMedicion = medicion.DateOrigen?.ToString("HH:mm:ss") ?? "",
|
||||
NivelFreaticoDelPozo = medicion.nivelFreaticoDelPozo?.ToString() ?? "",
|
||||
Totalizador = medicion.Totalizador.ToString() ?? "",
|
||||
Caudal = medicion.CAUDAL ?? "",
|
||||
FechaMedicion = medicion.FECHA_MEDICION_CAUDAL?.ToString("yyyy-MM-dd") ?? "",
|
||||
HoraMedicion = medicion.FECHA_MEDICION_CAUDAL?.ToString("HH:mm:ss") ?? "",
|
||||
NivelFreaticoDelPozo = medicion.NIVEL_FREATICO_DEL_POZO ?? "",
|
||||
Totalizador = medicion.TOTALIZADOR_CAUDAL ?? "",
|
||||
}
|
||||
};
|
||||
await _registrarMedicion.EnviarMedicionAsync(medicion, body, fechaEnvio);
|
||||
listaMediciones.Add(new {Id = medicion.Id,FechaEnvio = fechaEnvio.ToString("yyyy-MM-dd HH:mm:ss"), Enviado = medicion.Enviado + 1});
|
||||
}
|
||||
|
||||
var response = await _registrarMedicion.EnviarMedicionAsync(medicion, body, fechaEnvio);
|
||||
|
||||
logsEnviados.Add(response);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FileLoggerHelper.LogError($"[Error] {ex.Message}.", ex);
|
||||
WriteLineAndLog($"Error al enviar la medición con ID {medicion.Code}.", ConsoleColor.Red);
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"[Error]: medicion[{medicion.ID}], mensaje: {ex.Message}");
|
||||
}
|
||||
}
|
||||
var listaMedicionesJson = JsonSerializer.Serialize(listaMediciones);
|
||||
|
||||
if (listaMediciones.Count > 0)
|
||||
try
|
||||
{
|
||||
await MedicionScadaRepository.ActualizarMedicionesAsync(listaMedicionesJson);
|
||||
var idMediciones = mediciones.Select(x => x.ID).ToList();
|
||||
await _dGAMedicionRepository.GuardarMedicionesEnviadasAsync(idMediciones);
|
||||
await _logEnvioRepository.InsertarLogRespuesta(logsEnviados);
|
||||
}
|
||||
await WriteLineAndLog("FIN","Fin proceso de recuperación DGA","");
|
||||
catch (Exception e)
|
||||
{
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"[Error] {e.Message}");
|
||||
}
|
||||
|
||||
logsEnviados.Clear();
|
||||
mediciones.Clear();
|
||||
pageNumber++;
|
||||
}
|
||||
|
||||
ConsoleLoggerHelper.WriteLineAndLogEventoAsync("FIN","Fin proceso de recuperación DGA","");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FileLoggerHelper.LogError($"[Error] {ex.Message}.", ex);
|
||||
WriteLineAndLog($"Error al procesar las mediciones.", ConsoleColor.Red);
|
||||
ConsoleLoggerHelper.WriteLineAndLogInfo($"Error al procesar las mediciones.", ConsoleColor.Red);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void WriteLineAndLog(string msj, ConsoleColor? color = null)
|
||||
{
|
||||
if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value))
|
||||
{
|
||||
Console.ForegroundColor = (ConsoleColor)color;
|
||||
Console.WriteLine(msj);
|
||||
Console.ResetColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{msj}");
|
||||
}
|
||||
|
||||
FileLoggerHelper.LogInformation($"{msj}");
|
||||
}
|
||||
|
||||
static async Task WriteLineAndLog(string evento, string proceso, string operacion = null, ConsoleColor? color = null)
|
||||
{
|
||||
if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value))
|
||||
{
|
||||
Console.ForegroundColor = (ConsoleColor)color;
|
||||
Console.WriteLine($"{proceso}");
|
||||
Console.ResetColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{proceso}");
|
||||
}
|
||||
FileLoggerHelper.LogInformation($"{proceso}");
|
||||
await FileLoggerHelper.InsertarLogsAsync(evento,proceso,operacion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,54 +0,0 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public static class Encriptador
|
||||
{
|
||||
private static readonly byte[] key = Encoding.ASCII.GetBytes("1234567891234567");
|
||||
private static readonly byte[] iv = Encoding.ASCII.GetBytes("Devjoker7.37hAES");
|
||||
|
||||
public static string Encripta(string Cadena)
|
||||
{
|
||||
|
||||
using Aes aesAlg = Aes.Create();
|
||||
aesAlg.Key = key;
|
||||
aesAlg.IV = iv;
|
||||
|
||||
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||||
|
||||
using (MemoryStream msEncrypt = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||||
{
|
||||
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
|
||||
{
|
||||
swEncrypt.Write(Cadena);
|
||||
}
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(msEncrypt.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
public static string Desencripta(string Cadena)
|
||||
{
|
||||
using Aes aesAlg = Aes.Create();
|
||||
aesAlg.Key = key;
|
||||
aesAlg.IV = iv;
|
||||
|
||||
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||||
|
||||
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(Cadena)))
|
||||
{
|
||||
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
|
||||
{
|
||||
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
|
||||
{
|
||||
return srDecrypt.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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<bool> InsertarDgaMacroResultado(List<DgaMacroResultado> dgaMacroResultados)
|
||||
public async Task<bool> 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<bool> InsertarDgaCaudal(List<DGAInsert> 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<bool> InsertarDgaSensorResultado(List<DgaSensorResultado> dgaSensorResultado)
|
||||
public async Task<bool> InsertarDgaNivel(List<DGAInsert> 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<bool> InsertarDgaMacroResultadoSupFlujSuma(List<DgaMacroResultadoSupFlujSuma> 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<bool> 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<bool> 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<bool> 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,74 +0,0 @@
|
|||
using System.Data;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Shared.DTO.Integracion_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public class JobsDgaSupFlujRepository
|
||||
{
|
||||
public async Task<bool> InsertarDgaMacroResultadoSupFluj(List<DgaMacroResultadoSupFluj> dgaMacroResultadoSupFluj)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Configurar la conexión a la base de datos
|
||||
using (SqlConnection connection = new SqlConnection(BdConexion.StringConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
await connection.ExecuteAsync("TRUNCATE TABLE DGA_MACRO_RESULTADO_SUP_FLUJ");
|
||||
|
||||
await SpCalculoDgaSupFluj();
|
||||
|
||||
string sql = "INSERT INTO DGA_MACRO_RESULTADO_SUP_FLUJ (TagName, TimeStamp, Value, Quality) VALUES (@TagName, @TimeStamp, @Value, @Quality)";
|
||||
await connection.ExecuteAsync(sql, dgaMacroResultadoSupFluj);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SpCalculoDgaSupFluj()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var connection = new SqlConnection(BdConexion.StringConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
await connection.ExecuteAsync(
|
||||
"SP_CALCULO_DGA_SUP_FLUJ",
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
return true; // Éxito
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SpTraspasoDatosAchirdSupFluj()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var connection = new SqlConnection(BdConexion.StringConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
await connection.ExecuteAsync(
|
||||
"SP_TRASPASO_DATOS_ACHIRD_SUP_FLUJ",
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
return true; // Éxito
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
69
DAL/LogEnvioRepository.cs
Normal file
69
DAL/LogEnvioRepository.cs
Normal file
|
@ -0,0 +1,69 @@
|
|||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Serilog;
|
||||
using Shared.DTO;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public class LogEnvioRepository
|
||||
{
|
||||
public async Task<bool> InsertarLogProcesoAsync(LogProceso log)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
|
||||
var sql = @"
|
||||
INSERT INTO dbo.DGA_LOGS_PROCESOS
|
||||
(
|
||||
NOMBRE_PROCESO,
|
||||
FECHA_EJECUCION
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
@NombreProceso,
|
||||
@FechaEjecucion
|
||||
);";
|
||||
|
||||
await connection.ExecuteAsync(sql, log);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> InsertarLogRespuesta(List<LogMedicionEnvio> logsEnviados)
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
try
|
||||
{
|
||||
var sql = @"INSERT INTO DGA_LOGS_ENVIOS (
|
||||
ESTADO_ENVIO,
|
||||
JSON_ENVIO,
|
||||
JSON_RESPUESTA,
|
||||
COMPROBANTE,
|
||||
FECHA_ENVIO,
|
||||
ID_DGA_DATO)
|
||||
VALUES (
|
||||
@ESTADO_ENVIO,
|
||||
@JSON_ENVIO,
|
||||
@JSON_RESPUESTA,
|
||||
@COMPROBANTE,
|
||||
@FECHA_ENVIO,
|
||||
@ID_DGA_DATO);";
|
||||
|
||||
await connection.ExecuteAsync(sql, logsEnviados);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error al insertar logs de respuesta {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public class LogMedicionScadaRepository
|
||||
{
|
||||
public async Task<bool> InsertarLogMedicionScadaAsync(LogMedicionScada logMedicionScada)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var connection = new SqlConnection(BdConexion.StringConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
// Insertar todos los datos de la lista usando Dapper
|
||||
var sql = @"INSERT INTO dbo.DGA_LOGS_OPERACION
|
||||
(estado_envio, json_enviado, json_recibido, comprobante, fecha_envio, id_medicion_smartscada_operacion)
|
||||
VALUES
|
||||
(@EstadoEnvio, @JsonEnviado, @JsonRecibido, @Comprobante, @FechaEnvio, @IdMedicionSmartscadaOperacion)";
|
||||
await connection.ExecuteAsync(sql, logMedicionScada);
|
||||
|
||||
return true; // Éxito
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
54
DAL/MedicionDGARepository.cs
Normal file
54
DAL/MedicionDGARepository.cs
Normal file
|
@ -0,0 +1,54 @@
|
|||
using System.Data;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public class MedicionDGARepository
|
||||
{
|
||||
public async Task<List<DatoDGA>> ObtenerMedicionesAsync()
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
|
||||
var result = await connection.QueryAsync<DatoDGA>(
|
||||
"SP_OBTENER_DGA_DATOS",
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
return result.ToList();
|
||||
}
|
||||
|
||||
public async Task<List<DatoDGATemporal>> ObtenerMedicionesPorLoteAsync(int pageNumber)
|
||||
{
|
||||
var nroPagina = new DynamicParameters();
|
||||
nroPagina.Add("@PageNumber", pageNumber);
|
||||
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
|
||||
var resultado = await connection.QueryAsync<DatoDGATemporal>(
|
||||
"SP_OBTENER_LOTE_DGA_DATOS",
|
||||
nroPagina,
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
return resultado.ToList();
|
||||
}
|
||||
|
||||
public async Task<bool> GuardarMedicionesEnviadasAsync(List<int> medicionesGuardadas)
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
try
|
||||
{
|
||||
var query = @"UPDATE DGA_DATOS SET ENVIADO = 1 WHERE ID IN @Ids";
|
||||
|
||||
await connection.ExecuteAsync(query, new { Ids = medicionesGuardadas });
|
||||
return true;
|
||||
}
|
||||
catch(Exception ex) {
|
||||
|
||||
throw new Exception($"Error {ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
using System.Data;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
namespace DAL
|
||||
{
|
||||
public class MedicionScadaRepository
|
||||
{
|
||||
public async Task<List<MedicionScada>> ObtenerMedicionesAsync()
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
|
||||
var result = await connection.QueryAsync<MedicionScada>(
|
||||
"SP_OBTENER_MEDICION_SMARTSCADA_OPERACION",
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
return result.ToList();
|
||||
}
|
||||
|
||||
public static async Task<bool> ActualizarMedicionesAsync(string medicionesJson)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
await connection.ExecuteAsync("SP_ACTUALIZAR_MEDICION_SMARTSCADA_OPERACION", new { JsonMediciones = medicionesJson }, commandType: CommandType.StoredProcedure);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,66 +1,74 @@
|
|||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using DAL;
|
||||
using DAL;
|
||||
using Serilog;
|
||||
using Shared.DTO.Envios_DGA;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DAS
|
||||
{
|
||||
public class RegistrarMedicion
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly LogMedicionScadaRepository _logMedicionScadaRepository;
|
||||
private readonly LogEnvioRepository _logMedicionScadaRepository;
|
||||
|
||||
public RegistrarMedicion(HttpClient httpClient, LogMedicionScadaRepository logMedicionScadaRepository)
|
||||
public RegistrarMedicion(HttpClient httpClient, LogEnvioRepository logMedicionScadaRepository)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_logMedicionScadaRepository = logMedicionScadaRepository;
|
||||
}
|
||||
|
||||
public async Task<bool> EnviarMedicionAsync(MedicionScada medicion, MedicionSubterraneaRequest request,DateTime fechaEnvio)
|
||||
{
|
||||
var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss-0000");
|
||||
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
content.Headers.Add("codigoObra", medicion.Code);
|
||||
content.Headers.Add("timeStampOrigen", timeStamp);
|
||||
|
||||
var response = await _httpClient.PostAsync($"{SubterraneaApiUrl.BaseUrl}{SubterraneaApiUrl.EndPoint}", content);
|
||||
string jsonRecibido = await response.Content.ReadAsStringAsync();
|
||||
string estado = response.IsSuccessStatusCode ? "OK" : "ERROR";
|
||||
string comprobante = string.Empty;
|
||||
if (response.IsSuccessStatusCode)
|
||||
public async Task<LogMedicionEnvio> EnviarMedicionAsync(DatoDGATemporal medicion, MedicionSubterraneaRequest request, DateTime fechaEnvio)
|
||||
{
|
||||
var log = new LogMedicionEnvio();
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(jsonRecibido);
|
||||
if (doc.RootElement.TryGetProperty("data", out var dataProp) &&
|
||||
dataProp.TryGetProperty("numeroComprobante", out var comprobanteProp))
|
||||
var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss-0000", CultureInfo.InvariantCulture);
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
|
||||
var req = new HttpRequestMessage(HttpMethod.Post, $"{SubterraneaApiUrl.BaseUrl}{SubterraneaApiUrl.EndPoint}SSSSS");
|
||||
req.Headers.Add("codigoObra", medicion.CODIGO_DGA);
|
||||
req.Headers.Add("timeStampOrigen", timeStamp);
|
||||
req.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
log.JSON_ENVIO = json;
|
||||
log.FECHA_ENVIO = DateTime.UtcNow;
|
||||
log.ID_DGA_DATO = medicion.ID;
|
||||
|
||||
using var response = await _httpClient.SendAsync(req);
|
||||
string jsonRecibido = await response.Content.ReadAsStringAsync();
|
||||
log.JSON_RESPUESTA = jsonRecibido;
|
||||
|
||||
if (response == null || !response.IsSuccessStatusCode)
|
||||
{
|
||||
comprobante = comprobanteProp.GetString() ?? "";
|
||||
log.COMPROBANTE = null;
|
||||
log.ESTADO_ENVIO = "ERROR";
|
||||
}
|
||||
|
||||
var apiResponse = JsonSerializer.Deserialize<ApiResponse<MedicionSubterraneaResponse>>(jsonRecibido, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
|
||||
if (apiResponse == null || string.IsNullOrEmpty(apiResponse.Status) || apiResponse.Status != "00")
|
||||
{
|
||||
log.COMPROBANTE = null;
|
||||
log.ESTADO_ENVIO = "ERROR";
|
||||
}
|
||||
catch
|
||||
|
||||
log.COMPROBANTE = apiResponse.Data.NumeroComprobante ?? null;
|
||||
log.ESTADO_ENVIO = "EXITO";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
log.COMPROBANTE = null;
|
||||
log.ESTADO_ENVIO = "ERROR";
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
var logMedicionScada = new LogMedicionScada
|
||||
{
|
||||
EstadoEnvio = estado,
|
||||
JsonEnviado = json,
|
||||
JsonRecibido = jsonRecibido,
|
||||
Comprobante = comprobante,
|
||||
FechaEnvio = fechaEnvio,
|
||||
IdMedicionSmartscadaOperacion = medicion.Id
|
||||
};
|
||||
|
||||
await _logMedicionScadaRepository.InsertarLogMedicionScadaAsync(logMedicionScada);
|
||||
|
||||
return true;
|
||||
return log;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,22 +46,21 @@ namespace Integracion_DGA
|
|||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
services.AddSingleton<IConfiguration>(configuration);
|
||||
services.AddScoped<MedicionScadaRepository>();
|
||||
services.AddScoped<MedicionDGARepository>();
|
||||
services.AddScoped<EnvioDGA>();
|
||||
services.AddHttpClient<RegistrarMedicion>();
|
||||
services.AddScoped<JobsDgaRepository>();
|
||||
services.AddScoped<JobsDgaSupFlujRepository>();
|
||||
services.AddScoped<LogMedicionScadaRepository>();
|
||||
services.AddScoped<LogEnvioRepository>();
|
||||
services.AddScoped<ApiService>();
|
||||
services.AddScoped<BusinessLogic>();
|
||||
services.AddScoped<ObtencionDatosDga>();
|
||||
})
|
||||
.Build();
|
||||
|
||||
var envioDGA = host.Services.GetRequiredService<EnvioDGA>();
|
||||
var bussinessLogic = host.Services.GetRequiredService<BusinessLogic>();
|
||||
var bussinessLogic = host.Services.GetRequiredService<ObtencionDatosDga>();
|
||||
var apiService = host.Services.GetRequiredService<ApiService>();
|
||||
|
||||
await bussinessLogic.Run();
|
||||
await bussinessLogic.ObtenerDatosDga();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,10 +46,10 @@ namespace Recuperacion_DGA
|
|||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
services.AddSingleton<IConfiguration>(configuration);
|
||||
services.AddScoped<MedicionScadaRepository>();
|
||||
services.AddScoped<MedicionDGARepository>();
|
||||
services.AddScoped<EnvioDGA>();
|
||||
services.AddHttpClient<RegistrarMedicion>();
|
||||
services.AddScoped<LogMedicionScadaRepository>();
|
||||
services.AddScoped<LogEnvioRepository>();
|
||||
})
|
||||
.Build();
|
||||
|
||||
|
|
15
SHARED/DTO/Envios_DGA/ApiResponse.cs
Normal file
15
SHARED/DTO/Envios_DGA/ApiResponse.cs
Normal file
|
@ -0,0 +1,15 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class ApiResponse<T>
|
||||
{
|
||||
public string? Status { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public T? Data { get; set; }
|
||||
}
|
||||
}
|
27
SHARED/DTO/Envios_DGA/DatoDGA.cs
Normal file
27
SHARED/DTO/Envios_DGA/DatoDGA.cs
Normal file
|
@ -0,0 +1,27 @@
|
|||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class DatoDGA
|
||||
{
|
||||
public int ID { get; set; }
|
||||
|
||||
public string? CODIGO_DGA { get; set; }
|
||||
|
||||
public string? MACRO { get; set; }
|
||||
|
||||
public string? SENSOR { get; set; }
|
||||
|
||||
public string? CAUDAL { get; set; }
|
||||
|
||||
public string? TOTALIZADOR_CAUDAL { get; set; }
|
||||
|
||||
public DateTime? FECHA_MEDICION_CAUDAL { get; set; }
|
||||
|
||||
public string? NIVEL_FREATICO_DEL_POZO { get; set; }
|
||||
|
||||
public DateTime? FECHA_MEDICION_NIVEL { get; set; }
|
||||
|
||||
public string? TIPO_EMPRESA { get; set; }
|
||||
|
||||
public int ENVIADO { get; set; } = 0;
|
||||
}
|
||||
}
|
18
SHARED/DTO/Envios_DGA/DatoDGATemporal.cs
Normal file
18
SHARED/DTO/Envios_DGA/DatoDGATemporal.cs
Normal file
|
@ -0,0 +1,18 @@
|
|||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class DatoDGATemporal
|
||||
{
|
||||
public int ID { get; set; }
|
||||
public string? CODIGO_DGA { get; set; }
|
||||
|
||||
public string? CAUDAL { get; set; }
|
||||
|
||||
public string? TOTALIZADOR_CAUDAL { get; set; }
|
||||
|
||||
public DateTime? FECHA_MEDICION_CAUDAL { get; set; }
|
||||
|
||||
public string? NIVEL_FREATICO_DEL_POZO { get; set; }
|
||||
|
||||
public string? TIPO_EMPRESA { get; set; }
|
||||
}
|
||||
}
|
12
SHARED/DTO/Envios_DGA/LogMedicionEnvio.cs
Normal file
12
SHARED/DTO/Envios_DGA/LogMedicionEnvio.cs
Normal file
|
@ -0,0 +1,12 @@
|
|||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class LogMedicionEnvio
|
||||
{
|
||||
public string ESTADO_ENVIO { get; set; } = string.Empty;
|
||||
public string? JSON_ENVIO { get; set; }
|
||||
public string? JSON_RESPUESTA { get; set; }
|
||||
public string? COMPROBANTE { get; set; }
|
||||
public DateTime FECHA_ENVIO { get; set; }
|
||||
public int ID_DGA_DATO { get; set; }
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class LogMedicionScada
|
||||
{
|
||||
public string EstadoEnvio { get; set; }
|
||||
public string JsonEnviado { get; set; }
|
||||
public string JsonRecibido { get; set; }
|
||||
public string Comprobante { get; set; }
|
||||
public DateTime FechaEnvio { get; set; }
|
||||
public long IdMedicionSmartscadaOperacion { get; set; }
|
||||
}
|
||||
}
|
|
@ -1,28 +0,0 @@
|
|||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class MedicionScada
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Code { get; set; }
|
||||
|
||||
public DateTime? DateOrigen { get; set; }
|
||||
|
||||
public DateTime? DateMedicionSup { get; set; }
|
||||
|
||||
public decimal? Caudal { get; set; }
|
||||
|
||||
public decimal? Altura { get; set; }
|
||||
|
||||
public DateTime? DateMedicionSub { get; set; }
|
||||
|
||||
public decimal? Totalizador { get; set; }
|
||||
|
||||
public decimal? Caudalsub { get; set; }
|
||||
|
||||
public decimal? Nivel { get; set; }
|
||||
public DateTime? FechaEnvio { get; set; }
|
||||
public int Enviado { get; set; }
|
||||
public string? tipo_empresa { get; set; }
|
||||
public string? nivelFreaticoDelPozo { get; set; }
|
||||
}
|
||||
}
|
|
@ -2,24 +2,24 @@
|
|||
{
|
||||
public class MedicionSubterraneaRequest
|
||||
{
|
||||
public Autenticacion Autenticacion { get; set; }
|
||||
public Medicion MedicionSubterranea { get; set; }
|
||||
public Autenticacion Autenticacion { get; set; } = new();
|
||||
public Medicion MedicionSubterranea { get; set; } = new();
|
||||
}
|
||||
|
||||
public class Autenticacion
|
||||
{
|
||||
public string Password { get; set; }
|
||||
public string RutEmpresa { get; set; }
|
||||
public string RutUsuario { get; set; }
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public string RutEmpresa { get; set; } = string.Empty;
|
||||
public string RutUsuario { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class Medicion
|
||||
{
|
||||
public string Caudal { get; set; }
|
||||
public string FechaMedicion { get; set; }
|
||||
public string HoraMedicion { get; set; }
|
||||
public string NivelFreaticoDelPozo { get; set; }
|
||||
public string Totalizador { get; set; }
|
||||
public string? Caudal { get; set; }
|
||||
public string? FechaMedicion { get; set; }
|
||||
public string? HoraMedicion { get; set; }
|
||||
public string? NivelFreaticoDelPozo { get; set; }
|
||||
public string? Totalizador { get; set; }
|
||||
public string? TipoEmpresa { get; set; }
|
||||
|
||||
}
|
||||
|
|
13
SHARED/DTO/Envios_DGA/MedicionSubterraneaResponse.cs
Normal file
13
SHARED/DTO/Envios_DGA/MedicionSubterraneaResponse.cs
Normal file
|
@ -0,0 +1,13 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Shared.DTO.Envios_DGA
|
||||
{
|
||||
public class MedicionSubterraneaResponse
|
||||
{
|
||||
public string? NumeroComprobante { get; set; }
|
||||
}
|
||||
}
|
15
SHARED/DTO/Integracion_DGA/DGAInsert.cs
Normal file
15
SHARED/DTO/Integracion_DGA/DGAInsert.cs
Normal file
|
@ -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; }
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
namespace Shared.DTO.Integracion_DGA;
|
||||
|
||||
public partial class DgaMacroResultado
|
||||
{
|
||||
public string TagName { get; set; } = null!;
|
||||
|
||||
public DateTime TimeStamp { get; set; }
|
||||
|
||||
public double? Value { get; set; }
|
||||
|
||||
public string? Quality { get; set; }
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
namespace Shared.DTO.Integracion_DGA;
|
||||
|
||||
public partial class DgaMacroResultadoSupFluj
|
||||
{
|
||||
public string TagName { get; set; } = null!;
|
||||
|
||||
public DateTime TimeStamp { get; set; }
|
||||
|
||||
public double? Value { get; set; }
|
||||
|
||||
public string? Quality { get; set; }
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
namespace Shared.DTO.Integracion_DGA;
|
||||
|
||||
public partial class DgaMacroResultadoSupFlujSuma
|
||||
{
|
||||
public string TagName { get; set; } = null!;
|
||||
|
||||
public DateTime TimeStamp { get; set; }
|
||||
|
||||
public double? Value { get; set; }
|
||||
|
||||
public string? Quality { get; set; }
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
namespace Shared.DTO.Integracion_DGA;
|
||||
|
||||
public partial class DgaSensorResultado
|
||||
{
|
||||
public string TagName { get; set; } = null!;
|
||||
|
||||
public DateTime TimeStamp { get; set; }
|
||||
|
||||
public double? Value { get; set; }
|
||||
|
||||
public string? Quality { get; set; }
|
||||
}
|
14
SHARED/DTO/LogProceso.cs
Normal file
14
SHARED/DTO/LogProceso.cs
Normal file
|
@ -0,0 +1,14 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Shared.DTO
|
||||
{
|
||||
public class LogProceso
|
||||
{
|
||||
public string NombreProceso { get; set; } = string.Empty;
|
||||
public DateTime FechaEjecucion { get; set; }
|
||||
}
|
||||
}
|
39
SHARED/Helper/ConsoleLoggerHelper.cs
Normal file
39
SHARED/Helper/ConsoleLoggerHelper.cs
Normal file
|
@ -0,0 +1,39 @@
|
|||
using System;
|
||||
|
||||
namespace Shared.Helper
|
||||
{
|
||||
public static class ConsoleLoggerHelper
|
||||
{
|
||||
public static void WriteLineAndLogInfo(string msj, ConsoleColor? color = null)
|
||||
{
|
||||
if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value))
|
||||
{
|
||||
Console.ForegroundColor = color.Value;
|
||||
Console.WriteLine(msj);
|
||||
Console.ResetColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(msj);
|
||||
}
|
||||
|
||||
FileLoggerHelper.LogInformation(msj);
|
||||
}
|
||||
|
||||
public static void WriteLineAndLogEventoAsync(string evento, string proceso, string operacion = "", ConsoleColor? color = null)
|
||||
{
|
||||
if (color.HasValue && Enum.IsDefined(typeof(ConsoleColor), color.Value))
|
||||
{
|
||||
Console.ForegroundColor = color.Value;
|
||||
Console.WriteLine(proceso);
|
||||
Console.ResetColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(proceso);
|
||||
}
|
||||
|
||||
FileLoggerHelper.LogInformation(proceso);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,4 @@
|
|||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
using Shared.DTO.VariablesEntorno;
|
||||
|
||||
|
@ -10,7 +8,7 @@ namespace Shared.Helper
|
|||
{
|
||||
public static void ConfigureLogger(IConfiguration configuration)
|
||||
{
|
||||
var logFilePath = configuration.GetSection("Logging:LogFile:Path").Value;
|
||||
var logFilePath = configuration.GetSection("Logging:LogFile:Path").Value ?? "";
|
||||
var logFileFullPath = Path.Combine(Directory.GetCurrentDirectory(), logFilePath);
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
|
@ -28,31 +26,5 @@ namespace Shared.Helper
|
|||
{
|
||||
Log.Error(ex, message);
|
||||
}
|
||||
|
||||
public static async Task<bool> InsertarLogsAsync(string evento, string proceso, string operacion)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var connection = new SqlConnection(BdConexion.StringConnection);
|
||||
await connection.OpenAsync();
|
||||
|
||||
string sql = @"INSERT INTO DGA_LOGS_REGISTROS_ENVIOS (evento, proceso, operacion)
|
||||
VALUES (@evento, @proceso, @operacion)";
|
||||
|
||||
await connection.ExecuteAsync(sql, new
|
||||
{
|
||||
evento,
|
||||
proceso,
|
||||
operacion
|
||||
});
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LogError("Error al insertar logs", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,8 +7,6 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.66" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.6" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
|
|
Loading…
Add table
Reference in a new issue