880 lines
41 KiB
C#
880 lines
41 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Data;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.ServiceProcess;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Timers;
|
|
using Ultimus.Utilitarios;
|
|
using System.Configuration.Install;
|
|
using System.Reflection;
|
|
using System.Configuration;
|
|
using ULA.Cathay.CreditoModel.Credito;
|
|
using ULA.Cathay.CreditoModel.StoreProcedures;
|
|
using System.Data.Entity;
|
|
using Ultimus.Interfaces;
|
|
using Ultimus.Interfaces.UltimusIntegration;
|
|
using ULA.Cathay.CreditoModel.DAL.Credito;
|
|
using ULA.Cathay.RenovacionLineas.IntegracionesSAP;
|
|
using Newtonsoft.Json;
|
|
using ULA.Cathay.CreditoModel.DAL.CorporativoDatosRecientes;
|
|
using ULA.Cathay.CreditoModel.CorporativoDatosRecientes;
|
|
using Ultimus.Interfaces.UltimusForm;
|
|
using ULA.Cathay.CreditoModel.Entidades;
|
|
|
|
namespace ULA.Cathay.RenovacionLineas
|
|
{
|
|
public partial class ServicioRenovacionLineas : ServiceBase
|
|
{
|
|
private UltimusLogs Logs = new UltimusLogs("ServicioRenovacionLineas");
|
|
private Timer tmTimer = new Timer(15000);
|
|
private bool IsStillExecutionTime = false;
|
|
Int32 timeOutQuery = 60;
|
|
|
|
public ServicioRenovacionLineas()
|
|
{
|
|
InitializeComponent();
|
|
this.tmTimer.Elapsed += new System.Timers.ElapsedEventHandler(tmTimer_Elapsed);
|
|
|
|
}
|
|
|
|
static void Main(string[] args)
|
|
{
|
|
if (Environment.UserInteractive)
|
|
{
|
|
string parameter = string.Concat(args);
|
|
switch (parameter)
|
|
{
|
|
case "--install":
|
|
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
|
|
break;
|
|
case "--uninstall":
|
|
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
|
|
break;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ServiceBase[] ServicesToRun;
|
|
ServicesToRun = new ServiceBase[]
|
|
{
|
|
new ServicioRenovacionLineas()
|
|
};
|
|
ServiceBase.Run(ServicesToRun);
|
|
}
|
|
|
|
}
|
|
|
|
protected override void OnStart(string[] args)
|
|
{
|
|
try
|
|
{
|
|
Logs.Trace("servicio iniciado");
|
|
|
|
decimal intervalo = decimal.Parse(ConfigurationManager.AppSettings["TimerInterval"].ToString());
|
|
Logs.Trace("el intervalo de tiempo configurado " + intervalo + " horas");
|
|
|
|
intervalo = intervalo > 24 ? 24 : intervalo;
|
|
tmTimer.Interval = (double)(3600000 * intervalo);
|
|
Logs.Trace("el intervalo de tiempo para verificar la hora y el dia asignado es cada " + intervalo + " horas");
|
|
|
|
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["TimeOutQuery"]) ||
|
|
!Int32.TryParse(ConfigurationManager.AppSettings["TimeOutQuery"].ToString(), out timeOutQuery))
|
|
{
|
|
timeOutQuery = 180;
|
|
Logs.Trace("se establece por defecto tiempo de time out a consulta de DB en :" + timeOutQuery + "segundos");
|
|
}
|
|
else
|
|
Logs.Trace("se establece tiempo de time out a consulta de DB en :" + timeOutQuery + "segundos");
|
|
|
|
|
|
tmTimer.Start();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
Stop(); //si revienta debe detener el servicio
|
|
}
|
|
}
|
|
|
|
protected override void OnContinue()
|
|
{
|
|
base.OnContinue();
|
|
tmTimer.Start();
|
|
}
|
|
|
|
protected override void OnPause()
|
|
{
|
|
base.OnPause();
|
|
tmTimer.Stop();
|
|
}
|
|
|
|
protected override void OnStop()
|
|
{
|
|
// TODO: Add code here to perform any tear-down necessary to stop your service.
|
|
base.OnStop();
|
|
Logs.Trace("servicio detenido");
|
|
tmTimer.Stop();
|
|
}
|
|
|
|
protected override void OnShutdown()
|
|
{
|
|
base.OnShutdown();
|
|
tmTimer.Stop();
|
|
}
|
|
|
|
private void tmTimer_Elapsed(object sender, ElapsedEventArgs e)
|
|
{
|
|
if (IsTime())//verifica si es la hora de ejecutar la revision
|
|
{
|
|
if (!IsStillExecutionTime)//impide ejecutar mas de una revision en la misma hora
|
|
{
|
|
Logs.Trace("Es hora para para ejecutar la revision");
|
|
IsStillExecutionTime = true;
|
|
EjecutarRenovaciones();
|
|
|
|
}
|
|
}
|
|
else
|
|
IsStillExecutionTime = false;
|
|
|
|
}
|
|
|
|
private bool IsTime()
|
|
{//verifica si es la hora y el dia para ejecutar la revision
|
|
|
|
try
|
|
{
|
|
using (CreditoContex db = new CreditoContex())
|
|
{
|
|
ConfiguracionRenovacionLineas configuracion = db.ConfiguracionRenovacionLineas.FirstOrDefault();
|
|
DateTime ToDay = DateTime.Now;
|
|
int LastDayMonth = DateTime.DaysInMonth(ToDay.Year, ToDay.Month);
|
|
|
|
if (configuracion.HoraEjecucion == ToDay.Hour &&
|
|
((configuracion.DiaEjecucion == ToDay.Day && configuracion.DiaEjecucion <= LastDayMonth)
|
|
|| (configuracion.DiaEjecucion > LastDayMonth && ToDay.Day == LastDayMonth)))
|
|
return true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
return false;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public void EjecutarRenovaciones()
|
|
{
|
|
CorreosAutomaticosPendientes Correo = new CorreosAutomaticosPendientes();
|
|
CorreosAutomaticosPendientes CorreoMensual = new CorreosAutomaticosPendientes();
|
|
try
|
|
{
|
|
System.ServiceModel.BasicHttpBinding BindingSAP = new System.ServiceModel.BasicHttpBinding();
|
|
|
|
System.ServiceModel.HttpTransportSecurity security = new System.ServiceModel.HttpTransportSecurity();
|
|
security.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
|
|
|
|
BindingSAP.Security.Transport = security;
|
|
BindingSAP.MaxReceivedMessageSize = int.MaxValue;
|
|
BindingSAP.MaxBufferPoolSize = int.MaxValue;
|
|
|
|
BindingSAP.OpenTimeout = new TimeSpan(0, 2, 0);
|
|
BindingSAP.CloseTimeout = new TimeSpan(0, 2, 0);
|
|
BindingSAP.SendTimeout = new TimeSpan(0, 2, 0);
|
|
BindingSAP.ReceiveTimeout = new TimeSpan(0, 2, 0);
|
|
string Mensaje = string.Empty;
|
|
|
|
System.ServiceModel.EndpointAddress EndpointSAP = new System.ServiceModel.EndpointAddress(new ObtieneParametros().GetValueKeyRegedit("UltimusIntegracionesSAPUrl", false));
|
|
IncidentesActivosClienteDAL mIncidentesActivosCliente = new IncidentesActivosClienteDAL();
|
|
|
|
using (CreditoContex db = new CreditoContex())
|
|
{
|
|
int NumIncidente = 0;
|
|
string TaskID = null;
|
|
List<ControlCartera> Lineas = new List<ControlCartera>();
|
|
DateTime ToDay = DateTime.Now;
|
|
|
|
ConfiguracionRenovacionLineas configuracion = db.ConfiguracionRenovacionLineas.Include(c => c.Procesos).Include(c => c.Etapas).FirstOrDefault();
|
|
Etapas EtapaInicio = configuracion == null || configuracion.Procesos == null ? null : db.Etapas.Where(c => c.IdEtapa == configuracion.Procesos.IdProceso && c.IdEtapa == 1).FirstOrDefault();
|
|
|
|
if (configuracion == null || EtapaInicio == null || configuracion.Etapas == null || configuracion.Procesos == null)
|
|
{
|
|
|
|
Logs.Trace("se requiere la configuración de renovacion de líneas");
|
|
return;
|
|
}
|
|
|
|
Logs.Trace("Inicia busqueda de líneas a renovar");
|
|
|
|
ControlCarteraDAL controlDAL = new ControlCarteraDAL();
|
|
|
|
Lineas = controlDAL.Obtener(null, configuracion.TotalDiasVencimiento, configuracion.RenovarVencidas);
|
|
|
|
if (Lineas == null || Lineas.Count == 0)
|
|
{
|
|
Logs.Trace("No se encontró líneas para renovar");
|
|
return;
|
|
}
|
|
|
|
Logs.Trace(string.Format("Se encontró {0} líneas para renovar", Lineas.Count));
|
|
|
|
using (IntegracionesSAPClient sap = new IntegracionesSAPClient(BindingSAP, EndpointSAP))
|
|
{
|
|
foreach (var linea in Lineas)
|
|
{
|
|
Logs.Trace(string.Format("inicia activación de línea {0}", linea.IdLinea));
|
|
|
|
int? MaxId = null;
|
|
|
|
LineaResponse LineaSAP = sap.ConsultaLinea(linea.IdLinea);
|
|
BpResponse ClienteSAP = LineaSAP != null ? sap.ConsultaBP(LineaSAP.NumCliente, LineaSAP.Identificacion, EnumOperacionesCliente.Ambas, null) : null;
|
|
|
|
if (LineaSAP == null || ClienteSAP == null)
|
|
{
|
|
Logs.Trace(string.Format("No se encontraron datos en SAP para la línea {0}", linea.IdLinea));
|
|
|
|
continue;
|
|
}
|
|
|
|
Logs.Trace(string.Format("para la linea {0} se encontro los siguientes datos: {1}", linea.IdLinea, JsonConvert.SerializeObject(LineaSAP)));
|
|
Logs.Trace(string.Format("para la linea {0} se encontro el cliente con los siguientes datos: {1}", linea.IdLinea, JsonConvert.SerializeObject(ClienteSAP)));
|
|
|
|
Ejecutivo ejecutivo = db.Ejecutivo.Where(c => c.CodigoEjecutivo == ClienteSAP.CodEjecutivoActivo).FirstOrDefault();
|
|
|
|
#region VERIFICA INCIDENTES ACTIVOS
|
|
|
|
using (StoreProceduresCredito sp = new StoreProceduresCredito())
|
|
{
|
|
List<IncidentesActivosCliente> IncidenteActivoCliente = mIncidentesActivosCliente.Obtener(ClienteSAP.Identificacion);
|
|
|
|
if (IncidenteActivoCliente != null && IncidenteActivoCliente.Count > 0)
|
|
{
|
|
var IncienteReciente = IncidenteActivoCliente.FirstOrDefault();
|
|
|
|
//ejecutivo = db.Ejecutivo.Where(c => IncienteReciente.UsuarioCreador.Contains(c.UserId)).FirstOrDefault();
|
|
|
|
var ControlCarteraLinea = db.ControlCartera.AsNoTracking().Where(c => c.IdLinea == linea.IdLinea && c.SolicitudGenerada == true).ToList();
|
|
|
|
var IncidenteActivoLinea = ControlCarteraLinea != null && (from i in IncidenteActivoCliente
|
|
join cc in ControlCarteraLinea
|
|
on i.Incidente equals cc.Incidente
|
|
select i).Any();
|
|
|
|
|
|
|
|
if (IncidenteActivoLinea)
|
|
{
|
|
Mensaje = string.Format("No se puede continuar con la renovación de la línea {0}, ya que hay incidentes activos con este mismo número de línea", linea.IdLinea);
|
|
|
|
//ejecutivo = db.Ejecutivo.Where(c => c.CodigoEjecutivo == ClienteSAP.CodEjecutivoActivo).FirstOrDefault();
|
|
|
|
if (ejecutivo != null)
|
|
{
|
|
Correo.IdCorreo = 0;
|
|
if (ControlCarteraLinea != null)
|
|
{
|
|
var sol = ControlCarteraLinea.Where(x => x.IdSolicitud != null && x.Incidente != null).FirstOrDefault();
|
|
Correo.IdSolicitud = sol != null ? Convert.ToInt32(sol.IdSolicitud) : 0;
|
|
}
|
|
Logs.Trace("CodEjecutivoActivo: " + ClienteSAP.CodEjecutivoActivo);
|
|
Correo.NombreFiltroCorreo = "NotificacionRenovacion";
|
|
Correo.UserID = new Ultimus.Utilitarios.ObtieneParametros().GetValueKeyRegedit("UltimusDomains", false) + "/" + ejecutivo.UserId;
|
|
EnviarCorreoAutomatico(Correo, 0, Mensaje, ejecutivo);
|
|
}
|
|
Logs.Trace(Mensaje);
|
|
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
if (ejecutivo == null)
|
|
{
|
|
Logs.Trace(string.Format("No se puede continuar con la renovación de la línea {0}, ya que el ejecutivos con código {1} no existe en la base de datos.", linea.IdLinea, ClienteSAP.CodEjecutivoActivo));
|
|
continue;
|
|
}
|
|
|
|
#region CreaIncidente
|
|
using (UltimusIntegrationAPIController UltimusIntgration = new UltimusIntegrationAPIController())
|
|
{
|
|
using (UltimusIntegrationClient UltimusClient = new UltimusIntegrationClient(UltimusIntgration.wSHttpBinding, UltimusIntgration.endpointAddress))
|
|
{
|
|
UltimusIncident DataTask = new UltimusIncident();
|
|
string error = "";
|
|
|
|
Logs.Trace("Crear Incidente: UsuarioIniciador:" + configuracion.UsuarioIniciador + " NombreProceso: " + configuracion.Procesos.NombreProceso.Trim() + " DescripcionEtapa: " + EtapaInicio.DescripcionEtapa);
|
|
|
|
if (!UltimusClient.GetTaskByFilters(configuracion.UsuarioIniciador, configuracion.Procesos.NombreProceso.Trim(), EtapaInicio.DescripcionEtapa, 0, out DataTask, out error) || !string.IsNullOrWhiteSpace(error))
|
|
throw new Exception("GetTaskByFilters: no se pudo obtener el taskid para generar los incidentes de renovacion. " + error);
|
|
|
|
TaskID = DataTask.TaskId;
|
|
}
|
|
|
|
|
|
string user = new Ultimus.Utilitarios.ObtieneParametros().GetValueKeyRegedit("UltimusDomains", false) + "/" + ejecutivo.UserId;
|
|
|
|
List<NodeVariables> Variables = new List<NodeVariables>();
|
|
|
|
List<object> EjecutivoAsistenteServicio = new List<object>();
|
|
EjecutivoAsistenteServicio.Add(string.Format("USER:org=Business Organization, user={0}", user));
|
|
EjecutivoAsistenteServicio.Add(string.Format("JFG:org=Business Organization,dept=Cathay OC,jfg=Asistente Servicios"));
|
|
Variables.Add(new NodeVariables()
|
|
{
|
|
NodeName = "TaskData.Global.EjecutivoAsistenteServicio",
|
|
NodeValues = EjecutivoAsistenteServicio
|
|
});
|
|
|
|
|
|
Variables.Add(
|
|
new NodeVariables()
|
|
{
|
|
NodeName = "TaskData.Global.Etapa",
|
|
NodeValue = configuracion.Etapas.DescripcionEtapa
|
|
});
|
|
|
|
Variables.Add(
|
|
new NodeVariables()
|
|
{
|
|
NodeName = "TaskData.Global.CodigoTipoTramite",
|
|
NodeValue = configuracion.CodigoTipoTramite
|
|
});
|
|
|
|
NumIncidente = UltimusIntgration.CompleteTask(configuracion.UsuarioIniciador, TaskID, "", ClienteSAP.Identificacion.Trim() + " | " + linea.NombreCliente.Trim(), Variables);
|
|
|
|
}
|
|
#endregion
|
|
|
|
#region CLIENTE
|
|
var cliente = new Cliente();
|
|
|
|
var ControlCartera = db.ControlCartera.AsNoTracking().Where(c => c.IdLinea == linea.IdLinea).FirstOrDefault();
|
|
|
|
MaxId = db.Cliente.Max(c => (int?)c.IdCliente);
|
|
MaxId = MaxId.HasValue ? MaxId + 1 : 1;
|
|
|
|
cliente.IdCliente = MaxId.Value;
|
|
cliente.IdTipoTramite = configuracion.CodigoTipoTramite;
|
|
cliente.IdClasificacionCliente = ControlCartera.IdClasificacionCliente;
|
|
cliente.IdTipoCliente = ControlCartera.IdTipoCliente;
|
|
cliente.IdTipoIngreso = ControlCartera.IdTipoIngreso;
|
|
cliente.IdTipoIdentificacion = ControlCartera.IdTipoIdentificacion;
|
|
|
|
string NumeroIdentificacion = string.Empty;
|
|
if (ControlCartera.IdTipoCliente == 2)
|
|
NumeroIdentificacion = ClienteSAP.Identificacion.Replace("-", "");
|
|
else
|
|
NumeroIdentificacion = ClienteSAP.Identificacion;
|
|
|
|
cliente.NumeroIdentificacion = NumeroIdentificacion;
|
|
cliente.PrimerNombre = ControlCartera.IdTipoCliente == 1 ? ClienteSAP.Nombre : "";
|
|
cliente.SegundoNombre = null;
|
|
cliente.PrimerApellido = ClienteSAP.PrimerApellido;
|
|
cliente.SegundoApellido = ClienteSAP.SegundoApellido;
|
|
cliente.ClienteesCorporativo = null;
|
|
cliente.SolicitarRequisitosBasicos = null;
|
|
cliente.RazonSocial = ControlCartera.IdTipoCliente == 2 ? ClienteSAP.Nombre : "";
|
|
cliente.CodigoBP = LineaSAP.NumCliente;
|
|
cliente.Contacto = null;
|
|
cliente.Puesto = null;
|
|
cliente.IdEjecutivo = ejecutivo != null ? (int?)ejecutivo.IdEjecutivo : null;
|
|
cliente.ReferenciasCIC = null;
|
|
cliente.ReferenciasCIBERISK = null;
|
|
cliente.ReferenciasCCSS = null;
|
|
cliente.ComentariosCIC = null;
|
|
cliente.ComentariosCIBERISK = null;
|
|
cliente.ComentariosCCSS = null;
|
|
cliente.PatronoGobierno = null;
|
|
cliente.CodigoCiiu = ClienteSAP.CodigoCiiu;
|
|
cliente.CodNivelCapacidadPago = ClienteSAP.CodNivelCapacidadPago;
|
|
cliente.CodigoCategoriaRiesgo = ClienteSAP.CategoriaRiesgo;
|
|
|
|
int CodRiesgoCambiario;
|
|
if (!string.IsNullOrWhiteSpace(ClienteSAP.CodRiesgoCambiario) && int.TryParse(ClienteSAP.CodRiesgoCambiario, out CodRiesgoCambiario))
|
|
cliente.CodRiesgoCambiario = CodRiesgoCambiario;
|
|
|
|
cliente.CodGeneraMonedaExtrangera = ClienteSAP.CodGeneraMonedaExtrangera;
|
|
cliente.CodClasificacionMetodologia = null;
|
|
cliente.UsuarioCreador = configuracion.UsuarioIniciador;
|
|
cliente.FechaCreacion = DateTime.Now;
|
|
|
|
ClienteDAL clienteDAL = new ClienteDAL();
|
|
clienteDAL.InsertarActualizar(cliente);
|
|
|
|
#endregion
|
|
|
|
#region Solicitud
|
|
ULA.Cathay.CreditoModel.Credito.Solicitud solicitud = new CreditoModel.Credito.Solicitud();
|
|
|
|
MaxId = db.Solicitud.Max(c => (int?)c.IdSolicitud);
|
|
MaxId = MaxId.HasValue ? MaxId + 1 : 1;
|
|
|
|
solicitud.IdSolicitud = MaxId.Value;
|
|
solicitud.Incidente = NumIncidente;
|
|
solicitud.Proceso = configuracion.Procesos.NombreProceso;
|
|
solicitud.ConCodeudor = null;
|
|
solicitud.EstadoSolicitud = true;
|
|
solicitud.UsuarioCreador = configuracion.UsuarioIniciador;
|
|
solicitud.FechaCreacion = DateTime.Now;
|
|
solicitud.IdEstadoBandeja = "E";
|
|
|
|
SolicitudDAL solicitudDAL = new SolicitudDAL();
|
|
solicitudDAL.Insertar(solicitud);
|
|
|
|
#endregion
|
|
|
|
#region solicitante
|
|
Solicitante solicitante = new Solicitante();
|
|
|
|
solicitante.IdSolicitud = solicitud.IdSolicitud;
|
|
solicitante.IdCliente = cliente.IdCliente;
|
|
solicitante.IdTipoSolicitante = 1;
|
|
solicitante.EsPrincipal = true;
|
|
solicitante.UsuarioCreador = configuracion.UsuarioIniciador;
|
|
solicitante.FechaCreacion = DateTime.Now;
|
|
if (ControlCartera.IdTipoSolicitante != null)
|
|
solicitante.IdTipoSolicitante = Convert.ToInt32(ControlCartera.IdTipoSolicitante);
|
|
|
|
SolicitanteDAL solicitanteDAL = new SolicitanteDAL();
|
|
|
|
solicitanteDAL.InsertarActualizar(solicitante);
|
|
|
|
#endregion
|
|
|
|
#region oferta
|
|
OfertaDAL ofertaDAL = new OfertaDAL();
|
|
if (ControlCartera.IdTipoCategoria != null)
|
|
{
|
|
ofertaDAL.InsertaActualizarOfertaSolicitud(solicitud.IdSolicitud, Convert.ToInt32(ControlCartera.IdTipoCategoria));
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region gestion
|
|
GestionRenovacionLineas gestion = new GestionRenovacionLineas();
|
|
|
|
gestion.IdSolicitud = solicitud.IdSolicitud;
|
|
gestion.IdLinea = linea.IdLinea;
|
|
gestion.MontoLinea = linea.MontoLinea;
|
|
gestion.IdMoneda = linea.IdMoneda;
|
|
gestion.FechaVencimiento = linea.FechaVencimiento;
|
|
gestion.RenovarCliente = null;
|
|
gestion.FechaDecisionGestion = DateTime.Now;
|
|
gestion.Justificacion = null;
|
|
gestion.GerenciaApruebaRenovacion = null;
|
|
gestion.FechaDecisionGerencia = null;
|
|
gestion.ComentariosGerencia = null;
|
|
|
|
GestionRenovacionLineasDAL gestDAL = new GestionRenovacionLineasDAL();
|
|
gestDAL.InsertarActualizar(gestion);
|
|
#endregion
|
|
|
|
#region control cartera
|
|
linea.IdSolicitud = solicitud.IdSolicitud;
|
|
linea.Incidente = NumIncidente;
|
|
linea.SolicitudGenerada = true;
|
|
linea.FechaIncidente = DateTime.Now;
|
|
|
|
db.Entry(linea).State = System.Data.Entity.EntityState.Modified;
|
|
db.SaveChanges();
|
|
#endregion
|
|
|
|
#region Registra Incidente Activo Cliente
|
|
mIncidentesActivosCliente.InsertarActualizar(new IncidentesActivosCliente
|
|
{
|
|
NumeroIndentificacion = cliente.NumeroIdentificacion,
|
|
IdSolicitud = solicitud.IdSolicitud,
|
|
NombreProceso = solicitud.Proceso,
|
|
UsuarioCreador = configuracion.UsuarioIniciador,
|
|
UltimaEtapaCompletada = EtapaInicio.DescripcionEtapa,
|
|
Incidente = NumIncidente
|
|
});
|
|
#endregion
|
|
|
|
Mensaje = string.Format("Activacion de la renovación de la línea: {1} completado con exito para el cliente {4} con identificación: {0}. incidente{2}, solicitud {3}", ClienteSAP.Identificacion, linea.IdLinea, NumIncidente, solicitud.IdSolicitud, ClienteSAP.Nombre);
|
|
Logs.Trace(Mensaje);
|
|
|
|
#region NotificacionRenovacion
|
|
Correo.IdCorreo = 0;
|
|
Correo.IdSolicitud = solicitud.IdSolicitud;
|
|
Correo.NombreFiltroCorreo = "NotificacionRenovacion";
|
|
Correo.UserID = new Ultimus.Utilitarios.ObtieneParametros().GetValueKeyRegedit("UltimusDomains", false) + "/" + ejecutivo.UserId;
|
|
|
|
Logs.Trace("CodEjecutivoActivo: " + ejecutivo.Correo);
|
|
Logs.Trace("UserID: " + Correo.UserID);
|
|
EnviarCorreoAutomatico(Correo, NumIncidente, Mensaje, ejecutivo);
|
|
#endregion
|
|
|
|
|
|
|
|
#region REGISTRAR RECORDATORIO SEGUIMIENTO
|
|
Logs.Trace("REGISTRAR RECORDATORIO SEGUIMIENTO");
|
|
TiemposEjecucionNotificacionesCompletionTimeDAL Tiempo = new TiemposEjecucionNotificacionesCompletionTimeDAL();
|
|
|
|
DateTime fecha_calculada_notificacion = DateTime.Today;
|
|
Logs.Trace("Fecha Inicio: " + fecha_calculada_notificacion.ToString());
|
|
|
|
DateTime fechavencimiento = DateTime.Today.AddDays(Tiempo.Obtener(EnumTiempos.NotificacionCasosPendientes).Dias);
|
|
Logs.Trace("Fecha Fin: " + fechavencimiento.ToString());
|
|
|
|
int diasabiles = 0;
|
|
|
|
|
|
diasabiles = TotalDiasHabiles(fecha_calculada_notificacion, fechavencimiento);
|
|
fecha_calculada_notificacion = FechaADiasHabiles(DateTime.Today, diasabiles);
|
|
CorreoMensual.FechaCreacion = fecha_calculada_notificacion;
|
|
CorreoMensual.TotalDiasEspera = 0;
|
|
CorreoMensual.UserID = new Ultimus.Utilitarios.ObtieneParametros().GetValueKeyRegedit("UltimusDomains", false) + "/" + ejecutivo.UserId;
|
|
CorreoMensual.NombreFiltroCorreo = "NotificarRecordatorioRenovacionUnMes";
|
|
CorreoMensual.Incident = NumIncidente;
|
|
CorreoMensual.IdSolicitud = solicitud.IdSolicitud;
|
|
Logs.Trace("NombreFiltroCorreo = " + CorreoMensual.NombreFiltroCorreo + " " + "Incident = " + CorreoMensual.Incident.ToString());
|
|
RegistrarCorreoAutomatico(CorreoMensual);
|
|
#endregion
|
|
Logs.Trace(Mensaje);
|
|
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
}
|
|
|
|
}
|
|
|
|
#region EnviarCorreoAutomatico
|
|
public BaseJson EnviarCorreoAutomatico(CorreosAutomaticosPendientes correo, int Incidente, string Notificacion, Ejecutivo ejecutivo, List<BookmarkCorreoJSON> BookmarkExtra = null)
|
|
{
|
|
BaseJson model = new BaseJson();
|
|
FiltroCorreoProcesoJSON filtro = new FiltroCorreoProcesoJSON();
|
|
Procesos ObjProcesos = new Procesos();
|
|
ProcesosDAL ObjProcesosDAL = new ProcesosDAL();
|
|
string error = null;
|
|
UltimusUser UserEmail = null;
|
|
List<UltimusUser> ListaUserEmail = null;
|
|
List<EstructuraOrgChart> ListaEstructuraOC = null;
|
|
|
|
try
|
|
{
|
|
|
|
ObjProcesos = ObjProcesosDAL.Obtener(1);
|
|
|
|
using (CreditoContex db = new CreditoContex())
|
|
{
|
|
|
|
|
|
filtro.Proceso = "Credito";
|
|
filtro.NombreFiltro = "NotificacionRenovacion";
|
|
filtro.CodSolicitud = (long)correo.IdSolicitud;
|
|
filtro.Etapa = "";
|
|
filtro.Incidente = Incidente;
|
|
filtro.UserID = correo.UserID;
|
|
filtro.CC = new List<string>();
|
|
filtro.Destinatario = new List<string>();
|
|
filtro.ListaParametros = new List<ParametrosCorreoJSON>();
|
|
filtro.ListaBookmarks = new List<BookmarkCorreoJSON>();
|
|
filtro.DocumentosAdjuntos = new List<string>();
|
|
|
|
UltimusIntegrationAPIController Binding = new UltimusIntegrationAPIController();
|
|
|
|
using (UltimusIntegrationClient IntegrationClient = new UltimusIntegrationClient(Binding.wSHttpBinding, Binding.endpointAddress))
|
|
{
|
|
IntegrationClient.GetUserInformation(correo.UserID, out UserEmail, out error);
|
|
|
|
switch (correo.NombreFiltroCorreo)
|
|
{
|
|
case "NotificacionRenovacion":
|
|
|
|
Logs.Trace("Inicio de envio de notificacion");
|
|
#region Ejecutivo
|
|
if (ejecutivo != null && !string.IsNullOrEmpty(ejecutivo.Correo))
|
|
filtro.Destinatario.Add(ejecutivo.Correo);
|
|
Logs.Trace(ejecutivo.Correo);
|
|
|
|
#endregion
|
|
|
|
#region Asistente de Servicio
|
|
ListaEstructuraOC = new EstructuraOrgChartDAL().Obtener(EnumRolFuncional.Asistente_Servicios, null);
|
|
|
|
ListaUserEmail = null;
|
|
if (ListaEstructuraOC != null && ListaEstructuraOC.Count > 0)
|
|
{
|
|
foreach (var lista in ListaEstructuraOC)
|
|
{
|
|
if (!string.IsNullOrEmpty(lista.Name))
|
|
{
|
|
ListaUserEmail = ObtenerCorreos(lista.Name, Convert.ToInt32(lista.IdTipoEstructuraOrgChart));
|
|
foreach (UltimusUser Email in ListaUserEmail)
|
|
{
|
|
if (!string.IsNullOrEmpty(Email.EmailAddress))
|
|
filtro.Destinatario.Add(Email.EmailAddress);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
#endregion
|
|
|
|
filtro.ListaBookmarks.Add(new BookmarkCorreoJSON { Nombre = "NOTIFICACION", Valor = Notificacion });
|
|
break;
|
|
}
|
|
|
|
}
|
|
|
|
using (UltimusFormAPIController InterfaceClient = new UltimusFormAPIController())
|
|
filtro = InterfaceClient.EnviarCorreoFiltro(filtro);
|
|
|
|
if (filtro != null && filtro.CodigoRespuesta != null)
|
|
{
|
|
Logs.Trace(!string.IsNullOrEmpty(filtro.CodigoRespuesta) ? filtro.CodigoRespuesta : "");
|
|
Logs.Trace(!string.IsNullOrEmpty(filtro.DescripcionRespuesta) ? filtro.DescripcionRespuesta : "");
|
|
model.CodigoRespuesta = filtro.CodigoRespuesta;
|
|
model.DescripcionRespuesta = filtro.DescripcionRespuesta;
|
|
|
|
}
|
|
else
|
|
{
|
|
Logs.Trace("No se pudo obtener la respuesta del servicio de correos");
|
|
}
|
|
|
|
|
|
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
model.CodigoRespuesta = TipoCodigoRespuesta.ERROR.ToString();
|
|
Logs.Error(ex);
|
|
}
|
|
|
|
return model;
|
|
}
|
|
#endregion
|
|
|
|
#region TotalDiasHabiles
|
|
|
|
public int TotalDiasHabiles(DateTime FechaInicio, DateTime FechaFin)
|
|
{
|
|
int total_dias = 0;
|
|
int total_dias_habiles = 0;
|
|
int total_dias_feriados = 0;
|
|
int total_dias_libres = 0;
|
|
|
|
List<DiasJSON> DiasSemanles = new List<DiasJSON>();
|
|
List<ExclusionDay> DiasFeriados = new List<ExclusionDay>();
|
|
List<DayOfWeek> DiasLibres = new List<DayOfWeek>();
|
|
|
|
try
|
|
{
|
|
FechaInicio = FechaInicio.Date;
|
|
FechaFin = FechaFin.Date;
|
|
|
|
if (FechaFin < FechaInicio || FechaFin == FechaInicio)
|
|
return total_dias_habiles;
|
|
|
|
TimeSpan ts = FechaFin - FechaInicio; // Total duration
|
|
total_dias = ts.Days;
|
|
|
|
#region CALCULA DIAS POR SEMANA
|
|
int total_semanas = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks
|
|
int remainder = (int)(ts.TotalDays % 7); // Number of remaining days
|
|
|
|
foreach (var dia in Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToList())
|
|
{
|
|
int total = total_semanas;
|
|
|
|
int sinceLastDay = (int)(FechaFin.DayOfWeek - dia); // Number of days since last [day]
|
|
if (sinceLastDay < 0) sinceLastDay += 7; // Adjust for negative days since last [day]
|
|
|
|
// If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.
|
|
if (remainder >= sinceLastDay)
|
|
{ total++; }
|
|
|
|
DiasSemanles.Add(new DiasJSON
|
|
{
|
|
Dia = dia,
|
|
Total = total
|
|
});
|
|
}
|
|
#endregion
|
|
|
|
string error;
|
|
UltimusIntegrationAPIController InterfaceClient = new UltimusIntegrationAPIController();
|
|
using (UltimusIntegrationClient client = new UltimusIntegrationClient(InterfaceClient.wSHttpBinding, InterfaceClient.endpointAddress))
|
|
{
|
|
#region DIAS LIBRES
|
|
|
|
List<DayOfWeekJSON> OffDays;
|
|
|
|
if (client.GetOffDays(out OffDays, out error))
|
|
{
|
|
foreach (var item in OffDays)
|
|
{
|
|
DiasLibres.Add((DayOfWeek)item);
|
|
}
|
|
}
|
|
|
|
if (DiasSemanles.Count > 0 && DiasLibres.Count > 0)
|
|
total_dias_libres = DiasSemanles.Where(c => DiasLibres.Contains(c.Dia)).Sum(c => c.Total);
|
|
|
|
#endregion
|
|
|
|
#region DIAS FERIADOS
|
|
if (client.GetExclusionDays(out DiasFeriados, out error))
|
|
{
|
|
foreach (var item in DiasFeriados)
|
|
{
|
|
DateTime DiaFeriado = new DateTime(DateTime.Now.Year, item.Month, item.Day);
|
|
|
|
if (DiaFeriado >= FechaInicio && DiaFeriado <= FechaFin && !DiasLibres.Where(c => c == DiaFeriado.DayOfWeek).Any())
|
|
total_dias_feriados++;
|
|
}
|
|
|
|
}
|
|
#endregion
|
|
}
|
|
|
|
//calcula los dias habiles
|
|
total_dias_habiles = total_dias - total_dias_feriados - total_dias_libres;
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
}
|
|
|
|
return total_dias_habiles;
|
|
}
|
|
#endregion
|
|
|
|
#region FechaADiasHabiles
|
|
public DateTime FechaADiasHabiles(DateTime FechaInicio, int DiasHabiles)
|
|
{
|
|
DateTime FechaCalculada = DateTime.Now;
|
|
int dias_calculados = 0;
|
|
bool CorrectDate = false;
|
|
|
|
try
|
|
{
|
|
if (DiasHabiles == 0)
|
|
{
|
|
FechaCalculada = FechaInicio;
|
|
}
|
|
else
|
|
{
|
|
|
|
while (!CorrectDate)
|
|
{
|
|
FechaCalculada = FechaCalculada.AddDays(DiasHabiles);
|
|
dias_calculados = TotalDiasHabiles(FechaInicio, FechaCalculada);
|
|
|
|
if (dias_calculados == DiasHabiles) CorrectDate = true;
|
|
else if (dias_calculados > DiasHabiles) DiasHabiles++;
|
|
else if (dias_calculados < DiasHabiles) DiasHabiles--;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
}
|
|
|
|
return FechaCalculada;
|
|
}
|
|
#endregion
|
|
|
|
#region RegistrarCorreoAutomatico
|
|
public CorreosAutomaticosPendientes RegistrarCorreoAutomatico(CorreosAutomaticosPendientes Correo)
|
|
{
|
|
Etapas Etapa = new Etapas();
|
|
EtapasDAL EtapasDAL = new EtapasDAL();
|
|
try
|
|
{
|
|
Etapa = EtapasDAL.ObtenerEtapa(EnumEtapas.RE_Gestio_Renovacion);
|
|
Correo.IdEtapa = Etapa.IdEtapa;
|
|
using (CreditoContex db = new CreditoContex())
|
|
{
|
|
//Aplica para los casos en los que no se envia cargada la fecha de creación
|
|
if (Correo.FechaCreacion == DateTime.MinValue || Correo.FechaCreacion == default(DateTime))
|
|
Correo.FechaCreacion = DateTime.Today;
|
|
|
|
int? Next_id = db.CorreosAutomaticosPendientes.Max(t => (int?)t.IdCorreo);
|
|
Correo.IdCorreo = (Next_id == null) ? 1 : Next_id.Value + 1;
|
|
|
|
db.CorreosAutomaticosPendientes.Add(Correo);
|
|
db.SaveChanges();
|
|
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
}
|
|
return Correo;
|
|
}
|
|
#endregion
|
|
|
|
#region ObtenerCorreos
|
|
public List<UltimusUser> ObtenerCorreos(string NameJobFunction, int IdTipoEstructuraOrgChart, string NameGroup = null, string UserName = null)
|
|
{
|
|
List<UltimusUser> respuesta = new List<UltimusUser>();
|
|
UltimusIntegrationAPIController Binding = new UltimusIntegrationAPIController();
|
|
UltimusUser UserEmail = null;
|
|
|
|
string error = null;
|
|
try
|
|
{
|
|
using (UltimusIntegrationClient IntegrationClient = new UltimusIntegrationClient(Binding.wSHttpBinding, Binding.endpointAddress))
|
|
{
|
|
switch (IdTipoEstructuraOrgChart)
|
|
{
|
|
case 1:
|
|
IntegrationClient.GetUserForJobFunction("Business Organization", "Cathay OC", NameJobFunction.Trim(), out UserEmail, out error);
|
|
if (UserEmail != null)
|
|
respuesta.Add(UserEmail);
|
|
break;
|
|
case 2:
|
|
IntegrationClient.GetJobFunctionGroupMembers("Cathay OC", NameJobFunction.Trim(), out respuesta, out error);
|
|
break;
|
|
case 3:
|
|
IntegrationClient.GetGroupUserMembers(NameGroup, out respuesta, out error);
|
|
break;
|
|
default:
|
|
IntegrationClient.GetUserInformation(UserName, out UserEmail, out error);
|
|
if (UserEmail != null)
|
|
respuesta.Add(UserEmail);
|
|
break;
|
|
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logs.Error(ex);
|
|
throw ex;
|
|
}
|
|
return respuesta;
|
|
}
|
|
#endregion
|
|
}
|
|
|
|
public class DiasJSON
|
|
{
|
|
public DayOfWeek Dia { get; set; }
|
|
public string Nombre { get { return Dia.ToString(); } }
|
|
public int Total { get; set; }
|
|
}
|
|
}
|