Example #1
0
        public DTO.Account Save(DTO.Account account, Guid clientId, Guid currentAccount, bool addCurrentAppStore = true, bool simplifiedCustomer = false)
        {
            if (account.IsNull())
            {
                throw new ArgumentException("Necessário informar os dados de usuário");
            }

            if (account.Email.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("E-mail não informado");
            }

            Account _account = null;
            bool    convertCustomerToCompany = false;

            using (var transaction = Connection.BeginTransaction())
            {
                try
                {
                    ApplicationStore applicationStore = applicationStoreRepository.GetByClientId(clientId);

                    if (!applicationStore.IsNull())
                    {
                        Account accountDO = null;
                        var     document  = !account.Document.IsNullOrWhiteSpace() ? account.Document : null;

                        if (account.Code.IsEmpty())
                        {
                            accountDO = accountService.Get(account.Email, document, applicationStore, true, true);
                        }

                        if (account.Code.IsEmpty() && accountDO.IsNull())
                        {
                            if (account.Password.IsNullorEmpty())
                            {
                                account.Password = Account.GeneratePassword();
                            }

                            //get store code
                            var storeCode = applicationStore.GetStoreCodeByAuthType(account.StoreCode, true);

                            //get application on parameters
                            var applicationStores = applicationStoreService.Get(account.Applications, storeCode);

                            if (applicationStores.IsNull())
                            {
                                applicationStores = new List <ApplicationStore>();
                            }

                            if (addCurrentAppStore)
                            {
                                applicationStores.Add(applicationStoreService.Get(applicationStore, storeCode));
                            }

                            _account = account.Transfer(applicationStores);

                            Role _role;
                            applicationStores.ForEach(x =>
                            {
                                _role = roleRepository.GetByApplication(x.ApplicationCode, storeCode);

                                if (!_role.IsNull())
                                {
                                    _account.ConnectRole(_role);
                                }
                            });

                            Guid originStore = applicationStore.Store.IsMain ? Guid.Empty : applicationStore.Store.Code;

                            accountService.Add(_account, applicationStore, originStore, simplifiedCustomer);
                        }
                        else if (!currentAccount.IsEmpty())
                        {
                            if (!account.Code.IsEmpty())
                            {
                                var accounts = accountService.CheckEmailAndDocument(account.Email, account.Document, applicationStore, false);

                                if (accounts.Any(a => a.Code != account.Code))
                                {
                                    throw new ArgumentException("E-mail ou Docuemnto já cadastrados com outros dados");
                                }

                                _account = accountService.GetIfHasPermissionToUpdate(currentAccount, account.Code);
                            }
                            else
                            {
                                _account = accountService.GetIfHasPermissionToUpdate(currentAccount, accountDO.Code);
                            }

                            var newAccount = account.Transfer();

                            if (_account.Customer.IsNull() && !newAccount.Customer.IsNull())
                            {
                                if (newAccount.Customer.Type == CustomerType.Person)
                                {
                                    _account.Customer = new Person()
                                    {
                                        FirstName   = !newAccount.Customer.Name.IsNullOrWhiteSpace() ? newAccount.Customer.Name : newAccount.Customer.Email,
                                        Email       = newAccount.Customer.Email,
                                        Gender      = ((Person)newAccount.Customer).Gender,
                                        Cpf         = ((Person)newAccount.Customer).Cpf.ClearStrings(),
                                        Addresses   = newAccount.Customer.Addresses,
                                        AddressData = newAccount.Customer.Addresses.Serialize(),
                                        Password    = newAccount.Password
                                    };
                                }
                                else
                                {
                                    _account.Customer = new Company()
                                    {
                                        Cnpj        = ((Company)newAccount.Customer).Cnpj.ClearStrings(),
                                        Email       = newAccount.Customer.Email,
                                        Name        = !newAccount.Customer.Name.IsNullOrWhiteSpace() ? newAccount.Customer.Name : newAccount.Customer.Email,
                                        Addresses   = newAccount.Customer.Addresses,
                                        AddressData = newAccount.Customer.Addresses.Serialize(),
                                        Password    = newAccount.Password
                                    };
                                }

                                _account.Customer = customerRepository.Save(_account.Customer);
                            }

                            accountService.Update(_account, applicationStore.Store, newAccount);
                        }
                        else
                        {
                            throw new ArgumentException("Usuário já cadastrado");
                        }


                        if (!_account.Customer.IsNull() && !_account.Code.IsEmpty() && !_account.Customer.Email.IsNullOrWhiteSpace())
                        {
                            customerImportService.RemoveMember(_account.Email, _account.Document);
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Aplicação inválida");
                    }

                    account.Metadata = metadataService.SaveValue(account.GetMetadata(_account.Code)).Cast <AccountMetadata>().ToList();

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();

                    if (ex.Message == "Necessário converter customer do tipo person para company")
                    {
                        convertCustomerToCompany = true;
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            if (convertCustomerToCompany && !_account.IsNull())
            {
                customerRepository.ChangeCustomerType(_account, CustomerType.Company);

                account = Save(account, clientId, currentAccount);

                return(account);
            }

            return(new DTO.Account(_account));
        }