Ejemplo n.º 1
0
        public void Validacoes()
        {
            AssertionConcern.AssertArgumentNotEquals(this.VeiculoId, 0, "Veiculo é obrigatório!");
            AssertionConcern.AssertArgumentNotEquals(this.MotoristaId, 0, "Motorista é obrigatório!");
            AssertionConcern.AssertArgumentNotEquals(this.DataSaida.Date, new DateTime(0001, 01, 01).Date, "A Data de saida é obrigatória!");
            AssertionConcern.AssertArgumentNotEquals(this.DataChegada.Date, new DateTime(0001, 01, 01).Date, "A Data de chegada é obrigatória!");
            AssertionConcern.AssertArgumentNotEquals(this.OrigemCidadeId, 0, "Cidade de origem é obrigatória!");
            AssertionConcern.AssertArgumentNotEquals(this.DestinoCidadeId, 0, "Cidade de destino é obrigatória!");
            AssertionConcern.AssertArgumentNotEquals(this.OrigemCidadeId, 0, "Cidade de origem é obrigatória!");
            AssertionConcern.AssertArgumentTrue(this.ToneladaPrecoUnitario > 1, "O preço unitário deve ser maior do que R$1,00!");
            AssertionConcern.AssertArgumentTrue(this.ToneladaCarga > 1, "A quantidade transportada deve ser maior do que 1!");
            AssertionConcern.AssertArgumentFalse(this.OrigemCidadeId == this.DestinoCidadeId, "As cidades devem ser diferentes!");
            AssertionConcern.AssertArgumentTrue(this.ValorTotalBruto == (this.ToneladaCarga * this.ToneladaPrecoUnitario), "Erro ao calcular o total bruto!");
            AssertionConcern.AssertArgumentTrue(this.ValorTotalLiquido == (this.ValorTotalBruto - this.ValorTotalDespesa), "Erro ao calcular o total liquido!");
            AssertionConcern.AssertArgumentFalse(this.DataSaida.Date > this.DataChegada.Date, "A data de chegada não pode ser menor que a data de saida!");

            if (this.despesas != null)
            {
                foreach (var item in this.despesas)
                {
                    AssertionConcern.AssertArgumentEquals(this.DataChegada.Date, item.DataLancamento.Date, "A Data de Lançamento deve ser a mesma da chegada!");
                }
            }

            if (this.combustivel != null)
            {
                foreach (var item in this.combustivel)
                {
                    AssertionConcern.AssertArgumentEquals(this.DataChegada.Date, item.DataLancamento.Date, "A Data de Lançamento deve ser a mesma da chegada!");
                }
            }
        }
        public new async Task RemoveLogic(int id, ProdutoTipo obj)
        {
            var produtoTipo = await _produtoTipoService.GetById(id);

            AssertionConcern.AssertArgumentFalse(produtoTipo.Produtos.Any(produto => produto.Ativo == true), "Não é possivel Excluir Existem produtos Cadastrados com esse Tipo de Produto");
            produtoTipo.Ativo = false;
            await _produtoTipoService.RemoveLogic(id, produtoTipo);
        }
 public void validacoes()
 {
     AssertionConcern.AssertArgumentFalse(this.DataLancamento.Date == new DateTime(0001, 01, 01).Date, "Data de lançamento é obrigatório!");
     AssertionConcern.AssertArgumentNotEmpty(this.Historico, "Histórico é obrigatório!");
     AssertionConcern.AssertArgumentLength(this.Historico, 5, 60, "Histórico deve conter no mínimo 5 caracteres");
     AssertionConcern.AssertArgumentFalse(this.Valor <= 0, "Valor Deve ser maior que 0!");
     //AssertionConcern.AssertArgumentFalse(this.DataLancamento.Date == viagem.DataChegada.Date, "A data de lançamento deve ser a mesma da chegada");
 }
Ejemplo n.º 4
0
        private void ProtectPassword(string currentPassword, string changedPassword)
        {
            AssertionConcern.AssertArgumentNotEquals(currentPassword, changedPassword, "The password is unchanged.");
            AssertionConcern.AssertArgumentFalse(DomainRegistry.PasswordService.IsWeak(changedPassword), "The password must be stronger.");
            AssertionConcern.AssertArgumentNotEquals(this.Username, changedPassword, "The username and password must not be the same.");

            this.Password = AsEncryptedValue(changedPassword);
        }
        public new async Task Add(UsuarioPerfil obj)
        {
            var listExist =
                await _usuarioPerfilService.GetAll(perfil => perfil.NomeUsuarioPerfil == obj.NomeUsuarioPerfil && perfil.Ativo == true);

            AssertionConcern.AssertArgumentFalse(listExist.Count > 0, "Perfil ja Cadastrado");

            await _usuarioPerfilService.Add(obj);
        }
