Example #1
0
        private async Task <EmployeeRegisterResult> CreateNewEmployee(ResolveFieldContext <object> context)
        {
            var companyId = context.GetArgument <int>("companyId");
            var isSendLoginPasswordOnEmail = context.GetArgument <bool>("isSendLoginPasswordOnEmail");
            var newEmployee  = context.GetArgument <ApplicationUser>("employee");
            var actionResult = new EmployeeRegisterResult();

            try
            {
                // Если был выбран пункт "Отправить логин и пароль на указанный e-mail", то
                // тогда генерируем пароль, создаем пользователя и
                // отправляем логин и пароль на указанный email
                if (isSendLoginPasswordOnEmail)
                {
                    string password = PasswordGenerator.Generate();

                    await _unitOfWork.BeginTransactionAsync();

                    try
                    {
                        // Ищем указанный отдел
                        var department = (await _unitOfWork.Department.Find(d =>
                                                                            d.Name.ToLower().Equals(newEmployee.Department.Name.ToLower()))).FirstOrDefault();

                        // Если он найдена то добавляем его
                        if (department is null)
                        {
                            await _unitOfWork.Department.Insert(newEmployee.Department);

                            await _unitOfWork.SaveChangesAsync();
                        }
                        else
                        {
                            newEmployee.Department = department;
                        }

                        // Ищем указанную должность
                        var position = (await _unitOfWork.Position.Find(p =>
                                                                        p.Name.ToLower().Equals(newEmployee.Position.Name.ToLower()))).FirstOrDefault();

                        // Если она не найдена то добавляем ее
                        if (position is null)
                        {
                            await _unitOfWork.Position.Insert(newEmployee.Position);

                            await _unitOfWork.SaveChangesAsync();
                        }
                        else
                        {
                            newEmployee.Position = position;
                        }

                        newEmployee.UserName = newEmployee.Email;

                        // Создаем нового пользователя
                        var result = await _userManager.CreateAsync(newEmployee, password);

                        if (result.Succeeded)
                        {
                            // Добавляем успешно созданого пользователя к указанной компании
                            await _unitOfWork.Company.AddEmployee(companyId, newEmployee);

                            await _unitOfWork.SaveChangesAsync();

                            // Отправляем на указанный e-mail письмо с инструкциями, логином и паролем
                            ApplicationUser user = await _userManager.GetUserAsync((ClaimsPrincipal)context.UserContext);

                            await _emailSender.SendRegestrationDateAsync(String.Format("{0} {1} {2}",
                                                                                       user.LastName,
                                                                                       user.FirstName,
                                                                                       user.Patronymic), newEmployee.Email, password, String.Format("{0}login", _configuration["WebClientUrl"]));

                            // Создаем уведомление о присоединении нового сотрудника к компании
                            CompanyNotification newCompanyNotification = new CompanyNotification
                            {
                                Author      = user,
                                CompanyId   = companyId,
                                NewEmployee = newEmployee,
                                Type        = DAL.Entities.CompanyNotificationType.EmployeeJoin,
                                DateTime    = DateTime.Now
                            };

                            await _unitOfWork.CompanyNotification.Insert(newCompanyNotification);
                        }
                        else
                        {
                            throw new Exception("Пользователь не был создан!!");
                        }

                        _unitOfWork.Commit();

                        actionResult.Status   = true;
                        actionResult.Employee = newEmployee;
                    }
                    catch (Exception)
                    {
                        actionResult.Status   = false;
                        actionResult.Employee = null;

                        _unitOfWork.Rollback();
                    }
                }
                else
                {
                    ApplicationUser user = await _userManager.GetUserAsync((ClaimsPrincipal)context.UserContext);

                    // Иначе создаем запрос на регистрацию на базе указанных даннных
                    string code = await _unitOfWork.User.CreateRegistrationRequest(newEmployee, user.Id);

                    if (!string.IsNullOrEmpty(code))
                    {
                        await _emailSender.SendInvitationAsync(newEmployee.Email, _configuration["WebClientUrl"] + $"join?ref={code}&email={newEmployee.Email}");

                        actionResult.Status = true;
                    }
                    else
                    {
                        actionResult.Status   = false;
                        actionResult.Employee = null;
                    }
                }
            }
            catch (Exception)
            {
                actionResult.Status   = false;
                actionResult.Employee = null;
            }

            return(actionResult);
        }
Example #2
0
        public async Task <IActionResult> ExtendedRegistration([FromBody] ExtendedRegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                await _unitOfWork.BeginTransactionAsync();

                try
                {
                    var request = (await _unitOfWork.RegistrationRequest.Find(r => r.Code.Equals(model.Ref)))?.FirstOrDefault();

                    if (request is null)
                    {
                        throw new Exception("Неверный код");
                    }

                    var department = (await _unitOfWork.Department.Find(d => d.Name.ToLower().Equals(request.Department.ToLower())))?.FirstOrDefault();

                    if (department is null)
                    {
                        var newDepartment = new Department
                        {
                            Name = request.Department,
                        };

                        await _unitOfWork.Department.Insert(newDepartment);

                        await _unitOfWork.SaveChangesAsync();

                        department = newDepartment;
                    }

                    var position = (await _unitOfWork.Position.Find(p =>
                                                                    p.Name.ToLower().Equals(request.Position.ToLower())))?.FirstOrDefault();

                    if (position is null)
                    {
                        var newPosition = new Position
                        {
                            Name = request.Position
                        };

                        await _unitOfWork.Position.Insert(newPosition);

                        await _unitOfWork.SaveChangesAsync();

                        position = newPosition;
                    }


                    var newEmployee = new ApplicationUser
                    {
                        UserName   = request.Email,
                        Email      = request.Email,
                        FirstName  = request.FirstName,
                        LastName   = request.LastName,
                        Patronymic = request.Patronymic,
                        Department = department,
                        Position   = position
                    };

                    newEmployee.CompanyEmployees = new List <CompanyEmployee>
                    {
                        new CompanyEmployee
                        {
                            CompanyId = request.CompanyId,
                            User      = newEmployee
                        }
                    };

                    // Создаем нового пользователя
                    var result = await _userManager.CreateAsync(newEmployee, model.Password);

                    if (result.Succeeded)
                    {
                        await _unitOfWork.RegistrationRequest.Delete(request.RegistrationRequestId);

                        await _unitOfWork.SaveChangesAsync();

                        // Создаем уведомление о присоединении нового сотрудника к компании
                        CompanyNotification newCompanyNotification = new CompanyNotification
                        {
                            Author      = newEmployee,
                            CompanyId   = request.CompanyId,
                            NewEmployee = newEmployee,
                            Type        = CompanyNotificationType.EmployeeJoin,
                            DateTime    = DateTime.Now
                        };

                        await _unitOfWork.CompanyNotification.Insert(newCompanyNotification);

                        _unitOfWork.Commit();
                        return(Ok());
                    }
                    else
                    {
                        _unitOfWork.Rollback();
                        return(BadRequest(result.Errors));
                    }
                }
                catch (Exception ex)
                {
                    _unitOfWork.Rollback();
                    return(BadRequest(ex.Message));
                }
            }

            string messages = string.Join("; ", ModelState.Values
                                          .SelectMany(x => x.Errors)
                                          .Select(x => x.ErrorMessage));

            return(BadRequest(messages));
        }