예제 #1
0
    private void BindResults()
    {
        try
        {
            EntidadesConosud dc         = new EntidadesConosud();
            ArchivosSueldos  newArchivo = new ArchivosSueldos();
            if (RadUpload1.UploadedFiles.Count > 0)
            {
                #region Lectura y Carga Archivo Excel
                string          rutaArchivo = Server.MapPath("ArchivosSueldos") + "/" + RadUpload1.UploadedFiles[0].GetName();
                OleDbConnection connection  = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + rutaArchivo + ";Extended Properties=Excel 8.0");
                OleDbCommand    command     = new OleDbCommand("SELECT * FROM [Info$]", connection);
                OleDbDataReader dr;
                try
                {
                    connection.Open();
                    dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch
                {
                    connection = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + rutaArchivo + ";Extended Properties=Excel 8.0");
                    command    = new OleDbCommand("SELECT * FROM [FEBRERO$]", connection);
                    connection.Open();
                    dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                }

                DataTable excelData = new DataTable("ExcelData");
                excelData.Load(dr);

                var AlllegajosExcel = (from excel in excelData.AsEnumerable()
                                       select new
                {
                    dni = excel.Field <object>("DNI"),
                    fechaIngeso = excel.Field <DateTime?>("FECHA DE INGRESO"),
                    Categoria = excel.Field <string>("CATEGORIA SEGÚN CCT"),
                    Funcion = excel.Field <string>("FUNCION"),
                    NombreCompleto = excel.Field <string>("APELLIDO Y NOMBRE"),
                    FechaNacimiento = excel.Field <DateTime?>("FECHA DE NACIMIENTO"),
                    CUIL = excel.Field <double?>("CUIL"),
                    EncuadreGremial = excel.Field <string>("ENCUADRE GREMIAL"),

                    Basico = excel.Field <decimal?>("BASICO/VALOR HORA SEGÚN CCT"),
                    BasicoLiquidado = excel.Field <decimal?>("BASICO LIQUIDADO"),
                    HorasExtras = excel.Field <decimal?>("HORAS EXTRAS"),
                    AdicionalesRemunerativos = excel.Field <decimal?>("ADICIONALES REMUNERATIVOS (SIN HORAS EXTRAS)"),
                    Vacaciones = excel.Field <decimal?>("VACACIONES"),
                    SAC = excel.Field <decimal?>("SAC"),
                    TotalBruto = excel.Field <decimal?>("TOTAL BRUTO"),
                    AsigFliares = excel.Field <decimal?>("ASIGN FLIARES"),
                    AdicionalesNoRemunerativos = excel.Field <decimal?>("ADICIONALES NO REMUNERATIVOS"),
                    Descuentos = excel.Field <decimal?>("DESCUENTOS"),
                    TotalNeto = excel.Field <decimal?>("TOTAL NETO"),
                    CUITEmpresa = excel.Field <double?>("CUIT_(EMPRESA)"),
                    Periodo = excel.Field <DateTime?>("MES DE LIQUIDACIÓN"),
                    NroContrato = excel.Field <object>("CONTRATO N°"),
                    RazonSocial = excel.Field <string>("RAZON SOCIAL")
                }).ToList();
                #endregion

                #region Valido informacion
                ///Valido que el periodo no exista en la base
                ///
                var claveArchivo = (from L in AlllegajosExcel
                                    where L.Periodo != null
                                    select new { L.Periodo, L.NroContrato, L.CUITEmpresa, L.RazonSocial });

                if (claveArchivo.Count() > 0)
                {
                    int    mes     = claveArchivo.First().Periodo.Value.Month;
                    int    ano     = claveArchivo.First().Periodo.Value.Year;
                    string cuitemp = claveArchivo.First().CUITEmpresa.ToString();
                    string nrocon  = claveArchivo.First().NroContrato.ToString();

                    Entidades.Empresa emp = (from E in dc.Empresa
                                             where E.CUIT == cuitemp
                                             select E).FirstOrDefault();
                    if (emp == null)
                    {
                        string scriptstring = "alert('La empresa " + claveArchivo.First().RazonSocial + " no existe en la base de datos.');";
                        ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript2", scriptstring, true);
                        return;
                    }


                    if ((from D in dc.DatosDeSueldos
                         where D.objContrato.Codigo == nrocon && D.objEmpresa.CUIT == cuitemp &&
                         D.Periodo.Value.Year == ano && D.Periodo.Value.Month == mes
                         select D).Count() > 0)
                    {
                        string scriptstring = "alert('El periodo "
                                              + mes + "/" + ano + " del contrato " + nrocon + " correspondiente a " + claveArchivo.First().RazonSocial
                                              + " ya existe, debe eliminar el archivo del listado para completar la acción.');";

                        ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript1", scriptstring, true);
                        return;
                    }
                }
                else
                {
                    string scriptstring = "alert('El archivo no contiene informacion.');";
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript2", scriptstring, true);
                    return;
                }

                #endregion

                #region Actualizacion de info

                List <string> legajosDni = (from L in AlllegajosExcel
                                            where L.dni != null
                                            select L.dni.ToString()).ToList();

                List <Entidades.Legajos> LegajosEncontrados = dc.Legajos.Where(
                    Helpers.ContainsExpression <Entidades.Legajos, string>(l => l.NroDoc, legajosDni)).ToList <Entidades.Legajos>();

                /// Actualizo la información de los legajos encontrados
                foreach (Entidades.Legajos leg in LegajosEncontrados)
                {
                    var LegExcel = (from L in AlllegajosExcel
                                    where L.dni.ToString() == leg.NroDoc
                                    select L).First();

                    //leg.FuncionCCT = LegExcel.Funcion;
                    leg.FechaIngreos = LegExcel.fechaIngeso;
                    //leg.CategoriaCCT = LegExcel.Categoria;
                }

                /// Con la información de los legajos nuevos
                /// doy de alta a los nuevos legajos
                List <string> legajosDniBase = (from L in dc.Legajos
                                                select L.NroDoc).ToList();


                List <string> LegajosDniNevos = (from L in legajosDni
                                                 where !legajosDniBase.Contains(L)
                                                 select L).ToList();

                foreach (string dni in LegajosDniNevos)
                {
                    var LegExcel = (from L in AlllegajosExcel
                                    where L.dni == dni
                                    select L).First();

                    if (dni != null && dni != "" && dni.Length == 8)
                    {
                        Entidades.Legajos leg = new Entidades.Legajos();
                        //leg.FuncionCCT = LegExcel.Funcion;
                        leg.FechaIngreos = LegExcel.fechaIngeso;
                        //leg.CategoriaCCT = LegExcel.Categoria;
                        leg.NroDoc = dni;

                        if (LegExcel.NombreCompleto.IndexOf(",") > 0)
                        {
                            leg.Apellido = LegExcel.NombreCompleto.Substring(0, LegExcel.NombreCompleto.IndexOf(",")).Trim();
                            leg.Nombre   = LegExcel.NombreCompleto.Substring(LegExcel.NombreCompleto.IndexOf(",") + 1).Replace(".", "").Trim();
                        }
                        else
                        {
                            leg.Apellido = LegExcel.NombreCompleto.Substring(0, LegExcel.NombreCompleto.IndexOf(" ")).Trim();
                            leg.Nombre   = LegExcel.NombreCompleto.Substring(LegExcel.NombreCompleto.IndexOf(" ") + 1).Replace(".", "").Trim();
                        }

                        leg.FechaNacimiento = LegExcel.FechaNacimiento;

                        if (LegExcel.CUIL != null)
                        {
                            leg.CUIL = string.Format("{0:##-########-#}", long.Parse(LegExcel.CUIL.ToString()));
                        }

                        leg.objConvenio = (from Cla in dc.Clasificacion
                                           where Cla.Tipo == "Convenio" && Cla.Descripcion.Contains(LegExcel.EncuadreGremial)
                                           select Cla).FirstOrDefault();

                        dc.AddToLegajos(leg);
                    }
                }
                #endregion

                #region Carga registro de Archivo
                long idUsuario = long.Parse(this.Session["idusu"].ToString());
                newArchivo.Nombre     = RadUpload1.UploadedFiles[0].GetName();
                newArchivo.SegUsuario = (from U in dc.SegUsuario
                                         where U.IdSegUsuario == idUsuario
                                         select U).First();

                newArchivo.FechaCreacion = DateTime.Now;
                dc.AddToArchivosSueldos(newArchivo);
                #endregion

                #region Generacion Información Sueldo Mensual
                List <Entidades.DatosDeSueldos> dtosSuel = new List <DatosDeSueldos>();
                foreach (var item in AlllegajosExcel)
                {
                    string StringDNI = Convert.ToInt32(item.dni).ToString();

                    Entidades.Legajos leg = (from L in dc.Legajos
                                             where L.NroDoc == StringDNI
                                             select L).FirstOrDefault();

                    string cuitemp = string.Empty;
                    if (item.CUITEmpresa.HasValue)
                    {
                        cuitemp = item.CUITEmpresa.Value.ToString();
                    }
                    Entidades.Empresa emp = (from E in dc.Empresa
                                             where E.CUIT == cuitemp
                                             select E).FirstOrDefault();

                    string nrocont = string.Empty;
                    if (item.NroContrato != null)
                    {
                        nrocont = item.NroContrato.ToString();
                    }
                    Entidades.Contrato cont = (from E in dc.Contrato
                                               where E.Codigo == nrocont
                                               select E).FirstOrDefault();

                    if (leg != null && emp != null && cont != null)
                    {
                        Entidades.DatosDeSueldos DatoSueldo = new DatosDeSueldos();
                        DatoSueldo.objLegajo = leg;
                        DatoSueldo.AdicionalesNORemunerativos = item.AdicionalesNoRemunerativos;
                        DatoSueldo.AdicionalesRemunerativos   = item.AdicionalesRemunerativos;
                        DatoSueldo.AsignacionFamiliar         = item.AsigFliares;
                        DatoSueldo.Basico_ValorHora           = item.Basico;
                        DatoSueldo.BasicoLiquidado            = item.BasicoLiquidado;
                        DatoSueldo.Descuentos  = item.Descuentos;
                        DatoSueldo.HorasExtras = item.HorasExtras;
                        DatoSueldo.SAC         = item.SAC;
                        DatoSueldo.TotalBruto  = item.TotalBruto;
                        DatoSueldo.TotalNeto   = item.TotalNeto;
                        DatoSueldo.Vacaciones  = item.Vacaciones;
                        DatoSueldo.Periodo     = item.Periodo;
                        DatoSueldo.objEmpresa  = emp;
                        DatoSueldo.objContrato = cont;
                        dtosSuel.Add(DatoSueldo);
                    }
                }
                #endregion


                if (dtosSuel.Count > 0)
                {
                    foreach (Entidades.DatosDeSueldos ds in dtosSuel)
                    {
                        newArchivo.colDatosDeSueldos.Add(ds);
                    }

                    dc.SaveChanges();
                    gvArchivos.Rebind();
                }
                else
                {
                    string scriptstring = "alert('No existe informacion de Sueldos en el archivo o no estan cargado ninguno de los contratos o legagos en el sistema');";
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript2", scriptstring, true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            string script = string.Format("alert('Error al procesar archivo!  {0}');", ex.Message.Replace("'", " "));
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", script, true);
        }
    }
    private void BindResults()
    {
        StreamWriter _sw = null;

        _sw = new StreamWriter(Server.MapPath("") + "\\logInfoPlanes.txt", true);

        try
        {
            ArchivosSueldos newArchivo = new ArchivosSueldos();
            if (RadUpload1.UploadedFiles.Count > 0)
            {
                #region Lectura y Carga Archivo Excel
                string          rutaArchivo = Server.MapPath("ArchivosPlanTrabajo") + "/" + RadUpload1.UploadedFiles[0].GetName();
                OleDbConnection connection  = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + rutaArchivo + ";Extended Properties=Excel 12.0;HDR=YES;");
                OleDbCommand    command     = new OleDbCommand("SELECT * FROM [Info$]", connection);
                OleDbDataReader dr;
                try
                {
                    connection.Open();
                    dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch
                {
                    connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + rutaArchivo + ";Extended Properties=\"Excel 12.0;HDR=YES;\"");
                    command    = new OleDbCommand("SELECT * FROM [Info$]", connection);
                    connection.Open();
                    dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                }

                DataTable excelData = new DataTable("ExcelData");
                excelData.Load(dr);

                var AlllegajosExcel = (from excel in excelData.AsEnumerable()
                                       select new
                {
                    Contrato = excel.Field <object>("Contrato"),
                    Contratista = excel.Field <object>("Contratista"),
                    Sindicato = excel.Field <object>("Sindicato"),
                    Aplicacion = excel.Field <object>("Aplicacion") == null ? 0 : Convert.ToDecimal(excel.Field <object>("Aplicacion"))
                }).Where(w => w.Contrato != null && w.Contratista != null && w.Sindicato != null).ToList();

                //_sw.WriteLine("Total Registros:" + AlllegajosExcel.Count);
                ////_sw.WriteLine("Total Contratos:" + AlllegajosExcel.Where(w => w.Contrato.ToString().Contains("UOCRA")).Count());
                //_sw.WriteLine("Total Sindicato:" + AlllegajosExcel.Where(w => w.Sindicato.ToString().Contains("UOCRA")).Count());

                var oucra = (from o in AlllegajosExcel
                             where o.Sindicato.ToString().Contains("UOCRA")
                             group o by new { o.Contrato, o.Contratista } into g
                             select new
                {
                    Total = g.Sum(w => w.Aplicacion),
                    Contrato = g.Key.Contrato.ToString(),
                    Contratista = g.Key.Contratista
                }).ToList();

                var independientes = (from o in AlllegajosExcel
                                      where (o.Sindicato.ToString().ToLower().Contains("(sin informacion)") || o.Sindicato.ToString().ToLower().Contains("independiente"))
                                      group o by new { o.Contrato, o.Contratista } into g
                                      select new
                {
                    Total = g.Sum(w => w.Aplicacion),
                    Contrato = g.Key.Contrato.ToString(),
                    Contratista = g.Key.Contratista
                }).ToList();

                var otros = (from o in AlllegajosExcel
                             where !o.Sindicato.ToString().Contains("UOCRA") && !(o.Sindicato.ToString().ToLower().Contains("(sin informacion)") || o.Sindicato.ToString().ToLower().Contains("independiente"))
                             group o by new { o.Contrato, o.Contratista } into g
                             select new
                {
                    Total = g.Sum(w => w.Aplicacion),
                    Contrato = g.Key.Contrato.ToString(),
                    Contratista = g.Key.Contratista
                }).ToList();

                var contratosEmpresas = (from o in AlllegajosExcel

                                         select new
                {
                    Contrato = o.Contrato.ToString(),
                    Contratista = o.Contratista
                }).Distinct().ToList();



                //decimal UOCRA = Math.Round(AlllegajosExcel.Where(w => w.Sindicato.ToString().Contains("UOCRA")).Sum(w => w.Aplicacion));
                //decimal Independientes = Math.Round(AlllegajosExcel.Where(w => w.Sindicato.ToString().ToLower().Contains("(sin informacion)")).Sum(w => w.Aplicacion));
                //decimal Otros = Math.Round(AlllegajosExcel.Where(w => !w.Sindicato.ToString().Contains("UOCRA") && !w.Sindicato.ToString().ToLower().Contains("(sin informacion)")).Sum(w => w.Aplicacion));

                #endregion

                #region Actualizacion de info del plan de trabajo

                using (EntidadesConosud dc = new EntidadesConosud())
                {
                    List <InformacionPlanTrabajo> currents = (from i in dc.InformacionPlanTrabajo
                                                              where i.Periodo == cboPeriodos.SelectedValue
                                                              select i).ToList();

                    if (currents.Count > 0)
                    {
                        foreach (var item in currents)
                        {
                            dc.InformacionPlanTrabajo.DeleteObject(item);
                        }
                    }


                    foreach (var item in contratosEmpresas)
                    {
                        var T_UOCRA = oucra.Where(w => w.Contratista.ToString().Trim() == item.Contratista.ToString().Trim() && w.Contrato.ToString() == item.Contrato).FirstOrDefault();
                        var T_INDEP = independientes.Where(w => w.Contratista.ToString().Trim() == item.Contratista.ToString().Trim() && w.Contrato.ToString() == item.Contrato).FirstOrDefault();
                        var T_OTROS = otros.Where(w => w.Contratista.ToString().Trim() == item.Contratista.ToString().Trim() && w.Contrato.ToString() == item.Contrato).FirstOrDefault();

                        InformacionPlanTrabajo current = new InformacionPlanTrabajo();
                        current.Periodo        = cboPeriodos.SelectedValue;
                        current.INDEPENDIENTES = T_INDEP != null?Convert.ToInt32(T_INDEP.Total) : 0;

                        current.UOCRA = T_UOCRA != null?Convert.ToInt32(T_UOCRA.Total) : 0;

                        current.OTROS = T_OTROS != null?Convert.ToInt32(T_OTROS.Total) : 0;

                        current.Empresa  = item.Contratista.ToString();
                        current.Contrato = item.Contrato;

                        dc.AddToInformacionPlanTrabajo(current);
                    }

                    dc.SaveChanges();

                    //if (current == null)
                    //{
                    //    current = new InformacionPlanTrabajo();
                    //    current.Periodo = cboPeriodos.SelectedValue;
                    //    current.INDEPENDIENTES = Convert.ToInt32(Independientes);
                    //    current.UOCRA = Convert.ToInt32(UOCRA);
                    //    current.OTROS = Convert.ToInt32(Otros);

                    //    dc.AddToInformacionPlanTrabajo(current);
                    //}
                    //else
                    //{
                    //    current.INDEPENDIENTES = Convert.ToInt32(Independientes);
                    //    current.UOCRA = Convert.ToInt32(UOCRA);
                    //    current.OTROS = Convert.ToInt32(Otros);
                    //}

                    //dc.SaveChanges();
                }

                #endregion
            }
        }
        catch (Exception ex)
        {
            _sw.WriteLine(ex.Message.ToString());
            _sw.WriteLine(ex.StackTrace);
            if (ex.InnerException != null)
            {
                _sw.WriteLine(ex.InnerException.Message.ToString());
            }

            string script = string.Format("alert('Error al procesar archivo!  {0}');", ex.Message.Replace("'", " "));
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", script, true);
        }

        _sw.Close();
    }