Ejemplo n.º 6
0
        public new async Task RemoveLogic(int id, Usuario obj)
        {
            var user = await _usuarioService.GetById(id);

            AssertionConcern.AssertArgumentFalse(user == null, Errors.UserNotFound);

            user.Ativo = false;

            await _usuarioService.RemoveLogic(id, user);
        }
        public User Add(string name, string email, string password)
        {
            User user = GetByEmail(email);

            AssertionConcern.AssertArgumentFalse(user != null, ErrorMessages.UserAlreadyExist);

            user = new User(name, email, password);
            user.ValidateCadastration();

            return(_repository.Add(user));
        }
Ejemplo n.º 8
0
 void AssertTimeSpans(Repetition repetition, DateRange timeSpan)
 {
     if (repetition.Repeats == RepeatType.DoesNotRepeat)
     {
         AssertionConcern.AssertArgumentEquals(repetition.Ends, timeSpan.Ends, "Non-repeating entry must end with time span end.");
     }
     else
     {
         AssertionConcern.AssertArgumentFalse(timeSpan.Ends > repetition.Ends, "Time span must end when or before repetition ends.");
     }
 }
Ejemplo n.º 9
0
        public RegistrationInvitation OfferRegistrationInvitation(string description)
        {
            AssertionConcern.AssertStateTrue(this.Active, "Tenant is not active.");
            AssertionConcern.AssertArgumentFalse(this.IsRegistrationAvailableThrough(description), "Invitation already exists.");

            RegistrationInvitation invitation = new RegistrationInvitation(this.TenantId, Guid.NewGuid().ToString(), description);

            AssertionConcern.AssertStateTrue(this.registrationInvitations.Add(invitation), "The invitation should have been added.");

            return(invitation);
        }
        public new async Task RemoveLogic(int id, UsuarioPerfil obj)
        {
            var usuarioPeril = await _usuarioPerfilService.GetById(id);

            AssertionConcern.AssertArgumentFalse(usuarioPeril.Usuarios.Count > 0, "Não é possivel excluir existem Usuarios Cadastrados com esse Perfil");
            AssertionConcern.AssertArgumentFalse(usuarioPeril.ServicoUsuarioPerfil.Count > 0, "Não é possivel excluir existem Servicos Cadastrados com esse Perfil");

            usuarioPeril.SetAtivoFalse();


            await _usuarioPerfilService.RemoveLogic(id, usuarioPeril);
        }
Ejemplo n.º 11
0
 public void PagarContas(List <ContaPagar> contasPagar)
 {
     AssertionConcern.AssertArgumentFalse(contasPagar.Any(x => x.ContaPagarCodigo.Equals(0)), Erros.ThereAccountPayableWithCodeZero);
     contasPagar.ForEach(x =>
     {
         var contaPagarAtual              = _contaPagarRepository.ObterPorCodigoComCompra(x.ContaPagarCodigo);
         contaPagarAtual.Pago             = x.Pago;
         contaPagarAtual.StatusContaPagar = x.Pago
             ? StatusContaPagarEnum.Pago
             : StatusContaPagarEnum.Aberto;
         _contaPagarRepository.Atualizar(contaPagarAtual);
     });
 }
Ejemplo n.º 12
0
 public void ReceberContas(List <ContaReceber> contasReceber)
 {
     AssertionConcern.AssertArgumentFalse(contasReceber.Any(x => x.ContaReceberCodigo.Equals(0)), Erros.ThereReceivableWithZeroCode);
     contasReceber.ForEach(x =>
     {
         var contaReceberAtual                = _contaReceberRepository.ObterPorCodigoComVenda(x.ContaReceberCodigo);
         contaReceberAtual.Recebido           = x.Recebido;
         contaReceberAtual.StatusContaReceber = x.Recebido
             ? StatusContaReceberEnum.Recebido
             : StatusContaReceberEnum.Aberto;
         _contaReceberRepository.Atualizar(contaReceberAtual);
     });
 }
