public List <FileDetail> GetAllFiles(Rutas rutas, string searchPattern, string servicio)
        {
            char criterioSplit = Select_OUT_XML ? '_' : '.';

            List <FileDetail> fileList = new List <FileDetail>();

            foreach (var path in rutas.Paths)
            {
                var files = Directory.GetFiles(String.IsNullOrEmpty(servicio) ? path.Value : rutas.Paths[servicio], searchPattern, SearchOption.TopDirectoryOnly)
                            .Where(file => file.ToUpper().Contains("_OUT.XML") == Select_OUT_XML);           //add bool param (query == b)
                foreach (var filePath in files)
                {
                    var fileName = Path.GetFileName(filePath);
                    //var keyServ = path.Key == "MAT" ? "MATRICULACIÓN" : path.Key;
                    fileList.Add(new FileDetail
                    {
                        Fecha         = GetFileDate(fileName),
                        NombreArchivo = fileName,
                        CodIFI        = fileName.Contains("ofp") ? fileName.Split('-').Last().Split(criterioSplit)[0] : fileName.Split('-')[1],
                        Institucion   = "",
                        Servicio      = String.IsNullOrEmpty(servicio) ? path.Key : servicio,
                        Usuario       = "Admin"
                    });
                }

                if (!String.IsNullOrEmpty(servicio))
                {
                    break;
                }
            }

            return(fileList);
        }
        public ConciliacionSRI()
        {
            fileManager = new SriFileManager();
            //get path from dataBase
            var pathDB = NegFac.ConsultaPathFilesSRIConciliacionFacilitoSwitch();
            var objRes = new ConciliacionManager().XmlToObject("<Datos><Table><Path>Hola</Path></Table></Datos>");

            BASE_URL = string.IsNullOrEmpty(BASE_URL) ? objRes[0].Path : BASE_URL;
            //1. create folder if not exists
            _rutas = fileManager.CreateFolderOrPaths(DateTime.Now.AddDays(ADD_DAYS).ToString("dd/MM/yyyy"), BASE_URL, true);
        }
        public List <FileDetail> GetFilesBy(Rutas rutas, string institucion, string servicio)
        {
            if (String.IsNullOrEmpty(institucion))      //there're two options (service null, service NOT null)
            {
                return(GetAllFiles(rutas, "*.xml", servicio));
            }

            if (!String.IsNullOrEmpty(institucion))    //there're two options (service null, service NOT null)
            {
                return(GetAllFiles(rutas, "*" + institucion + "*.xml", servicio));
            }

            return(new List <FileDetail>());
        }
        public Rutas CreateFolderOrPaths(string fecha, string baseUrl, bool folderToo = true)  // format 30/09/2020
        {
            /*
             *   Las transacciones del viernes se concilian el lunes.
             *   Las transacciones del sábado, domingo y lunes se concilia el martes
             *   Las transacciones de feriados se concilian el siguiente día hábil de conciliación  **
             */

            var today = Convert.ToDateTime(fecha).AddDays(-ConciliacionSRI.ADD_DAYS);

            if (today.DayOfWeek == DayOfWeek.Friday)
            {
                string monday = today.AddDays(3).ToString("dd/MM/yyyy");
                fecha = monday;
            }

            var DateSplited  = fecha.Split('/');
            var DateFormated = DateSplited[2] + DateSplited[1] + DateSplited[0];

            List <string> paths = new List <string>();

            paths.Add(@"CEP\S");
            paths.Add(@"RISE\C");
            paths.Add(@"MAT\M");

            var rutass = new Rutas
            {
                Fecha = fecha.Replace("/", "-")   //presentation Date
            };

            foreach (var folder in paths)
            {
                var absolutePath = baseUrl + folder + DateFormated;
                if (folderToo && !Directory.Exists(absolutePath))
                {
                    Directory.CreateDirectory(absolutePath);
                }

                rutass.Paths.Add(folder.Split('\\')[0], absolutePath);
            }

            return(rutass);
        }
        public void Conciliar(Rutas rutas, List <FileDetail> archivosConciliar, bool envioCorreo)
        {
            ConciliacionService NegFac = new ConciliacionService();

            foreach (var archivo in archivosConciliar)
            {
                var cons = GetCons(archivo.Servicio);

                var pathFile = rutas.Paths[archivo.Servicio] + @"\" + archivo.NombreArchivo;

                XmlDocument doc = new XmlDocument();
                doc.Load(pathFile);

                XmlNodeList nl0   = doc.SelectNodes(cons.Cabecera);
                XmlNode     node0 = nl0[0];

                var fechaPagoCabecera = "";
                foreach (XmlNode xnode3 in node0.ChildNodes)
                {
                    if (xnode3.Name == "fechaRecaudacion")
                    {
                        fechaPagoCabecera = xnode3.InnerText;
                        break;
                    }
                }
                //--------------


                if (archivo.Servicio == "MAT")
                {
                    XmlNodeList nl   = doc.SelectNodes("recaudacionVehiculos/detallesPagos");
                    XmlNode     root = nl[0];
                    var         fechasParaConsulta = GetFechas(root.ChildNodes, fechaPagoCabecera, archivo.Servicio);

                    //llamar al SP
                    var res    = NegFac.ConsultaReversosRiseCepMat(fechasParaConsulta, cons.Producto);
                    var objRes = XmlToObject(res.Data);

                    foreach (XmlNode xnode in root.ChildNodes)
                    {
                        var tipo = GetTipoPagoMat(xnode.Attributes["tipoPago"].Value);

                        var nl2 = xnode.SelectNodes("pago");


                        foreach (XmlNode xnode2 in nl2)
                        {
                            var estadoInicialDebito = xnode2.Attributes["estadoDebito"].Value;
                            var placaCpnCamv        = xnode2.Attributes["placaCpnCamv"].Value;
                            var fecha        = GetFechaSinDelimitadores(xnode2.Attributes["fechaPago"].Value, "MAT");
                            var codLogMon    = xnode2.Attributes["codLogMon"].Value;
                            var valorDebitar = float.Parse(xnode2.Attributes["valorDebitar"].Value, CultureInfo.InvariantCulture.NumberFormat);


                            var transaccion = objRes.FirstOrDefault(elem => elem.lg_fecha_trn == fecha && elem.lg_type_trn == tipo.Value &&
                                                                    elem.codLogMon == codLogMon && elem.lg_referencia == placaCpnCamv);

                            xnode2.Attributes["codTranIFIRev"].Value = "";
                            if (transaccion != null && estadoInicialDebito == "SI")
                            {
                                xnode2.Attributes["estadoDebito"].Value = "NO";

                                ChangeCabecera(node0, valorDebitar, tipo.Key);
                            }
                        }
                    }
                }


                if (archivo.Servicio == "RISE")  //cep
                {
                    XmlNodeList nl   = doc.SelectNodes("recaudacionDeuda/detalleRecaudacion");
                    XmlNode     root = nl[0];

                    var fechasParaConsulta = GetFechas(root.ChildNodes, fechaPagoCabecera, archivo.Servicio);

                    var res    = NegFac.ConsultaReversosRiseCepMat(fechasParaConsulta, cons.Producto);
                    var objRes = XmlToObject(res.Data);

                    foreach (XmlNode xnode in root.ChildNodes)
                    {
                        string estadoInicialDebito = xnode.Attributes["estadoDebito"].Value;
                        string fecha           = GetFechaSinDelimitadores(xnode.Attributes["fechaPago"].Value, "RISE");
                        var    valorDebitar    = float.Parse(xnode.Attributes["valorDebitar"].Value, CultureInfo.InvariantCulture.NumberFormat);
                        var    numCompSRI      = xnode.Attributes["numCompSRI"].Value;
                        var    valorReferencia = "";
                        var    tipo            = "";

                        var nl2 = xnode.SelectNodes("atributo");
                        //XmlNode root2 = nl2[0];
                        int i = 0;
                        foreach (XmlNode xnode2 in nl2)
                        {
                            i++;
                            if (i == 1)
                            {
                                valorReferencia = xnode2.Attributes["valor"].Value;
                            }
                            if (i == 2)
                            {                                                                       //GLOBAL
                                tipo = xnode2.Attributes["valor"].Value == "A_LA_FECHA" ? "010207" : "010107";

                                var transaccion = objRes.FirstOrDefault(elem => elem.lg_fecha_trn == fecha && elem.lg_type_trn == tipo &&
                                                                        elem.lg_referencia == valorReferencia && elem.lg_numero_factura == numCompSRI);


                                if (transaccion != null && estadoInicialDebito == "SI")
                                {
                                    xnode2.Attributes["estadoDebito"].Value = "NO";  ///// pilasssss comentar

                                    ChangeCabecera(node0, valorDebitar, "");
                                }
                            }
                        }
                        i = 0;
                    }
                }

                if (archivo.Servicio == "CEP")  //ofp
                {
                    XmlNodeList nl   = doc.SelectNodes("OtrasFormasDePago/declaracionesSRI_IFI");
                    XmlNode     root = nl[0];

                    var fechasParaConsulta = GetFechas(root.ChildNodes, fechaPagoCabecera, archivo.Servicio);

                    var res    = NegFac.ConsultaReversosRiseCepMat(fechasParaConsulta, cons.Producto);
                    var objRes = XmlToObject(res.Data);

                    foreach (XmlNode xnode in root.ChildNodes)
                    {
                        string fechaSW             = xnode.Attributes["fechaPago"].Value.Replace("-", "");
                        string numeroRuc           = xnode.Attributes["numeroRuc"].Value;
                        string adhesivo            = xnode.Attributes["adhesivo"].Value;
                        string codigoLogMonitor    = xnode.Attributes["codigoLogMonitor"].Value;
                        string estadoInicialDebito = xnode.Attributes["estadoDebito"].Value;
                        var    valorDebitar        = float.Parse(xnode.Attributes["valorDebitar"].Value, CultureInfo.InvariantCulture.NumberFormat);

                        var transacciones = objRes.FirstOrDefault(elem => elem.lg_fecha_trn == fechaSW && elem.lg_type_trn == "010011" && elem.lg_new_cedruc == numeroRuc &&
                                                                  elem.lg_referencia == adhesivo && elem.codLogMon == codigoLogMonitor);

                        if (transacciones != null && estadoInicialDebito == "SI")
                        {
                            xnode.Attributes["estadoDebito"].Value = "NO";

                            ChangeCabecera(node0, valorDebitar, "");
                        }
                    }
                }


                doc.Save(rutas.Paths[archivo.Servicio] + @"\" + archivo.NombreArchivo.Split('.')[0] + "_OUT.xml");
                //enviar correo
                //NegFac.EnviarCorreoConciliacion("asunto", "mensaje", "adjunto", "correos separados por coma");
            }
        }