/// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <bool> Handle(BulkWorksRequest request, CancellationToken cancellationToken)
            {
                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.WorksFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(false);
                }

                Obra.SetPropertyIndexes(headers);

                var estadosObraDict = await estadoObraRepository.GetAll()
                                      .ToDictionaryAsync(div => div.Nombre, div => div.Id)
                                      .ConfigureAwait(false);

                List <Obra> newObras = new List <Obra>();

                HashSet <string> existentWorks = (await repository.GetAll().Select(u => u.CodigoObra).ToListAsync().ConfigureAwait(false)).ToHashSet();

                foreach (string[] dataRow in data)
                {
                    Obra newObra = new Obra(dataRow);

                    if (existentWorks.Contains(newObra.CodigoObra))
                    {
                        continue;
                    }

                    newObra.LastAction     = "CREATE";
                    newObra.LastActionDate = DateTime.UtcNow;

                    if (!string.IsNullOrEmpty(newObra.EstadoObra.Nombre))
                    {
                        if (!estadosObraDict.ContainsKey(newObra.EstadoObra.Nombre))
                        {
                            throw new Exception($"No el estado de la obra {newObra.EstadoObra.Nombre} en el maestro de tecnologias");
                        }
                        newObra.IdEstadoObra = estadosObraDict[newObra.EstadoObra.Nombre];
                    }

                    newObras.Add(newObra);
                    existentWorks.Add(newObra.CodigoObra);
                }

                await repository.BulkInsertAsync(newObras).ConfigureAwait(false);;

                return(true);
            }
Beispiel #2
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <bool> Handle(BulkOutSourcersRequest request, CancellationToken cancellationToken)
            {
                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.OutSourcersFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(false);
                }

                Subcontrata.SetPropertyIndexes(headers);

                List <Subcontrata> newSubcontratas = new List <Subcontrata>();

                HashSet <string> existentCifs = (await repository.GetAll().Select(u => u.Cif).ToListAsync().ConfigureAwait(false)).ToHashSet();

                foreach (string[] dataRow in data)
                {
                    Subcontrata newSubcontrata = new Subcontrata(dataRow);

                    if (existentCifs.Contains(newSubcontrata.Cif))
                    {
                        continue;
                    }

                    newSubcontrata.LastAction     = "CREATE";
                    newSubcontrata.LastActionDate = DateTime.UtcNow;

                    newSubcontratas.Add(newSubcontrata);
                    existentCifs.Add(newSubcontrata.Cif);
                }

                await repository.BulkInsertAsync(newSubcontratas).ConfigureAwait(false);;

                return(true);
            }
Beispiel #3
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <bool> Handle(BulkDepartmentsRequest request, CancellationToken cancellationToken)
            {
                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.DepartmentsFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(false);
                }

                Departamento.SetPropertyIndexes(headers);

                List <Departamento> newDepartamentos = new List <Departamento>();

                List <long> existentIdWorkday = await repository.GetAll().Select(u => u.IdWorkday).ToListAsync().ConfigureAwait(false);

                foreach (string[] dataRow in data)
                {
                    Departamento newDepartamento = new Departamento(dataRow);

                    if (existentIdWorkday.Contains(newDepartamento.IdWorkday))
                    {
                        continue;
                    }

                    newDepartamento.LastAction     = "CREATE";
                    newDepartamento.LastActionDate = DateTime.UtcNow;

                    newDepartamentos.Add(newDepartamento);
                }

                await repository.BulkInsertAsync(newDepartamentos).ConfigureAwait(false);;

                return(true);
            }
