Ejemplo n.º 1
0
 public HttpResponseMessage GeraCnpj()
 {
     {
         var cnpj = CpfCnpjUtils.GerarCnpj();
         return(Request.CreateResponse(HttpStatusCode.OK, cnpj));
     }
 }
Ejemplo n.º 2
0
        public HttpResponseMessage PostEmpresa([FromBody] Empresa empresa)
        {
            if (CpfCnpjUtils.IsValid(empresa.Cnpj))
            {
                EmpresaContexto.Add(empresa);
                return(Request.CreateResponse(HttpStatusCode.Created, EmpresaContexto.ConsultarTodos()));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "CNPJ Invalido!"));
        }
Ejemplo n.º 3
0
        public HttpResponseMessage PostPessoa([FromBody] Pessoa pessoa)
        {
            if (CpfCnpjUtils.IsValid(pessoa.Cpf))
            {
                PessoaContexto.Add(pessoa);
                return(Request.CreateResponse(HttpStatusCode.Created, PessoaContexto.ConsultarTodos()));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "CPF Invalido!"));
        }
Ejemplo n.º 4
0
        public IActionResult Get()
        {
            try
            {
                List <ContractSignedView> resp = new List <ContractSignedView>();

                var typeUser  = (ETypeUser)Convert.ToInt32(User.FindFirst(ClaimTypes.Role)?.Value);
                int companyId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);

                var contracts = _service.GetSmartContractSigneds(typeUser, companyId);

                if (contracts == null || contracts.Count() <= 0)
                {
                    return(NotFound());
                }

                foreach (var item in contracts)
                {
                    var signed = new ContractSignedView();
                    signed.Id = item.Id;

                    var contract = _contractService.GetSmartContract(item.SmartContractId);
                    signed.IdContract           = contract.Id;
                    signed.Title                = contract.Title;
                    signed.Description          = contract.Description;
                    signed.TerminationCondition = contract.TerminationCondition;
                    signed.ConclusionCondition  = contract.ConclusionCondition;
                    signed.Value                = contract.Value;

                    var company = _companyService.GetCompany(item.CompanyId);
                    signed.DocumentCompany = company.CNPJ;
                    signed.EmailCompany    = company.Email;
                    signed.IdCompany       = company.Id;
                    signed.NameCompany     = company.Name;
                    signed.NicknameCompany = company.Nickname;
                    signed.PhoneCompany    = company.Phone;

                    var customer = _customerService.GetCustomers().First(w => w.Id == item.CustomerId);
                    signed.DocumentCustomer = CpfCnpjUtils.IsValid(customer.Cpf) ? customer.Cpf : customer.CNPJ;
                    signed.EmailCustomer    = customer.Email;
                    signed.IdCustomer       = customer.Id;
                    signed.NameCustomer     = customer.FirstName + customer.LastName;
                    signed.NicknameCustomer = customer.Nickname;
                    signed.PhoneCustomer    = customer.Phone;

                    resp.Add(signed);
                }

                return(Ok(resp));
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.Message));
            }
        }
Ejemplo n.º 5
0
        public HttpResponseMessage Post([FromBody] Entidade entidade)
        {
            if (!CpfCnpjUtils.IsValid(entidade.CpfOuCnpj))
            {
                ModelState.AddModelError("", "O cpf ou cnpj é inválido");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
            }

            EntidadeContexto.Add(entidade);
            return(Request.CreateResponse(HttpStatusCode.Created, EntidadeContexto.ConsultarTodos()));
        }
