public ActionResult Registration(RegProducerViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewBagProducerList();
                return(View("Index", model));
            }

            ViewBagAppointmentList(model.ProducerId);
            var producerName = DB.producernames.Single(x => x.ProducerId == model.ProducerId).ProducerName;
            var company      = DB.AccountCompany.SingleOrDefault(x => x.ProducerId == model.ProducerId);

            // если от данного производителя регистрировались, возвращаем форму для регистрации пользователя с моделью RegDomainViewModel
            if (company != null)
            {
                var modelDomainView = new RegDomainViewModel()
                {
                    Producers = model.ProducerId, ProducerName = producerName
                };
                ViewBag.DomainList = company.CompanyDomainName
                                     .Select(x => new OptionElement {
                    Text = '@' + x.Name, Value = x.Id.ToString()
                })
                                     .ToList();
                return(View("DomainRegistration", modelDomainView));
            }

            var modelUi = new RegViewModel()
            {
                ProducerId = model.ProducerId, ProducerName = producerName
            };

            return(View(modelUi));
        }
        private Account SaveAccount(AccountCompany accountCompany, RegViewModel Reg_ViewModel = null, RegDomainViewModel RegDomain_ViewModel = null, RegNotProducerViewModel RegNotProducer_ViewModel = null, string Pass = null)
        {
            var newAccount = new Account();

            newAccount.EnabledEnum = UserStatus.New;
            newAccount.TypeUser    = (sbyte)TypeUsers.ProducerUser;
            newAccount.CompanyId   = accountCompany.Id;

            // регистрация первого пользователя компании
            if (Reg_ViewModel != null)
            {
                newAccount.Login           = Reg_ViewModel.login;
                newAccount.Password        = Md5HashHelper.GetHash(Pass);
                newAccount.PasswordUpdated = DateTime.Now;
                newAccount.FirstName       = Reg_ViewModel.FirstName;
                newAccount.LastName        = Reg_ViewModel.LastName;
                newAccount.OtherName       = Reg_ViewModel.OtherName;
                newAccount.Name            = Reg_ViewModel.LastName + " " + Reg_ViewModel.FirstName + " " + Reg_ViewModel.OtherName;
                newAccount.Phone           = Reg_ViewModel.PhoneNumber;
                newAccount.AppointmentId   = Reg_ViewModel.AppointmentId;
            }

            // регистрация второго и последующих пользователей производителя
            if (RegDomain_ViewModel != null)
            {
                newAccount.Login           = RegDomain_ViewModel.Mailname + "@" + DB.CompanyDomainName.Single(x => x.Id == RegDomain_ViewModel.EmailDomain).Name;
                newAccount.Password        = Md5HashHelper.GetHash(Pass);
                newAccount.PasswordUpdated = DateTime.Now;
                newAccount.FirstName       = RegDomain_ViewModel.FirstName;
                newAccount.LastName        = RegDomain_ViewModel.LastName;
                newAccount.OtherName       = RegDomain_ViewModel.OtherName;
                newAccount.Name            = RegDomain_ViewModel.LastName + " " + RegDomain_ViewModel.FirstName + " " + RegDomain_ViewModel.OtherName;
                newAccount.Phone           = RegDomain_ViewModel.PhoneNumber;
                newAccount.AppointmentId   = RegDomain_ViewModel.AppointmentId;
            }

            // Если компания в списке отсутствует
            if (RegNotProducer_ViewModel != null)
            {
                // создали новую должность
                var appointment = new AccountAppointment()
                {
                    Name = RegNotProducer_ViewModel.Appointment, GlobalEnabled = false
                };
                DB.Entry(appointment).State = EntityState.Added;
                DB.SaveChanges();

                newAccount.Login         = RegNotProducer_ViewModel.login;
                newAccount.FirstName     = RegNotProducer_ViewModel.FirstName;
                newAccount.LastName      = RegNotProducer_ViewModel.LastName;
                newAccount.OtherName     = RegNotProducer_ViewModel.OtherName;
                newAccount.Name          = RegNotProducer_ViewModel.LastName + " " + RegNotProducer_ViewModel.FirstName + " " + RegNotProducer_ViewModel.OtherName;
                newAccount.Phone         = RegNotProducer_ViewModel.PhoneNumber;
                newAccount.AppointmentId = appointment.Id;
                // особый статус
                newAccount.EnabledEnum = UserStatus.Request;
            }

            DB.Entry(newAccount).State = EntityState.Added;
            DB.SaveChanges();
            return(newAccount);
        }
        public ActionResult DomainRegistration(RegDomainViewModel model)
        {
            var company = DB.AccountCompany.Single(x => x.ProducerId == model.Producers);

            // проверка email
            var domain = company.CompanyDomainName.SingleOrDefault(x => x.Id == model.EmailDomain);

            if (model.Mailname?.Contains("@") == true)
            {
                var parts = model.Mailname.Split('@');
                model.Mailname = parts[0];
                if (!String.Equals(domain?.Name, parts[1], StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("Mailname", "Домен должен совпадать с выбранным");
                }
            }
            var ea = new EmailAddressAttribute();

            if (domain == null || !ea.IsValid($"{model.Mailname}@{domain.Name}"))
            {
                ModelState.AddModelError("Mailname", "Неверный формат email");
            }

            // если невалидный ввод - возвращаем
            if (!ModelState.IsValid)
            {
                ViewBag.DomainList = company.CompanyDomainName.Select(x => new OptionElement {
                    Text = '@' + x.Name, Value = x.Id.ToString()
                }).ToList();
                ViewBagAppointmentList(model.Producers);
                return(View(model));
            }

            // если пользователь с таким email уже регистрировался - возвращаем
            var emailAdress = model.Mailname + "@" + DB.CompanyDomainName.Single(x => x.Id == model.EmailDomain).Name;
            var userExsist  = DB.Account.Any(x => x.Login == emailAdress);

            if (userExsist)
            {
                ViewBag.DomainList = company.CompanyDomainName.Select(x => new OptionElement {
                    Text = '@' + x.Name, Value = x.Id.ToString()
                }).ToList();
                ViewBagAppointmentList(model.Producers);
                ErrorMessage("Данный email уже зарегистрирован в нашей базе, попробуйте восстановить пароль");
                return(View(model));
            }

            // создали новый аккаунт
            var password = GetRandomPassword();
            var account  = SaveAccount(accountCompany: company, RegDomain_ViewModel: model, Pass: password);

            var regionCodes = DB.Regions().Select(x => x.Id).ToList();

            foreach (var regionCode in regionCodes)
            {
                account.AccountRegion.Add(new AccountRegion()
                {
                    AccountId = account.Id, RegionId = regionCode
                });
            }

            // ищем группу "все пользователи", если такой нет - создаем
            var otherGroup = DB.AdminGroup();

            // добавляем пользователя в группу все пользователи
            account.AccountGroup.Add(otherGroup);
            account.LastUpdatePermisison = DateTime.Now;
            DB.SaveChanges();

            // отправили письмо о регистрации
            Mails.SendRegistrationMessage(account, password);
            SuccessMessage("Письмо с паролем отправлено на ваш email");
            return(Redirect("~"));
        }