Ejemplo n.º 13
0
        public void Create(ImmobilizedCreateCommand obj)
        {
            //Validation
            AssertionConcern.AssertArgumentNotEmpty(obj.Title, "O Titulo não pode ser vazio");
            AssertionConcern.AssertArgumentNotEmpty(obj.Localization, "O Localização não pode ser vazio");
            AssertionConcern.AssertArgumentNotEmpty(obj.Description, "O Descrição não pode ser vazio");
            AssertionConcern.AssertArgumentNotNull(obj.Active, "O Ativo não pode ser vazio");
            AssertionConcern.AssertArgumentNotEmpty(obj.Serial, "O Serial não pode ser vazio");
            AssertionConcern.AssertArgumentFalse(_repository.HasExists(obj.Serial), "Ja existe cadastro com esse serial");

            var entity = new Immobilized
                    (obj.Title, obj.Description, obj.Localization, obj.Active, obj.Serial);
            _repository.Save(entity);
        }
Ejemplo n.º 14
0
        public void AddGroup(Group group, GroupMemberService groupMemberService)
        {
            AssertionConcern.AssertArgumentNotNull(group, "Group must not be null.");
            AssertionConcern.AssertArgumentEquals(this.TenantId, group.TenantId, "Wrong tenant for this group.");
            AssertionConcern.AssertArgumentFalse(groupMemberService.IsMemberGroup(group, this.ToGroupMember()), "Group recurrsion.");

            if (this.GroupMembers.Add(group.ToGroupMember()) && (!this.IsInternalGroup))
            {
                DomainEventPublisher
                .Instance
                .Publish(new GroupGroupAdded(
                             this.TenantId,
                             this.Name,
                             group.Name));
            }
        }
Ejemplo n.º 15
0
        private void VerificarEstoque(IEnumerable <ItemVenda> itensVenda)
        {
            var produtosQueFaltamNoEstoque = new List <Tuple <string, int, int> >();

            itensVenda.ForEach(x =>
            {
                var estoque = _estoqueRepository.ObterPorCodigoProduto(x.ProdutoCodigo);
                if (estoque.Quantidade - x.Quantidade < 0)
                {
                    produtosQueFaltamNoEstoque.Add(new Tuple <string, int, int>(x.ProdutoNome, x.Quantidade,
                                                                                estoque.Quantidade));
                }
            });
            AssertionConcern.AssertArgumentFalse(produtosQueFaltamNoEstoque.Any(),
                                                 MensagemDeEstoqueInsuficiente(produtosQueFaltamNoEstoque));
        }
        public Vote RegisterVote(string email, long restaurantId)
        {
            User user = _userService.GetByEmail(email);

            AssertionConcern.AssertArgumentNotNull(user, ErrorMessages.UserNotFound);
            Restaurant restaurant = _restaurantService.GetById(restaurantId);

            AssertionConcern.AssertArgumentNotNull(restaurant, ErrorMessages.RestaurantNotFound);

            Vote vote = _repository.GetVote(DateTime.Now, user);

            AssertionConcern.AssertArgumentFalse(vote != null, ErrorMessages.YouAlreadyVoteToday);

            vote = new Vote(user, restaurant);
            return(_repository.RegisterVote(vote));
        }
Ejemplo n.º 17
0
        public new async Task RemoveLogic(int id, Produto obj)
        {
            var produto = await _produtoService.GetById(id);

            AssertionConcern.AssertArgumentFalse(produto.ProdutoClienteSaidaItems.Any(saida => saida.Ativo == true),
                                                 "Não é possivel Excluir Existem produtos Vendidos");


            AssertionConcern.AssertArgumentFalse(produto.ProdutoEstoques.Any(estoque => estoque.Ativo == true),
                                                 "Não é possivel Excluir Existem produtos no Estoque");


            AssertionConcern.AssertArgumentFalse(produto.ProdutoFornecedorEntradas.Any(estoque => estoque.Ativo == true),
                                                 "Não é possivel Excluir Existem produtos entradas de produto fornecedor");


            produto.Ativo = false;
            await _produtoService.RemoveLogic(id, produto);
        }
Ejemplo n.º 18
0
        public new async Task Add(Usuario obj)
        {
            var user = await _usuarioService.GetAll(usuario => usuario.EmpresaId == obj.EmpresaId &&
                                                    String.Equals(usuario.Email, obj.Email, StringComparison.OrdinalIgnoreCase));

            AssertionConcern.AssertArgumentFalse(user.Count > 0, Errors.DuplicateEmail);

            var senha = obj.Senha;

            obj.SetSenha(obj.Senha, obj.Senha);
            await _usuarioService.Add(obj);

            var corpo = new StringBuilder();

            corpo.AppendFormat("Email é {0} Senha{1}", obj.Email, senha);

            await new EmailManager().EnviarEmail("Usuario Sonic TI", corpo, new List <string>()
            {
                obj.Email
            }, new List <Attachment>());
        }