Beispiel #4
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <bool> Handle(BulkRolesRequest request, CancellationToken cancellationToken)
            {
                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.RolesFile, cancellationToken).ConfigureAwait(false);

                string[] headers = csv.Item1;
                // Identificar los índices donde están los datos de IdUsuarioWorkday y Rol
                int idUsuarioWorkDayIndex = Array.IndexOf(headers, "IDWD");
                int roleIndex             = Array.IndexOf(headers, "ROL");


                string[][] data = csv.Item2;

                // Si no hay datos salida
                if (!data.Any())
                {
                    return(false);
                }

                // eliminar filas sin IdUsuarioWorkday
                data = data.Where(a => !string.IsNullOrWhiteSpace(a[idUsuarioWorkDayIndex])).ToArray();

                // eliminar duplicados
                data = data.GroupBy(g => g[idUsuarioWorkDayIndex])
                       .Select(g => g.Last())
                       .ToArray();

                // Si no hay datos salida
                if (!data.Any())
                {
                    return(false);
                }

                // traerse todos los empleados
                long[] idUsuariosWorkday = data.Select(a => long.Parse(a[idUsuarioWorkDayIndex])).ToArray();

                var empleadosDictionary = await repositoryEmpleado.GetAll()
                                          .Include(e => e.IdUsuarioWorkDayNavigation)
                                          .Include(e => e.EmpleadoRole)
                                          .ThenInclude(er => er.IdRoleNavigation)
                                          .Where(e => e.IdUsuarioWorkDay != null && idUsuariosWorkday.Contains(e.IdUsuarioWorkDayNavigation.IdWorkDay))
                                          .ToDictionaryAsync(x => x.IdUsuarioWorkDayNavigation.IdWorkDay, x => x)
                                          .ConfigureAwait(false);

                // traerse todos los roles del CSV
                var roles = data.Select(a => a[roleIndex]).Distinct().ToArray();

                // traducir roles del CSV
                var rolesTranslations = roles.Select(s => new { s, dbName = Role.TranslateCsvToDbRoleName(s) }).ToDictionary(x => x.s, x => x.dbName);

                // excluir nulos y no reconocidos
                var rolesDbName = rolesTranslations.Values.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();

                // diccionario de roles
                var rolesDictionary = await repositoryRole.GetAll()
                                      .Where(r => rolesDbName.Contains(r.Nombre))
                                      .ToDictionaryAsync(r => r.Nombre, r => r)
                                      .ConfigureAwait(false);



                foreach (string[] dataRow in data)
                {
                    Empleado emp          = empleadosDictionary[long.Parse(dataRow[idUsuarioWorkDayIndex])];
                    string   newRol       = dataRow[roleIndex];
                    string   newRolDbName = rolesTranslations[newRol];

                    // Roles del empleado exceptuando Empleado y Administrator
                    var currentAppRoles = emp.EmpleadoRole
                                          .Where(x => x.IdRoleNavigation.Nombre != Role.RoleNames.Empleado.ToString() && x.IdRoleNavigation.Nombre != Role.RoleNames.Administrator.ToString())
                                          .ToArray();

                    // borrado
                    if (newRolDbName == null)
                    {
                        for (int i = currentAppRoles.Length - 1; i >= 0; i--)
                        {
                            repositoryEmpleadoRole.DeletedRange(new EmpleadoRole[] { currentAppRoles[i] });
                        }
                        continue;
                    }

                    // modificación // nuevo
                    if (!currentAppRoles.Select(r => r.IdRoleNavigation.Nombre).Contains(newRolDbName))
                    {
                        for (int i = currentAppRoles.Length - 1; i >= 0; i--)
                        {
                            repositoryEmpleadoRole.DeletedRange(new EmpleadoRole[] { currentAppRoles[i] });
                        }
                        repositoryEmpleadoRole.Add(new EmpleadoRole
                        {
                            IdEmpleado = emp.Id,
                            IdRole     = rolesDictionary[newRolDbName].Id
                        });;
                    }
                }
                await repositoryEmpleadoRole.SaveChangesAsync().ConfigureAwait(false);

                return(true);
            }