Ejemplo n.º 6
0
        public IActionResult Authenticate([FromBody] User model)
        {
            // Recupera o usuário
            var userModel = _userService.LogarUser(new LoginUserModel(model.Username, model.Password));

            // Verifica se o usuário existe
            if (userModel == null)
            {
                return(NotFound(new { message = "Usuário ou senha inválidos" }));
            }

            var user = _mapper.Map <UserView>(userModel);

            // Gera o Token
            user.AccessToken = TokenService.GenerateToken(user);

            switch (user.TypeUser)
            {
            case ETypeUser.Customer:
                var customer = _customerService.GetCustomers().FirstOrDefault(w => w.User.Id == user.Id);
                user.Name     = customer.FirstName;
                user.Nickname = customer.LastName;
                user.Phone    = customer.Phone;
                user.Email    = customer.Email;
                user.Document = CpfCnpjUtils.IsValid(customer.Cpf) ? customer.Cpf : customer.CNPJ;
                break;

            case ETypeUser.Company:
                var company = _companyService.GetCompanies().FirstOrDefault(w => w.User.Id == user.Id);
                user.Name     = company.Name;
                user.Nickname = company.Nickname;
                user.Phone    = company.Phone;
                user.Email    = company.Email;
                user.Document = company.CNPJ;
                break;

            case ETypeUser.Employee:
                break;
            }

            return(Ok(user));
        }
Ejemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="nickname"></param>
        /// <param name="cNPJ"></param>
        /// <param name="phone"></param>
        /// <param name="email"></param>
        /// <param name="deleted"></param>
        /// <param name="blocked"></param>
        public UpdateCompanyModel(long id, string name, string nickname, string cNPJ, string phone, string email, bool deleted, bool blocked)
        {
            Id        = id;
            Name      = name;
            Nickname  = nickname;
            CNPJ      = cNPJ;
            Phone     = phone;
            Email     = email;
            UpdatedOn = DateTime.Now;
            Deleted   = deleted;
            Blocked   = blocked;

            AddNotifications(new Contract()
                             .IsGreaterThan(Id, 0, "Id", "Id inválido")
                             .IsNotNullOrEmpty(Email, "Email", "O e-mail é obrigatório.")
                             .IsEmail(Email, "Email", "E-mail incorreto.")
                             .IsTrue(CpfCnpjUtils.IsValid(CNPJ), "CNPJ", "O CNPJ informado não é válido")
                             .IsNotNullOrEmpty(CNPJ, "CNPJ", "O CNPJ é obrigatório.")
                             .IsNotNullOrEmpty(Nickname, "Nickname", "O nome fantasia é obrigatório.")
                             .IsNotNullOrEmpty(Name, "Name", "A razão social é obrigatória."));
        }
Ejemplo n.º 8
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                try
                {
                    var propertyName = validationContext.ObjectType.GetProperty(_tipoPessoaProperty);
                    if (propertyName == null)
                    {
                        return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                    }
                    var propertyValue = propertyName.GetValue(validationContext.ObjectInstance, null);
                    if (propertyValue == null)
                    {
                        return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                    }

                    if ((int)propertyValue == (int)TipoPessoa.PJ)
                    {
                        if (!CpfCnpjUtils.IsCnpj(value.ToString()))
                        {
                            return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                        }
                    }
                    else if ((int)propertyValue == (int)TipoPessoa.PF)
                    {
                        if (!CpfCnpjUtils.IsCpf(value.ToString()))
                        {
                            return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                        }
                    }
                }
                catch
                {
                    return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                }
            }
            return(ValidationResult.Success);
        }
Ejemplo n.º 9
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var propertyName = validationContext.ObjectType.GetProperty(_tipoSeguroProperty);
                if (propertyName == null)
                {
                    return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                }
                var propertyValue = propertyName.GetValue(validationContext.ObjectInstance, null);
                if (propertyValue == null)
                {
                    return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                }

                try
                {
                    if ((int)propertyValue == (int)TipoSeguro.Automovel)
                    {
                        if (!Regex.IsMatch(value.ToString(), @"^[a-zA-Z]{3}-[0-9]{4}$"))
                        {
                            return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                        }
                    }
                    else if ((int)propertyValue == (int)TipoSeguro.Vida)
                    {
                        if (!CpfCnpjUtils.IsCpf(value.ToString()))
                        {
                            return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                        }
                    }
                }
                catch
                {
                    return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
                }
            }
            return(ValidationResult.Success);
        }