Ejemplo n.º 19
0
        public new async Task Add(List <ProdutoFornecedorEntrada> obj)
        {
            foreach (var item in obj)
            {
                var objList = await _produtoFornecedorEntradaService.GetAll(entrada => entrada.NotaFiscalId == item.NotaFiscalId && entrada.EmpresaId == item.EmpresaId);

                AssertionConcern.AssertArgumentFalse(objList.Any(), "Nota fiscal ja cadastrada");
            }

            await _produtoFornecedorEntradaService.Add(obj);

            //atualizar estoque

            foreach (var item in obj.Where(item => item.ProdutoId != null))
            {
                var estoque = await
                              _produtoEstoqueService.GetProdutoEstoque(
                    produtoEstoque =>
                    produtoEstoque.EmpresaId == item.EmpresaId && produtoEstoque.ProdutoId == item.ProdutoId);


                if (estoque == null)
                {
                    estoque = new ProdutoEstoque(0, item.EmpresaId, item.ProdutoId, item.QuantidadeEntrada, item.ValorUnitario, true);
                    await _produtoEstoqueService.Add(estoque);
                }
                else
                {
                    var quantEstoque = estoque.QuantidadeEstoque;
                    quantEstoque += item.QuantidadeEntrada;
                    estoque.SetEstoque(quantEstoque);
                    estoque.SetValorVenda(item.ValorUnitario);
                    await _produtoEstoqueService.Update(estoque);
                }
            }
        }
Ejemplo n.º 20
0
 protected void SelfAssertArgumentFalse(bool boolValue, string message)
 {
     AssertionConcern.AssertArgumentFalse(boolValue, message);
 }
Ejemplo n.º 21
0
 public void Should_ThrowsAssertArgumentFalse()
 {
     AssertionConcern.AssertArgumentFalse(true, ErrorMessage);
 }
Ejemplo n.º 22
0
 public void Should_AssertArgumentFalse()
 {
     Assert.DoesNotThrow(() => AssertionConcern.AssertArgumentFalse(false, ErrorMessage));
 }
