Пример #1
0
        public void Add(
            [DataBind("contacts")] Contact[] contacts,
            uint clientId,
            string comment)
        {
            var client  = Client.FindAndCheck <Client>(clientId);
            var address = new Address(client);

            RecreateOnlyIfNullBinder.Prepare(this);
            BindObjectInstance(address, "address", AutoLoadBehavior.NewRootInstanceIfInvalidKey);
            if (client.Payers.Count > 1 && address.AvaliableForUsers != null && address.AvaliableForUsers.Count > 0)
            {
                address.AvaliableForUsers.Each(u => DbSession.Refresh(u));
                if (address.AvaliableForUsers.All(u => u.Payer.Id != address.LegalEntity.Payer.Id))
                {
                    Add(client.Id);
                    PropertyBag["client"]  = client;
                    PropertyBag["address"] = address;
                    Error("Ошибка регистрации: попытка зарегистрировать пользователя и адрес в различных Плательщиках");
                    return;
                }
            }
            client.AddAddress(address);
            address.UpdateContacts(contacts);
            DbSession.Save(address);
            address.Maintain(DbSession);

            address.CreateFtpDirectory();
            address.AddBillingComment(comment);
            new Mailer(DbSession).Registred(address, comment, Defaults);
            Notify("Адрес доставки создан");
            RedirectUsingRoute("client", "show", new { client.Id });
        }
        public void Add(
            [DataBind("contacts")] Contact[] contacts,
            [DataBind("regionSettings")] RegionSettings[] regionSettings,
            [DataBind("persons")] Person[] persons,
            string comment,
            bool sendClientCard,
            uint clientId,
            string mails,
            string jsonSource,
            string[] phonesForSendToUserArray,
            string[] phonesForSendToAdminArray)
        {
            /*Грязный ХАК, почему-то если принудительно не загрузить так, не делается Service.FindAndCheck<Service>(clientId)*/
            DbSession.Get <Client>(clientId);
            DbSession.Get <Supplier>(clientId);
            var service = Service.FindAndCheck <Service>(clientId);
            var user    = new User(service);
            var address = new Address();

            SetARDataBinder(AutoLoadBehavior.NullIfInvalidKey);
            var account = user.Accounting;

            BindObjectInstanceForUser(user, "user", jsonSource);
            BindObjectInstance(address, "address", AutoLoadBehavior.NewInstanceIfInvalidKey);
            BindObjectInstance(account, "account", AutoLoadBehavior.NewInstanceIfInvalidKey);

            if (!IsValid(user))
            {
                Add(clientId, user);
                PropertyBag["account"]                  = account;
                PropertyBag["UserMessage"]              = comment;
                PropertyBag["SendToEmail"]              = sendClientCard;
                PropertyBag["emailForSend"]             = mails;
                PropertyBag["InputPersonsList"]         = persons;
                PropertyBag["InputContactsList"]        = contacts;
                PropertyBag["SelectedRegions"]          = regionSettings;
                PropertyBag["deliveryAddress"]          = address.Value ?? "";
                PropertyBag["phonesForSendToUserList"]  = user.GetPhonesForSendingSms();
                PropertyBag["phonesForSendToAdminList"] = GetAdminByRegionForSms(user.RootService.HomeRegion.Id);
                if (!String.IsNullOrEmpty(jsonSource))
                {
                    var errorSummary = Validator.GetErrorSummary(user);
                    throw new Exception(errorSummary.InvalidProperties.Implode(x => $"{x} {errorSummary.GetErrorsForProperty(x).Implode()}"));
                }
                return;
            }

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

            if (service.IsClient() && ((Client)service).Payers.Count > 1)
            {
                if ((user.AvaliableAddresses.Any() && user.AvaliableAddresses.Select(s => s.LegalEntity).All(l => l.Payer.Id != user.Payer.Id)) || (address != null && address.LegalEntity.Payer.Id != user.Payer.Id))
                {
                    Add(service.Id);
                    PropertyBag["user"]    = user;
                    PropertyBag["address"] = address;
                    Error("Ошибка регистрации: попытка зарегистрировать пользователя и адрес в различных Плательщиках");
                    return;
                }
            }

            service.AddUser(user);
            user.Setup(DbSession);
            var password = user.CreateInAd(Session);

            if (string.IsNullOrEmpty(jsonSource))
            {
                user.WorkRegionMask  = regionSettings.GetBrowseMask();
                user.OrderRegionMask = regionSettings.GetOrderMask();
            }
            else
            {
                mails = user.EmailForCard;
            }
            user.SetFtpAccess(user.FtpAccess);

            var passwordChangeLog = new PasswordChangeLogEntity(user.Login);

            DbSession.Save(passwordChangeLog);
            user.UpdateContacts(contacts);
            user.UpdatePersons(persons);

            if (service.IsClient() && address != null)
            {
                address = ((Client)service).AddAddress(address);
                user.RegistredWith(address);
                address.SaveAndFlush();
                address.Maintain(DbSession);
            }
            DbSession.Save(service);

            if (address != null)
            {
                address.CreateFtpDirectory();
            }

            new Mailer(DbSession).Registred(user, comment, Defaults);
            user.AddBillingComment(comment);
            if (address != null)
            {
                address.AddBillingComment(comment);
                new Mailer(DbSession).Registred(address, comment, Defaults);
            }
            if (user.Client != null)
            {
                var message = string.Format("$$$Пользователю {0} - ({1}) подключены следующие адреса доставки: \r\n {2}",
                                            user.Id,
                                            user.Name,
                                            user.AvaliableAddresses.Implode(a => string.Format("\r\n {0} - ({1})", a.Id, a.Name)));
                DbSession.Save(new AuditRecord(message, user.Client)
                {
                    MessageType = LogMessageType.System
                });
            }

            string smsLog = ReportHelper.SendSmsPasswordToUser(user, password.Password, phonesForSendToUserArray);

            smsLog = smsLog + " " + ReportHelper.SendSmsToRegionalAdmin(user, password.Password, phonesForSendToAdminArray);
            passwordChangeLog.SmsLog = smsLog;

            var haveMails = !String.IsNullOrEmpty(mails) && !String.IsNullOrEmpty(mails.Trim());

            // Если установлена галка отсылать рег. карту на email и задан email (в спец поле или в контактной информации)
            if (sendClientCard && (haveMails || !string.IsNullOrEmpty(user.EmailForCard)))
            {
                var smtpId = ReportHelper.SendClientCard(user,
                                                         password.Password,
                                                         false,
                                                         Defaults,
                                                         mails);
                passwordChangeLog.SetSentTo(smtpId, new[] { mails }.Where(s => !String.IsNullOrWhiteSpace(s)).Implode());
                DbSession.Save(passwordChangeLog);

                Notify("Пользователь создан");

                if (string.IsNullOrEmpty(jsonSource))
                {
                    if (service.IsClient())
                    {
                        RedirectUsingRoute("Clients", "show", new { service.Id });
                    }
                    else
                    {
                        RedirectUsingRoute("Suppliers", "show", new { service.Id });
                    }
                }
                else
                {
                    Response.StatusCode = 200;
                    CancelView();
                }
            }
            else if (string.IsNullOrEmpty(jsonSource))
            {
                Redirect("main", "report", new { id = user.Id, passwordId = password.PasswordId });
            }
            else
            {
                Response.StatusCode = 200;
                CancelView();
            }
        }