private Payer RegisterPayer(AdditionalSettings additionalSettings, Payer payer, uint?existingPayerId, string name, string fullname)
        {
            Payer currentPayer = null;

            if (additionalSettings.PayerExists)
            {
                if ((payer != null && payer.Id != 0) || existingPayerId.HasValue)
                {
                    var id = existingPayerId.HasValue ? existingPayerId.Value : payer.Id;
                    currentPayer = DbSession.Load <Payer>(id);
                    if (currentPayer.Orgs.Count == 0)
                    {
                        var org = new LegalEntity(currentPayer);
                        currentPayer.Orgs.Add(org);
                        DbSession.Save(org);
                    }
                }
            }
            if (currentPayer == null)
            {
                currentPayer = new Payer(name, fullname);
                currentPayer.BeforeNamePrefix = "Аптека";
                DbSession.Save(currentPayer);
            }
            return(currentPayer);
        }
        public void RegisterSupplier()
        {
            var supplier = new Supplier();
            var user     = new User();

            supplier.Account             = new SupplierAccount(supplier);
            PropertyBag["options"]       = new AdditionalSettings();
            PropertyBag["supplier"]      = supplier;
            PropertyBag["user"]          = user;
            PropertyBag["regions"]       = Region.All(DbSession).ToArray();
            PropertyBag["SingleRegions"] = true;
        }
        private void CreateDrugstore(Client client, AdditionalSettings additionalSettings, Supplier supplier)
        {
            if (additionalSettings.ShowForOneSupplier)
            {
                client.Settings.InvisibleOnFirm         = DrugstoreType.Hidden;
                client.Settings.NoiseCosts              = true;
                client.Settings.NoiseCostExceptSupplier = DbSession.Load <Supplier>(supplier.Id);
            }
            DbSession.Save(client);
            DbSession.Flush();

            client.MaintainIntersection(DbSession);
            client.Addresses.Each(a => a.MaintainInscribe(DbSession));
        }
        public void RegisterClient()
        {
            var regions = Region.All(DbSession).ToArray();
            var client  = new Client(new Payer(""), regions.First());
            var user    = new User(client);

            PropertyBag["defaultSettings"] = Defaults;
            PropertyBag["client"]          = client;
            PropertyBag["user"]            = user;
            PropertyBag["address"]         = client.AddAddress("");
            PropertyBag["account"]         = user.Accounting;
            PropertyBag["permissions"]     = UserPermission.FindPermissionsForDrugstore(DbSession);
            PropertyBag["regions"]         = regions;
            PropertyBag["clientContacts"]  = new[] { new Contact(ContactType.Phone, string.Empty), new Contact(ContactType.Email, string.Empty) };
            PropertyBag["options"]         = new AdditionalSettings();
        }
        public void RegisterClient([DataBind("client")] Client client,
                                   ulong homeRegion,
                                   [DataBind("regionSettings")] RegionSettings[] regionSettings,
                                   [DataBind("permissions")] UserPermission[] permissions,
                                   [DataBind("options")] AdditionalSettings options,
                                   [DataBind("payer")] Payer payer,
                                   uint?existingPayerId,
                                   [DataBind("supplier")] Supplier supplier,
                                   [DataBind("clientContacts")] Contact[] clientContacts,
                                   [DataBind("userContacts")] Contact[] userContacts,
                                   [DataBind("userPersons")] Person[] userPersons,
                                   string additionalEmailsForSendingCard,
                                   string comment)
        {
            PasswordCreation password = null;
            var fullName     = client.FullName.Replace("№", "N").Trim();
            var name         = client.Name.Replace("№", "N").Trim();
            var currentPayer = RegisterPayer(options, payer, existingPayerId, name, fullName);

            client = new Client(currentPayer, DbSession.Load <Region>(homeRegion))
            {
                FullName          = fullName,
                Name              = name,
                MaskRegion        = regionSettings.GetBrowseMask(),
                Registration      = new RegistrationInfo(Admin),
                ContactGroupOwner = new ContactGroupOwner()
            };
            Defaults.Apply(client);
            client.Settings.WorkRegionMask  = client.MaskRegion;
            client.Settings.OrderRegionMask = regionSettings.GetOrderMask();
            var     user    = new User(client);
            var     address = new Address();
            Account account = user.Accounting;

            BindObjectInstance(client.Settings, "client.Settings");
            BindObjectInstance(user, "user");
            BindObjectInstance(account, "account");
            SetARDataBinder(AutoLoadBehavior.NullIfInvalidKey);
            BindObjectInstance(address, "address");

            var equalClientInRegion = DbSession.QueryOver <Client>().Where(c => c.HomeRegion.Id == homeRegion && c.Name == name).RowCount() > 0;
            var forValidation       = new List <object> {
                client
            };

            if (!options.RegisterEmpty)
            {
                forValidation.Add(user);
                client.AddUser(user);
            }

            if (!IsValid(forValidation) || equalClientInRegion)
            {
                DbSession.Delete(currentPayer);
                RegisterClient();
                PropertyBag["clientContacts"] = clientContacts;
                PropertyBag["client"]         = client;
                PropertyBag["user"]           = user;
                PropertyBag["address"]        = address;
                PropertyBag["options"]        = options;
                PropertyBag["account"]        = account;
                if (equalClientInRegion)
                {
                    Error(string.Format("В данном регионе уже существует клиент с таким именем {0}", name));
                }
                return;
            }

            if (String.IsNullOrEmpty(address.Value) || options.RegisterEmpty)
            {
                address = null;
            }

            if (options.RegisterEmpty)
            {
                user = null;
            }

            if (address != null)
            {
                address.Value = address.Value.Replace("№", "N").Trim();
                client.AddAddress(address);
            }

            CreateDrugstore(client, options, supplier);
            AddContacts(client.ContactGroupOwner, clientContacts);

            if (user != null)
            {
                CreateUser(user, permissions, userPersons);
                user.UpdateContacts(userContacts);
                user.RegistredWith(client.Addresses.LastOrDefault());

                password = user.CreateInAd(Session);

                var log = new PasswordChangeLogEntity(user.Login);
                if (options.SendRegistrationCard)
                {
                    log = SendRegistrationCard(log, user, password.Password, additionalEmailsForSendingCard);
                }

                string smsLog = "";
                if (options.SendSmsToUser)
                {
                    var phonesForSendToUserArray = user.GetPhonesForSendingSms().Select(x => x.Number).ToArray();
                    smsLog = smsLog + " " + ReportHelper.SendSmsPasswordToUser(user, password.Password, phonesForSendToUserArray);
                }

                if (options.SendSmsToAdmin)
                {
                    var phonesForSendToAdminArray = GetPhoneSupportByRegionForSms(user.RootService.HomeRegion.Id);
                    smsLog = smsLog + " " + ReportHelper.SendSmsToRegionalAdmin(user, password.Password, phonesForSendToAdminArray);
                }
                log.SmsLog = smsLog;

                DbSession.Save(log);
            }

            client.Addresses.Each(a => a.CreateFtpDirectory());
            client.AddBillingComment(comment);
            new Mailer(DbSession).ClientRegistred(client, comment, Defaults);

            if (!options.FillBillingInfo)
            {
                Mail().NotifyBillingAboutClientRegistration(client);
            }

            if (options.FillBillingInfo)
            {
                Redirect("Register", "RegisterPayer", new {
                    id = client.Payers.Single().Id,
                    showRegistrationCard = options.ShowRegistrationCard,
                    passwordId           = password != null ? password.PasswordId : ""
                });
            }
            else if (client.Users.Count > 0 && options.ShowRegistrationCard)
            {
                Redirect("main", "report", new {
                    id         = client.Users.First().Id,
                    passwordId = password.PasswordId
                });
            }
            else
            {
                Notify("Регистрация завершена успешно");
                RedirectTo(client);
            }
        }
        public void RegisterSupplier(
            [DataBind("supplierContacts")] Contact[] supplierContacts,
            ulong homeRegion,
            [DataBind("regionSettings")] RegionSettings[] regionSettings,
            [DataBind("options")] AdditionalSettings options,
            [DataBind("payer")] Payer payer,
            uint?existingPayerId,
            [DataBind("userContacts")] Contact[] userContacts,
            [DataBind("userPersons")] Person[] userPersons,
            string additionalEmailsForSendingCard,
            string comment)
        {
            var supplier = new Supplier();

            supplier.RegionMask = regionSettings.GetBrowseMask();
            SetARDataBinder(AutoLoadBehavior.NewRootInstanceIfInvalidKey);
            BindObjectInstance(supplier, "supplier");
            SetBinder(new DataBinder());

            var currentPayer = RegisterPayer(options, payer, existingPayerId, supplier.Name, supplier.FullName);

            supplier.HomeRegion        = DbSession.Load <Region>(homeRegion);
            supplier.Payer             = currentPayer;
            supplier.Account           = new SupplierAccount(supplier);
            supplier.ContactGroupOwner = new ContactGroupOwner(supplier.GetAditionalContactGroups());
            supplier.Registration      = new RegistrationInfo(Admin);

            var user = new User(supplier.Payer, supplier);

            BindObjectInstance(user, "user");

            if (!IsValid(supplier, user, options))
            {
                RegisterSupplier();
                PropertyBag["options"]  = options;
                PropertyBag["supplier"] = supplier;
                PropertyBag["user"]     = user;
                PropertyBag["options"]  = options;
                return;
            }
            var tokens = DbSession.Query <FederalSupplierToken>().ToList();

            supplier.IsFederal = tokens.Select(x => x.Name)
                                 .Any(x => supplier.Name.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                                      supplier.FullName.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0);
            supplier.ContactGroupOwner.AddContactGroup(new ContactGroup(ContactGroupType.MiniMails));
            currentPayer.Suppliers.Add(supplier);
            currentPayer.UpdatePaymentSum();
            AddContacts(supplier.ContactGroupOwner, supplierContacts);
            supplier.OrderRules.Add(new OrderSendRules(Defaults, supplier));
            DbSession.Save(supplier);

            foreach (var group in supplier.ContactGroupOwner.ContactGroups)
            {
                var persons  = BindObject <List <Person> >(group.Type + "Persons");
                var contacts = BindObject <List <Contact> >(group.Type + "Contacts");

                group.Persons  = persons;
                group.Contacts = contacts;
            }

            var groups = BindObject <RegionalDeliveryGroup[]>("orderDeliveryGroup");

            foreach (var group in groups)
            {
                group.Region            = DbSession.Load <Region>(group.Region.Id);
                group.Name              = "Доставка заказов " + group.Region.Name;
                group.ContactGroupOwner = supplier.ContactGroupOwner;
                supplier.ContactGroupOwner.ContactGroups.Add(group);

                //повторная валидация, тк когда производился binding валидация не прошла
                //тк не было заполнено поле Name
                Validator.IsValid(group);
            }

            foreach (var group in supplier.ContactGroupOwner.ContactGroups)
            {
                group.Adopt();
                DbSession.Save(group);
                group.Persons.Each(p => DbSession.Save(p));
            }

            DbSession.Flush();

            DbSession.Query <Region>()
            .Where(r => (r.Id & supplier.RegionMask) > 0)
            .Each(r => supplier.AddRegion(r, DbSession));
            CreateSupplier(supplier);
            Maintainer.MaintainIntersection(supplier, DbSession);

            user.UpdateContacts(userContacts);
            foreach (var person in userPersons)
            {
                user.AddContactPerson(person.Name);
            }
            user.AssignDefaultPermission(DbSession);
            user.Setup(DbSession);

            var password = user.CreateInAd(Session);

            supplier.AddBillingComment(comment);

            Mailer.SupplierRegistred(supplier, comment);
            //Создание директорий для поставщика на фтп
            supplier.CreateDirs();

            var log = new PasswordChangeLogEntity(user.Login);

            if (options.SendRegistrationCard)
            {
                log = SendRegistrationCard(log, user, password.Password, additionalEmailsForSendingCard);
            }

            string smsLog = "";

            if (options.SendSmsToUser)
            {
                var phonesForSendToUserArray = user.GetPhonesForSendingSms().Select(x => x.Number).ToArray();
                smsLog = smsLog + " " + ReportHelper.SendSmsPasswordToUser(user, password.Password, phonesForSendToUserArray);
            }

            if (options.SendSmsToAdmin)
            {
                var phonesForSendToAdminArray = GetPhoneSupportByRegionForSms(user.RootService.HomeRegion.Id);
                smsLog = smsLog + " " + ReportHelper.SendSmsToRegionalAdmin(user, password.Password, phonesForSendToAdminArray);
            }
            log.SmsLog = smsLog;

            DbSession.Save(log);

            if (options.FillBillingInfo)
            {
                Redirect("Register", "RegisterPayer", new {
                    id = supplier.Payer.Id,
                    showRegistrationCard = options.ShowRegistrationCard,
                    passwordId           = password.PasswordId
                });
            }
            else if (supplier.Users.Count > 0 && options.ShowRegistrationCard)
            {
                Redirect("main", "report", new {
                    id         = supplier.Users.First().Id,
                    passwordId = password.PasswordId
                });
            }
            else
            {
                Notify("Регистрация завершена успешно");
                Redirect("Suppliers", "Show", new { id = supplier.Id });
            }
        }