Ejemplo n.º 10
0
        public string ValidatingFields()
        {
            string msg;

            if (!CpfCnpjUtils.IsValid(this.CPF.ToString()))
            {
                return("CPF ou CNPJ inválidos;");
            }

            ErrorValidatingFields = false;

            if (this.Id == 0)
            {
                msg = "cadastro";
            }
            else
            {
                msg = "edição";
            }

            return("O " + msg + " foi realizado com sucesso.");
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Construtor
        /// </summary>
        /// <param name="name">Razão social da empresa</param>
        /// <param name="nickname">Fantasia da empresa</param>
        /// <param name="cNPJ">CNPJ</param>
        /// <param name="phone">Telefone da empresa</param>
        /// <param name="email">Email da empresa</param>
        public CreateCompanyModel(string name, string nickname, string cNPJ, string phone, string email)
        {
            Id             = 0;
            Name           = name;
            Nickname       = nickname;
            CNPJ           = cNPJ;
            Phone          = phone;
            Email          = email;
            CreatedOn      = DateTime.Now;
            UpdatedOn      = DateTime.Now;
            Deleted        = false;
            Blocked        = false;
            SmartContracts = null;
            User           = null;

            AddNotifications(new Contract()
                             .IsNotNullOrEmpty(Email, "Email", "O e-mail é obrigatório.")
                             .IsEmail(Email, "Email", "E-mail incorreto.")
                             .IsTrue(!CpfCnpjUtils.IsValid(CNPJ), "CNPJ", "O CNPJ informado não é válido")
                             .IsNotNullOrEmpty(CNPJ, "CNPJ", "O CNPJ é obrigatório.")
                             .IsNotNullOrEmpty(Nickname, "Nickname", "O nome fantasia é obrigatório.")
                             .IsNotNullOrEmpty(Name, "Name", "A razão social é obrigatória."));
        }
        public JsonResult Incluir(ClienteModel model)
        {
            BoCliente       bo    = new BoCliente();
            BoBeneficiarios boBen = new BoBeneficiarios();

            if (!this.ModelState.IsValid)
            {
                List <string> erros = (from item in ModelState.Values
                                       from error in item.Errors
                                       select error.ErrorMessage).ToList();

                Response.StatusCode = 400;
                return(Json(string.Join(Environment.NewLine, erros)));
            }
            else
            {
                bool   invalido = false;
                string msg      = "";
                if (bo.VerificarExistencia(model.CPF))
                {
                    msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} já cadastrado!", model.CPF));
                    invalido = true;
                }
                if (!CpfCnpjUtils.IsValid(model.CPF))
                {
                    msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} invalido!", model.CPF));
                    invalido = true;
                }

                if (invalido)
                {
                    Response.StatusCode = 400;
                    return(Json(msg));
                }

                model.Id = bo.Incluir(new Cliente()
                {
                    CPF           = model.CPF,
                    CEP           = model.CEP,
                    Cidade        = model.Cidade,
                    Email         = model.Email,
                    Estado        = model.Estado,
                    Logradouro    = model.Logradouro,
                    Nacionalidade = model.Nacionalidade,
                    Nome          = model.Nome,
                    Sobrenome     = model.Sobrenome,
                    Telefone      = model.Telefone
                });

                if (model.Benficiarios != null)
                {
                    foreach (var item in model.Benficiarios)
                    {
                        if (!CpfCnpjUtils.IsValid(item.CPF))
                        {
                            msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} invalido!", item.CPF));
                            invalido = true;
                        }
                        if (model.Benficiarios.Count(c => c.CPF == item.CPF) > 1)
                        {
                            msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} já cadastrado!", item.CPF));
                            invalido = true;
                        }
                        if (invalido)
                        {
                            Response.StatusCode = 400;
                            return(Json(msg));
                        }

                        boBen.Incluir(new Benificiario()
                        {
                            CPF       = item.CPF,
                            Nome      = item.Nome,
                            IdCliente = model.Id
                        });
                    }
                }

                return(Json("Cadastro efetuado com sucesso"));
            }
        }
        public JsonResult Alterar(ClienteModel model)
        {
            BoCliente       bo    = new BoCliente();
            BoBeneficiarios boBen = new BoBeneficiarios();

            if (!this.ModelState.IsValid)
            {
                List <string> erros = (from item in ModelState.Values
                                       from error in item.Errors
                                       select error.ErrorMessage).ToList();

                Response.StatusCode = 400;
                return(Json(string.Join(Environment.NewLine, erros)));
            }
            else
            {
                var    oCliente = bo.Consultar(model.Id);
                bool   invalido = false;
                string msg      = "";
                if (bo.VerificarExistencia(model.CPF) && oCliente.CPF != model.CPF)
                {
                    msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} já cadastrado!", model.CPF));
                    invalido = true;
                }
                if (!CpfCnpjUtils.IsValid(model.CPF))
                {
                    msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} invalido!", model.CPF));
                    invalido = true;
                }

                if (invalido)
                {
                    Response.StatusCode = 400;
                    return(Json(msg));
                }

                bo.Alterar(new Cliente()
                {
                    Id            = model.Id,
                    CEP           = model.CEP,
                    Cidade        = model.Cidade,
                    Email         = model.Email,
                    Estado        = model.Estado,
                    Logradouro    = model.Logradouro,
                    Nacionalidade = model.Nacionalidade,
                    Nome          = model.Nome,
                    Sobrenome     = model.Sobrenome,
                    Telefone      = model.Telefone,
                    CPF           = model.CPF
                });

                var listaBeneficiadosExcluidos = new List <Benificiario>();
                var listaBeneficiados          = boBen.Consultar(model.Id);

                if (model.Benficiarios != null)
                {
                    foreach (var item in model.Benficiarios)
                    {
                        if (!CpfCnpjUtils.IsValid(item.CPF))
                        {
                            msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} invalido!", item.CPF));
                            invalido = true;
                        }
                        if (model.Benficiarios.Count(c => c.CPF == item.CPF) > 1)
                        {
                            msg      = string.Join(Environment.NewLine, string.Format("CPF:{0} já cadastrado!", item.CPF));
                            invalido = true;
                        }
                    }
                    if (invalido)
                    {
                        Response.StatusCode = 400;
                        return(Json(msg));
                    }

                    listaBeneficiadosExcluidos = listaBeneficiados.Where(w => !model.Benficiarios.Select(s => s.CPF).Contains(w.CPF)).ToList();

                    foreach (var item in model.Benficiarios)
                    {
                        var oBeneficiado = listaBeneficiados.FirstOrDefault(w => w.CPF == item.CPF);

                        if (oBeneficiado == null)
                        {
                            boBen.Incluir(new Benificiario()
                            {
                                CPF       = item.CPF,
                                Nome      = item.Nome,
                                IdCliente = model.Id
                            });
                        }
                        else
                        {
                            oBeneficiado.CPF       = item.CPF;
                            oBeneficiado.Nome      = item.Nome;
                            oBeneficiado.IdCliente = model.Id;
                            boBen.Alterar(oBeneficiado);
                        }
                    }
                }
                else
                {
                    listaBeneficiadosExcluidos = listaBeneficiados;
                }
                foreach (var item in listaBeneficiadosExcluidos)
                {
                    boBen.Excluir(item.Id);
                }

                return(Json("Cadastro alterado com sucesso"));
            }
        }
Ejemplo n.º 14
0
 protected override bool IsValid(PropertyValidatorContext context)
 {
     return(CpfCnpjUtils.IsCpf(context.PropertyValue.ToString()));
 }