Beispiel #5
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <BulkEmployeesExternalResult> Handle(BulkEmployeesExternalRequest request, CancellationToken cancellationToken)
            {
                Stopwatch stopWatch = new Stopwatch();

                stopWatch.Start();



                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.EmployeesFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(new BulkEmployeesExternalResult());
                }

                IntegracionExternos.SetPropertyIndexes(headers);

                //adjudicación obra diccionario
                //var adjudicacionDict = await adjudicacionObraRepository.GetAll()
                //     .ToDictionaryAsync(div => div.IdObra, div => div.Id)
                //     .ConfigureAwait(false);

                List <IntegracionExternos> newIntegracionExternos = new List <IntegracionExternos>();
                List <Empleado>            newEmpleados           = new List <Empleado>();

                List <Exception> errores = new List <Exception>();
                Dictionary <string, Empleado> empleadosDict = new Dictionary <string, Empleado>();

                HashSet <string> existentIdIntegracionExternos = (await repository.GetAll().Select(u => u.Nif).ToListAsync().ConfigureAwait(false)).ToHashSet();
                HashSet <string> existentNifs = new HashSet <string>();

                int intOrder = -50000000;

                //int intOrder = empleadoRepository.GetAll().Last().Id;

                foreach (string[] dataRow in data)
                {
                    try
                    {
                        IntegracionExternos newIntegracionExterno = new IntegracionExternos(dataRow);
                        newIntegracionExterno.Id     = intOrder;
                        newIntegracionExterno.Origen = request.Origen;

                        //Formateamos el NIF
                        newIntegracionExterno.Nif = newIntegracionExterno.NifOriginal.Trim().ToUpper().Replace("-", "").Replace("_", "").Replace("/", "");

                        //Comprobamos que en la bbdd no se hubiera creado ya ese empleado
                        if (existentIdIntegracionExternos.Contains(newIntegracionExterno.Nif))
                        {
                            //errores.Add(new Exception($"Fila {intOrder + 50000002}: El usuario con NIF: {newIntegracionExterno.Nif} ya está registrado en integracion externo."));
                            continue;
                        }
                        //Comprobamos que no se haya insertado ya
                        if (existentNifs.Contains(newIntegracionExterno.Nif))
                        {
                            //errores.Add(new Exception($"Fila {intOrder + 50000002}: El usuario con NIF: {newIntegracionExterno.Nif} está repetido."));
                            continue;
                        }
                        if (newIntegracionExterno.Nif.Length > 13)
                        {
                            errores.Add(new Exception($"Fila {intOrder + 50000002}: El usuario con NIF: {newIntegracionExterno.Nif} no se ha insertado correctamente. Formato de DNI conflictivo"));
                            continue;
                        }

                        Empleado newEmpleado = new Empleado(newIntegracionExterno);
                        newEmpleado.Id = intOrder;
                        newEmpleado.IdFichaLaboralNavigation.Id = intOrder;
                        newEmpleado.IdFichaMedicaNavigation.Id  = intOrder;
                        newEmpleado.InterAcciona = false;

                        //if (!adjudicacionDict.ContainsKey(newIntegracionExterno.codobra))
                        //    throw new Exception($"No existe la obra  {newIntegracionExterno.codobra} en el maestro de obras");
                        //newEmpleado.AdjudicacionTrabajoObra.IdDivision = divisionDict[newIntegracionExterno.Division];

                        newIntegracionExternos.Add(newIntegracionExterno);
                        newEmpleados.Add(newEmpleado);
                        empleadosDict.Add(newIntegracionExterno.Nif, newEmpleado);

                        existentNifs.Add(newIntegracionExterno.Nif);
                    }
                    catch (Exception ex)
                    {
                        errores.Add(ex);
                    }
                    finally
                    {
                        intOrder++;
                    }
                }

                SendTimeOperationToLogger("Create Entities");

                repository.UnitOfWork.BeginTransaction();

                // BULK WORKDAY
                await repository.BulkInsertAsync(newIntegracionExternos).ConfigureAwait(false);

                newIntegracionExternos.Select(c => { c.Empleado.First().IdIntegracionExternos = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk Workday Entities");

                // BULK  FICHA MEDICA
                List <FichaMedica> listaFichMedica = newEmpleados.Select(c => c.IdFichaMedicaNavigation).ToList();
                await fichaMedicaRepository.BulkInsertAsync(listaFichMedica).ConfigureAwait(false);

                listaFichMedica.Select(c => { c.Empleado.First().IdFichaMedica = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk FichaMedica Entities");

                // BULK FICHA LABORAL
                List <FichaLaboral> listaFichLaboral = newEmpleados.Select(c => c.IdFichaLaboralNavigation).ToList();
                await fichaLaboralRepository.BulkInsertAsync(listaFichLaboral).ConfigureAwait(false);

                listaFichLaboral.Select(c => { c.Empleado.First().IdFichaLaboral = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk Ficha Laboral Entities");

                // BULK EMPLEADOS
                await empleadoRepository.BulkInsertAsync(newEmpleados).ConfigureAwait(false);

                SendTimeOperationToLogger("Bulk Empleados Entities");

                // BULK ROLE EMPLEADO
                List <EmpleadoRole> listaEmpleadoRole = new List <EmpleadoRole>();

                Role roleEmpleado = await roleRepository.GetAll().FirstOrDefaultAsync(c => c.Nombre == "Empleado").ConfigureAwait(false);

                newEmpleados = newEmpleados.OrderBy(c => c.Id).ToList();

                newEmpleados.Select(c =>
                {
                    int flag = 1;

                    listaEmpleadoRole.Add(new EmpleadoRole()
                    {
                        IdEmpleado     = c.Id,
                        IdRole         = roleEmpleado.Id,
                        LastAction     = "CREATE",
                        LastActionDate = DateTime.UtcNow,
                        Id             = flag
                    });

                    flag++;

                    return(c);
                }).ToList();

                await empleadoRoleRepository.BulkInsertWithOutSetOutputAsync(listaEmpleadoRole).ConfigureAwait(false);

                SendTimeOperationToLogger("Bulk Roles");

                repository.UnitOfWork.Commit();

                SendTimeOperationToLogger("Commit");

                return(new BulkEmployeesExternalResult
                {
                    Errores = errores.Select(ex => ex.Message).ToList()
                });
            }
Beispiel #6
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <BulkWorkAwardResult> Handle(BulkWorkAwardRequest request, CancellationToken cancellationToken)
            {
                List <Exception> errores = new List <Exception>();

                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.WorkAwardFile, cancellationToken).ConfigureAwait(false);

                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(new BulkWorkAwardResult());
                }

                AdjudicacionTrabajoObra.SetPropertyIndexes(headers);


                List <AdjudicacionTrabajoObra> newAdjudicacionObras = new List <AdjudicacionTrabajoObra>();

                Dictionary <string, int> obrasDict = await obraRepository.GetAll()
                                                     .ToDictionaryAsync(div => div.CodigoObra, div => div.Id)
                                                     .ConfigureAwait(false);

                Dictionary <string, int> subContratasDict = await subcontrataRepository.GetAll()
                                                            .ToDictionaryAsync(div => div.Cif, div => div.Id)
                                                            .ConfigureAwait(false);

                HashSet <string> existentAwardWorks = (await repository.GetAll()
                                                       .Select(adj => $"{adj.IdObra}__{adj.IdSubcontrata}")
                                                       .ToListAsync().ConfigureAwait(false)).ToHashSet();


                int intOrder = -50000000;

                foreach (string[] dataRow in data)
                {
                    try
                    {
                        AdjudicacionTrabajoObra newAdjudicacionObra = new AdjudicacionTrabajoObra(dataRow);

                        if (!obrasDict.ContainsKey(newAdjudicacionObra.Obra.CodigoObra))
                        {
                            errores.Add(new Exception($"Fila {intOrder + 50000002}: La obra: {newAdjudicacionObra.Obra.CodigoObra} no existe en la BBDD"));
                            continue;
                        }
                        newAdjudicacionObra.IdObra = obrasDict[newAdjudicacionObra.Obra.CodigoObra];
                        newAdjudicacionObra.Obra   = null;


                        if (!subContratasDict.ContainsKey(newAdjudicacionObra.Subcontrata.Cif))
                        {
                            errores.Add(new Exception($"Fila {intOrder + 50000002}: La subcontrata: {newAdjudicacionObra.Subcontrata.Cif} no existe en la BBDD"));
                            continue;
                        }
                        newAdjudicacionObra.IdSubcontrata = subContratasDict[newAdjudicacionObra.Subcontrata.Cif];
                        newAdjudicacionObra.Subcontrata   = null;

                        //Si la adjudicación ya existía no se vuelve a insertar
                        if (existentAwardWorks.Contains($"{newAdjudicacionObra.IdObra}__{newAdjudicacionObra.IdSubcontrata}"))
                        {
                            continue;
                        }

                        newAdjudicacionObra.LastAction     = "CREATE";
                        newAdjudicacionObra.LastActionDate = DateTime.UtcNow;

                        newAdjudicacionObras.Add(newAdjudicacionObra);
                        existentAwardWorks.Add($"{newAdjudicacionObra.IdObra}__{newAdjudicacionObra.IdSubcontrata}");
                    }
                    finally
                    {
                        intOrder++;
                    }
                }

                await repository.BulkInsertAsync(newAdjudicacionObras).ConfigureAwait(false);;

                return(new BulkWorkAwardResult
                {
                    Errores = errores.Select(ex => ex.Message).ToList()
                });
            }
Beispiel #7
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <BulkEmployeesResult> Handle(BulkEmployeesRequest request, CancellationToken cancellationToken)
            {
                Stopwatch stopWatch = new Stopwatch();

                stopWatch.Start();

                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.EmployeesFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(new BulkEmployeesResult());
                }

                UsuarioWorkDay.SetPropertyIndexes(headers);

                var divisionDict = await divisionRepository.GetAll()
                                   .ToDictionaryAsync(div => div.IdWorkday, div => div.Id)
                                   .ConfigureAwait(false);

                var departamentosDict = await departamentoRepository.GetAll()
                                        .ToDictionaryAsync(div => div.IdWorkday, div => div.Id)
                                        .ConfigureAwait(false);

                var localizacionesDict = await localizacionRepository.GetAll()
                                         .ToDictionaryAsync(div => div.Nombre, div => div.Id)
                                         .ConfigureAwait(false);

                var tecnologiasDict = await tecnologiaRepository.GetAll()
                                      .ToDictionaryAsync(div => div.Nombre, div => div.Id)
                                      .ConfigureAwait(false);

                List <UsuarioWorkDay> newUsuariosWorkday = new List <UsuarioWorkDay>();
                List <Empleado>       newEmpleados       = new List <Empleado>();

                List <Exception>            errores       = new List <Exception>();
                Dictionary <long, Empleado> empleadosDict = new Dictionary <long, Empleado>();

                HashSet <long> existentIdWorkday = (await repository.GetAll().Select(u => u.IdWorkDay).ToListAsync().ConfigureAwait(false)).ToHashSet();

                int intOrder = -50000000;

                for (int i = 0; i < data.Length; i++)
                {
                    try
                    {
                        string[]       dataRow           = data[i];
                        UsuarioWorkDay newUsuarioWorkday = new UsuarioWorkDay(dataRow);
                        newUsuarioWorkday.Id = intOrder;

                        if (existentIdWorkday.Contains(newUsuarioWorkday.IdWorkDay))
                        {
                            continue;
                        }

                        Empleado newEmpleado = new Empleado(newUsuarioWorkday);
                        newEmpleado.Id = intOrder;
                        newEmpleado.IdFichaLaboralNavigation.Id = intOrder;
                        newEmpleado.IdFichaMedicaNavigation.Id  = intOrder;

                        if (!divisionDict.ContainsKey(newUsuarioWorkday.Division))
                        {
                            throw new Exception($"No existe la división {newUsuarioWorkday.Division} en el maestro de divisiones");
                        }
                        newEmpleado.IdFichaLaboralNavigation.IdDivision = divisionDict[newUsuarioWorkday.Division];

                        if (!string.IsNullOrEmpty(newUsuarioWorkday.Tecnologia))
                        {
                            if (!tecnologiasDict.ContainsKey(newUsuarioWorkday.Tecnologia))
                            {
                                throw new Exception($"No existe la tecnologia {newUsuarioWorkday.Tecnologia} en el maestro de tecnologias");
                            }
                            newEmpleado.IdFichaLaboralNavigation.IdTecnologia = tecnologiasDict[newUsuarioWorkday.Tecnologia];
                        }

                        if (!departamentosDict.ContainsKey(newUsuarioWorkday.Departamento))
                        {
                            throw new Exception($"No existe el departamento {newUsuarioWorkday.Departamento} en el maestro de departamentos");
                        }
                        newEmpleado.IdFichaLaboralNavigation.IdDepartamento = departamentosDict[newUsuarioWorkday.Departamento];

                        if (!localizacionesDict.ContainsKey(newUsuarioWorkday.Localizacion))
                        {
                            throw new Exception($"No existe la localización {newUsuarioWorkday.Localizacion} en el maestro de localizaciones");
                        }
                        newEmpleado.IdFichaLaboralNavigation.IdLocalizacion = localizacionesDict[newUsuarioWorkday.Localizacion];

                        newUsuariosWorkday.Add(newUsuarioWorkday);
                        newEmpleados.Add(newEmpleado);
                        empleadosDict.Add(newUsuarioWorkday.IdWorkDay, newEmpleado);
                    }
                    catch (Exception ex)
                    {
                        errores.Add(new Exception($"Error parseando empleado: fila {i + 2}: {ex.Message}", ex));
                    }
                    finally
                    {
                        intOrder++;
                    }
                }

                SendTimeOperationToLogger("Create Entities");

                repository.UnitOfWork.BeginTransaction();

                // BULK WORKDAY
                await repository.BulkInsertAsync(newUsuariosWorkday).ConfigureAwait(false);

                newUsuariosWorkday.Select(c => { c.Empleado.First().IdUsuarioWorkDay = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk Workday Entities");

                // BULK  FICHA MEDICA
                List <FichaMedica> listaFichMedica = newEmpleados.Select(c => c.IdFichaMedicaNavigation).ToList();
                await fichaMedicaRepository.BulkInsertAsync(listaFichMedica).ConfigureAwait(false);

                listaFichMedica.Select(c => { c.Empleado.First().IdFichaMedica = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk FichaMedica Entities");

                // BULK FICHA LABORAL
                List <FichaLaboral> listaFichLaboral = newEmpleados.Select(c => c.IdFichaLaboralNavigation).ToList();
                await fichaLaboralRepository.BulkInsertAsync(listaFichLaboral).ConfigureAwait(false);

                listaFichLaboral.Select(c => { c.Empleado.First().IdFichaLaboral = c.Id; return(c); }).ToList();

                SendTimeOperationToLogger("Bulk Ficha Laboral Entities");

                // BULK EMPLEADOS
                await empleadoRepository.BulkInsertAsync(newEmpleados).ConfigureAwait(false);

                SendTimeOperationToLogger("Bulk Empleados Entities");

                // BULK ACTUALIZACION RESPONSABLES
                listaFichLaboral = await UpdateResponsableFichaLaboral(listaFichLaboral).ConfigureAwait(false);

                await fichaLaboralRepository.BulkUpdateAsync(listaFichLaboral).ConfigureAwait(false);

                SendTimeOperationToLogger("Bulk Responsables");

                // BULK ROLE EMPLEADO

                List <EmpleadoRole> listaEmpleadoRole = new List <EmpleadoRole>();

                Role roleEmpleado = await roleRepository.GetAll().FirstOrDefaultAsync(c => c.Nombre == "Empleado").ConfigureAwait(false);

                newEmpleados = newEmpleados.OrderBy(c => c.Id).ToList();

                newEmpleados.Select(c =>
                {
                    int flag = 1;

                    listaEmpleadoRole.Add(new EmpleadoRole()
                    {
                        IdEmpleado     = c.Id,
                        IdRole         = roleEmpleado.Id,
                        LastAction     = "CREATE",
                        LastActionDate = DateTime.UtcNow,
                        Id             = flag
                    });

                    flag++;

                    return(c);
                }).ToList();

                await empleadoRoleRepository.BulkInsertWithOutSetOutputAsync(listaEmpleadoRole).ConfigureAwait(false);

                SendTimeOperationToLogger("Bulk Roles");

                repository.UnitOfWork.Commit();

                SendTimeOperationToLogger("Commit");

                return(new BulkEmployeesResult
                {
                    Errores = errores.Select(ex => ex.Message).ToList()
                });
            }
Beispiel #8
0
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <IntegrationFileStorageResult> Handle(IntegrationFileStorageRequest request, CancellationToken cancellationToken)
            {
                IEnumerable <string> fileList = await fileStorageService.ListFilesAsync(integrationSettings.IntegrationPath).ConfigureAwait(false);

                //Comprobamos si los ficheros han sido procesados
                List <string> fileListProcessed = resultadosIntegracionRepository
                                                  .GetBy(r => fileList.Contains(r.OriginFileName))
                                                  .Select(r => r.OriginFileName)
                                                  .Distinct().ToList();

                List <string> fileListToProcess = fileList.Except(fileListProcessed).ToList();
                Regex         regex             = new Regex(integrationSettings.FileNamePatern);

                foreach (string fileToProcess in fileListToProcess.OrderBy(fn => fn))
                {
                    if (!regex.IsMatch(fileToProcess))
                    {
                        continue;
                    }
                    byte[] fileContent = await fileStorageService.GetFileContentAsync($"{integrationSettings.IntegrationPath}/{fileToProcess}");

                    Dictionary <string, string> intFiles = zipFilesRepository.GetZippedFilesContentStringAsync(fileContent);

                    string fileLocations = string.Empty, fileDepartments = string.Empty, fileEmployees = string.Empty;

                    foreach (var item in intFiles)
                    {
                        if (item.Key.StartsWith("CCL"))
                        {
                            fileLocations = item.Value;
                        }
                        else if (item.Key.StartsWith("CCO"))
                        {
                            fileDepartments = item.Value;
                        }
                        else if (item.Key.StartsWith("CD"))
                        {
                            fileEmployees = item.Value;
                        }
                    }

                    try
                    {
                        //Fijamos una fecha para todas las trazas de la integración
                        resultadosIntegracionRepository.IntegrationProcessDateTime = DateTime.Now;
                        //Establecemos el fichero zip de migración para luego poder filtrar los procesados
                        resultadosIntegracionRepository.ProcessedFileName = fileToProcess;

                        //Todo el proceso está aropado por una transacción
                        repository.UnitOfWork.BeginTransaction();

                        //Integración localizaciones
                        (string[], string[][])csvLocations = BulkUtils.ReadCsvFromStringAsync(fileLocations);
                        await ImportLocalizations(csvLocations).ConfigureAwait(false);

                        await localizacionRepository.SaveChangesAsync().ConfigureAwait(false);

                        SendTimeOperationToLogger("Bulk Localizaciones");
                        //Integración Departamentos
                        (string[], string[][])csvDapartments = BulkUtils.ReadCsvFromStringAsync(fileDepartments);
                        await ImportDepartments(csvDapartments).ConfigureAwait(false);

                        await departamentoRepository.SaveChangesAsync().ConfigureAwait(false);

                        SendTimeOperationToLogger("Bulk Departamentos");
                        //Integración Empleados
                        (string[], string[][])csvEmployees = BulkUtils.ReadCsvFromStringAsync(fileEmployees);
                        await ImportEmployees(csvEmployees).ConfigureAwait(false);

                        //Guardamos todos los cambios
                        await resultadosIntegracionRepository.SaveChangesAsync().ConfigureAwait(false);

                        repository.UnitOfWork.Commit();

                        SendTimeOperationToLogger("Commit");
                    }
                    catch (Exception)
                    {
                        repository.UnitOfWork.Rollback();
                        throw;
                    }
                }

                return(new IntegrationFileStorageResult());
            }
            /// <summary>
            /// Handle
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async Task <bool> Handle(BulkLocationsRequest request, CancellationToken cancellationToken)
            {
                (string[], string[][])csv = await BulkUtils.ReadCsvAsync(request.LocationsFile, cancellationToken).ConfigureAwait(false);


                string[]   headers = csv.Item1;
                string[][] data    = csv.Item2;
                if (!data.Any())
                {
                    return(false);
                }

                Localizacion.SetPropertyIndexes(headers);
                Area.SetPropertyIndexes(headers);
                Region.SetPropertyIndexes(headers);
                Pais.SetPropertyIndexes(headers);

                List <string> existentLocations = await repository.GetAll().Select(u => u.Nombre).ToListAsync().ConfigureAwait(false);

                List <Area> existentAreas = (await areaRepository.GetAll()
                                             .Select(a => new {
                    a.Region.IdPais,
                    Area = a
                }).ToListAsync().ConfigureAwait(false))
                                            .Select(x => {
                    var aNew    = x.Area;
                    aNew.IdPais = x.IdPais;
                    return(aNew);
                }).ToList();
                List <Region> existentRegions = await regionRepository.GetAll().ToListAsync().ConfigureAwait(false);

                List <Pais> existentPaises = await paisRepository.GetAll().ToListAsync().ConfigureAwait(false);

                List <Localizacion> newLocalizaciones = new List <Localizacion>();
                List <Area>         newAreas          = new List <Area>();
                List <Region>       newRegions        = new List <Region>();
                List <Pais>         newPaises         = new List <Pais>();

                int indexArea   = existentAreas.Max(p => p.Id);
                int indexRegion = existentRegions.Max(p => p.Id);
                int indexPais   = existentPaises.Max(p => p.Id);

                foreach (string[] dataRow in data)
                {
                    Localizacion newLocalizacion = new Localizacion(dataRow);
                    Area         newArea         = new Area(dataRow);
                    Region       newRegion       = new Region(dataRow);
                    Pais         newPais         = new Pais(dataRow);

                    if (!string.IsNullOrEmpty(newPais.Nombre))
                    {
                        if (existentPaises.Any(p => p.Nombre == newPais.Nombre))
                        {
                            newPais = existentPaises.Single(p => p.Nombre == newPais.Nombre);
                        }
                        else if (newPaises.Any(p => p.Nombre == newPais.Nombre))
                        {
                            newPais = newPaises.Single(p => p.Nombre == newPais.Nombre);
                        }
                        else
                        {
                            indexPais++;
                            newPais.Id             = indexPais;
                            newPais.LastAction     = "CREATE";
                            newPais.LastActionDate = DateTime.UtcNow;
                            newPaises.Add(newPais);
                        }

                        if (!string.IsNullOrEmpty(newRegion.Nombre))
                        {
                            if (existentRegions.Any(p => p.Nombre == newRegion.Nombre))
                            {
                                newRegion = existentRegions.Single(p => p.Nombre == newRegion.Nombre);
                            }
                            else if (newRegions.Any(p => p.Nombre == newRegion.Nombre))
                            {
                                newRegion = newRegions.Single(p => p.Nombre == newRegion.Nombre);
                            }
                            else
                            {
                                indexRegion++;
                                newRegion.Id             = indexRegion;
                                newRegion.IdPais         = newPais.Id;
                                newRegion.LastAction     = "CREATE";
                                newRegion.LastActionDate = DateTime.UtcNow;
                                newRegions.Add(newRegion);
                            }
                        }
                        else if (!string.IsNullOrEmpty(newArea.Nombre))
                        {
                            if (existentRegions.Any(p => p.Nombre == newArea.Nombre))
                            {
                                newRegion = existentRegions.Single(p => p.Nombre == newArea.Nombre);
                            }
                            else if (newRegions.Any(p => p.Nombre == newArea.Nombre))
                            {
                                newRegion = newRegions.Single(p => p.Nombre == newArea.Nombre);
                            }
                            else
                            {
                                indexRegion++;
                                newRegion.Id             = indexRegion;
                                newRegion.Nombre         = newArea.Nombre;
                                newRegion.IdPais         = newPais.Id;
                                newRegion.LastAction     = "CREATE";
                                newRegion.LastActionDate = DateTime.UtcNow;
                                newRegions.Add(newRegion);
                            }
                        }

                        if (!string.IsNullOrEmpty(newArea.Nombre))
                        {
                            if (existentAreas.Any(p => p.Nombre == newArea.Nombre && p.IdPais == newPais.Id))
                            {
                                newArea = existentAreas.Single(p => p.Nombre == newArea.Nombre && p.IdPais == newPais.Id);
                            }
                            else if (newAreas.Any(p => p.Nombre == newArea.Nombre && p.IdPais == newPais.Id))
                            {
                                newArea = newAreas.Single(p => p.Nombre == newArea.Nombre && p.IdPais == newPais.Id);
                            }
                            else
                            {
                                indexArea++;
                                newArea.Id             = indexArea;
                                newArea.IdRegion       = newRegion.Id;
                                newArea.IdPais         = newPais.Id;
                                newArea.LastAction     = "CREATE";
                                newArea.LastActionDate = DateTime.UtcNow;
                                newAreas.Add(newArea);
                            }
                        }
                    }

                    if (existentLocations.Contains(newLocalizacion.Nombre))
                    {
                        continue;
                    }

                    newLocalizacion.IdArea = null;
                    if (!string.IsNullOrEmpty(newArea.Nombre))
                    {
                        newLocalizacion.IdArea = newArea.Id;
                    }

                    newLocalizacion.LastAction     = "CREATE";
                    newLocalizacion.LastActionDate = DateTime.UtcNow;

                    newLocalizaciones.Add(newLocalizacion);
                }

                await paisRepository.BulkInsertAsync(newPaises).ConfigureAwait(false);

                await regionRepository.BulkInsertAsync(newRegions).ConfigureAwait(false);

                await areaRepository.BulkInsertAsync(newAreas).ConfigureAwait(false);

                await repository.BulkInsertAsync(newLocalizaciones).ConfigureAwait(false);

                //repository.AddRange(newLocalizaciones);
                //await repository.SaveChangesAsync().ConfigureAwait(false);

                return(true);
            }