diff --git a/Microservicios/MsUsuarios/Context/ModelContext.cs b/Microservicios/MsUsuarios/Context/ModelContext.cs index f9f9b50..8e5decb 100644 --- a/Microservicios/MsUsuarios/Context/ModelContext.cs +++ b/Microservicios/MsUsuarios/Context/ModelContext.cs @@ -76,6 +76,8 @@ namespace MSAdminUsuarios.Context .HasName("PERFILESMS_PK"); entity.ToTable("PERFILESMS"); + + entity.Property(e => e.TX_UUID_PFL).HasMaxLength(40); }); @@ -86,7 +88,7 @@ namespace MSAdminUsuarios.Context entity.ToTable("PERFILESPORUSUARIO"); - entity.Property(e => e.TX_UUID_PFLXUSU).HasMaxLength(40); + entity.Property(e => e.TX_UUID_USUMS).HasMaxLength(40); }); diff --git a/Microservicios/MsUsuarios/Context/PERFIL.cs b/Microservicios/MsUsuarios/Context/PERFIL.cs index a002578..2491aed 100644 --- a/Microservicios/MsUsuarios/Context/PERFIL.cs +++ b/Microservicios/MsUsuarios/Context/PERFIL.cs @@ -10,6 +10,7 @@ namespace MSAdminUsuarios.Context public string? TX_PERFIL_PFL { get; set; } public int? BL_ESTADO_PFL { get; set; } = 1; public int? NU_ROL_PFL { get; set; } + public string? TX_UUID_PFL { get; set; } } } diff --git a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs index f13dbfd..f4cf927 100644 --- a/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs +++ b/Microservicios/MsUsuarios/Context/PERFILPORUSUARIO.cs @@ -9,7 +9,7 @@ namespace MSAdminUsuarios.Context public string? TX_FKDOC_USUMS { get; set; } public int? NU_FK_PFL { get; set; } public int? BL_ESTADO_PFLXUSU { get; set; } = 1; - public string? TX_UUID_PFLXUSU { get; set; } + public string? TX_UUID_USUMS { get; set; } } } diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs index 9e1a6a4..b86f9b0 100644 --- a/Microservicios/MsUsuarios/Controllers/PerfilesController.cs +++ b/Microservicios/MsUsuarios/Controllers/PerfilesController.cs @@ -39,6 +39,13 @@ namespace MSAdminUsuarios.Controllers if (guardado == null) return ValidationProblem(); + if (guardado.TX_UUID_PFL == null) + { + Guid uuid = Guid.NewGuid(); + var UUID = uuid.ToString(); + guardado.TX_UUID_PFL = UUID; + } + _context.PERFILESMs.Add(guardado); await _context.SaveChangesAsync(); return Ok(); diff --git a/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs index 98e1a3b..0f1cff8 100644 --- a/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs +++ b/Microservicios/MsUsuarios/Controllers/PerfilesPorUsuarioController.cs @@ -53,7 +53,7 @@ namespace MSAdminUsuarios.Controllers var count = 0; // Se cambia a estado 0 todos los perfiles por usuario existentes - var existe_plfxusu = _context.PERFILESPORUSUARIOs.Where(x => x.BL_ESTADO_PFLXUSU == 1 && x.TX_FKDOC_USUMS == guardar[0].TX_FKDOC_USUMS).ToList(); + var existe_plfxusu = _context.PERFILESPORUSUARIOs.Where(x => x.BL_ESTADO_PFLXUSU == 1 && x.TX_UUID_USUMS == guardar[0].TX_UUID_USUMS).ToList(); foreach (var cu in existe_plfxusu) { @@ -68,7 +68,7 @@ namespace MSAdminUsuarios.Controllers //Se comprueba existencia de cada pxu en base de datos var existe_pxu = (from dm in _context.PERFILESPORUSUARIOs where dm.NU_FK_PFL == pxu.NU_FK_PFL - && dm.TX_FKDOC_USUMS == pxu.TX_FKDOC_USUMS + && dm.TX_UUID_USUMS == pxu.TX_UUID_USUMS select dm).ToList(); if (existe_pxu.Count() > 0) diff --git a/Microservicios/MsUsuarios/Controllers/UsuariosController.cs b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs index 5814db8..6752448 100644 --- a/Microservicios/MsUsuarios/Controllers/UsuariosController.cs +++ b/Microservicios/MsUsuarios/Controllers/UsuariosController.cs @@ -8,6 +8,11 @@ using Microsoft.EntityFrameworkCore; using System.Linq; using Microsoft.IdentityModel.Tokens; using RabbitMQ.Client; +using Newtonsoft.Json; +using System.Threading.Channels; +using MSAdminUsuarios.Dto.Externos.MsAgendaMedica; +using static MSAdminUsuarios.Utils.RabbitMQService; +using MSAdminUsuarios.Utils; namespace MSAdminUsuarios.Controllers { @@ -17,11 +22,12 @@ namespace MSAdminUsuarios.Controllers { private readonly ModelContext _context; private readonly Encripter _encript = new(); - //private readonly IModel _channel; + private readonly IModel _channel; - public UsuariosController(ModelContext context) + public UsuariosController(ModelContext context, IModel channel) { _context = context; + _channel = channel; } //public UsuariosController(ModelContext context, IModel channel) //{ @@ -208,7 +214,7 @@ namespace MSAdminUsuarios.Controllers Guid uuid = Guid.NewGuid(); var UUID = uuid.ToString(); usuario.TX_UUID_USUMS = UUID; - } + } _context.USUARIOSMs.Add(usuario); await _context.SaveChangesAsync(); @@ -284,6 +290,41 @@ namespace MSAdminUsuarios.Controllers _context.USUARIOSMs.Update(existe); _context.SaveChanges(); + /* + * 1. Perfiles del usuario + * 2. Buscar el perfil de medico + * 3. Si existe la relacion + * 3.1. Se hace la actualizacion de datos + * + */ + + List perfilesUsuario = this._context.PERFILESPORUSUARIOs.Where(pxu => pxu.TX_UUID_USUMS == existe.TX_UUID_USUMS).ToList(); + + if (perfilesUsuario.Count > 0 && perfilesUsuario.Exists(pxu => pxu.NU_FK_PFL == 1)) + { + using (_channel) + { + var medico = new MedicoDto() + { + TX_UUID_MDC = existe.TX_UUID_USUMS, + TX_LUGARESATEN_MDC = existe.TX_SEDES_USUMS + }; + + string jsonMedico = JsonConvert.SerializeObject(medico); + + string exchange = MQExchanges.AgendaMedica; + + // Publish Usuario + RabbitMQMessages.PublishToMessageQueue( + channel: _channel, + exchange: exchange, + routingKey: $"{exchange}.{MQueues.medico}.patch", + message: jsonMedico + ); + } + + } + _errorModel.error = false; _errorModel.cuerpo.Add("Usuario actualizado."); dbContextTransaction.Commit(); diff --git a/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs b/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs new file mode 100644 index 0000000..3e83a29 --- /dev/null +++ b/Microservicios/MsUsuarios/Dto/Externos/MsAgendaMedica/MedicoDto.cs @@ -0,0 +1,31 @@ +namespace MSAdminUsuarios.Dto.Externos.MsAgendaMedica +{ + public class MedicoDto + { + public int? NU_TIPOID_MDC { get; set; } + public string TX_DOCUMENTO_MDC { get; set; } = null!; + public string? TX_REGPROF_MDC { get; set; } + public string? TX_CODIGO_MDC { get; set; } + public int? NU_CARGO_MDC { get; set; } + public int? NU_TIPOPROF_MDC { get; set; } + public string? TX_PRINOMBRE_MDC { get; set; } + public string? TX_SEGNOMBRE_MDC { get; set; } + public string? TX_PRIAPELLIDO_MDC { get; set; } + public string? TX_SEGAPELLIDO_MDC { get; set; } + public string? TX_DIRECCION_MDC { get; set; } + public string? TX_EMAIL_MDC { get; set; } + public string? TX_TELEFONO_MDC { get; set; } + public string? NU_CELULAR_MDC { get; set; } + public int? NU_MODCONTRATACION_MDC { get; set; } + public string? TX_ESPECIALIDAD_MDC { get; set; } + public int? BL_ADSCRITO_MDC { get; set; } + public int? BL_PERCITAWEB_MDC { get; set; } + public int? BL_ESTADO_MDC { get; set; } + public int? NU_MAXCITASEXTRA_MDC { get; set; } + public string? TX_GRUPOSCUPS_MDC { get; set; } + public string? CL_AGENDA_MDC { get; set; } + public string? TX_LUGARESATEN_MDC { get; set; } + public string? TX_UUID_MDC { get; set; } + + } +} diff --git a/Microservicios/MsUsuarios/Utils/GenericTools.cs b/Microservicios/MsUsuarios/Utils/GenericTools.cs new file mode 100644 index 0000000..6a55256 --- /dev/null +++ b/Microservicios/MsUsuarios/Utils/GenericTools.cs @@ -0,0 +1,87 @@ +using System.Linq.Expressions; + +namespace MSAdminUsuarios.Utils +{ + public static class GenericTools + { + /// + /// Permite clonar los valores de un objeto recorriendo cada parámetro + /// (,,). + /// + /// Objeto el cual se va a leer sus propiedades y valores + /// Objeto el cual se va a ESCRIBIR los valores del origen basado en el nombre de la propiedad. + /// Lista con nombres de propiedades a excluir de la copia + public static void CloneObj(T origin, T destiny, params Expression>[] exceptions) where T : class + { + var destinyProps = typeof(T).GetProperties(); + var exceptionProps = new HashSet(); + if (exceptions != null) + { + foreach (var exception in exceptions) + { + if (exception.Body is MemberExpression memberExpression) + { + exceptionProps.Add(memberExpression.Member.Name); + } + } + } + + foreach (var prop in typeof(T).GetProperties()) + { + var originName = prop.Name; + if (exceptionProps.Contains(originName)) + continue; + + for (int i = 0; i < destinyProps.Length; i++) + { + if (destinyProps[i].Name == originName) + { + destinyProps[i].SetValue(destiny, prop.GetValue(origin, null)); + i = destinyProps.Length + 1; + } + } + } + } + + /// + /// Permite tomar parcialmente la información de un obejto Origen, validar si existe en el destino y si es diferente de nulo, para setearle el valor asignado + /// (,,). + /// + /// Objeto el cual se va a leer sus propiedades y valores + /// Objeto el cual se va a ESCRIBIR los valores del origen basado en el nombre de la propiedad. + /// Lista con nombres de propiedades a excluir de la copia + public static void ClonePartialObj(TFrom origin, TTo destiny, params Expression>[] exceptions) where TTo : class + { + var destinyProps = typeof(TTo).GetProperties(); + var exceptionProps = new HashSet(); + if (exceptions != null) + { + foreach (var exception in exceptions) + { + if (exception.Body is MemberExpression memberExpression) + { + exceptionProps.Add(memberExpression.Member.Name); + } + } + } + + foreach (var prop in typeof(TFrom).GetProperties()) + { + var originName = prop.Name; + var originValue = prop.GetValue(origin, null); + if (exceptionProps.Contains(originName)) + continue; + + for (int i = 0; i < destinyProps.Length; i++) + { + if (destinyProps[i].Name == originName && originValue != null) + { + destinyProps[i].SetValue(destiny, originValue); + i = destinyProps.Length + 1; + } + } + } + } + + } +} diff --git a/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs b/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs new file mode 100644 index 0000000..0a00645 --- /dev/null +++ b/Microservicios/MsUsuarios/Utils/RabbitMQMessages.cs @@ -0,0 +1,20 @@ +using RabbitMQ.Client; +using System.Text; + +namespace MSAdminUsuarios.Utils +{ + public static class RabbitMQMessages + { + public static void PublishToMessageQueue(IModel channel, string exchange, string routingKey, string message) + { + var body = Encoding.UTF8.GetBytes(message); + + channel.BasicPublish( + exchange: exchange, + routingKey: routingKey, + basicProperties: null, + body: body + ); + } + } +} diff --git a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs index 4ccd70e..947c61e 100644 --- a/Microservicios/MsUsuarios/Utils/RabbitMQService.cs +++ b/Microservicios/MsUsuarios/Utils/RabbitMQService.cs @@ -12,17 +12,53 @@ using System.Text; namespace MSAdminUsuarios.Utils { + public readonly struct MQExchanges + { + public static readonly string AgendaMedica = "MsAgendaMedica"; + public static readonly string Usuarios = "MSAdminUsuarios"; + } + + public readonly struct MQueues + { + public static readonly string medico = "UsuarioMedico"; + public static readonly string PerfilesPorUsuario = "PerfilesPorUsuario"; + public static readonly string Usuarios = "Usuarios"; + public static readonly string FirmaUsuario = $"{Usuarios}.Firma"; + + } + public class MsComunicadoresModel + { + public string exchange { get; set; } = ""; + public List queues { get; set; } = new(); + } public static class RabbitMQService { private static string[] _queues = Array.Empty(); private static string _exchange = "MSAdminUsuarios"; + private static string Exchange + { + get { return _exchange; } + set { _exchange = value; } + } + + private static readonly MsComunicadoresModel ExchangePrincipal = new() + { + exchange = Exchange, + queues = { MQueues.PerfilesPorUsuario, MQueues.Usuarios } + + }; + + private static readonly List ListaExchanges = new() { + ExchangePrincipal, + new() { + exchange = MQExchanges.AgendaMedica, + queues = { MQueues.medico } + } + }; public static IModel GetRabbitMQChannel(IServiceProvider serviceProvider, string projectName) { - //var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog()); - //var logger = loggerFactory.CreateLogger("Rabbit1"); - var connection = serviceProvider.GetService(); if (connection == null) @@ -32,45 +68,35 @@ namespace MSAdminUsuarios.Utils //Declare exchange if it doesnt already exist var exchangeName = projectName; - _exchange = exchangeName; + Exchange = exchangeName; - - channel.ExchangeDeclare( - exchange: exchangeName, - type: ExchangeType.Topic, - durable: true, - autoDelete: false, - arguments: null - ); - - _queues = new string[] - { - $"{exchangeName}.PerfilesPorUsuario", - $"{exchangeName}.Usuarios" - }; - - foreach (var queue in _queues) - { - channel.QueueDeclare( - queue: queue, + ListaExchanges.ForEach(ex => { + channel.ExchangeDeclare( + exchange: ex.exchange, + type: ExchangeType.Topic, durable: true, - exclusive: false, autoDelete: false, arguments: null ); - channel.QueueBind( - queue: queue, - exchange: exchangeName, - routingKey: $"{queue}.*" - ); - } + ex.queues.ForEach(q => { + string queue = $"{ex.exchange}.{q}"; - channel.QueueBind( - queue: $"{exchangeName}.Usuarios", - exchange: exchangeName, - routingKey: $"{exchangeName}.Usuarios.*.*" - ); + channel.QueueDeclare( + queue: queue, + durable: true, + exclusive: false, + autoDelete: false, + arguments: null + ); + + channel.QueueBind( + queue: queue, + exchange: ex.exchange, + routingKey: $"{queue}.*" + ); + }); + }); return channel; } @@ -80,46 +106,32 @@ namespace MSAdminUsuarios.Utils RabbitMQConfig mqConfig = builder.Configuration.GetSection("RabbitMQConfig").Get(); var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().AddEventLog()); - try + //var logger = loggerFactory.CreateLogger("Rabbit2"); + //logger.LogInformation("Inicia Rabbitmq con"); + + ConnectionFactory factory = new() { - //var logger = loggerFactory.CreateLogger("Rabbit2"); - //logger.LogInformation("Inicia Rabbitmq con"); - - ConnectionFactory factory = new() - { - HostName = mqConfig.HostName, - UserName = mqConfig.UserName, - Password = mqConfig.Password, - }; - - IConnection connection = factory.CreateConnection(); - IModel channel = connection.CreateModel(); - - EventingBasicConsumer consumer = new(channel); - - consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; - - List queues = new() - { - $"{projectName}.PerfilesPorUsuario", - $"{projectName}.Usuarios", + HostName = mqConfig.HostName, + UserName = mqConfig.UserName, + Password = mqConfig.Password, }; - foreach (var queue in queues) - { - channel.BasicConsume( - queue: queue, - autoAck: false, - consumer: consumer - ); - } - } - catch (Exception ex) - { + IConnection connection = factory.CreateConnection(); + IModel channelReceptor = connection.CreateModel(); - Console.WriteLine(ex.Message); + EventingBasicConsumer consumer = new(channelReceptor); + + consumer.Received += RabbitMQService.ConsumeRabbitMQEvent; + + + foreach (var queue in ExchangePrincipal.queues) + { + channelReceptor.BasicConsume( + queue: $"{ExchangePrincipal.exchange}.{queue}", + autoAck: false, + consumer: consumer + ); } - } @@ -191,7 +203,7 @@ namespace MSAdminUsuarios.Utils try { - var UsuariosCtrl = new UsuariosController(context); + var UsuariosCtrl = new UsuariosController(context, model); if (controller[2] == "post") { var data = JsonConvert.DeserializeObject(message);