/// <summary>
        /// This method creates an user for an existing customer 
        /// </summary>
        public MembershipCreateStatus InsertUserForCustomer(Customer originalCustomer, User user)
        {
            var membershipManager = new MembershipManager(this);


            MembershipCreateStatus status;

            membershipManager.Insert(user, out status, true);

            if (status == MembershipCreateStatus.Success)
            {
                originalCustomer.UserId = user.UserId;
                DbContext.SubmitChanges();

                return MembershipCreateStatus.Success;
            }

            return status;
        }
示例#2
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Customer customer = new Customer();

        // Clone the original customer for the linq track changes
        if (originalCustomer != null)
        {
            customer.CopyPropertiesFrom(originalCustomer);
        }

        customer.BlockSalesInDebit = true;

        if (Company.MatrixId.HasValue)
        {
            customer.CompanyId = Company.MatrixId.Value;
        }
        else
        {
            customer.CompanyId = Company.CompanyId;
        }

        customer.BankId = null;
        if (!String.IsNullOrEmpty(cboBank.SelectedValue))
        {
            customer.BankId = Convert.ToInt32(cboBank.SelectedValue);
        }

        customer.Agency = null;
        if (!String.IsNullOrEmpty(txtAgency.Text))
        {
            customer.Agency = txtAgency.Text;
        }

        customer.AccountNumber = null;
        if (!String.IsNullOrEmpty(txtAccountNumber.Text))
        {
            customer.AccountNumber = txtAccountNumber.Text;
        }

        customer.AccountCreatedDate = null;
        if (!String.IsNullOrEmpty(txtAccountCreatedDate.Text))
        {
            customer.AccountCreatedDate = Convert.ToDateTime(txtAccountCreatedDate.Text);
        }

        ///vendor
        if (!String.IsNullOrEmpty(cboVendors.SelectedValue))
        {
            customer.SalesPersonId = Convert.ToInt32(cboVendors.SelectedValue);
        }

        if (Page.ViewState["SalesPersonId"] != null)
        {
            customer.SalesPersonId = Convert.ToInt32(Page.ViewState["SalesPersonId"]);
        }

        if (ucVendorComission.CurrencyValue.HasValue)
        {
            customer.SalesPersonCommission = ucVendorComission.CurrencyValue;
        }

        if (!String.IsNullOrEmpty(cboSupplementalVendor.SelectedValue))
        {
            customer.SupplementalSalesPersonId = Convert.ToInt32(cboSupplementalVendor.SelectedValue);
        }

        if (Page.ViewState["supplementalSalesPersonId"] != null)
        {
            customer.SupplementalSalesPersonId = Convert.ToInt32(Page.ViewState["supplementalSalesPersonId"]);
        }

        if (ucSupplementalVendorComission.CurrencyValue.HasValue)
        {
            customer.SupplementalSalesPersonCommission = ucSupplementalVendorComission.CurrencyValue;
        }

        customer.RepresentantId = null;
        if (!String.IsNullOrEmpty(cboRepresentant.SelectedValue))
        {
            customer.RepresentantId = Convert.ToInt32(cboRepresentant.SelectedValue);
        }

        customer.CreditLimit = ucCurrFieldCreditLimit.CurrencyValue;

        customer.CustomerTypeId = null;
        if (!String.IsNullOrEmpty(cboCustomerType.SelectedValue))
        {
            customer.CustomerTypeId = Convert.ToInt32(cboCustomerType.SelectedValue);
        }

        //fill field ranking
        customer.Ranking = rtnRanking.CurrentRating;

        if (ucProfile.ProfileEntity != null)
        {
            if (String.IsNullOrEmpty(ucProfile.ProfileEntity.Phone.Trim('-', '_', '(', ')')) && String.IsNullOrEmpty(ucProfile.ProfileEntity.CellPhone.Trim('-', '_', '(', ')')) && String.IsNullOrEmpty(ucProfile.ProfileEntity.HomePhone.Trim('-', '_', '(', ')')))
            {
                ShowError("Ao menos um telefone deve ser preenchido!");
                return;
            }

            // Add the entity to Insert
            if (ucProfile.ProfileEntity.ProfileId == 0)
            {
                customer.Profile = ucProfile.ProfileEntity;
            }
        }
        else
        {
            // Add the entity to Insert
            customer.LegalEntityProfileId = ucProfile.CompanyProfileEntity.LegalEntityProfileId;
            if (ucProfile.CompanyProfileEntity.LegalEntityProfileId == 0)
            {
                customer.LegalEntityProfile = ucProfile.CompanyProfileEntity;
            }
        }

        //
        //Insert
        //

        if (Page.ViewState["CustomerId"] == null && Page.ViewState["ProfileExists"] != "0")
        {
            membershipManager = new MembershipManager(this);
            companyManager    = new CompanyManager(this);

            if (!String.IsNullOrEmpty(txtUserName.Text))
            {
                customer.CreatedByUser = User.Identity.UserName;
                status = customerManager.Insert(customer, FillUser());

                ShowMessage(status);
                chkRemoveUser.Visible = (status == MembershipCreateStatus.Success);
                lblPassword.Visible   = txtPassword.Visible = !(status == MembershipCreateStatus.Success);


                if (status == MembershipCreateStatus.Success)
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);
                }

                return;
            }

            customer.CreatedByUser = User.Identity.UserName;
            customerManager.Insert(customer);
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);
        } // Update
        else
        {
            membershipManager = new MembershipManager(this);
            customerManager   = new CustomerManager(this);
            var user = FillUser();

            customer.ModifiedByUser = User.Identity.UserName;
            //
            //Delete the user account of customer
            //
            if (chkRemoveUser.Checked)
            {
                customer.User         = null;
                lblMessage.Text       = String.Empty;
                chkRemoveUser.Checked = false;
                chkRemoveUser.Visible = false;
                txtUserName.Text      = String.Empty;
                lblPassword.Visible   = txtPassword.Visible = true;

                customerManager.Update(originalCustomer, customer);
                return;
            }

            if (originalCustomer.UserId.HasValue)
            {
                if (originalCustomer.User.UserName != txtUserName.Text)
                {
                    if (customerManager.GetCustomerByUserName(Company.CompanyId, txtUserName.Text) != null)
                    {
                        lblMessage.Text = "Já existe um cliente com esse usuário nesta empresa!";
                        return;
                    }

                    customerManager.UpdateUserNameOfCustomer(originalCustomer, txtUserName.Text);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(txtUserName.Text) && !originalCustomer.UserId.HasValue)
            {
                if (customerManager.GetCustomerByUserName(Company.CompanyId, txtUserName.Text) != null)
                {
                    lblMessage.Text = "Já existe um cliente com esse usuário nesta empresa!";
                    return;
                }

                membershipManager.Insert(user, out status, true);

                if (status == MembershipCreateStatus.Success)
                {
                    customer.UserId = user.UserId;
                    customerManager.Update(originalCustomer, customer);

                    chkRemoveUser.Visible = true;
                    txtPassword.Visible   = false;
                    lblPassword.Visible   = false;
                }
            }

            customerManager.Update(originalCustomer, customer);

            //
            // In case of cnpj/cpf already exists in another category but the same cnpj/cpf is not yet a customer
            // the data will be loaded and save as update not insert, then this code redirects correctly to finalize
            // the register.
            //
            if (Page.ViewState["CustomerId"] == null)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);
            }
        }
    }
        /// <summary>
        /// This method insert an customer and an user atached
        /// this method return true when customer and user inserted
        /// </summary>
        public MembershipCreateStatus Insert(Customer customer, User user)
        {
            MembershipCreateStatus status;
            var companyManager = new CompanyManager(this);
            var membershipManager = new MembershipManager(this);

            membershipManager.Insert(user, out status, true);
            //
            // creates an new user
            //
            if (status == MembershipCreateStatus.Success)
            {
                customer.UserId = user.UserId;
                customer.CreatedDate = customer.ModifiedDate = DateTime.Now;
                Insert(customer);
                return MembershipCreateStatus.Success;
            }

            return status;
        }
        /// <summary>
        /// M�todo usado para criar a primeira companhia, utilizado na tela de registro
        /// </summary>
        /// <param name="newCompany"></param>
        /// <param name="newUser"></param>
        /// <param name="newProfile"></param>
        /// <returns></returns>
        public InsertCompanyStatus InsertMatrixCompany(Company newCompany, User newUser, Profile profile)
        {
            //
            // Insert the profile
            //
            var pManager = new ProfileManager(this);

            // Profile profile = pManager.GetProfile(newProfile.CPF) ?? newProfile;
            //if (profile.ProfileId == 0)
            pManager.Insert(profile);
            //else
            //{
            //    profile.Name = newProfile.Name;
            //    profile.Email = newProfile.Email;
            //    profile.PostalCode = newProfile.PostalCode;
            //    //profile.Address = newProfile.Address;
            //    profile.AddressComp = newProfile.AddressComp;
            //    profile.AddressNumber = newProfile.AddressNumber;
            //    profile.Phone = newProfile.Phone;
            //    DbContext.SubmitChanges();
            //}

            //
            //Insert Admin user
            //
            Int32 UserId;
            //newUser.ProfileId
            DataClasses.User original_User = GetUserByUserName(newUser.Email);
            if (original_User != null)
            {
                UserId = original_User.UserId;
            }
            else
            {
                MembershipCreateStatus status;
                var membershipManager = new MembershipManager(this);
                newUser.ProfileId = profile.ProfileId;
                membershipManager.Insert(
                    newUser,
                    out status,
                    (Membership.Provider as VivinaMembershipProvider).RequiresValidEmail);

                //
                //verify if the status of the inclusion are ok
                //
                if (status != MembershipCreateStatus.Success)
                {
                    DataManager.Rollback();
                    switch (status)
                    {
                        case MembershipCreateStatus.DuplicateUserName:
                            return InsertCompanyStatus.DuplicatedUserName;
                        case MembershipCreateStatus.InvalidPassword:
                            return InsertCompanyStatus.InvalidPassword;
                        case MembershipCreateStatus.DuplicateEmail:
                            return InsertCompanyStatus.DuplicatedAdminEmail;
                        default:
                            return InsertCompanyStatus.InvalidUser;
                    }
                }
                UserId = newUser.UserId;
            }

            if (newCompany.LegalEntityProfile.IsLiberalProfessional)
                newCompany.LegalEntityProfile.CompanyName = newCompany.LegalEntityProfile.FantasyName = profile.Name;

            var insertCompanyStatus = InsertCompany(newCompany, UserId, 0);

            newCompany.ReferenceCompanyId = newCompany.CompanyId;
            newCompany.MatrixId = newCompany.CompanyId;
            DbContext.SubmitChanges();

            return insertCompanyStatus;
        }
        /// <summary>
        /// This method inserts a user
        /// </summary>
        /// <param name="companyId">Can't be null</param>
        /// <param name="user">Can't be null. This entity can't be attached in db</param>
        /// <param name="depositId">can be null</param>
        /// <returns>a status based on InsertCompanyStatus</returns>
        public InsertCompanyStatus InsertUser(int companyId, int? depositId, int? representantId, User user, Profile profile)
        {
            var membershipManager = new MembershipManager(this);

            //
            //method to insert a new user
            //

            var provider = Membership.Provider as VivinaMembershipProvider;
            MembershipCreateStatus status;

            membershipManager.Insert(user, out status, provider.RequiresValidEmail);

            //
            //verifies if the status of the inclusion is ok
            //

            if (status != MembershipCreateStatus.Success)
            {
                DataManager.Rollback();
                switch (status)
                {
                    case MembershipCreateStatus.InvalidPassword:
                        return InsertCompanyStatus.InvalidPassword;
                    case MembershipCreateStatus.DuplicateEmail:
                        return InsertCompanyStatus.DuplicatedAdminEmail;
                }
            }

            if (profile.ProfileId == 0)
                new ProfileManager(this).Insert(profile);

            AttachProfileEntityToUser(companyId, user.UserId, profile.ProfileId);

            if (representantId.HasValue)
                AddRepresentantToUser(companyId, user.UserId, Convert.ToInt32(representantId));

            //
            // Associate the User with company
            //
            if (!IsCompanyUser(companyId, user.UserId))
                AssociateUser(companyId, user.UserId, depositId, true);

            return InsertCompanyStatus.Success;
        }
        public InsertCompanyStatus InsertUser(int companyId, User user, Profile profile, int? depositId)
        {
            //
            // If ProfileId equal 0 then the profile no exists in bd
            //
            var pManager = new ProfileManager(this);
            if (profile.ProfileId == 0)
                pManager.Insert(profile);

            //
            //method to insert a new user
            //
            var provider = Membership.Provider as VivinaMembershipProvider;
            MembershipCreateStatus status;
            var membershipManager = new MembershipManager(this);
            user.ProfileId = profile.ProfileId;
            membershipManager.Insert(user, out status, provider.RequiresValidEmail);
            //
            //verify if the status of the inclusion is ok
            //
            if (status != MembershipCreateStatus.Success)
            {
                DataManager.Rollback();
                switch (status)
                {
                    case MembershipCreateStatus.InvalidPassword:
                        return InsertCompanyStatus.InvalidPassword;
                    case MembershipCreateStatus.DuplicateEmail:
                        return InsertCompanyStatus.DuplicatedAdminEmail;
                }
            }

            //
            // Associate the User with company
            //
            AssociateUser(companyId, user.UserId, depositId, true);

            //
            // Insert a Employee
            //
            var humanResourcesManager = new HumanResourcesManager(this);
            var employee = new Employee();
            employee.IsActive = true;
            employee.ProfileId = profile.ProfileId;
            employee.CompanyId = companyId;
            humanResourcesManager.InsertEmployee(employee, new List<EmployeeAdditionalInformation>());

            return InsertCompanyStatus.Success;
        }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Customer customer = new Customer();

        // Clone the original customer for the linq track changes 
        if (originalCustomer != null)
        {
            customer.CopyPropertiesFrom(originalCustomer);
        }

        customer.BlockSalesInDebit = true;

        if (Company.MatrixId.HasValue)
            customer.CompanyId = Company.MatrixId.Value;
        else
            customer.CompanyId = Company.CompanyId;

        customer.BankId = null;
        if (!String.IsNullOrEmpty(cboBank.SelectedValue))
            customer.BankId = Convert.ToInt32(cboBank.SelectedValue);

        customer.Agency = null;
        if (!String.IsNullOrEmpty(txtAgency.Text))
            customer.Agency = txtAgency.Text;

        customer.AccountNumber = null;
        if (!String.IsNullOrEmpty(txtAccountNumber.Text))
            customer.AccountNumber = txtAccountNumber.Text;

        customer.AccountCreatedDate = null;
        if (!String.IsNullOrEmpty(txtAccountCreatedDate.Text))
            customer.AccountCreatedDate = Convert.ToDateTime(txtAccountCreatedDate.Text);

        ///vendor
        if (!String.IsNullOrEmpty(cboVendors.SelectedValue))
            customer.SalesPersonId = Convert.ToInt32(cboVendors.SelectedValue);

        if (Page.ViewState["SalesPersonId"] != null)
            customer.SalesPersonId = Convert.ToInt32(Page.ViewState["SalesPersonId"]);

        if (ucVendorComission.CurrencyValue.HasValue)
            customer.SalesPersonCommission = ucVendorComission.CurrencyValue;
      
        if (!String.IsNullOrEmpty(cboSupplementalVendor.SelectedValue))
            customer.SupplementalSalesPersonId = Convert.ToInt32(cboSupplementalVendor.SelectedValue);

        if (Page.ViewState["supplementalSalesPersonId"] != null)
            customer.SupplementalSalesPersonId = Convert.ToInt32(Page.ViewState["supplementalSalesPersonId"]);
        
        if (ucSupplementalVendorComission.CurrencyValue.HasValue)
            customer.SupplementalSalesPersonCommission = ucSupplementalVendorComission.CurrencyValue;

        customer.RepresentantId = null;
        if (!String.IsNullOrEmpty(cboRepresentant.SelectedValue))
            customer.RepresentantId = Convert.ToInt32(cboRepresentant.SelectedValue);

        customer.CreditLimit = ucCurrFieldCreditLimit.CurrencyValue;
        
        customer.CustomerTypeId = null;
        if (!String.IsNullOrEmpty(cboCustomerType.SelectedValue))
            customer.CustomerTypeId = Convert.ToInt32(cboCustomerType.SelectedValue);

        //fill field ranking
        customer.Ranking = rtnRanking.CurrentRating;

        if (ucProfile.ProfileEntity != null)
        {
            if (String.IsNullOrEmpty(ucProfile.ProfileEntity.Phone.Trim('-', '_', '(', ')')) && String.IsNullOrEmpty(ucProfile.ProfileEntity.CellPhone.Trim('-', '_', '(', ')')) && String.IsNullOrEmpty(ucProfile.ProfileEntity.HomePhone.Trim('-', '_', '(', ')')))
            {
                ShowError("Ao menos um telefone deve ser preenchido!");
                return;
            }

            // Add the entity to Insert
            if (ucProfile.ProfileEntity.ProfileId == 0)
                customer.Profile = ucProfile.ProfileEntity;
        }
        else
        {
            // Add the entity to Insert
            customer.LegalEntityProfileId = ucProfile.CompanyProfileEntity.LegalEntityProfileId;
            if (ucProfile.CompanyProfileEntity.LegalEntityProfileId == 0)
                customer.LegalEntityProfile = ucProfile.CompanyProfileEntity;
        }

        //
        //Insert
        //

        if (Page.ViewState["CustomerId"] == null && Page.ViewState["ProfileExists"] != "0")
        {
            membershipManager = new MembershipManager(this);
            companyManager = new CompanyManager(this);

            if (!String.IsNullOrEmpty(txtUserName.Text))
            {
                customer.CreatedByUser = User.Identity.UserName;
                status = customerManager.Insert(customer, FillUser());

                ShowMessage(status);
                chkRemoveUser.Visible = (status == MembershipCreateStatus.Success);
                lblPassword.Visible = txtPassword.Visible = !(status == MembershipCreateStatus.Success);


                if (status == MembershipCreateStatus.Success)
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);

                return;
            }

            customer.CreatedByUser = User.Identity.UserName;
            customerManager.Insert(customer);
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);

        } // Update
        else
        {
            membershipManager = new MembershipManager(this);
            customerManager = new CustomerManager(this);
            var user = FillUser();

            customer.ModifiedByUser = User.Identity.UserName;
            //
            //Delete the user account of customer
            //
            if (chkRemoveUser.Checked)
            {                
                customer.User = null;
                lblMessage.Text = String.Empty;
                chkRemoveUser.Checked = false;
                chkRemoveUser.Visible = false;
                txtUserName.Text = String.Empty;
                lblPassword.Visible = txtPassword.Visible = true;

                customerManager.Update(originalCustomer, customer);
                return;
            }

            if (originalCustomer.UserId.HasValue)
            {
                if (originalCustomer.User.UserName != txtUserName.Text)
                {
                    if (customerManager.GetCustomerByUserName(Company.CompanyId, txtUserName.Text) != null)
                    {
                        lblMessage.Text = "Já existe um cliente com esse usuário nesta empresa!";
                        return;
                    }

                    customerManager.UpdateUserNameOfCustomer(originalCustomer, txtUserName.Text);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(txtUserName.Text) && !originalCustomer.UserId.HasValue)
            {
                if (customerManager.GetCustomerByUserName(Company.CompanyId, txtUserName.Text) != null)
                {
                    lblMessage.Text = "Já existe um cliente com esse usuário nesta empresa!";
                    return;
                }

                membershipManager.Insert(user, out status, true);

                if (status == MembershipCreateStatus.Success)
                {
                    customer.UserId = user.UserId;
                    customerManager.Update(originalCustomer, customer);

                    chkRemoveUser.Visible = true;
                    txtPassword.Visible = false;
                    lblPassword.Visible = false;
                }

            }
         
            customerManager.Update(originalCustomer, customer);

            //
            // In case of cnpj/cpf already exists in another category but the same cnpj/cpf is not yet a customer
            // the data will be loaded and save as update not insert, then this code redirects correctly to finalize
            // the register.
            //
            if (Page.ViewState["CustomerId"] == null)
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "location='Customer.aspx?CustomerId=" + customer.CustomerId + "';", true);
        }
    }