Ejemplo n.º 23
0
        public static string BuildQRCode(this string xml, string QRCodeTokenID, string QRCodeTokenCsc, DateTime?ContingencyDate)
        {
            AssertionConcern.AssertArgumentNotNullEmpty(xml, "XML obrigatório para gerar o QRCode");

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);

            var ns = new XmlNamespaceManager(xmlDocument.NameTable);

            ns.AddNamespace("nfe", "http://www.portalfiscal.inf.br/nfe");
            ns.AddNamespace("sign", "http://www.w3.org/2000/09/xmldsig#");

            var model = xmlDocument.SelectSingleNode("//*[local-name()='mod']");

            //AssertionConcern.AssertArgumentNotNull(model, "Não foi possível encontrar o node \"mod\" no XML da NF para poder montar o QRCode");
            if (model?.InnerText != "65")
            {
                return(xml);
            }

            var tokenID  = QRCodeTokenID;
            var tokenCsc = QRCodeTokenCsc;

            AssertionConcern.AssertArgumentFalse((string.IsNullOrEmpty(tokenID) || string.IsNullOrEmpty(tokenCsc)), "QrCode Token e QrCode Token Csc são obrigatórios para NFCe");

            var qrcodeUrl = xmlDocument.SelectSingleNode("//*[local-name()='qrCode']");

            AssertionConcern.AssertArgumentNotNull(qrcodeUrl, "Não foi possível encontrar o node \"qrCode\" no XML da NF para poder montar o QRCode");

            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:infNFe", ns), "Não foi possível encontrar o node \"infNFe\" no XML da NF para poder montar o QRCode");
            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:tpAmb", ns), "Não foi possível encontrar o node \"tpAmb\" no XML da NF para poder montar o QRCode");
            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:ide/nfe:dhEmi", ns), "Não foi possível encontrar o node \"dhEmi\" no XML da NF para poder montar o QRCode");
            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:total/nfe:ICMSTot/nfe:vNF", ns), "Não foi possível encontrar o node \"vNF\" no XML da NF para poder montar o QRCode");
            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:total/nfe:ICMSTot/nfe:vICMS", ns), "Não foi possível encontrar o node \"vICMS\" no XML da NF para poder montar o QRCode");
            AssertionConcern.AssertArgumentNotNull(xmlDocument.SelectSingleNode("//nfe:enviNFe/nfe:NFe/sign:Signature/sign:SignedInfo/sign:Reference/sign:DigestValue", ns), "Não foi possível encontrar o node \"DigestValue\" no XML da NF para poder montar o QRCode");

            var tpEmis = xmlDocument.SelectSingleNode("//nfe:tpEmis", ns).InnerText;

            //[44 exatos] - chNFe -- Chave de Acesso da NFCe
            //ex: NFe13140213998916000124650010000003461000003464
            var chNFe = xmlDocument.SelectSingleNode("//nfe:infNFe", ns).Attributes["Id"].InnerText.Substring(3); //Remove "NFe" do início

            //[3 exatos] nVersao -- Versão do QR Code -- Nessa versão informar "100"
            const string nVersao = "2";

            //[1 exato] tpAmb -- Identificação do Ambiente (1 – Produção, 2 –Homologação)
            var tpAmb = xmlDocument.SelectSingleNode("//nfe:tpAmb", ns).InnerText;

            //[11-20] cDest -- Documento de Identificação do Consumidor (CNPJ/CPF/ID Estrangeiro)
            var cDest = "";

            if (xmlDocument.SelectSingleNode("//nfe:dest/nfe:CNPJ", ns) != null)
            {
                cDest = xmlDocument.SelectSingleNode("//nfe:dest/nfe:CNPJ", ns).InnerText.PadLeft(14, '0');
            }
            else if (xmlDocument.SelectSingleNode("//nfe:dest/nfe:CPF", ns) != null)
            {
                cDest = xmlDocument.SelectSingleNode("//nfe:dest/nfe:CPF", ns).InnerText.PadLeft(11, '0');
            }
            else if (xmlDocument.SelectSingleNode("//nfe:dest/nfe:idEstrangeiro", ns) != null)
            {
                cDest = xmlDocument.SelectSingleNode("//nfe:dest/nfe:idEstrangeiro", ns).InnerText.PadLeft(11, '0');
            }
            //Identificação do cliente não é obrigatória para NFCe

            //[50 convertido para hex] dhEmi -- Data e Hora de Emissão da NFC-e
            DateTime dEmi;

            DateTime.TryParse(xmlDocument.SelectSingleNode("//nfe:ide/nfe:dhEmi", ns).InnerText, out dEmi);
            var dhEmi = dEmi.ToString("dd");

            //[15] vNF -- Valor Total da NFC-e
            var vNF = xmlDocument.SelectSingleNode("//nfe:total/nfe:ICMSTot/nfe:vNF", ns).InnerText;

            //[15] vICMS -- Valor Total ICMS na NFC-e
            var vICMS = xmlDocument.SelectSingleNode("//nfe:total/nfe:ICMSTot/nfe:vICMS", ns).InnerText;

            //[56 exatos convertido para hex] digVal -- Digest Value da NFC-e
            var digVal = xmlDocument.SelectSingleNode("//nfe:enviNFe/nfe:NFe/sign:Signature/sign:SignedInfo/sign:Reference/sign:DigestValue", ns).InnerText;

            digVal = digVal.ToHexString();

            var sb = new StringBuilder();

            int tokenIDSignificantNumber;

            if (!int.TryParse(tokenID, out tokenIDSignificantNumber))
            {
                throw new InvalidOperationException(string.Format("Código identificador do CSC é inválido. Devem ser informados apenas números. Valor: {0}", tokenID));
            }

            var qrCodeTemplate = string.Empty;

            if (ContingencyDate.HasValue)
            {
                qrCodeTemplate = "{0}|{1}|{2}|{3}|{4}|{5}|{6}";
            }
            else
            {
                qrCodeTemplate = "{0}|{1}|{2}|{6}";
            }

            sb.AppendFormat(qrCodeTemplate, chNFe, nVersao, tpAmb, dhEmi, vNF, digVal, tokenIDSignificantNumber);

            var hash = string.Concat(sb.ToString(), tokenCsc).GenerateHash();

            sb.AppendFormat("|{0}", hash);

            var qrCode = string.Format(qrcodeUrl.InnerText.IndexOf('?') > -1 ? "{0}&p={1}" : "{0}?p={1}", qrcodeUrl.InnerText, sb);

            xmlDocument.SelectSingleNode("//*[local-name()='qrCode']").InnerText = "{QRCODE}";
            xmlDocument.InnerXml = xmlDocument.OuterXml.Replace("{QRCODE}", string.Format("<![CDATA[{0}]]>", qrCode));

            return(xmlDocument.OuterXml);
        }